diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 49a36c31d..02f3f7f03 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3779,6 +3779,17 @@ "null" ] }, + "exploration": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunExploration", + "description": "What the run explored: the repository's code map brought to the base\nbefore planning, and the build's tool calls before its first write.\nAbsent for a run that neither planned nor built." + } + ] + }, "files_modified": { "description": "The files the run changed.", "examples": [ @@ -4162,6 +4173,17 @@ } ] }, + "traceability": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunTrace", + "description": "Each acceptance criterion of the ticket (or of the plan's criteria\nmap) traced to the files and definitions changed for it, the tests\nthat cover it, and what proves it on the pull request's head. A row\nwhose proof isn't `proven`, or with no code or no tests, is an open\ngap. Absent until the run's pull request has a description built for\nits head." + } + ] + }, "trigger": { "$ref": "#/components/schemas/RunTrigger", "description": "How the run was started and by whom (as in the runs list)." @@ -4437,6 +4459,103 @@ ], "type": "object" }, + "RunCodeMapRefresh": { + "description": "What bringing the code map to the base did (`common::code_map`).", + "properties": { + "commit": { + "description": "The commit the map describes now.", + "examples": [ + "c0ffee1234567890c0ffee1234567890c0ffee12" + ], + "type": "string" + }, + "missed": { + "description": "Sections to rebuild that the model left out: the next run rebuilds\nthem.", + "examples": [ + [] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "rebuilt": { + "description": "Sections written again from the base.", + "examples": [ + [ + "build" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "reused": { + "description": "Sections kept as they were.", + "examples": [ + [ + "architecture", + "stack", + "area:apps" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "why": { + "description": "`new`, `current`, `changed` or `unknown changes`.", + "examples": [ + "changed" + ], + "type": "string" + } + }, + "required": [ + "commit", + "why" + ], + "type": "object" + }, + "RunCoderExploration": { + "description": "The build's tool calls before its first write, and the map it had.", + "properties": { + "calls_before_first_write": { + "description": "Tool calls before the first file was written; absent when it wrote\nnone.", + "examples": [ + 4 + ], + "format": "int32", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "map_commit": { + "description": "The code map's commit the build started from; absent when it had\nnone.", + "examples": [ + "c0ffee1234567890c0ffee1234567890c0ffee12" + ], + "type": [ + "string", + "null" + ] + }, + "tool_calls": { + "description": "All the build's tool calls.", + "examples": [ + 31 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, "RunCoveredBy": { "description": "The open pull request that already does a run's work.", "properties": { @@ -4673,6 +4792,34 @@ ], "type": "object" }, + "RunExploration": { + "description": "What a run explored, and what it started from.", + "properties": { + "code_map": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunCodeMapRefresh", + "description": "The repository's code map, brought to the run's base before\nplanning; absent when the run didn't plan." + } + ] + }, + "coder": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunCoderExploration", + "description": "The build's exploration; absent before it built." + } + ] + } + }, + "type": "object" + }, "RunMergeStanding": { "description": "Where a run's pull request stands on its way to merge.", "properties": { @@ -5307,6 +5454,143 @@ ], "type": "object" }, + "RunTrace": { + "description": "Each acceptance criterion traced to the code, tests and proof of one\nhead (`common::trace`).", + "properties": { + "head": { + "description": "The pull request's head the trace is of.", + "examples": [ + "c0ffee1234567890c0ffee1234567890c0ffee12" + ], + "type": "string" + }, + "rows": { + "description": "One row per criterion.", + "items": { + "$ref": "#/components/schemas/RunTraceRow" + }, + "type": "array" + } + }, + "required": [ + "head", + "rows" + ], + "type": "object" + }, + "RunTraceCode": { + "description": "A changed file traced to a criterion.", + "properties": { + "path": { + "description": "The file's path in the repository.", + "examples": [ + "src/utils/filters.ts" + ], + "type": "string" + }, + "symbols": { + "description": "Functions, types and constants it adds or changes.", + "examples": [ + [ + "dedupeBySlug" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "path" + ], + "type": "object" + }, + "RunTraceProof": { + "description": "What proves a criterion on the head.", + "properties": { + "by": { + "description": "What ran: `end to end on staging and the preview` or `tests with and\nwithout the change`; empty when nothing did.", + "examples": [ + "end to end on staging and the preview" + ], + "type": "string" + }, + "detail": { + "description": "What the run showed.", + "examples": [ + "fails on staging (1 failed) and passes on the preview (1 passed)" + ], + "type": "string" + }, + "state": { + "description": "`proven`, `not_the_ticket` (passes without the change), `failing`,\n`missing` (no test), `unverified` (a side couldn't run) or `not_run`.", + "examples": [ + "proven" + ], + "type": "string" + } + }, + "required": [ + "state" + ], + "type": "object" + }, + "RunTraceRow": { + "description": "One criterion's row of the trace.", + "properties": { + "code": { + "description": "The changed files traced to it, each with the definitions it adds\nor changes there.", + "items": { + "$ref": "#/components/schemas/RunTraceCode" + }, + "type": "array" + }, + "criterion": { + "description": "The criterion, as written.", + "examples": [ + "Only one sport filter chip shows on /camps" + ], + "type": "string" + }, + "page": { + "description": "The site path it is about, when it names one.", + "examples": [ + "/camps" + ], + "type": "string" + }, + "proof": { + "$ref": "#/components/schemas/RunTraceProof", + "description": "What proves it on the head." + }, + "source": { + "description": "Where it was written: `ticket` or `plan` (the plan's criteria map).", + "examples": [ + "ticket" + ], + "type": "string" + }, + "tests": { + "description": "The tests that cover it (`file` or `file › title`).", + "examples": [ + [ + "e2e/camps.spec.ts › shows one chip" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "criterion", + "source", + "proof" + ], + "type": "object" + }, "RunTrigger": { "description": "How a run was started, in words, with a link to what started it.", "properties": { diff --git a/docs/code-map.md b/docs/code-map.md new file mode 100644 index 000000000..77b653e59 --- /dev/null +++ b/docs/code-map.md @@ -0,0 +1,80 @@ +# The code map + +What CoderHelm knows about each repository's code, kept current with its +default branch, so the planner and the coder start from it instead of +exploring the layout again on every run. + +Code: `services/common/src/code_map.rs` (the rules, pure) and +`services/worker/src/passes/code_map.rs` (reading, writing, recording). + +## What it holds + +The map is kept on the repository's agent file record (settings table, +`sk = AGENTS#REPO#`, attribute `code_map`), beside the agent +file. It is made of sections: + +| Section | What it says | Read from | +| --- | --- | --- | +| `architecture` | What the repository is for, its main parts, how requests and jobs flow, where each part is deployed | README, agent guidance, infrastructure roots | +| `stack` | Languages, frameworks, runtimes and the versions the manifests pin | Top-level manifests and toolchain files | +| `build` | Install, build, type-check, lint, test (each suite) and run commands, and what CI runs | CI workflows, manifests, test and lint config | +| `conventions` | Style, lint and format rules, naming, error handling, logging, test layout, guidance and the pull request template | Agent guidance, tooling config, the template | +| `dependencies` | Which packages, services and infrastructure depend on which | Every package manifest up to two levels deep, compose files | +| `area:` | One per top-level folder (at most 12): what it holds, its packages and entry points by path, where each concern lives | The folder's listing, its manifests and entry points | + +Each section is stamped with the commit it describes. The map is stamped +with the commit and the tree it was last brought to. + +## Kept current, section by section + +Before the planner starts, the map is brought to the run's base: + +1. **Same commit, or same tree.** Every section is reused. No tree is read and + no model is called. +2. **Otherwise** GitHub's comparison from the map's commit to the base gives + the changed paths, and each path marks the sections it touches: + - a top-level manifest touches `stack`, `build` and `dependencies`; + - a package manifest deeper in the tree touches `stack`, `dependencies` + and its area; + - CI touches `build`; + - lint and format config touch `conventions` and `build`; + - guidance and the pull request template touch `conventions`; + - the README touches `architecture`; + - infrastructure (Terraform, CDK, CloudFormation, Kubernetes, compose) + touches `architecture` and `dependencies`; + - a file added, removed or renamed in an area, or an entry point + (`main`, `index`, `lib`, `app`, `server`, `handler`, route tables) + changed there, touches that area; + - an area added or gone touches `architecture`. + + A plain edit inside a source file touches nothing: the map describes + structure, not every line. +3. **A comparison that can't be read, or that GitHub cut** (300 files or + more), rebuilds every section. + +Only the touched sections are read again (their own files, at most ten each) +and written, all in one model call. The rest are kept. A section the reply +left out keeps its older stamp. The map tells the agents it may be out of +date, and the next run rebuilds it. + +## Who reads it + +- **The planner** gets the map in its system prompt, after the repository's + instruction files. +- **The coder** gets the stored map in every round's system prompt. The coder + reads the map without refreshing it, so its prompt stays the same across a + run's rounds. + +## What it saves, on the run + +Two run attributes, served by `GET /api/runs/{run_id}` under `exploration`: + +- `code_map_refresh` (`exploration.code_map`): the commit the map was + brought to, why (`new`, `current`, `changed`, `unknown changes`), and the + sections reused, rebuilt and missed. +- `exploration` (`exploration.coder`): the build's tool calls before its + first write (`calls_before_first_write`), all its tool calls, and the + map's commit when it started from one (`map_commit`). Comparing runs with + 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`. diff --git a/docs/criteria-trace.md b/docs/criteria-trace.md new file mode 100644 index 000000000..22247e138 --- /dev/null +++ b/docs/criteria-trace.md @@ -0,0 +1,85 @@ +# Criteria traced to code, tests and proof + +For each run, every acceptance criterion is linked to the code changed for +it, the tests that cover it, and what proves it on the pull request's head. +The link is a record on the run, a table in the description, and open items +for whatever is missing. + +Code: `services/common/src/trace.rs` (pure). The description builds the +trace (`services/worker/src/passes/description.rs`), and the run API serves +it. + +## The criteria + +The criteria are the ticket's acceptance list, else its Expected lines, +else the plan's `## Criteria map` (`common::e2e_proof::criteria_or_map`), +the same list the two-way proof uses. Each row records whether it came from +the `ticket` or the `plan`. + +A criteria map line can name the code it is built in: + +``` +- | page: | e2e: › | asserts: <what a person sees> | code: <files or functions> +``` + +## Each row + +| Column | How it is read | +| --- | --- | +| Code | The diff's non-test files that the map line's `code:` names, by path or by a definition in their patch. Without `code:`, it is the files whose path, added definitions or added lines share at least two of the criterion's words (or one in the path or definitions). A ticket with one criterion owns the whole change. Each file carries the definitions it adds or changes (`fn`, `function`, `class`, `def`, `func`, and so on). | +| Tests | The map line's end-to-end test, plus the diff's test files whose path or test titles share the criterion's words. A spec that the map gives to another criterion is never taken by words alone. | +| Proof | The criterion's two-way proof on this head (staging and the preview, with the server HTML check from `e2e_proof`). Without one, its tests' runs with and without the change (the tests and scope check). Otherwise not run yet, or no test. | + +A proof is one of `proven`, `not_the_ticket` (passes without the change), +`failing`, `missing`, `unverified` or `not_run`. + +## Gaps + +A criterion is an open gap when no change in the diff is traced to it, no +test on the head covers it, or its proof doesn't hold. Each gap is listed +in the description's open items with what is missing. + +The gaps are also work for the coder (`common::trace::coder_items`), fed +into the same loop as the run's other open gaps: + +- Each build of the description records them on the run's checks ledger + (`run_guard::Ledger::trace`, for the head it was built for). There they + are open items like any check's: they hold the draft (`open_findings`) + and the run converges on them (`run_guard::Target`). +- When the two-way proof runs on a fresh head (`pr_watch`), the + description is built first, then the proof's items and the trace's go + back to the coder together, in one fix round + (`resume::queue_own_review_round`). +- For a pull request with no preview, where no two-way proof runs, the + description build sends the trace's items itself. +- A criterion whose two-way proof already sends an item (a test missing, + failing on the preview, or passing on staging too) is sent once, by the + proof. The trace adds an item for it only when no changed code is traced + to it. + +## Where it shows + +- **Pull request description:** a compact table, `Acceptance criteria, + traced`, in the "Full test evidence" fold. It is rebuilt from the facts of + the head on every push, like the rest of the description. +- **Run record:** attribute `traceability` (JSON), written on every build of + the description. +- **Run API:** `GET /api/runs/{run_id}` returns `traceability`: + +```json +{ + "head": "c0ffee1…", + "rows": [ + { + "criterion": "Only one sport filter chip shows on /camps", + "source": "ticket", + "page": "/camps", + "code": [{ "path": "src/utils/filters.ts", "symbols": ["dedupeSportsBySlug"] }], + "tests": ["e2e/camps.spec.ts › shows one chip"], + "proof": { "state": "proven", "by": "end to end on staging and the preview", "detail": "…" } + } + ] +} +``` + +The replay case is `services/worker/src/passes/incidents/dh_criteria_traced_to_proof.rs`. diff --git a/docs/incidents/dg_code_map_kept_current.md b/docs/incidents/dg_code_map_kept_current.md new file mode 100644 index 000000000..93663be67 --- /dev/null +++ b/docs/incidents/dg_code_map_kept_current.md @@ -0,0 +1,5 @@ +# dg. `dg_code_map_kept_current` + +**What happened:** Every run rediscovered the repository. The planner listed the tree and read the README, the manifests and CI to learn the stack and the test commands, and then the coder did the same again before its first edit. The repository's agent file was written once at install, and again only when a top-level config file changed. Neither agent was given it, so each run paid for the same layout twice and nothing recorded how much. + +**The guarantee:** Each repository keeps a code map on its agent file record (`common::code_map`). The map has sections for architecture, stack and versions, build and test commands, conventions, dependencies between packages, and one section per top-level area, each stamped with the commit it describes. Before the planner starts, the map is brought to the run's base (`passes::code_map::refresh`). If the commit or tree is unchanged, every section is reused. Otherwise only the sections that the comparison's paths touch are read again and rebuilt, in one model call. A section the reply left out keeps its older stamp, is marked as possibly out of date, and is rebuilt on the next run. The planner and the coder both get the map as context, and the build's tool calls before its first write are kept on the run with the map's commit (`exploration`). diff --git a/docs/incidents/dh_criteria_traced_to_proof.md b/docs/incidents/dh_criteria_traced_to_proof.md new file mode 100644 index 000000000..e6810f081 --- /dev/null +++ b/docs/incidents/dh_criteria_traced_to_proof.md @@ -0,0 +1,11 @@ +# dh. `dh_criteria_traced_to_proof` + +**What happened:** A ticket had two acceptance criteria: one filter chip per sport on a camps page, and the page view tracked there. The pull request changed the chip code and added an end-to-end spec for the chip, and its two-way proof passed. Its description listed the files and the checks, but nothing tied either one to the criteria. The tracking criterion had changed code and no test, and neither the description, the run page nor the API said so. + +**The guarantee:** Every build of the description traces each criterion (the ticket's, else the plan's criteria map) to three things, all in `common::trace`: + +- the files and definitions changed for it (the map line's `code:`, else matched by its words); +- the tests that cover it; +- its proof on the head: the two-way end-to-end proof with the served-page check, else its tests' runs with and without the change. + +The table sits in the description's checks and is rebuilt from the facts on every push. A criterion with no traced code, no test, or no proof that holds is listed as an open item. The trace is kept on the run (`traceability`) and served by `GET /api/runs/{run_id}`. diff --git a/docs/incidents/di_infra_checklist_answered.md b/docs/incidents/di_infra_checklist_answered.md new file mode 100644 index 000000000..8457354d1 --- /dev/null +++ b/docs/incidents/di_infra_checklist_answered.md @@ -0,0 +1,5 @@ +# di. `di_infra_checklist_answered` + +**What happened:** A ticket asked for a queue between the API and the worker. The plan read the Terraform and added the queue resource and the IAM statement. It left several things unsaid: how the queue rolls out across environments, how it rolls back, what else the worker role serves, what the queue costs and its limits, and which alarm shows it backing up. The change was right, but the reviewer had to ask about each of these, one comment at a time. + +**The guarantee:** When the plan's files or the ticket reach infrastructure, CI, auth and security, data, a hot path or observability, design.md answers that area's checklist under `## Non-functional checks` (`common::nfr_check`). The lists are data in one file, `services/common/src/nfr_checklists.json`. Each answer says where it comes from (a file, a command or a lookup), and an item that doesn't apply says why. Anything missing goes back with the plan's other gaps in the same send-back. It adds no stop and no approval. diff --git a/docs/non-functional-checks.md b/docs/non-functional-checks.md new file mode 100644 index 000000000..1ae60baad --- /dev/null +++ b/docs/non-functional-checks.md @@ -0,0 +1,63 @@ +# Non-functional checks in planning + +Some changes reach infrastructure, CI, auth and security, data, a hot path, +or observability. For those, the plan answers a short checklist for each +area before any code is written. A careful engineer settles these points +before such a change, and a reviewer otherwise has to ask about them one at +a time. + +Code: `services/common/src/nfr_check.rs`. The checklists are data, in one +file: `services/common/src/nfr_checklists.json`. + +## The areas + +| Area | Applies when | Items | +| --- | --- | --- | +| `infrastructure` | Terraform, CDK, CloudFormation, Kubernetes, containers, serverless config | `rollout`, `rollback`, `blast_radius`, `environments`, `permissions`, `cost`, `limits`, `monitoring` | +| `ci` | CI workflows and deploy pipelines | `triggers`, `rollback`, `permissions`, `blast_radius`, `limits` | +| `security` | Authentication, authorization, IAM, WAF, secrets, untrusted input | `threat`, `permissions`, `secrets`, `input`, `compatibility` | +| `data` | Schemas, migrations, stored data | `migration_safety`, `compatibility`, `rollback`, `environments`, `existing_rows` | +| `performance` | Hot paths, queries, caching, anything the ticket calls slow | `hot_path`, `cost_per_call`, `limits`, `measurement` | +| `observability` | Alarms, metrics, dashboards, logs, tracing | `signal`, `thresholds`, `routing`, `noise` | + +An area applies when one of the plan's files matches its `paths`: + +- `ext`: the file's extension; +- `names`: the file name; +- `dirs`: a folder on the path; +- `prefixes`: the path's start; +- `contains`: a word in a path segment. + +It also applies when the ticket names one of the area's `words`. + +To add an area or an item, edit the JSON file: the planner's instructions +and the check both read it. Update the table above to match. + +## What the plan writes + +In design.md: + +``` +## Non-functional checks +### Infrastructure +- rollout: `deploy.yml` applies `infra/` to staging, then prod (source: `.github/workflows/deploy.yml`) +- cost: n/a: inside the free tier at the measured 3k messages a day +``` + +`- <area>.<item>: ...` without a heading works too. + +- Every item of every area that applies has a line. +- An answer comes from the code or a lookup, and says where. That means a + `source:`, a backticked file or command, or the lookup it rests on. +- An item that doesn't apply says `n/a: <why>`, with a reason of at least a + few words. + +## When something is missing + +Each missing section, item, reason or source is a plan gap. It goes back to +the planner with the plan's other gaps, in the same single send-back +(`passes::plan`). The checklist adds no stop, no question to a person and no +approval. A plan whose change reaches none of the areas leaves the section +out. + +The replay case is `services/worker/src/passes/incidents/di_infra_checklist_answered.rs`. diff --git a/services/common/src/code_map.rs b/services/common/src/code_map.rs new file mode 100644 index 000000000..6c75d764f --- /dev/null +++ b/services/common/src/code_map.rs @@ -0,0 +1,1139 @@ +//! A repository's code map: what CoderHelm knows about the code, kept +//! current with the default branch, so the planner and the coder start +//! from it instead of exploring the layout again on every run. +//! +//! It lives on the repository's agent file record (`common::agent_file`, +//! `pk = <team>`, `sk = AGENTS#REPO#<owner/repo>`, attribute [`FIELD`]) and +//! is made of sections, each stamped with the commit it describes: +//! +//! - five sections for the whole repository: its architecture, its stack and +//! versions, how to build, test and run it, its conventions, and the +//! dependencies between its packages and services ([`GLOBAL`]); +//! - one section per top-level area (`services/`, `apps/`, at most +//! [`MAX_AREAS`]): its structure and entry points ([`AREA_PREFIX`]). +//! +//! The map as a whole is stamped with the commit and the tree it was last +//! brought to. On every run the base is compared with the stamp +//! ([`plan_refresh`]): +//! +//! - the same commit, or the same tree (byte-identical files): every section +//! is reused; +//! - otherwise the comparison's changed paths decide ([`sections_touched`]): +//! a manifest changes the stack, build and dependency sections; CI the +//! build section; lint and format config the conventions; a file added, +//! removed or renamed in an area, or an entry point or package manifest +//! changed in it, that area's section; an area added or gone, the +//! architecture. A plain edit inside a source file changes no section; +//! - a comparison that could not be read, or was cut by GitHub, rebuilds +//! every section. +//! +//! Only the sections to rebuild are read again (their own files, +//! [`inputs_for`]) and written in one model call ([`prompt`], +//! [`parse_reply`]); the rest are reused as they are. A section the reply +//! left out keeps its older stamp and is rebuilt on the next run. +//! +//! What a run saves is recorded on it ([`Exploration`]): the coder's tool +//! calls before its first write, and whether it started from a map. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::agent_file::{self, Kind}; + +/// The agent file record's attribute that holds the map, as JSON. +pub const FIELD: &str = "code_map"; +/// The run record's attribute for what the planner's refresh did. +pub const REFRESH_FIELD: &str = "code_map_refresh"; +/// The run record's attribute for the coder's exploration. +pub const EXPLORATION_FIELD: &str = "exploration"; + +/// Top-level areas with a section of their own; the rest are named in the +/// architecture section. +pub const MAX_AREAS: usize = 12; +/// Files read for one section. +pub const MAX_INPUT_FILES: usize = 10; +/// Characters of one file read for a section. +pub const MAX_FILE_CHARS: usize = 4_000; +/// Paths listed for one area. +pub const MAX_LISTING: usize = 100; +/// Characters of file content in one request, across every section: a +/// first build of a large repository reads less of each file. +pub const MAX_PROMPT_FILE_CHARS: usize = 150_000; +/// Characters of the map given to an agent. +pub const MAX_RENDER_CHARS: usize = 24_000; +/// Files GitHub lists for one comparison at most: a list this long may be +/// cut, so it is not trusted. +pub const COMPARE_FILE_LIMIT: usize = 300; + +/// The id prefix of an area's section (`area:services`). +pub const AREA_PREFIX: &str = "area:"; + +/// The whole-repository sections: id, title, what it says. +pub const GLOBAL: &[(&str, &str, &str)] = &[ + ( + "architecture", + "Architecture", + "what the repository is for, its main parts and how a request or job flows through them, and where each part is deployed", + ), + ( + "stack", + "Tech stack and versions", + "languages, frameworks, runtimes and the versions the manifests and toolchain files pin", + ), + ( + "build", + "Build, test and run", + "the exact commands to install, build, type-check, lint, test (each suite: unit, integration, end-to-end) and run locally, and what CI runs", + ), + ( + "conventions", + "Conventions", + "code style, lint and format rules, naming, error handling and logging patterns, test layout, and what the repository's guidance and pull request template ask", + ), + ( + "dependencies", + "Dependencies between packages and services", + "which packages, services and infrastructure depend on which, shared libraries, and what changes together", + ), +]; + +pub fn area_id(dir: &str) -> String { + format!("{AREA_PREFIX}{dir}") +} + +/// One section of the map. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Section { + pub id: String, + pub text: String, + /// The commit this section describes. + pub commit: String, +} + +/// A repository's code map. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct CodeMap { + /// The commit the map was last brought to. + pub commit: String, + /// That commit's tree. + #[serde(default)] + pub tree: String, + pub sections: Vec<Section>, + /// When it was last written (RFC 3339). + #[serde(default)] + pub updated_at: String, +} + +impl CodeMap { + pub fn section(&self, id: &str) -> Option<&Section> { + self.sections.iter().find(|s| s.id == id) + } + + /// The areas it has a section for. + pub fn areas(&self) -> Vec<String> { + self.sections + .iter() + .filter_map(|s| s.id.strip_prefix(AREA_PREFIX).map(str::to_string)) + .collect() + } + + /// Sections still describing an older commit than the map's. + pub fn behind(&self) -> Vec<String> { + self.sections + .iter() + .filter(|s| s.commit != self.commit) + .map(|s| s.id.clone()) + .collect() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option<Self> { + serde_json::from_str(s).ok() + } +} + +// ── What a change touches ────────────────────────────────────────────────── + +/// One file of a comparison. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Changed { + pub path: String, + /// `added`, `removed`, `modified`, `renamed`, `copied` or `changed`. + pub status: String, + /// A renamed file's old path. + pub previous: Option<String>, +} + +impl Changed { + pub fn new(path: &str, status: &str) -> Self { + Self { + path: path.to_string(), + status: status.to_string(), + previous: None, + } + } + + fn structural(&self) -> bool { + matches!( + self.status.as_str(), + "added" | "removed" | "renamed" | "copied" + ) + } +} + +/// The files a GitHub comparison (`compare/base...head`) lists. `None` when +/// the list may be cut (GitHub lists at most [`COMPARE_FILE_LIMIT`]): the +/// caller then rebuilds every section. +pub fn changed_from_compare(v: &Value) -> Option<Vec<Changed>> { + let files = v.get("files")?.as_array()?; + if files.len() >= COMPARE_FILE_LIMIT { + return None; + } + Some( + files + .iter() + .filter_map(|f| { + let path = f.get("filename")?.as_str()?; + Some(Changed { + path: path.to_string(), + status: f + .get("status") + .and_then(|s| s.as_str()) + .unwrap_or("modified") + .to_string(), + previous: f + .get("previous_filename") + .and_then(|s| s.as_str()) + .map(str::to_string), + }) + }) + .collect(), + ) +} + +fn name_of(path: &str) -> String { + path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase() +} + +/// Package manifests, wherever they are (a monorepo keeps one per package). +const PACKAGE_MANIFESTS: &[&str] = &[ + "package.json", + "cargo.toml", + "go.mod", + "pyproject.toml", + "requirements.txt", + "setup.py", + "pom.xml", + "build.gradle", + "build.gradle.kts", + "gemfile", + "composer.json", + "mix.exs", + "pubspec.yaml", + "package.swift", + "deno.json", +]; + +/// Whether `path` is a package manifest. +pub fn is_package_manifest(path: &str) -> bool { + PACKAGE_MANIFESTS.contains(&name_of(path).as_str()) +} + +const ENTRY_STEMS: &[&str] = &[ + "main", "index", "app", "lib", "server", "handler", "cli", "__main__", "manage", "program", + "routes", "router", "urls", "wsgi", "asgi", +]; + +const CODE_EXTS: &[&str] = &[ + "rs", "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "go", "rb", "java", "kt", "cs", "php", + "swift", "ex", "exs", "dart", "scala", +]; + +/// Whether `path` is an entry point: a `main`, `index`, `lib`, `app`, +/// `server`, `handler` or route table source file. +pub fn is_entry_point(path: &str) -> bool { + let name = name_of(path); + let Some((stem, ext)) = name.rsplit_once('.') else { + return false; + }; + CODE_EXTS.contains(&ext) && ENTRY_STEMS.contains(&stem) +} + +/// Whether `path` describes infrastructure or how services are wired +/// (Terraform, CDK, CloudFormation, Kubernetes, compose files). +pub fn is_infra(path: &str) -> bool { + let low = path.to_ascii_lowercase(); + let name = name_of(path); + low.ends_with(".tf") + || low.ends_with(".tfvars") + || name == "cdk.json" + || name.starts_with("docker-compose") + || name.starts_with("compose.") + || name == "serverless.yml" + || name == "template.yaml" + || name == "template.yml" + || name == "chart.yaml" + || low.split('/').any(|s| { + matches!( + s, + "k8s" | "kubernetes" | "helm" | "charts" | "terraform" | "cloudformation" + ) + }) +} + +/// The top-level areas of a tree that get a section: folders that hold +/// files, not hidden ones, the largest [`MAX_AREAS`], by name. +pub fn areas_of<S: AsRef<str>>(paths: &[S]) -> Vec<String> { + let mut counts: BTreeMap<String, usize> = BTreeMap::new(); + for p in paths { + if let Some(d) = agent_file::top_dir(p.as_ref()) { + if !d.starts_with('.') { + *counts.entry(d.to_string()).or_default() += 1; + } + } + } + let mut by_size: Vec<(String, usize)> = counts.into_iter().collect(); + by_size.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0))); + by_size.truncate(MAX_AREAS); + let mut out: Vec<String> = by_size.into_iter().map(|(d, _)| d).collect(); + out.sort(); + out +} + +/// The sections a changed file makes stale. A plain edit inside a source +/// file touches none: the map describes structure, not every line. +pub fn sections_touched(c: &Changed, areas: &[String]) -> BTreeSet<String> { + let mut out = BTreeSet::new(); + let paths: Vec<&str> = std::iter::once(c.path.as_str()) + .chain(c.previous.as_deref()) + .collect(); + for path in paths { + match agent_file::kind_of(path) { + Some(Kind::Guidance) | Some(Kind::PrTemplate) => { + out.insert("conventions".to_string()); + } + Some(Kind::Readme) => { + out.insert("architecture".to_string()); + } + Some(Kind::Manifest) => { + for s in ["stack", "build", "dependencies"] { + out.insert(s.to_string()); + } + } + Some(Kind::Ci) => { + out.insert("build".to_string()); + } + Some(Kind::Tooling) => { + out.insert("conventions".to_string()); + out.insert("build".to_string()); + } + None => {} + } + let nested_manifest = path.contains('/') && is_package_manifest(path); + if nested_manifest { + out.insert("stack".to_string()); + out.insert("dependencies".to_string()); + } + if is_infra(path) { + out.insert("architecture".to_string()); + out.insert("dependencies".to_string()); + } + if let Some(dir) = agent_file::top_dir(path) { + let structural = c.structural() || is_entry_point(path) || nested_manifest; + if structural && areas.iter().any(|a| a == dir) { + out.insert(area_id(dir)); + } + } + } + out +} + +/// What a run does to the map before it starts. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Refresh { + /// Sections written again from the repository at the base. + pub rebuild: Vec<String>, + /// Sections kept as they are. + pub reuse: Vec<String>, + /// Sections of areas that are gone. + pub drop: Vec<String>, + /// Why, in a few words: `new`, `current`, `changed`, `unknown changes`. + pub why: String, +} + +impl Refresh { + pub fn is_noop(&self) -> bool { + self.rebuild.is_empty() && self.drop.is_empty() + } +} + +fn wanted(areas: &[String]) -> Vec<String> { + GLOBAL + .iter() + .map(|(id, _, _)| id.to_string()) + .chain(areas.iter().map(|a| area_id(a))) + .collect() +} + +/// What to rebuild for a run whose base is `base` (tree `tree`), with the +/// areas the base has (`areas_now`) and the comparison's files since the +/// map's stamp (`changes`, `None` when it could not be read). Pure. +pub fn plan_refresh( + map: Option<&CodeMap>, + base: &str, + tree: &str, + areas_now: &[String], + changes: Option<&[Changed]>, +) -> Refresh { + let want = wanted(areas_now); + let Some(map) = map.filter(|m| !m.sections.is_empty()) else { + return Refresh { + rebuild: want, + why: "new".into(), + ..Default::default() + }; + }; + let have: BTreeSet<&str> = map.sections.iter().map(|s| s.id.as_str()).collect(); + let drop: Vec<String> = map + .sections + .iter() + .filter(|s| !want.contains(&s.id)) + .map(|s| s.id.clone()) + .collect(); + let behind: BTreeSet<String> = map.behind().into_iter().collect(); + let same = map.commit == base || (!tree.is_empty() && map.tree == tree); + let mut rebuild: BTreeSet<String> = want + .iter() + .filter(|id| !have.contains(id.as_str()) || behind.contains(*id)) + .cloned() + .collect(); + let why = if same { + "current" + } else { + match changes { + None => { + rebuild.extend(want.iter().cloned()); + "unknown changes" + } + Some(changes) => { + for c in changes { + rebuild.extend(sections_touched(c, areas_now)); + } + let before: BTreeSet<String> = map.areas().into_iter().collect(); + let now: BTreeSet<String> = areas_now.iter().cloned().collect(); + if before != now { + rebuild.insert("architecture".to_string()); + } + "changed" + } + } + }; + let rebuild: Vec<String> = want + .iter() + .filter(|id| rebuild.contains(*id)) + .cloned() + .collect(); + let reuse = want + .iter() + .filter(|id| have.contains(id.as_str()) && !rebuild.contains(id)) + .cloned() + .collect(); + Refresh { + rebuild, + reuse, + drop, + why: why.to_string(), + } +} + +// ── Reading a section's sources ──────────────────────────────────────────── + +/// The files read to write section `id`, from the tree's file paths: its +/// own sources only, at most [`MAX_INPUT_FILES`]. +pub fn inputs_for<S: AsRef<str>>(id: &str, paths: &[S]) -> Vec<String> { + let paths: Vec<&str> = paths.iter().map(|p| p.as_ref()).collect(); + let kinds = |want: &[Kind]| -> Vec<String> { + agent_file::files_to_read(&paths) + .into_iter() + .filter(|p| agent_file::kind_of(p).is_some_and(|k| want.contains(&k))) + .collect() + }; + let mut out: Vec<String> = match id { + "architecture" => { + let mut v = kinds(&[Kind::Readme, Kind::Guidance]); + v.extend( + paths + .iter() + .filter(|p| is_infra(p) && p.matches('/').count() <= 1) + .map(|p| p.to_string()), + ); + v + } + "stack" => kinds(&[Kind::Manifest]), + "build" => kinds(&[Kind::Ci, Kind::Manifest, Kind::Tooling]), + "conventions" => kinds(&[Kind::Guidance, Kind::Tooling, Kind::PrTemplate]), + "dependencies" => { + let mut v: Vec<String> = paths + .iter() + .filter(|p| is_package_manifest(p) && p.matches('/').count() <= 2) + .map(|p| p.to_string()) + .collect(); + v.sort_by_key(|p| (p.matches('/').count(), p.clone())); + v.extend( + paths + .iter() + .filter(|p| is_infra(p) && name_of(p).contains("compose")) + .map(|p| p.to_string()), + ); + v + } + _ => match id.strip_prefix(AREA_PREFIX) { + Some(dir) => { + let prefix = format!("{dir}/"); + let mut v: Vec<String> = paths + .iter() + .filter(|p| p.starts_with(&prefix)) + .filter(|p| is_package_manifest(p) || is_entry_point(p)) + .map(|p| p.to_string()) + .collect(); + // Shallow first: a package's manifest and entry before deep ones. + v.sort_by_key(|p| (p.matches('/').count(), !is_package_manifest(p), p.clone())); + v + } + None => Vec::new(), + }, + }; + let mut seen = BTreeSet::new(); + out.retain(|p| seen.insert(p.clone())); + out.truncate(MAX_INPUT_FILES); + out +} + +/// The part of the tree a section is written from: for an area, its paths +/// (at most [`MAX_LISTING`]); for the rest, the top two levels of folders +/// with their file counts. +pub fn listing_for<S: AsRef<str>>(id: &str, paths: &[S]) -> String { + if let Some(dir) = id.strip_prefix(AREA_PREFIX) { + let prefix = format!("{dir}/"); + let under: Vec<&str> = paths + .iter() + .map(|p| p.as_ref()) + .filter(|p| p.starts_with(&prefix)) + .collect(); + let mut out: Vec<String> = under + .iter() + .take(MAX_LISTING) + .map(|p| p.to_string()) + .collect(); + if under.len() > MAX_LISTING { + out.push(format!("... and {} more files", under.len() - MAX_LISTING)); + } + return out.join("\n"); + } + let mut counts: BTreeMap<String, usize> = BTreeMap::new(); + let mut root: Vec<String> = Vec::new(); + for p in paths.iter().map(|p| p.as_ref()) { + let parts: Vec<&str> = p.split('/').collect(); + match parts.len() { + 1 => root.push(p.to_string()), + 2 => *counts.entry(format!("{}/", parts[0])).or_default() += 1, + _ => { + *counts + .entry(format!("{}/{}/", parts[0], parts[1])) + .or_default() += 1 + } + } + } + let mut out: Vec<String> = root; + out.extend(counts.into_iter().map(|(d, n)| format!("{d} ({n} files)"))); + out.truncate(MAX_LISTING * 2); + out.join("\n") +} + +/// One section to write, with what it is written from. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Source { + pub id: String, + pub listing: String, + /// (path, content), each content cut at [`MAX_FILE_CHARS`]. + pub files: Vec<(String, String)>, +} + +fn title_of(id: &str) -> String { + match GLOBAL.iter().find(|(g, _, _)| *g == id) { + Some((_, t, _)) => t.to_string(), + None => format!( + "Area `{}/`: structure and entry points", + id.trim_start_matches(AREA_PREFIX) + ), + } +} + +fn ask_of(id: &str) -> String { + match GLOBAL.iter().find(|(g, _, _)| *g == id) { + Some((_, _, a)) => a.to_string(), + None => "what this folder holds, its packages or modules and their entry points (by path), where its code for each concern lives, and how it is tested".to_string(), + } +} + +/// The model's instructions for writing sections. +pub const SYSTEM: &str = "You write a repository's code map: short, factual sections an engineer \ +reads before changing the code. Write only what the files and listings shown say; name paths, \ +commands and versions exactly as they appear; never guess a command or a version. When the \ +files don't say something, write that it isn't stated. Plain markdown, no code fences around a \ +section, at most about 25 lines per section."; + +/// The one request that writes every section in `sources`. Each section's +/// reply starts with a line `=== <id> ===`. +pub fn prompt(repo: &str, sources: &[Source]) -> String { + let files: usize = sources.iter().map(|s| s.files.len()).sum(); + let per_file = (MAX_PROMPT_FILE_CHARS / files.max(1)).clamp(500, MAX_FILE_CHARS); + let mut out = format!( + "Repository: {repo}\n\nWrite these sections. Start each with its own line `=== <id> ===`, \ + exactly as given, then its text.\n" + ); + for s in sources { + out.push_str(&format!( + "\n## Section `{}`: {}\nWhat it says: {}.\n\nPaths:\n{}\n", + s.id, + title_of(&s.id), + ask_of(&s.id), + s.listing + )); + for (path, content) in &s.files { + out.push_str(&format!( + "\n--- {path} ---\n{}\n", + crate::truncate_str(content, per_file) + )); + } + } + out +} + +/// The sections a reply wrote, among `wanted`: (id, text). A section the +/// reply left out, or left empty, is not in it. +pub fn parse_reply(reply: &str, wanted: &[String]) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = Vec::new(); + let mut cur: Option<(String, Vec<&str>)> = None; + let flush = |cur: &mut Option<(String, Vec<&str>)>, out: &mut Vec<(String, String)>| { + if let Some((id, lines)) = cur.take() { + let text = lines.join("\n").trim().to_string(); + if !text.is_empty() && !out.iter().any(|(i, _)| *i == id) { + out.push((id, text)); + } + } + }; + for line in reply.lines() { + let t = line.trim(); + let marker = t + .strip_prefix("===") + .and_then(|r| r.strip_suffix("===")) + .map(|r| r.trim().trim_matches('`').trim()); + if let Some(id) = marker { + flush(&mut cur, &mut out); + if wanted.iter().any(|w| w == id) { + cur = Some((id.to_string(), Vec::new())); + } + continue; + } + if let Some((_, lines)) = cur.as_mut() { + lines.push(line); + } + } + flush(&mut cur, &mut out); + out +} + +/// The map after a refresh: kept sections as they were, rebuilt ones with +/// the new text stamped `base`, gone areas dropped, in a fixed order. A +/// section that was to be rebuilt and wasn't keeps its older stamp. +pub fn apply( + map: Option<&CodeMap>, + refresh: &Refresh, + built: &[(String, String)], + base: &str, + tree: &str, + now: &str, +) -> CodeMap { + let mut by_id: BTreeMap<String, Section> = map + .map(|m| { + m.sections + .iter() + .filter(|s| !refresh.drop.contains(&s.id)) + .map(|s| (s.id.clone(), s.clone())) + .collect() + }) + .unwrap_or_default(); + for (id, text) in built { + by_id.insert( + id.clone(), + Section { + id: id.clone(), + text: text.clone(), + commit: base.to_string(), + }, + ); + } + // The map is at `base` now: sections the comparison didn't touch + // describe it as well as they did the older commit. + for id in &refresh.reuse { + if let Some(s) = by_id.get_mut(id) { + if !refresh.rebuild.contains(id) { + s.commit = base.to_string(); + } + } + } + let mut sections: Vec<Section> = GLOBAL + .iter() + .filter_map(|(id, _, _)| by_id.remove(*id)) + .collect(); + sections.extend(by_id.into_values()); + CodeMap { + commit: base.to_string(), + tree: tree.to_string(), + sections, + updated_at: now.to_string(), + } +} + +/// The map as an agent reads it, at most [`MAX_RENDER_CHARS`]. Empty for +/// no map. +pub fn render(map: &CodeMap) -> String { + if map.sections.is_empty() { + return String::new(); + } + let short: String = map.commit.chars().take(7).collect(); + let behind = map.behind(); + let mut out = format!( + "\n\n## What CoderHelm already knows about this repository\n\ + The repository's code map, kept current with its default branch at `{short}`. Start \ + from it instead of exploring the layout again: read only the files this change needs, \ + and check a detail in the code before you rely on it." + ); + if !behind.is_empty() { + out.push_str(&format!( + " These sections describe an older commit and may be out of date: {}.", + behind + .iter() + .map(|b| format!("`{b}`")) + .collect::<Vec<_>>() + .join(", ") + )); + } + out.push('\n'); + for s in &map.sections { + let part = format!("\n### {}\n{}\n", title_of(&s.id), s.text.trim()); + if out.len() + part.len() > MAX_RENDER_CHARS { + out.push_str("\n(Further sections left out for length.)\n"); + break; + } + out.push_str(&part); + } + out +} + +// ── What a run saved ─────────────────────────────────────────────────────── + +/// What the planner's refresh did, kept on the run ([`REFRESH_FIELD`]). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct RefreshRecord { + /// The commit the map was brought to. + pub commit: String, + pub why: String, + pub reused: Vec<String>, + pub rebuilt: Vec<String>, + /// Sections to rebuild the reply left out (rebuilt next run). + #[serde(default)] + pub missed: Vec<String>, +} + +/// How much the coder explored before its first write, kept on the run +/// ([`EXPLORATION_FIELD`]): with `map_commit` set it started from the map, +/// so runs with and without one can be compared. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Exploration { + /// Tool calls before the first file was written; `None` when it wrote + /// nothing. + pub calls_before_first_write: Option<u32>, + /// All tool calls of the build. + pub tool_calls: u32, + /// The map's commit the coder was given, when it was given one. + #[serde(default)] + pub map_commit: Option<String>, +} + +/// Counts the coder's tool calls until its first write. Shared by the +/// build's tool executor. +#[derive(Debug, Default)] +pub struct ExploreCounter { + calls: std::sync::atomic::AtomicU32, + first_write: std::sync::Mutex<Option<u32>>, +} + +impl ExploreCounter { + /// A tool call was made. + pub fn call(&self) { + self.calls + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + + /// A write went through: the calls up to it (itself not counted) are + /// the exploration, kept once. + pub fn wrote(&self) { + let n = self.calls.load(std::sync::atomic::Ordering::Relaxed); + let mut fw = self.first_write.lock().unwrap_or_else(|e| e.into_inner()); + if fw.is_none() { + *fw = Some(n.saturating_sub(1)); + } + } + + pub fn exploration(&self, map_commit: Option<String>) -> Exploration { + Exploration { + calls_before_first_write: *self.first_write.lock().unwrap_or_else(|e| e.into_inner()), + tool_calls: self.calls.load(std::sync::atomic::Ordering::Relaxed), + map_commit, + } + } +} + +// ── Storage ──────────────────────────────────────────────────────────────── + +/// The map kept for `repo`, if any. +pub async fn load( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, +) -> Option<CodeMap> { + use aws_sdk_dynamodb::types::AttributeValue as A; + let out = dynamo + .get_item() + .table_name(table) + .key("pk", A::S(team_id.to_string())) + .key("sk", A::S(agent_file::sk(repo))) + .projection_expression("#m") + .expression_attribute_names("#m", FIELD) + .send() + .await + .ok()?; + out.item()? + .get(FIELD) + .and_then(|v| v.as_s().ok()) + .and_then(|s| CodeMap::from_json(s)) +} + +/// Keeps the map on the repository's agent file record (made when there is +/// none: a record without text is never regenerated, `agent_file::due`). +pub async fn save( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + repo: &str, + map: &CodeMap, +) -> Result<(), String> { + use aws_sdk_dynamodb::types::AttributeValue as A; + dynamo + .update_item() + .table_name(table) + .key("pk", A::S(team_id.to_string())) + .key("sk", A::S(agent_file::sk(repo))) + .update_expression("SET #m = :m") + .expression_attribute_names("#m", FIELD) + .expression_attribute_values(":m", A::S(map.to_json())) + .send() + .await + .map(|_| ()) + .map_err(|e| format!("code map write: {e}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tree() -> Vec<String> { + [ + "README.md", + ".github/pull_request_template.md", + "package.json", + "pnpm-workspace.yaml", + ".github/workflows/ci.yml", + "eslint.config.mjs", + "apps/web/package.json", + "apps/web/src/index.tsx", + "apps/web/src/pages/home.tsx", + "apps/web/src/pages/about.tsx", + "apps/studio/package.json", + "apps/studio/src/main.ts", + "services/api/Cargo.toml", + "services/api/src/main.rs", + "services/api/src/routes/users.rs", + "infra/main.tf", + "infra/variables.tf", + ] + .map(String::from) + .to_vec() + } + + fn built_map() -> CodeMap { + let areas = areas_of(&tree()); + let r = plan_refresh(None, "c1", "t1", &areas, None); + let built: Vec<(String, String)> = r + .rebuild + .iter() + .map(|id| (id.clone(), format!("text of {id}"))) + .collect(); + apply(None, &r, &built, "c1", "t1", "2026-11-18T00:00:00Z") + } + + #[test] + fn a_first_run_builds_every_section_stamped_with_its_commit() { + let m = built_map(); + let ids: Vec<&str> = m.sections.iter().map(|s| s.id.as_str()).collect(); + assert_eq!( + ids, + vec![ + "architecture", + "stack", + "build", + "conventions", + "dependencies", + "area:apps", + "area:infra", + "area:services" + ] + ); + assert!(m.sections.iter().all(|s| s.commit == "c1")); + assert_eq!((m.commit.as_str(), m.tree.as_str()), ("c1", "t1")); + assert!(m.behind().is_empty()); + } + + #[test] + fn the_same_commit_or_tree_reuses_every_section() { + let m = built_map(); + let areas = areas_of(&tree()); + let r = plan_refresh(Some(&m), "c1", "t1", &areas, None); + assert!(r.is_noop(), "{r:?}"); + assert_eq!(r.reuse.len(), 8); + // Another commit with byte-identical files (a revert, a merge of + // nothing): the tree says so, no comparison needed. + let r = plan_refresh(Some(&m), "c2", "t1", &areas, None); + assert!(r.is_noop(), "{r:?}"); + assert_eq!(r.why, "current"); + } + + #[test] + fn only_the_sections_a_change_touches_are_rebuilt() { + let m = built_map(); + let areas = areas_of(&tree()); + // Plain edits inside source files: nothing to rebuild. + let edits = vec![ + Changed::new("apps/web/src/pages/home.tsx", "modified"), + Changed::new("services/api/src/routes/users.rs", "modified"), + ]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&edits)); + assert!(r.rebuild.is_empty(), "{r:?}"); + // A new route file in the API and its entry point: that area only. + let api = vec![ + Changed::new("services/api/src/routes/orders.rs", "added"), + Changed::new("services/api/src/main.rs", "modified"), + ]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&api)); + assert_eq!(r.rebuild, vec!["area:services".to_string()]); + assert!(r.reuse.contains(&"area:apps".to_string())); + // A bumped dependency in a package: stack and dependencies, and the + // package's area. + let dep = vec![Changed::new("apps/web/package.json", "modified")]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&dep)); + assert_eq!( + r.rebuild, + vec![ + "stack".to_string(), + "dependencies".to_string(), + "area:apps".to_string() + ] + ); + // CI and lint config. + let ci = vec![ + Changed::new(".github/workflows/ci.yml", "modified"), + Changed::new("eslint.config.mjs", "modified"), + ]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&ci)); + assert_eq!( + r.rebuild, + vec!["build".to_string(), "conventions".to_string()] + ); + // Infrastructure. + let tf = vec![Changed::new("infra/queues.tf", "added")]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&tf)); + assert_eq!( + r.rebuild, + vec![ + "architecture".to_string(), + "dependencies".to_string(), + "area:infra".to_string() + ] + ); + } + + #[test] + fn a_new_area_is_built_and_a_gone_one_dropped() { + let m = built_map(); + let mut paths = tree(); + paths.retain(|p| !p.starts_with("infra/")); + paths.push("e2e/home.spec.ts".into()); + let areas = areas_of(&paths); + let changes = vec![ + Changed::new("infra/main.tf", "removed"), + Changed::new("infra/variables.tf", "removed"), + Changed::new("e2e/home.spec.ts", "added"), + ]; + let r = plan_refresh(Some(&m), "c2", "t2", &areas, Some(&changes)); + assert!(r.rebuild.contains(&"area:e2e".to_string()), "{r:?}"); + assert!(r.rebuild.contains(&"architecture".to_string())); + assert_eq!(r.drop, vec!["area:infra".to_string()]); + let built = vec![ + ("architecture".to_string(), "new arch".to_string()), + ("area:e2e".to_string(), "specs".to_string()), + ("dependencies".to_string(), "deps".to_string()), + ]; + let after = apply(Some(&m), &r, &built, "c2", "t2", "now"); + assert!(after.section("area:infra").is_none()); + assert_eq!(after.section("area:e2e").unwrap().commit, "c2"); + assert_eq!( + after.section("area:apps").unwrap().text, + "text of area:apps" + ); + assert_eq!(after.section("area:apps").unwrap().commit, "c2"); + assert!(after.behind().is_empty()); + } + + #[test] + fn unknown_changes_rebuild_everything_and_a_missed_section_is_retried() { + let m = built_map(); + let areas = areas_of(&tree()); + let r = plan_refresh(Some(&m), "c2", "t2", &areas, None); + assert_eq!(r.rebuild.len(), 8); + assert_eq!(r.why, "unknown changes"); + // The reply wrote only two of them: the rest keep the old stamp and + // the next run rebuilds them even with no change at all. + let built = vec![ + ("architecture".to_string(), "a".to_string()), + ("stack".to_string(), "s".to_string()), + ]; + let after = apply(Some(&m), &r, &built, "c2", "t2", "now"); + assert_eq!(after.behind().len(), 6); + let next = plan_refresh(Some(&after), "c2", "t2", &areas, None); + assert_eq!(next.rebuild.len(), 6, "{next:?}"); + assert!(render(&after).contains("describe an older commit")); + } + + #[test] + fn a_cut_comparison_is_not_trusted() { + let files: Vec<Value> = (0..COMPARE_FILE_LIMIT) + .map(|i| serde_json::json!({"filename": format!("src/f{i}.rs"), "status": "modified"})) + .collect(); + assert!(changed_from_compare(&serde_json::json!({ "files": files })).is_none()); + let small = serde_json::json!({"files": [ + {"filename": "b.rs", "status": "renamed", "previous_filename": "a.rs"} + ]}); + let c = changed_from_compare(&small).unwrap(); + assert_eq!(c[0].previous.as_deref(), Some("a.rs")); + } + + #[test] + fn each_section_reads_its_own_sources() { + let t = tree(); + assert_eq!( + inputs_for("area:services", &t), + vec!["services/api/Cargo.toml", "services/api/src/main.rs"] + ); + assert!(inputs_for("build", &t).contains(&".github/workflows/ci.yml".to_string())); + assert!(inputs_for("conventions", &t).contains(&"eslint.config.mjs".to_string())); + assert!(inputs_for("dependencies", &t).contains(&"apps/web/package.json".to_string())); + assert!(inputs_for("architecture", &t).contains(&"README.md".to_string())); + assert!(listing_for("area:apps", &t).contains("apps/web/src/index.tsx")); + assert!(!listing_for("area:apps", &t).contains("services/")); + } + + #[test] + fn replies_parse_by_marker_and_only_for_wanted_sections() { + let wanted = vec!["stack".to_string(), "area:apps".to_string()]; + let reply = "Here you go.\n=== stack ===\nRust 1.86, Next.js 15.\n\n=== `area:apps` ===\n- `apps/web`: the site\n=== build ===\nnot asked\n=== stack ===\nagain"; + let got = parse_reply(reply, &wanted); + assert_eq!( + got, + vec![ + ("stack".to_string(), "Rust 1.86, Next.js 15.".to_string()), + ( + "area:apps".to_string(), + "- `apps/web`: the site".to_string() + ), + ] + ); + let p = prompt( + "acme/shop", + &[Source { + id: "area:apps".into(), + listing: "apps/web/src/index.tsx".into(), + files: vec![("apps/web/package.json".into(), "{}".into())], + }], + ); + assert!(p.contains("=== <id> ===") && p.contains("--- apps/web/package.json ---")); + } + + #[test] + fn a_large_first_build_stays_within_its_budget() { + let sources: Vec<Source> = (0..17) + .map(|i| Source { + id: format!("area:a{i}"), + listing: String::new(), + files: (0..10) + .map(|j| (format!("a{i}/f{j}.rs"), "x".repeat(10_000))) + .collect(), + }) + .collect(); + let p = prompt("acme/big", &sources); + assert!(p.len() < MAX_PROMPT_FILE_CHARS + 20_000, "{}", p.len()); + } + + #[test] + fn the_counter_keeps_the_calls_before_the_first_write() { + let c = ExploreCounter::default(); + for _ in 0..7 { + c.call(); + } + c.call(); // the write itself + c.wrote(); + c.call(); + c.wrote(); + let e = c.exploration(Some("c1".into())); + assert_eq!(e.calls_before_first_write, Some(7)); + assert_eq!(e.tool_calls, 9); + assert_eq!( + ExploreCounter::default() + .exploration(None) + .calls_before_first_write, + None + ); + } + + #[test] + fn the_rendered_map_is_bounded_and_names_its_commit() { + let m = built_map(); + let r = render(&m); + assert!(r.contains("`c1`") && r.contains("### Tech stack and versions")); + assert!(r.contains("### Area `services/`")); + assert!(render(&CodeMap::default()).is_empty()); + let mut big = m.clone(); + for s in &mut big.sections { + s.text = "x".repeat(6_000); + } + assert!(render(&big).len() <= MAX_RENDER_CHARS + 200); + assert!(CodeMap::from_json(&m.to_json()) == Some(m)); + } +} diff --git a/services/common/src/e2e_proof.rs b/services/common/src/e2e_proof.rs index fe14aa1ba..8ff7c1f22 100644 --- a/services/common/src/e2e_proof.rs +++ b/services/common/src/e2e_proof.rs @@ -46,7 +46,8 @@ pub const PLANNER: &str = "\n\n## The criteria map (CoderHelm checks it)\n\ Start from the ticket's acceptance criteria (or its Expected lines) and plan how each one is \ proven end to end. Write a `## Criteria map` section in design.md with one line per criterion:\n\ `- <the criterion> | page: <the page or URL path it is about> | e2e: <spec path in the \ -end-to-end suite> › <test title> | asserts: <what a person sees there>`\n\ +end-to-end suite> › <test title> | asserts: <what a person sees there> | code: <the files or \ +functions changed for it>`\n\ - A criterion that names a page or something a person sees gets an end-to-end test that loads \ that page and asserts it. Unit tests may go with it but never replace it.\n\ - The test must fail on the base branch's deployment (staging) today, which shows the bug, and \ @@ -371,6 +372,9 @@ pub struct MapLine { /// The reason it has no end-to-end test (`e2e: none: <why>`). pub none: Option<String>, pub asserts: String, + /// The code the criterion is built in, as the plan names it (`code: + /// <paths or symbols>`): what the trace links it to (`common::trace`). + pub code: String, } impl MapLine { @@ -426,6 +430,7 @@ pub fn parse_map(design: &str) -> Vec<MapLine> { } } "asserts" | "assert" | "expect" => m.asserts = v, + "code" | "files" => m.code = v, _ => {} } } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 810f813f7..a7cb8339b 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -6,6 +6,9 @@ pub mod agent_file; /// The agent log of a run: its file format, outcomes, order and redaction /// (worker writes it, gateway serves it). pub mod agent_log; +/// A repository's code map: sections stamped with the commit they describe, +/// rebuilt only where a change touched them, given to the planner and coder. +pub mod code_map; /// Distributed fencing lock for a team+repo memory snapshot. Lives in common /// because BOTH writers must honor it: the worker's run-scoped memory open and /// the gateway's dashboard memory-delete (an unlocked delete raced a concurrent @@ -13,6 +16,11 @@ pub mod agent_log; pub mod memlock; pub mod model_access; pub mod model_ids; +/// Non-functional checklists a plan answers when its change reaches +/// infrastructure, performance, data, security or observability. +pub mod nfr_check; +/// Each acceptance criterion traced to the code, the tests and the proof. +pub mod trace; /// Expiring once-only claims (dedup markers, leases) on the settings table. /// Shared so every claim compares its expiry the same way. diff --git a/services/common/src/nfr_check.rs b/services/common/src/nfr_check.rs new file mode 100644 index 000000000..75076ae2b --- /dev/null +++ b/services/common/src/nfr_check.rs @@ -0,0 +1,463 @@ +//! What a plan settles before code when its change reaches infrastructure, +//! CI, auth and security, data, a hot path or observability. +//! +//! A plan for a change to a Terraform module, a migration or an alarm read +//! the code and planned the edit, and left unsaid what a careful engineer +//! settles first: how it rolls out and back, what else the resource +//! serves, the permissions and cost it adds, the data it meets in each +//! environment. Here those questions are data, one short checklist per +//! area, in one file ([`CHECKLISTS`], `nfr_checklists.json`): +//! +//! - **Which areas apply** ([`areas_for`]): a planned file matches the +//! area's paths (an extension, a file name, a folder, a path prefix, a +//! word in the path), or the ticket names one of its words. +//! - **The plan answers each item** under [`HEADING`] in design.md, one +//! line per item: `- <item>: <answer> (source: <file, command or +//! lookup>)` under a `### <area>` heading, or `- <area>.<item>: ...`. +//! An answer comes from the code or a lookup, so it says where; `n/a: +//! <reason>` says why the item doesn't apply. +//! - **What is unanswered is a plan gap** ([`plan_gaps`]), sent back with +//! the plan's other gaps. It adds no stop and no approval: the plan goes +//! back once like any other gap, and nothing waits on a person. + +use std::collections::BTreeSet; +use std::sync::OnceLock; + +use serde::Deserialize; + +/// The checklists, as data. +pub const CHECKLISTS: &str = include_str!("nfr_checklists.json"); + +/// The design.md section the answers go under. +pub const HEADING: &str = "## Non-functional checks"; + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct Paths { + #[serde(default)] + pub ext: Vec<String>, + #[serde(default)] + pub names: Vec<String>, + #[serde(default)] + pub dirs: Vec<String>, + #[serde(default)] + pub prefixes: Vec<String>, + #[serde(default)] + pub contains: Vec<String>, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct Item { + pub id: String, + pub ask: String, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct Area { + pub id: String, + pub title: String, + pub when: String, + #[serde(default)] + pub paths: Paths, + #[serde(default)] + pub words: Vec<String>, + pub items: Vec<Item>, +} + +#[derive(Debug, Clone, Default, Deserialize)] +struct File { + areas: Vec<Area>, +} + +/// Every area, read once from [`CHECKLISTS`]. +pub fn areas() -> &'static [Area] { + static AREAS: OnceLock<Vec<Area>> = OnceLock::new(); + AREAS.get_or_init(|| { + serde_json::from_str::<File>(CHECKLISTS) + .map(|f| f.areas) + .unwrap_or_default() + }) +} + +impl Area { + /// Whether `path` is one of this area's files. + pub fn matches_path(&self, path: &str) -> bool { + let low = path.trim_start_matches("./").to_ascii_lowercase(); + let name = low.rsplit('/').next().unwrap_or(&low); + let dirs: Vec<&str> = low.split('/').collect(); + let dirs = &dirs[..dirs.len().saturating_sub(1)]; + let p = &self.paths; + p.ext.iter().any(|e| name.ends_with(e.as_str())) + || p.names.iter().any(|n| name == n) + || p.dirs.iter().any(|d| dirs.contains(&d.as_str())) + || p.prefixes.iter().any(|x| low.starts_with(x.as_str())) + || p.contains.iter().any(|c| { + low.split('/') + .any(|seg| seg.contains(c.as_str()) && !seg.contains("author")) + }) + } + + /// Whether `text` (the ticket) names one of this area's words: a + /// phrase anywhere, a single word as a whole word. + pub fn named_in(&self, text: &str) -> bool { + let low = text.to_ascii_lowercase(); + let words: BTreeSet<&str> = low + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '+' || c == '-')) + .filter(|w| !w.is_empty()) + .collect(); + self.words.iter().any(|w| { + if w.contains(' ') { + low.contains(w.as_str()) + } else { + words.contains(w.as_str()) + } + }) + } +} + +/// Why an area applies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Applies { + pub area: String, + /// The planned files that matched, or empty when the ticket's words did. + pub files: Vec<String>, +} + +/// The areas a plan answers for: by its planned files, or by the ticket. +pub fn areas_for<S: AsRef<str>>(files: &[S], ticket: &str) -> Vec<Applies> { + areas() + .iter() + .filter_map(|a| { + let hit: Vec<String> = files + .iter() + .map(|f| f.as_ref()) + .filter(|f| a.matches_path(f)) + .map(str::to_string) + .collect(); + (!hit.is_empty() || a.named_in(ticket)).then(|| Applies { + area: a.id.clone(), + files: hit, + }) + }) + .collect() +} + +fn area(id: &str) -> Option<&'static Area> { + areas().iter().find(|a| a.id == id) +} + +/// One answer line of the plan's section. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Answer { + pub area: String, + pub item: String, + pub text: String, +} + +fn key(s: &str) -> String { + s.trim() + .trim_matches(|c: char| c == '`' || c == '*') + .trim() + .to_ascii_lowercase() + .replace([' ', '-'], "_") +} + +/// The area a `### ` heading names: its id or its title. +fn area_of_heading(h: &str) -> Option<String> { + let k = key(h); + areas() + .iter() + .find(|a| key(&a.id) == k || key(&a.title) == k) + .map(|a| a.id.clone()) +} + +/// The answers under [`HEADING`] in `design`. +pub fn parse(design: &str) -> Option<Vec<Answer>> { + let at = design.find(HEADING)?; + let rest = &design[at + HEADING.len()..]; + let end = rest.find("\n## ").unwrap_or(rest.len()); + let mut out = Vec::new(); + let mut current: Option<String> = None; + for line in rest[..end].lines() { + let t = line.trim(); + if let Some(h) = t.strip_prefix("### ") { + current = area_of_heading(h); + continue; + } + let Some(t) = t.strip_prefix("- ").or_else(|| t.strip_prefix("* ")) else { + continue; + }; + let Some((k, v)) = t.split_once(':') else { + continue; + }; + let k = key(k); + let (a, i) = match k.split_once(['.', '/']) { + Some((a, i)) if area(a).is_some() => (a.to_string(), i.to_string()), + _ => match ¤t { + Some(c) => (c.clone(), k.clone()), + None => continue, + }, + }; + out.push(Answer { + area: a, + item: i, + text: v.trim().to_string(), + }); + } + Some(out) +} + +/// An answer that says the item doesn't apply, and its reason (possibly +/// empty). +fn not_applicable(text: &str) -> Option<&str> { + let low = text.to_ascii_lowercase(); + for p in [ + "n/a", + "na", + "not applicable", + "doesn't apply", + "does not apply", + "none", + ] { + if low == p || low.starts_with(&format!("{p}:")) || low.starts_with(&format!("{p} ")) { + let rest = &text[p.len()..]; + return Some(rest.trim_start_matches([':', ' ', '-', '—', '(']).trim()); + } + } + None +} + +/// Whether an answer says where it comes from: a `source:`, a backticked +/// file or command, or the lookup it rests on. +fn has_source(text: &str) -> bool { + let low = text.to_ascii_lowercase(); + low.contains("source:") + || low.contains("from the lookup") + || low.contains("lookup:") + || text.matches('`').count() >= 2 +} + +/// What the plan leaves unanswered, one line each for its send-back. Empty +/// when no area applies. +pub fn plan_gaps<S: AsRef<str>>(design: &str, files: &[S], ticket: &str) -> Vec<String> { + let applies = areas_for(files, ticket); + if applies.is_empty() { + return Vec::new(); + } + let why = |a: &Applies| { + if a.files.is_empty() { + "the ticket names it".to_string() + } else { + format!( + "the plan changes {}", + a.files + .iter() + .take(3) + .map(|f| format!("`{f}`")) + .collect::<Vec<_>>() + .join(", ") + ) + } + }; + let Some(answers) = parse(design) else { + let list = applies + .iter() + .filter_map(|a| area(&a.area).map(|ar| (a, ar))) + .map(|(a, ar)| { + format!( + "{} ({}): {}", + ar.title, + why(a), + ar.items + .iter() + .map(|i| format!("`{}`", i.id)) + .collect::<Vec<_>>() + .join(", ") + ) + }) + .collect::<Vec<_>>() + .join("; "); + return vec![format!( + "design.md has no `{HEADING}` section, and the change reaches {list}. Under it, write a `### <area>` heading and one line per item: `- <item>: <answer> (source: <file, command or lookup>)`, or `- <item>: n/a: <why it doesn't apply>`. Answer from the code and lookups, not from a person." + )]; + }; + let mut out = Vec::new(); + for a in &applies { + let Some(ar) = area(&a.area) else { continue }; + for item in &ar.items { + let found = answers + .iter() + .find(|x| x.area == ar.id && key(&x.item) == key(&item.id)); + let name = format!("{} `{}`", ar.title, item.id); + match found { + None => out.push(format!( + "`{HEADING}` doesn't answer {name} ({}): {}. Answer it from the code or a lookup, with its source, or say `n/a: <why>`.", + why(a), + item.ask + )), + Some(x) => match not_applicable(&x.text) { + Some(reason) if reason.split_whitespace().count() < 3 => out.push(format!( + "{name} says it doesn't apply without saying why. Give the reason (`n/a: <why>`), or answer it." + )), + Some(_) => {} + None if x.text.split_whitespace().count() < 3 => out.push(format!( + "{name} has no real answer (\"{}\"): {}.", + x.text, item.ask + )), + None if !has_source(&x.text) => out.push(format!( + "{name} doesn't say where its answer comes from. Name the file, command or lookup it rests on (`source: ...`)." + )), + None => {} + }, + } + } + } + out +} + +/// What the planner is told: the rule, and every area's checklist in one +/// line each. +pub fn planner_section() -> String { + let mut out = format!( + "\n\n## Non-functional checks (CoderHelm checks them)\n\ +When the change reaches one of the areas below (by the files it plans, or because the ticket \ +names it), write a `{HEADING}` section in design.md with a `### <area>` heading per area and one \ +line per item: `- <item>: <answer> (source: <file, command or lookup>)`. Answer from the code \ +and from lookups, never from a guess; an item that doesn't apply says `n/a: <why>`. A plan whose \ +change reaches none of them leaves the section out.\n" + ); + for a in areas() { + out.push_str(&format!( + "- {} (`{}`), when {}: {}\n", + a.title, + a.id, + a.when, + a.items + .iter() + .map(|i| format!("`{}` ({})", i.id, i.ask)) + .collect::<Vec<_>>() + .join("; ") + )); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_checklists_load_and_each_area_has_items() { + let ids: Vec<&str> = areas().iter().map(|a| a.id.as_str()).collect(); + assert_eq!( + ids, + vec![ + "infrastructure", + "ci", + "security", + "data", + "performance", + "observability" + ] + ); + for a in areas() { + assert!(a.items.len() >= 4, "{}", a.id); + assert!(!a.when.is_empty() && !a.title.is_empty()); + let ids: BTreeSet<&str> = a.items.iter().map(|i| i.id.as_str()).collect(); + assert_eq!(ids.len(), a.items.len(), "duplicate item in {}", a.id); + } + } + + #[test] + fn areas_apply_by_planned_files_or_the_ticket() { + let got = |files: &[&str], ticket: &str| -> Vec<String> { + areas_for(files, ticket) + .into_iter() + .map(|a| a.area) + .collect() + }; + assert_eq!( + got(&["infra/queues.tf"], "Add a queue"), + vec!["infrastructure"] + ); + assert_eq!( + got(&[".github/workflows/deploy.yml"], "Speed up deploys"), + vec!["ci"] + ); + assert_eq!( + got(&["db/migrations/0042_add_slug.sql"], "Add a slug"), + vec!["data"] + ); + assert_eq!( + got(&["src/auth/session.ts"], "Fix sign out"), + vec!["security"] + ); + assert_eq!( + got(&["ops/alarms/api.ts"], "Page on 5xx"), + vec!["observability"] + ); + assert_eq!( + got(&["src/search.ts"], "Search is slow on large teams"), + vec!["performance"] + ); + assert!(got( + &["src/components/Button.tsx", "docs/authors.md"], + "Fix the label" + ) + .is_empty()); + } + + const DESIGN_OK: &str = "## Approach\nAdd the queue.\n\n## Non-functional checks\n### Infrastructure\n- rollout: applied by the `deploy-staging` then `deploy-prod` workflow (source: `.github/workflows/deploy.yml`)\n- rollback: revert the commit; the queue is empty until the producer ships (source: `infra/queues.tf`)\n- blast_radius: only the new queue; no existing resource changes (source: `terraform plan` in CI)\n- environments: staging and prod both apply `infra/` (source: `infra/envs/`)\n- permissions: the worker role gets `sqs:SendMessage` on this queue only (source: `infra/iam.tf`)\n- cost: n/a: under the free tier at the measured 2k messages a day\n- limits: message size 256 KB; payloads are under 4 KB (source: `src/jobs/payload.ts`)\n- monitoring: the age-of-oldest-message alarm in `infra/alarms.tf` (source: `infra/alarms.tf`)\n"; + + #[test] + fn a_plan_that_answers_every_item_has_no_gaps() { + let gaps = plan_gaps(DESIGN_OK, &["infra/queues.tf"], "Add a queue"); + assert!(gaps.is_empty(), "{gaps:#?}"); + // The `area.item` form reads the same. + let flat = "## Non-functional checks\n- data.migration_safety: 3k rows, no lock (source: lookup: row count)\n- data.compatibility: the column is nullable first (source: `db/migrations/0042.sql`)\n- data.rollback: drop the column (source: `db/migrations/0042.down.sql`)\n- data.environments: staging 1.2k rows, prod 3k (source: lookup: counts per environment)\n- data.existing_rows: n/a: the column is new and stays empty until the next release\n"; + assert!(plan_gaps(flat, &["db/migrations/0042.sql"], "").is_empty()); + } + + #[test] + fn missing_section_items_reasons_and_sources_are_gaps() { + let none = plan_gaps("## Approach\nx\n", &["infra/queues.tf"], "Add a queue"); + assert_eq!(none.len(), 1); + assert!(none[0].contains("`## Non-functional checks`") && none[0].contains("`rollout`")); + let weak = "## Non-functional checks\n### Infrastructure\n- rollout: by the deploy workflow\n- rollback: n/a\n- cost: tbd\n"; + let gaps = plan_gaps(weak, &["infra/queues.tf"], ""); + assert!( + gaps.iter() + .any(|g| g.contains("`rollout`") && g.contains("where its answer comes from")), + "{gaps:#?}" + ); + assert!(gaps + .iter() + .any(|g| g.contains("`rollback`") && g.contains("without saying why"))); + assert!(gaps + .iter() + .any(|g| g.contains("`cost`") && g.contains("no real answer"))); + assert!(gaps + .iter() + .any(|g| g.contains("`monitoring`") && g.contains("doesn't answer"))); + // Five not answered at all, three answered badly. + assert_eq!(gaps.len(), 8, "{gaps:#?}"); + } + + #[test] + fn a_change_outside_every_area_needs_nothing() { + assert!(plan_gaps( + "## Approach\nx", + &["src/components/Card.tsx"], + "Fix the card title" + ) + .is_empty()); + } + + #[test] + fn the_planner_is_told_every_area() { + let s = planner_section(); + for a in areas() { + assert!(s.contains(&format!("(`{}`)", a.id)), "{}", a.id); + } + assert!(s.contains(HEADING)); + } +} diff --git a/services/common/src/nfr_checklists.json b/services/common/src/nfr_checklists.json new file mode 100644 index 000000000..0fc0c513a --- /dev/null +++ b/services/common/src/nfr_checklists.json @@ -0,0 +1,125 @@ +{ + "areas": [ + { + "id": "infrastructure", + "title": "Infrastructure", + "when": "the change touches Terraform, CDK, CloudFormation, Kubernetes, containers or serverless config", + "paths": { + "ext": [".tf", ".tfvars"], + "names": ["cdk.json", "serverless.yml", "serverless.yaml", "template.yaml", "template.yml", "dockerfile", "chart.yaml", "values.yaml", "kustomization.yaml"], + "dirs": ["terraform", "cdk", "cloudformation", "k8s", "kubernetes", "helm", "charts", "infra", "infrastructure", "deploy"], + "prefixes": [], + "contains": [] + }, + "words": ["terraform", "cdk", "cloudformation", "kubernetes", "k8s", "helm", "load balancer", "autoscaling", "vpc", "subnet", "s3 bucket", "dynamodb table", "lambda function"], + "items": [ + { "id": "rollout", "ask": "how it rolls out, in which order across environments" }, + { "id": "rollback", "ask": "how it is rolled back, and what a rollback loses" }, + { "id": "blast_radius", "ask": "what else the changed resources serve (services, environments, tenants)" }, + { "id": "environments", "ask": "which environments it reaches, and whether each has the same resources today" }, + { "id": "permissions", "ask": "the permissions it adds or changes, scoped to which resources" }, + { "id": "cost", "ask": "what it adds to cost, from the resource's pricing and expected use" }, + { "id": "limits", "ask": "the limits, quotas and timeouts it meets or changes" }, + { "id": "monitoring", "ask": "the alarm, metric or log that shows it failing" } + ] + }, + { + "id": "ci", + "title": "CI and deploy pipelines", + "when": "the change touches CI workflows or deploy pipelines", + "paths": { + "ext": [], + "names": [".gitlab-ci.yml", "jenkinsfile", "azure-pipelines.yml", "bitbucket-pipelines.yml"], + "dirs": [], + "prefixes": [".github/workflows/", ".circleci/", ".buildkite/"], + "contains": [] + }, + "words": ["github actions", "ci pipeline", "deploy pipeline", "workflow file"], + "items": [ + { "id": "triggers", "ask": "which branches, events and environments run it" }, + { "id": "rollback", "ask": "how a bad pipeline change is undone without a broken deploy" }, + { "id": "permissions", "ask": "the tokens, secrets and permissions the jobs use, and their scope" }, + { "id": "blast_radius", "ask": "which jobs, deploys or repositories depend on what changed" }, + { "id": "limits", "ask": "timeouts, concurrency and runner time it adds" } + ] + }, + { + "id": "security", + "title": "Auth and security", + "when": "the change touches authentication, authorization, IAM, WAF, secrets or untrusted input", + "paths": { + "ext": [], + "names": [], + "dirs": ["auth", "authz", "security", "iam", "waf"], + "prefixes": [], + "contains": ["auth", "login", "session", "oauth", "permission", "iam", "waf", "cors", "csrf", "secret", "crypto"] + }, + "words": ["authentication", "authorization", "login", "password", "permission", "permissions", "iam", "waf", "cors", "csrf", "secret", "secrets", "encryption", "sso", "oauth", "xss", "injection", "access control"], + "items": [ + { "id": "threat", "ask": "what someone could misuse in the change, and what stops it" }, + { "id": "permissions", "ask": "who or what gains access to what, at the least it needs" }, + { "id": "secrets", "ask": "where secrets and tokens come from, and that none is logged or committed" }, + { "id": "input", "ask": "how untrusted input is validated or encoded" }, + { "id": "compatibility", "ask": "whether existing sessions, tokens and clients keep working, or how they move" } + ] + }, + { + "id": "data", + "title": "Data and migrations", + "when": "the change touches schemas, migrations, stored data or its shape", + "paths": { + "ext": [".sql"], + "names": ["schema.prisma", "schema.rb", "alembic.ini"], + "dirs": ["migrations", "migration", "migrate", "alembic", "seeds", "schema"], + "prefixes": [], + "contains": [] + }, + "words": ["migration", "migrate", "backfill", "schema", "column", "database", "data model"], + "items": [ + { "id": "migration_safety", "ask": "how the migration runs on the real data: its size, locks and duration" }, + { "id": "compatibility", "ask": "old and new code both working against the data during the deploy (expand and contract)" }, + { "id": "rollback", "ask": "how the data change is undone, and what a rollback keeps" }, + { "id": "environments", "ask": "each environment's data it meets, with counts from a lookup" }, + { "id": "existing_rows", "ask": "existing rows: backfilled, defaulted or left, and why" } + ] + }, + { + "id": "performance", + "title": "Performance", + "when": "the change touches a hot path, a query, a loop over stored data, caching or anything the ticket says is slow", + "paths": { + "ext": [], + "names": [], + "dirs": ["cache", "caching"], + "prefixes": [], + "contains": [] + }, + "words": ["latency", "slow", "slowness", "performance", "timeout", "timeouts", "throughput", "memory", "cpu", "n+1", "pagination", "cache", "caching", "p95", "p99", "rate limit"], + "items": [ + { "id": "hot_path", "ask": "whether the changed code is on a hot path and how often it runs, from a lookup or the code" }, + { "id": "cost_per_call", "ask": "what each call costs now: queries, network calls, memory" }, + { "id": "limits", "ask": "the timeouts, payload sizes and rate limits it meets" }, + { "id": "measurement", "ask": "how the effect is measured before and after" } + ] + }, + { + "id": "observability", + "title": "Observability", + "when": "the change adds or changes alarms, metrics, dashboards, logs or tracing", + "paths": { + "ext": [], + "names": [], + "dirs": ["monitoring", "alarms", "alerts", "dashboards", "observability", "telemetry"], + "prefixes": [], + "contains": ["alarm", "alert", "dashboard", "metric", "telemetry", "otel", "sentry", "datadog", "newrelic"] + }, + "words": ["alarm", "alarms", "alert", "alerts", "alerting", "dashboard", "metric", "metrics", "observability", "tracing", "on-call", "monitoring"], + "items": [ + { "id": "signal", "ask": "the alarm, metric or log that shows it working and the one that shows it failing" }, + { "id": "thresholds", "ask": "thresholds and periods, from the current baseline" }, + { "id": "routing", "ask": "who or what is notified" }, + { "id": "noise", "ask": "the expected volume, so it doesn't alert on noise" } + ] + } + ] +} diff --git a/services/common/src/pr_facts.rs b/services/common/src/pr_facts.rs index 612bc53df..3c43b0daa 100644 --- a/services/common/src/pr_facts.rs +++ b/services/common/src/pr_facts.rs @@ -394,6 +394,10 @@ pub struct Facts { /// out of scope; each is not verified until it is taken out or moved in. #[serde(default)] pub scope_breaches: Vec<crate::scope_ledger::Breach>, + /// Each acceptance criterion traced to its code, tests and proof on + /// this head (`crate::trace`): shown as a table with the checks. + #[serde(default)] + pub trace: Option<crate::trace::Trace>, } impl Facts { diff --git a/services/common/src/trace.rs b/services/common/src/trace.rs new file mode 100644 index 000000000..c4c5f22ab --- /dev/null +++ b/services/common/src/trace.rs @@ -0,0 +1,886 @@ +//! Each acceptance criterion traced to the code that changed for it, the +//! tests that cover it, and what proves it on the head. +//! +//! A pull request said what it changed and listed its checks, but nothing +//! tied the two to what the ticket asked: a reader could not tell which +//! criterion a file served, whether any test exercised it, or whether a +//! criterion had been dropped along the way. The trace is that link, as a +//! record ([`Trace`], kept on the run as [`FIELD`] and served by the run +//! API) and as a compact table in the description's checks ([`table`]), +//! rebuilt from the facts of the head on every push like the rest of the +//! description. +//! +//! For each criterion (the ticket's, else the plan's criteria map: +//! `e2e_proof::criteria_or_map`) the trace reads, from facts only: +//! +//! - **Code** ([`Link`]): the diff's non-test files the plan's map line +//! names (`| code: <paths or symbols>`), else the files whose path, added +//! definitions or added lines share the criterion's words. A ticket with +//! one criterion owns the whole change. +//! - **Tests**: the map line's end-to-end test, and the diff's test files +//! that name the criterion's words in their path or test titles (all of +//! them for a one-criterion ticket). +//! - **Proof** ([`Proof`]): the criterion's two-way end-to-end proof on the +//! head (staging and the preview, with the server HTML check), else its +//! tests' runs with and without the change, else nothing yet. +//! +//! A criterion with no traced code, no test, or no proof that holds is an +//! open gap ([`gaps`]): the description lists it under its open items, never +//! as done. + +use serde::{Deserialize, Serialize}; + +use crate::e2e_proof::{self, Criterion, MapLine, Outcome}; + +/// The run record attribute that keeps the trace, as JSON. +pub const FIELD: &str = "traceability"; + +/// Characters of a criterion shown in the table. +const CELL_CHARS: usize = 90; +/// Definitions named per file. +const MAX_SYMBOLS: usize = 4; + +/// One changed file traced to a criterion, with the definitions it adds or +/// changes there. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Link { + pub path: String, + #[serde(default)] + pub symbols: Vec<String>, +} + +/// What the proof of a criterion came to. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + /// Fails without the change and passes with it. + Proven, + /// Passes with and without the change: it doesn't test the criterion. + NotTheTicket, + /// Fails with the change. + Failing, + /// No test of it on the head. + Missing, + /// A side couldn't run. + Unverified, + /// Nothing has run for this head yet. + #[default] + NotRun, +} + +impl State { + pub fn words(self) -> &'static str { + match self { + State::Proven => "proven", + State::NotTheTicket => "passes without the change", + State::Failing => "fails with the change", + State::Missing => "no test", + State::Unverified => "unverified", + State::NotRun => "not run yet", + } + } +} + +/// How a criterion is proven on the head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Proof { + pub state: State, + /// What ran: `end to end on staging and the preview`, `tests with and + /// without the change`, or empty. + #[serde(default)] + pub by: String, + #[serde(default)] + pub detail: String, +} + +/// One criterion's row. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Row { + pub criterion: String, + /// `ticket` or `plan`: where the criterion was written. + pub source: String, + #[serde(default)] + pub page: String, + #[serde(default)] + pub code: Vec<Link>, + #[serde(default)] + pub tests: Vec<String>, + pub proof: Proof, +} + +/// The trace of one head. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Trace { + pub head: String, + pub rows: Vec<Row>, +} + +impl Trace { + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + pub fn from_json(s: &str) -> Option<Self> { + serde_json::from_str(s).ok() + } +} + +/// A changed test file's runs with and without the change +/// (`habits_check`), as the trace reads it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TestRun { + pub path: String, + pub state: State, + pub detail: String, +} + +/// What the trace is built from. +pub struct Inputs<'a> { + pub head: &'a str, + pub criteria: &'a [Criterion], + /// The criteria came from the plan's map, not the ticket. + pub from_plan: bool, + pub map: &'a [MapLine], + /// The diff's files: path, status, patch. + pub files: &'a [(String, String, String)], + /// The two-way end-to-end proofs kept on the run. + pub proofs: &'a [e2e_proof::Proof], + /// The changed tests' runs with and without the change on this head. + pub test_runs: &'a [TestRun], +} + +/// Whether `path` is a test file. +pub fn is_test_path(path: &str) -> bool { + let low = path.to_ascii_lowercase(); + let name = low.rsplit('/').next().unwrap_or(&low); + e2e_proof::is_e2e_path(path) + || low.split('/').any(|s| { + matches!( + s, + "test" | "tests" | "__tests__" | "spec" | "specs" | "testdata" + ) + }) + || name.contains(".test.") + || name.contains(".spec.") + || name.contains("_test.") + || name.starts_with("test_") +} + +fn added_lines(patch: &str) -> impl Iterator<Item = &str> { + patch + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| &l[1..]) +} + +const DEF_PREFIXES: &[&str] = &[ + "pub(crate) async fn ", + "pub(crate) fn ", + "pub async fn ", + "pub fn ", + "async fn ", + "fn ", + "pub struct ", + "struct ", + "pub enum ", + "enum ", + "pub trait ", + "export default function ", + "export async function ", + "export function ", + "async function ", + "function ", + "export const ", + "export class ", + "class ", + "export interface ", + "interface ", + "export type ", + "async def ", + "def ", + "func ", +]; + +fn ident(s: &str) -> Option<String> { + let s = s.trim_start_matches('('); + let id: String = s + .chars() + .skip_while(|c| c.is_whitespace()) + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$') + .collect(); + (id.len() >= 2 && !id.chars().all(|c| c.is_ascii_digit())).then_some(id) +} + +/// The definitions a patch adds or changes: declared on an added line, or +/// named by a hunk header's context. +pub fn symbols(patch: &str) -> Vec<String> { + let mut out: Vec<String> = Vec::new(); + let mut push = |s: String| { + if !out.contains(&s) { + out.push(s); + } + }; + for line in patch.lines() { + let body = if let Some(rest) = line.strip_prefix("@@") { + rest.split_once("@@").map(|(_, ctx)| ctx).unwrap_or("") + } else if line.starts_with('+') && !line.starts_with("+++") { + &line[1..] + } else { + continue; + }; + let t = body.trim_start(); + // Go methods: `func (r *T) Name(`. + if let Some(rest) = t.strip_prefix("func (") { + if let Some(id) = rest.split_once(") ").and_then(|(_, n)| ident(n)) { + push(id); + } + continue; + } + for p in DEF_PREFIXES { + if let Some(rest) = t.strip_prefix(p) { + if let Some(id) = ident(rest) { + push(id); + } + break; + } + } + } + out +} + +/// Five-letter stems of the words worth matching, as the criteria map's +/// matching reads them; identifiers split at their case changes and +/// underscores. +fn stems(text: &str) -> Vec<String> { + const SKIP: &[&str] = &[ + "should", "there", "which", "where", "these", "those", "after", "when", "with", "from", + "that", "this", "only", "into", "have", "test", "tests", "spec", "file", "index", "true", + "false", "return", "const", "export", "import", "function", "string", "number", + ]; + let mut split = String::with_capacity(text.len()); + let mut prev_lower = false; + for c in text.chars() { + if c.is_ascii_uppercase() && prev_lower { + split.push(' '); + } + prev_lower = c.is_ascii_lowercase(); + split.push(c); + } + let mut out: Vec<String> = split + .split(|c: char| !c.is_ascii_alphanumeric()) + .map(str::to_ascii_lowercase) + .filter(|w| w.len() >= 4 && !SKIP.contains(&w.as_str())) + .map(|w| w.chars().take(5).collect()) + .collect(); + out.sort(); + out.dedup(); + out +} + +fn overlap(a: &[String], b: &[String]) -> usize { + a.iter().filter(|w| b.contains(w)).count() +} + +/// The words of a criterion the trace matches on: its text, page and what +/// its map line asserts. +fn criterion_stems(c: &Criterion, m: Option<&MapLine>) -> Vec<String> { + let mut t = c.text.clone(); + if let Some(p) = &c.page { + t.push(' '); + t.push_str(p); + } + if let Some(m) = m { + t.push(' '); + t.push_str(&m.asserts); + t.push(' '); + t.push_str(&m.code); + } + stems(&t) +} + +/// What the map line names as the code for its criterion +/// (`| code: a/b.ts, slugToIds`). +fn named_code(m: Option<&MapLine>) -> Vec<String> { + m.map(|m| { + m.code + .split([',', ';']) + .map(|s| s.trim().trim_matches('`').trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() + }) + .unwrap_or_default() +} + +fn names_file(named: &[String], path: &str, syms: &[String]) -> bool { + named.iter().any(|n| { + path == n + || path.ends_with(&format!("/{n}")) + || (!n.contains('/') && !n.contains('.') && syms.iter().any(|s| s == n)) + }) +} + +fn proof_of_two_way(p: &e2e_proof::Proof) -> Proof { + let (state, detail) = match e2e_proof::outcome(p) { + Outcome::Proven(w) => (State::Proven, w), + Outcome::NotTheTicket(w) => (State::NotTheTicket, w), + Outcome::CoderWork(w) => (State::Failing, w), + Outcome::Missing(w) => (State::Missing, w), + Outcome::Unverified(w) => (State::Unverified, w), + }; + Proof { + state, + by: "end to end on staging and the preview".into(), + detail, + } +} + +fn proof_of_runs(runs: &[&TestRun]) -> Option<Proof> { + let pick = |s: State| runs.iter().find(|r| r.state == s); + let order = [ + State::Proven, + State::Failing, + State::NotTheTicket, + State::Unverified, + State::NotRun, + ]; + let r = order.iter().find_map(|s| pick(*s))?; + let detail = match r.state { + State::Proven => format!("`{}` fails without the change and passes with it", r.path), + _ if r.detail.trim().is_empty() => format!("`{}`: {}", r.path, r.state.words()), + _ => format!( + "`{}`: {}", + r.path, + crate::truncate_str(r.detail.trim(), 200) + ), + }; + Some(Proof { + state: r.state, + by: "tests with and without the change".into(), + detail, + }) +} + +/// The trace of the head. Pure: the description builds it from what it +/// read, and the eval from recorded cases. +pub fn build(i: &Inputs) -> Trace { + let one = i.criteria.len() == 1; + let code_files: Vec<(&str, Vec<String>, Vec<String>)> = i + .files + .iter() + .filter(|(p, status, _)| !is_test_path(p) && status != "removed") + .map(|(p, _, patch)| { + let syms = symbols(patch); + let mut words = stems(p); + words.extend(stems(&syms.join(" "))); + words.extend(stems( + &added_lines(patch).take(200).collect::<Vec<_>>().join(" "), + )); + words.sort(); + words.dedup(); + (p.as_str(), syms, words) + }) + .collect(); + let test_files: Vec<(&str, Vec<String>, Vec<String>)> = i + .files + .iter() + .filter(|(p, status, _)| is_test_path(p) && status != "removed") + .map(|(p, _, patch)| { + let titles = e2e_proof::test_titles(&added_lines(patch).collect::<Vec<_>>().join("\n")); + let mut words = stems(p); + words.extend(stems(&titles.join(" "))); + (p.as_str(), titles, words) + }) + .collect(); + let on_head = e2e_proof::on_head(i.proofs, i.head); + // The specs the plan's map gives to a criterion: never another + // criterion's test by its words alone. + let mapped_specs: Vec<String> = i + .map + .iter() + .filter(|m| !m.test.trim().is_empty()) + .map(MapLine::spec) + .collect(); + let test_words = if one { 0 } else { 2 }; + let rows = i + .criteria + .iter() + .map(|c| { + let m = e2e_proof::line_for(c, i.map); + let want = criterion_stems(c, m); + let named = named_code(m); + let mut code: Vec<Link> = code_files + .iter() + .filter(|(p, syms, words)| { + if !named.is_empty() { + return names_file(&named, p, syms); + } + overlap(&want, words) >= 2 + || overlap(&want, &stems(&format!("{p} {}", syms.join(" ")))) >= 1 + }) + .map(|(p, syms, _)| Link { + path: p.to_string(), + symbols: syms.iter().take(MAX_SYMBOLS).cloned().collect(), + }) + .collect(); + if code.is_empty() && one { + code = code_files + .iter() + .map(|(p, syms, _)| Link { + path: p.to_string(), + symbols: syms.iter().take(MAX_SYMBOLS).cloned().collect(), + }) + .collect(); + } + let mut tests: Vec<String> = Vec::new(); + if let Some(m) = m.filter(|m| !m.test.trim().is_empty()) { + tests.push(m.test.trim().to_string()); + } + for (p, titles, words) in &test_files { + let spec_of_map = tests + .iter() + .any(|t| crate::ci_repro::spec_and_title(t).0 == *p); + if spec_of_map || mapped_specs.iter().any(|m| m == p) { + continue; + } + if overlap(&want, words) >= test_words { + let best = titles + .iter() + .max_by_key(|t| overlap(&want, &stems(t))) + .filter(|t| overlap(&want, &stems(t)) > 0); + tests.push(match best { + Some(t) => format!("{p} › {t}"), + None => p.to_string(), + }); + } + } + // The two-way proof made for this very criterion: the proof + // keeps the criterion's text as the same list gave it. + let two_way = on_head.iter().find(|p| p.criterion.trim() == c.text.trim()); + let proof = match two_way { + Some(p) => proof_of_two_way(p), + None => { + let runs: Vec<&TestRun> = i + .test_runs + .iter() + .filter(|r| { + tests + .iter() + .any(|t| crate::ci_repro::spec_and_title(t).0 == r.path) + }) + .collect(); + proof_of_runs(&runs).unwrap_or_else(|| Proof { + state: if tests.is_empty() { + State::Missing + } else { + State::NotRun + }, + ..Default::default() + }) + } + }; + Row { + criterion: c.text.trim().to_string(), + source: if i.from_plan { "plan" } else { "ticket" }.to_string(), + page: c.page.clone().unwrap_or_default(), + code, + tests, + proof, + } + }) + .collect(); + Trace { + head: i.head.to_string(), + rows, + } +} + +/// One open gap of the trace. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Gap { + pub criterion: String, + pub what: String, + /// The two-way proof already reports it (the description says it once). + pub by_two_way: bool, +} + +/// What the trace leaves open: a criterion no changed code is traced to, +/// one no test covers, one whose proof doesn't hold. +pub fn gaps(t: &Trace) -> Vec<Gap> { + let mut out = Vec::new(); + for r in &t.rows { + let two_way = r.proof.by.starts_with("end to end"); + let mut push = |what: String, by_two_way: bool| { + out.push(Gap { + criterion: r.criterion.clone(), + what, + by_two_way, + }) + }; + if r.code.is_empty() { + push("no change in the diff is traced to it".into(), false); + } + if r.tests.is_empty() { + push("no test on the head covers it".into(), false); + continue; + } + match r.proof.state { + State::Proven => {} + State::NotRun => push( + "its tests haven't run with and without the change on this head".into(), + false, + ), + s => push( + if r.proof.detail.is_empty() { + s.words().to_string() + } else { + r.proof.detail.clone() + }, + two_way, + ), + } + } + out +} + +/// What goes back to the coder for the trace's gaps: one instruction per +/// gap the two-way proof doesn't already send (`e2e_proof::coder_items`), +/// each starting with [`CODER_ITEM`]. A proof still running or a side that +/// couldn't run is not coder work. +pub fn coder_items(t: &Trace) -> Vec<String> { + let mut out: Vec<String> = Vec::new(); + for r in &t.rows { + // The two-way proof sends its own item for a test it found missing, + // failing or not testing the ticket: only the untraced code is + // the trace's to send for that criterion. + let two_way = r.proof.by.starts_with("end to end"); + let c = r.criterion.trim(); + let item = if r.code.is_empty() { + format!( + "{CODER_ITEM} \"{c}\": no change in the diff is traced to it. Build it, or name the code that already does it in the plan's criteria map (`| code: <files or functions>`)." + ) + } else if two_way { + continue; + } else if r.tests.is_empty() { + format!( + "{CODER_ITEM} \"{c}\": no test on the head covers it. Add a test that fails without the change and passes with it." + ) + } else { + match r.proof.state { + State::Failing => format!( + "{CODER_ITEM} \"{c}\": its test fails with the change ({}). Fix the code, not the test.", + r.proof.detail + ), + State::NotTheTicket => format!( + "{CODER_ITEM} \"{c}\": its test passes without the change too ({}). Make it assert what the criterion asks, so it fails without the change.", + r.proof.detail + ), + State::Missing => format!( + "{CODER_ITEM} \"{c}\": no test of it on the head. Add one that fails without the change and passes with it." + ), + _ => continue, + } + }; + if !out.contains(&item) { + out.push(item); + } + } + out +} + +/// How a trace item starts, so it is told from the two-way proof's. +pub const CODER_ITEM: &str = "Criteria trace:"; + +fn cell(s: &str) -> String { + s.replace('|', "\\|").replace('\n', " ") +} + +fn short(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +/// The trace as the description shows it: one row per criterion, compact. +/// Empty for no criteria. +pub fn table(t: &Trace) -> String { + if t.rows.is_empty() { + return String::new(); + } + let head: String = t.head.chars().take(7).collect(); + let mut out = format!( + "**Acceptance criteria, traced** (on `{head}`)\n\n| Criterion | Code | Tests | Proof |\n|---|---|---|---|\n" + ); + for r in &t.rows { + let crit = { + let c = r.criterion.trim(); + if c.chars().count() > CELL_CHARS { + format!("{}…", c.chars().take(CELL_CHARS).collect::<String>()) + } else { + c.to_string() + } + }; + let code = if r.code.is_empty() { + "none traced".to_string() + } else { + let mut parts: Vec<String> = r + .code + .iter() + .take(3) + .map(|l| match l.symbols.first() { + Some(s) => format!("`{}` (`{s}`)", short(&l.path)), + None => format!("`{}`", short(&l.path)), + }) + .collect(); + if r.code.len() > 3 { + parts.push(format!("+{}", r.code.len() - 3)); + } + parts.join(", ") + }; + let tests = if r.tests.is_empty() { + "none".to_string() + } else { + let mut parts: Vec<String> = r + .tests + .iter() + .take(2) + .map(|t| { + let (spec, title) = crate::ci_repro::spec_and_title(t); + if title.is_empty() { + format!("`{}`", short(&spec)) + } else { + format!("`{}` › {title}", short(&spec)) + } + }) + .collect(); + if r.tests.len() > 2 { + parts.push(format!("+{}", r.tests.len() - 2)); + } + parts.join(", ") + }; + let proof = match (r.proof.state, r.proof.by.as_str()) { + (State::Proven, b) if b.starts_with("end to end") => "proven both ways".to_string(), + (State::Proven, _) => "proven: fails without the change".to_string(), + (s, _) => s.words().to_string(), + }; + out.push_str(&format!( + "| {} | {} | {} | {} |\n", + cell(&crit), + cell(&code), + cell(&tests), + cell(&proof) + )); + } + out.trim_end().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ci_repro::{Leg, Record}; + + fn crit(text: &str, page: Option<&str>) -> Criterion { + Criterion { + text: text.into(), + page: page.map(str::to_string), + visible: page.is_some(), + } + } + + fn file(path: &str, patch: &str) -> (String, String, String) { + (path.into(), "modified".into(), patch.into()) + } + + fn files() -> Vec<(String, String, String)> { + vec![ + file( + "apps/web/src/utils/filterMaps.ts", + "@@ -1,3 +1,9 @@ export function slugToId(\n+export function slugToIds(slug: string, rows: Row[]) {\n+ // every sport row sharing the slug\n+}\n", + ), + file( + "apps/web/src/components/SportsFilter.tsx", + "@@ -10 +10,2 @@\n+ const chips = dedupeSportsBySlug(sports);\n+export const dedupeSportsBySlug = (s) => s;\n", + ), + file( + "apps/web/src/lib/analytics.ts", + "@@ -1 +1 @@\n+export function trackPageView(page: string) {}\n", + ), + file( + "e2e/camps.spec.ts", + "@@ -0,0 +1,5 @@\n+test('shows one multi-sport filter chip', async ({ page }) => {\n+ await page.goto('/club/summer-camps');\n+});\n", + ), + ] + } + + fn map() -> Vec<MapLine> { + e2e_proof::parse_map( + "## Criteria map\n- Only one multi-sport filter chip shows | page: /club/summer-camps | e2e: e2e/camps.spec.ts › shows one multi-sport filter chip | asserts: one Multi-Sport chip | code: filterMaps.ts, dedupeSportsBySlug\n- Page views are tracked on the camps page | page: /club/summer-camps | e2e: none: an analytics call | asserts: a page view event\n", + ) + } + + fn proven(criterion: &str, head: &str) -> e2e_proof::Proof { + e2e_proof::Proof { + criterion: criterion.into(), + page: "/club/summer-camps".into(), + test: "e2e/camps.spec.ts › shows one multi-sport filter chip".into(), + record: Record { + head: head.into(), + base: Leg { + ran: true, + failed: 1, + ..Default::default() + }, + change: Leg { + ran: true, + passed: 1, + ..Default::default() + }, + ..Default::default() + }, + ..Default::default() + } + } + + #[test] + fn each_criterion_links_its_code_tests_and_proof() { + let criteria = vec![ + crit( + "Only one multi-sport filter chip shows", + Some("/club/summer-camps"), + ), + crit("Page views are tracked on the camps page", None), + ]; + let m = map(); + let f = files(); + let proofs = vec![proven( + "Only one multi-sport filter chip shows", + "abc1234def", + )]; + let t = build(&Inputs { + head: "abc1234def", + criteria: &criteria, + from_plan: false, + map: &m, + files: &f, + proofs: &proofs, + test_runs: &[], + }); + let chip = &t.rows[0]; + let paths: Vec<&str> = chip.code.iter().map(|l| l.path.as_str()).collect(); + assert_eq!( + paths, + vec![ + "apps/web/src/utils/filterMaps.ts", + "apps/web/src/components/SportsFilter.tsx" + ] + ); + assert_eq!(chip.code[0].symbols, vec!["slugToId", "slugToIds"]); + assert_eq!( + chip.tests, + vec!["e2e/camps.spec.ts › shows one multi-sport filter chip"] + ); + assert_eq!(chip.proof.state, State::Proven); + // The second criterion: its code by its words, no test, an open gap. + let views = &t.rows[1]; + assert_eq!(views.code[0].path, "apps/web/src/lib/analytics.ts"); + assert!(views.tests.is_empty()); + assert_eq!(views.proof.state, State::Missing); + let g = gaps(&t); + assert_eq!(g.len(), 1, "{g:?}"); + assert_eq!(g[0].criterion, "Page views are tracked on the camps page"); + assert!(g[0].what.contains("no test")); + let tbl = table(&t); + assert!(tbl.contains("| Criterion | Code | Tests | Proof |")); + assert!(tbl.contains("`filterMaps.ts` (`slugToId`)")); + assert!(tbl.contains("proven both ways")); + assert!(tbl.contains("| none | no test |")); + assert_eq!(Trace::from_json(&t.to_json()), Some(t)); + } + + #[test] + fn a_proof_of_another_head_does_not_count_and_tests_runs_do() { + let criteria = vec![crit("Only one multi-sport filter chip shows", None)]; + let m = map(); + let f = files(); + let old = vec![proven("Only one multi-sport filter chip shows", "0000000")]; + let runs = vec![TestRun { + path: "e2e/camps.spec.ts".into(), + state: State::NotTheTicket, + detail: String::new(), + }]; + let t = build(&Inputs { + head: "abc1234", + criteria: &criteria, + from_plan: true, + map: &m, + files: &f, + proofs: &old, + test_runs: &runs, + }); + assert_eq!(t.rows[0].source, "plan"); + assert_eq!(t.rows[0].proof.state, State::NotTheTicket); + assert_eq!(t.rows[0].proof.by, "tests with and without the change"); + let g = gaps(&t); + assert_eq!(g.len(), 1); + assert!(!g[0].by_two_way); + // A criterion nothing in the diff serves, with several criteria. + let criteria = vec![ + crit("Only one multi-sport filter chip shows", None), + crit("Refunds are emailed within a day", None), + ]; + let t = build(&Inputs { + head: "abc1234", + criteria: &criteria, + from_plan: false, + map: &[], + files: &f, + proofs: &[], + test_runs: &[], + }); + let refunds = &t.rows[1]; + assert!(refunds.code.is_empty() && refunds.tests.is_empty()); + let g = gaps(&t); + assert!(g + .iter() + .any(|x| x.criterion.starts_with("Refunds") && x.what.contains("no change"))); + assert!(table(&t).contains("none traced")); + } + + #[test] + fn one_criterion_owns_the_whole_change() { + let criteria = vec![crit("The export retries a timed out poll", None)]; + let f = vec![ + file("src/poller.rs", "@@ -1 +1 @@\n+pub fn backoff() {}\n"), + file( + "src/poller_test.rs", + "@@ -1 +1 @@\n+fn gives_up_after_three() {}\n", + ), + ]; + let t = build(&Inputs { + head: "h", + criteria: &criteria, + from_plan: false, + map: &[], + files: &f, + proofs: &[], + test_runs: &[TestRun { + path: "src/poller_test.rs".into(), + state: State::Proven, + detail: String::new(), + }], + }); + assert_eq!(t.rows[0].code[0].path, "src/poller.rs"); + assert_eq!(t.rows[0].tests, vec!["src/poller_test.rs"]); + assert_eq!(t.rows[0].proof.state, State::Proven); + assert!(gaps(&t).is_empty()); + assert!(table(&t).contains("proven: fails without the change")); + } + + #[test] + fn definitions_are_read_from_added_lines_and_hunk_headers() { + let p = "@@ -40,6 +40,8 @@ impl Poller {\n+ pub async fn poll_once(&self) {\n@@ -90 +92 @@ def handle(event):\n+def retry_later(job):\n+class Backoff:\n+func (p *Poller) Next() int {\n+ const x = 1;\n"; + assert_eq!( + symbols(p), + vec!["poll_once", "handle", "retry_later", "Backoff", "Next"] + ); + assert!(is_test_path("src/__tests__/a.ts") && is_test_path("pkg/a_test.go")); + assert!(!is_test_path("src/attest.ts")); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index a1701c4c2..d21d4634c 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -1343,6 +1343,19 @@ pub struct Run { /// For a `covered_by_pr` run: the open pull request that already does the /// work, and why. pub covered_by: Option<RunCoveredBy>, + /// Each acceptance criterion of the ticket (or of the plan's criteria + /// map) traced to the files and definitions changed for it, the tests + /// that cover it, and what proves it on the pull request's head. A row + /// whose proof isn't `proven`, or with no code or no tests, is an open + /// gap. Absent until the run's pull request has a description built for + /// its head. + #[serde(skip_serializing_if = "Option::is_none")] + pub traceability: Option<RunTrace>, + /// What the run explored: the repository's code map brought to the base + /// before planning, and the build's tool calls before its first write. + /// Absent for a run that neither planned nor built. + #[serde(skip_serializing_if = "Option::is_none")] + pub exploration: Option<RunExploration>, /// A lesson recorded for the repository when the fix was elsewhere. #[schema(example = json!(null))] pub lesson: Option<String>, @@ -1515,6 +1528,124 @@ pub struct RunToolingFailure { pub tried: Vec<String>, } +/// Each acceptance criterion traced to the code, tests and proof of one +/// head (`common::trace`). +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunTrace { + /// The pull request's head the trace is of. + #[schema(example = "c0ffee1234567890c0ffee1234567890c0ffee12")] + pub head: String, + /// One row per criterion. + pub rows: Vec<RunTraceRow>, +} + +/// One criterion's row of the trace. +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunTraceRow { + /// The criterion, as written. + #[schema(example = "Only one sport filter chip shows on /camps")] + pub criterion: String, + /// Where it was written: `ticket` or `plan` (the plan's criteria map). + #[schema(example = "ticket")] + pub source: String, + /// The site path it is about, when it names one. + #[serde(default)] + #[schema(example = "/camps")] + pub page: String, + /// The changed files traced to it, each with the definitions it adds + /// or changes there. + #[serde(default)] + pub code: Vec<RunTraceCode>, + /// The tests that cover it (`file` or `file › title`). + #[serde(default)] + #[schema(example = json!(["e2e/camps.spec.ts › shows one chip"]))] + pub tests: Vec<String>, + /// What proves it on the head. + pub proof: RunTraceProof, +} + +/// A changed file traced to a criterion. +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunTraceCode { + /// The file's path in the repository. + #[schema(example = "src/utils/filters.ts")] + pub path: String, + /// Functions, types and constants it adds or changes. + #[serde(default)] + #[schema(example = json!(["dedupeBySlug"]))] + pub symbols: Vec<String>, +} + +/// What proves a criterion on the head. +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunTraceProof { + /// `proven`, `not_the_ticket` (passes without the change), `failing`, + /// `missing` (no test), `unverified` (a side couldn't run) or `not_run`. + #[schema(example = "proven")] + pub state: String, + /// What ran: `end to end on staging and the preview` or `tests with and + /// without the change`; empty when nothing did. + #[serde(default)] + #[schema(example = "end to end on staging and the preview")] + pub by: String, + /// What the run showed. + #[serde(default)] + #[schema(example = "fails on staging (1 failed) and passes on the preview (1 passed)")] + pub detail: String, +} + +/// What a run explored, and what it started from. +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunExploration { + /// The repository's code map, brought to the run's base before + /// planning; absent when the run didn't plan. + pub code_map: Option<RunCodeMapRefresh>, + /// The build's exploration; absent before it built. + pub coder: Option<RunCoderExploration>, +} + +/// What bringing the code map to the base did (`common::code_map`). +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunCodeMapRefresh { + /// The commit the map describes now. + #[schema(example = "c0ffee1234567890c0ffee1234567890c0ffee12")] + pub commit: String, + /// `new`, `current`, `changed` or `unknown changes`. + #[schema(example = "changed")] + pub why: String, + /// Sections kept as they were. + #[serde(default)] + #[schema(example = json!(["architecture", "stack", "area:apps"]))] + pub reused: Vec<String>, + /// Sections written again from the base. + #[serde(default)] + #[schema(example = json!(["build"]))] + pub rebuilt: Vec<String>, + /// Sections to rebuild that the model left out: the next run rebuilds + /// them. + #[serde(default)] + #[schema(example = json!([]))] + pub missed: Vec<String>, +} + +/// The build's tool calls before its first write, and the map it had. +#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] +pub struct RunCoderExploration { + /// Tool calls before the first file was written; absent when it wrote + /// none. + #[schema(example = 4)] + pub calls_before_first_write: Option<u32>, + /// All the build's tool calls. + #[serde(default)] + #[schema(example = 31)] + pub tool_calls: u32, + /// The code map's commit the build started from; absent when it had + /// none. + #[serde(default)] + #[schema(example = "c0ffee1234567890c0ffee1234567890c0ffee12")] + pub map_commit: Option<String>, +} + /// The open pull request that already does a run's work. #[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)] pub struct RunCoveredBy { @@ -1965,6 +2096,14 @@ fn run_of( stop_kind: st("stop_kind").filter(|s| !s.is_empty()), tooling_failure: st("tooling_failure").and_then(|s| serde_json::from_str(&s).ok()), covered_by: st("covered_by").and_then(|s| serde_json::from_str(&s).ok()), + traceability: st(common::trace::FIELD).and_then(|s| serde_json::from_str(&s).ok()), + exploration: { + let code_map: Option<RunCodeMapRefresh> = + st(common::code_map::REFRESH_FIELD).and_then(|s| serde_json::from_str(&s).ok()); + let coder: Option<RunCoderExploration> = + st(common::code_map::EXPLORATION_FIELD).and_then(|s| serde_json::from_str(&s).ok()); + (code_map.is_some() || coder.is_some()).then_some(RunExploration { code_map, coder }) + }, // A lesson recorded for the repository when the fix was elsewhere. lesson: st("lesson"), // A person closed the run on purpose (`run_close`): who, when, why, diff --git a/services/worker/src/passes/code_map.rs b/services/worker/src/passes/code_map.rs new file mode 100644 index 000000000..04665e574 --- /dev/null +++ b/services/worker/src/passes/code_map.rs @@ -0,0 +1,249 @@ +//! The repository's code map in the worker (`common::code_map` has the +//! rules): brought to the run's base before the planner starts, given to +//! the planner and the coder, and what the coder still explored recorded +//! on the run. +//! +//! - [`refresh`]: compares the map's stamp with the base and rebuilds only +//! the sections the changes since then touched (all of them for a first +//! run), in one model call; the rest are reused. +//! - [`block`]: the stored map as a prompt section, for an agent that only +//! reads it (the coder in every round). +//! - [`record_exploration`]: the build's tool calls before its first write, +//! and the map it was given, on the run. + +use common::code_map::{self as cm, CodeMap, Exploration, RefreshRecord, Source}; +use tracing::{info, warn}; + +use super::attr_s; +use crate::agent::provider::{self, ModelProvider}; +use crate::clients::github::GitHubClient; +use crate::models::TokenUsage; +use crate::WorkerState; + +/// What [`refresh`] leaves the planner: the map as a prompt section. +pub(crate) struct ForRun { + pub block: String, + pub record: RefreshRecord, +} + +async fn load(state: &WorkerState, team_id: &str, repo: &str) -> Option<CodeMap> { + cm::load( + &state.dynamo, + &state.config.settings_table_name, + team_id, + repo, + ) + .await +} + +/// The stored map of `owner/name` as a prompt section, or empty. +pub(crate) async fn block(state: &WorkerState, team_id: &str, owner: &str, name: &str) -> String { + load(state, team_id, &format!("{owner}/{name}")) + .await + .map(|m| cm::render(&m)) + .unwrap_or_default() +} + +/// The commit of the stored map of `owner/name`, when there is one. +pub(crate) async fn commit( + state: &WorkerState, + team_id: &str, + owner: &str, + name: &str, +) -> Option<String> { + load(state, team_id, &format!("{owner}/{name}")) + .await + .filter(|m| !m.sections.is_empty()) + .map(|m| m.commit) +} + +/// Brings the map of `owner/name` to the head of `base_branch` and returns +/// it as a prompt section. `None` when the base can't be read; the run goes +/// on without a map (the planner explores as before). +#[allow(clippy::too_many_arguments)] +pub(crate) async fn refresh( + state: &WorkerState, + github: &GitHubClient, + provider: &ModelProvider, + usage: &mut TokenUsage, + team_id: &str, + owner: &str, + name: &str, + base_branch: &str, +) -> Option<ForRun> { + let repo = format!("{owner}/{name}"); + let base = github.get_ref(owner, name, base_branch).await.ok()?; + let tree_sha = github + .get_tree_sha(owner, name, &base) + .await + .unwrap_or_default(); + let map = load(state, team_id, &repo).await; + let same = map + .as_ref() + .is_some_and(|m| m.commit == base || (!tree_sha.is_empty() && m.tree == tree_sha)); + // An unchanged base with nothing behind needs no tree and no model call. + if let Some(m) = map.as_ref().filter(|m| same && m.behind().is_empty()) { + let r = cm::plan_refresh(Some(m), &base, &tree_sha, &m.areas(), None); + if r.is_noop() { + return Some(ForRun { + block: cm::render(m), + record: RefreshRecord { + commit: m.commit.clone(), + why: r.why, + reused: r.reuse, + ..Default::default() + }, + }); + } + } + let paths: Vec<String> = match github.get_tree(owner, name, &base).await { + Ok(t) => t + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect(), + Err(e) => { + warn!(repo, error = %e, "The code map's tree could not be read; the stored map is used as it is"); + return map.map(|m| ForRun { + block: cm::render(&m), + record: RefreshRecord { + commit: m.commit.clone(), + why: "tree unreadable".into(), + ..Default::default() + }, + }); + } + }; + let areas = cm::areas_of(&paths); + let changes = match map.as_ref() { + Some(m) if !same && !m.commit.is_empty() => github + .get_diff(owner, name, &m.commit, &base) + .await + .ok() + .and_then(|v| cm::changed_from_compare(&v)), + _ => None, + }; + let plan = cm::plan_refresh(map.as_ref(), &base, &tree_sha, &areas, changes.as_deref()); + let mut built: Vec<(String, String)> = Vec::new(); + if !plan.rebuild.is_empty() { + let mut sources: Vec<Source> = Vec::new(); + for id in &plan.rebuild { + let mut files = Vec::new(); + for path in cm::inputs_for(id, &paths) { + if let Ok(content) = github.read_file(owner, name, &path, &base).await { + files.push((path, content)); + } + } + sources.push(Source { + id: id.clone(), + listing: cm::listing_for(id, &paths), + files, + }); + } + match provider::converse_simple( + state, + provider, + provider.primary_model_id(), + cm::SYSTEM, + &cm::prompt(&repo, &sources), + usage, + ) + .await + { + Ok(reply) => built = cm::parse_reply(&reply, &plan.rebuild), + Err(e) => { + warn!(repo, error = %e, "The code map's sections could not be written; the stored ones are kept") + } + } + } + let missed: Vec<String> = plan + .rebuild + .iter() + .filter(|id| !built.iter().any(|(b, _)| b == *id)) + .cloned() + .collect(); + let next = cm::apply( + map.as_ref(), + &plan, + &built, + &base, + &tree_sha, + &chrono::Utc::now().to_rfc3339(), + ); + if next.sections.is_empty() { + return None; + } + if map.as_ref() != Some(&next) { + if let Err(e) = cm::save( + &state.dynamo, + &state.config.settings_table_name, + team_id, + &repo, + &next, + ) + .await + { + warn!(repo, error = %e, "The code map could not be kept"); + } + } + info!( + repo, + why = %plan.why, + rebuilt = built.len(), + reused = plan.reuse.len(), + missed = missed.len(), + "Code map brought to the base" + ); + Some(ForRun { + block: cm::render(&next), + record: RefreshRecord { + commit: base, + why: plan.why, + reused: plan.reuse, + rebuilt: built.into_iter().map(|(id, _)| id).collect(), + missed, + }, + }) +} + +async fn set_run_json(state: &WorkerState, team_id: &str, run_id: &str, field: &str, json: String) { + if run_id.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("SET #f = :v") + .expression_attribute_names("#f", field) + .expression_attribute_values(":v", attr_s(&json)) + .send() + .await + { + warn!(run_id, field, error = %e, "Could not keep the code map's record on the run"); + } +} + +/// What the planner's refresh did, on the run. +pub(crate) async fn record_refresh( + state: &WorkerState, + team_id: &str, + run_id: &str, + r: &RefreshRecord, +) { + let json = serde_json::to_string(r).unwrap_or_default(); + set_run_json(state, team_id, run_id, cm::REFRESH_FIELD, json).await; +} + +/// The build's exploration, on the run. +pub(crate) async fn record_exploration( + state: &WorkerState, + team_id: &str, + run_id: &str, + e: &Exploration, +) { + let json = serde_json::to_string(e).unwrap_or_default(); + set_run_json(state, team_id, run_id, cm::EXPLORATION_FIELD, json).await; +} diff --git a/services/worker/src/passes/description.rs b/services/worker/src/passes/description.rs index ec53e3ebd..cb0849bde 100644 --- a/services/worker/src/passes/description.rs +++ b/services/worker/src/passes/description.rs @@ -583,6 +583,15 @@ struct RunBits { two_way: Vec<common::e2e_proof::Proof>, /// The scope decided at plan time (`common::scope_ledger`). scope: Option<common::scope_ledger::Ledger>, + /// The run behind the pull request. + run_id: String, + /// The ticket's text, for its acceptance criteria. + ticket_body: String, + /// The plan's design.md, for its criteria map. + design: String, + /// The changed tests' runs with and without the change, and the head + /// they ran on (`habits_check`). + test_runs: (String, Vec<common::trace::TestRun>), } impl Gathered { @@ -644,9 +653,79 @@ impl Gathered { super::description_facts::with_preview(&mut f, preview); super::description_facts::with_two_way(&mut f, &self.run.two_way); super::description_facts::with_scope(&mut f, self.run.scope.as_ref(), &self.files); + if let Some(t) = self.trace() { + super::description_facts::with_trace(&mut f, t); + } f.waiting = self.run.waiting.clone(); f } + + /// Each acceptance criterion traced to this head's code, tests and + /// proof (`common::trace`); `None` when the run has no criteria. + fn trace(&self) -> Option<common::trace::Trace> { + use common::e2e_proof as ep; + let acceptance = super::stop_judge::acceptance(&self.run.ticket_body); + let map = ep::parse_map(&self.run.design); + let from_ticket = ep::criteria(&self.run.title, &self.run.ticket_body, &acceptance); + let criteria = + ep::criteria_or_map(&self.run.title, &self.run.ticket_body, &acceptance, &map); + if criteria.is_empty() { + return None; + } + let (runs_head, runs) = &self.run.test_runs; + let runs: &[common::trace::TestRun] = if ci_same_head(runs_head, self.head()) { + runs + } else { + &[] + }; + Some(common::trace::build(&common::trace::Inputs { + head: self.head(), + from_plan: criteria != from_ticket, + criteria: &criteria, + map: &map, + files: &self.files, + proofs: &self.run.two_way, + test_runs: runs, + })) + } +} + +fn ci_same_head(a: &str, b: &str) -> bool { + !a.is_empty() && common::ci_repro::same_sha(a, b) +} + +/// The changed tests' runs with and without the change, as the trace reads +/// them, and the head they ran on: from the run's checks ledger +/// (`run_guard`, the tests and scope check). +async fn test_runs_of( + state: &WorkerState, + team_id: &str, + run_id: &str, + scope: &str, +) -> (String, Vec<common::trace::TestRun>) { + use super::habits_check::Verdict; + use common::trace::{State, TestRun}; + let cell = super::run_guard::LedgerCell::load(state, team_id, run_id, scope).await; + let (head, outcome) = cell.update(|l| (l.habits.head.clone(), l.habits_outcome.clone())); + let Some(Ok(Some(facts))) = outcome else { + return (head, Vec::new()); + }; + let runs = facts + .tests + .iter() + .map(|t| TestRun { + path: t.path.clone(), + state: match t.verdict { + Verdict::Proven => State::Proven, + Verdict::PassesEitherWay => State::NotTheTicket, + Verdict::FailsWithChange => State::Failing, + Verdict::FailsBeforeAsserting => State::Unverified, + Verdict::NotRun => State::NotRun, + }, + detail: t.detail.clone(), + }) + .collect(); + (head, runs) } /// The attributes on a run that carry what its title's form was read from @@ -689,6 +768,8 @@ async fn run_bits( } else { String::new() }; + let design = super::e2e_proof::design_of(state, team_id, &run_id, owner, repo).await; + let test_runs = test_runs_of(state, team_id, &run_id, &format!("{owner}/{repo}")).await; ( RunBits { ticket_id: get("ticket_id"), @@ -710,6 +791,10 @@ async fn run_bits( .get(common::scope_ledger::FIELD) .and_then(|v| v.as_s().ok()) .map(|s| common::scope_ledger::Ledger::from_json(s)), + run_id: run_id.clone(), + ticket_body: get("ticket_body"), + design, + test_runs, }, run_id, ) @@ -915,6 +1000,30 @@ async fn build( let next = match gather(state, github, team_id, owner, repo, number).await { Ok(g) if g.head() == head => { let facts = g.facts_of(&base, dependency); + // The trace of this head, on the run for its API. + if let Some(t) = facts.trace.as_ref() { + save_trace(state, team_id, &g.run.run_id, t).await; + let gaps = record_trace_gaps(state, team_id, &g.run.run_id, owner, repo, t).await; + // Without a preview no two-way proof runs to send the trace's + // items with its own (`pr_watch`): the trace sends them. + if g.run.preview.is_none() && !gaps.is_empty() { + let queued = super::resume::queue_own_review_round( + state, + github, + team_id, + &g.run.run_id, + &head, + &gaps, + ) + .await; + tracing::info!( + pr_number = number, + items = gaps.len(), + fixing = matches!(queued, super::resume::OwnRound::Fixing), + "The criteria trace sent work back to the coder" + ); + } + } let reply = match reader { Some(r) => ask_reader(state, r, &facts, &base).await, None => None, @@ -969,6 +1078,75 @@ async fn build( } } +/// The trace of the head on the run (`common::trace::FIELD`), for the run +/// API. +async fn save_trace(state: &WorkerState, team_id: &str, run_id: &str, t: &common::trace::Trace) { + if run_id.is_empty() { + return; + } + if let Err(e) = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", super::attr_s(team_id)) + .key("run_id", super::attr_s(run_id)) + .update_expression("SET #f = :v") + .expression_attribute_names("#f", common::trace::FIELD) + .expression_attribute_values(":v", super::attr_s(&t.to_json())) + .send() + .await + { + warn!(run_id, error = %e, "Could not keep the criteria trace on the run"); + } +} + +/// The trace's open items on the run's checks ledger (`run_guard`), so the +/// run converges on them and the next fix round works them; a head with +/// none clears them. +async fn record_trace_gaps( + state: &WorkerState, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + t: &common::trace::Trace, +) -> Vec<String> { + if run_id.is_empty() { + return Vec::new(); + } + let gaps = super::run_guard::TraceGaps { + head: t.head.clone(), + items: common::trace::coder_items(t), + }; + let cell = + super::run_guard::LedgerCell::load(state, team_id, run_id, &format!("{owner}/{repo}")) + .await; + let items = gaps.items.clone(); + let changed = cell.update(|l| { + let changed = l.trace != gaps; + l.trace = gaps; + changed + }); + if changed { + cell.save(state, team_id, run_id).await; + } + items +} + +/// The trace's open items for `head`, as the run's ledger holds them. +pub(crate) async fn trace_items( + state: &WorkerState, + team_id: &str, + run_id: &str, + owner: &str, + repo: &str, + head: &str, +) -> Vec<String> { + super::run_guard::LedgerCell::load(state, team_id, run_id, &format!("{owner}/{repo}")) + .await + .update(|l| l.trace.on(head).to_vec()) +} + /// The lines CoderHelm wrote about the pull request's CI, true for `head` /// (`common::ci_lines::reconcile`): "CI is failing" goes once the head moved /// or its checks show no failure, a revert's "Deferred" line once its work diff --git a/services/worker/src/passes/description_facts.rs b/services/worker/src/passes/description_facts.rs index 8bfd829bd..3ba58d28b 100644 --- a/services/worker/src/passes/description_facts.rs +++ b/services/worker/src/passes/description_facts.rs @@ -517,6 +517,27 @@ pub fn with_two_way(f: &mut Facts, proofs: &[common::e2e_proof::Proof]) { } } +/// Each criterion traced to its code, tests and proof on this head +/// (`common::trace`): kept in the facts for the table, and every gap the +/// two-way proof doesn't already report is an open item, said as not +/// verified with what is missing. +pub fn with_trace(f: &mut Facts, trace: common::trace::Trace) { + for g in common::trace::gaps(&trace) { + if g.by_two_way { + continue; + } + let what = format!("\"{}\" traced to the change", g.criterion); + if f.unverified + .iter() + .any(|u| u.what == what && u.why == g.what) + { + continue; + } + f.unverified.push(Unverified { what, why: g.what }); + } + f.trace = Some(trace); +} + /// The run's scope decisions in the facts (`common::scope_ledger`): what /// the change leaves out, as the ledger says, and each out-of-scope item /// the diff (`files`: path, status, patch; tests included) brings back, @@ -835,6 +856,13 @@ pub fn shape_for( }) .collect(); let evidence = pr_steps::evidence_block(&facts.steps, &own_checks, &facts.evidence); + // Each criterion traced to its code, tests and proof, with the checks: + // rebuilt from the facts of the head like everything around it. + let checks_block = match facts.trace.as_ref().map(common::trace::table) { + Some(t) if !t.is_empty() && r.evidence.trim().is_empty() => t, + Some(t) if !t.is_empty() => format!("{}\n\n{t}", r.evidence.trim_end()), + _ => r.evidence.clone(), + }; let mut out = format!("{LEAD_START}\n{}\n\n{LEAD_END}\n\n", r.visible); out.push_str(checked.trim()); for (start, inner, end) in [ @@ -845,7 +873,7 @@ pub fn shape_for( ), ( common::pr_body::CHECKS_START, - r.evidence.as_str(), + checks_block.as_str(), common::pr_body::CHECKS_END, ), (EVIDENCE_START, "", EVIDENCE_END), diff --git a/services/worker/src/passes/e2e_proof.rs b/services/worker/src/passes/e2e_proof.rs index 19a6c37aa..4b84efc72 100644 --- a/services/worker/src/passes/e2e_proof.rs +++ b/services/worker/src/passes/e2e_proof.rs @@ -422,7 +422,7 @@ async fn served_legs( /// The plan's design.md for the run's ticket and repository, empty when /// it can't be read. -async fn design_of( +pub(crate) async fn design_of( state: &WorkerState, team_id: &str, run_id: &str, diff --git a/services/worker/src/passes/explore_guard.rs b/services/worker/src/passes/explore_guard.rs index c936e86ed..d8c4b046b 100644 --- a/services/worker/src/passes/explore_guard.rs +++ b/services/worker/src/passes/explore_guard.rs @@ -102,6 +102,8 @@ pub struct ExploreGuard { kept: Mutex<Vec<(String, String)>>, /// The helpers this build added: (path, definition, body). added: Mutex<Vec<(String, minimal_change::Def, String)>>, + /// The round's tool calls up to its first write (`common::code_map`). + pub counter: common::code_map::ExploreCounter, } impl ExploreGuard { diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index afad127be..1e2c963f9 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -260,10 +260,22 @@ pub async fn run( // What outcomes taught the coder here (lessons naming what people // changed, and the prompt variant its bandit picked) sits with the // repository's own instructions, capped by `rewards::implement_block`. + // The repository's code map (`code_map`), brought to the base when the + // run planned: the coder starts from it instead of exploring the layout. + let (code_map_block, code_map_commit) = match run_id { + Some(_) => ( + super::code_map::block(state, &msg.team_id, &msg.repo_owner, &msg.repo_name).await, + super::code_map::commit(state, &msg.team_id, &msg.repo_owner, &msg.repo_name).await, + ), + None => (String::new(), None), + }; let system = coder_system( &msg.repo_owner, &msg.repo_name, - &format!("{rules_block}{instructions_block}{}", msg.coder_learning), + &format!( + "{rules_block}{instructions_block}{code_map_block}{}", + msg.coder_learning + ), &msg.team_instructions, &tests_block, ); @@ -1367,6 +1379,17 @@ pub async fn run( // A file this round (or the rounds before it) changed and then put // back leaves no commit of its own on the pull request. super::round::fold_churn(github, &msg.repo_owner, &msg.repo_name, branch).await; + // How much the build explored before its first write, and whether it + // started from the code map: kept on the run to compare runs with and + // without one. + if let Some(rid) = run_id.filter(|_| round_for == super::write_guard::RoundFor::Build) { + let e = executor + .write_executor + .explore + .counter + .exploration(code_map_commit.clone()); + super::code_map::record_exploration(state, &msg.team_id, rid, &e).await; + } Ok(ImplementResult { files_modified: files, timed_out, @@ -2224,6 +2247,9 @@ impl<'a> ToolExecutor for WriteToolExecutor<'a> { } } let out = self.execute_tool(name, input).await; + if out.is_ok() && is_write_tool(name) { + self.explore.counter.wrote(); + } let out = match out { Ok(serde_json::Value::String(text)) if is_write_tool(name) => { Ok(json!(match self.check_now_note() { @@ -4187,6 +4213,8 @@ impl<'a> ToolExecutor for CombinedWriteToolExecutor<'a> { name: &str, input: &serde_json::Value, ) -> Result<serde_json::Value, Box<dyn std::error::Error + Send + Sync>> { + // Every call counts toward the exploration before the first write. + self.write_executor.explore.counter.call(); if name == "bash" { if let Some(out) = self.bash_with_tools(input).await? { return Ok(out); diff --git a/services/worker/src/passes/incidents/dg_code_map_kept_current.rs b/services/worker/src/passes/incidents/dg_code_map_kept_current.rs new file mode 100644 index 000000000..28e8f454d --- /dev/null +++ b/services/worker/src/passes/incidents/dg_code_map_kept_current.rs @@ -0,0 +1,129 @@ +//! dg. Every run rediscovered the repository. The planner listed the tree +//! and read the README, the manifests and CI to learn the stack and the +//! test commands; then the coder, with none of that, did it again before +//! its first edit. The repository's agent file was written once at install +//! and again only when a top-level config file changed, and neither agent +//! was given it, so the same layout was paid for twice per run and nothing +//! said how much. +//! +//! Guarantee: each repository keeps a code map (`common::code_map`) on its +//! agent file record: architecture, stack and versions, build and test +//! commands, conventions, dependencies between packages, and one section +//! per top-level area, each stamped with the commit it describes. Before +//! the planner starts, the map is brought to the run's base +//! (`passes::code_map::refresh`): the same commit or tree reuses every +//! section; otherwise only the sections the comparison's paths touch are +//! read again and rebuilt, in one model call, and a section the reply left +//! out is retried on the next run. The planner and the coder both get the +//! map as context, and the build's tool calls before its first write are +//! kept on the run with the map's commit (`exploration`). + +use common::code_map::{self as cm, Changed, CodeMap}; + +use super::fixture; + +fn tree() -> Vec<String> { + let mut paths: Vec<String> = fixture::monorepo().tree; + paths.extend( + [ + "README.md", + "package.json", + ".github/workflows/ci.yml", + "apps/web/package.json", + "apps/web/src/index.ts", + "apps/studio/package.json", + "e2e/home.spec.ts", + ] + .map(String::from), + ); + paths.sort(); + paths.dedup(); + paths +} + +/// The first run: every section, stamped with its base. +fn first_run(paths: &[String]) -> CodeMap { + let areas = cm::areas_of(paths); + let r = cm::plan_refresh(None, "base1", "tree1", &areas, None); + assert_eq!(r.why, "new"); + let reply: String = r + .rebuild + .iter() + .map(|id| format!("=== {id} ===\nWhat `{id}` holds.\n")) + .collect(); + let built = cm::parse_reply(&reply, &r.rebuild); + assert_eq!(built.len(), r.rebuild.len()); + cm::apply(None, &r, &built, "base1", "tree1", "t") +} + +#[test] +fn the_map_is_built_once_and_only_what_changed_is_rebuilt() { + let paths = tree(); + let map = first_run(&paths); + assert!(map.section("area:apps").is_some() && map.section("area:e2e").is_some()); + let areas = cm::areas_of(&paths); + + // The next run, after ten merged pull requests that only edited code: + // nothing is read again, no model call. + let edits: Vec<Changed> = (0..10) + .map(|i| Changed::new(&format!("apps/web/src/blocks/card{i}.tsx"), "modified")) + .collect(); + let r = cm::plan_refresh(Some(&map), "base2", "tree2", &areas, Some(&edits)); + assert!(r.rebuild.is_empty(), "{r:?}"); + let map = cm::apply(Some(&map), &r, &[], "base2", "tree2", "t"); + assert!(map.sections.iter().all(|s| s.commit == "base2")); + + // A new end-to-end spec and a CI change: the e2e area and the build + // section, nothing else. + let changes = vec![ + Changed::new("e2e/checkout.spec.ts", "added"), + Changed::new(".github/workflows/ci.yml", "modified"), + ]; + let r = cm::plan_refresh(Some(&map), "base3", "tree3", &areas, Some(&changes)); + assert_eq!(r.rebuild, vec!["build".to_string(), "area:e2e".to_string()]); + assert!(r.reuse.contains(&"area:apps".to_string())); + let built = vec![("build".to_string(), "pnpm test; CI runs e2e".to_string())]; + let map = cm::apply(Some(&map), &r, &built, "base3", "tree3", "t"); + // The e2e section the reply left out keeps its older stamp, is named + // as possibly out of date, and is rebuilt by the next run. + assert_eq!(map.behind(), vec!["area:e2e".to_string()]); + assert!(cm::render(&map).contains("`area:e2e`")); + let next = cm::plan_refresh(Some(&map), "base3", "tree3", &areas, Some(&[])); + assert_eq!(next.rebuild, vec!["area:e2e".to_string()]); +} + +#[test] +fn the_planner_and_the_coder_start_from_the_map_and_the_run_keeps_the_count() { + let plan = include_str!("../plan.rs"); + let refresh_at = plan + .find("super::code_map::refresh(") + .expect("the planner brings the map to the base"); + let system_at = plan + .find("You are the planning engineer") + .expect("the planner's system prompt"); + assert!(refresh_at < system_at, "the map is ready before the prompt"); + assert!( + plan.contains("{code_map}"), + "the planner's prompt carries it" + ); + assert!(plan.contains("record_refresh(")); + + let implement = include_str!("../implement.rs"); + assert!(implement.contains("super::code_map::block(")); + assert!(implement.contains("{code_map_block}")); + assert!(implement.contains("record_exploration(")); + assert!(implement.contains("explore.counter.call()")); + assert!(implement.contains("explore.counter.wrote()")); + + // What a run keeps: the calls before the first write and the map's + // commit, so runs with and without a map compare. + let c = cm::ExploreCounter::default(); + for _ in 0..4 { + c.call(); + } + c.wrote(); + let e = c.exploration(Some("base3".into())); + assert_eq!(e.calls_before_first_write, Some(3)); + let json = serde_json::to_value(&e).unwrap(); + assert_eq!(json["map_commit"], "base3"); +} diff --git a/services/worker/src/passes/incidents/dh_criteria_traced_to_proof.rs b/services/worker/src/passes/incidents/dh_criteria_traced_to_proof.rs new file mode 100644 index 000000000..e40e26169 --- /dev/null +++ b/services/worker/src/passes/incidents/dh_criteria_traced_to_proof.rs @@ -0,0 +1,240 @@ +//! dh. A ticket listed two acceptance criteria: one filter chip per sport +//! on a camps page, and the page view tracked there. The pull request +//! changed the chip code, added an end-to-end spec for the chip, and its +//! two-way proof passed. Its description listed the files and the checks, +//! and nothing tied either to the criteria: the tracking criterion had +//! changed code and no test at all, and no line of the description, the +//! run page or the API said so. A reader had to match files and tests to +//! the ticket by hand to find the criterion left unproven. +//! +//! Guarantee: every build of the description traces each criterion (the +//! ticket's, else the plan's criteria map) to the files and definitions +//! changed for it (the map line's `code:`, else its words), the tests that +//! cover it, and its proof on the head: the two-way end-to-end proof with +//! the served-page check, else its tests' runs with and without the change +//! (`common::trace`). The table is in the description's checks, rebuilt +//! from the facts on every push; a criterion with no traced code, no test +//! or no proof that holds is an open item; and the trace is kept on the run +//! (`traceability`) and served by the run API. + +use crate::passes::description_facts; +use common::ci_repro::{Leg, Record}; +use common::e2e_proof::{self as ep, Proof}; +use common::pr_facts::{Facts, FileChange}; +use common::trace::{self, Inputs, State}; + +const HEAD: &str = "c0ffee1234567890c0ffee1234567890c0ffee12"; + +const TICKET: &str = "On /club/summer-camps the sport filter shows two Multi-Sport chips.\n\nAcceptance Criteria\n- Only one multi-sport filter chip shows on /club/summer-camps\n- Page views of the camps page are tracked"; + +const DESIGN: &str = "## Criteria map\n- Only one multi-sport filter chip shows | page: /club/summer-camps | e2e: e2e/camps.spec.ts › shows one multi-sport filter chip | asserts: one Multi-Sport chip | code: filterMaps.ts, dedupeSportsBySlug\n- Page views of the camps page are tracked | page: /club/summer-camps | e2e: none: an analytics call | asserts: a page view event\n"; + +fn diff() -> Vec<(String, String, String)> { + vec![ + ( + "apps/web/src/utils/filterMaps.ts".into(), + "modified".into(), + "@@ -1 +1,4 @@\n+export function dedupeSportsBySlug(rows: Row[]) {\n+ return uniqBy(rows, (r) => r.slug);\n+}\n".into(), + ), + ( + "apps/web/src/lib/analytics.ts".into(), + "modified".into(), + "@@ -1 +1,2 @@\n+export function trackPageView(page: string) {}\n".into(), + ), + ( + "e2e/camps.spec.ts".into(), + "added".into(), + "@@ -0,0 +1,3 @@\n+test('shows one multi-sport filter chip', async ({ page }) => {\n+ await page.goto('/club/summer-camps');\n+});\n".into(), + ), + ] +} + +fn proven_chip() -> Proof { + Proof { + criterion: "Only one multi-sport filter chip shows on /club/summer-camps".into(), + page: "/club/summer-camps".into(), + test: "e2e/camps.spec.ts › shows one multi-sport filter chip".into(), + record: Record { + head: HEAD.into(), + base: Leg { + ran: true, + failed: 1, + target: "https://staging.example.test".into(), + ..Default::default() + }, + change: Leg { + ran: true, + passed: 1, + target: "https://pr-41.example.test".into(), + ..Default::default() + }, + ..Default::default() + }, + ..Default::default() + } +} + +fn the_trace() -> trace::Trace { + let acceptance = crate::passes::stop_judge::acceptance(TICKET); + let map = ep::parse_map(DESIGN); + let criteria = ep::criteria_or_map("Duplicate chip", TICKET, &acceptance, &map); + assert_eq!(criteria.len(), 2, "{criteria:?}"); + trace::build(&Inputs { + head: HEAD, + criteria: &criteria, + from_plan: false, + map: &map, + files: &diff(), + proofs: &[proven_chip()], + test_runs: &[], + }) +} + +#[test] +fn each_criterion_is_traced_and_the_unproven_one_is_open() { + let t = the_trace(); + let chip = &t.rows[0]; + assert_eq!(chip.code[0].path, "apps/web/src/utils/filterMaps.ts"); + assert_eq!(chip.code[0].symbols, vec!["dedupeSportsBySlug"]); + assert_eq!(chip.proof.state, State::Proven); + let views = &t.rows[1]; + assert_eq!(views.code[0].path, "apps/web/src/lib/analytics.ts"); + assert!(views.tests.is_empty()); + assert_eq!(views.proof.state, State::Missing); + + let mut f = Facts { + head: HEAD.into(), + files: diff() + .iter() + .map(|(p, s, _)| FileChange { + path: p.clone(), + status: s.clone(), + changed: 3, + ..Default::default() + }) + .collect(), + files_complete: true, + ..Default::default() + }; + description_facts::with_two_way(&mut f, &[proven_chip()]); + description_facts::with_trace(&mut f, t.clone()); + // The open item names the criterion and what is missing, once. + let open: Vec<_> = f + .unverified + .iter() + .filter(|u| u.what.contains("Page views")) + .collect(); + assert_eq!(open.len(), 1, "{:?}", f.unverified); + assert!(open[0].why.contains("no test")); + + // The table is in the description, in its checks, from the facts. + let shaped = description_facts::shape("", "fix: one Multi-Sport chip", f, None); + let body = &shaped.body; + assert!( + body.contains("| Criterion | Code | Tests | Proof |"), + "{body}" + ); + assert!(body.contains("proven both ways")); + assert!(body.contains("| none | no test |")); + let fold = body + .find(common::pr_body::EVIDENCE) + .expect("the checks fold"); + assert!(body.find("Acceptance criteria, traced").unwrap() > fold); + // Built again from the same facts, the same table: nothing piles up. + let again = description_facts::shape( + body, + "fix: one Multi-Sport chip", + shaped.facts.clone(), + None, + ); + assert_eq!(again.body.matches("Acceptance criteria, traced").count(), 1); +} + +#[test] +fn the_trace_is_kept_on_the_run_and_served_by_the_api() { + let description = include_str!("../description.rs"); + assert!(description.contains("with_trace(&mut f, t)")); + assert!(description.contains("save_trace(state, team_id")); + let api = include_str!("../../../../gateway/src/routes/api.rs"); + assert!(api.contains("traceability: st(common::trace::FIELD)")); + let t = the_trace(); + assert_eq!(trace::Trace::from_json(&t.to_json()), Some(t)); +} + +#[test] +fn an_open_criterion_drives_a_fix_round_like_any_open_gap() { + use crate::passes::run_guard::{Ledger, Target, TraceGaps}; + let t = the_trace(); + // The untested criterion is the coder's work; the proven one is not. + let items = trace::coder_items(&t); + assert_eq!(items.len(), 1, "{items:?}"); + assert!(items[0].starts_with(trace::CODER_ITEM)); + assert!(items[0].contains("Page views") && items[0].contains("no test")); + + // A criterion whose two-way proof sends its own item is sent once. + let mut both_green = proven_chip(); + both_green.record.base = Leg { + ran: true, + passed: 1, + ..Default::default() + }; + let acceptance = crate::passes::stop_judge::acceptance(TICKET); + let map = ep::parse_map(DESIGN); + let criteria = ep::criteria_or_map("Duplicate chip", TICKET, &acceptance, &map); + let not_the_ticket = trace::build(&Inputs { + head: HEAD, + criteria: &criteria, + from_plan: false, + map: &map, + files: &diff(), + proofs: std::slice::from_ref(&both_green), + test_runs: &[], + }); + let proof_items = ep::coder_items(std::slice::from_ref(&both_green), HEAD); + assert_eq!(proof_items.len(), 1); + let trace_items = trace::coder_items(¬_the_ticket); + assert!( + !trace_items.iter().any(|i| i.contains("multi-sport")), + "{trace_items:?}" + ); + let merged = + crate::passes::pr_watch::with_trace_items(proof_items.clone(), trace_items.clone()); + assert_eq!(merged.len(), 2, "{merged:?}"); + assert_eq!( + crate::passes::pr_watch::with_trace_items(merged.clone(), trace_items).len(), + 2 + ); + + // On the run's ledger the trace's items are open items: the run + // converges on them and they hold the draft. + let mut l = Ledger::default(); + let before = Target::of(&l).open.len(); + l.trace = TraceGaps { + head: HEAD.into(), + items: items.clone(), + }; + let target = Target::of(&l); + assert_eq!(target.open.len(), before + 1, "{:?}", target.open); + assert!(target.open.iter().any(|o| o.contains("Page views"))); + assert!(l + .open_findings() + .iter() + .any(|f| f.point == "check_blocked" && f.detail.contains("The criteria trace"))); + assert_eq!(l.trace.on(HEAD), items.as_slice()); + assert!(l.trace.on("0000000").is_empty()); + + // Wired: the description records them, the watch sends them with the + // proof's in one round, and without a preview the trace sends them. + let description = include_str!("../description.rs"); + assert!(description.contains("record_trace_gaps(state, team_id")); + assert!(description.contains("g.run.preview.is_none() && !gaps.is_empty()")); + assert!(description.contains("queue_own_review_round(")); + let watch = include_str!("../pr_watch.rs"); + let at = watch + .find("super::description::trace_items(") + .expect("the watch reads them"); + let queue = watch[at..] + .find("queue_own_review_round(") + .expect("and queues them"); + assert!(watch[at..at + queue].contains("with_trace_items(items, trace)")); +} diff --git a/services/worker/src/passes/incidents/di_infra_checklist_answered.rs b/services/worker/src/passes/incidents/di_infra_checklist_answered.rs new file mode 100644 index 000000000..c146febe6 --- /dev/null +++ b/services/worker/src/passes/incidents/di_infra_checklist_answered.rs @@ -0,0 +1,95 @@ +//! di. A ticket asked for a queue between the API and the worker. The plan +//! read the Terraform, added the queue resource and the IAM statement, and +//! said nothing about how it rolls out across environments, how it rolls +//! back, what else the worker role serves, what the queue costs or limits, +//! or the alarm that shows it backing up. The change was right; what a +//! careful engineer settles before an infrastructure change was left to the +//! reviewer to ask, one comment at a time. +//! +//! Guarantee: when the plan's files or the ticket reach infrastructure, CI, +//! auth and security, data, a hot path or observability, design.md answers +//! that area's checklist under `## Non-functional checks` +//! (`common::nfr_check`; the lists are data in `nfr_checklists.json`). +//! Each answer says where it comes from (a file, a command, a lookup); an +//! item that doesn't apply says why. What is missing goes back with the +//! plan's other gaps in the same send-back: no new stop, no approval. + +use common::nfr_check; + +const TICKET: &str = "Add a queue between the API and the worker so exports don't time out."; + +const TASKS: &str = "- [ ] infra/queues.tf: [create] The export queue and its dead-letter queue\n- [ ] infra/iam.tf: [modify] Let the worker role send and receive on the queue\n- [ ] services/api/src/export.rs: [modify] Send the export job to the queue\n"; + +const DESIGN_SILENT: &str = + "## Approach\nAdd an SQS queue in `infra/queues.tf` and send exports to it.\n"; + +const DESIGN_ANSWERED: &str = "## Approach\nAdd an SQS queue.\n\n## Non-functional checks\n### Infrastructure\n- rollout: `deploy.yml` applies `infra/` to staging, then prod after approval (source: `.github/workflows/deploy.yml`)\n- rollback: revert the commit; the API keeps its direct path until the queue's consumer is live (source: `services/api/src/export.rs`)\n- blast_radius: a new queue; the worker role gains two actions on it only (source: `infra/iam.tf`)\n- environments: staging and prod both apply `infra/` with their own tfvars (source: `infra/envs/`)\n- permissions: `sqs:SendMessage` for the API role and `sqs:ReceiveMessage` for the worker role, on this queue's ARN (source: `infra/iam.tf`)\n- cost: n/a: about 3k messages a day, inside the free tier per the lookup of last month's export count\n- limits: 256 KB per message; an export job is under 2 KB (source: `services/api/src/export.rs`)\n- monitoring: an alarm on the oldest message's age over 10 minutes (source: `infra/alarms.tf`)\n### Auth and security\n- threat: only the two roles reach the queue; no public policy (source: `infra/iam.tf`)\n- permissions: least privilege as above (source: `infra/iam.tf`)\n- secrets: n/a: the roles use instance credentials, no new secret\n- input: the worker validates the job's schema before running it (source: `services/worker/src/jobs.rs`)\n- compatibility: existing exports keep the direct path until the flag flips (source: `services/api/src/export.rs`)\n"; + +fn planned() -> Vec<String> { + crate::passes::feature::plan_files::planned_files(TASKS) + .into_iter() + .map(|f| f.path) + .collect() +} + +#[test] +fn an_infrastructure_plan_answers_its_checklist_or_goes_back() { + let files = planned(); + let applies: Vec<String> = nfr_check::areas_for(&files, TICKET) + .into_iter() + .map(|a| a.area) + .collect(); + assert_eq!(applies, vec!["infrastructure", "security"]); + + let gaps = nfr_check::plan_gaps(DESIGN_SILENT, &files, TICKET); + assert_eq!(gaps.len(), 1, "{gaps:#?}"); + assert!(gaps[0].contains("`## Non-functional checks`")); + assert!(gaps[0].contains("`rollback`") && gaps[0].contains("`blast_radius`")); + assert!(gaps[0].contains("`infra/queues.tf`")); + + assert!(nfr_check::plan_gaps(DESIGN_ANSWERED, &files, TICKET).is_empty()); + + // An answer with no source, and a "doesn't apply" with no reason, go back. + let weak = DESIGN_ANSWERED + .replace("(source: `infra/alarms.tf`)", "") + .replace( + "an alarm on the oldest message's age over 10 minutes", + "an alarm on the queue", + ) + .replace( + "- secrets: n/a: the roles use instance credentials, no new secret", + "- secrets: n/a", + ); + let gaps = nfr_check::plan_gaps(&weak, &files, TICKET); + assert_eq!(gaps.len(), 2, "{gaps:#?}"); + assert!(gaps + .iter() + .any(|g| g.contains("`monitoring`") && g.contains("where its answer comes from"))); + assert!(gaps + .iter() + .any(|g| g.contains("`secrets`") && g.contains("without saying why"))); +} + +#[test] +fn the_checklist_is_a_plan_gap_never_a_stop() { + let plan = include_str!("../plan.rs"); + let at = plan + .find("common::nfr_check::plan_gaps(") + .expect("the plan check reads the checklists"); + let after = &plan[at..]; + let back = after + .find("back.extend(nfr_gaps") + .expect("into the send-back"); + assert!(back < 600, "the gaps join the send-back right there"); + assert!(!after[..back].contains("needs_input") && !after[..back].contains("approval")); + assert!(plan.contains("nfr = common::nfr_check::planner_section()")); + // The lists are data: every area has its items and the planner is told + // each one. + let told = nfr_check::planner_section(); + for a in nfr_check::areas() { + assert!(told.contains(&a.title)); + for i in &a.items { + assert!(told.contains(&format!("`{}`", i.id)), "{}.{}", a.id, i.id); + } + } +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 34bcbba77..871247080 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1266,6 +1266,9 @@ mod branch_update; mod checks; pub(crate) mod ci_repro; pub mod code_graph; +/// The repository's code map: brought to the base before planning, given +/// to the planner and the coder (`common::code_map`). +pub(crate) mod code_map; mod completeness; pub mod conventions; pub mod conversation; diff --git a/services/worker/src/passes/plan.rs b/services/worker/src/passes/plan.rs index d685c6024..a88160f8a 100644 --- a/services/worker/src/passes/plan.rs +++ b/services/worker/src/passes/plan.rs @@ -299,13 +299,36 @@ pub async fn run( for the new behaviour, at its exact path in the suite, following the suite's conventions \ (page objects, tags, area labels, test map)." ); + // The repository's code map, brought to this run's base: only the + // sections the changes since its stamp touched are written again + // (`common::code_map`). The planner starts from it instead of + // exploring the layout again. + let code_map = match super::code_map::refresh( + state, + github, + provider, + usage, + &msg.team_id, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + ) + .await + { + Some(m) => { + super::code_map::record_refresh(state, &msg.team_id, run_id, &m.record).await; + m.block + } + None => String::new(), + }; let system = format!( "You are the planning engineer for the {owner}/{repo} repository. {stance}\ Research the codebase using the provided tools, then generate an implementation plan \ that CoderHelm carries out to the end, verification included.\n\n\ You have access to these repos:\n{repos_list}\n\n\ All tools default to {owner}/{repo} when the `repo` parameter is omitted. \ - To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{team_block}{tests_block}{feature_block}{smallest}{criteria_map}", + To explore another repo, pass `repo` as `owner/name` (e.g. `\"{default_repo}\"`).{cross_repo}{instructions_block}{code_map}{team_block}{tests_block}{feature_block}{smallest}{criteria_map}{nfr}", + nfr = common::nfr_check::planner_section(), owner = msg.repo_owner, repo = msg.repo_name, stance = super::ownership::planner_stance(), @@ -1061,6 +1084,19 @@ Then the ```fix_location.json block described above."#, // triggers, a fallback and its test, counts in every environment. let release_gaps = super::release_plan::plan_gaps(&draft, &abilities.release); back.extend(release_gaps.iter().cloned()); + // The non-functional checklists (`common::nfr_check`): a change that + // reaches infrastructure, CI, auth, data, a hot path or observability + // answers its area's items from the code and lookups. A plan gap like + // the others: no stop, no approval. + let nfr_gaps = common::nfr_check::plan_gaps( + &draft.design, + &super::feature::plan_files::planned_files(&draft.tasks) + .into_iter() + .map(|f| f.path) + .collect::<Vec<_>>(), + &ticket_words, + ); + back.extend(nfr_gaps.iter().cloned()); // 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_watch.rs b/services/worker/src/passes/pr_watch.rs index 6d08b5578..39bcd9dd7 100644 --- a/services/worker/src/passes/pr_watch.rs +++ b/services/worker/src/passes/pr_watch.rs @@ -559,6 +559,18 @@ async fn release(state: &WorkerState, c: &Candidate, field: &str, value: &str) { /// Marks a head's red checks as dealt with (judged not this change's, see /// `flaky`): the sweep doesn't send them to the fix loop. +/// The two-way proof's items for the head, then the trace's +/// (`common::trace::coder_items`, which already leaves out what the proof +/// sends), each once: one fix round works them all. +pub fn with_trace_items(mut items: Vec<String>, trace: Vec<String>) -> Vec<String> { + for t in trace { + if !items.contains(&t) { + items.push(t); + } + } + items +} + pub(crate) async fn mark_ci_head(state: &WorkerState, team_id: &str, run_id: &str, head: &str) { if head.is_empty() { return; @@ -847,12 +859,25 @@ async fn preview(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> P CAPTURING.store(false, std::sync::atomic::Ordering::SeqCst); proved = fresh; let items = common::e2e_proof::coder_items(&proofs, &st.head); - if fresh && !items.is_empty() { - let queued = super::resume::queue_own_review_round( - state, github, &c.team_id, &c.run_id, &st.head, &items, + if fresh { + // The description is built for this head first: it records the + // criteria the trace leaves open on the run's ledger. + super::description::rebuild_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, ) .await; - info!(run_id = %c.run_id, pr = c.pr, items = items.len(), queued = ?matches!(queued, super::resume::OwnRound::Fixing), "PR watch: the two-way proof sent work back to the coder"); + let trace = super::description::trace_items( + state, &c.team_id, &c.run_id, &c.owner, &c.repo, &st.head, + ) + .await; + let items = with_trace_items(items, trace); + if !items.is_empty() { + let queued = super::resume::queue_own_review_round( + state, github, &c.team_id, &c.run_id, &st.head, &items, + ) + .await; + info!(run_id = %c.run_id, pr = c.pr, items = items.len(), queued = ?matches!(queued, super::resume::OwnRound::Fixing), "PR watch: the two-way proof and the criteria trace sent work back to the coder"); + } } } let moved = proved @@ -861,10 +886,12 @@ async fn preview(state: &WorkerState, github: &GitHubClient, c: &Candidate) -> P }); if moved { info!(run_id = %c.run_id, pr = c.pr, stage = ?st.stage, "PR watch: the preview moved; the description follows"); - super::description::rebuild_run( - state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, - ) - .await; + if !proved { + super::description::rebuild_run( + state, github, &c.team_id, &c.run_id, &c.owner, &c.repo, c.pr, + ) + .await; + } super::ready::request_for( state, &c.team_id, diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index dd7dc96a0..eab03ec30 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -1359,6 +1359,31 @@ pub struct Ledger { /// to (`settle::Record`). #[serde(default)] pub settle: super::settle::Record, + /// The criteria the trace leaves open on the newest head the + /// description was built for (`common::trace::coder_items`): open items + /// like any check's, so the run converges on them and a fix round works + /// them. + #[serde(default)] + pub trace: TraceGaps, +} + +/// The trace's open items on one head. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TraceGaps { + pub head: String, + pub items: Vec<String>, +} + +impl TraceGaps { + /// The items for `head`; none for another head (the trace of that head + /// hasn't been read yet). + pub fn on(&self, head: &str) -> &[String] { + if !head.is_empty() && common::ci_repro::same_sha(&self.head, head) { + &self.items + } else { + &[] + } + } } /// A record larger than this drops its longest text: DynamoDB's item limit is @@ -1456,6 +1481,10 @@ impl Ledger { if let Some(Err(why)) = &self.habits_outcome { open.push(proof::check_item("The tests and scope check", why)); } + // The criteria the trace leaves open hold the draft like a check's. + for item in &self.trace.items { + open.push(proof::blocked_item("The criteria trace", item)); + } open }