From 9a5e70ed3272ced86a778772470c7416b42fd10d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 14:55:27 -0500 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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/8] 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(")); +} From 43f848716180c533f35ac5af59e1c148aa8d9ea0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 00:07:18 -0500 Subject: [PATCH 6/8] Every step of PR work knows the other repositories its change reaches An installation contract index, built with each repository's code graph and refreshed on every push, records per repository the endpoints, GraphQL fields, events, packages, imported symbols and environment variables it exposes and uses (common::contracts). Every pass of PR work reads it (passes::xrepo): the planner sees the consumers and a plan that ignores them goes back; the coder and every round through it start with the consumers' lines; the reviewer raises a removed contract a consumer still uses as a required finding; a pull request touching contracts others use carries a compatibility section unless it changes them. Every loop has find_consumers. Reading stays unrestricted. Private reads by work posting to a public repository are kept per installation; a write tool copying them is refused, and every text the GitHub client writes there has them taken out by the same leak check. Incident xt holds the invariants. --- docs/code-map.md | 39 + ..._contract_change_reaches_every_consumer.md | 18 + services/common/src/agent_policy/registry.rs | 1 + services/common/src/contracts.rs | 1888 +++++++++++++++++ services/common/src/lib.rs | 3 + services/common/src/repo_reach.rs | 142 +- services/common/src/tool_registry.rs | 1 + services/worker/src/agent/provider.rs | 29 +- services/worker/src/agent/reach.rs | 185 +- services/worker/src/clients/github.rs | 116 +- services/worker/src/passes/code_graph.rs | 125 +- services/worker/src/passes/feedback.rs | 6 +- services/worker/src/passes/implement.rs | 20 + .../passes/incidents/bm_teams_never_cross.rs | 2 + .../xp_answers_read_the_other_repo.rs | 8 +- ..._contract_change_reaches_every_consumer.rs | 411 ++++ services/worker/src/passes/mod.rs | 1 + services/worker/src/passes/plan.rs | 29 + services/worker/src/passes/pr.rs | 4 + services/worker/src/passes/review_pr.rs | 26 +- services/worker/src/passes/run_map.rs | 2 +- services/worker/src/passes/xrepo.rs | 581 +++++ 22 files changed, 3590 insertions(+), 47 deletions(-) create mode 100644 docs/incidents/xt_contract_change_reaches_every_consumer.md create mode 100644 services/common/src/contracts.rs create mode 100644 services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs create mode 100644 services/worker/src/passes/xrepo.rs diff --git a/docs/code-map.md b/docs/code-map.md index 77b653e59..eb8004c42 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -78,3 +78,42 @@ Two run attributes, served by `GET /api/runs/{run_id}` under `exploration`: and without a `map_commit` shows how much exploration the map saves. The replay case is `services/worker/src/passes/incidents/dg_code_map_kept_current.rs`. + +## The installation's contract index + +Beside each repository's map, CoderHelm keeps one index for the whole +installation: per repository, the contracts it exposes and the ones it uses +(HTTP endpoints, GraphQL root fields, events and queue messages, packages and +the symbols imported from them, environment variables). It is what tells a +run which other repositories a change reaches before it plans, codes or +reviews. + +Code: `services/common/src/contracts.rs` (extraction, the record, the index, +pure) and `services/worker/src/passes/xrepo.rs` (what each step of a run reads +from it). + +- **Built with the code graph.** The code graph's index pass extracts each + file's contracts with plain patterns, no model. A first build reads every + file; a push replaces only the changed files' entries. A repository with + no record yet is queued for a first read when work in the installation + starts, a few per step. +- **One query per team.** Every record sits in one partition + (`pk = XC#{team}`, `sk = REPO#{owner/name}`, gzipped JSON), read in one + paginated query and kept in memory for ten minutes. What a change reaches + is worked out in memory, never by searching every repository. +- **Bounded.** A file over 256 KB is skipped, a pass reads at most 6,000 + files, a file adds at most 80 entries and a repository holds at most 4,000 + (environment reads, then imported symbols, go first). A stored record + stays under 300 KB. Imported symbols are kept only for packages some + repository of the installation exposes. +- **Read by every pass.** The planner's first message lists what its likely + files reach, and a plan that changes a contract another repository uses + either changes that repository too or says how it stays compatible under + `## Compatibility`. The coder's first message carries the consumers' own + lines (at most six excerpts). The reviewer raises a removed contract a + consumer still uses as a required finding. A pull request that touches + contracts others use carries a compatibility section. Every loop has + `find_consumers`. +- **Private stays private.** Reading is never limited. In a public + repository, nothing CoderHelm writes names a private repository or copies + its code; the incident page `xt` has the details. diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md new file mode 100644 index 000000000..c7303a234 --- /dev/null +++ b/docs/incidents/xt_contract_change_reaches_every_consumer.md @@ -0,0 +1,18 @@ +# xt. `xt_contract_change_reaches_every_consumer` + +**What happened:** PR work knew one repository at a time. A ticket asked a bookstore's orders service to return a book's price in cents and to retire an old route. The plan named the route and its test, the coder changed them, and the reviewer passed the pull request. Another repository's book page fetched that route, a reading app subscribed to an order event the same change renamed, and a shared types package described the old shape. Nothing in planning, coding, review or the pull request named any of them. The agents could have searched every repository; none did, and nothing made them. + +**Why:** Knowing the rest of the installation was left to the model. The app map covers HTTP calls when a team has built it, and the read tools can search anything, but no step was given the other repositories a change reaches before it acted, and nothing checked the plan, the review or the pull request against them. + +**The guarantee (invariants, enforced in code):** + +- **An installation index, cheap and current.** For every repository of the installation, the contracts it exposes and the ones it uses: HTTP endpoints, GraphQL root fields, events and queue messages, packages and the symbols other repositories import from them, and environment variables (`common::contracts`). It is extracted with plain patterns by the code graph's index pass, which already reads the repository: a first build reads every file, a push replaces only the changed files' entries. All of a team's records sit in one partition and are read in one query, kept in memory for ten minutes. Every bound is a constant: file size, files per pass, entries per file and per repository, the stored record's size, links per answer, excerpts and characters per prompt. A repository with no record yet is queued for a first read, a few per step. +- **Planning.** The planner's first message lists what the ticket's likely files expose to other repositories and use from them. A plan whose files carry a contract another repository uses goes back once unless it changes every such repository (a group per repository, the multi-repository plan the run builds and links in merge order) or says how it stays compatible under `## Compatibility`. +- **Coding, fix rounds and CI rounds.** The coder's first message carries the consumers' own lines, read from each repository's default branch, so every round through the coder starts knowing its callers. A round a person asks for loads the same index. +- **Review.** The reviewer is shown each contract the change touches that another repository uses, and every contract the change removes or renames while a consumer still uses it is a required, blocking finding citing that consumer, whatever the model said. A rewrite that keeps the contract is not one. The reviewer's code graph covers the installation's other repositories too. +- **Shipping.** A pull request whose change touches contracts other repositories use, with neither those repositories in the run nor a compatibility section in its description, gets one, with every removed contract marked breaking. +- **Every loop can ask.** Every worker loop with tools has `find_consumers` over the index, and its prompt says to ask it before changing or explaining a contract. +- **No limit to one repository.** A source scan fails on a prompt that limits PR work to one repository, and on any graph registry PR work opens without the team's other repositories. +- **Privacy on every surface.** Reading stays unrestricted. Work posting to a public repository keeps every private read, from the tools and from what the index showed it. A write tool whose input copies a private line, or names a private repository or a path read in one, is refused with the reason, and every text the GitHub client writes into that repository (pull request titles and bodies, commit messages, comments, reviews, release notes) has what came from a private repository taken out by the same leak check. The reviewer and the compatibility section say "a private repository of the installation" instead of a name. A private repository's work may reference freely. + +**Where it's enforced:** `common::contracts::{extract, Record, Index::links, Index::breaks, compat_section, team_index, answer}`, `common::repo_reach::{note_private, guard_public, code_refused}`, the worker's `passes::xrepo::RunContracts::{load, planner_section, plan_gaps, coder_context, review_section, break_findings, compat_note}` and `with_compat`, `passes::code_graph::{refresh_contracts, RepoGraphs::load_map, offer}`, `agent::reach::{offer, prompt, Exec}`, `agent::provider::converse_as` and `clients::github::public_payload`. diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 86ef10db0..67f54572e 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -177,6 +177,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("list_repos", Risk::Read), ("read_repo_file", Risk::Read), ("search_repo", Risk::Read), + ("find_consumers", Risk::Read), ("github__read_file", Risk::Read), ("github__search_code", Risk::Read), ("github__list_directory", Risk::Read), diff --git a/services/common/src/contracts.rs b/services/common/src/contracts.rs new file mode 100644 index 000000000..4a2843337 --- /dev/null +++ b/services/common/src/contracts.rs @@ -0,0 +1,1888 @@ +//! The installation's contract index: for every repository of a team's +//! GitHub installation, the contracts it exposes and the ones it uses, so +//! a run knows which other repositories a change reaches before it plans, +//! codes or reviews, the way a senior developer who knows the whole system +//! would. +//! +//! A contract is anything one repository offers another: +//! +//! - an HTTP **endpoint** (a route it defines; a request another makes), +//! - a **GraphQL** root field (a schema's `Query`, `Mutation` or +//! `Subscription` field; an operation that asks for it), +//! - an **event** or queue message (a topic it publishes; one it +//! subscribes to), +//! - a **package** (the name its manifest gives it; a dependency on it), +//! and the **symbols** other repositories import from it (shared types +//! and functions), +//! - an **environment** variable (set in infrastructure or config; read in +//! code). +//! +//! **Built with the code graph.** The code graph's index pass +//! (`worker::passes::code_graph`) already downloads the repository at its +//! default branch on a first build and re-reads only the changed files on +//! each push. The same pass extracts each file's contracts ([`extract`], +//! plain patterns, no model) and writes the repository's [`Record`] in one +//! item: a push replaces only the changed files' entries +//! ([`Record::replace_files`]). Nothing is rebuilt on a schedule. +//! +//! **Read in one query.** Every record of a team sits in one partition +//! (`pk = XC#{team}`, `sk = REPO#{owner/name}`, gzipped JSON), so the whole +//! installation's index is one paginated query, kept in memory for +//! [`KEEP_SECS`] per team ([`team_index`]). What a change reaches is then +//! worked out in memory ([`Index::links`]), never by searching every +//! repository per request. +//! +//! **Bounded.** A file over [`MAX_FILE_BYTES`] is skipped, a pass scans at +//! most [`MAX_SCAN_FILES`] files, a file contributes at most +//! [`MAX_PER_FILE`] entries and a repository at most [`MAX_ENTRIES`]; a +//! record over [`MAX_BODY_BYTES`] gzipped drops environment reads first, +//! then imported symbols, until it fits. Imported symbols are kept only for +//! packages some repository of the installation exposes, so a repository's +//! imports of public libraries cost nothing. + +use std::collections::{BTreeSet, HashMap}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use regex::Regex; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// A file larger than this is not read for contracts. +pub const MAX_FILE_BYTES: usize = 256 * 1024; +/// Files one index pass reads for contracts at most. +pub const MAX_SCAN_FILES: usize = 6_000; +/// Entries one file contributes at most. +pub const MAX_PER_FILE: usize = 80; +/// Entries one repository's record holds at most. +pub const MAX_ENTRIES: usize = 4_000; +/// The largest record stored (gzipped bytes): DynamoDB's item limit is 400 KB. +pub const MAX_BODY_BYTES: usize = 300_000; +/// How long a team's index is kept in memory between reads. +pub const KEEP_SECS: u64 = 600; +/// Links one question returns at most. +pub const MAX_LINKS: usize = 40; + +/// The tool every loop is offered to ask the index. +pub const TOOL: &str = "find_consumers"; +/// The heading under which a plan or a pull request says how a contract +/// change stays compatible with the consumers it doesn't update. +pub const COMPAT_HEADING: &str = "## Compatibility"; + +// ── Entries ──────────────────────────────────────────────────────────────── + +/// What kind of contract. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + Endpoint, + Graphql, + Event, + Package, + Symbol, + Env, +} + +impl Kind { + pub fn word(self) -> &'static str { + match self { + Kind::Endpoint => "endpoint", + Kind::Graphql => "GraphQL field", + Kind::Event => "event", + Kind::Package => "package", + Kind::Symbol => "imported symbol", + Kind::Env => "environment variable", + } + } +} + +/// Whether a repository offers the contract or relies on it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Side { + Exposes, + Uses, +} + +/// One contract one file exposes or uses, at its line. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct Entry { + #[serde(rename = "k")] + pub kind: Kind, + /// The contract's key: a normalized path (`/books/{}`), `Query.books`, + /// a topic, a package name, `package#Symbol`, a variable name. + #[serde(rename = "n")] + pub key: String, + #[serde(rename = "s")] + pub side: Side, + #[serde(rename = "f")] + pub file: String, + #[serde(rename = "l")] + pub line: u32, + /// The HTTP method when known, else empty. + #[serde(rename = "d", default, skip_serializing_if = "String::is_empty")] + pub detail: String, +} + +impl Entry { + fn new(kind: Kind, key: impl Into, side: Side, file: &str, line: usize) -> Self { + Entry { + kind, + key: key.into(), + side, + file: file.to_string(), + line: line as u32, + detail: String::new(), + } + } + + fn with(mut self, detail: &str) -> Self { + self.detail = detail.to_uppercase(); + self + } + + /// `file:line`. + pub fn at(&self) -> String { + format!("{}:{}", self.file, self.line) + } + + /// The contract as people read it (`GET /books/{}`, `Query.books`). + pub fn label(&self) -> String { + match (self.kind, self.detail.is_empty()) { + (Kind::Endpoint, false) if self.detail != "*" => { + format!("{} {}", self.detail, self.key) + } + _ => self.key.clone(), + } + } +} + +// ── What is read ─────────────────────────────────────────────────────────── + +const SKIP_DIRS: [&str; 14] = [ + "node_modules/", + "vendor/", + "dist/", + "build/", + "target/", + ".git/", + ".next/", + "coverage/", + "__pycache__/", + "generated/", + "__generated__/", + ".venv/", + "out/", + "fixtures/", +]; + +const CODE_EXT: [&str; 18] = [ + "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "rs", "go", "java", "kt", "rb", "php", "cs", + "graphql", "gql", "vue", "svelte", +]; + +fn name_of(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +fn ext_of(path: &str) -> &str { + let n = name_of(path); + n.rsplit_once('.').map(|(_, e)| e).unwrap_or("") +} + +fn is_manifest(path: &str) -> bool { + let n = name_of(path); + matches!( + n, + "package.json" | "Cargo.toml" | "pyproject.toml" | "go.mod" + ) || (n.starts_with("requirements") && n.ends_with(".txt")) +} + +fn is_env_file(path: &str) -> bool { + let n = name_of(path); + matches!( + n, + ".env.example" | ".env.sample" | ".env.template" | ".env.defaults" + ) +} + +fn is_config(path: &str) -> bool { + let e = ext_of(path); + let n = name_of(path); + e == "tf" + || ((e == "yml" || e == "yaml") + && (n.starts_with("docker-compose") + || n.starts_with("compose") + || n == "serverless.yml" + || n == "template.yaml" + || n == "app.yaml" + || path.contains("k8s/") + || path.contains("helm/") + || path.contains("deploy/") + || path.contains("infra/") + || path.contains("kubernetes/"))) +} + +/// Whether a file of a repository is read for contracts. +pub fn scans(path: &str) -> bool { + let p = format!("/{path}"); + if SKIP_DIRS.iter().any(|d| p.contains(&format!("/{d}"))) { + return false; + } + let n = name_of(path); + if n.ends_with(".min.js") || n.ends_with(".d.ts") || n.ends_with(".map") { + return false; + } + is_manifest(path) || is_env_file(path) || is_config(path) || CODE_EXT.contains(&ext_of(path)) +} + +// ── Extraction ───────────────────────────────────────────────────────────── + +fn re(p: &str) -> Regex { + Regex::new(p).expect("contract pattern") +} + +static ROUTE_JS: LazyLock = LazyLock::new(|| { + re( + r#"\b(?:app|router|server|fastify|hono|routes|route|r|express)\s*\.\s*(get|post|put|patch|delete|all|options|head)\s*\(\s*['"`](/[^'"`\s]*)['"`]"#, + ) +}); +static ROUTE_PY: LazyLock = LazyLock::new(|| { + re( + r#"@\s*\w+\s*\.\s*(get|post|put|patch|delete|route|api_route)\s*\(\s*[rf]?['"](/[^'"]*)['"]"#, + ) +}); +static ROUTE_ATTR: LazyLock = + LazyLock::new(|| re(r#"#\[\s*(get|post|put|patch|delete)\s*\(\s*"(/[^"]*)""#)); +static ROUTE_AXUM: LazyLock = + LazyLock::new(|| re(r#"\.route\s*\(\s*"(/[^"]*)"\s*,\s*(get|post|put|patch|delete)?"#)); +static ROUTE_GO: LazyLock = + LazyLock::new(|| re(r#"\.(GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\s*\(\s*"(/[^"]*)""#)); +static ROUTE_SPRING: LazyLock = LazyLock::new(|| { + re( + r#"@(Get|Post|Put|Patch|Delete|Request)Mapping\s*\(\s*(?:value\s*=\s*|path\s*=\s*)?"(/[^"]*)""#, + ) +}); +static CALL: LazyLock = LazyLock::new(|| { + re( + r#"(?:\$fetch|\bfetch|\bky|\buseSWR|\b(?:axios|api|apiClient|client|http|https|request|requests|httpx|session|this\.http|\w+Client|\w+Api)\s*\.\s*(get|post|put|patch|delete|request|head))\s*(?:<[^>()]*>)?\s*\(\s*[fr]?['"`]([^'"`]+)['"`]"#, + ) +}); +static GQL_TYPE: LazyLock = + LazyLock::new(|| re(r"(?m)^\s*(?:extend\s+)?type\s+(Query|Mutation|Subscription)\b[^{]*\{")); +static GQL_FIELD: LazyLock = LazyLock::new(|| re(r"^\s*([A-Za-z_]\w*)\s*[(:]")); +static GQL_OP: LazyLock = LazyLock::new(|| { + re( + r"\b(query|mutation|subscription)\b\s*[A-Za-z_]?\w*\s*(?:\([^)]*\))?\s*(?:@\w+\s*)*\{\s*(?:[A-Za-z_]\w*\s*:\s*)?([A-Za-z_]\w*)", + ) +}); +static PUBLISH: LazyLock = LazyLock::new(|| { + re( + r#"\b(?:publish\w*|produce\w*|enqueue\w*|send_?[Ee]vent|putEvents?)\s*\(\s*['"`]([A-Za-z0-9_.:/\-]{3,})['"`]"#, + ) +}); +static SUBSCRIBE: LazyLock = LazyLock::new(|| { + re( + r#"\b(?:subscribe\w*|consume\w*|listen\w*|on_?[Ee]vent)\s*\(\s*['"`]([A-Za-z0-9_.:/\-]{3,})['"`]"#, + ) +}); +static TOPIC_FIELD: LazyLock = LazyLock::new(|| { + re( + r#"\b(?:topic|topicName|TopicName|queueName|QueueName|DetailType|detail_type|eventName|event_name)\s*[:=]\s*['"]([A-Za-z0-9_.:/\-]{3,})['"]"#, + ) +}); +static TOPICS_LIST: LazyLock = LazyLock::new(|| { + re( + r#"(?:\btopics\s*[:=]\s*\[|"detail-type"\s*:\s*\[|@KafkaListener\s*\(\s*topics\s*=\s*\{?|@(?:Sqs|Rabbit|Jms)Listener\s*\(\s*(?:queues\s*=\s*|value\s*=\s*)?\{?)\s*['"]([A-Za-z0-9_.:/\-]{3,})['"]"#, + ) +}); +static ENV_READ: LazyLock = LazyLock::new(|| { + re( + r#"(?:process\.env\.|import\.meta\.env\.|process\.env\[\s*['"]|os\.environ(?:\.get)?\s*[\[(]\s*['"]|os\.getenv\s*\(\s*['"]|env::var(?:_os)?\s*\(\s*"|System\.getenv\s*\(\s*"|os\.Getenv\s*\(\s*"|ENV\[\s*['"])([A-Z][A-Z0-9_]{2,})"#, + ) +}); +static ENV_SET: LazyLock = LazyLock::new(|| { + re(r#"^\s*(?:-\s*)?(?:name:\s*)?["']?([A-Z][A-Z0-9_]{2,})["']?\s*(?:[:=]|$)"#) +}); +static IMPORT_JS: LazyLock = + LazyLock::new(|| re(r#"import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*['"]([^'".][^'"]*)['"]"#)); +static IMPORT_PY: LazyLock = + LazyLock::new(|| re(r"(?m)^\s*from\s+([A-Za-z_][\w.]*)\s+import\s+\(?([\w, \t]+)")); +static USE_RS: LazyLock = LazyLock::new(|| { + re(r"(?m)^\s*(?:pub\s+)?use\s+([a-z_][a-z0-9_]*)::(?:[\w:]*::)?(\{[^}]*\}|[A-Za-z_]\w*)") +}); + +/// Variables nearly every service reads: never a contract between two of +/// them. +const COMMON_ENV: [&str; 26] = [ + "NODE_ENV", + "PORT", + "HOST", + "PATH", + "HOME", + "DEBUG", + "LOG_LEVEL", + "AWS_REGION", + "AWS_DEFAULT_REGION", + "TZ", + "LANG", + "PWD", + "USER", + "SHELL", + "ENV", + "ENVIRONMENT", + "STAGE", + "RUST_LOG", + "PYTHONPATH", + "GITHUB_TOKEN", + "HOSTNAME", + "TERM", + "TMPDIR", + "VERCEL_ENV", + "NEXT_RUNTIME", + "CI", +]; + +/// A request or route path, normalized: the host and query left out, each +/// parameter (`:id`, `{id}`, ``, `[id]`, `${id}`) written `{}`, lower +/// case. `None` for anything that isn't a path with at least one segment. +pub fn norm_path(raw: &str) -> Option { + let mut s = raw.trim(); + if let Some(i) = s.find("://") { + let rest = &s[i + 3..]; + s = &rest[rest.find('/')?..]; + } + while s.starts_with("${") { + s = &s[s.find('}')? + 1..]; + } + if !s.starts_with('/') || s.starts_with("//") { + return None; + } + let s = s.split(['?', '#']).next()?; + let segs: Vec = s + .split('/') + .filter(|x| !x.is_empty()) + .filter(|x| !(x.starts_with('(') && x.ends_with(')'))) + .map(|seg| { + let param = seg.starts_with(':') + || seg.contains("${") + || (seg.starts_with('{') && seg.ends_with('}')) + || (seg.starts_with('<') && seg.ends_with('>')) + || (seg.starts_with('[') && seg.ends_with(']')) + || seg == "*"; + if param { + "{}".to_string() + } else { + seg.to_lowercase() + } + }) + .collect(); + if segs.is_empty() || segs.iter().any(|s| s.contains(' ')) { + return None; + } + Some(format!("/{}", segs.join("/"))) +} + +/// Whether two normalized paths name the same endpoint: the same segments +/// (`{}` matching any), or the shorter one, of two segments or more, the +/// tail of the longer (a client calling through a base path like `/api`). +pub fn paths_match(a: &str, b: &str) -> bool { + let sa: Vec<&str> = a.split('/').filter(|x| !x.is_empty()).collect(); + let sb: Vec<&str> = b.split('/').filter(|x| !x.is_empty()).collect(); + let (short, long) = if sa.len() <= sb.len() { + (&sa, &sb) + } else { + (&sb, &sa) + }; + if short.is_empty() || (short.len() != long.len() && short.len() < 2) { + return false; + } + let tail = &long[long.len() - short.len()..]; + let same = short + .iter() + .zip(tail.iter()) + .all(|(x, y)| x == y || *x == "{}" || *y == "{}"); + // Two paths of parameters alone say nothing. + same && short.iter().any(|s| *s != "{}") +} + +/// A package name as it is matched: lower case, `-` and `_` alike. +pub fn norm_package(name: &str) -> String { + name.trim().to_lowercase().replace('-', "_") +} + +/// The package an import names: `@scope/name` or the first segment. +fn package_of_import(spec: &str) -> Option { + let spec = spec.trim(); + if spec.is_empty() || spec.starts_with('.') || spec.starts_with('/') || spec.contains(':') { + return None; + } + let mut parts = spec.split('/'); + let first = parts.next()?; + let base = if first.starts_with('@') { + format!("{first}/{}", parts.next()?) + } else { + first.to_string() + }; + Some(norm_package(&base)) +} + +fn line_at(src: &str, offset: usize) -> usize { + src[..offset.min(src.len())] + .bytes() + .filter(|b| *b == b'\n') + .count() + + 1 +} + +fn names_in(list: &str) -> Vec { + list.split(',') + .filter_map(|n| { + let n = n.trim().trim_start_matches("type ").trim(); + let n = n.split(" as ").next().unwrap_or(n).trim(); + let ok = !n.is_empty() + && n != "self" + && n != "*" + && n.chars().all(|c| c.is_alphanumeric() || c == '_'); + ok.then(|| n.to_string()) + }) + .collect() +} + +/// Every contract `source` (the file at `path`) exposes or uses. Imported +/// symbols are kept only for packages `keep` accepts (those the +/// installation exposes), so imports of public libraries cost nothing. +pub fn extract(path: &str, source: &str, keep: &dyn Fn(&str) -> bool) -> Vec { + if source.len() > MAX_FILE_BYTES { + return Vec::new(); + } + let mut out: Vec = Vec::new(); + if is_manifest(path) { + manifest(path, source, &mut out); + } else if is_env_file(path) || is_config(path) { + for (i, l) in source.lines().enumerate() { + if let Some(c) = ENV_SET.captures(l) { + let k = &c[1]; + if !COMMON_ENV.contains(&k) { + out.push(Entry::new(Kind::Env, k, Side::Exposes, path, i + 1)); + } + } + } + events(path, source, &mut out); + } else { + routes(path, source, &mut out); + graphql(path, source, &mut out); + events(path, source, &mut out); + for c in ENV_READ.captures_iter(source) { + let k = &c[1]; + if !COMMON_ENV.contains(&k) { + let at = line_at(source, c.get(1).map(|m| m.start()).unwrap_or(0)); + out.push(Entry::new(Kind::Env, k, Side::Uses, path, at)); + } + } + imports(path, source, keep, &mut out); + } + out.sort(); + out.dedup_by(|a, b| { + a.kind == b.kind && a.key == b.key && a.side == b.side && a.detail == b.detail + }); + out.sort_by_key(|e| e.line); + out.truncate(MAX_PER_FILE); + out +} + +fn routes(path: &str, src: &str, out: &mut Vec) { + // File-system routes: Next.js `app/**/route.ts` and `pages/api/**`. + let p = format!("/{path}"); + if let Some(i) = p.find("/app/") { + let rest = &p[i + 4..]; + if let Some(dir) = rest + .strip_suffix("/route.ts") + .or_else(|| rest.strip_suffix("/route.js")) + { + if let Some(k) = norm_path(dir) { + for m in ["GET", "POST", "PUT", "PATCH", "DELETE"] { + let pat = format!("export async function {m}"); + let pat2 = format!("export function {m}"); + if let Some(o) = src.find(&pat).or_else(|| src.find(&pat2)) { + out.push( + Entry::new(Kind::Endpoint, &k, Side::Exposes, path, line_at(src, o)) + .with(m), + ); + } + } + } + } + } + if let Some(i) = p.find("/pages/api/") { + let rest = &p[i + 6..]; + let rest = rest.rsplit_once('.').map(|(r, _)| r).unwrap_or(rest); + let rest = rest.strip_suffix("/index").unwrap_or(rest); + if let Some(k) = norm_path(rest) { + out.push(Entry::new(Kind::Endpoint, k, Side::Exposes, path, 1).with("*")); + } + } + let mut defined_lines: BTreeSet = BTreeSet::new(); + for (rx, m_ix, p_ix) in [ + (&*ROUTE_JS, 1, 2), + (&*ROUTE_PY, 1, 2), + (&*ROUTE_ATTR, 1, 2), + (&*ROUTE_GO, 1, 2), + (&*ROUTE_SPRING, 1, 2), + ] { + for c in rx.captures_iter(src) { + let Some(k) = norm_path(&c[p_ix]) else { + continue; + }; + let method = match c[m_ix].to_lowercase().as_str() { + "route" | "api_route" | "all" | "handlefunc" | "handle" | "request" => { + "*".to_string() + } + m => m.to_string(), + }; + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + defined_lines.insert(at); + out.push(Entry::new(Kind::Endpoint, k, Side::Exposes, path, at).with(&method)); + } + } + for c in ROUTE_AXUM.captures_iter(src) { + let Some(k) = norm_path(&c[1]) else { + continue; + }; + let method = c.get(2).map(|m| m.as_str()).unwrap_or("*"); + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + defined_lines.insert(at); + out.push(Entry::new(Kind::Endpoint, k, Side::Exposes, path, at).with(method)); + } + for c in CALL.captures_iter(src) { + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + if defined_lines.contains(&at) { + continue; + } + let Some(k) = norm_path(&c[2]) else { + continue; + }; + let method = c + .get(1) + .map(|m| m.as_str()) + .filter(|m| *m != "request") + .unwrap_or("*"); + out.push(Entry::new(Kind::Endpoint, k, Side::Uses, path, at).with(method)); + } +} + +fn graphql(path: &str, src: &str, out: &mut Vec) { + let gql_file = matches!(ext_of(path), "graphql" | "gql"); + if !gql_file + && !src.contains("gql`") + && !src.contains("graphql(") + && !src.contains("type Query") + { + return; + } + // The schema: each root type's fields. + for c in GQL_TYPE.captures_iter(src) { + let root = c[1].to_string(); + let start = c.get(0).map(|m| m.end()).unwrap_or(0); + let mut depth = 1usize; + for (line, l) in (line_at(src, start)..).zip(src[start..].lines()) { + if depth == 1 { + if let Some(f) = GQL_FIELD.captures(l) { + out.push(Entry::new( + Kind::Graphql, + format!("{root}.{}", &f[1]), + Side::Exposes, + path, + line, + )); + } + } + depth += l.matches(['{', '(']).count(); + depth = depth.saturating_sub(l.matches(['}', ')']).count()); + if depth == 0 { + break; + } + } + } + // The operations: each one's first root field. + for c in GQL_OP.captures_iter(src) { + let root = match &c[1] { + "query" => "Query", + "mutation" => "Mutation", + _ => "Subscription", + }; + let at = line_at(src, c.get(2).map(|m| m.start()).unwrap_or(0)); + out.push(Entry::new( + Kind::Graphql, + format!("{root}.{}", &c[2]), + Side::Uses, + path, + at, + )); + } +} + +fn events(path: &str, src: &str, out: &mut Vec) { + let lines: Vec<&str> = src.lines().collect(); + let around = |at: usize| -> String { + let lo = at.saturating_sub(3); + let hi = (at + 1).min(lines.len()); + lines[lo..hi].join("\n").to_lowercase() + }; + for c in PUBLISH.captures_iter(src) { + let at = line_at(src, c.get(1).map(|m| m.start()).unwrap_or(0)); + out.push(Entry::new(Kind::Event, &c[1], Side::Exposes, path, at)); + } + for c in SUBSCRIBE.captures_iter(src) { + let at = line_at(src, c.get(1).map(|m| m.start()).unwrap_or(0)); + out.push(Entry::new(Kind::Event, &c[1], Side::Uses, path, at)); + } + for c in TOPICS_LIST.captures_iter(src) { + let at = line_at(src, c.get(1).map(|m| m.start()).unwrap_or(0)); + out.push(Entry::new(Kind::Event, &c[1], Side::Uses, path, at)); + } + for c in TOPIC_FIELD.captures_iter(src) { + let at = line_at(src, c.get(1).map(|m| m.start()).unwrap_or(0)); + let near = around(at); + let side = if [ + "subscribe", + "consumer", + "listen", + "handler", + "trigger", + "rule", + ] + .iter() + .any(|w| near.contains(w)) + { + Side::Uses + } else { + Side::Exposes + }; + out.push(Entry::new(Kind::Event, &c[1], side, path, at)); + } +} + +fn imports(path: &str, src: &str, keep: &dyn Fn(&str) -> bool, out: &mut Vec) { + let mut add = |pkg: &str, names: Vec, at: usize| { + if !keep(pkg) { + return; + } + for n in names { + out.push(Entry::new( + Kind::Symbol, + format!("{pkg}#{n}"), + Side::Uses, + path, + at, + )); + } + }; + match ext_of(path) { + "ts" | "tsx" | "js" | "jsx" | "mjs" | "cjs" | "vue" | "svelte" => { + for c in IMPORT_JS.captures_iter(src) { + if let Some(pkg) = package_of_import(&c[2]) { + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + add(&pkg, names_in(&c[1]), at); + } + } + } + "py" => { + for c in IMPORT_PY.captures_iter(src) { + let pkg = norm_package(c[1].split('.').next().unwrap_or("")); + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + add(&pkg, names_in(&c[2]), at); + } + } + "rs" => { + for c in USE_RS.captures_iter(src) { + let krate = &c[1]; + if matches!(krate, "crate" | "self" | "super" | "std" | "core" | "alloc") { + continue; + } + let list = c[2].trim_start_matches('{').trim_end_matches('}'); + let at = line_at(src, c.get(0).map(|m| m.start()).unwrap_or(0)); + add(&norm_package(krate), names_in(list), at); + } + } + _ => {} + } +} + +fn find_line(src: &str, needle: &str) -> usize { + src.find(needle).map(|o| line_at(src, o)).unwrap_or(1) +} + +fn manifest(path: &str, src: &str, out: &mut Vec) { + let n = name_of(path); + if n == "package.json" { + let Ok(v) = serde_json::from_str::(src) else { + return; + }; + if let Some(name) = v["name"].as_str().filter(|s| !s.is_empty()) { + out.push(Entry::new( + Kind::Package, + norm_package(name), + Side::Exposes, + path, + find_line(src, "\"name\""), + )); + } + for sec in ["dependencies", "devDependencies", "peerDependencies"] { + for dep in v[sec].as_object().into_iter().flat_map(|o| o.keys()) { + out.push(Entry::new( + Kind::Package, + norm_package(dep), + Side::Uses, + path, + find_line(src, &format!("\"{dep}\"")), + )); + } + } + return; + } + if n == "go.mod" { + let mut in_require = false; + for (i, l) in src.lines().enumerate() { + let t = l.trim(); + if let Some(m) = t.strip_prefix("module ") { + out.push(Entry::new( + Kind::Package, + norm_package(m.trim()), + Side::Exposes, + path, + i + 1, + )); + } else if t.starts_with("require (") { + in_require = true; + } else if in_require && t == ")" { + in_require = false; + } else if let Some(dep) = + t.strip_prefix("require ") + .or(if in_require { Some(t) } else { None }) + { + if let Some(name) = dep.split_whitespace().next().filter(|s| !s.is_empty()) { + out.push(Entry::new( + Kind::Package, + norm_package(name), + Side::Uses, + path, + i + 1, + )); + } + } + } + return; + } + if n.starts_with("requirements") { + for (i, l) in src.lines().enumerate() { + let t = l.trim(); + if t.is_empty() || t.starts_with('#') || t.starts_with('-') { + continue; + } + let name: String = t + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || *c == '.') + .collect(); + if !name.is_empty() { + out.push(Entry::new( + Kind::Package, + norm_package(&name), + Side::Uses, + path, + i + 1, + )); + } + } + return; + } + // Cargo.toml and pyproject.toml: the package's name, and each + // dependency table's names (or a list's). + let mut section = String::new(); + let mut in_list = false; + for (i, l) in src.lines().enumerate() { + let t = l.trim(); + if t.starts_with('[') && !in_list { + section = t.trim_matches(['[', ']']).to_string(); + continue; + } + let named = matches!(section.as_str(), "package" | "project" | "tool.poetry"); + if named { + if let Some(v) = t.strip_prefix("name") { + let v = v + .trim_start() + .trim_start_matches('=') + .trim() + .trim_matches('"'); + if !v.is_empty() { + out.push(Entry::new( + Kind::Package, + norm_package(v), + Side::Exposes, + path, + i + 1, + )); + } + continue; + } + } + let deps_table = section.ends_with("dependencies"); + if deps_table && !t.is_empty() && !t.starts_with('#') { + let name: String = t + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_') + .collect(); + if !name.is_empty() && name != "python" { + out.push(Entry::new( + Kind::Package, + norm_package(&name), + Side::Uses, + path, + i + 1, + )); + } + } + if named && t.starts_with("dependencies") && t.contains('[') { + in_list = !t.contains(']'); + continue; + } + if in_list { + if t.starts_with(']') { + in_list = false; + continue; + } + let name: String = t + .trim_matches(['"', '\'', ',']) + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '-' || *c == '_' || *c == '.') + .collect(); + if !name.is_empty() { + out.push(Entry::new( + Kind::Package, + norm_package(&name), + Side::Uses, + path, + i + 1, + )); + } + } + } +} + +// ── A repository's record ────────────────────────────────────────────────── + +/// One repository's contracts, stamped with the commit they describe. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Record { + pub repo: String, + #[serde(default)] + pub commit: String, + #[serde(default)] + pub entries: Vec, +} + +impl Record { + /// The record with `files`' entries replaced by `fresh` (a push: only + /// the changed files; a deleted file's go), then held to + /// [`MAX_ENTRIES`]. + pub fn replace_files(&mut self, files: &[String], fresh: Vec) { + let gone: BTreeSet<&str> = files.iter().map(String::as_str).collect(); + self.entries.retain(|e| !gone.contains(e.file.as_str())); + self.entries.extend(fresh); + self.entries + .sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line))); + self.cap(MAX_ENTRIES); + } + + /// At most `max` entries: environment reads go first, then imported + /// symbols, then environment settings; exposures are kept longest. + fn cap(&mut self, max: usize) { + for (kind, side) in [ + (Kind::Env, Side::Uses), + (Kind::Symbol, Side::Uses), + (Kind::Env, Side::Exposes), + (Kind::Event, Side::Uses), + (Kind::Endpoint, Side::Uses), + ] { + if self.entries.len() <= max { + return; + } + let over = self.entries.len() - max; + let mut dropped = 0; + self.entries.retain(|e| { + if dropped < over && e.kind == kind && e.side == side { + dropped += 1; + false + } else { + true + } + }); + } + self.entries.truncate(max); + } + + /// The record as stored: gzipped JSON, at most [`MAX_BODY_BYTES`] + /// (entries trimmed the way [`Record::replace_files`] trims them). + pub fn to_body(&self) -> Vec { + let mut r = self.clone(); + loop { + let body = crate::app_map::gzip(&serde_json::to_vec(&r).unwrap_or_default()); + if body.len() <= MAX_BODY_BYTES || r.entries.is_empty() { + return body; + } + let keep = r.entries.len() * 3 / 4; + r.cap(keep); + } + } + + pub fn from_body(bytes: &[u8]) -> Option { + let raw = crate::app_map::gunzip(bytes, 16 * MAX_BODY_BYTES)?; + serde_json::from_slice(&raw).ok() + } + + /// The packages this repository exposes, with the folder each covers. + pub fn packages(&self) -> Vec<(String, String)> { + self.entries + .iter() + .filter(|e| e.kind == Kind::Package && e.side == Side::Exposes) + .map(|e| { + let dir = e.file.rsplit_once('/').map(|(d, _)| d).unwrap_or(""); + (e.key.clone(), dir.to_string()) + }) + .collect() + } + + /// The package `path` belongs to: the deepest manifest folder holding it. + pub fn package_of(&self, path: &str) -> Option { + self.packages() + .into_iter() + .filter(|(_, dir)| dir.is_empty() || path.starts_with(&format!("{dir}/"))) + .max_by_key(|(_, dir)| dir.len()) + .map(|(p, _)| p) + } +} + +// ── The installation's index ─────────────────────────────────────────────── + +/// Which way a link points from the files asked about. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Direction { + /// Another repository uses what these files expose. + Consumer, + /// These files use what another repository exposes. + Producer, +} + +/// A contract between a file of the repository asked about and a file of +/// another repository of the installation. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct Link { + pub direction: Direction, + pub kind: Kind, + /// The contract as people read it. + pub contract: String, + /// `file:line` in the repository asked about. + pub here: String, + /// The other repository (`owner/name`). + pub repo: String, + /// `file:line` there. + pub at: String, +} + +impl Link { + /// One line naming both ends. + pub fn line(&self) -> String { + match self.direction { + Direction::Consumer => format!( + "{} `{}` (here at {}) is used by {} at {}", + self.kind.word(), + self.contract, + self.here, + self.repo, + self.at + ), + Direction::Producer => format!( + "{} `{}` (used here at {}) is exposed by {} at {}", + self.kind.word(), + self.contract, + self.here, + self.repo, + self.at + ), + } + } + + /// The same line for a public repository's readers when the other end + /// is private: no repository name and no path, only what kind of place. + pub fn line_without_names(&self) -> String { + match self.direction { + Direction::Consumer => format!( + "{} `{}` (here at {}) is used in a private repository of the installation", + self.kind.word(), + self.contract, + self.here + ), + Direction::Producer => format!( + "{} `{}` (used here at {}) is exposed by a private repository of the installation", + self.kind.word(), + self.contract, + self.here + ), + } + } +} + +/// Every repository's record, read at once. +#[derive(Debug, Clone, Default)] +pub struct Index { + pub records: Vec, +} + +fn same_repo(a: &str, b: &str) -> bool { + a.eq_ignore_ascii_case(b) +} + +fn keys_match(kind: Kind, a: &str, b: &str) -> bool { + match kind { + Kind::Endpoint => paths_match(a, b), + _ => a == b, + } +} + +impl Index { + pub fn record(&self, repo: &str) -> Option<&Record> { + self.records.iter().find(|r| same_repo(&r.repo, repo)) + } + + pub fn is_empty(&self) -> bool { + self.records.iter().all(|r| r.entries.is_empty()) + } + + /// Every package some repository of the installation exposes. + pub fn exposed_packages(&self) -> BTreeSet { + self.records + .iter() + .flat_map(|r| r.packages().into_iter().map(|(p, _)| p)) + .collect() + } + + /// What `paths` of `repo` reach in the installation's other + /// repositories: the uses elsewhere of what they expose (consumers; + /// for a file inside a package, the package's dependents and every + /// symbol they import from it) and the exposures elsewhere of what they + /// use (producers). At most [`MAX_LINKS`], consumers first. + pub fn links(&self, repo: &str, paths: &[String]) -> Vec { + let Some(own) = self.record(repo) else { + return Vec::new(); + }; + let asked: BTreeSet<&str> = paths.iter().map(String::as_str).collect(); + let mine: Vec<&Entry> = own + .entries + .iter() + .filter(|e| asked.contains(e.file.as_str())) + .collect(); + let packages: BTreeSet<(String, String)> = paths + .iter() + .filter_map(|p| { + let pkg = own.package_of(p)?; + let manifest = own + .entries + .iter() + .find(|e| e.kind == Kind::Package && e.side == Side::Exposes && e.key == pkg) + .map(Entry::at) + .unwrap_or_default(); + Some((pkg, manifest)) + }) + .collect(); + let mut out: BTreeSet = BTreeSet::new(); + for other in self.records.iter().filter(|r| !same_repo(&r.repo, repo)) { + for theirs in &other.entries { + for e in &mine { + if e.kind != theirs.kind + || e.side == theirs.side + || !keys_match(e.kind, &e.key, &theirs.key) + { + continue; + } + let (direction, contract) = if e.side == Side::Exposes { + (Direction::Consumer, e.label()) + } else { + (Direction::Producer, theirs.label()) + }; + out.insert(Link { + direction, + kind: e.kind, + contract, + here: e.at(), + repo: other.repo.clone(), + at: theirs.at(), + }); + } + if theirs.side != Side::Uses { + continue; + } + for (pkg, manifest) in &packages { + let hit = match theirs.kind { + Kind::Package => &theirs.key == pkg, + Kind::Symbol => theirs.key.split('#').next() == Some(pkg.as_str()), + _ => false, + }; + if hit { + out.insert(Link { + direction: Direction::Consumer, + kind: theirs.kind, + contract: theirs.key.clone(), + here: manifest.clone(), + repo: other.repo.clone(), + at: theirs.at(), + }); + } + } + } + } + // Consumers first; within them, the kinds that break hardest. + let mut v: Vec = out.into_iter().collect(); + v.sort_by_key(|l| (l.direction, l.kind == Kind::Env, l.kind)); + v.truncate(MAX_LINKS); + v + } + + /// Every repository that exposes or uses a contract named `key` (an + /// endpoint path, a GraphQL field, a topic, a package, a variable), + /// as `(repo, entry)`. + pub fn lookup(&self, key: &str) -> Vec<(String, Entry)> { + let key = key.trim(); + let path = norm_path(key.split_whitespace().last().unwrap_or(key)); + let pkg = norm_package(key); + let mut out = Vec::new(); + for r in &self.records { + for e in &r.entries { + let hit = match e.kind { + Kind::Endpoint => path.as_deref().is_some_and(|p| paths_match(p, &e.key)), + Kind::Package => e.key == pkg, + Kind::Symbol => { + e.key == pkg || e.key.split('#').nth(1).is_some_and(|s| s == key) + } + Kind::Graphql => { + e.key.eq_ignore_ascii_case(key) + || e.key.split('.').nth(1).is_some_and(|f| f == key) + } + _ => e.key == key, + }; + if hit { + out.push((r.repo.clone(), e.clone())); + } + if out.len() >= MAX_LINKS { + return out; + } + } + } + out + } +} + +// ── What a change does to a contract ─────────────────────────────────────── + +/// The lines a unified patch removes (with their base-side numbers) and +/// the text of the lines it adds. +pub fn patch_lines(patch: &str) -> (Vec<(u64, String)>, Vec) { + let mut removed = Vec::new(); + let mut added = Vec::new(); + let mut old: u64 = 0; + for l in patch.lines() { + if let Some(h) = l.strip_prefix("@@ -") { + old = h + .split([',', ' ']) + .next() + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + continue; + } + if let Some(t) = l.strip_prefix('-') { + removed.push((old, t.to_string())); + old += 1; + } else if let Some(t) = l.strip_prefix('+') { + added.push(t.to_string()); + } else { + old += 1; + } + } + (removed, added) +} + +/// A contract a change removes or renames that other repositories of the +/// installation use: a certain break for each of them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Break { + pub kind: Kind, + pub contract: String, + /// Where it was defined (`file:line`, base side). + pub at: String, + pub file: String, + pub line: u64, + /// `(repo, file:line)` of each use elsewhere. + pub consumers: Vec<(String, String)>, +} + +/// Whether the added lines still expose `e` (the definition was rewritten, +/// not removed). +fn still_exposed(path: &str, e: &Entry, added: &[String]) -> bool { + let text = added.join("\n"); + match e.kind { + Kind::Graphql => { + let field = e.key.split('.').nth(1).unwrap_or(""); + added.iter().any(|l| { + GQL_FIELD + .captures(l) + .is_some_and(|c| c.get(1).map(|m| m.as_str()) == Some(field)) + }) + } + Kind::Package => { + text.contains(&format!("\"{}\"", e.key)) + || norm_package(&text).contains(&format!("\"{}\"", e.key)) + || norm_package(&text).contains(&e.key) + } + Kind::Env => added + .iter() + .any(|l| ENV_SET.captures(l).is_some_and(|c| c[1] == e.key)), + _ => extract(path, &text, &|_| true).iter().any(|x| { + x.kind == e.kind && x.side == Side::Exposes && keys_match(e.kind, &x.key, &e.key) + }), + } +} + +impl Index { + /// The contracts `changed` (`(path, patch)` of `repo`) removes or + /// renames that another repository uses: each a certain break. A + /// definition rewritten with its contract kept is not one. + pub fn breaks(&self, repo: &str, changed: &[(String, String)]) -> Vec { + let Some(own) = self.record(repo) else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (path, patch) in changed { + let (removed, added) = patch_lines(patch); + if removed.is_empty() { + continue; + } + let gone: BTreeSet = removed.iter().map(|(n, _)| *n).collect(); + let links = self.links(repo, std::slice::from_ref(path)); + for e in own + .entries + .iter() + .filter(|e| &e.file == path && e.side == Side::Exposes) + { + if !gone.contains(&(e.line as u64)) || still_exposed(path, e, &added) { + continue; + } + let mut consumers: Vec<(String, String)> = links + .iter() + .filter(|l| { + l.direction == Direction::Consumer + && l.here == e.at() + && (l.kind == e.kind + || (e.kind == Kind::Package + && matches!(l.kind, Kind::Package | Kind::Symbol))) + }) + .map(|l| (l.repo.clone(), l.at.clone())) + .collect(); + consumers.dedup(); + if consumers.is_empty() { + continue; + } + out.push(Break { + kind: e.kind, + contract: e.label(), + at: e.at(), + file: e.file.clone(), + line: e.line as u64, + consumers, + }); + } + } + out + } +} + +/// Whether `text` carries a compatibility section. +pub fn has_compat(text: &str) -> bool { + text.lines() + .any(|l| l.trim().eq_ignore_ascii_case(COMPAT_HEADING)) +} + +/// The consumer links whose repository isn't one the work changes: the +/// ones a change must keep compatible, or bring into its plan. +pub fn outside<'a>(links: &'a [Link], work_repos: &[String]) -> Vec<&'a Link> { + links + .iter() + .filter(|l| { + l.direction == Direction::Consumer + && l.kind != Kind::Env + && !work_repos.iter().any(|r| same_repo(r, &l.repo)) + }) + .collect() +} + +/// A line for one link, as a reader of `public_target` may see it: a +/// private repository is never named in a public one. +pub fn shown(l: &Link, public_target: bool, private: &dyn Fn(&str) -> bool) -> String { + if public_target && private(&l.repo) { + l.line_without_names() + } else { + l.line() + } +} + +/// The compatibility section a pull request carries when its change +/// touches contracts other repositories use and doesn't update them, and +/// its description has none. `None` when nothing is owed. +pub fn compat_section( + owed: &[&Link], + breaks: &[Break], + public_target: bool, + private: &dyn Fn(&str) -> bool, +) -> Option { + if owed.is_empty() && breaks.is_empty() { + return None; + } + let mut out = format!( + "{COMPAT_HEADING}\nThis change touches contracts other repositories of the installation \ + use, and this pull request doesn't change them:\n" + ); + let mut seen = BTreeSet::new(); + for l in owed.iter().take(12) { + let line = shown(l, public_target, private); + if seen.insert(line.clone()) { + out.push_str(&format!("- {line}\n")); + } + } + for b in breaks.iter().take(6) { + let named = b + .consumers + .iter() + .filter(|(r, _)| !(public_target && private(r))) + .map(|(r, at)| format!("{r} at {at}")) + .collect::>(); + let hidden = b.consumers.len() - named.len(); + let mut who = named.join(", "); + if hidden > 0 { + if !who.is_empty() { + who.push_str(" and "); + } + who.push_str(&format!( + "{hidden} place(s) in private repositories of the installation" + )); + } + out.push_str(&format!( + "- **Breaking:** {} `{}` (removed at {}) is still used by {who}\n", + b.kind.word(), + b.contract, + b.at + )); + } + out.push_str( + "\nThe change must stay backward compatible with them, or they need the matching change \ + before this merges.\n", + ); + Some(out) +} + +// ── Storage ──────────────────────────────────────────────────────────────── + +/// The partition every record of a team sits in. +pub fn pk(team_id: &str) -> String { + format!("XC#{team_id}") +} + +/// A repository's record's sort key. +pub fn sk(repo: &str) -> String { + format!("REPO#{}", repo.to_lowercase()) +} + +type DynamoClient = aws_sdk_dynamodb::Client; + +/// One repository's stored record, when it has one. +pub async fn load_record( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, +) -> Option { + use aws_sdk_dynamodb::types::AttributeValue; + let out = dynamo + .get_item() + .table_name(table) + .key("pk", AttributeValue::S(pk(team_id))) + .key("sk", AttributeValue::S(sk(repo))) + .send() + .await + .ok()?; + let body = out.item()?.get("body")?.as_b().ok()?; + Record::from_body(body.as_ref()) +} + +/// Writes one repository's record; the team's index in memory is dropped +/// so the next read has it. +pub async fn save_record( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + record: &Record, +) -> Result<(), String> { + use aws_sdk_dynamodb::primitives::Blob; + use aws_sdk_dynamodb::types::AttributeValue; + dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(pk(team_id))) + .item("sk", AttributeValue::S(sk(&record.repo))) + .item("repo", AttributeValue::S(record.repo.clone())) + .item("commit", AttributeValue::S(record.commit.clone())) + .item( + "entries", + AttributeValue::N(record.entries.len().to_string()), + ) + .item("body", AttributeValue::B(Blob::new(record.to_body()))) + .item( + "updated_at", + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; + CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(team_id); + Ok(()) +} + +async fn read_index(dynamo: &DynamoClient, table: &str, team_id: &str) -> Result { + use aws_sdk_dynamodb::types::AttributeValue; + let mut records = Vec::new(); + let mut start = None; + loop { + let out = dynamo + .query() + .table_name(table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(pk(team_id))) + .expression_attribute_values(":p", AttributeValue::S("REPO#".into())) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; + for it in out.items() { + if let Some(r) = it + .get("body") + .and_then(|b| b.as_b().ok()) + .and_then(|b| Record::from_body(b.as_ref())) + { + records.push(r); + } + } + match out.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + Ok(Index { records }) +} + +type Kept = (Instant, Arc); +static CACHE: LazyLock>> = LazyLock::new(Default::default); + +/// The team's whole index, read at most every [`KEEP_SECS`] (one query). +/// `None` when it can't be read or holds nothing yet. +pub async fn team_index(dynamo: &DynamoClient, table: &str, team_id: &str) -> Option> { + if team_id.is_empty() { + return None; + } + if let Some((at, idx)) = CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(team_id) + .cloned() + { + if at.elapsed() < Duration::from_secs(KEEP_SECS) { + return (!idx.is_empty()).then_some(idx); + } + } + let idx = match read_index(dynamo, table, team_id).await { + Ok(i) => Arc::new(i), + Err(e) => { + tracing::warn!(error = %e, "Contract index: could not be read"); + return None; + } + }; + CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(team_id.to_string(), (Instant::now(), idx.clone())); + (!idx.is_empty()).then_some(idx) +} + +// ── The tool every loop has ──────────────────────────────────────────────── + +/// What every loop's system prompt says about the index. +pub fn prompt() -> String { + format!( + "Before you change, plan, review or explain an endpoint, a GraphQL field, an event or \ + queue message, a package, an exported type or function, or an environment variable, \ + call {TOOL}: the installation's index of which repositories expose and use it, each at \ + its file and line. Keep every consumer working: change it in the same plan, or keep \ + the change backward compatible and say so under `{COMPAT_HEADING}`." + ) +} + +/// The tool's definition. +pub fn def() -> Value { + json!({ + "name": TOOL, + "description": "The installation's contract index: which repositories use what a file exposes (consumers) and which expose what it uses (producers): endpoints, GraphQL fields, events and queue messages, packages and the symbols imported from them, environment variables. Give a file (`path`, in `repo` or this work's repository) or a contract (`key`: an endpoint like GET /books/:id, a GraphQL field like Query.books, a topic, a package name, a variable). Answers from the index, every repository at once, each with its file:line.", + "input_schema": {"type": "object", "properties": { + "repo": {"type": "string", "description": "owner/name; leave out for this work's repository"}, + "path": {"type": "string", "description": "A file's path in that repository"}, + "key": {"type": "string", "description": "A contract to find everywhere"} + }} + }) +} + +/// The tool's answer over `index` for a loop working in `here`. +pub fn answer(index: Option<&Index>, here: &str, input: &Value) -> (String, Vec) { + let Some(index) = index else { + return ( + "The installation's contract index has no entries yet (it is built with each \ + repository's code graph). Use search_repo across the installation instead." + .to_string(), + Vec::new(), + ); + }; + let repo = input["repo"] + .as_str() + .map(str::trim) + .filter(|r| !r.is_empty()) + .unwrap_or(here); + if let Some(path) = input["path"] + .as_str() + .map(str::trim) + .filter(|p| !p.is_empty()) + { + if index.record(repo).is_none() { + return ( + format!( + "{repo} isn't in the contract index yet. Use search_repo for the contract's \ + name across the installation." + ), + Vec::new(), + ); + } + let links = index.links(repo, &[path.to_string()]); + if links.is_empty() { + return ( + format!( + "Nothing in another repository of the installation uses what {repo} {path} \ + exposes, or exposes what it uses, as far as the index knows." + ), + Vec::new(), + ); + } + let text = links + .iter() + .map(|l| format!("- {}", l.line())) + .collect::>() + .join("\n"); + return (text, links); + } + let key = input["key"].as_str().unwrap_or("").trim(); + if key.is_empty() { + return ("Give a `path` or a `key`.".to_string(), Vec::new()); + } + let hits = index.lookup(key); + if hits.is_empty() { + return ( + format!("No repository of the installation exposes or uses `{key}`, as far as the index knows."), + Vec::new(), + ); + } + let links: Vec = hits + .iter() + .map(|(r, e)| Link { + direction: if e.side == Side::Exposes { + Direction::Producer + } else { + Direction::Consumer + }, + kind: e.kind, + contract: e.label(), + here: String::new(), + repo: r.clone(), + at: e.at(), + }) + .collect(); + let text = hits + .iter() + .map(|(r, e)| { + format!( + "- {r} {} {} `{}` at {}", + if e.side == Side::Exposes { + "exposes" + } else { + "uses" + }, + e.kind.word(), + e.label(), + e.at() + ) + }) + .collect::>() + .join("\n"); + (text, links) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn all(_: &str) -> bool { + true + } + + #[test] + fn paths_normalize_and_match() { + assert_eq!(norm_path("/books/:id").as_deref(), Some("/books/{}")); + assert_eq!( + norm_path("/books/${id}?full=1").as_deref(), + Some("/books/{}") + ); + assert_eq!( + norm_path("https://api.example.com/v1/books/{bookId}").as_deref(), + Some("/v1/books/{}") + ); + assert_eq!(norm_path("${API}/books/").as_deref(), Some("/books/{}")); + assert_eq!(norm_path("/"), None); + assert_eq!(norm_path("books"), None); + assert!(paths_match("/books/{}", "/books/{}")); + assert!(paths_match("/api/books/{}", "/books/{}")); + assert!(!paths_match("/books", "/authors")); + assert!(!paths_match("/{}", "/books/{}")); + assert!(!paths_match("/{}/{}", "/a/{}/{}")); + } + + #[test] + fn every_kind_is_extracted() { + let api = "app.get('/books/:id', (req, res) => {});\nrouter.post(\"/orders\", create);\nawait publish('order.placed', o);\nconst key = process.env.STRIPE_KEY;\n"; + let e = extract("src/routes.ts", api, &all); + let has = |k: Kind, key: &str, s: Side| { + e.iter().any(|x| x.kind == k && x.key == key && x.side == s) + }; + assert!(has(Kind::Endpoint, "/books/{}", Side::Exposes)); + assert!(has(Kind::Endpoint, "/orders", Side::Exposes)); + assert!(has(Kind::Event, "order.placed", Side::Exposes)); + assert!(has(Kind::Env, "STRIPE_KEY", Side::Uses)); + let web = "import { Book, formatPrice } from '@acme/book-types';\nconst r = await fetch(`/api/books/${id}`);\nconst o = await api.post('/orders', body);\nconsumer.subscribe('order.placed');\n"; + let e = extract("src/books.tsx", web, &|p| p == "@acme/book_types"); + let has = |k: Kind, key: &str, s: Side| { + e.iter().any(|x| x.kind == k && x.key == key && x.side == s) + }; + assert!(has(Kind::Endpoint, "/api/books/{}", Side::Uses)); + assert!(has(Kind::Endpoint, "/orders", Side::Uses)); + assert!(has(Kind::Event, "order.placed", Side::Uses)); + assert!(has(Kind::Symbol, "@acme/book_types#Book", Side::Uses)); + assert!(has( + Kind::Symbol, + "@acme/book_types#formatPrice", + Side::Uses + )); + // A public library's imports are not kept. + let e = extract("src/a.ts", "import { useState } from 'react';", &|p| { + p != "react" + }); + assert!(e.is_empty()); + let schema = "type Query {\n books(first: Int): [Book!]!\n book(id: ID!): Book\n}\ntype Book { id: ID! }\n"; + let e = extract("schema.graphql", schema, &all); + assert!(e + .iter() + .any(|x| x.key == "Query.books" && x.side == Side::Exposes && x.line == 2)); + assert!(e.iter().any(|x| x.key == "Query.book" && x.line == 3)); + assert!(!e.iter().any(|x| x.key == "Query.id")); + let op = "const Q = gql`\n query Shelf($n: Int) {\n books(first: $n) { id }\n }\n`;"; + let e = extract("src/shelf.ts", op, &all); + assert!(e + .iter() + .any(|x| x.key == "Query.books" && x.side == Side::Uses)); + let pkg = + "{\n \"name\": \"@acme/book-types\",\n \"dependencies\": {\"left-pad\": \"1\"}\n}"; + let e = extract("package.json", pkg, &all); + assert!(e.iter().any(|x| x.kind == Kind::Package + && x.key == "@acme/book_types" + && x.side == Side::Exposes + && x.line == 2)); + let e = extract( + "Cargo.toml", + "[package]\nname = \"shelf-core\"\n\n[dependencies]\nserde = \"1\"\n", + &all, + ); + assert!(e + .iter() + .any(|x| x.key == "shelf_core" && x.side == Side::Exposes)); + assert!(e.iter().any(|x| x.key == "serde" && x.side == Side::Uses)); + let e = extract(".env.example", "STRIPE_KEY=\nPORT=3000\n", &all); + assert!(e + .iter() + .any(|x| x.key == "STRIPE_KEY" && x.side == Side::Exposes)); + assert!(!e.iter().any(|x| x.key == "PORT")); + assert!(scans("src/a.ts") && scans("package.json") && !scans("node_modules/x/a.js")); + assert!(!scans("assets/logo.png")); + } + + fn rec(repo: &str, entries: Vec) -> Record { + Record { + repo: repo.into(), + commit: "c".into(), + entries, + } + } + + fn bookstore() -> Index { + let api = extract( + "src/routes/books.ts", + "\n\napp.get('/books/:id', show);\napp.delete('/books/:id', drop);\n", + &all, + ); + let mut api_rec = rec("acme/orders-api", api); + api_rec.replace_files( + &[], + extract("package.json", "{\"name\": \"orders-api\"}", &all), + ); + let web = extract( + "src/pages/book.tsx", + "const b = await fetch(`/api/books/${id}`);\n", + &all, + ); + let types_pkg = extract("package.json", "{\"name\": \"@acme/book-types\"}", &all); + let mut types = rec("acme/book-types", types_pkg); + types.replace_files( + &[], + extract("src/book.ts", "export interface Book {}\n", &all), + ); + let mut web_rec = rec("acme/storefront", web); + web_rec.replace_files( + &[], + extract( + "src/cart.ts", + "import { Book } from '@acme/book-types';\n", + &all, + ), + ); + Index { + records: vec![api_rec, web_rec, types], + } + } + + #[test] + fn the_index_links_both_ways_and_reads_packages() { + let idx = bookstore(); + let l = idx.links("acme/orders-api", &["src/routes/books.ts".into()]); + assert!(l.iter().any(|l| l.direction == Direction::Consumer + && l.repo == "acme/storefront" + && l.at == "src/pages/book.tsx:1" + && l.here == "src/routes/books.ts:3")); + let p = idx.links("acme/storefront", &["src/pages/book.tsx".into()]); + assert!(p + .iter() + .any(|l| l.direction == Direction::Producer && l.repo == "acme/orders-api")); + // A file of a package reaches whoever imports from the package. + let t = idx.links("acme/book-types", &["src/book.ts".into()]); + assert!(t.iter().any(|l| l.kind == Kind::Symbol + && l.repo == "acme/storefront" + && l.at == "src/cart.ts:1")); + assert!(idx.links("acme/unknown", &["x".into()]).is_empty()); + } + + #[test] + fn a_removed_route_with_a_consumer_is_a_break_and_a_rewrite_is_not() { + let idx = bookstore(); + let removed = + "@@ -3,2 +3,1 @@\n-app.get('/books/:id', show);\n app.delete('/books/:id', drop);\n"; + let b = idx.breaks( + "acme/orders-api", + &[("src/routes/books.ts".into(), removed.into())], + ); + assert_eq!(b.len(), 1); + assert_eq!(b[0].at, "src/routes/books.ts:3"); + assert_eq!( + b[0].consumers, + vec![( + "acme/storefront".to_string(), + "src/pages/book.tsx:1".to_string() + )] + ); + let kept = "@@ -3,1 +3,1 @@\n-app.get('/books/:id', show);\n+app.get('/books/:id', showWithAuthor);\n"; + assert!(idx + .breaks( + "acme/orders-api", + &[("src/routes/books.ts".into(), kept.into())] + ) + .is_empty()); + } + + #[test] + fn records_are_incremental_bounded_and_round_trip() { + let mut r = rec("acme/a", extract("src/a.ts", "app.get('/a/b', h);", &all)); + r.replace_files( + &["src/a.ts".into()], + extract("src/a.ts", "app.get('/a/c', h);", &all), + ); + assert_eq!(r.entries.len(), 1); + assert_eq!(r.entries[0].key, "/a/c"); + let back = Record::from_body(&r.to_body()).unwrap(); + assert_eq!(back, r); + let mut big = rec("acme/b", Vec::new()); + let many: Vec = (0..MAX_ENTRIES + 50) + .map(|i| Entry::new(Kind::Env, format!("VAR_{i}"), Side::Uses, "x.ts", i)) + .collect(); + big.replace_files(&[], many); + assert_eq!(big.entries.len(), MAX_ENTRIES); + } + + #[test] + fn the_tool_answers_by_file_and_by_key() { + let idx = bookstore(); + let (t, links) = answer( + Some(&idx), + "acme/orders-api", + &json!({"path": "src/routes/books.ts"}), + ); + assert!(t.contains("acme/storefront") && !links.is_empty()); + let (t, _) = answer( + Some(&idx), + "acme/orders-api", + &json!({"key": "GET /books/:id"}), + ); + assert!(t.contains("acme/orders-api exposes") && t.contains("acme/storefront uses")); + let (t, _) = answer(None, "acme/orders-api", &json!({"key": "x"})); + assert!(t.contains("search_repo")); + } + + #[test] + fn the_compat_section_never_names_a_private_repo_in_a_public_one() { + let idx = bookstore(); + let links = idx.links("acme/orders-api", &["src/routes/books.ts".into()]); + let owed = outside(&links, &["acme/orders-api".into()]); + assert!(!owed.is_empty()); + let private = |r: &str| r == "acme/storefront"; + let public = compat_section(&owed, &[], true, &private).unwrap(); + assert!(public.starts_with(COMPAT_HEADING)); + assert!(!public.contains("acme/storefront") && !public.contains("src/pages/book.tsx")); + let internal = compat_section(&owed, &[], false, &private).unwrap(); + assert!(internal.contains("acme/storefront at src/pages/book.tsx:1")); + // A plan that changes the consumer too owes nothing. + assert!(outside( + &links, + &["acme/orders-api".into(), "acme/storefront".into()] + ) + .is_empty()); + assert!(has_compat(&public)); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 90a938e7d..2e4f57086 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -210,6 +210,9 @@ pub mod staging_cms; // Anthropic SSE calls, metered per attempt (drops, retries, the deadline) pub mod model_stream; // Titan embeddings, metered as CoderHelm's own cost +/// The installation's contract index: which repositories expose and use +/// each endpoint, schema field, event, package and variable. +pub mod contracts; pub mod embed; /// Knowledge bases: files a team uploads, read into cited passages that the /// brain chat and the team's agents search. diff --git a/services/common/src/repo_reach.rs b/services/common/src/repo_reach.rs index 7e4bc8338..fc3392cc3 100644 --- a/services/common/src/repo_reach.rs +++ b/services/common/src/repo_reach.rs @@ -338,13 +338,17 @@ fn quotable(line: &str) -> Option<&str> { /// 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. +/// more) and something of it was read, and each path read. A repository +/// only known by name (no path, no lines: one the contract index named) +/// is matched by its `owner/name`, so a common word that happens to be a +/// repository's name stays readable. 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 { + let read = !r.path.is_empty() || !r.lines.is_empty(); + if read && short.chars().count() >= 5 { out.push(short); } if !r.path.is_empty() { @@ -479,6 +483,108 @@ fn redact_prose(text: &str, reads: &[Read]) -> String { out.join("\n").trim().to_string() } +// ── Every surface of a public repository ────────────────────────────────── +// +// A reply is one surface. Code, commit messages, pull request titles and +// bodies, review comments and release notes written into a public +// repository are the others, and they are written by other steps than the +// loop that read: the coder reads a consumer in a private repository, the +// description step writes the body later. So every read of a private +// repository by work posting to a public one is also kept here, by the +// public repository it posts to and the installation that read it +// ([`note_private`]), and every text +// CoderHelm writes into that repository goes through [`guard_public`] +// (the GitHub client's one place for it). A private-to-private change +// keeps nothing and is never edited: it may reference freely. + +/// How long what a run read stays kept for its public repository. +pub const LEDGER_KEEP_SECS: u64 = 6 * 3600; +/// Reads kept for one public repository at most (the oldest go first). +pub const LEDGER_MAX_READS: usize = 2_000; +/// Public repositories kept at most. +const LEDGER_MAX_TARGETS: usize = 500; + +/// Keyed by the installation that read and the public repository its work +/// posts to (`{installation}:{owner/name}`): one installation's reads are +/// never held against another's writes. +#[allow(clippy::type_complexity)] +static LEDGER: LazyLock< + std::sync::Mutex)>>, +> = LazyLock::new(Default::default); + +fn ledger_key(installation: u64, target: &str) -> String { + format!("{installation}:{}", target.trim().to_lowercase()) +} + +/// Keeps what work posting to the public repository `target` read in +/// private ones (the caller knows `target` is public and `reads` private). +pub fn note_private(installation: u64, target: &str, reads: &[Read]) { + if reads.is_empty() || target.trim().is_empty() { + return; + } + let mut l = LEDGER.lock().unwrap_or_else(|e| e.into_inner()); + let keep = std::time::Duration::from_secs(LEDGER_KEEP_SECS); + l.retain(|_, (at, _)| at.elapsed() < keep); + let key = ledger_key(installation, target); + if l.len() >= LEDGER_MAX_TARGETS && !l.contains_key(&key) { + if let Some(oldest) = l + .iter() + .min_by_key(|(_, (at, _))| *at) + .map(|(k, _)| k.clone()) + { + l.remove(&oldest); + } + } + let (at, kept) = l + .entry(key) + .or_insert_with(|| (std::time::Instant::now(), Vec::new())); + *at = std::time::Instant::now(); + for r in reads { + if !kept.contains(r) { + kept.push(r.clone()); + } + } + if kept.len() > LEDGER_MAX_READS { + let over = kept.len() - LEDGER_MAX_READS; + kept.drain(..over); + } +} + +/// What `installation`'s work posting to `target` read in private +/// repositories, kept. +pub fn private_for(installation: u64, target: &str) -> Vec { + let l = LEDGER.lock().unwrap_or_else(|e| e.into_inner()); + match l.get(&ledger_key(installation, target)) { + Some((at, reads)) if at.elapsed() < std::time::Duration::from_secs(LEDGER_KEEP_SECS) => { + reads.clone() + } + _ => Vec::new(), + } +} + +/// `text` as it may be written into `target`: unchanged when nothing +/// private was read for it (a private repository, or nothing read), else +/// with what came from a private repository taken out ([`redact`]). +pub fn guard_public(installation: u64, target: &str, text: &str) -> String { + let reads = private_for(installation, target); + if leak(text, &reads).is_none() { + return text.to_string(); + } + tracing::warn!( + target, + "Text for a public repository carried private content; taken out" + ); + redact(text, &reads) +} + +/// What the coder is told when a file it writes into a public repository +/// copies a private one. +pub fn code_refused(why: &str) -> String { + format!( + "Refused: this repository is public, and this write carries content from a private repository of the team ({why}). Write the code in your own words for this repository: no line copied from a private repository and no private repository's name or path in code, comments or messages. Keep the behaviour you need." + ) +} + // ── The guard on what people read ────────────────────────────────────────── /// A sentence in which CoderHelm says, in the first person, that it can't @@ -748,6 +854,38 @@ mod tests { assert_eq!(strip(honest, &r), honest); } + #[test] + fn every_public_surface_is_guarded_and_private_targets_are_not() { + let reads = [ + Read { + repo: "acme/pricing-engine".into(), + path: "src/discounts.ts".into(), + lines: vec!["export const memberDiscount = (cart) => cart.total * 0.15;".into()], + }, + Read { + repo: "acme/orders".into(), + path: String::new(), + lines: Vec::new(), + }, + ]; + note_private(7, "acme/open-shelf", &reads); + let body = "Prices now match acme/pricing-engine.\nMembers get their discount.\nSee acme/orders for the caller."; + let kept = guard_public(7, "ACME/open-shelf", body); + assert_eq!(kept, "Members get their discount."); + // A repository known only by name is matched by owner/name alone. + assert_eq!( + guard_public(7, "acme/open-shelf", "Two orders were placed."), + "Two orders were placed." + ); + // Another installation's writes are never held to these reads. + assert_eq!(guard_public(8, "acme/open-shelf", body), body); + // A target nothing was kept for (private, or nothing read) is untouched. + assert_eq!(guard_public(7, "acme/back-office", body), body); + let code = "const d = (cart) => cart.total * 0.15;\nexport const memberDiscount = (cart) => cart.total * 0.15;"; + assert!(leak(code, &private_for(7, "acme/open-shelf")).is_some()); + assert!(code_refused("x").starts_with("Refused")); + } + #[test] fn refusal_statuses_are_read() { assert_eq!(status_of(&ReadError::NotFound("x".into())), 404); diff --git a/services/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index b3f856777..6fa847fcf 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -68,6 +68,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("list_repos", Risk::Read), ("read_repo_file", Risk::Read), ("search_repo", Risk::Read), + ("find_consumers", Risk::Read), ("graph_definition", Risk::Read), ("graph_callers", Risk::Read), ("graph_impact", Risk::Read), diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 4f4705ef7..8b95bac0b 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -401,13 +401,28 @@ async fn converse_as( let missing = access.as_ref().err().cloned().unwrap_or_default(); // 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(), - ); + // The installation's contract index (`common::contracts`): every loop + // can ask which repositories use what it is changing or explaining. + let index = if reaches { + common::contracts::team_index( + &state.dynamo, + &state.config.settings_table_name, + &provider.scope.team, + ) + .await + } else { + None + }; + 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(), + access.as_ref().map(|a| a.installation).unwrap_or(0), + ) + .with_index(index, &provider.scope.repo); let system = if reaches { super::reach::prompt(system_prompt) } else { diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs index 1f2bd7fe3..5e6ede0f1 100644 --- a/services/worker/src/agent/reach.rs +++ b/services/worker/src/agent/reach.rs @@ -8,9 +8,16 @@ //! ([`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. +//! +//! The same loop is offered the installation's contract index +//! (`common::contracts`, the `find_consumers` tool) and told to ask it +//! before it changes or explains a contract. Work posting to a public +//! repository keeps what it read in a private one (`repo_reach:: +//! note_private`), and a write tool's input that copies it is refused +//! with the reason, so code written there never carries it. use std::collections::{BTreeSet, HashMap}; -use std::sync::{LazyLock, Mutex}; +use std::sync::{Arc, LazyLock, Mutex}; use std::time::{Duration, Instant}; use common::mcp_remote::http::GuardedHttps; @@ -38,6 +45,8 @@ pub struct Access { /// `owner/name` (lower case) of each repository GitHub says is /// public. Any other is private, a failed read included. pub public: BTreeSet, + /// The installation the token is for. + pub installation: u64, } impl Access { @@ -96,6 +105,7 @@ async fn read_access(state: &crate::WorkerState, team: &str) -> Result Vec { if out.is_empty() { return out; } - for d in repo_reach::defs() { + for d in repo_reach::defs() + .into_iter() + .chain([common::contracts::def()]) + { let name = d["name"].as_str().unwrap_or_default().to_string(); if out.iter().any(|t| t.name == name) { continue; @@ -136,13 +149,50 @@ pub fn offer(tools: &[ToolDefinition]) -> Vec { /// `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(); + let words = format!("{} {}", repo_reach::prompt(), common::contracts::prompt()); if system.contains(&words) { return system.to_string(); } format!("{}\n\n{words}", system.trim_end()) } +/// Whether a tool writes what its input carries (a file's content, an +/// edit, a commit): what such a call writes into a public repository is +/// held to `repo_reach::leak`. +pub fn writes(name: &str) -> bool { + let n = name.to_lowercase(); + let reads = ["read", "search", "list", "graph_", "map_", "find", "get_"]; + if reads.iter().any(|r| n.starts_with(r)) { + return false; + } + [ + "write", + "edit", + "create_file", + "replace", + "insert", + "patch", + "append", + "commit", + "apply", + ] + .iter() + .any(|w| n.contains(w)) +} + +/// Every string a tool's input carries, one after another. +fn input_text(v: &Value, out: &mut String) { + match v { + Value::String(s) => { + out.push_str(s); + out.push('\n'); + } + Value::Array(a) => a.iter().for_each(|x| input_text(x, out)), + Value::Object(o) => o.values().for_each(|x| input_text(x, out)), + _ => {} + } +} + /// 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 { @@ -164,10 +214,15 @@ pub struct Exec<'a> { 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>, + /// The repository this loop's reply goes to and the repositories known + /// public, when that repository is public; `None` otherwise (nothing to + /// keep apart). + public_reply: Option<(u64, String, BTreeSet)>, private_reads: Mutex>, + /// The installation's contract index, for `find_consumers`, and the + /// repository the work is in. + index: Option>, + here: String, } impl<'a> Exec<'a> { @@ -185,16 +240,31 @@ impl<'a> Exec<'a> { refusals: Mutex::new(Vec::new()), public_reply: None, private_reads: Mutex::new(Vec::new()), + index: None, + here: String::new(), } } + /// The installation's contract index for `find_consumers`, asked from + /// `here` (the work's repository). + pub fn with_index(mut self, index: Option>, here: &str) -> Self { + self.index = index; + self.here = here.to_string(); + self + } + /// 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 { + pub fn posting_to( + mut self, + target: &str, + public: &BTreeSet, + installation: u64, + ) -> Self { if is_public(public, target) { - self.public_reply = Some(public.clone()); + self.public_reply = Some((installation, target.to_string(), public.clone())); } self } @@ -209,7 +279,7 @@ impl<'a> Exec<'a> { } fn keep_reads(&self, reads: Vec) { - let Some(public) = &self.public_reply else { + let Some((installation, target, public)) = &self.public_reply else { return; }; let private: Vec = reads @@ -217,6 +287,9 @@ impl<'a> Exec<'a> { .filter(|r| !is_public(public, &r.repo)) .collect(); if !private.is_empty() { + // Kept for every later write into the public repository too: + // the pull request, its commits and its comments. + repo_reach::note_private(*installation, target, &private); self.private_reads .lock() .unwrap_or_else(|e| e.into_inner()) @@ -224,6 +297,20 @@ impl<'a> Exec<'a> { } } + /// Why a write tool's input may not be written into this loop's public + /// repository (it copies a private one), or `None`. + fn refused_write(&self, name: &str, input: &Value) -> Option { + let (installation, target, _) = self.public_reply.as_ref()?; + if !writes(name) { + return None; + } + let mut reads = self.private_reads(); + reads.extend(repo_reach::private_for(*installation, target)); + let mut text = String::new(); + input_text(input, &mut text); + repo_reach::leak(&text, &reads) + } + /// Every refusal a call of this loop returned so far. pub fn refusals(&self) -> Vec { self.refusals @@ -258,6 +345,29 @@ impl ToolExecutor for Exec<'_> { self.keep_reads(out.seen); return Ok(json!(out.text)); } + if name == common::contracts::TOOL { + let (text, links) = common::contracts::answer(self.index.as_deref(), &self.here, input); + self.keep_reads( + links + .iter() + .map(|l| Read { + repo: l.repo.clone(), + path: l + .at + .rsplit_once(':') + .map(|(p, _)| p) + .unwrap_or("") + .to_string(), + lines: Vec::new(), + }) + .collect(), + ); + return Ok(json!(text)); + } + if let Some(why) = self.refused_write(name, input) { + tracing::warn!(tool = name, why = %why, "A write into a public repository copied a private one; refused"); + return Ok(json!(repo_reach::code_refused(&why))); + } let out = self.inner.execute(name, input).await; match &out { Err(e) => { @@ -348,16 +458,69 @@ mod tests { for t in repo_reach::TOOLS { assert_eq!(coder.iter().filter(|n| *n == t).count(), 1, "{t}"); } + assert_eq!( + coder + .iter() + .filter(|n| *n == common::contracts::TOOL) + .count(), + 1 + ); // Offered once, even when a loop names one itself. let again = names(offer(&[tool(repo_reach::LIST_REPOS)])); - assert_eq!(again.len(), 3); + assert_eq!(again.len(), 4); // 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!(p.contains(&repo_reach::prompt())); + assert!(p.ends_with(&common::contracts::prompt())); assert_eq!(prompt(&p), p); } + struct Wrote; + #[async_trait::async_trait] + impl ToolExecutor for Wrote { + async fn execute( + &self, + _name: &str, + _input: &Value, + ) -> Result> { + Ok(json!("written")) + } + } + + /// Code written into a public repository never copies a private one; + /// into a private one it may. + #[tokio::test] + async fn a_public_write_that_copies_a_private_repo_is_refused() { + let public: BTreeSet = ["acme/open-catalog".to_string()].into(); + let line = "export const shelfPrice = (book) => book.list * 0.85;"; + let read = Read { + repo: "acme/pricing-rules".into(), + path: "src/shelf.ts".into(), + lines: vec![line.into()], + }; + let exec = Exec::new(&Wrote, None, "").posting_to("acme/open-catalog", &public, 7); + exec.keep_reads(vec![read.clone()]); + let copied = json!({"path": "src/price.ts", "content": format!("{line}\n")}); + let out = exec.execute("write_file", &copied).await.unwrap(); + assert!(out.as_str().unwrap().starts_with("Refused")); + let own = + json!({"path": "src/price.ts", "content": "export const price = (b) => b.list;\n"}); + assert_eq!( + exec.execute("write_file", &own).await.unwrap(), + json!("written") + ); + // A later step writing into the same public repository is held too. + assert!(!repo_reach::private_for(7, "acme/open-catalog").is_empty()); + let private = Exec::new(&Wrote, None, "").posting_to("acme/back-office", &public, 7); + private.keep_reads(vec![read]); + assert_eq!( + private.execute("write_file", &copied).await.unwrap(), + json!("written") + ); + assert!(writes("write_file") && writes("str_replace_edit") && !writes("read_file")); + } + #[test] fn a_failed_retry_keeps_the_first_answer() { let first = "The label rounds months down. I can't open the helper."; diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 52906daa3..0246f280e 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -107,6 +107,65 @@ async fn ok_or_body( } } +/// What a text written into a public repository says when all of it came +/// from a private one. +pub const LEFT_OUT: &str = + "This concerns code in a private repository of the installation, so the details are left out here."; + +/// The repository (`owner/name`) a REST write goes to, from its URL. +pub fn write_target(url: &str) -> Option { + let rest = url.split("/repos/").nth(1)?; + let mut parts = rest.split('/'); + let owner = parts.next().filter(|s| !s.is_empty())?; + let name = parts.next().filter(|s| !s.is_empty())?; + Some(format!("{owner}/{name}")) +} + +/// A write's JSON as it may reach a public repository: every text a +/// person reads there (a `body`, a `title`, a commit or dismissal +/// `message`, each inline comment's `body`) with what work posting to that +/// repository read in a private one taken out +/// (`common::repo_reach::guard_public`). A private repository, or one +/// nothing private was read for, gets the JSON as it was. Every POST, +/// PATCH and PUT this client sends goes through here, so code, commits, +/// pull requests, reviews, comments and releases are held alike. +pub fn public_payload(installation: u64, url: &str, v: &serde_json::Value) -> serde_json::Value { + let Some(target) = write_target(url) else { + return v.clone(); + }; + if common::repo_reach::private_for(installation, &target).is_empty() { + return v.clone(); + } + let mut out = v.clone(); + let guard = |o: &mut serde_json::Map| { + for key in ["body", "title", "message"] { + if let Some(t) = o.get(key).and_then(|t| t.as_str()) { + let kept = common::repo_reach::guard_public(installation, &target, t); + if kept != t { + // A text left empty still says something true. + let kept = if kept.trim().is_empty() { + LEFT_OUT.to_string() + } else { + kept + }; + o.insert(key.into(), serde_json::Value::String(kept)); + } + } + } + }; + if let Some(o) = out.as_object_mut() { + guard(o); + if let Some(cs) = o.get_mut("comments").and_then(|c| c.as_array_mut()) { + for c in cs { + if let Some(co) = c.as_object_mut() { + guard(co); + } + } + } + } + out +} + /// A write's JSON as GitHub takes it: a `body` (and each inline comment's /// `body`) within GitHub's 65,536-character limit, fitted by /// `common::pr_body_fit` (required sections and CoderHelm's markers kept, @@ -1797,7 +1856,11 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; - let mut req = self.http.post(url).json(&bounded_payload(body)); + let mut req = self.http.post(url).json(&bounded_payload(&public_payload( + self.installation_id, + url, + body, + ))); for (k, v) in headers { req = req.header(k, v); } @@ -1811,7 +1874,11 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; - let mut req = self.http.patch(url).json(&bounded_payload(body)); + let mut req = self.http.patch(url).json(&bounded_payload(&public_payload( + self.installation_id, + url, + body, + ))); for (k, v) in headers { req = req.header(k, v); } @@ -4052,7 +4119,10 @@ impl GitHubClient { body["sha"] = serde_json::json!(s); } let headers = self.auth_headers().await?; - let mut req = self.http.put(&url).json(&body); + let mut req = + self.http + .put(&url) + .json(&public_payload(self.installation_id, &url, &body)); for (k, v) in headers { req = req.header(k, v); } @@ -5272,10 +5342,11 @@ impl GitHubClient { ) -> Result<(), Box> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}"); let headers = self.auth_headers().await?; - let mut req = self - .http - .put(&url) - .json(&serde_json::json!({ "body": body })); + let mut req = self.http.put(&url).json(&public_payload( + self.installation_id, + &url, + &serde_json::json!({ "body": body }), + )); for (k, v) in headers { req = req.header(k, v); } @@ -5359,10 +5430,14 @@ impl GitHubClient { "{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}/dismissals" ); let headers = self.auth_headers().await?; - let mut req = self.http.put(&url).json(&serde_json::json!({ - "message": message, - "event": "DISMISS", - })); + let mut req = self.http.put(&url).json(&public_payload( + self.installation_id, + &url, + &serde_json::json!({ + "message": message, + "event": "DISMISS", + }), + )); for (k, v) in headers { req = req.header(k, v); } @@ -5381,10 +5456,11 @@ impl GitHubClient { ) -> Result<(), Box> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}"); let headers = self.auth_headers().await?; - let mut req = self - .http - .put(&url) - .json(&bounded_payload(&serde_json::json!({ "body": body }))); + let mut req = self.http.put(&url).json(&bounded_payload(&public_payload( + self.installation_id, + &url, + &serde_json::json!({ "body": body }), + ))); for (k, v) in headers { req = req.header(k, v); } @@ -7857,7 +7933,15 @@ mod body_limit_tests { for send in ["async fn post(", "async fn patch(", "async fn post_empty("] { let at = src.find(send).unwrap(); let rest = &src[at..at + 600]; - assert!(rest.contains("bounded_payload(body)"), "{send}"); + // Bounded, and held for a public repository first. + let flat: String = rest.split_whitespace().collect(); + assert!( + flat.contains("bounded_payload(body)") + || flat.contains( + "bounded_payload(&public_payload(self.installation_id,url,body,))" + ), + "{send}" + ); } } } diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index 725dc6c16..a47c25f87 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -697,6 +697,11 @@ async fn index_pass( let all_paths: Vec = snapshot.tree().await; let file_set: HashSet = all_paths.iter().cloned().collect(); + // The installation's contract index follows the same pass + // (`common::contracts`): a first build reads every file, a push only + // the changed ones. + refresh_contracts(state, &msg, &snapshot, &all_paths, &head).await; + // Which files to (re)extract this pass. let targets: Vec = match &msg.changed_files { Some(changed) => changed @@ -937,6 +942,93 @@ async fn index_pass( Ok(()) } +/// Brings the repository's record in the installation's contract index +/// (`common::contracts`) to `head`: on a push, only the changed files' +/// entries are replaced (a deleted file's go); a first build, or a push to +/// a repository with no record yet, reads every file. A package this pass +/// newly exposes has the repositories that depend on it read again in +/// full, at most [`REQUEUE_CAP`], so their imports of it are kept. +async fn refresh_contracts( + state: &WorkerState, + msg: &GraphIndexMessage, + snapshot: &crate::clients::repo_snapshot::RepoSnapshot, + all_paths: &[String], + head: &str, +) { + use common::contracts as xc; + let table = &state.config.settings_table_name; + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let team = xc::team_index(&state.dynamo, table, &msg.team_id).await; + let exposed: std::collections::BTreeSet = team + .as_ref() + .map(|i| i.exposed_packages()) + .unwrap_or_default(); + let stored = match &msg.changed_files { + Some(_) => xc::load_record(&state.dynamo, table, &msg.team_id, &repo).await, + None => None, + }; + let (mut record, files): (xc::Record, Vec) = match (stored, &msg.changed_files) { + (Some(r), Some(changed)) => (r, changed.clone()), + _ => ( + xc::Record { + repo: repo.clone(), + ..Default::default() + }, + all_paths.to_vec(), + ), + }; + let before: std::collections::BTreeSet = + record.packages().into_iter().map(|(p, _)| p).collect(); + let mut scanned: Vec = Vec::new(); + let mut fresh = Vec::new(); + for path in files + .iter() + .filter(|p| xc::scans(p)) + .take(xc::MAX_SCAN_FILES) + { + scanned.push(path.clone()); + let Some(src) = snapshot.read_file(path).await else { + continue; // deleted or binary: its entries go + }; + fresh.extend(xc::extract(path, &src, &|p| exposed.contains(p))); + } + record.commit = head.to_string(); + record.replace_files(&scanned, fresh); + if let Err(e) = xc::save_record(&state.dynamo, table, &msg.team_id, &record).await { + warn!(repo = %repo, error = %e, "Contract index: the record could not be written"); + return; + } + info!(repo = %repo, files = scanned.len(), entries = record.entries.len(), "Contract index: repository brought to its head"); + let Some(team) = team else { + return; + }; + let mut queued = 0; + for pkg in record + .packages() + .into_iter() + .map(|(p, _)| p) + .filter(|p| !before.contains(p) && !exposed.contains(p)) + { + for other in team.records.iter().filter(|r| { + !r.repo.eq_ignore_ascii_case(&repo) + && r.entries.iter().any(|e| { + e.kind == xc::Kind::Package && e.side == xc::Side::Uses && e.key == pkg + }) + }) { + if queued >= REQUEUE_CAP { + return; + } + if queue_full_index(state, &msg.team_id, &other.repo, msg.installation_id, false).await + { + queued += 1; + } + } + } +} + +/// Repositories read again at most when one pass newly exposes a package. +const REQUEUE_CAP: usize = 10; + // ─── Query API (what the agent's tools call) ──────────────────────────────── /// A handle to one repo's built graph (see [`availability`]). @@ -1175,6 +1267,9 @@ pub fn offer( if let Some(m) = graphs.map() { system.push_str(&m.prompt_line(role)); } + if let Some(c) = graphs.contracts() { + system.push_str(&c.prompt_line(role)); + } true } @@ -1348,6 +1443,9 @@ pub struct RepoGraphs { /// The team's app map for this step (`run_map`): its lookups ride with /// the graph's, so every agent that reads code gets them the same way. map: Option, + /// The installation's contract index for this step (`xrepo`): which + /// other repositories expose and use what the work touches. + contracts: Option, } impl RepoGraphs { @@ -1391,6 +1489,7 @@ impl RepoGraphs { run: common::live::store::RunRef::default(), others: tokio::sync::Mutex::new(HashMap::new()), map: None, + contracts: None, } } @@ -1400,11 +1499,31 @@ impl RepoGraphs { self } - /// Reads the team's app map for this step and adds it (nothing when - /// there is none, or it is stale). + /// Adds the installation's contract index (read once for this step). + pub fn with_contracts(mut self, contracts: Option) -> Self { + self.contracts = contracts; + self + } + + /// Reads the installation's maps for this step and adds them: the team's + /// app map (nothing when there is none, or it is stale) and the contract + /// index (`xrepo`), so every pass that reads code knows the other + /// repositories its change reaches. pub async fn load_map(self, state: &WorkerState) -> Self { let map = super::run_map::RunMap::load(state, &self.team_id, &self.default_repo).await; - self.with_map(map) + let contracts = super::xrepo::RunContracts::load( + state, + &self.team_id, + &self.default_repo, + self.installation_id, + ) + .await; + self.with_map(map).with_contracts(contracts) + } + + /// The installation's contract index for this step, when it has one. + pub fn contracts(&self) -> Option<&super::xrepo::RunContracts> { + self.contracts.as_ref() } /// The team's app map for this step, when it has one. diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index e9ed4f587..83179ec8f 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -897,7 +897,11 @@ Rules: .with_run( &msg.run_id, format!("{}/{}#{}", msg.repo_owner, msg.repo_name, msg.pr_number), - ); + ) + // The installation's maps: the app map and the contract index, so a + // round a person asked for knows the other repositories it reaches. + .load_map(state) + .await; super::code_graph::offer( &graphs, super::code_graph::Role::Coder, diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 51bf7c9ab..abcc9f859 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -760,6 +760,25 @@ pub async fn run( &mut tools, &mut full_system, ); + // The code in the team's other repositories that uses what this work + // changes, read up front (`xrepo`): the coder, and every CI and fix + // round through here, starts knowing its consumers. + let related = match graphs.contracts() { + Some(c) => { + let groups: Vec<(String, String)> = plan + .repo_tasks + .iter() + .map(|r| (format!("{}/{}", r.owner, r.name), r.tasks.clone())) + .collect(); + let files = super::run_map::planned( + &format!("{}/{}", msg.repo_owner, msg.repo_name), + &plan.tasks, + &groups, + ); + c.coder_context(github, &files).await + } + None => String::new(), + }; // `check_url` on the team's own public pages. let web = super::web_check::WebCheck::load( state, @@ -956,6 +975,7 @@ pub async fn run( // Attach the ticket's design mockups as images — the implementer must SEE // the design, not just the plan's text rendering of it (mirrors plan.rs). + let prompt = format!("{prompt}{related}"); let mut content_blocks = vec![serde_json::json!({"type": "text", "text": prompt})]; for img in &msg.image_attachments { if let Some(b64) = 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 0c1508149..d4846d5a1 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -332,6 +332,8 @@ 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/contracts.rs::CACHE", "team id; holds that team's own contract index"), + ("common/src/repo_reach.rs::LEDGER", "installation id plus a public `owner/repo`: what that installation read in private repositories, only ever taken out of its own writes there"), ("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/xp_answers_read_the_other_repo.rs b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs index c0fc289ab..ffa129380 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 @@ -378,7 +378,7 @@ fn all_repos() -> Vec { 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()); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set(), 1); exec.execute( repo_reach::READ_REPO_FILE, &json!({"repo": RULES, "path": DISCOUNT}), @@ -425,7 +425,7 @@ 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()); + reach::Exec::new(&Nothing, Some(&reader), "").posting_to(RULES, &public_set(), 1); private_target .execute( repo_reach::READ_REPO_FILE, @@ -436,7 +436,7 @@ async fn private_replies_and_public_to_public_replies_may_quote() { assert!(private_target.private_reads().is_empty()); let public_target = - reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set()); + reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set(), 1); public_target .execute( repo_reach::READ_REPO_FILE, @@ -463,7 +463,7 @@ async fn private_replies_and_public_to_public_replies_may_quote() { 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()); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set(), 1); exec.execute( repo_reach::READ_REPO_FILE, &json!({"repo": RULES, "path": DISCOUNT}), diff --git a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs new file mode 100644 index 000000000..c89f95f5d --- /dev/null +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -0,0 +1,411 @@ +//! xt. PR work knew one repository at a time. A ticket asked the orders +//! service of a bookstore to return a book's price in cents and to retire +//! the old book route. The plan named the route and its test; the coder +//! changed them; the reviewer passed the pull request. The storefront +//! fetched that route from its book page, the reading app subscribed to the +//! order event the same change renamed, and a shared types package the +//! storefront imported described the old shape. Nothing in planning, +//! coding, review or the pull request named any of them: an agent could +//! have searched every repository, and none did. +//! +//! Guarantee: the installation's contract index (`common::contracts`), +//! built with each repository's code graph and refreshed on every push, +//! knows per repository the endpoints, GraphQL fields, events, packages, +//! imported symbols and environment variables it exposes and uses. Every +//! pass of PR work reads it (`passes::xrepo`): the planner sees the +//! consumers and a plan that ignores them goes back; the coder's first +//! message carries the consumers' own lines; the reviewer raises a removed +//! contract a consumer still uses as a required finding citing it; a pull +//! request that touches contracts others use carries a compatibility +//! section unless it changes them too. Every loop has `find_consumers`. +//! What is written into a public repository never names a private one or +//! copies its code; reading is never limited. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use common::contracts::{self as xc, Index, Record}; +use common::repo_reach::{self, Read}; + +use crate::passes::xrepo::{RunContracts, BREAK_RULE, BREAK_TITLE}; + +const API: &str = "acme/orders-api"; +const SHOP: &str = "acme/storefront"; +const APP: &str = "acme/reader-app"; +const TYPES: &str = "acme/book-types"; +const INSTALLATION: u64 = 42; + +fn all(_: &str) -> bool { + true +} + +fn record(repo: &str, files: &[(&str, &str)]) -> Record { + let mut r = Record { + repo: repo.into(), + commit: "c0ffee".into(), + entries: Vec::new(), + }; + for (path, src) in files { + r.replace_files(&[], xc::extract(path, src, &all)); + } + r +} + +/// The bookstore: an orders service, a storefront, a reading app and a +/// shared types package. +fn bookstore() -> Arc { + let api = record( + API, + &[ + ( + "src/routes/books.ts", + "import { show } from './show';\n\napp.get('/books/:id', show);\napp.post('/orders', place);\n", + ), + ( + "src/events.ts", + "export async function placed(o) {\n await publish('order.placed', o);\n}\n", + ), + ("package.json", "{\"name\": \"orders-api\"}"), + ], + ); + let shop = record( + SHOP, + &[ + ( + "src/pages/book.tsx", + "export async function load(id) {\n return fetch(`/api/books/${id}`);\n}\n", + ), + ( + "src/cart.ts", + "import { Book, priceLabel } from '@acme/book-types';\n", + ), + ], + ); + let app = record( + APP, + &[( + "src/orders/listen.ts", + "bus.subscribe('order.placed', onPlaced);\n", + )], + ); + let types = record( + TYPES, + &[ + ("package.json", "{\n \"name\": \"@acme/book-types\"\n}"), + ("src/book.ts", "export interface Book { price: number }\n"), + ], + ); + Arc::new(Index { + records: vec![api, shop, app, types], + }) +} + +/// The orders service and the reading app are public; the storefront and +/// the types package are private. +fn public() -> BTreeSet { + [API.to_string(), APP.to_string()].into() +} + +fn run(repo: &str) -> RunContracts { + RunContracts::of(bookstore(), repo, public(), INSTALLATION) +} + +fn files(repo: &str, paths: &[&str]) -> Vec<(String, String)> { + paths + .iter() + .map(|p| (repo.to_string(), p.to_string())) + .collect() +} + +/// The planner sees every consumer, and a plan that changes a contract +/// without its consumers or a compatibility note goes back. +#[test] +fn the_planner_sees_the_consumers_and_a_plan_that_ignores_them_goes_back() { + let c = run(API); + let section = c.planner_section(&["src/routes/books.ts".into(), "src/events.ts".into()]); + assert!(section.contains(SHOP) && section.contains("src/pages/book.tsx:2")); + assert!(section.contains(APP) && section.contains("src/orders/listen.ts:1")); + assert!(section.contains(xc::COMPAT_HEADING)); + let planned = files(API, &["src/routes/books.ts", "src/events.ts"]); + let design = "## Approach\nReturn the price in cents.\n"; + let back = c.plan_gaps(&planned, design, &[API.into()]); + assert_eq!(back.len(), 1); + assert!(back[0].contains(SHOP) && back[0].contains(APP)); + // A multi-repository plan that changes every consumer owes nothing. + assert!(c + .plan_gaps(&planned, design, &[API.into(), SHOP.into(), APP.into()]) + .is_empty()); + // Nor does a plan that says how it stays compatible. + let compatible = format!( + "{design}\n{}\nThe old route stays until the storefront moves.\n", + xc::COMPAT_HEADING + ); + assert!(c.plan_gaps(&planned, &compatible, &[API.into()]).is_empty()); + // A file nobody else uses owes nothing. + assert!(c + .plan_gaps(&files(API, &["src/show.ts"]), design, &[API.into()]) + .is_empty()); + // Packages reach whoever imports from them. + let t = run(TYPES).planner_section(&["src/book.ts".into()]); + assert!(t.contains(SHOP) && t.contains("@acme/book_types#Book")); +} + +/// A route the change removes while another repository still fetches it is +/// a required finding citing that consumer; one it keeps is not. +#[test] +fn a_removed_contract_is_a_required_finding_citing_the_consumer() { + let removed = vec![( + "src/routes/books.ts".to_string(), + "@@ -3,2 +3,1 @@\n-app.get('/books/:id', show);\n app.post('/orders', place);\n" + .to_string(), + )]; + // The storefront is private and the orders service public: the + // finding never names the storefront or its path. + let f = run(API).break_findings(&removed); + assert_eq!(f.len(), 1); + assert_eq!(f[0].title, BREAK_TITLE); + assert_eq!(f[0].required.as_deref(), Some(BREAK_RULE)); + assert_eq!(f[0].severity, "blocking"); + assert!(f[0] + .body + .contains("a private repository of the installation")); + assert!(!f[0].body.contains(SHOP) && !f[0].body.contains("src/pages/book.tsx")); + // Between private repositories the finding cites the consumer's line. + let private = RunContracts::of(bookstore(), API, BTreeSet::new(), INSTALLATION); + let f = private.break_findings(&removed); + assert!(f[0] + .body + .contains("`src/pages/book.tsx:2` in acme/storefront")); + let section = private.review_section(&removed); + assert!( + section.contains("REMOVES or RENAMES") + && section.contains("acme/storefront at src/pages/book.tsx:2") + ); + // A rewrite that keeps the route is not a break. + let kept = vec![( + "src/routes/books.ts".to_string(), + "@@ -3,1 +3,1 @@\n-app.get('/books/:id', show);\n+app.get('/books/:id', showInCents);\n" + .to_string(), + )]; + assert!(private.break_findings(&kept).is_empty()); + assert!(private + .review_section(&kept) + .contains("Contracts the changed files carry")); +} + +/// A pull request never ships a contract change with known consumers +/// without either changing them or a compatibility section. +#[test] +fn a_pull_request_never_ships_without_its_consumers_or_a_compatibility_note() { + let c = run(API); + let changed = vec![( + "src/events.ts".to_string(), + "@@ -2,1 +2,1 @@\n- await publish('order.placed', o);\n+ await publish('order.created', o);\n".to_string(), + )]; + let body = "Closes #12\n\n**Summary** Rename the order event."; + let note = c.compat_note(&changed, &[API.into()], body).unwrap(); + assert!(note.starts_with(xc::COMPAT_HEADING)); + assert!(note.contains("**Breaking:**") && note.contains(APP)); + assert!(c + .compat_note(&changed, &[API.into(), APP.into()], body) + .is_none()); + let said = format!( + "{body}\n\n{}\nBoth names are published for a release.", + xc::COMPAT_HEADING + ); + assert!(c.compat_note(&changed, &[API.into()], &said).is_none()); + // Every pull request a run opens passes the check, after the body is + // final and before GitHub sees it. + let pr = include_str!("../pr.rs"); + let run = super::fixture::fn_src(pr, "pub async fn run("); + let checked = run + .find("description::checked_for_diff(&full_body, &diff)") + .unwrap(); + let compat = run + .find("super::xrepo::with_compat(state, msg, plan, &diff, &full_body)") + .unwrap(); + let opened = run.find(concat!(".create_pull", "_request(")).unwrap(); + assert!(checked < compat && compat < opened); +} + +/// Every pass of PR work reads the index, through the registry every +/// agent that reads code asks, and every loop can ask it. +#[test] +fn the_index_is_used_not_bypassed() { + let plan = include_str!("../plan.rs"); + let run = super::fixture::fn_src(plan, "pub async fn run("); + let overview = run.find("c.planner_section(&likely)").unwrap(); + let first = run.find("let mut content_blocks = vec![").unwrap(); + assert!(overview < first); + assert!(run.contains("c.plan_gaps(")); + let implement = include_str!("../implement.rs"); + let run = super::fixture::fn_src(implement, "pub async fn run("); + let related = run.find("c.coder_context(github, &files)").unwrap(); + let used = run.find("format!(\"{prompt}{related}\")").unwrap(); + let first = run.find("let mut content_blocks = vec![").unwrap(); + assert!(related < used && used < first); + let review = include_str!("../review_pr.rs"); + assert!(review.contains("c.review_section(&super::xrepo::changed_of(&compare))")); + assert!(review.contains("c.break_findings(&super::xrepo::changed_of(&compare))")); + // Each pass loads the installation's maps for its step. + for (file, src) in [ + ("plan.rs", plan), + ("implement.rs", implement), + ("review_pr.rs", review), + ("feedback.rs", include_str!("../feedback.rs")), + ] { + assert!(src.contains(".load_map(state)"), "{file}"); + } + let graph = include_str!("../code_graph.rs"); + let load = super::fixture::fn_src(graph, "pub async fn load_map("); + assert!(load.contains("super::xrepo::RunContracts::load(")); + let offer = super::fixture::fn_src(graph, "pub fn offer("); + assert!(offer.contains("graphs.contracts()")); + // The index follows every push: the code graph's pass refreshes it. + let pass = super::fixture::fn_src(graph, "async fn index_pass("); + assert!(pass.contains("refresh_contracts(state, &msg, &snapshot, &all_paths, &head)")); + // Every loop is offered find_consumers and told to ask it first. + let provider = include_str!("../../agent/provider.rs"); + let loop_ = super::fixture::fn_src(provider, "async fn converse_as("); + assert!(loop_.contains("common::contracts::team_index(")); + assert!(loop_.contains(".with_index(index, &provider.scope.repo)")); + let offered = crate::agent::reach::offer(&[crate::agent::llm::ToolDefinition { + name: "read_file".into(), + description: String::new(), + input_schema: serde_json::json!({}), + }]); + assert!(offered.iter().any(|t| t.name == xc::TOOL)); + assert!(crate::agent::reach::prompt("You fix code.").contains(&xc::prompt())); +} + +/// No prompt or code path limits PR work to one repository. +#[test] +fn no_pr_work_is_limited_to_one_repository() { + const LIMITS: &[&str] = &[ + "one repository at a time", + "read only this repository", + "work only in this repository", + "only the work's repository", + "only in this repository", + "do not read other repositories", + "don't read other repositories", + "ignore other repositories", + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut found = Vec::new(); + let mut loads = 0; + for f in rs_files(&root) { + let p = f.to_string_lossy().replace('\\', "/"); + if p.contains("/incidents/") { + continue; + } + let text = std::fs::read_to_string(&f).unwrap_or_default(); + let low = text.to_lowercase(); + for l in LIMITS { + // The one place that says how a run spanning several + // repositories ends when CI fails: it says so to people, true + // and named, rather than fixing them one by one. + let told = p.ends_with("/passes/resume.rs") + && low.contains( + "coderhelm fixes ci one repository at a time and this run spans several", + ); + if low.contains(l) && !(told && *l == "one repository at a time") { + found.push(format!("{p}: {l}")); + } + } + // Every graph registry PR work opens may read the team's other + // repositories: none is opened with an empty list of them. + let mut rest = text.as_str(); + while let Some(i) = rest.find("RepoGraphs::load(") { + let call: String = rest[i..].lines().take(9).collect::>().join("\n"); + if call.contains("Vec::new()") { + found.push(format!( + "{p}: a RepoGraphs::load with no other repositories" + )); + } + loads += 1; + rest = &rest[i + 1..]; + } + } + assert!(loads >= 5, "{loads}"); + 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 +} + +/// What is written into a public repository (a pull request, its +/// commits, its review comments) never names a private repository the +/// work read; a private repository's own writes are never edited. +#[test] +fn every_public_surface_is_held_and_private_ones_reference_freely() { + let c = run(API); + // Showing the planner its consumers keeps them for the public target. + let _ = c.planner_section(&["src/routes/books.ts".into()]); + assert!(repo_reach::private_for(INSTALLATION, API) + .iter() + .any(|r| r.repo == SHOP)); + repo_reach::note_private( + INSTALLATION, + API, + &[Read { + repo: SHOP.into(), + path: "src/pages/book.tsx".into(), + lines: vec![" return fetch(`/api/books/${id}`);".into()], + }], + ); + let pr = serde_json::json!({ + "title": "Price in cents", + "body": "Prices are in cents now.\nThe acme/storefront book page reads them at src/pages/book.tsx.", + }); + let held = crate::clients::github::public_payload( + INSTALLATION, + "https://api.github.com/repos/acme/orders-api/pulls", + &pr, + ); + assert_eq!(held["body"], "Prices are in cents now."); + let commit = serde_json::json!({"message": "Cents\n\nMatches acme/storefront.", "tree": "t"}); + let held = crate::clients::github::public_payload( + INSTALLATION, + "https://api.github.com/repos/acme/orders-api/git/commits", + &commit, + ); + assert_eq!(held["message"], "Cents"); + let review = serde_json::json!({"body": "ok", "comments": [{"path": "src/routes/books.ts", "body": "acme/storefront still calls this."}]}); + let held = crate::clients::github::public_payload( + INSTALLATION, + "https://api.github.com/repos/acme/orders-api/pulls/3/reviews", + &review, + ); + assert_eq!( + held["comments"][0]["body"], + crate::clients::github::LEFT_OUT + ); + // A private repository's pull request may name what it read. + let private = crate::clients::github::public_payload( + INSTALLATION, + "https://api.github.com/repos/acme/storefront/pulls", + &pr, + ); + assert_eq!(private, pr); + // Another installation's writes to the same repository are its own. + let other = crate::clients::github::public_payload( + INSTALLATION + 1, + "https://api.github.com/repos/acme/orders-api/pulls", + &pr, + ); + assert_eq!(other, pr); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index cf69cfb31..efb87db81 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1526,6 +1526,7 @@ pub mod web_check; pub mod webhooks; pub mod weekly_summary; pub mod write_guard; +pub mod xrepo; /// The email of the person a run is for, when the ticket names one: their /// own connections to personal MCP servers are used for the run. diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index 79192e1a9..3cf7faa2e 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -923,6 +923,19 @@ Then the ```fix_location.json block described above."#, } None => prompt, }; + // The installation's contract index in short: what the likely files + // expose to the team's other repositories and use from them (`xrepo`). + let prompt = match graphs.contracts() { + Some(c) => { + let likely: Vec = found + .iter() + .flat_map(|(_, hits)| hits.iter()) + .filter_map(|h| h.lines().next().map(|p| p.trim().to_string())) + .collect(); + format!("{prompt}{}", c.planner_section(&likely)) + } + None => prompt, + }; let mut content_blocks = vec![serde_json::json!({"type": "text", "text": prompt})]; for img in &msg.image_attachments { if let Some(b64) = @@ -1128,6 +1141,22 @@ Then the ```fix_location.json block described above."#, &draft.design, )); } + // A plan whose files carry contracts other repositories use changes + // those repositories too, or says how it stays compatible (`xrepo`). + if let Some(c) = graphs.contracts() { + let groups: Vec<(String, String)> = draft + .repo_tasks + .iter() + .map(|r| (format!("{}/{}", r.owner, r.name), r.tasks.clone())) + .collect(); + let mut work: Vec = vec![default_repo.clone()]; + work.extend(groups.iter().map(|(r, _)| r.clone())); + back.extend(c.plan_gaps( + &super::run_map::planned(&default_repo, &draft.tasks, &groups), + &draft.design, + &work, + )); + } // The repository's files, once the repository is settled (`check_files`: // a re-plan after a switch or a file mismatch): a task whose tag doesn't // match the repository goes back in this same send-back, never in a diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 3c79d986c..7e5e050bd 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -623,6 +623,10 @@ Return ONLY the markdown body text."#, // A change the diff does not contain never opens a pull request. let full_body = crate::passes::description::checked_for_diff(&full_body, &diff); + // A change touching contracts other repositories of the installation + // use, which neither changes them nor says how it stays compatible, + // says so in its description (`xrepo`). + let full_body = super::xrepo::with_compat(state, msg, plan, &diff, &full_body).await; // The PR title and squash commit follow the team's templates. let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 10fae1e45..c528a3798 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -2715,12 +2715,13 @@ async fn run_once( ) .await; let system = format!("{system}{}", web.prompt_section()); + // Every repository of the installation, never this one alone. let graphs = super::code_graph::RepoGraphs::load( state, &msg.team_id, msg.installation_id, &format!("{}/{}", msg.repo_owner, msg.repo_name), - Vec::new(), + super::plan::fetch_team_repos(state, &msg.team_id).await, "reviewer", msg.pr_number, ) @@ -3372,7 +3373,8 @@ async fn run_once( &msg.team_id, msg.installation_id, &format!("{}/{}", msg.repo_owner, msg.repo_name), - Vec::new(), + // Every repository of the installation, never this one alone. + super::plan::fetch_team_repos(state, &msg.team_id).await, "reviewer", msg.pr_number, ) @@ -3429,6 +3431,16 @@ async fn run_once( } None => graph_context, }; + // The installation's contract index (`xrepo`): every contract the + // change touches that another repository uses, and each it removes + // while one still does. + let graph_context = match graphs.contracts() { + Some(c) => format!( + "{graph_context}{}", + c.review_section(&super::xrepo::changed_of(&compare)) + ), + None => graph_context, + }; // CI evidence: the PR's ACTUAL check results for this head, injected into // the prompt. A reviewer claim like "this cannot install" is refutable by a @@ -4095,6 +4107,16 @@ async fn run_once( Vec::new() } }; + // A contract the change removes or renames while another + // repository of the installation still uses it: a required finding + // citing the consumer, whatever the model said (`xrepo`). + if let Some(c) = graphs.contracts() { + for f in c.break_findings(&super::xrepo::changed_of(&compare)) { + info!(pr = msg.pr_number, file = %f.file, "A contract another repository uses is removed"); + findings.retain(|x| x.title != f.title || x.file != f.file); + findings.push(f); + } + } if let Some(f) = super::review_rules::e2e_finding(&changed_list, &tree) { info!( pr = msg.pr_number, diff --git a/services/worker/src/passes/run_map.rs b/services/worker/src/passes/run_map.rs index b8ecc0955..069c579b3 100644 --- a/services/worker/src/passes/run_map.rs +++ b/services/worker/src/passes/run_map.rs @@ -1,7 +1,7 @@ //! The app map for runs: the cross-repository map the App map page draws //! (`common::app_map`), read by the run's own agents. //! -//! A run plans, codes and reviews one repository at a time. The map knows +//! A run's step works in one repository and reads them all. The map knows //! what that repository's code is to the rest of the app: which other //! repositories call its endpoints, which screens and journeys stand on a //! file, which outside services it reaches and which cloud resources deploy diff --git a/services/worker/src/passes/xrepo.rs b/services/worker/src/passes/xrepo.rs new file mode 100644 index 000000000..ff4fc2a40 --- /dev/null +++ b/services/worker/src/passes/xrepo.rs @@ -0,0 +1,581 @@ +//! The installation's contract index for runs: every step of PR work knows +//! which other repositories of the installation its change reaches, the +//! way a senior developer who knows the whole system does, without +//! searching every repository per request. +//! +//! The index (`common::contracts`) holds, per repository, the endpoints, +//! GraphQL fields, events, packages, imported symbols and environment +//! variables it exposes and uses, kept current by the code graph's index +//! pass. A step reads it once ([`RunContracts::load`], one cached query per +//! team) and rides it in [`super::code_graph::RepoGraphs`], the registry +//! every pass that reads code already asks, next to the app map: +//! +//! - **Planning**: the planner's first message lists what the ticket's +//! likely files expose to other repositories and use from them +//! ([`RunContracts::planner_section`]). A plan whose files carry +//! contracts another repository uses goes back once +//! ([`RunContracts::plan_gaps`]) unless it either changes every consumer +//! (a `## owner/repo` group per consumer: the multi-repository plan the +//! run builds and links in merge order) or says how it stays compatible +//! under `## Compatibility`. +//! - **Coding, fix rounds and CI rounds** (all through the coder): the +//! consumers' own lines, read from their repositories, are in the first +//! message ([`RunContracts::coder_context`]). +//! - **Review**: the reviewer is shown every contract the change touches +//! that another repository uses ([`RunContracts::review_section`]), and a +//! contract the change removes or renames while a consumer still uses it +//! is a required finding citing the consumer ([`RunContracts:: +//! break_findings`]), whatever the model said. +//! - **Shipping**: a pull request whose change touches contracts other +//! repositories use, with neither those repositories in the run nor a +//! compatibility section in its description, gets one +//! ([`RunContracts::compat_note`]). +//! +//! Reading is never limited. What is written into a public repository +//! never names a private one: every private repository this step shows +//! the run is kept for the public repository the work posts to +//! (`common::repo_reach::note_private`), and the GitHub client takes it +//! out of anything written there; the reviewer and the compatibility +//! section say "a private repository of the installation" instead. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use common::contracts::{self as xc, Index, Link}; +use common::repo_reach::{self, Read}; +use tracing::info; + +use super::review_agent::Finding; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// Consumer excerpts the coder is given at most. +pub const MAX_EXCERPTS: usize = 6; +/// Lines of each excerpt. +pub const EXCERPT_LINES: usize = 24; +/// The longest related-code section the coder reads (about 3,000 tokens). +pub const CONTEXT_CHARS: usize = 12_000; +/// The longest section the planner or the reviewer reads (about 1,000 tokens). +pub const SECTION_CHARS: usize = 4_000; +/// Repositories without a record queued for a first read, per step. +pub const BACKFILL_PER_STEP: usize = 3; +/// The rule a certain break is required by. +pub const BREAK_RULE: &str = + "a contract another repository of the installation uses is never removed or renamed while it still uses it"; +/// The title of a certain break's finding. +pub const BREAK_TITLE: &str = "Breaks a consumer in another repository"; + +/// The index for one step of work on one repository. +pub struct RunContracts { + repo: String, + index: Arc, + /// The repositories GitHub says are public (lower case). + public: BTreeSet, + /// The installation the work reads with. + installation: u64, +} + +impl RunContracts { + /// Reads the team's index once for this step (cached per team), and + /// queues a first read of the work's repository and of a few others + /// that have no record yet, so the index covers the installation. + /// `None` (and nothing said) when the index holds nothing yet. + pub async fn load( + state: &WorkerState, + team_id: &str, + repo: &str, + installation_id: u64, + ) -> Option { + let table = &state.config.settings_table_name; + let index = xc::team_index(&state.dynamo, table, team_id).await; + let known: BTreeSet = index + .as_ref() + .map(|i| i.records.iter().map(|r| r.repo.to_lowercase()).collect()) + .unwrap_or_default(); + let mut queued = 0; + let mut repos = vec![repo.to_string()]; + repos.extend(super::plan::fetch_team_repos(state, team_id).await); + for r in repos { + if queued >= BACKFILL_PER_STEP { + break; + } + if !known.contains(&r.to_lowercase()) + && super::code_graph::queue_full_index(state, team_id, &r, installation_id, false) + .await + { + info!(repo = %r, "Contract index: first read queued"); + queued += 1; + } + } + let index = index?; + let public = crate::agent::reach::access(state, team_id) + .await + .map(|a| a.public) + .unwrap_or_default(); + info!( + team_id, + repo, + repos = index.records.len(), + "Contract index: offered to the step" + ); + Some(Self::of(index, repo, public, installation_id)) + } + + /// Over an index already read (tests; callers that hold one). + pub fn of( + index: Arc, + repo: &str, + public: BTreeSet, + installation: u64, + ) -> RunContracts { + RunContracts { + repo: repo.to_string(), + index, + public, + installation, + } + } + + /// Whether the work's repository is public. + pub fn public_target(&self) -> bool { + crate::agent::reach::is_public(&self.public, &self.repo) + } + + fn private(&self, repo: &str) -> bool { + !crate::agent::reach::is_public(&self.public, repo) + } + + /// Every private repository and path `links` show, kept for the work's + /// public repository: nothing written there will name them. + fn note(&self, links: &[Link], lines: &[(String, String, Vec)]) { + if !self.public_target() { + return; + } + let mut reads: Vec = links + .iter() + .filter(|l| self.private(&l.repo)) + .map(|l| Read { + repo: l.repo.clone(), + path: l + .at + .rsplit_once(':') + .map(|(p, _)| p) + .unwrap_or("") + .to_string(), + lines: Vec::new(), + }) + .collect(); + reads.extend( + lines + .iter() + .filter(|(r, _, _)| self.private(r)) + .map(|(r, p, l)| Read { + repo: r.clone(), + path: p.clone(), + lines: l.clone(), + }), + ); + repo_reach::note_private(self.installation, &self.repo, &reads); + } + + /// The links of planned files `(repo, path)`, each repository's asked + /// of the index at once. + pub fn links(&self, files: &[(String, String)]) -> Vec { + let mut by_repo: std::collections::BTreeMap> = Default::default(); + for (r, p) in files.iter().take(60) { + by_repo.entry(r.clone()).or_default().push(p.clone()); + } + let mut out: Vec = Vec::new(); + for (r, paths) in by_repo { + out.extend(self.index.links(&r, &paths)); + } + out.truncate(xc::MAX_LINKS); + self.note(&out, &[]); + out + } + + /// What an agent is told about the index, by role. + pub fn prompt_line(&self, role: super::code_graph::Role) -> String { + use super::code_graph::Role; + let intro = format!( + "\n\nThe team's installation has a CONTRACT INDEX over all {} of its indexed \ + repositories ({}): which repository exposes and which uses each endpoint, GraphQL \ + field, event, package, imported symbol and environment variable.", + self.index.records.len(), + xc::TOOL + ); + let what = match role { + Role::Planner => format!( + " Call {} on each file you plan to change. When a change alters a contract \ + another repository uses, the plan either changes every consumer (a `## \ + owner/repo` group in tasks.md for each, in merge order) or keeps it backward \ + compatible and says how under `{}` in design.md, naming each consumer.", + xc::TOOL, + xc::COMPAT_HEADING + ), + Role::Coder => format!( + " Before you change what a file exposes, call {} on it and keep every consumer \ + working; the related code is in your first message.", + xc::TOOL + ), + Role::Reviewer => format!( + " For each changed file, call {} on it: a change that removes, renames or \ + reshapes a contract another repository uses is a breaking change; raise it \ + naming the consumer's file:line.", + xc::TOOL + ), + }; + let public = if self.public_target() { + " This repository is public: what you write into it (code, commits, the pull \ + request, findings) never names a private repository or its paths, and never \ + copies its code; say \"a private repository of the installation\"." + } else { + "" + }; + format!("{intro}{what}{public}") + } + + /// The planner's section: what the ticket's likely files expose to and + /// use from other repositories. At most [`SECTION_CHARS`]. + pub fn planner_section(&self, likely: &[String]) -> String { + let files: Vec<(String, String)> = likely + .iter() + .map(|p| (self.repo.clone(), p.clone())) + .collect(); + let links = self.links(&files); + let mut out = String::from( + "\n\n## Other repositories this work reaches (the installation's contract index)\n", + ); + if links.is_empty() { + out.push_str(&format!( + "None of the ticket's likely files expose or use a contract another of the {} \ + indexed repositories has. Call {} on each file you plan to change.\n", + self.index.records.len(), + xc::TOOL + )); + return out; + } + for l in &links { + let line = format!("- {}\n", l.line()); + if out.len() + line.len() > SECTION_CHARS - 400 { + break; + } + out.push_str(&line); + } + out.push_str(&format!( + "A plan that changes one of these contracts changes every consumer too (a `## \ + owner/repo` group in tasks.md for each, in merge order), or keeps the change \ + backward compatible and says how under `{}` in design.md.\n", + xc::COMPAT_HEADING + )); + out + } + + /// Plan gaps: the planned files carry contracts other repositories + /// use, the plan changes none of those repositories, and design.md + /// has no compatibility section. Sent back once. + pub fn plan_gaps( + &self, + planned: &[(String, String)], + design: &str, + work_repos: &[String], + ) -> Vec { + if xc::has_compat(design) { + return Vec::new(); + } + let links = self.links(planned); + let owed = xc::outside(&links, work_repos); + if owed.is_empty() { + return Vec::new(); + } + let lines: Vec = owed.iter().take(10).map(|l| l.line()).collect(); + let text = format!( + "The planned files carry contracts other repositories of the installation use, and \ + the plan neither changes them nor says how it stays compatible: {}. Either add a \ + `## owner/repo` group in tasks.md for each consumer that needs the matching change \ + (in the order the pull requests merge), or keep the change backward compatible and \ + add a `{}` section to design.md that says how, naming each consumer.", + lines.join("; "), + xc::COMPAT_HEADING + ); + vec![common::truncate_str(&text, 3_000).to_string()] + } + + /// The consumers' own lines for the coder's first message: what the + /// files this work changes expose, used elsewhere, read from each + /// consumer's default branch. At most [`MAX_EXCERPTS`] excerpts and + /// [`CONTEXT_CHARS`]; empty when nothing elsewhere uses them. + pub async fn coder_context(&self, github: &GitHubClient, files: &[(String, String)]) -> String { + let links: Vec = self + .links(files) + .into_iter() + .filter(|l| l.direction == xc::Direction::Consumer && l.kind != xc::Kind::Env) + .collect(); + if links.is_empty() { + return String::new(); + } + let mut out = String::from( + "\n\n## Code in other repositories that uses what this work changes\nFrom the \ + installation's contract index, read at each repository's default branch. Keep every \ + one working: change it in the plan's group for its repository, or keep the contract \ + backward compatible.\n", + ); + let mut seen: BTreeSet<(String, String)> = BTreeSet::new(); + let mut read: Vec<(String, String, Vec)> = Vec::new(); + for l in &links { + if seen.len() >= MAX_EXCERPTS || out.len() >= CONTEXT_CHARS { + break; + } + let Some((path, line)) = l.at.rsplit_once(':') else { + continue; + }; + if !seen.insert((l.repo.clone(), path.to_string())) { + continue; + } + let Some((owner, name)) = l.repo.split_once('/') else { + continue; + }; + let line: usize = line.parse().unwrap_or(1); + let start = line.saturating_sub(EXCERPT_LINES / 3).max(1); + let end = start + EXCERPT_LINES; + let Ok(branch) = github.get_default_branch(owner, name).await else { + continue; + }; + let Ok(text) = github + .read_file_lines(owner, name, path, &branch, start, end) + .await + else { + continue; + }; + let block = format!( + "\n### {} {} ({} `{}`, here at {})\n```\n{}```\n", + l.repo, + l.at, + l.kind.word(), + l.contract, + l.here, + text + ); + if out.len() + block.len() > CONTEXT_CHARS { + break; + } + out.push_str(&block); + read.push(( + l.repo.clone(), + path.to_string(), + text.lines() + .map(|x| x.split_once(" | ").map(|(_, t)| t).unwrap_or(x).to_string()) + .collect(), + )); + } + self.note(&links, &read); + info!(repo = %self.repo, excerpts = read.len(), tokens = out.len().div_ceil(4), "Contract index: the coder's related code"); + if read.is_empty() { + // Nothing could be read: the links alone, as the planner had them. + for l in links.iter().take(12) { + out.push_str(&format!("- {}\n", l.line())); + } + } + out + } + + /// The reviewer's section for a pull request's changed files + /// (`(path, patch)`): each certain break, and every contract the + /// changed files carry that another repository uses. At most + /// [`SECTION_CHARS`]; empty when nothing elsewhere is reached. + pub fn review_section(&self, changed: &[(String, String)]) -> String { + let breaks = self.index.breaks(&self.repo, changed); + let files: Vec<(String, String)> = changed + .iter() + .map(|(p, _)| (self.repo.clone(), p.clone())) + .collect(); + let links: Vec = self + .links(&files) + .into_iter() + .filter(|l| l.direction == xc::Direction::Consumer) + .collect(); + if breaks.is_empty() && links.is_empty() { + return String::new(); + } + let mut out = + String::from("\n## Other repositories (from the installation's contract index)\n"); + if !breaks.is_empty() { + out.push_str( + "Contracts this pull request REMOVES or RENAMES that other repositories still \ + use. Each is a certain break, raised as a blocking finding:\n", + ); + for b in &breaks { + out.push_str(&format!( + "- {} `{}` (removed at {}) is used by {}\n", + b.kind.word(), + b.contract, + b.at, + b.consumers + .iter() + .map(|(r, at)| format!("{r} at {at}")) + .collect::>() + .join(", ") + )); + } + } + if !links.is_empty() { + out.push_str( + "Contracts the changed files carry that other repositories use. If the change \ + alters one (its path, method, fields, payload, type, name or meaning), raise a \ + breaking-change finding naming the consumer's file:line; if it keeps it, say \ + nothing about it:\n", + ); + for l in links.iter().take(20) { + out.push_str(&format!("- {}\n", l.line())); + } + } + if self.public_target() { + out.push_str( + "This repository is public: a finding about a consumer in a private repository \ + says \"a private repository of the installation\" and never names it or its \ + paths.\n", + ); + } + let out = common::truncate_str(&out, SECTION_CHARS).to_string(); + info!(repo = %self.repo, breaks = breaks.len(), consumers = links.len(), "Contract index: the reviewer's check"); + out + } + + /// One required finding for each contract the change removes or + /// renames while another repository still uses it, citing the + /// consumer (never a private one's name in a public repository). + pub fn break_findings(&self, changed: &[(String, String)]) -> Vec { + let public = self.public_target(); + self.index + .breaks(&self.repo, changed) + .into_iter() + .map(|b| { + let named: Vec = b + .consumers + .iter() + .filter(|(r, _)| !(public && self.private(r))) + .map(|(r, at)| format!("`{at}` in {r}")) + .collect(); + let hidden = b.consumers.len() - named.len(); + let mut who = named.join(", "); + if hidden > 0 { + if !who.is_empty() { + who.push_str(", and "); + } + who.push_str(&format!( + "{hidden} place(s) in a private repository of the installation" + )); + } + let mut f = Finding { + file: b.file.clone(), + severity: "blocking".into(), + category: "breaking-change".into(), + title: BREAK_TITLE.into(), + body: format!( + "This change removes the {} `{}` (it was at {}), and other repositories \ + of this installation still use it: {who}. Keep it, or change those \ + callers in the same change and merge them first.", + b.kind.word(), + b.contract, + b.at + ), + evidence: Some("verified-defect".into()), + caused_by_diff: Some(true), + critical_path: Some("a contract other repositories use".into()), + ..Default::default() + }; + super::review_rules::require( + &mut f, + BREAK_RULE, + &format!( + "the installation's contract index lists {} use(s) of it in other repositories", + b.consumers.len() + ), + ); + f + }) + .collect() + } + + /// The compatibility section a pull request's description gets when + /// its change (`changed`: `(path, patch)`) touches contracts other + /// repositories use, none of them is one of `work_repos`, and `body` + /// has no `## Compatibility` section. `None` when nothing is owed. + pub fn compat_note( + &self, + changed: &[(String, String)], + work_repos: &[String], + body: &str, + ) -> Option { + if xc::has_compat(body) { + return None; + } + let files: Vec<(String, String)> = changed + .iter() + .map(|(p, _)| (self.repo.clone(), p.clone())) + .collect(); + let links = self.links(&files); + let owed = xc::outside(&links, work_repos); + let breaks: Vec = self + .index + .breaks(&self.repo, changed) + .into_iter() + .filter(|b| { + b.consumers + .iter() + .any(|(r, _)| !work_repos.iter().any(|w| w.eq_ignore_ascii_case(r))) + }) + .collect(); + let public = self.public_target(); + xc::compat_section(&owed, &breaks, public, &|r| self.private(r)) + } +} + +/// The changed files of a compare, as `(path, patch)`. +pub fn changed_of(compare: &serde_json::Value) -> Vec<(String, String)> { + compare["files"] + .as_array() + .into_iter() + .flatten() + .filter_map(|f| { + Some(( + f["filename"].as_str()?.to_string(), + f["patch"].as_str().unwrap_or("").to_string(), + )) + }) + .collect() +} + +/// The repositories a run's plan changes: the work's own, and each +/// multi-repository group's. +pub fn work_repos(msg_repo: &str, plan: &super::plan::PlanResult) -> Vec { + let mut out = vec![msg_repo.to_string()]; + out.extend( + plan.repo_tasks + .iter() + .map(|r| format!("{}/{}", r.owner, r.name)), + ); + out +} + +/// A pull request description with the compatibility section its change +/// owes (see [`RunContracts::compat_note`]), when the team has an index. +pub async fn with_compat( + state: &WorkerState, + msg: &crate::models::TicketMessage, + plan: &super::plan::PlanResult, + compare: &serde_json::Value, + body: &str, +) -> String { + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + let Some(c) = RunContracts::load(state, &msg.team_id, &repo, msg.installation_id).await else { + return body.to_string(); + }; + match c.compat_note(&changed_of(compare), &work_repos(&repo, plan), body) { + Some(section) => { + info!(repo = %repo, "Contract index: the pull request carries its compatibility section"); + format!("{}\n\n{section}", body.trim_end()) + } + None => body.to_string(), + } +} From adf44f097139daea1a3001afcd55a93ab6d7311f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 01:16:49 -0500 Subject: [PATCH 7/8] A removed or renamed contract is found by its text, every repository gets its contracts read, and private reads outlive the process - A package renamed in its manifest counts as removed; an endpoint moved to another HTTP method is a break, not a rewrite. Removals are matched by the patch's removed text, not by the index's line numbers, which may come from another commit than the pull request's base. - Repositories with no record, and dependents of a newly exposed package, get a contracts-only read with its own queue mark, which never reads the code graph's status: a repository whose graph is built is read too. Its graph and build status are left as they are. - What work posting to a public repository reads in private ones is also kept in a short-lived store item per installation, public repository and run. Every model loop waits for it to be stored, and the GitHub client reads it back before each write, so a write in a later invocation is held to an earlier read. - An unreadable index record is logged; per-step index logs are debug. --- docs/code-map.md | 5 +- ..._contract_change_reaches_every_consumer.md | 6 +- services/common/src/contracts.rs | 239 +++++++++++++- services/common/src/messages.rs | 6 + services/common/src/repo_reach.rs | 310 +++++++++++++++++- services/gateway/src/routes/github_webhook.rs | 1 + services/gateway/src/routes/graph.rs | 1 + services/worker/src/agent/provider.rs | 6 +- services/worker/src/agent/reach.rs | 12 +- services/worker/src/clients/github.rs | 23 +- services/worker/src/main.rs | 7 + services/worker/src/passes/code_graph.rs | 140 ++++++-- .../passes/incidents/bm_teams_never_cross.rs | 1 + ..._contract_change_reaches_every_consumer.rs | 91 ++++- services/worker/src/passes/pr.rs | 2 +- services/worker/src/passes/xrepo.rs | 33 +- 16 files changed, 807 insertions(+), 76 deletions(-) diff --git a/docs/code-map.md b/docs/code-map.md index eb8004c42..329a85e35 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -95,8 +95,9 @@ from it). - **Built with the code graph.** The code graph's index pass extracts each file's contracts with plain patterns, no model. A first build reads every file; a push replaces only the changed files' entries. A repository with - no record yet is queued for a first read when work in the installation - starts, a few per step. + no record yet (whatever its graph's state) is queued for a + contracts-only read when work in the installation starts, a few per + step, each at most once an hour. - **One query per team.** Every record sits in one partition (`pk = XC#{team}`, `sk = REPO#{owner/name}`, gzipped JSON), read in one paginated query and kept in memory for ten minutes. What a change reaches diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index c7303a234..0351eb6c4 100644 --- a/docs/incidents/xt_contract_change_reaches_every_consumer.md +++ b/docs/incidents/xt_contract_change_reaches_every_consumer.md @@ -6,13 +6,13 @@ **The guarantee (invariants, enforced in code):** -- **An installation index, cheap and current.** For every repository of the installation, the contracts it exposes and the ones it uses: HTTP endpoints, GraphQL root fields, events and queue messages, packages and the symbols other repositories import from them, and environment variables (`common::contracts`). It is extracted with plain patterns by the code graph's index pass, which already reads the repository: a first build reads every file, a push replaces only the changed files' entries. All of a team's records sit in one partition and are read in one query, kept in memory for ten minutes. Every bound is a constant: file size, files per pass, entries per file and per repository, the stored record's size, links per answer, excerpts and characters per prompt. A repository with no record yet is queued for a first read, a few per step. +- **An installation index, cheap and current.** For every repository of the installation, the contracts it exposes and the ones it uses: HTTP endpoints, GraphQL root fields, events and queue messages, packages and the symbols other repositories import from them, and environment variables (`common::contracts`). It is extracted with plain patterns by the code graph's index pass, which already reads the repository: a first build reads every file, a push replaces only the changed files' entries. All of a team's records sit in one partition and are read in one query, kept in memory for ten minutes. Every bound is a constant: file size, files per pass, entries per file and per repository, the stored record's size, links per answer, excerpts and characters per prompt. A repository with no record yet, whatever its graph's state, is queued for a contracts-only read (its graph and build status untouched), a few per step, each at most once an hour; so are the dependents of a package a pass newly exposes. - **Planning.** The planner's first message lists what the ticket's likely files expose to other repositories and use from them. A plan whose files carry a contract another repository uses goes back once unless it changes every such repository (a group per repository, the multi-repository plan the run builds and links in merge order) or says how it stays compatible under `## Compatibility`. - **Coding, fix rounds and CI rounds.** The coder's first message carries the consumers' own lines, read from each repository's default branch, so every round through the coder starts knowing its callers. A round a person asks for loads the same index. -- **Review.** The reviewer is shown each contract the change touches that another repository uses, and every contract the change removes or renames while a consumer still uses it is a required, blocking finding citing that consumer, whatever the model said. A rewrite that keeps the contract is not one. The reviewer's code graph covers the installation's other repositories too. +- **Review.** The reviewer is shown each contract the change touches that another repository uses, and every contract the change removes or renames while a consumer still uses it is a required, blocking finding citing that consumer, whatever the model said. A removal is found by the patch's text, not by line numbers: a route moved to another method, a package renamed, a field or topic gone are each one. A rewrite that keeps the contract is not one. The reviewer's code graph covers the installation's other repositories too. - **Shipping.** A pull request whose change touches contracts other repositories use, with neither those repositories in the run nor a compatibility section in its description, gets one, with every removed contract marked breaking. - **Every loop can ask.** Every worker loop with tools has `find_consumers` over the index, and its prompt says to ask it before changing or explaining a contract. - **No limit to one repository.** A source scan fails on a prompt that limits PR work to one repository, and on any graph registry PR work opens without the team's other repositories. -- **Privacy on every surface.** Reading stays unrestricted. Work posting to a public repository keeps every private read, from the tools and from what the index showed it. A write tool whose input copies a private line, or names a private repository or a path read in one, is refused with the reason, and every text the GitHub client writes into that repository (pull request titles and bodies, commit messages, comments, reviews, release notes) has what came from a private repository taken out by the same leak check. The reviewer and the compatibility section say "a private repository of the installation" instead of a name. A private repository's work may reference freely. +- **Privacy on every surface.** Reading stays unrestricted. Work posting to a public repository keeps every private read, from the tools and from what the index showed it, in memory and in a short-lived store item per installation, public repository and run; every loop waits for it to be stored, and the GitHub client reads it back before each write, so a write in a later invocation is held to an earlier read. A write tool whose input copies a private line, or names a private repository or a path read in one, is refused with the reason, and every text the GitHub client writes into that repository (pull request titles and bodies, commit messages, comments, reviews, release notes) has what came from a private repository taken out by the same leak check. The reviewer and the compatibility section say "a private repository of the installation" instead of a name. A private repository's work may reference freely. **Where it's enforced:** `common::contracts::{extract, Record, Index::links, Index::breaks, compat_section, team_index, answer}`, `common::repo_reach::{note_private, guard_public, code_refused}`, the worker's `passes::xrepo::RunContracts::{load, planner_section, plan_gaps, coder_context, review_section, break_findings, compat_note}` and `with_compat`, `passes::code_graph::{refresh_contracts, RepoGraphs::load_map, offer}`, `agent::reach::{offer, prompt, Exec}`, `agent::provider::converse_as` and `clients::github::public_payload`. diff --git a/services/common/src/contracts.rs b/services/common/src/contracts.rs index 4a2843337..f7168dc08 100644 --- a/services/common/src/contracts.rs +++ b/services/common/src/contracts.rs @@ -1224,29 +1224,43 @@ pub struct Break { pub consumers: Vec<(String, String)>, } -/// Whether the added lines still expose `e` (the definition was rewritten, -/// not removed). -fn still_exposed(path: &str, e: &Entry, added: &[String]) -> bool { - let text = added.join("\n"); +static MANIFEST_NAME: LazyLock = LazyLock::new(|| { + re(r#"^\s*\{?\s*(?:"name"\s*:\s*"([^"]+)"|name\s*=\s*"([^"]+)"|module\s+(\S+))"#) +}); + +/// Two HTTP methods name the same route: equal, or either unknown (`*`). +fn methods_match(a: &str, b: &str) -> bool { + a == b || a.is_empty() || b.is_empty() || a == "*" || b == "*" +} + +/// Whether `lines` (of the file at `path`: a patch's removed or added +/// lines) define the contract `e`: the same kind and key, and for an +/// endpoint the same method; a package by its exact name. +fn defines(path: &str, e: &Entry, lines: &[String]) -> bool { match e.kind { Kind::Graphql => { let field = e.key.split('.').nth(1).unwrap_or(""); - added.iter().any(|l| { + lines.iter().any(|l| { GQL_FIELD .captures(l) .is_some_and(|c| c.get(1).map(|m| m.as_str()) == Some(field)) }) } - Kind::Package => { - text.contains(&format!("\"{}\"", e.key)) - || norm_package(&text).contains(&format!("\"{}\"", e.key)) - || norm_package(&text).contains(&e.key) - } - Kind::Env => added + Kind::Package => lines.iter().any(|l| { + MANIFEST_NAME.captures(l).is_some_and(|c| { + (1..=3) + .filter_map(|i| c.get(i)) + .any(|m| norm_package(m.as_str()) == e.key) + }) + }), + Kind::Env => lines .iter() .any(|l| ENV_SET.captures(l).is_some_and(|c| c[1] == e.key)), - _ => extract(path, &text, &|_| true).iter().any(|x| { - x.kind == e.kind && x.side == Side::Exposes && keys_match(e.kind, &x.key, &e.key) + _ => extract(path, &lines.join("\n"), &|_| true).iter().any(|x| { + x.kind == e.kind + && x.side == Side::Exposes + && keys_match(e.kind, &x.key, &e.key) + && (e.kind != Kind::Endpoint || methods_match(&x.detail, &e.detail)) }), } } @@ -1265,14 +1279,16 @@ impl Index { if removed.is_empty() { continue; } - let gone: BTreeSet = removed.iter().map(|(n, _)| *n).collect(); + // What the patch removes, by its text: the index's line numbers + // may come from another commit than the pull request's base. + let removed: Vec = removed.into_iter().map(|(_, t)| t).collect(); let links = self.links(repo, std::slice::from_ref(path)); for e in own .entries .iter() .filter(|e| &e.file == path && e.side == Side::Exposes) { - if !gone.contains(&(e.line as u64)) || still_exposed(path, e, &added) { + if !defines(path, e, &removed) || defines(path, e, &added) { continue; } let mut consumers: Vec<(String, String)> = links @@ -1473,12 +1489,16 @@ async fn read_index(dynamo: &DynamoClient, table: &str, team_id: &str) -> Result .await .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; for it in out.items() { - if let Some(r) = it + match it .get("body") .and_then(|b| b.as_b().ok()) .and_then(|b| Record::from_body(b.as_ref())) { - records.push(r); + Some(r) => records.push(r), + None => tracing::warn!( + sk = it.get("sk").and_then(|v| v.as_s().ok()).map(String::as_str).unwrap_or(""), + "Contract index: a record could not be read; that repository is left out until its next pass" + ), } } match out.last_evaluated_key() { @@ -1489,6 +1509,120 @@ async fn read_index(dynamo: &DynamoClient, table: &str, team_id: &str) -> Result Ok(Index { records }) } +/// How long a queued contracts read holds before it may be queued again. +pub const READ_QUEUE_SECS: i64 = 3600; +/// When a contracts read may be queued: none is queued, or the one queued +/// is older than [`READ_QUEUE_SECS`]. It never reads the code graph's own +/// build status: a repository whose graph is built gets its read too. +pub const READ_QUEUE_CONDITION: &str = "attribute_not_exists(sk) OR #at < :cutoff"; + +/// Marks a contracts read of `repo` queued; `Ok(true)` when the caller +/// must now send it (one caller wins). +pub async fn mark_read_queued( + dynamo: &DynamoClient, + table: &str, + team_id: &str, + repo: &str, +) -> Result { + use aws_sdk_dynamodb::types::AttributeValue; + let now = chrono::Utc::now().timestamp(); + match dynamo + .put_item() + .table_name(table) + .item("pk", AttributeValue::S(pk(team_id))) + .item( + "sk", + AttributeValue::S(format!("QUEUED#{}", repo.to_lowercase())), + ) + .item("at", AttributeValue::N(now.to_string())) + .condition_expression(READ_QUEUE_CONDITION) + .expression_attribute_names("#at", "at") + .expression_attribute_values( + ":cutoff", + AttributeValue::N((now - READ_QUEUE_SECS).to_string()), + ) + .send() + .await + { + Ok(_) => Ok(true), + Err(e) => { + let held = e + .as_service_error() + .map(|se| se.is_conditional_check_failed_exception()) + .unwrap_or(false); + if held { + Ok(false) + } else { + Err(format!( + "{}", + aws_sdk_dynamodb::error::DisplayErrorContext(e) + )) + } + } + } +} + +/// Clears a contracts read's mark (its message couldn't be sent). +pub async fn unmark_read_queued(dynamo: &DynamoClient, table: &str, team_id: &str, repo: &str) { + use aws_sdk_dynamodb::types::AttributeValue; + let _ = dynamo + .delete_item() + .table_name(table) + .key("pk", AttributeValue::S(pk(team_id))) + .key( + "sk", + AttributeValue::S(format!("QUEUED#{}", repo.to_lowercase())), + ) + .send() + .await; +} + +/// The repositories to read first: those of `repos` (the work's first) +/// with no record in `known` (lower case), each once, at most `cap`. +pub fn backfill(known: &BTreeSet, repos: &[String], cap: usize) -> Vec { + let mut seen = BTreeSet::new(); + repos + .iter() + .filter(|r| !known.contains(&r.to_lowercase()) && seen.insert(r.to_lowercase())) + .take(cap) + .cloned() + .collect() +} + +/// The repositories to read again after `record` newly exposes packages +/// (`before`: the packages it exposed before this pass; `exposed`: those +/// the installation exposed): every other repository that depends on one, +/// whatever its graph's state, at most `cap`. +pub fn dependents_of_new( + team: &Index, + record: &Record, + before: &BTreeSet, + exposed: &BTreeSet, + cap: usize, +) -> Vec { + let new: BTreeSet = record + .packages() + .into_iter() + .map(|(p, _)| p) + .filter(|p| !before.contains(p) && !exposed.contains(p)) + .collect(); + let mut out: Vec = Vec::new(); + for other in team + .records + .iter() + .filter(|r| !same_repo(&r.repo, &record.repo)) + { + let depends = other + .entries + .iter() + .any(|e| e.kind == Kind::Package && e.side == Side::Uses && new.contains(&e.key)); + if depends && out.len() < cap { + out.push(other.repo.clone()); + } + } + out +} + type Kept = (Instant, Arc); static CACHE: LazyLock>> = LazyLock::new(Default::default); @@ -1827,6 +1961,77 @@ mod tests { .is_empty()); } + #[test] + fn a_method_change_and_a_package_rename_are_breaks() { + let idx = bookstore(); + // The index's line (3) and the patch's base line (9) differ: the + // removal is found by its text. + let moved = + "@@ -9,1 +9,1 @@\n-app.get('/books/:id', show);\n+app.post('/books/:id', show);\n"; + let b = idx.breaks( + "acme/orders-api", + &[("src/routes/books.ts".into(), moved.into())], + ); + assert_eq!(b.len(), 1); + assert_eq!(b[0].contract, "GET /books/{}"); + let renamed = "@@ -1,1 +1,1 @@\n-{\"name\": \"@acme/book-types\"}\n+{\"name\": \"@acme/book-types-core\"}\n"; + let b = idx.breaks( + "acme/book-types", + &[("package.json".into(), renamed.into())], + ); + assert_eq!(b.len(), 1); + assert_eq!(b[0].kind, Kind::Package); + assert!(b[0].consumers.iter().any(|(r, _)| r == "acme/storefront")); + let kept = "@@ -1,1 +1,1 @@\n-{\"name\": \"@acme/book-types\"}\n+{\"name\": \"@acme/book-types\", \"private\": true}\n"; + assert!(idx + .breaks("acme/book-types", &[("package.json".into(), kept.into())]) + .is_empty()); + } + + #[test] + fn reads_are_queued_for_every_repo_without_a_record_whatever_its_graph() { + // The mark never reads the code graph's status: a repository whose + // graph is built still gets its contracts read. + assert!(!READ_QUEUE_CONDITION.contains("#st")); + let known: BTreeSet = ["acme/orders-api".to_string()].into(); + let repos: Vec = [ + "acme/orders-api", + "acme/storefront", + "acme/Storefront", + "acme/reader-app", + "acme/book-types", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!( + backfill(&known, &repos, 2), + vec!["acme/storefront".to_string(), "acme/reader-app".to_string()] + ); + // A package newly exposed has its dependents read again. + let mut idx = bookstore(); + let mut shop = idx.records.remove(1); + shop.replace_files( + &[], + extract( + "package.json", + "{\"name\": \"shop\", \"dependencies\": {\"@acme/book-types\": \"1\"}}", + &all, + ), + ); + idx.records.push(shop); + let types = idx.record("acme/book-types").unwrap().clone(); + let none = BTreeSet::new(); + assert_eq!( + dependents_of_new(&idx, &types, &none, &none, 10), + vec!["acme/storefront".to_string()] + ); + // One already exposed before, or by the installation, is not new. + let had: BTreeSet = ["@acme/book_types".to_string()].into(); + assert!(dependents_of_new(&idx, &types, &had, &none, 10).is_empty()); + assert!(dependents_of_new(&idx, &types, &none, &had, 10).is_empty()); + } + #[test] fn records_are_incremental_bounded_and_round_trip() { let mut r = rec("acme/a", extract("src/a.ts", "app.get('/a/b', h);", &all)); diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 032a1bad1..a3915979f 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -778,6 +778,12 @@ pub struct GraphIndexMessage { pub branch: String, #[serde(default)] pub changed_files: Option>, + /// Read only the repository's contracts (`common::contracts`), in full, + /// leaving its graph and its build status as they are: the first read + /// of a repository that has no record yet, or a dependent of a package + /// another repository newly exposes. + #[serde(default)] + pub contracts_only: bool, } /// One step of a team's app map (`worker::passes::app_map`): `step` empty diff --git a/services/common/src/repo_reach.rs b/services/common/src/repo_reach.rs index fc3392cc3..566b6a533 100644 --- a/services/common/src/repo_reach.rs +++ b/services/common/src/repo_reach.rs @@ -126,7 +126,7 @@ pub struct Outcome { /// Content a call read: the repository (`owner/name`), the path, and the /// lines it returned. -#[derive(Debug, Clone, PartialEq, Eq, Default)] +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] pub struct Read { pub repo: String, pub path: String, @@ -489,13 +489,16 @@ fn redact_prose(text: &str, reads: &[Read]) -> String { // bodies, review comments and release notes written into a public // repository are the others, and they are written by other steps than the // loop that read: the coder reads a consumer in a private repository, the -// description step writes the body later. So every read of a private -// repository by work posting to a public one is also kept here, by the -// public repository it posts to and the installation that read it -// ([`note_private`]), and every text -// CoderHelm writes into that repository goes through [`guard_public`] -// (the GitHub client's one place for it). A private-to-private change -// keeps nothing and is never edited: it may reference freely. +// description step writes the body later, maybe in another invocation of +// the worker. So every read of a private repository by work posting to a +// public one is kept by the public repository it posts to and the +// installation that read it ([`note_private`]): in this process, and in +// the store ([`set_store`]) under the run that read it, for +// [`LEDGER_KEEP_SECS`]. Every text CoderHelm writes into that repository +// is checked against both: the GitHub client fills this process from the +// store first ([`refill`]), then takes private content out +// ([`guard_public`]). A private-to-private change keeps nothing and is +// never edited: it may reference freely. /// How long what a run read stays kept for its public repository. pub const LEDGER_KEEP_SECS: u64 = 6 * 3600; @@ -503,6 +506,10 @@ pub const LEDGER_KEEP_SECS: u64 = 6 * 3600; pub const LEDGER_MAX_READS: usize = 2_000; /// Public repositories kept at most. const LEDGER_MAX_TARGETS: usize = 500; +/// How long a fill from the store holds before the next write reads it again. +pub const REFILL_SECS: u64 = 30; +/// Stored batches read for one public repository at most. +pub const REFILL_MAX_ITEMS: usize = 200; /// Keyed by the installation that read and the public repository its work /// posts to (`{installation}:{owner/name}`): one installation's reads are @@ -512,20 +519,52 @@ static LEDGER: LazyLock< std::sync::Mutex)>>, > = LazyLock::new(Default::default); +/// When each `{installation}:{owner/name}` was last filled from the store. +static REFILLED: LazyLock>> = + LazyLock::new(Default::default); + fn ledger_key(installation: u64, target: &str) -> String { format!("{installation}:{}", target.trim().to_lowercase()) } -/// Keeps what work posting to the public repository `target` read in -/// private ones (the caller knows `target` is public and `reads` private). -pub fn note_private(installation: u64, target: &str, reads: &[Read]) { - if reads.is_empty() || target.trim().is_empty() { - return; - } +/// Where the reads are kept across processes: one batch per write, under +/// the ledger's key and the run that read it, gone after its time. +pub trait LedgerStore: Send + Sync { + /// Keeps one batch (`body`: gzipped JSON reads) until `expires` (epoch + /// seconds). + fn put<'a>( + &'a self, + key: &'a str, + run: &'a str, + body: Vec, + expires: i64, + ) -> LedgerFut<'a, Result<(), String>>; + /// Every batch kept under `key` that hasn't expired, at most `max`. + fn load<'a>(&'a self, key: &'a str, max: usize) -> LedgerFut<'a, Result>, String>>; +} + +/// A store call's future. +pub type LedgerFut<'a, T> = std::pin::Pin + Send + 'a>>; + +static STORE: LazyLock>>> = + LazyLock::new(Default::default); +static PENDING: LazyLock>>> = + LazyLock::new(Default::default); + +/// Sets the store (the worker sets DynamoDB's at start). +pub fn set_store(store: std::sync::Arc) { + *STORE.write().unwrap_or_else(|e| e.into_inner()) = Some(store); +} + +fn store() -> Option> { + STORE.read().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// The reads not kept yet, now kept in this process. +fn remember(key: String, reads: &[Read]) -> Vec { let mut l = LEDGER.lock().unwrap_or_else(|e| e.into_inner()); let keep = std::time::Duration::from_secs(LEDGER_KEEP_SECS); l.retain(|_, (at, _)| at.elapsed() < keep); - let key = ledger_key(installation, target); if l.len() >= LEDGER_MAX_TARGETS && !l.contains_key(&key) { if let Some(oldest) = l .iter() @@ -539,15 +578,191 @@ pub fn note_private(installation: u64, target: &str, reads: &[Read]) { .entry(key) .or_insert_with(|| (std::time::Instant::now(), Vec::new())); *at = std::time::Instant::now(); + let mut new = Vec::new(); for r in reads { if !kept.contains(r) { kept.push(r.clone()); + new.push(r.clone()); } } if kept.len() > LEDGER_MAX_READS { let over = kept.len() - LEDGER_MAX_READS; kept.drain(..over); } + new +} + +/// Keeps what `run` of `installation`, posting to the public repository +/// `target`, read in private ones (the caller knows `target` is public and +/// `reads` private): in this process, and in the store for a later +/// invocation ([`flush`] waits for the store's writes). +pub fn note_private(installation: u64, target: &str, run: &str, reads: &[Read]) { + if reads.is_empty() || target.trim().is_empty() { + return; + } + let key = ledger_key(installation, target); + let new = remember(key.clone(), reads); + if new.is_empty() { + return; + } + let (Some(store), Ok(rt)) = (store(), tokio::runtime::Handle::try_current()) else { + return; + }; + let body = crate::app_map::gzip(&serde_json::to_vec(&new).unwrap_or_default()); + let expires = chrono::Utc::now().timestamp() + LEDGER_KEEP_SECS as i64; + let run = if run.is_empty() { "step" } else { run }.to_string(); + let handle = rt.spawn(async move { + if let Err(e) = store.put(&key, &run, body, expires).await { + tracing::warn!(error = %e, "Private reads could not be kept for a later step; this step still checks them"); + } + }); + PENDING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(handle); +} + +/// Waits until every read noted so far is in the store. +pub async fn flush() { + let pending: Vec<_> = std::mem::take(&mut *PENDING.lock().unwrap_or_else(|e| e.into_inner())); + for h in pending { + let _ = h.await; + } +} + +/// Fills this process with what any run of `installation` posting to +/// `target` kept in the store, at most every [`REFILL_SECS`]: a write in a +/// later invocation is checked against reads made in an earlier one. +pub async fn refill(installation: u64, target: &str) { + let Some(store) = store() else { + return; + }; + let key = ledger_key(installation, target); + { + let r = REFILLED.lock().unwrap_or_else(|e| e.into_inner()); + if r.get(&key) + .is_some_and(|at| at.elapsed() < std::time::Duration::from_secs(REFILL_SECS)) + { + return; + } + } + match store.load(&key, REFILL_MAX_ITEMS).await { + Ok(batches) => { + let reads: Vec = batches + .iter() + .filter_map(|b| crate::app_map::gunzip(b, 8 * 1024 * 1024)) + .filter_map(|raw| serde_json::from_slice::>(&raw).ok()) + .flatten() + .collect(); + if !reads.is_empty() { + remember(key.clone(), &reads); + } + REFILLED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(key, std::time::Instant::now()); + } + Err(e) => { + tracing::warn!(error = %e, "Private reads could not be read back; this process's own are still checked") + } + } +} + +/// Forgets what this process keeps for `installation` and `target`, as a +/// fresh process would start (tests of [`refill`]). +pub fn forget_in_process(installation: u64, target: &str) { + let key = ledger_key(installation, target); + LEDGER + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&key); + REFILLED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&key); +} + +/// The store on DynamoDB: `pk = PRIV#{installation}:{owner/name}`, +/// `sk = RUN#{run}#{nanos}`, the gzipped reads and a `ttl`. +pub struct DynamoLedger { + pub dynamo: aws_sdk_dynamodb::Client, + pub table: String, +} + +impl LedgerStore for DynamoLedger { + fn put<'a>( + &'a self, + key: &'a str, + run: &'a str, + body: Vec, + expires: i64, + ) -> LedgerFut<'a, Result<(), String>> { + Box::pin(self.put_item(key, run, body, expires)) + } + + fn load<'a>(&'a self, key: &'a str, max: usize) -> LedgerFut<'a, Result>, String>> { + Box::pin(self.query(key, max)) + } +} + +impl DynamoLedger { + async fn put_item( + &self, + key: &str, + run: &str, + body: Vec, + expires: i64, + ) -> Result<(), String> { + use aws_sdk_dynamodb::primitives::Blob; + use aws_sdk_dynamodb::types::AttributeValue as A; + let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default(); + self.dynamo + .put_item() + .table_name(&self.table) + .item("pk", A::S(format!("PRIV#{key}"))) + .item("sk", A::S(format!("RUN#{run}#{nanos}"))) + .item("body", A::B(Blob::new(body))) + .item("ttl", A::N(expires.to_string())) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e))) + } + + async fn query(&self, key: &str, max: usize) -> Result>, String> { + use aws_sdk_dynamodb::types::AttributeValue as A; + let now = chrono::Utc::now().timestamp(); + let mut out = Vec::new(); + let mut start = None; + loop { + let page = self + .dynamo + .query() + .table_name(&self.table) + .key_condition_expression("pk = :pk") + .filter_expression("#ttl > :now") + .expression_attribute_names("#ttl", "ttl") + .expression_attribute_values(":pk", A::S(format!("PRIV#{key}"))) + .expression_attribute_values(":now", A::N(now.to_string())) + .scan_index_forward(false) + .set_exclusive_start_key(start.take()) + .send() + .await + .map_err(|e| format!("{}", aws_sdk_dynamodb::error::DisplayErrorContext(e)))?; + for it in page.items() { + if let Some(b) = it.get("body").and_then(|b| b.as_b().ok()) { + out.push(b.as_ref().to_vec()); + } + if out.len() >= max { + return Ok(out); + } + } + match page.last_evaluated_key() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => return Ok(out), + } + } + } } /// What `installation`'s work posting to `target` read in private @@ -868,7 +1083,7 @@ mod tests { lines: Vec::new(), }, ]; - note_private(7, "acme/open-shelf", &reads); + note_private(7, "acme/open-shelf", "run-1", &reads); let body = "Prices now match acme/pricing-engine.\nMembers get their discount.\nSee acme/orders for the caller."; let kept = guard_public(7, "ACME/open-shelf", body); assert_eq!(kept, "Members get their discount."); @@ -886,6 +1101,69 @@ mod tests { assert!(code_refused("x").starts_with("Refused")); } + /// A store in memory, as DynamoDB keeps the batches. + #[derive(Default)] + struct Mem(std::sync::Mutex>>>); + + impl LedgerStore for Mem { + fn put<'a>( + &'a self, + key: &'a str, + _run: &'a str, + body: Vec, + _: i64, + ) -> LedgerFut<'a, Result<(), String>> { + self.0 + .lock() + .unwrap() + .entry(key.into()) + .or_default() + .push(body); + Box::pin(async { Ok(()) }) + } + fn load<'a>( + &'a self, + key: &'a str, + max: usize, + ) -> LedgerFut<'a, Result>, String>> { + let got: Vec> = { + let m = self.0.lock().unwrap(); + m.get(key) + .cloned() + .unwrap_or_default() + .into_iter() + .take(max) + .collect() + }; + Box::pin(async move { Ok(got) }) + } + } + + /// A write in a later invocation (a fresh process) is checked against + /// what an earlier one read. + #[tokio::test] + async fn a_write_in_a_fresh_process_is_held_to_an_earlier_read() { + set_store(std::sync::Arc::new(Mem::default())); + let read = Read { + repo: "acme/pricing-engine".into(), + path: "src/tiers.ts".into(), + lines: vec!["export const goldTier = (cart) => cart.total * 0.8;".into()], + }; + note_private(11, "acme/open-shop", "run-9", &[read]); + flush().await; + forget_in_process(11, "acme/open-shop"); + assert!(private_for(11, "acme/open-shop").is_empty()); + let body = "Gold prices now follow acme/pricing-engine.\nGold members pay less."; + refill(11, "acme/open-shop").await; + assert_eq!( + guard_public(11, "acme/open-shop", body), + "Gold members pay less." + ); + // Another installation fills nothing from it. + refill(12, "acme/open-shop").await; + assert_eq!(guard_public(12, "acme/open-shop", body), body); + } + #[test] fn refusal_statuses_are_read() { assert_eq!(status_of(&ReadError::NotFound("x".into())), 404); diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 26872c0fc..c5d1e5bcd 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -4844,6 +4844,7 @@ async fn handle_push( repo_name: name.to_string(), branch: default_branch.to_string(), changed_files, + contracts_only: false, }); send_to_queue(state, &state.config.ticket_queue_url, &message).await } diff --git a/services/gateway/src/routes/graph.rs b/services/gateway/src/routes/graph.rs index 07b9b97f2..931ef6b23 100644 --- a/services/gateway/src/routes/graph.rs +++ b/services/gateway/src/routes/graph.rs @@ -418,6 +418,7 @@ pub(crate) async fn enqueue_full_index( repo_name: name.to_string(), branch: String::new(), // worker resolves the default branch changed_files: None, // full index + contracts_only: false, }); let sent = match serde_json::to_string(&msg) { Ok(body) => state diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 8b95bac0b..09f6b3091 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -422,7 +422,8 @@ async fn converse_as( .unwrap_or_default(), access.as_ref().map(|a| a.installation).unwrap_or(0), ) - .with_index(index, &provider.scope.repo); + .with_index(index, &provider.scope.repo) + .for_run(&provider.scope.run_id); let system = if reaches { super::reach::prompt(system_prompt) } else { @@ -547,6 +548,9 @@ async fn converse_as( let pass = super::run_log::current_pass(&scope.run_id).unwrap_or_else(|| step.to_string()); super::run_log::write(state, &scope.team, &scope.run_id, &pass, Some(step), &own).await; } + // What this loop read in private repositories is in the store before + // the step goes on, so a write in a later invocation is held to it. + common::repo_reach::flush().await; out } diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs index 5e6ede0f1..1813a5c07 100644 --- a/services/worker/src/agent/reach.rs +++ b/services/worker/src/agent/reach.rs @@ -223,6 +223,8 @@ pub struct Exec<'a> { /// repository the work is in. index: Option>, here: String, + /// The run the loop works for: what it reads is kept under it. + run: String, } impl<'a> Exec<'a> { @@ -242,9 +244,17 @@ impl<'a> Exec<'a> { private_reads: Mutex::new(Vec::new()), index: None, here: String::new(), + run: String::new(), } } + /// The run this loop works for (`repo_reach::note_private` keeps its + /// reads under it). + pub fn for_run(mut self, run: &str) -> Self { + self.run = run.to_string(); + self + } + /// The installation's contract index for `find_consumers`, asked from /// `here` (the work's repository). pub fn with_index(mut self, index: Option>, here: &str) -> Self { @@ -289,7 +299,7 @@ impl<'a> Exec<'a> { if !private.is_empty() { // Kept for every later write into the public repository too: // the pull request, its commits and its comments. - repo_reach::note_private(*installation, target, &private); + repo_reach::note_private(*installation, target, &self.run, &private); self.private_reads .lock() .unwrap_or_else(|e| e.into_inner()) diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 0246f280e..7e8737888 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -1850,12 +1850,22 @@ impl GitHubClient { Ok(resp.json().await?) } + /// Fills this process with the private reads kept for the repository a + /// write goes to (`common::repo_reach::refill`), so a write in a later + /// invocation than the read is held to it. + async fn refill_for(&self, url: &str) { + if let Some(target) = write_target(url) { + common::repo_reach::refill(self.installation_id, &target).await; + } + } + async fn post( &self, url: &str, body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; + self.refill_for(url).await; let mut req = self.http.post(url).json(&bounded_payload(&public_payload( self.installation_id, url, @@ -1874,6 +1884,7 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; + self.refill_for(url).await; let mut req = self.http.patch(url).json(&bounded_payload(&public_payload( self.installation_id, url, @@ -4119,6 +4130,7 @@ impl GitHubClient { body["sha"] = serde_json::json!(s); } let headers = self.auth_headers().await?; + self.refill_for(&url).await; let mut req = self.http .put(&url) @@ -5342,6 +5354,7 @@ impl GitHubClient { ) -> Result<(), Box> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}"); let headers = self.auth_headers().await?; + self.refill_for(&url).await; let mut req = self.http.put(&url).json(&public_payload( self.installation_id, &url, @@ -5430,6 +5443,7 @@ impl GitHubClient { "{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}/dismissals" ); let headers = self.auth_headers().await?; + self.refill_for(&url).await; let mut req = self.http.put(&url).json(&public_payload( self.installation_id, &url, @@ -5456,6 +5470,7 @@ impl GitHubClient { ) -> Result<(), Box> { let url = format!("{API_BASE}/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}"); let headers = self.auth_headers().await?; + self.refill_for(&url).await; let mut req = self.http.put(&url).json(&bounded_payload(&public_payload( self.installation_id, &url, @@ -6494,7 +6509,12 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result<(), Box> { let headers = self.auth_headers().await?; - let mut req = self.http.post(url).json(&bounded_payload(body)); + self.refill_for(url).await; + let mut req = self.http.post(url).json(&bounded_payload(&public_payload( + self.installation_id, + url, + body, + ))); for (k, v) in headers { req = req.header(k, v); } @@ -7935,6 +7955,7 @@ mod body_limit_tests { let rest = &src[at..at + 600]; // Bounded, and held for a public repository first. let flat: String = rest.split_whitespace().collect(); + assert!(flat.contains("self.refill_for(url).await;"), "{send}"); assert!( flat.contains("bounded_payload(body)") || flat.contains( diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 9ef31c4ce..accbe1601 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -83,6 +83,13 @@ async fn main() -> Result<(), Error> { // GitHub reads nobody waits on are kept for every worker process, so a // sweep asks GitHub only whether they changed (`github_shared`). + // What work posting to a public repository read in private ones is kept + // for every worker process, so a later write is held to it + // (`common::repo_reach`). + common::repo_reach::set_store(Arc::new(common::repo_reach::DynamoLedger { + dynamo: dynamo.clone(), + table: config.settings_table_name.clone(), + })); clients::github_shared::set_store(Arc::new(clients::github_shared::DynamoReads { dynamo: dynamo.clone(), table: config.analytics_table_name.clone(), diff --git a/services/worker/src/passes/code_graph.rs b/services/worker/src/passes/code_graph.rs index a47c25f87..90f7fc4d1 100644 --- a/services/worker/src/passes/code_graph.rs +++ b/services/worker/src/passes/code_graph.rs @@ -622,6 +622,9 @@ pub async fn run( msg: GraphIndexMessage, ) -> Result<(), Box> { use common::code_graph::{self as cg, BuildState}; + if msg.contracts_only { + return contracts_pass(state, msg).await; + } let table = &state.config.settings_table_name; let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); if !cg::is_enabled(&state.dynamo, table, &msg.team_id, &repo).await { @@ -1002,28 +1005,123 @@ async fn refresh_contracts( let Some(team) = team else { return; }; - let mut queued = 0; - for pkg in record - .packages() - .into_iter() - .map(|(p, _)| p) - .filter(|p| !before.contains(p) && !exposed.contains(p)) - { - for other in team.records.iter().filter(|r| { - !r.repo.eq_ignore_ascii_case(&repo) - && r.entries.iter().any(|e| { - e.kind == xc::Kind::Package && e.side == xc::Side::Uses && e.key == pkg - }) - }) { - if queued >= REQUEUE_CAP { - return; - } - if queue_full_index(state, &msg.team_id, &other.repo, msg.installation_id, false).await - { - queued += 1; - } + // Dependents are read for their contracts only, whatever state their + // graph is in. + for other in xc::dependents_of_new(&team, &record, &before, &exposed, REQUEUE_CAP) { + queue_contract_read(state, &msg.team_id, &other, msg.installation_id).await; + } +} + +/// Queues a read of `repo`'s contracts only (`GraphIndexMessage:: +/// contracts_only`), unless one is queued already (`common::contracts:: +/// mark_read_queued`, which never reads the graph's own status). Returns +/// whether this call queued it. +pub async fn queue_contract_read( + state: &WorkerState, + team_id: &str, + repo: &str, + installation_id: u64, +) -> bool { + let Some((owner, name)) = repo.split_once('/') else { + return false; + }; + if state.config.ticket_queue_url.is_empty() { + return false; + } + let table = &state.config.settings_table_name; + match common::contracts::mark_read_queued(&state.dynamo, table, team_id, repo).await { + Ok(true) => {} + Ok(false) => return false, + Err(e) => { + warn!(error = %e, repo, "Contract index: could not mark a read queued"); + return false; } } + let installation_id = if installation_id > 0 { + installation_id + } else { + team_installation_id(state, team_id).await.unwrap_or(0) + }; + let msg = crate::models::WorkerMessage::GraphIndex(GraphIndexMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + branch: String::new(), + changed_files: None, + contracts_only: true, + }); + let sent = match (installation_id, serde_json::to_string(&msg)) { + (0, _) => Err("no GitHub installation for the team".to_string()), + (_, Ok(body)) => state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()), + (_, Err(e)) => Err(e.to_string()), + }; + match sent { + Ok(()) => { + info!(repo, "Contract index: read queued"); + true + } + Err(e) => { + warn!(error = %e, repo, "Contract index: could not queue a read"); + common::contracts::unmark_read_queued(&state.dynamo, table, team_id, repo).await; + false + } + } +} + +/// A contracts-only read: the repository's contracts in full, its graph +/// and build status untouched. A repository whose graph was turned off +/// gets an empty record, so it isn't queued again. +async fn contracts_pass( + state: &WorkerState, + msg: GraphIndexMessage, +) -> Result<(), Box> { + let table = &state.config.settings_table_name; + let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); + if !common::code_graph::is_enabled(&state.dynamo, table, &msg.team_id, &repo).await { + let empty = common::contracts::Record { + repo: repo.clone(), + commit: "off".into(), + entries: Vec::new(), + }; + common::contracts::save_record(&state.dynamo, table, &msg.team_id, &empty).await?; + return Ok(()); + } + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + let branch = if msg.branch.is_empty() { + github + .get_default_branch(&msg.repo_owner, &msg.repo_name) + .await? + } else { + msg.branch.clone() + }; + let head = github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch) + .await?; + let bytes = github + .download_tarball(&msg.repo_owner, &msg.repo_name, &head) + .await?; + let snapshot = crate::clients::repo_snapshot::RepoSnapshot::from_tarball(&bytes)?; + let all_paths: Vec = snapshot.tree().await; + let full = GraphIndexMessage { + changed_files: None, + ..msg + }; + refresh_contracts(state, &full, &snapshot, &all_paths, &head).await; + Ok(()) } /// Repositories read again at most when one pass newly exposes a package. @@ -1347,6 +1445,7 @@ pub async fn queue_full_index( repo_name: name.to_string(), branch: String::new(), changed_files: None, + contracts_only: false, }); let sent = match (installation_id, serde_json::to_string(&msg)) { (0, _) => Err("no GitHub installation for the team".to_string()), @@ -1516,6 +1615,7 @@ impl RepoGraphs { &self.team_id, &self.default_repo, self.installation_id, + &self.run.run_id, ) .await; self.with_map(map).with_contracts(contracts) 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 d4846d5a1..b2b40f107 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -333,6 +333,7 @@ const CACHES: &[(&str, &str)] = &[ ("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/contracts.rs::CACHE", "team id; holds that team's own contract index"), + ("common/src/repo_reach.rs::REFILLED", "installation id plus a public `owner/repo`: only when that key was last filled from the store"), ("common/src/repo_reach.rs::LEDGER", "installation id plus a public `owner/repo`: what that installation read in private repositories, only ever taken out of its own writes there"), ("common/src/hybrid/client.rs::TOKENS", "installation id"), ("common/src/hybrid/client.rs::FAILING", "installation id"), diff --git a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs index c89f95f5d..e05f5911f 100644 --- a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -222,7 +222,7 @@ fn a_pull_request_never_ships_without_its_consumers_or_a_compatibility_note() { .find("description::checked_for_diff(&full_body, &diff)") .unwrap(); let compat = run - .find("super::xrepo::with_compat(state, msg, plan, &diff, &full_body)") + .find("super::xrepo::with_compat(state, msg, plan, &diff, &full_body, run_id)") .unwrap(); let opened = run.find(concat!(".create_pull", "_request(")).unwrap(); assert!(checked < compat && compat < opened); @@ -261,6 +261,19 @@ fn the_index_is_used_not_bypassed() { assert!(load.contains("super::xrepo::RunContracts::load(")); let offer = super::fixture::fn_src(graph, "pub fn offer("); assert!(offer.contains("graphs.contracts()")); + // Repositories with no record, and dependents of a newly exposed + // package, are read for their contracts only, whatever their graph's + // state: never through the graph's own queue, which skips a built one. + let xrepo = include_str!("../xrepo.rs"); + let load = super::fixture::fn_src(xrepo, "pub async fn load("); + assert!(load.contains("queue_contract_read(") && !load.contains("queue_full_index(")); + let refresh = super::fixture::fn_src(graph, "async fn refresh_contracts("); + assert!(refresh.contains("queue_contract_read(") && !refresh.contains("queue_full_index(")); + let read = super::fixture::fn_src(graph, "pub async fn queue_contract_read("); + assert!(read.contains("mark_read_queued(") && !read.contains("code_graph::mark_queued(")); + assert!( + super::fixture::fn_src(graph, "pub async fn run(").contains("contracts_pass(state, msg)") + ); // The index follows every push: the code graph's pass refreshes it. let pass = super::fixture::fn_src(graph, "async fn index_pass("); assert!(pass.contains("refresh_contracts(state, &msg, &snapshot, &all_paths, &head)")); @@ -361,6 +374,7 @@ fn every_public_surface_is_held_and_private_ones_reference_freely() { repo_reach::note_private( INSTALLATION, API, + "run-1", &[Read { repo: SHOP.into(), path: "src/pages/book.tsx".into(), @@ -409,3 +423,78 @@ fn every_public_surface_is_held_and_private_ones_reference_freely() { ); assert_eq!(other, pr); } + +/// The store as DynamoDB keeps it, in memory. +#[derive(Default)] +struct Kept(std::sync::Mutex>>>); + +impl repo_reach::LedgerStore for Kept { + fn put<'a>( + &'a self, + key: &'a str, + _run: &'a str, + body: Vec, + _: i64, + ) -> repo_reach::LedgerFut<'a, Result<(), String>> { + self.0 + .lock() + .unwrap() + .entry(key.into()) + .or_default() + .push(body); + Box::pin(async { Ok(()) }) + } + fn load<'a>( + &'a self, + key: &'a str, + max: usize, + ) -> repo_reach::LedgerFut<'a, Result>, String>> { + let got: Vec> = self + .0 + .lock() + .unwrap() + .get(key) + .cloned() + .unwrap_or_default() + .into_iter() + .take(max) + .collect(); + Box::pin(async move { Ok(got) }) + } +} + +/// The coder read a private consumer in one invocation; the pull request +/// is written in another, a fresh process with nothing in memory. The +/// write is still held to the read. +#[tokio::test] +async fn a_write_in_a_later_invocation_is_held_to_an_earlier_read() { + const TARGET: &str = "acme/open-orders"; + repo_reach::set_store(Arc::new(Kept::default())); + repo_reach::note_private( + INSTALLATION, + TARGET, + "run-7", + &[Read { + repo: SHOP.into(), + path: "src/pages/checkout.tsx".into(), + lines: vec![" const total = await fetch(`/api/orders/${id}/total`);".into()], + }], + ); + // The loop's end waits for the store (`provider::converse_as`). + repo_reach::flush().await; + let provider = include_str!("../../agent/provider.rs"); + assert!(super::fixture::fn_src(provider, "async fn converse_as(") + .contains("common::repo_reach::flush().await")); + // A fresh process: nothing kept in memory. + repo_reach::forget_in_process(INSTALLATION, TARGET); + let body = serde_json::json!({"body": "Totals load faster.\nThe acme/storefront checkout reads them."}); + let url = format!("https://api.github.com/repos/{TARGET}/pulls"); + assert_eq!( + crate::clients::github::public_payload(INSTALLATION, &url, &body), + body + ); + // The GitHub client fills it from the store before every write. + repo_reach::refill(INSTALLATION, TARGET).await; + let held = crate::clients::github::public_payload(INSTALLATION, &url, &body); + assert_eq!(held["body"], "Totals load faster."); +} diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 7e5e050bd..5a643b43c 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -626,7 +626,7 @@ Return ONLY the markdown body text."#, // A change touching contracts other repositories of the installation // use, which neither changes them nor says how it stays compatible, // says so in its description (`xrepo`). - let full_body = super::xrepo::with_compat(state, msg, plan, &diff, &full_body).await; + let full_body = super::xrepo::with_compat(state, msg, plan, &diff, &full_body, run_id).await; // The PR title and squash commit follow the team's templates. let conventions = super::load_git_conventions(state, &msg.team_id, &msg.ticket_id).await; diff --git a/services/worker/src/passes/xrepo.rs b/services/worker/src/passes/xrepo.rs index ff4fc2a40..7ba672637 100644 --- a/services/worker/src/passes/xrepo.rs +++ b/services/worker/src/passes/xrepo.rs @@ -73,6 +73,8 @@ pub struct RunContracts { public: BTreeSet, /// The installation the work reads with. installation: u64, + /// The run the step is for: what it shows is kept under it. + run: String, } impl RunContracts { @@ -85,6 +87,7 @@ impl RunContracts { team_id: &str, repo: &str, installation_id: u64, + run: &str, ) -> Option { let table = &state.config.settings_table_name; let index = xc::team_index(&state.dynamo, table, team_id).await; @@ -92,18 +95,17 @@ impl RunContracts { .as_ref() .map(|i| i.records.iter().map(|r| r.repo.to_lowercase()).collect()) .unwrap_or_default(); - let mut queued = 0; + // Repositories with no record yet, whatever their graph's state, + // are read for their contracts only: at most BACKFILL_PER_STEP + // queued per step, from at most four times as many tries. let mut repos = vec![repo.to_string()]; repos.extend(super::plan::fetch_team_repos(state, team_id).await); - for r in repos { + let mut queued = 0; + for r in xc::backfill(&known, &repos, BACKFILL_PER_STEP * 4) { if queued >= BACKFILL_PER_STEP { break; } - if !known.contains(&r.to_lowercase()) - && super::code_graph::queue_full_index(state, team_id, &r, installation_id, false) - .await - { - info!(repo = %r, "Contract index: first read queued"); + if super::code_graph::queue_contract_read(state, team_id, &r, installation_id).await { queued += 1; } } @@ -112,13 +114,15 @@ impl RunContracts { .await .map(|a| a.public) .unwrap_or_default(); - info!( + tracing::debug!( team_id, repo, repos = index.records.len(), "Contract index: offered to the step" ); - Some(Self::of(index, repo, public, installation_id)) + let mut c = Self::of(index, repo, public, installation_id); + c.run = run.to_string(); + Some(c) } /// Over an index already read (tests; callers that hold one). @@ -133,6 +137,7 @@ impl RunContracts { index, public, installation, + run: String::new(), } } @@ -175,7 +180,7 @@ impl RunContracts { lines: l.clone(), }), ); - repo_reach::note_private(self.installation, &self.repo, &reads); + repo_reach::note_private(self.installation, &self.repo, &self.run, &reads); } /// The links of planned files `(repo, path)`, each repository's asked @@ -369,7 +374,7 @@ impl RunContracts { )); } self.note(&links, &read); - info!(repo = %self.repo, excerpts = read.len(), tokens = out.len().div_ceil(4), "Contract index: the coder's related code"); + tracing::debug!(repo = %self.repo, excerpts = read.len(), tokens = out.len().div_ceil(4), "Contract index: the coder's related code"); if read.is_empty() { // Nothing could be read: the links alone, as the planner had them. for l in links.iter().take(12) { @@ -437,7 +442,7 @@ impl RunContracts { ); } let out = common::truncate_str(&out, SECTION_CHARS).to_string(); - info!(repo = %self.repo, breaks = breaks.len(), consumers = links.len(), "Contract index: the reviewer's check"); + tracing::debug!(repo = %self.repo, breaks = breaks.len(), consumers = links.len(), "Contract index: the reviewer's check"); out } @@ -566,9 +571,11 @@ pub async fn with_compat( plan: &super::plan::PlanResult, compare: &serde_json::Value, body: &str, + run_id: &str, ) -> String { let repo = format!("{}/{}", msg.repo_owner, msg.repo_name); - let Some(c) = RunContracts::load(state, &msg.team_id, &repo, msg.installation_id).await else { + let Some(c) = RunContracts::load(state, &msg.team_id, &repo, msg.installation_id, run_id).await + else { return body.to_string(); }; match c.compat_note(&changed_of(compare), &work_repos(&repo, plan), body) { From da42726c9291c4d7ed3657a49ddedf479606f875 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 5 Dec 2026 02:53:45 -0500 Subject: [PATCH 8/8] Public-repository privacy fails closed when visibility isn't known When the installation's listing can't be read, or doesn't name a repository, that repository counts as private when it was read and as public when it is written to (reach::Visibility). Only a target the listing names, and not as public, is private. The model loops, the contract index view and so the GitHub client's held writes all decide through it, and a loop whose listing failed still keeps its reads under the team's installation. Reading is never limited by it. --- ..._contract_change_reaches_every_consumer.md | 2 +- services/worker/src/agent/provider.rs | 15 +- services/worker/src/agent/reach.rs | 143 ++++++++++++++++-- .../xp_answers_read_the_other_repo.rs | 15 +- ..._contract_change_reaches_every_consumer.rs | 71 ++++++++- services/worker/src/passes/xrepo.rs | 22 +-- 6 files changed, 231 insertions(+), 37 deletions(-) diff --git a/docs/incidents/xt_contract_change_reaches_every_consumer.md b/docs/incidents/xt_contract_change_reaches_every_consumer.md index 0351eb6c4..32a2dc24d 100644 --- a/docs/incidents/xt_contract_change_reaches_every_consumer.md +++ b/docs/incidents/xt_contract_change_reaches_every_consumer.md @@ -13,6 +13,6 @@ - **Shipping.** A pull request whose change touches contracts other repositories use, with neither those repositories in the run nor a compatibility section in its description, gets one, with every removed contract marked breaking. - **Every loop can ask.** Every worker loop with tools has `find_consumers` over the index, and its prompt says to ask it before changing or explaining a contract. - **No limit to one repository.** A source scan fails on a prompt that limits PR work to one repository, and on any graph registry PR work opens without the team's other repositories. -- **Privacy on every surface.** Reading stays unrestricted. Work posting to a public repository keeps every private read, from the tools and from what the index showed it, in memory and in a short-lived store item per installation, public repository and run; every loop waits for it to be stored, and the GitHub client reads it back before each write, so a write in a later invocation is held to an earlier read. A write tool whose input copies a private line, or names a private repository or a path read in one, is refused with the reason, and every text the GitHub client writes into that repository (pull request titles and bodies, commit messages, comments, reviews, release notes) has what came from a private repository taken out by the same leak check. The reviewer and the compatibility section say "a private repository of the installation" instead of a name. A private repository's work may reference freely. +- **Privacy on every surface.** Reading stays unrestricted. Work posting to a public repository keeps every private read, from the tools and from what the index showed it, in memory and in a short-lived store item per installation, public repository and run; every loop waits for it to be stored, and the GitHub client reads it back before each write, so a write in a later invocation is held to an earlier read. A write tool whose input copies a private line, or names a private repository or a path read in one, is refused with the reason, and every text the GitHub client writes into that repository (pull request titles and bodies, commit messages, comments, reviews, release notes) has what came from a private repository taken out by the same leak check. The reviewer and the compatibility section say "a private repository of the installation" instead of a name. Visibility fails closed: when the installation's listing can't be read, or doesn't name a repository, that repository counts as private when it was read and as public when it is written to; only a target the listing names, and not as public, is private. A private repository's work may reference freely. **Where it's enforced:** `common::contracts::{extract, Record, Index::links, Index::breaks, compat_section, team_index, answer}`, `common::repo_reach::{note_private, guard_public, code_refused}`, the worker's `passes::xrepo::RunContracts::{load, planner_section, plan_gaps, coder_context, review_section, break_findings, compat_note}` and `with_compat`, `passes::code_graph::{refresh_contracts, RepoGraphs::load_map, offer}`, `agent::reach::{offer, prompt, Exec}`, `agent::provider::converse_as` and `clients::github::public_payload`. diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 09f6b3091..4512bb471 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -414,13 +414,18 @@ async fn converse_as( None }; let exec = super::reach::Exec::new(tool_executor, reader.as_ref(), &missing) + // Visibility fails closed: with no listing, every source is + // private and every target public (`reach::Visibility`). .posting_to( &provider.scope.repo, - &access - .as_ref() - .map(|a| a.public.clone()) - .unwrap_or_default(), - access.as_ref().map(|a| a.installation).unwrap_or(0), + &super::reach::Visibility::of(&access), + match &access { + Ok(a) => a.installation, + Err(_) if reaches => { + super::reach::installation_of(state, &provider.scope.team).await + } + Err(_) => 0, + }, ) .with_index(index, &provider.scope.repo) .for_run(&provider.scope.run_id); diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs index 1813a5c07..3dcd5a54f 100644 --- a/services/worker/src/agent/reach.rs +++ b/services/worker/src/agent/reach.rs @@ -115,6 +115,14 @@ async fn read_access(state: &crate::WorkerState, team: &str) -> Result u64 { + crate::passes::review_reminder::team_installation_id(state, team) + .await + .unwrap_or(0) +} + /// `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 { @@ -208,6 +216,62 @@ pub fn is_public(public: &BTreeSet, repo: &str) -> bool { .any(|p| p.rsplit('/').next() == Some(r.as_str())) } +/// What the installation's listing says about repositories' visibility, +/// read so that privacy fails closed: a repository whose visibility isn't +/// known is private as a source (what was read in it is kept from public +/// writes) and public as a target (what is written there is held). Only a +/// target the listing names, and doesn't name as public, is private. +/// Reading is never limited by it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Visibility { + /// Every repository the listing named (lower case); `None` when the + /// listing couldn't be read. + listed: Option>, + /// The repositories it named public (lower case). + public: BTreeSet, +} + +impl Visibility { + /// From a listing: every repository it named, and those public. + pub fn known>(listed: I, public: &BTreeSet) -> Self { + Visibility { + listed: Some(listed.into_iter().map(|r| r.to_lowercase()).collect()), + public: public.iter().map(|r| r.to_lowercase()).collect(), + } + } + + /// No listing: nothing is known. + pub fn unknown() -> Self { + Visibility::default() + } + + /// From the team's access, or its failure. + pub fn of(access: &Result) -> Self { + match access { + Ok(a) => Self::known(a.repos.iter().map(|r| r.name.clone()), &a.public), + Err(_) => Self::unknown(), + } + } + + /// Whether what was read in `repo` is kept from public writes: every + /// repository not known public. + pub fn source_private(&self, repo: &str) -> bool { + !is_public(&self.public, repo) + } + + /// Whether what is written into `repo` is held: every repository not + /// known private (listed, and not public). + pub fn target_public(&self, repo: &str) -> bool { + if is_public(&self.public, repo) { + return true; + } + match &self.listed { + Some(listed) => !is_public(listed, repo), + None => true, + } + } +} + /// A loop's executor with the cross-repository tools in front of it. pub struct Exec<'a> { inner: &'a dyn ToolExecutor, @@ -217,7 +281,7 @@ pub struct Exec<'a> { /// The repository this loop's reply goes to and the repositories known /// public, when that repository is public; `None` otherwise (nothing to /// keep apart). - public_reply: Option<(u64, String, BTreeSet)>, + public_reply: Option<(u64, String, Visibility)>, private_reads: Mutex>, /// The installation's contract index, for `find_consumers`, and the /// repository the work is in. @@ -267,14 +331,9 @@ impl<'a> Exec<'a> { /// 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, - installation: u64, - ) -> Self { - if is_public(public, target) { - self.public_reply = Some((installation, target.to_string(), public.clone())); + pub fn posting_to(mut self, target: &str, vis: &Visibility, installation: u64) -> Self { + if !target.trim().is_empty() && vis.target_public(target) { + self.public_reply = Some((installation, target.to_string(), vis.clone())); } self } @@ -289,12 +348,13 @@ impl<'a> Exec<'a> { } fn keep_reads(&self, reads: Vec) { - let Some((installation, target, public)) = &self.public_reply else { + let Some((installation, target, vis)) = &self.public_reply else { return; }; let private: Vec = reads .into_iter() - .filter(|r| !is_public(public, &r.repo)) + // The target's own content is never another repository's. + .filter(|r| !r.repo.eq_ignore_ascii_case(target) && vis.source_private(&r.repo)) .collect(); if !private.is_empty() { // Kept for every later write into the public repository too: @@ -498,11 +558,70 @@ mod tests { } } + /// Privacy fails closed: with no listing, every source is private and + /// every target public; with one, an unlisted target is public, an + /// unlisted source private, and a listed, non-public target private. + #[tokio::test] + async fn visibility_fails_closed_when_the_listing_is_unknown() { + let none = Visibility::of(&Err("the listing failed".into())); + assert!(none.target_public("acme/back-office") && none.source_private("acme/open-catalog")); + let known = Visibility::known( + [ + "acme/open-catalog".to_string(), + "acme/back-office".to_string(), + ], + &["acme/open-catalog".to_string()].into(), + ); + assert!( + known.target_public("acme/open-catalog") && !known.target_public("acme/back-office") + ); + assert!(known.target_public("acme/beyond-the-listing")); + assert!( + known.source_private("acme/beyond-the-listing") + && !known.source_private("acme/open-catalog") + ); + // A loop with no listing, posting anywhere: a copy of another + // repository is refused, its own repository's content is not. + let line = "export const shelfPrice = (book) => book.list * 0.85;"; + let exec = Exec::new(&Wrote, None, "").posting_to("acme/back-office", &none, 7); + exec.keep_reads(vec![Read { + repo: "acme/open-catalog".into(), + path: "src/shelf.ts".into(), + lines: vec![line.into()], + }]); + let copied = json!({"path": "src/price.ts", "content": line}); + assert!(exec + .execute("write_file", &copied) + .await + .unwrap() + .as_str() + .unwrap() + .starts_with("Refused")); + let own = Exec::new(&Wrote, None, "").posting_to("acme/back-office", &none, 7); + own.keep_reads(vec![Read { + repo: "acme/back-office".into(), + path: "src/own.ts".into(), + lines: vec!["export const ownHelper = (value) => value * 2;".into()], + }]); + let mine = json!({"path": "src/x.ts", "content": "export const ownHelper = (value) => value * 2;"}); + assert_eq!( + own.execute("write_file", &mine).await.unwrap(), + json!("written") + ); + } + /// Code written into a public repository never copies a private one; /// into a private one it may. #[tokio::test] async fn a_public_write_that_copies_a_private_repo_is_refused() { - let public: BTreeSet = ["acme/open-catalog".to_string()].into(); + let public = Visibility::known( + [ + "acme/open-catalog".to_string(), + "acme/back-office".to_string(), + "acme/pricing-rules".to_string(), + ], + &["acme/open-catalog".to_string()].into(), + ); let line = "export const shelfPrice = (book) => book.list * 0.85;"; let read = Read { repo: "acme/pricing-rules".into(), 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 ffa129380..fa418add4 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 @@ -365,6 +365,11 @@ fn public_set() -> std::collections::BTreeSet { [API, SITE].iter().map(|r| r.to_string()).collect() } +/// What the listing says: every repository named, the API and site public. +fn vis() -> reach::Visibility { + reach::Visibility::known(all_repos().into_iter().map(|r| r.name), &public_set()) +} + fn all_repos() -> Vec { let mut r = repos(); r.push(RepoInfo::new(RULES, "main")); @@ -378,7 +383,7 @@ fn all_repos() -> Vec { 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(), 1); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &vis(), 1); exec.execute( repo_reach::READ_REPO_FILE, &json!({"repo": RULES, "path": DISCOUNT}), @@ -424,8 +429,7 @@ async fn a_public_reply_gives_the_conclusion_of_a_private_read_without_quoting_i 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(), 1); + let private_target = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(RULES, &vis(), 1); private_target .execute( repo_reach::READ_REPO_FILE, @@ -435,8 +439,7 @@ async fn private_replies_and_public_to_public_replies_may_quote() { .unwrap(); assert!(private_target.private_reads().is_empty()); - let public_target = - reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set(), 1); + let public_target = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &vis(), 1); public_target .execute( repo_reach::READ_REPO_FILE, @@ -463,7 +466,7 @@ async fn private_replies_and_public_to_public_replies_may_quote() { 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(), 1); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &vis(), 1); exec.execute( repo_reach::READ_REPO_FILE, &json!({"repo": RULES, "path": DISCOUNT}), diff --git a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs index e05f5911f..234d43e54 100644 --- a/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -106,8 +106,13 @@ fn public() -> BTreeSet { [API.to_string(), APP.to_string()].into() } +/// The installation's listing: every repository named, `public` public. +fn listing(public: &BTreeSet) -> crate::agent::reach::Visibility { + crate::agent::reach::Visibility::known([API, SHOP, APP, TYPES].map(String::from), public) +} + fn run(repo: &str) -> RunContracts { - RunContracts::of(bookstore(), repo, public(), INSTALLATION) + RunContracts::of(bookstore(), repo, listing(&public()), INSTALLATION) } fn files(repo: &str, paths: &[&str]) -> Vec<(String, String)> { @@ -171,7 +176,7 @@ fn a_removed_contract_is_a_required_finding_citing_the_consumer() { .contains("a private repository of the installation")); assert!(!f[0].body.contains(SHOP) && !f[0].body.contains("src/pages/book.tsx")); // Between private repositories the finding cites the consumer's line. - let private = RunContracts::of(bookstore(), API, BTreeSet::new(), INSTALLATION); + let private = RunContracts::of(bookstore(), API, listing(&BTreeSet::new()), INSTALLATION); let f = private.break_findings(&removed); assert!(f[0] .body @@ -498,3 +503,65 @@ async fn a_write_in_a_later_invocation_is_held_to_an_earlier_read() { let held = crate::clients::github::public_payload(INSTALLATION, &url, &body); assert_eq!(held["body"], "Totals load faster."); } + +/// The installation's listing can't be read (a refused token, a passing +/// GitHub error). Privacy fails closed: the work's repository counts as +/// public and every other as private. The index view, the tool reads and a +/// later write in a fresh process all stay redacted; reading goes on. +#[tokio::test] +async fn a_listing_failure_fails_closed_on_every_surface() { + const TARGET: &str = "acme/orders-unlisted"; + let unknown = crate::agent::reach::Visibility::of(&Err("GitHub refused the listing".into())); + repo_reach::set_store(Arc::new(Kept::default())); + // The index view: the planner still sees the consumers (reading goes + // on), the finding never names them, and what it showed is kept. + let index = bookstore(); + let mut api = index.records[0].clone(); + api.repo = TARGET.into(); + let mut records = index.records.clone(); + records.push(api); + let c = RunContracts::of( + Arc::new(Index { records }), + TARGET, + unknown.clone(), + INSTALLATION, + ); + assert!(c.public_target()); + let section = c.planner_section(&["src/routes/books.ts".into()]); + assert!(section.contains(SHOP)); + let removed = vec![( + "src/routes/books.ts".to_string(), + "@@ -3,1 +3,0 @@\n-app.get('/books/:id', show);\n".to_string(), + )]; + let f = c.break_findings(&removed); + assert!(!f.is_empty() && f.iter().all(|f| !f.body.contains(SHOP))); + // The tool reads: a loop posting to the target keeps what it read. + struct Nothing; + #[async_trait::async_trait] + impl crate::agent::llm::ToolExecutor for Nothing { + async fn execute( + &self, + _: &str, + _: &serde_json::Value, + ) -> Result> { + Ok(serde_json::json!("written")) + } + } + let exec = crate::agent::reach::Exec::new(&Nothing, None, "") + .posting_to(TARGET, &unknown, INSTALLATION) + .for_run("run-3"); + let read = serde_json::json!({"repo": APP, "path": "src/orders/listen.ts"}); + let _ = crate::agent::llm::ToolExecutor::execute(&exec, "read_file", &read).await; + // Reading went on, and what it read is kept for the target. + assert!(repo_reach::private_for(INSTALLATION, TARGET) + .iter() + .any(|r| r.repo == APP)); + // A later write, in a fresh process, toward the target. + repo_reach::flush().await; + repo_reach::forget_in_process(INSTALLATION, TARGET); + repo_reach::refill(INSTALLATION, TARGET).await; + let body = serde_json::json!({"body": "Orders load faster.\nThe acme/storefront book page and acme/reader-app listener follow."}); + let url = format!("https://api.github.com/repos/{TARGET}/pulls"); + let held = crate::clients::github::public_payload(INSTALLATION, &url, &body); + assert_eq!(held["body"], "Orders load faster."); +} diff --git a/services/worker/src/passes/xrepo.rs b/services/worker/src/passes/xrepo.rs index 7ba672637..3b7d2004a 100644 --- a/services/worker/src/passes/xrepo.rs +++ b/services/worker/src/passes/xrepo.rs @@ -69,8 +69,8 @@ pub const BREAK_TITLE: &str = "Breaks a consumer in another repository"; pub struct RunContracts { repo: String, index: Arc, - /// The repositories GitHub says are public (lower case). - public: BTreeSet, + /// What the listing says about visibility; unknown fails closed. + vis: crate::agent::reach::Visibility, /// The installation the work reads with. installation: u64, /// The run the step is for: what it shows is kept under it. @@ -110,17 +110,17 @@ impl RunContracts { } } let index = index?; - let public = crate::agent::reach::access(state, team_id) - .await - .map(|a| a.public) - .unwrap_or_default(); + // A listing that can't be read fails closed: the work's repository + // counts as public, every other as private. + let vis = + crate::agent::reach::Visibility::of(&crate::agent::reach::access(state, team_id).await); tracing::debug!( team_id, repo, repos = index.records.len(), "Contract index: offered to the step" ); - let mut c = Self::of(index, repo, public, installation_id); + let mut c = Self::of(index, repo, vis, installation_id); c.run = run.to_string(); Some(c) } @@ -129,13 +129,13 @@ impl RunContracts { pub fn of( index: Arc, repo: &str, - public: BTreeSet, + vis: crate::agent::reach::Visibility, installation: u64, ) -> RunContracts { RunContracts { repo: repo.to_string(), index, - public, + vis, installation, run: String::new(), } @@ -143,11 +143,11 @@ impl RunContracts { /// Whether the work's repository is public. pub fn public_target(&self) -> bool { - crate::agent::reach::is_public(&self.public, &self.repo) + self.vis.target_public(&self.repo) } fn private(&self, repo: &str) -> bool { - !crate::agent::reach::is_public(&self.public, repo) + self.vis.source_private(repo) } /// Every private repository and path `links` show, kept for the work's