diff --git a/docs/code-map.md b/docs/code-map.md index 77b653e5..329a85e3 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -78,3 +78,43 @@ 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 (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 + 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 00000000..32a2dc24 --- /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, 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 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, 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/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index 86ef10db..67f54572 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 00000000..f7168dc0 --- /dev/null +++ b/services/common/src/contracts.rs @@ -0,0 +1,2093 @@ +//! 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)>, +} + +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(""); + lines.iter().any(|l| { + GQL_FIELD + .captures(l) + .is_some_and(|c| c.get(1).map(|m| m.as_str()) == Some(field)) + }) + } + 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, &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)) + }), + } +} + +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; + } + // 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 !defines(path, e, &removed) || defines(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() { + match it + .get("body") + .and_then(|b| b.as_b().ok()) + .and_then(|b| Record::from_body(b.as_ref())) + { + 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() { + Some(k) if !k.is_empty() => start = Some(k.clone()), + _ => break, + } + } + 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); + +/// 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 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)); + 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 90a938e7..2e4f5708 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/messages.rs b/services/common/src/messages.rs index 032a1bad..a3915979 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 7e4bc833..566b6a53 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, @@ -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,323 @@ 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, 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; +/// 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; +/// 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 +/// never held against another's writes. +#[allow(clippy::type_complexity)] +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()) +} + +/// 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); + 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(); + 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 +/// 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 +1069,101 @@ 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", "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."); + // 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")); + } + + /// 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/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index b3f85677..6fa847fc 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/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 26872c0f..c5d1e5bc 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 07b9b97f..931ef6b2 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 4f4705ef..4512bb47 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -401,13 +401,34 @@ 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) + // Visibility fails closed: with no listing, every source is + // private and every target public (`reach::Visibility`). + .posting_to( + &provider.scope.repo, + &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); let system = if reaches { super::reach::prompt(system_prompt) } else { @@ -532,6 +553,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 1f2bd7fe..3dcd5a54 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 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 { @@ -119,7 +137,10 @@ pub fn offer(tools: &[ToolDefinition]) -> 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 +157,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 { @@ -158,16 +216,79 @@ 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, 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, Visibility)>, private_reads: Mutex>, + /// The installation's contract index, for `find_consumers`, and the + /// 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> { @@ -185,16 +306,34 @@ impl<'a> Exec<'a> { refusals: Mutex::new(Vec::new()), public_reply: None, 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 { + 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 { - if is_public(public, target) { - self.public_reply = Some(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 } @@ -209,14 +348,18 @@ impl<'a> Exec<'a> { } fn keep_reads(&self, reads: Vec) { - let Some(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: + // the pull request, its commits and its comments. + repo_reach::note_private(*installation, target, &self.run, &private); self.private_reads .lock() .unwrap_or_else(|e| e.into_inner()) @@ -224,6 +367,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 +415,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 +528,128 @@ 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")) + } + } + + /// 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 = 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(), + 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 52906daa..7e873788 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, @@ -1791,13 +1850,27 @@ 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?; - 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); } @@ -1811,7 +1884,12 @@ impl GitHubClient { body: &serde_json::Value, ) -> Result> { let headers = self.auth_headers().await?; - let mut req = self.http.patch(url).json(&bounded_payload(body)); + self.refill_for(url).await; + 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 +4130,11 @@ impl GitHubClient { body["sha"] = serde_json::json!(s); } let headers = self.auth_headers().await?; - let mut req = self.http.put(&url).json(&body); + self.refill_for(&url).await; + 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 +5354,12 @@ 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 })); + self.refill_for(&url).await; + 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 +5443,15 @@ 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", - })); + self.refill_for(&url).await; + 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 +5470,12 @@ 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 }))); + self.refill_for(&url).await; + 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); } @@ -6418,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); } @@ -7857,7 +7953,16 @@ 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("self.refill_for(url).await;"), "{send}"); + assert!( + flat.contains("bounded_payload(body)") + || flat.contains( + "bounded_payload(&public_payload(self.installation_id,url,body,))" + ), + "{send}" + ); } } } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 9ef31c4c..accbe160 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 725dc6c1..90f7fc4d 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 { @@ -697,6 +700,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 +945,188 @@ 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; + }; + // 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. +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 +1365,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 } @@ -1252,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()), @@ -1348,6 +1542,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 +1588,7 @@ impl RepoGraphs { run: common::live::store::RunRef::default(), others: tokio::sync::Mutex::new(HashMap::new()), map: None, + contracts: None, } } @@ -1400,11 +1598,32 @@ 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, + &self.run.run_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 e9ed4f58..83179ec8 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 51bf7c9a..abcc9f85 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 0c150814..b2b40f10 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,9 @@ 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::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"), ("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 c0fc289a..fa418add 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()); + 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()); + 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()); + 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()); + 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 new file mode 100644 index 00000000..234d43e5 --- /dev/null +++ b/services/worker/src/passes/incidents/xt_contract_change_reaches_every_consumer.rs @@ -0,0 +1,567 @@ +//! 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() +} + +/// 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, listing(&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, listing(&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, run_id)") + .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()")); + // 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)")); + // 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, + "run-1", + &[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); +} + +/// 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."); +} + +/// 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/mod.rs b/services/worker/src/passes/mod.rs index cf69cfb3..efb87db8 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 79192e1a..3cf7faa2 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 3c79d986..5a643b43 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, 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/review_pr.rs b/services/worker/src/passes/review_pr.rs index 10fae1e4..c528a379 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 b8ecc095..069c579b 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 00000000..3b7d2004 --- /dev/null +++ b/services/worker/src/passes/xrepo.rs @@ -0,0 +1,588 @@ +//! 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, + /// 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. + run: String, +} + +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, + run: &str, + ) -> 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(); + // 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); + let mut queued = 0; + for r in xc::backfill(&known, &repos, BACKFILL_PER_STEP * 4) { + if queued >= BACKFILL_PER_STEP { + break; + } + if super::code_graph::queue_contract_read(state, team_id, &r, installation_id).await { + queued += 1; + } + } + let index = index?; + // 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, vis, installation_id); + c.run = run.to_string(); + Some(c) + } + + /// Over an index already read (tests; callers that hold one). + pub fn of( + index: Arc, + repo: &str, + vis: crate::agent::reach::Visibility, + installation: u64, + ) -> RunContracts { + RunContracts { + repo: repo.to_string(), + index, + vis, + installation, + run: String::new(), + } + } + + /// Whether the work's repository is public. + pub fn public_target(&self) -> bool { + self.vis.target_public(&self.repo) + } + + fn private(&self, repo: &str) -> bool { + self.vis.source_private(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, &self.run, &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); + 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) { + 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(); + tracing::debug!(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, + 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, run_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(), + } +}