From d7bc0b0c8e9ae41878d8066b0ae03b105c839461 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 11:51:32 -0400 Subject: [PATCH 1/5] Plan check before the first PR; each fix round gets its own budget and never fails an open PR A complex ticket's plan listed several new files. The first implement pass changed one, the proof check listed the rest as "gaps under Open items" and the PR opened anyway. CoderHelm's reviewer then asked for changes three times; each round re-entered implement inside what was left of one worker invocation, the third was killed mid-way, the stuck-run sweep marked the run failed while its PR was open and green, and nothing said what the round had pushed. Plan coverage (plan_coverage.rs): - The plan's task checklist is compared with the branch's diff, task by task. Missing tasks get up to two implement rounds aimed at exactly them, then a continuation in a fresh invocation (bounded); a continuation keeps its branch and is told what is left. - Planned work still missing stops the run before any PR, with a plain status naming the tasks; the branch is copied to -wip so a later run's reset can't lose it. Only tasks the plan marks optional may be left out, and the PR names them under Open items with the reason. - The proof judge sees the checklist and reports planned_work; it gets a fix round and is never downgraded to Open items. - tasks.md marks only the tasks the branch did. - A continuation no longer resets its own branch to base. Fix rounds (common::run_round, passes/round.rs): - CI fix, review fix and feedback rounds each run with their own deadline, measured from the invocation they run in, recorded on the run as `round`. A round with too little of its invocation left is parked and runs first in a fresh one; a round that uses its budget with work left continues there (up to three steps). - A round that can't finish leaves the run completed with `round_incomplete` (why, the commits it pushed, the files): "Pull request open; the last fix round didn't finish: ". Feedback and resume errors on a run with an open PR end the same way instead of failed. - The stuck-run sweep waits for a round's own deadline, and a stuck run with an open PR becomes completed with round_incomplete, never failed. No lost work: every coder write is already its own commit on the branch; the coder is told to write each task's files as soon as the task is done, the deadline note asks it to write any finished file before stopping, and an unfinished round records the commits it pushed. API: Run.round_incomplete (OpenAPI), and POST /api/runs/{id}/retry resumes the unfinished round on the same run ("resuming"), giving one automated-fix slot back. --- docs/api/openapi.json | 122 ++- lambda/stuck-run-cleanup/handler.py | 130 ++- lambda/tests/test_stuck_run_cleanup.py | 49 ++ services/common/src/lib.rs | 3 + services/common/src/messages.rs | 5 + services/common/src/run_round.rs | 619 ++++++++++++++ services/gateway/src/routes/api.rs | 359 ++++++++- services/worker/src/agent/anthropic.rs | 26 +- services/worker/src/main.rs | 28 + services/worker/src/models.rs | 1 + services/worker/src/passes/e2e.rs | 1 + services/worker/src/passes/feedback.rs | 91 ++- services/worker/src/passes/implement.rs | 80 +- services/worker/src/passes/link_checks.rs | 2 +- services/worker/src/passes/mod.rs | 288 ++++++- services/worker/src/passes/plan_coverage.rs | 581 ++++++++++++++ services/worker/src/passes/proof.rs | 132 ++- services/worker/src/passes/resume.rs | 849 ++++++++++++++++---- services/worker/src/passes/round.rs | 281 +++++++ 19 files changed, 3443 insertions(+), 204 deletions(-) create mode 100644 services/common/src/run_round.rs create mode 100644 services/worker/src/passes/plan_coverage.rs create mode 100644 services/worker/src/passes/round.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index ef3e20536..549b134eb 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -1977,6 +1977,30 @@ ], "type": "object" }, + "PushedCommit": { + "description": "A commit a fix round pushed before it stopped.", + "properties": { + "message": { + "description": "Its subject line.", + "examples": [ + "WEB-42: Add the gallery tabs" + ], + "type": "string" + }, + "sha": { + "description": "The commit's SHA.", + "examples": [ + "4f2a9c1e7b3d5a6c8e0f1a2b3c4d5e6f7a8b9c0d" + ], + "type": "string" + } + }, + "required": [ + "sha", + "message" + ], + "type": "object" + }, "Quarantine": { "description": "The tests quarantined for the calling repository.", "properties": { @@ -2657,6 +2681,87 @@ ], "type": "object" }, + "RoundIncomplete": { + "description": "The last fix round on the run's open pull request didn't finish. The\nrun's status stays `completed` (the pull request is open); this says\nwhich round stopped, why, and what it pushed.", + "properties": { + "at": { + "description": "When it stopped (RFC 3339).", + "examples": [ + "2026-10-22T15:40:02Z" + ], + "type": "string" + }, + "can_resume": { + "description": "Whether `POST /api/runs/{run_id}/retry` resumes the round on the same\npull request.", + "examples": [ + true + ], + "type": "boolean" + }, + "files": { + "description": "The files those commits changed.", + "examples": [ + [ + "src/blocks/gallery/tabs.tsx" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "kind": { + "description": "The round: `ci_fix` (CI failed and CoderHelm was fixing it),\n`review_fix` (CoderHelm's reviewer asked for changes) or `feedback`\n(a person's review or comments).", + "examples": [ + "review_fix" + ], + "type": [ + "string", + "null" + ] + }, + "number": { + "description": "Which fix of the run it was (1 for the first; 0 when not numbered).", + "examples": [ + 3 + ], + "format": "int32", + "minimum": 0, + "type": "integer" + }, + "pushed": { + "description": "The commits the round pushed to the pull request's branch before it\nstopped, oldest first.", + "items": { + "$ref": "#/components/schemas/PushedCommit" + }, + "type": "array" + }, + "reason": { + "description": "Why it stopped, in plain words.", + "examples": [ + "the review fix round ran out of its time budget 3 times in a row" + ], + "type": "string" + }, + "summary": { + "description": "The run's status as a person reads it.", + "examples": [ + "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row." + ], + "type": "string" + } + }, + "required": [ + "number", + "reason", + "summary", + "pushed", + "files", + "at", + "can_resume" + ], + "type": "object" + }, "Run": { "description": "One run, in full.", "properties": { @@ -3036,6 +3141,17 @@ "null" ] }, + "round_incomplete": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RoundIncomplete", + "description": "Set when the run's pull request is open but the last fix round on it\n(a CI fix, a review fix or a feedback round) didn't finish. Null\notherwise. Resume it with `POST /api/runs/{run_id}/retry`." + } + ] + }, "run_id": { "description": "The run's id, a ULID: the same id as in the path.", "examples": [ @@ -3145,7 +3261,7 @@ "description": "What a run action did.", "properties": { "status": { - "description": "`retrying` after a retry, `cancelled` after a cancel.", + "description": "`retrying` after a retry, `resuming` when a retry resumed the run's\nunfinished fix round, `cancelled` after a cancel.", "examples": [ "retrying" ], @@ -6433,7 +6549,7 @@ }, "/api/runs/{run_id}/retry": { "post": { - "description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=`.", + "description": "Starts the run's ticket again as a new run. Only a run that is `failed`, `needs_input`, `needs_outside_change`, `cancelled` or `closed` can be retried; the old run becomes `retried`, so retrying it twice is refused with `400`. Find the new run with `GET /api/runs?q=`.\n\nA `completed` run whose `round_incomplete` is set (its pull request is open but the last fix round on it didn't finish) is resumed instead: the same run picks the round up again on the same pull request, with a fresh time budget, and the answer's status is `resuming`.", "operationId": "retryRun", "parameters": [ { @@ -6459,7 +6575,7 @@ } } }, - "description": "The ticket is queued again.", + "description": "The ticket is queued again (`retrying`), or the unfinished round is resumed on the same run (`resuming`).", "headers": { "RateLimit-Limit": { "description": "Requests this key may make in a minute.", diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 3c6db5477..9cf8603fa 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -12,6 +12,15 @@ checkpoint, else its newest pass trace. A run that reached none of them stopped before its first pass, and the message says so instead of "during unknown pass". + +Fix rounds (services/common/src/run_round.rs): a CI fix, review fix or +feedback round on an open pull request has its own time budget, recorded on +the run as `round` with a `deadline_at`. The sweep leaves a run alone until +that deadline (plus a grace period) has passed, however long the run itself +has existed. And a stuck run whose pull request is open is never marked +failed: it is completed with `round_incomplete` saying the last round didn't +finish, so the person sees "Pull request open; the last fix round didn't +finish" and can resume it. """ import logging @@ -37,6 +46,17 @@ NOT_A_PASS = {"", "unknown", "cancelled", "closed", "done", "awaiting_ci"} BEFORE_FIRST_PASS = "before its first pass" +# Mirrors services/common/src/run_round.rs (a test there reads these lines). +ROUND_FIELD = "round" +INCOMPLETE_FIELD = "round_incomplete" +ROUND_BUDGET_SECONDS = 750 +ROUND_SWEEP_GRACE_SECONDS = 300 +ROUND_LABELS = { + "ci_fix": "CI fix round", + "review_fix": "review fix round", + "feedback": "feedback round", +} + _dynamodb = None @@ -76,6 +96,83 @@ def failure_message(pass_name): ) +def _parse_time(value): + try: + t = datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return t if t.tzinfo else t.replace(tzinfo=timezone.utc) + + +def round_in_budget(run, now): + """True while the run's fix round is inside its own budget (plus grace). + + A round's clock starts when the round does, never when the run started: + a run that is days old can be working a fresh round. + """ + rnd = run.get(ROUND_FIELD) or {} + if not isinstance(rnd, dict) or rnd.get("state", "running") != "running": + return False + deadline = _parse_time(rnd.get("deadline_at")) + if deadline is None: + started = _parse_time(rnd.get("started_at")) + if started is None: + return False + deadline = started + timedelta(seconds=ROUND_BUDGET_SECONDS) + return now < deadline + timedelta(seconds=ROUND_SWEEP_GRACE_SECONDS) + + +def has_pull_request(run): + try: + number = int(run.get("pr_number") or 0) + except (TypeError, ValueError): + number = 0 + return number > 0 or bool((run.get("pr_url") or "").strip()) + + +def round_kind(run, pass_name): + """The round a stuck run was working: the one it recorded, else the one + its pass points to (the same mapping as run_round::Kind::of_pass).""" + rnd = run.get(ROUND_FIELD) or {} + kind = rnd.get("kind") if isinstance(rnd, dict) else "" + if kind in ROUND_LABELS: + return kind + p = (pass_name or "").split(":")[0] + if p in ("ci_fix", "test"): + return "ci_fix" + if p == "feedback": + return "feedback" + return "review_fix" + + +def incomplete_reason(kind, pass_name): + label = ROUND_LABELS.get(kind, "fix round") + where = f" during the {pass_name} pass" if pass_name else "" + return f"the {label} stopped{where} without reporting back (time limit)" + + +def incomplete_record(run, pass_name, now_iso): + """The `round_incomplete` map for a stuck run whose pull request is open.""" + rnd = run.get(ROUND_FIELD) or {} + if not isinstance(rnd, dict): + rnd = {} + kind = round_kind(run, pass_name) + return { + "kind": kind, + "number": rnd.get("number", 0), + "reason": incomplete_reason(kind, pass_name), + "pushed": [], + "files": [], + "at": now_iso, + "feedback": rnd.get("feedback", ""), + "scoped": rnd.get("scoped", True), + } + + +def status_line(reason): + return f"Pull request open; the last fix round didn't finish: {reason}." + + def _checkpoint_pass(team_id, run_id): if not CHECKPOINTS_TABLE: return "" @@ -137,9 +234,11 @@ def handler(event, context): ":awaiting": SWEPT_STATUSES[1], }, "ProjectionExpression": ( - "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s" + "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " + "#round, pr_number, pr_url" ), } + scan_kwargs["ExpressionAttributeNames"]["#round"] = ROUND_FIELD while True: resp = runs_table.scan(**scan_kwargs) @@ -147,6 +246,9 @@ def handler(event, context): updated = item.get("updated_at", item.get("created_at", "")) status = item.get("status", "") cutoff = running_cutoff if status == "running" else awaiting_cutoff + if status == "running" and round_in_budget(item, now): + # Its fix round is still inside its own budget. + continue if updated and updated < cutoff: stuck_runs.append(item) @@ -179,9 +281,29 @@ def handler(event, context): names = {"#s": "status"} values = {":now": datetime.now(timezone.utc).isoformat(), ":orig": orig_status} - # A stuck "running" run is a hard failure; a stuck "awaiting_ci" run is - # finalized as completed (its PR exists — hand it to a human). - if orig_status == "awaiting_ci": + # A stuck "running" run is a hard failure, unless its pull request is + # open: then a fix round on it stopped, and the run says so instead + # of failing. A stuck "awaiting_ci" run is finalized as completed (its + # PR exists — hand it to a human). + if orig_status == "running" and has_pull_request(run): + now_iso = datetime.now(timezone.utc).isoformat() + record = incomplete_record(run, pass_name, now_iso) + names["#round"] = ROUND_FIELD + names["#inc"] = INCOMPLETE_FIELD + update = ( + "SET #s = :new, status_run_id = :sri, #inc = :inc, current_pass = :cp, " + "updated_at = :now REMOVE #round" + ) + values.update( + { + ":new": "completed", + ":sri": f"completed#{run_id}", + ":inc": record, + ":cp": "done", + } + ) + logger.warning(f"Run {run_id}: {status_line(record['reason'])}") + elif orig_status == "awaiting_ci": update = "SET #s = :new, status_run_id = :sri, error_message = :err, updated_at = :now" values.update( { diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 1faf421e5..d64b81099 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -59,5 +59,54 @@ def test_closed_is_a_state_not_a_pass(self): self.assertEqual(sweep.last_known_pass(run), "implement") +class Rounds(unittest.TestCase): + NOW = sweep.datetime(2026, 10, 26, 15, 0, tzinfo=sweep.timezone.utc) + + def test_a_round_inside_its_own_budget_is_not_swept(self): + # The run is days old; its round started a few minutes ago. + run = { + "created_at": "2026-10-20T09:00:00+00:00", + "round": {"state": "running", "deadline_at": "2026-10-26T15:05:00+00:00"}, + } + self.assertTrue(sweep.round_in_budget(run, self.NOW)) + # Past the deadline and the grace period, it is. + late = self.NOW + sweep.timedelta(seconds=300 + sweep.ROUND_SWEEP_GRACE_SECONDS + 1) + self.assertFalse(sweep.round_in_budget(run, late)) + + def test_a_round_without_a_deadline_uses_its_start_and_the_budget(self): + run = {"round": {"state": "running", "started_at": "2026-10-26T14:55:00+00:00"}} + self.assertTrue(sweep.round_in_budget(run, self.NOW)) + + def test_a_parked_round_or_no_round_has_no_budget_to_wait_for(self): + self.assertFalse(sweep.round_in_budget({}, self.NOW)) + parked = {"round": {"state": "pending", "deadline_at": "2026-10-26T16:00:00+00:00"}} + self.assertFalse(sweep.round_in_budget(parked, self.NOW)) + + def test_a_stuck_run_with_an_open_pr_is_not_failed(self): + run = { + "pr_number": 41, + "current_pass": "implement", + "round": {"kind": "review_fix", "number": 3, "feedback": "Add the tabs"}, + } + self.assertTrue(sweep.has_pull_request(run)) + rec = sweep.incomplete_record(run, "implement", "2026-10-26T15:00:00+00:00") + self.assertEqual(rec["kind"], "review_fix") + self.assertEqual(rec["number"], 3) + self.assertEqual(rec["feedback"], "Add the tabs") + line = sweep.status_line(rec["reason"]) + self.assertTrue(line.startswith("Pull request open; the last fix round didn't finish:")) + self.assertNotIn("failed", line.lower()) + + def test_the_round_kind_falls_back_to_the_pass(self): + self.assertEqual(sweep.round_kind({}, "ci_fix:2"), "ci_fix") + self.assertEqual(sweep.round_kind({}, "feedback"), "feedback") + self.assertEqual(sweep.round_kind({}, "implement"), "review_fix") + + def test_no_pr_means_no_pr(self): + self.assertFalse(sweep.has_pull_request({})) + self.assertFalse(sweep.has_pull_request({"pr_number": 0, "pr_url": ""})) + self.assertTrue(sweep.has_pull_request({"pr_url": "https://example.com/pull/1"})) + + if __name__ == "__main__": unittest.main() diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 6478cf18b..1817af794 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -104,6 +104,9 @@ pub mod run_fail; /// The questions a run asks when it needs a person's answer, and the /// answers people give in CoderHelm. pub mod run_questions; +/// Fix rounds on an open pull request: each with its own time budget, +/// resumable, and never a failed run when one doesn't finish. +pub mod run_round; /// Run statuses; which ones a person set; closing and reopening a run. pub mod run_status; #[cfg(test)] diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 68178b1ef..676becb38 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -821,6 +821,11 @@ pub struct FeedbackMessage { /// Times this feedback was sent again after a transient model error. #[serde(default)] pub model_retries: u32, + /// Steps this feedback round already used: each step has its own time + /// budget, and a round that runs out of it with work left continues in + /// the next step (see `run_round`). + #[serde(default)] + pub round_attempt: u32, } #[derive(Serialize, Deserialize, Debug, Clone, Default)] diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs new file mode 100644 index 000000000..5f76494e7 --- /dev/null +++ b/services/common/src/run_round.rs @@ -0,0 +1,619 @@ +//! Fix rounds on a run's open pull request, each with its own time budget. +//! +//! After a run opens its pull request, more work can come to it: CI fails +//! and CoderHelm fixes it (a CI fix round), CoderHelm's own reviewer asks for +//! changes (a review fix round), or a person comments (a feedback round). +//! Each round used to run inside whatever was left of one worker invocation +//! (a 15 minute limit), with no deadline of its own: a review fix that +//! started after the review had used most of the invocation was killed half +//! way, the stuck-run sweep then marked the whole run `failed` although its +//! pull request was open and green, and nothing said what the round had +//! pushed. +//! +//! The rules here: +//! +//! - A round gets its own budget ([`BUDGET_SECS`]), measured from the +//! invocation it runs in, never from when the run started. A round that +//! would start with less than [`MIN_START_SECS`] left is parked +//! ([`State::Pending`]) and runs first thing in a fresh invocation. +//! - A round that uses its budget with work left continues in a fresh +//! invocation, up to [`MAX_ATTEMPTS`] in all: a resumable unit. +//! - The round being worked is on the run record ([`FIELD`]) with its +//! deadline, so the stuck-run sweep waits for that deadline (plus +//! [`SWEEP_GRACE_SECS`]) before it calls the worker gone. +//! - A round that doesn't finish while the pull request is open never fails +//! the run. The run is `completed` with [`INCOMPLETE_FIELD`] saying which +//! round, why, and the commits it pushed; [`status_line`] is how a person +//! reads it, and Resume ([`may_resume`]) runs the round again. +//! +//! The sweep is Python (`lambda/stuck-run-cleanup/handler.py`) and mirrors +//! the field names and numbers; a test below reads it. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; + +/// The run record field that holds the round being worked (or parked). +pub const FIELD: &str = "round"; +/// The run record field that says the last round didn't finish. +pub const INCOMPLETE_FIELD: &str = "round_incomplete"; + +/// One worker invocation's hard limit, in seconds. +pub const WORKER_LIMIT_SECS: u64 = 900; +/// A round's own time budget, in seconds: one invocation less the time to +/// record what it did, push the status and hand over. +pub const BUDGET_SECS: u64 = WORKER_LIMIT_SECS - 150; +/// A round doesn't start in an invocation with less than this left; it is +/// parked and runs first in a fresh one. +pub const MIN_START_SECS: u64 = 420; +/// How many invocations one round may use before it is left unfinished. +pub const MAX_ATTEMPTS: u32 = 3; +/// How long past a round's deadline the stuck-run sweep waits before it +/// decides the worker is gone. +pub const SWEEP_GRACE_SECS: u64 = 300; +/// The most of a round's instructions kept on the record for a parked round +/// (CI logs can be long; the record has a 400 KB limit). +pub const MAX_FEEDBACK_CHARS: usize = 60_000; +/// The most commits an unfinished round lists. +pub const MAX_PUSHED: usize = 20; + +/// What a round is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// CI failed on the pull request; CoderHelm fixes it. + CiFix, + /// CoderHelm's own reviewer asked for changes. + ReviewFix, + /// A person's review or comments. + Feedback, +} + +impl Kind { + pub fn as_str(self) -> &'static str { + match self { + Kind::CiFix => "ci_fix", + Kind::ReviewFix => "review_fix", + Kind::Feedback => "feedback", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim() { + "ci_fix" => Some(Kind::CiFix), + "review_fix" => Some(Kind::ReviewFix), + "feedback" => Some(Kind::Feedback), + _ => None, + } + } + + /// The kind a pass name points to, for a round the record doesn't name + /// (the sweep, an older run). + pub fn of_pass(pass: &str) -> Kind { + match pass.split(':').next().unwrap_or("").trim() { + "ci_fix" | "test" => Kind::CiFix, + "feedback" => Kind::Feedback, + _ => Kind::ReviewFix, + } + } + + /// The round's name in a sentence. + pub fn label(self) -> &'static str { + match self { + Kind::CiFix => "CI fix round", + Kind::ReviewFix => "review fix round", + Kind::Feedback => "feedback round", + } + } +} + +/// Whether the round is being worked or waits for a fresh invocation. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum State { + #[default] + Running, + Pending, +} + +impl State { + fn as_str(self) -> &'static str { + match self { + State::Running => "running", + State::Pending => "pending", + } + } +} + +/// The round being worked, as the run record holds it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Round { + pub kind: Kind, + /// Which fix of the run this is (1 for the first). + pub number: u32, + /// Which invocation of the round this is (1 for the first). + pub attempt: u32, + pub state: State, + /// When this attempt started (RFC 3339). + pub started_at: String, + /// When this attempt's budget ends (RFC 3339). + pub deadline_at: String, + /// The branch head when the round first started: what it pushed is + /// everything after it. + pub base_sha: String, + /// What the round was asked to do, kept so a parked round can run. + pub feedback: String, + /// Whether the round may only change the files the pull request already + /// changes (a bot-driven fix). + pub scoped: bool, +} + +fn s(v: &str) -> AttributeValue { + AttributeValue::S(v.to_string()) +} + +fn n(v: u32) -> AttributeValue { + AttributeValue::N(v.to_string()) +} + +fn get_s(m: &HashMap, k: &str) -> String { + m.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn get_n(m: &HashMap, k: &str) -> u32 { + m.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or(0) +} + +/// `text` cut to at most `max` bytes at a character boundary. +fn cut(text: &str, max: usize) -> String { + crate::truncate_str(text, max).to_string() +} + +impl Round { + /// A new round that starts now, with its budget from `now`. + pub fn start( + kind: Kind, + number: u32, + base_sha: &str, + feedback: &str, + scoped: bool, + now: chrono::DateTime, + ) -> Round { + Round { + kind, + number, + attempt: 1, + state: State::Running, + started_at: now.to_rfc3339(), + deadline_at: (now + chrono::Duration::seconds(BUDGET_SECS as i64)).to_rfc3339(), + base_sha: base_sha.to_string(), + feedback: cut(feedback, MAX_FEEDBACK_CHARS), + scoped, + } + } + + /// This round, picked up by a fresh invocation now. + pub fn resumed(&self, now: chrono::DateTime) -> Round { + Round { + state: State::Running, + started_at: now.to_rfc3339(), + deadline_at: (now + chrono::Duration::seconds(BUDGET_SECS as i64)).to_rfc3339(), + ..self.clone() + } + } + + /// This round, parked for a fresh invocation. `next_attempt` when the + /// attempt that just ended used its budget. + pub fn parked(&self, next_attempt: bool) -> Round { + Round { + state: State::Pending, + attempt: self.attempt + u32::from(next_attempt), + ..self.clone() + } + } + + /// Whether another invocation may continue this round. + pub fn may_continue(&self) -> bool { + self.attempt < MAX_ATTEMPTS + } + + pub fn to_attr(&self) -> AttributeValue { + AttributeValue::M(HashMap::from([ + ("kind".to_string(), s(self.kind.as_str())), + ("number".to_string(), n(self.number)), + ("attempt".to_string(), n(self.attempt)), + ("state".to_string(), s(self.state.as_str())), + ("started_at".to_string(), s(&self.started_at)), + ("deadline_at".to_string(), s(&self.deadline_at)), + ("base_sha".to_string(), s(&self.base_sha)), + ("feedback".to_string(), s(&self.feedback)), + ("scoped".to_string(), AttributeValue::Bool(self.scoped)), + ])) + } + + pub fn from_attr(v: &AttributeValue) -> Option { + let m = v.as_m().ok()?; + Some(Round { + kind: Kind::parse(&get_s(m, "kind"))?, + number: get_n(m, "number"), + attempt: get_n(m, "attempt").max(1), + state: if get_s(m, "state") == "pending" { + State::Pending + } else { + State::Running + }, + started_at: get_s(m, "started_at"), + deadline_at: get_s(m, "deadline_at"), + base_sha: get_s(m, "base_sha"), + feedback: get_s(m, "feedback"), + scoped: m + .get("scoped") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(true), + }) + } + + /// The round on a run record, if any. + pub fn from_item(item: &HashMap) -> Option { + item.get(FIELD).and_then(Round::from_attr) + } +} + +/// A commit an unfinished round pushed. +#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)] +pub struct Pushed { + pub sha: String, + /// The commit's subject line. + pub message: String, +} + +/// Why the last round didn't finish, and what it left on the branch. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Incomplete { + pub kind: Option, + pub number: u32, + /// Why it stopped, in a person's words. + pub reason: String, + /// The commits it pushed before it stopped (newest last). + pub pushed: Vec, + /// The files those commits changed. + pub files: Vec, + /// When it stopped (RFC 3339). + pub at: String, + /// What the round was asked to do, so Resume can run it again. + pub feedback: String, + /// Whether the round was a bot-driven fix scoped to the PR's files. + pub scoped: bool, +} + +impl Incomplete { + /// The round, stopped for `reason`. + pub fn of(round: &Round, reason: &str, now: &str) -> Incomplete { + Incomplete { + kind: Some(round.kind), + number: round.number, + reason: reason.trim().to_string(), + pushed: Vec::new(), + files: Vec::new(), + at: now.to_string(), + feedback: round.feedback.clone(), + scoped: round.scoped, + } + } + + /// The sentence a person reads. + pub fn status_line(&self) -> String { + status_line(&self.reason) + } + + pub fn to_attr(&self) -> AttributeValue { + let pushed = self + .pushed + .iter() + .take(MAX_PUSHED) + .map(|p| { + AttributeValue::M(HashMap::from([ + ("sha".to_string(), s(&p.sha)), + ("message".to_string(), s(&cut(&p.message, 200))), + ])) + }) + .collect(); + let files = self.files.iter().take(100).map(|f| s(f)).collect(); + AttributeValue::M(HashMap::from([ + ( + "kind".to_string(), + s(self.kind.map(Kind::as_str).unwrap_or("")), + ), + ("number".to_string(), n(self.number)), + ("reason".to_string(), s(&cut(&self.reason, 500))), + ("pushed".to_string(), AttributeValue::L(pushed)), + ("files".to_string(), AttributeValue::L(files)), + ("at".to_string(), s(&self.at)), + ( + "feedback".to_string(), + s(&cut(&self.feedback, MAX_FEEDBACK_CHARS)), + ), + ("scoped".to_string(), AttributeValue::Bool(self.scoped)), + ])) + } + + pub fn from_attr(v: &AttributeValue) -> Option { + let m = v.as_m().ok()?; + let list = |k: &str| { + m.get(k) + .and_then(|v| v.as_l().ok()) + .cloned() + .unwrap_or_default() + }; + Some(Incomplete { + kind: Kind::parse(&get_s(m, "kind")), + number: get_n(m, "number"), + reason: get_s(m, "reason"), + pushed: list("pushed") + .iter() + .filter_map(|p| p.as_m().ok()) + .map(|p| Pushed { + sha: get_s(p, "sha"), + message: get_s(p, "message"), + }) + .collect(), + files: list("files") + .iter() + .filter_map(|f| f.as_s().ok().cloned()) + .collect(), + at: get_s(m, "at"), + feedback: get_s(m, "feedback"), + scoped: m + .get("scoped") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(true), + }) + } + + /// The unfinished round on a run record, if any. + pub fn from_item(item: &HashMap) -> Option { + item.get(INCOMPLETE_FIELD).and_then(Incomplete::from_attr) + } +} + +/// How a run whose pull request is open reads when its last round didn't +/// finish. Never "failed": the pull request is there and can be resumed. +pub fn status_line(reason: &str) -> String { + let reason = reason.trim().trim_end_matches('.'); + if reason.is_empty() { + "Pull request open; the last fix round didn't finish.".to_string() + } else { + format!("Pull request open; the last fix round didn't finish: {reason}.") + } +} + +/// Why a round that used every attempt's budget stopped. +pub fn out_of_time(kind: Kind, attempts: u32) -> String { + match attempts { + 0 | 1 => format!("the {} ran out of its time budget", kind.label()), + n => format!( + "the {} ran out of its time budget {n} times in a row", + kind.label() + ), + } +} + +/// Why a round failed with an error. +pub fn errored(kind: Kind, error: &str) -> String { + let error = error.lines().next().unwrap_or("").trim(); + format!("the {} hit an error ({})", kind.label(), cut(error, 300)) +} + +/// Whether Resume may run the last round again: the run finished with its +/// pull request open and says its last round didn't finish. +pub fn may_resume(status: &str, pr_number: u64, incomplete: bool) -> bool { + incomplete && pr_number > 0 && matches!(status, "completed" | "success") +} + +/// The commits a round pushed and the files they changed, from a GitHub +/// compare (`base...head`) response. +pub fn pushed_from_compare(compare: &serde_json::Value) -> (Vec, Vec) { + let pushed = compare["commits"] + .as_array() + .map(|a| { + a.iter() + .map(|c| Pushed { + sha: c["sha"].as_str().unwrap_or("").to_string(), + message: c["commit"]["message"] + .as_str() + .unwrap_or("") + .lines() + .next() + .unwrap_or("") + .to_string(), + }) + .filter(|p| !p.sha.is_empty()) + .collect::>() + }) + .unwrap_or_default(); + let files = compare["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(String::from)) + .collect() + }) + .unwrap_or_default(); + // The newest commits matter most when the list is cut. + let skip = pushed.len().saturating_sub(MAX_PUSHED); + (pushed.into_iter().skip(skip).collect(), files) +} + +/// One line for a progress note: what an unfinished round left on the +/// branch. +pub fn pushed_note(pushed: &[Pushed], files: &[String]) -> String { + if pushed.is_empty() { + return "It pushed no commits before it stopped.".to_string(); + } + let shas: Vec = pushed + .iter() + .map(|p| p.sha.chars().take(7).collect()) + .collect(); + format!( + "It pushed {} commit(s) to the pull request branch before it stopped ({}), changing {} file(s).", + pushed.len(), + shas.join(", "), + files.len() + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn now() -> chrono::DateTime { + chrono::Utc + .with_ymd_and_hms(2026, 10, 26, 14, 0, 0) + .single() + .unwrap() + } + + #[test] + fn a_round_has_its_own_budget_from_when_it_starts() { + let r = Round::start(Kind::ReviewFix, 2, "abc", "fix it", true, now()); + assert_eq!(r.attempt, 1); + assert_eq!(r.state, State::Running); + let deadline = chrono::DateTime::parse_from_rfc3339(&r.deadline_at).unwrap(); + assert_eq!( + (deadline.with_timezone(&chrono::Utc) - now()).num_seconds(), + BUDGET_SECS as i64 + ); + // Picked up later, the budget starts again from then: the run's own + // age never counts. + let later = now() + chrono::Duration::hours(5); + let again = r.parked(true).resumed(later); + assert_eq!(again.attempt, 2); + assert_eq!(again.state, State::Running); + let d = chrono::DateTime::parse_from_rfc3339(&again.deadline_at).unwrap(); + assert_eq!( + (d.with_timezone(&chrono::Utc) - later).num_seconds(), + BUDGET_SECS as i64 + ); + assert_eq!(again.base_sha, "abc"); + } + + #[test] + fn a_round_continues_a_bounded_number_of_times() { + let mut r = Round::start(Kind::CiFix, 1, "", "", true, now()); + let mut continued = 0; + while r.may_continue() { + r = r.parked(true).resumed(now()); + continued += 1; + } + assert_eq!(continued, MAX_ATTEMPTS - 1); + // Parking without using the budget (deferred before it started) + // doesn't spend an attempt. + let fresh = Round::start(Kind::ReviewFix, 1, "", "", true, now()); + assert_eq!(fresh.parked(false).attempt, 1); + } + + #[test] + fn rounds_round_trip_through_the_record() { + let r = Round::start(Kind::Feedback, 3, "sha1", "comments", false, now()).parked(false); + let back = Round::from_attr(&r.to_attr()).unwrap(); + assert_eq!(back, r); + let item = HashMap::from([(FIELD.to_string(), r.to_attr())]); + assert_eq!(Round::from_item(&item), Some(r.clone())); + + let mut inc = Incomplete::of(&r, "the review fix round ran out of its time budget", "t"); + inc.pushed = vec![Pushed { + sha: "0123456789".into(), + message: "Add the block".into(), + }]; + inc.files = vec!["src/a.ts".into()]; + let back = Incomplete::from_attr(&inc.to_attr()).unwrap(); + assert_eq!(back, inc); + } + + #[test] + fn the_long_feedback_of_a_parked_round_is_cut() { + let big = "x".repeat(MAX_FEEDBACK_CHARS * 2); + let r = Round::start(Kind::CiFix, 1, "", &big, true, now()); + assert!(r.feedback.len() <= MAX_FEEDBACK_CHARS); + } + + #[test] + fn the_status_says_the_pr_is_open_never_failed() { + let line = status_line(&out_of_time(Kind::ReviewFix, 3)); + assert_eq!( + line, + "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row." + ); + assert!(!line.to_lowercase().contains("failed")); + assert_eq!( + status_line(""), + "Pull request open; the last fix round didn't finish." + ); + assert_eq!( + errored(Kind::Feedback, "model call failed\nstack"), + "the feedback round hit an error (model call failed)" + ); + } + + #[test] + fn resume_is_offered_only_for_an_open_pr_whose_round_stopped() { + assert!(may_resume("completed", 12, true)); + assert!(!may_resume("completed", 12, false)); + assert!(!may_resume("completed", 0, true)); + assert!(!may_resume("merged", 12, true)); + assert!(!may_resume("running", 12, true)); + } + + #[test] + fn what_a_round_pushed_comes_from_the_compare() { + let compare = serde_json::json!({ + "commits": [ + {"sha": "aaaaaaa111", "commit": {"message": "Add the tabs\n\nbody"}}, + {"sha": "bbbbbbb222", "commit": {"message": "Add the tests"}} + ], + "files": [{"filename": "src/tabs.ts"}, {"filename": "src/tabs.test.ts"}] + }); + let (pushed, files) = pushed_from_compare(&compare); + assert_eq!(pushed.len(), 2); + assert_eq!(pushed[0].message, "Add the tabs"); + assert_eq!(files, vec!["src/tabs.ts", "src/tabs.test.ts"]); + assert_eq!( + pushed_note(&pushed, &files), + "It pushed 2 commit(s) to the pull request branch before it stopped (aaaaaaa, bbbbbbb), changing 2 file(s)." + ); + assert_eq!( + pushed_note(&[], &[]), + "It pushed no commits before it stopped." + ); + } + + #[test] + fn a_pass_name_points_to_its_round() { + assert_eq!(Kind::of_pass("ci_fix:2"), Kind::CiFix); + assert_eq!(Kind::of_pass("feedback"), Kind::Feedback); + assert_eq!(Kind::of_pass("implement"), Kind::ReviewFix); + for k in [Kind::CiFix, Kind::ReviewFix, Kind::Feedback] { + assert_eq!(Kind::parse(k.as_str()), Some(k)); + } + } + + /// The sweep is Python: it must use the same fields and numbers. + #[test] + fn the_stuck_run_sweep_knows_rounds() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let sweep = + std::fs::read_to_string(root.join("lambda/stuck-run-cleanup/handler.py")).unwrap(); + assert!(sweep.contains(&format!("ROUND_FIELD = \"{FIELD}\""))); + assert!(sweep.contains(&format!("INCOMPLETE_FIELD = \"{INCOMPLETE_FIELD}\""))); + assert!(sweep.contains(&format!("ROUND_SWEEP_GRACE_SECONDS = {SWEEP_GRACE_SECS}"))); + assert!(sweep.contains(&format!("ROUND_BUDGET_SECONDS = {BUDGET_SECS}"))); + assert!(sweep.contains("Pull request open; the last fix round didn't finish")); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index c01595078..5f2fc4f00 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -909,6 +909,53 @@ pub struct RunNote { pub timestamp: Option, } +/// A commit a fix round pushed before it stopped. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct PushedCommit { + /// The commit's SHA. + #[schema(example = "4f2a9c1e7b3d5a6c8e0f1a2b3c4d5e6f7a8b9c0d")] + pub sha: String, + /// Its subject line. + #[schema(example = "WEB-42: Add the gallery tabs")] + pub message: String, +} + +/// The last fix round on the run's open pull request didn't finish. The +/// run's status stays `completed` (the pull request is open); this says +/// which round stopped, why, and what it pushed. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RoundIncomplete { + /// The round: `ci_fix` (CI failed and CoderHelm was fixing it), + /// `review_fix` (CoderHelm's reviewer asked for changes) or `feedback` + /// (a person's review or comments). + #[schema(example = "review_fix")] + pub kind: Option, + /// Which fix of the run it was (1 for the first; 0 when not numbered). + #[schema(example = 3)] + pub number: u32, + /// Why it stopped, in plain words. + #[schema(example = "the review fix round ran out of its time budget 3 times in a row")] + pub reason: String, + /// The run's status as a person reads it. + #[schema( + example = "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row." + )] + pub summary: String, + /// The commits the round pushed to the pull request's branch before it + /// stopped, oldest first. + pub pushed: Vec, + /// The files those commits changed. + #[schema(example = json!(["src/blocks/gallery/tabs.tsx"]))] + pub files: Vec, + /// When it stopped (RFC 3339). + #[schema(example = "2026-10-22T15:40:02Z")] + pub at: String, + /// Whether `POST /api/runs/{run_id}/retry` resumes the round on the same + /// pull request. + #[schema(example = true)] + pub can_resume: bool, +} + /// One run, in full. #[derive(serde::Serialize, utoipa::ToSchema)] pub struct Run { @@ -1044,6 +1091,43 @@ pub struct Run { pub continued_run_id: Option, /// How the run was started and by whom (as in the runs list). pub trigger: run_trigger::RunTrigger, + /// Set when the run's pull request is open but the last fix round on it + /// (a CI fix, a review fix or a feedback round) didn't finish. Null + /// otherwise. Resume it with `POST /api/runs/{run_id}/retry`. + #[schema(example = json!(null))] + pub round_incomplete: Option, +} + +/// The run's unfinished fix round, as the API shows it. +fn round_incomplete_of(item: &run_search::Item) -> Option { + let inc = common::run_round::Incomplete::from_item(item)?; + let status = item + .get("status") + .and_then(|v| v.as_s().ok()) + .map(String::as_str) + .unwrap_or(""); + let pr_number = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + Some(RoundIncomplete { + kind: inc.kind.map(|k| k.as_str().to_string()), + number: inc.number, + summary: inc.status_line(), + reason: inc.reason, + pushed: inc + .pushed + .into_iter() + .map(|p| PushedCommit { + sha: p.sha, + message: p.message, + }) + .collect(), + files: inc.files, + at: inc.at, + can_resume: common::run_round::may_resume(status, pr_number, true), + }) } /// A question a run asked a person. @@ -1383,6 +1467,7 @@ fn run_of( .collect(), answers_url: st("answers_url"), continued_run_id: st("continued_run_id"), + round_incomplete: round_incomplete_of(item), } } @@ -1642,7 +1727,8 @@ pub async fn get_run_openspec( /// What a run action did. #[derive(serde::Serialize, utoipa::ToSchema)] pub struct RunActionResult { - /// `retrying` after a retry, `cancelled` after a cancel. + /// `retrying` after a retry, `resuming` when a retry resumed the run's + /// unfinished fix round, `cancelled` after a cancel. #[schema(example = "retrying")] pub status: String, } @@ -1657,10 +1743,14 @@ pub struct RunActionResult { description = "Starts the run's ticket again as a new run. Only a run that is `failed`, \ `needs_input`, `needs_outside_change`, `cancelled` or `closed` can be retried; the old run \ becomes `retried`, so retrying it twice is refused with `400`. Find the new run with \ - `GET /api/runs?q=`.", + `GET /api/runs?q=`.\n\n\ + A `completed` run whose `round_incomplete` is set (its pull request is open but the last \ + fix round on it didn't finish) is resumed instead: the same run picks the round up again \ + on the same pull request, with a fresh time budget, and the answer's status is \ + `resuming`.", params(("run_id" = String, Path, description = "The run's id.", example = "01JB8X6F4M2C9QZ3T7V5W1K0HA")), responses( - (status = 200, description = "The ticket is queued again.", body = RunActionResult, + (status = 200, description = "The ticket is queued again (`retrying`), or the unfinished round is resumed on the same run (`resuming`).", body = RunActionResult, example = json!({ "status": "retrying" })), (status = 400, description = "The run is not in a state that can be retried.", body = crate::openapi::ErrorBody), (status = 404, description = "No run with this id in the team.", body = crate::openapi::ErrorBody), @@ -1702,6 +1792,21 @@ pub async fn retry_run( .and_then(|v| v.as_s().ok()) .map(|s| s.as_str()) .unwrap_or(""); + // The run's pull request is open and its last fix round didn't finish: + // resume that round on the same run instead of starting the ticket over. + if let Some(inc) = common::run_round::Incomplete::from_item(item) { + let pr_number = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + if common::run_round::may_resume(status, pr_number, true) { + resume_round(&state, &claims, &run_id, item, &inc, pr_number).await?; + return Ok(Json(RunActionResult { + status: "resuming".into(), + })); + } + } if !matches!( status, "failed" | "needs_input" | "needs_outside_change" | "cancelled" | "closed" @@ -1856,6 +1961,157 @@ pub(crate) async fn retry_message( }) } +/// How Resume picks up a run's unfinished fix round. +#[derive(Debug, Clone, PartialEq, Eq)] +enum ResumeRoute { + /// The round's own instructions are kept: park it, and the resume runs + /// it first with a fresh budget. + Parked(common::run_round::Round), + /// Nothing kept to run directly: the resume reads CI and the review on + /// the head again, which brings the fix back. + Recheck, + /// A person's comments: the feedback round reads them again. + Feedback, +} + +fn resume_route( + inc: &common::run_round::Incomplete, + now: chrono::DateTime, +) -> ResumeRoute { + use common::run_round::{Kind, Round}; + match inc.kind { + Some(Kind::Feedback) => ResumeRoute::Feedback, + Some(kind) if !inc.feedback.trim().is_empty() => ResumeRoute::Parked( + Round::start(kind, inc.number, "", &inc.feedback, inc.scoped, now).parked(false), + ), + _ => ResumeRoute::Recheck, + } +} + +/// Resumes a run's unfinished fix round on its open pull request: the run +/// goes back to work under the same id, and the round gets a fresh budget. +/// A person asking is one more fix: one slot of the automated-fix budget is +/// given back so the round isn't refused for the budget it already used. +async fn resume_round( + state: &AppState, + claims: &Claims, + run_id: &str, + item: &run_search::Item, + inc: &common::run_round::Incomplete, + pr_number: u64, +) -> Result<(), StatusCode> { + let text = |k: &str| { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let repo = text("repo"); + let (owner, name) = repo + .split_once('/') + .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; + let mut installation_id = item + .get("installation_id") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + if installation_id == 0 { + installation_id = get_team_installation_id(state, &claims.team_id).await?; + } + let now = chrono::Utc::now(); + let route = resume_route(inc, now); + let (status, pass) = match route { + ResumeRoute::Feedback => ("running", "feedback"), + _ => ("awaiting_ci", "awaiting_ci"), + }; + let mut update = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&claims.team_id)) + .key("run_id", attr_s(run_id)) + .condition_expression("#s = :from") + .expression_attribute_names("#s", "status") + .expression_attribute_names("#inc", common::run_round::INCOMPLETE_FIELD) + .expression_attribute_names("#round", common::run_round::FIELD) + .expression_attribute_values(":from", attr_s(&text("status"))) + .expression_attribute_values(":s", attr_s(status)) + .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))) + .expression_attribute_values(":p", attr_s(pass)) + .expression_attribute_values(":t", attr_s(&now.to_rfc3339())); + update = match &route { + ResumeRoute::Parked(round) => update + .update_expression( + "SET #s = :s, status_run_id = :sri, current_pass = :p, updated_at = :t, #round = :r \ + REMOVE #inc", + ) + .expression_attribute_values(":r", round.to_attr()), + _ => update.update_expression( + "SET #s = :s, status_run_id = :sri, current_pass = :p, updated_at = :t \ + REMOVE #inc, #round", + ), + }; + update.send().await.map_err(|e| { + if common::run_fail::is_condition_failed(&e) { + StatusCode::CONFLICT + } else { + error!("Failed to resume the run's round: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + // One automated-fix slot back for the person's ask (best effort). + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&claims.team_id)) + .key("run_id", attr_s(run_id)) + .update_expression("ADD auto_fix_pushes :minus") + .condition_expression("auto_fix_pushes > :zero") + .expression_attribute_values(":minus", AttributeValue::N("-1".into())) + .expression_attribute_values(":zero", AttributeValue::N("0".into())) + .send() + .await; + let (queue, message) = match route { + ResumeRoute::Feedback => ( + &state.config.feedback_queue_url, + WorkerMessage::Feedback(FeedbackMessage { + team_id: claims.team_id.clone(), + installation_id, + run_id: run_id.to_string(), + repo_owner: owner.to_string(), + repo_name: name.to_string(), + pr_number, + review_id: 0, + ..Default::default() + }), + ), + _ => ( + &state.config.ticket_queue_url, + WorkerMessage::Resume(common::messages::ResumeMessage { + team_id: claims.team_id.clone(), + run_id: run_id.to_string(), + installation_id, + ..Default::default() + }), + ), + }; + let body = serde_json::to_string(&message).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .sqs + .send_message() + .queue_url(queue) + .message_body(&body) + .send() + .await + .map_err(|e| { + error!("Failed to enqueue the resumed round: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + info!(run_id, pr_number, "Unfinished fix round resumed"); + Ok(()) +} + /// Close a PR and delete a branch via the GitHub App token. Best-effort. async fn github_reset_branch( state: &AppState, @@ -5614,6 +5870,103 @@ mod tests { assert_eq!(run["continued_run_id"], "01JB8Z"); } + /// A run whose PR is open and whose last fix round didn't finish reads + /// as such, never as failed, and offers Resume. + #[test] + fn an_unfinished_round_shows_on_the_run_with_resume() { + use aws_sdk_dynamodb::types::AttributeValue as A; + use common::run_round::{Incomplete, Kind, Pushed, Round}; + let round = Round::start( + Kind::ReviewFix, + 3, + "abc", + "Add the tabs", + true, + chrono::Utc::now(), + ); + let mut inc = Incomplete::of( + &round, + "the review fix round ran out of its time budget", + "2026-10-22T15:40:02Z", + ); + inc.pushed = vec![Pushed { + sha: "4f2a9c1".into(), + message: "Add the tabs".into(), + }]; + let item = std::collections::HashMap::from([ + ("status".to_string(), A::S("completed".into())), + ("pr_number".to_string(), A::N("41".into())), + ( + common::run_round::INCOMPLETE_FIELD.to_string(), + inc.to_attr(), + ), + ]); + let usage = RunUsage { + tokens_in: 0, + tokens_out: 0, + cache_read: 0, + cache_write: 0, + cost_usd: 0.0, + }; + let run = serde_json::to_value(run_of(&item, "r1", usage)).unwrap(); + let r = &run["round_incomplete"]; + assert_eq!(run["status"], "completed"); + assert_eq!(r["kind"], "review_fix"); + assert_eq!(r["number"], 3); + assert_eq!(r["can_resume"], true); + assert_eq!(r["pushed"][0]["sha"], "4f2a9c1"); + assert!(r["summary"] + .as_str() + .unwrap() + .starts_with("Pull request open; the last fix round didn't finish")); + // Without one, the field is null. + let plain = + std::collections::HashMap::from([("status".to_string(), A::S("completed".into()))]); + let usage = RunUsage { + tokens_in: 0, + tokens_out: 0, + cache_read: 0, + cache_write: 0, + cost_usd: 0.0, + }; + assert!( + serde_json::to_value(run_of(&plain, "r2", usage)).unwrap()["round_incomplete"] + .is_null() + ); + } + + #[test] + fn resume_parks_a_round_it_can_run_and_rechecks_one_it_cannot() { + use common::run_round::{Incomplete, Kind, Round, State}; + let now = chrono::Utc::now(); + let round = Round::start(Kind::ReviewFix, 2, "abc", "Add the tabs", true, now); + let inc = Incomplete::of(&round, "out of time", "t"); + match super::resume_route(&inc, now) { + super::ResumeRoute::Parked(r) => { + assert_eq!(r.state, State::Pending); + assert_eq!(r.attempt, 1); + assert_eq!(r.feedback, "Add the tabs"); + assert_eq!(r.kind, Kind::ReviewFix); + } + other => panic!("{other:?}"), + } + // The sweep keeps no instructions: the resume reads CI and review again. + let swept = Incomplete { + kind: Some(Kind::ReviewFix), + ..Default::default() + }; + assert_eq!( + super::resume_route(&swept, now), + super::ResumeRoute::Recheck + ); + let fb = Incomplete { + kind: Some(Kind::Feedback), + feedback: "x".into(), + ..Default::default() + }; + assert_eq!(super::resume_route(&fb, now), super::ResumeRoute::Feedback); + } + #[test] fn github_only_identities_are_never_platform_admins() { assert!(verified_identity("USER#Google_1234567890")); diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index cff3160e6..7791f6b12 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -11,6 +11,22 @@ use tracing::{info, warn}; use crate::models::TokenUsage; +/// The reply of a tool loop that reached its deadline before the agent +/// finished: what was done so far is on the branch, the rest is not. +pub const TIMED_OUT_REPLY: &str = "(timed out — partial implementation)"; + +/// The note an agent gets when its deadline is two minutes away. Every +/// write it made is already a commit on the branch; a file it finished but +/// hasn't written yet is the only work that can still be lost, so it writes +/// that one (complete, never a stub) and stops. +pub const WRAP_UP_NOTE: &str = "[SYSTEM NOTE — DEADLINE] You are almost out of time. Your \ + completed edits are ALREADY committed (each write is its own commit on the branch), so do \ + NOT start anything new. If a file you have FINISHED is not written yet, write it now, \ + complete, in one call. Never write a stub, placeholder, or half-finished file to 'save \ + progress': a partial file breaks the build and is worse than leaving it unwritten (the next \ + step picks the task up). Then output a short summary: the tasks you finished, and the tasks \ + still to do. This is your LAST turn."; + static ANTHROPIC_VERSION: &str = "2023-06-01"; /// Reusable Anthropic client. @@ -693,7 +709,7 @@ pub async fn converse_tool_loop( if remaining < 30 { // Hard stop — not enough time even for one more API call warn!("Deadline imminent (<30s), forcing exit"); - return Ok("(timed out — partial implementation)".to_string()); + return Ok(TIMED_OUT_REPLY.to_string()); } else if remaining < 120 && !deadline_warned { deadline_warned = true; warn!( @@ -703,13 +719,7 @@ pub async fn converse_tool_loop( messages.push(( "user".to_string(), vec![json!({"type": "text", "text": - "[SYSTEM NOTE — DEADLINE] You are almost out of time. Your completed \ - edits are ALREADY committed (each edit committed as you made it), so \ - do NOT dump remaining work now. Above all, do NOT write a stub, \ - placeholder, or half-finished file to 'save progress' — a partial file \ - breaks the build and is worse than leaving it unfinished. Stop, and \ - output a short summary of what you finished and what still needs doing. \ - This is your LAST turn." + WRAP_UP_NOTE })], )); } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 55b958182..514a45596 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -316,6 +316,20 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) } let reason = common::run_fail::error_text(err); error!(run_id, error = %reason, "Feedback run failed"); + // The run's pull request is open: a feedback round that + // failed leaves it so, said plainly, with Resume. Not failed. + if passes::round::end_unfinished( + &state, + &team_id, + &run_id, + common::run_round::Kind::Feedback, + &reason, + false, + ) + .await + { + return; + } // The one failed-status write. It never overwrites a run that // was cancelled (a closed PR) or merged meanwhile. if let Err(werr) = common::run_fail::fail_run( @@ -423,8 +437,22 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) } models::WorkerMessage::Resume(msg) => { info!(team_id = %msg.team_id, run_id = %msg.run_id, "Resuming run from webhook event"); + let (team_id, run_id) = (msg.team_id.clone(), msg.run_id.clone()); if let Err(e) = passes::resume::run(&state, msg).await { error!("Resume failed: {e:?}"); + // A round this resume claimed (the run is "running") ends + // here: with its pull request open, the run says the round + // didn't finish instead of waiting for the sweep to fail it. + let reason = common::run_fail::error_text(&*e); + passes::round::end_unfinished( + &state, + &team_id, + &run_id, + common::run_round::Kind::ReviewFix, + &reason, + true, + ) + .await; } } models::WorkerMessage::Review(msg) => { diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 2e30c8c14..f50b2e898 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -297,6 +297,7 @@ mod tests { trigger_author: "alice".into(), defer_count: 2, model_retries: 0, + round_attempt: 1, }); let json = serde_json::to_string(&msg).unwrap(); let parsed: WorkerMessage = serde_json::from_str(&json).unwrap(); diff --git a/services/worker/src/passes/e2e.rs b/services/worker/src/passes/e2e.rs index 919ac342d..8cc95e45d 100644 --- a/services/worker/src/passes/e2e.rs +++ b/services/worker/src/passes/e2e.rs @@ -831,6 +831,7 @@ async fn own_pr_failures( trigger_author: String::new(), defer_count: 0, model_retries: 0, + round_attempt: 0, }; let queue = if state.config.feedback_queue_url.is_empty() { &state.config.ticket_queue_url diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index b40c01d84..b66991476 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -14,6 +14,9 @@ pub async fn run( state: &WorkerState, mut msg: FeedbackMessage, ) -> Result<(), Box> { + // This round's own clock (common::run_round): the time budget starts + // with this invocation, never with the run. + let start = std::time::Instant::now(); let mut usage = TokenUsage::default(); // Load team's Anthropic API key (required), gated for this run. @@ -467,9 +470,17 @@ pub async fn run( ); let commit_hint = conventions.commit_hint(&tokens); + // A later step of the same round: the earlier one's commits are there. + let continuing = if msg.round_attempt > 0 { + "\n## Continuing this round\nAn earlier step of this round ran out of time; everything it \ + wrote is already committed on the branch. Read the files first and finish only what is \ + left; don't redo or revert it.\n" + } else { + "" + }; let prompt = format!( r#"A reviewer left comments on PR #{pr_number}. - +{continuing} ## Review Comments {comments} {ci_failures} @@ -684,6 +695,32 @@ Rules: vec![serde_json::json!({"type": "text", "text": prompt})], )]; + // The round on the run record, with its deadline, while it works: the + // stuck-run sweep waits for that deadline, not the run's age. + if !super::round::may_start(start, std::time::Instant::now()) { + // Too little of this invocation is left for the round: the same + // feedback runs first in a fresh one, with its whole budget. + info!(run_id = %msg.run_id, "Feedback round deferred to a fresh step for its full budget"); + if send_delayed_feedback(state, &msg, 5).await { + return Ok(()); + } + } + let feedback_round = { + let base_sha = + super::round::branch_head(&github, &msg.repo_owner, &msg.repo_name, &branch).await; + let mut r = common::run_round::Round::start( + common::run_round::Kind::Feedback, + 0, + &base_sha, + &formatted, + ci_only, + chrono::Utc::now(), + ); + r.attempt = msg.round_attempt + 1; + r + }; + super::round::record(state, &msg.team_id, &msg.run_id, &feedback_round).await; + let model_id = provider.primary_model_id(); let response = provider::converse( state, @@ -698,7 +735,7 @@ Rules: llm::ConverseOptions { max_turns: 40, max_tokens: 16384, - deadline: None, + deadline: Some(super::round::deadline(start)), effort: None, }, None, @@ -709,6 +746,51 @@ Rules: s.drain_usage_into(&mut usage); } + // Out of this step's budget with work left: what it wrote is committed. + // The round continues in a fresh step (the comments are still + // unanswered, so it picks them up), or the run says it didn't finish. + // Nothing half-done is posted as a reply. + if super::implement::reached_deadline( + &response, + Some(super::round::deadline(start)), + std::time::Instant::now(), + ) { + if feedback_round.may_continue() { + let mut next = msg.clone(); + next.round_attempt = feedback_round.attempt; + if send_delayed_feedback(state, &next, 5).await { + super::add_progress_note( + state, + &msg.team_id, + &msg.run_id, + &format!( + "The feedback round used its time budget with work left; it continues in a fresh step with its own budget (step {} of {}).", + feedback_round.attempt + 1, + common::run_round::MAX_ATTEMPTS + ), + ) + .await; + return Ok(()); + } + } + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &super::round::Pr { + github: &github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + branch: &branch, + }, + &feedback_round, + &common::run_round::out_of_time(feedback_round.kind, feedback_round.attempt), + ) + .await; + super::webhooks::emit_run(state, &msg.team_id, &msg.run_id, "completed").await; + return Ok(()); + } + info!( run_id = %msg.run_id, "Feedback complete: {}", @@ -971,11 +1053,14 @@ Rules: cost_usd = if_not_exists(cost_usd, :zero) + :c, \ updated_at = :t, #s = :s, current_pass = :p, status_run_id = :sri, \ pass_history = list_append(if_not_exists(pass_history, :empty), :entry) \ - REMOVE error_message, #err", + REMOVE error_message, #err, #round, #inc", ) .condition_expression(common::run_status::not_ended("#s")) .expression_attribute_names("#s", "status") .expression_attribute_names("#err", "error") + // The round finished. + .expression_attribute_names("#round", common::run_round::FIELD) + .expression_attribute_names("#inc", common::run_round::INCOMPLETE_FIELD) .ended_values() .expression_attribute_values( ":ti", diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 575266294..008c1975f 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -124,6 +124,9 @@ fn checks_report( pub struct ImplementResult { pub files_modified: Vec, + /// The pass reached its deadline before the agent finished: what it + /// wrote is committed on the branch, the rest of the work is not done. + pub timed_out: bool, pub conversation_log: Vec, /// What the pass could read, looked up, and wrote as its evidence. pub evidence: super::proof::RunEvidence, @@ -837,7 +840,7 @@ pub async fn run( let mut conv_log: Vec = Vec::new(); // The coder's closing reply: its summary and `Evidence:` section. - let closing = provider::converse( + let mut closing = provider::converse( state, provider, common::agent_policy::Agent::Coder, @@ -1000,6 +1003,13 @@ pub async fn run( .cloned() .collect(); + // Cut short by the deadline: the loop's own marker, or the pass ended + // inside the wrap-up window (the agent summarized what was left). + let timed_out = reached_deadline(&closing, deadline, std::time::Instant::now()); + if closing == crate::agent::anthropic::TIMED_OUT_REPLY { + closing.clear(); + } + // What this pass could read and what it looked up, for the check before // the PR opens and for the PR description. let mut sources = Vec::new(); @@ -1030,6 +1040,7 @@ pub async fn run( let ci_gates = super::checks::kinds_from(&ci); Ok(ImplementResult { files_modified: files, + timed_out, conversation_log: conv_log, evidence: super::proof::RunEvidence { sources, @@ -1045,6 +1056,21 @@ pub async fn run( }) } +/// How close to its deadline a pass that ended counts as cut short by it: +/// the tool loop asks the agent to wrap up at two minutes left. +const WRAP_UP_WINDOW: std::time::Duration = std::time::Duration::from_secs(120); + +/// Whether a pass that ended with `closing` at `now` was cut short by its +/// deadline rather than finishing its work. +pub(crate) fn reached_deadline( + closing: &str, + deadline: Option, + now: std::time::Instant, +) -> bool { + closing.trim() == crate::agent::anthropic::TIMED_OUT_REPLY + || deadline.is_some_and(|d| now + WRAP_UP_WINDOW >= d) +} + /// The parts of the coder's task prompt. struct TaskPrompt<'a> { simple: bool, @@ -1092,6 +1118,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. - Use `edit_file` for modifying existing files (search/replace). Only use `write_file` for new files. - You should need 2-5 tool calls total, plus any lookups the rules below call for. - Only implement the listed tasks. Do not add extras. +- Write each file as soon as its change is done; never hold finished changes back for one write at the end. - NEVER leave placeholder text like TODO, FIXME, REPLACE_ME, or stub implementations. Every line you write must be complete, working code. - {commit} - {evidence_output} @@ -1120,6 +1147,7 @@ Go DIRECTLY to the target files listed in the OpenSpec. - Refer to the Design section for which files to modify and patterns to follow. - Validate your changes against the Acceptance Criteria. - Use `batch_write` for atomic multi-file changes (new files or when edit_file won't work). +- Write each task's files as soon as that task is done, so every finished task is its own commit on the branch. Never hold the files of several tasks back to write them all at the end: a step that runs out of time loses whatever wasn't written. - Follow existing code patterns exactly (imports, naming, structure, test style). - NEVER leave placeholder text like TODO, FIXME, REPLACE_ME, or stub implementations. Every line you write must be complete, working code. - NEVER delete existing functions, methods, or logic unless the task explicitly requires removing them. Modify code, don't gut it. @@ -3037,6 +3065,56 @@ mod task_prompt_tests { } } +#[cfg(test)] +mod deadline_tests { + use super::reached_deadline; + use std::time::{Duration, Instant}; + + #[test] + fn a_pass_cut_by_its_deadline_says_so() { + let now = Instant::now(); + // The loop's own marker. + assert!(reached_deadline( + crate::agent::anthropic::TIMED_OUT_REPLY, + Some(now + Duration::from_secs(600)), + now + )); + // Ended inside the wrap-up window: the agent summarized what's left. + assert!(reached_deadline( + "Done: tasks 1-2. Still to do: task 3.", + Some(now + Duration::from_secs(60)), + now + )); + // Finished with time to spare, or no deadline at all. + assert!(!reached_deadline( + "All tasks done.", + Some(now + Duration::from_secs(600)), + now + )); + assert!(!reached_deadline("All tasks done.", None, now)); + } + + #[test] + fn the_coder_is_told_to_commit_each_task_as_it_finishes_it() { + for simple in [true, false] { + let p = super::task_prompt(&super::TaskPrompt { + simple, + number: 1, + title: "t", + design: "", + continuation: "", + openspec: "", + files_hint: "", + feedback: "", + issue: "", + commit: "", + }); + assert!(p.contains("as soon as"), "simple={simple}"); + assert!(p.contains("at the end"), "simple={simple}"); + } + } +} + #[cfg(test)] mod run_checks_tests { use super::{check_steps, checks_report, extra_steps, gate_passed, CheckKind}; diff --git a/services/worker/src/passes/link_checks.rs b/services/worker/src/passes/link_checks.rs index 248d5d6fd..ff9957c54 100644 --- a/services/worker/src/passes/link_checks.rs +++ b/services/worker/src/passes/link_checks.rs @@ -1322,7 +1322,7 @@ pub async fn gate( usage, w.file_cache, Some(w.run_id), - None, + w.deadline, true, // bot-driven link fix — scoped to the PR ) .await; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 4bf3308ce..dbe0d62f1 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -723,6 +723,7 @@ pub mod open_pr_choice; pub mod ops_tools; mod plan; pub mod plan_chat; +pub(crate) mod plan_coverage; pub mod plan_execute; mod plan_judge; /// Plugin runs, publishing, source sync and results. @@ -753,6 +754,7 @@ pub mod review_scope; pub mod review_sweep; pub mod review_verdict; pub mod rewards; +pub(crate) mod round; mod security; #[cfg(test)] mod selfhost_links; @@ -2383,6 +2385,7 @@ async fn run_passes( checks::detect_ci(&github, &msg.repo_owner, &msg.repo_name, &msg.base_branch).await; implement::ImplementResult { files_modified, + timed_out: false, conversation_log: vec![], // The first attempt's lookups weren't kept; the proof check's // fix round can make them again. @@ -2791,8 +2794,29 @@ async fn run_passes( }) }; + // A continuation of this same run (out of time, a model error) keeps + // the commits its earlier attempt pushed: resetting the branch to its + // base here threw that work away before the continuation could build + // on it. + let keep_own_branch = same_run + && !skip_branch_reset + && ticket_update_pr.is_none() + && existing_pr.is_none() + && github + .get_ref(&msg.repo_owner, &msg.repo_name, &branch_name) + .await + .is_ok(); if ticket_update_pr.is_some() { // Progress note already posted; the branch keeps the PR's head. + } else if keep_own_branch { + info!(run_id, branch = %branch_name, "Continuation: keeping the earlier attempt's commits"); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("Continuing on {branch_name} from the earlier attempt's commits"), + ) + .await; } else if skip_branch_reset { let pr_number = existing_pr .as_ref() @@ -3488,6 +3512,12 @@ async fn run_passes( usage, ) .await; + // A continuation picks up the planned tasks the branch doesn't do yet. + let still_to_do = if msg.continuation > 0 { + continuation_feedback(&github, msg, &plan_result, &branch_name).await + } else { + None + }; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); let result = implement::run( @@ -3498,7 +3528,7 @@ async fn run_passes( &branch_name, &rules, &repo_instructions, - None, + still_to_do.as_deref(), &effective_complexity, &provider, usage, @@ -3700,33 +3730,106 @@ async fn run_passes( return Ok(()); } - // Mark all tasks as done in S3 openspec so retries/dashboard see progress - let tasks_key = format!( - "{}/tasks.md", - openspec_prefix( - &msg.team_id, - &msg.ticket_id, - &msg.repo_owner, - &msg.repo_name - ) - ); - let checked = plan_result.tasks.replace("- [ ]", "- [x]"); - if let Err(e) = state - .s3 - .put_object() - .bucket(&state.config.bucket_name) - .key(&tasks_key) - .body(checked.as_bytes().to_vec().into()) - .content_type("text/markdown") - .send() - .await - { - warn!(run_id, error = %e, "Failed to update tasks.md with checked items"); - } - result }; + // --- Plan check: the plan is done, task by task, before the PR --- + // What the implement pass changed is compared with the plan's checklist; + // tasks not done get rounds aimed at them, then a fresh invocation, and a + // pull request never opens with planned work missing. + check_cancelled(state, &msg.team_id, run_id).await?; + let mut impl_result = impl_result; + let mut plan_optional: Vec = Vec::new(); + let coverage = plan_coverage::close_gaps( + &plan_coverage::Work { + state, + msg, + github: &github, + plan: &plan_result, + branch: &branch_name, + rules: &rules, + repo_instructions: &repo_instructions, + provider: &provider, + file_cache: &file_cache, + run_id, + deadline: implement_deadline, + }, + &mut impl_result.evidence, + usage, + || has_time_for_remediation(start), + ) + .await; + if let Some(cov) = coverage { + // Only the tasks the branch did are checked off, so the run page and + // a later attempt see the truth. + save_checked_tasks( + state, + msg, + run_id, + &plan_coverage::checked_tasks_md(&plan_result.tasks, &cov), + ) + .await; + add_progress_note( + state, + &msg.team_id, + run_id, + &plan_coverage::progress_note(&cov), + ) + .await; + match plan_coverage::next(&cov, plan_coverage::MAX_ROUNDS, false) { + plan_coverage::Next::Complete => {} + plan_coverage::Next::OpenWithOptional => { + plan_optional = plan_coverage::optional_findings(&cov); + } + plan_coverage::Next::Round | plan_coverage::Next::Unfinished => { + // A fresh invocation, with its own time, continues from this + // branch (bounded); the continuation is told what's left. + save_checkpoint( + state, + &msg.team_id, + run_id, + "implement_started", + &branch_name, + 0, + usage, + ) + .await; + let resume_from = Some(("implement_started".to_string(), branch_name.clone(), 0u8)); + if try_auto_continue(state, msg, run_id, &resume_from, &["implement_started"]).await + { + add_progress_note( + state, + &msg.team_id, + run_id, + &format!( + "{} planned task(s) not done yet: continuing in a fresh step with its own time budget", + cov.required_missing().len() + ), + ) + .await; + close_memory(state, agent_memory.take()).await; + return Ok(()); + } + // Out of continuations: stop without a pull request, the + // work kept on a branch a later run won't reset. + save_checkpoint( + state, + &msg.team_id, + run_id, + "implement", + &branch_name, + 0, + usage, + ) + .await; + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + close_memory(state, agent_memory.take()).await; + return Err(plan_coverage::stop_reason(&cov, &kept).into()); + } + } + } + // --- Adversarial Test (multi-repo path) --- check_cancelled(state, &msg.team_id, run_id).await?; if has_time_for_remediation(start) { @@ -3970,11 +4073,25 @@ async fn run_passes( provider: &provider, file_cache: &file_cache, run_id, + deadline: implement_deadline, }; - let gaps = proof::prove(&work, &mut evidence, usage, || { + let mut gaps = proof::prove(&work, &mut evidence, usage, || { has_time_for_remediation(start) }) .await; + // Planned work the check found not done is never an Open item: the pull + // request doesn't open without it. + if !proof::planned_work(&gaps).is_empty() { + let kept = keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + close_memory(state, agent_memory.take()).await; + return Err(format!( + "{} The work so far is kept on branch `{kept}`.", + proof::unfinished_reason(&gaps) + ) + .into()); + } + // Tasks the plan marks optional and the change left out, named. + gaps.extend(plan_optional); // Every redirect and link the change adds or changes, checked live; a // failure that survives its fix round stops the run before the PR. let links = link_checks::gate(&work, &mut evidence, usage, || { @@ -4181,6 +4298,71 @@ async fn run_passes( Ok(()) } +/// Keeps a branch's commits on `-wip` when a run stops before its +/// pull request: a later run of the ticket resets the run branch to its +/// base, and the work must survive that. Returns the branch the work is on +/// (the run branch itself when the copy can't be made). +async fn keep_wip_branch(github: &GitHubClient, owner: &str, repo: &str, branch: &str) -> String { + let wip = format!("{branch}-wip"); + match github.create_branch(owner, repo, &wip, branch).await { + Ok(_) => wip, + Err(e) => { + warn!(branch, error = %e, "Could not keep the work on a WIP branch"); + branch.to_string() + } + } +} + +/// The plan's checklist with only the done tasks checked, written where the +/// run page and a later attempt read it. +async fn save_checked_tasks(state: &WorkerState, msg: &TicketMessage, run_id: &str, md: &str) { + let tasks_key = format!( + "{}/tasks.md", + openspec_prefix( + &msg.team_id, + &msg.ticket_id, + &msg.repo_owner, + &msg.repo_name + ) + ); + if let Err(e) = state + .s3 + .put_object() + .bucket(&state.config.bucket_name) + .key(&tasks_key) + .body(md.as_bytes().to_vec().into()) + .content_type("text/markdown") + .send() + .await + { + warn!(run_id, error = %e, "Failed to update tasks.md with checked items"); + } +} + +/// For a continuation: the planned tasks its branch doesn't do yet, as the +/// implement pass's instructions. `None` when all are done or it can't tell. +async fn continuation_feedback( + github: &GitHubClient, + msg: &TicketMessage, + plan: &plan::PlanResult, + branch: &str, +) -> Option { + let tasks = plan_coverage::plan_tasks(&plan.tasks); + if tasks.is_empty() { + return None; + } + let changed = plan_coverage::changed_files( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + branch, + ) + .await?; + let cov = plan_coverage::coverage(&tasks, &changed); + (!cov.required_missing().is_empty()).then(|| plan_coverage::round_feedback(&cov)) +} + /// Run implement → security → PR for a single repo. /// Returns a RepoPrResult with the created PR info. #[allow(clippy::too_many_arguments)] @@ -4315,6 +4497,48 @@ async fn run_repo_pipeline( .into()); } + // --- Plan check: this repository's tasks are done before its PR --- + let mut impl_result = impl_result; + let mut plan_optional: Vec = Vec::new(); + if let Some(cov) = plan_coverage::close_gaps( + &plan_coverage::Work { + state, + msg, + github, + plan: &repo_plan, + branch: branch_name, + rules, + repo_instructions, + provider, + file_cache, + run_id, + deadline: implement_deadline, + }, + &mut impl_result.evidence, + usage, + || has_time_for_remediation(start), + ) + .await + { + add_progress_note( + state, + &msg.team_id, + run_id, + &plan_coverage::progress_note(&cov), + ) + .await; + match plan_coverage::next(&cov, plan_coverage::MAX_ROUNDS, false) { + plan_coverage::Next::Complete => {} + plan_coverage::Next::OpenWithOptional => { + plan_optional = plan_coverage::optional_findings(&cov); + } + plan_coverage::Next::Round | plan_coverage::Next::Unfinished => { + let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; + return Err(plan_coverage::stop_reason(&cov, &kept).into()); + } + } + } + // --- Adversarial Test (catches bugs before security/PR) --- check_cancelled(state, &msg.team_id, run_id).await?; if has_time_for_remediation(start) { @@ -4511,11 +4735,21 @@ async fn run_repo_pipeline( provider, file_cache, run_id, + deadline: implement_deadline, }; - let gaps = proof::prove(&work, &mut evidence, usage, || { + let mut gaps = proof::prove(&work, &mut evidence, usage, || { has_time_for_remediation(start) }) .await; + if !proof::planned_work(&gaps).is_empty() { + let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; + return Err(format!( + "{} The work so far is kept on branch `{kept}`.", + proof::unfinished_reason(&gaps) + ) + .into()); + } + gaps.extend(plan_optional); let links = link_checks::gate(&work, &mut evidence, usage, || { has_time_for_remediation(start) }) diff --git a/services/worker/src/passes/plan_coverage.rs b/services/worker/src/passes/plan_coverage.rs new file mode 100644 index 000000000..b2329945e --- /dev/null +++ b/services/worker/src/passes/plan_coverage.rs @@ -0,0 +1,581 @@ +//! Before the first pull request opens, the plan is done: task by task. +//! +//! A complex ticket's plan listed several new files (a block, its schema, +//! its tabs, its tests). The first implement pass changed one file, ran out +//! of its time, and the pipeline went on: the proof check listed what was +//! missing as "gaps ... under Open items" and the pull request opened as if +//! the work were done. Review rounds then tried to build the rest. +//! +//! The plan's task checklist (`- [ ] path: what to do`, which the planner is +//! required to write) is compared with what the branch actually changes, one +//! task at a time ([`coverage`]). Planned tasks that aren't done get another +//! implement round aimed at exactly those tasks while there is time +//! ([`Next::Round`]); a run out of time continues in a fresh invocation from +//! its branch. If tasks the plan needs are still not done, the pull request +//! doesn't open: the run stops with a plain status naming them +//! ([`stop_reason`]). Only tasks the plan itself marks optional may be left +//! out, and the pull request then says so under Open items, with the reason +//! ([`optional_findings`]). + +use tracing::{info, warn}; + +use crate::agent::provider::ModelProvider; +use crate::clients::github::GitHubClient; +use crate::models::{TicketMessage, TokenUsage}; +use crate::passes::plan::PlanResult; +use crate::passes::proof::{Finding, RunEvidence}; +use crate::passes::FileCache; +use crate::WorkerState; + +/// How many extra implement rounds missing planned tasks get in one +/// invocation, before the run continues in a fresh one. +pub const MAX_ROUNDS: u32 = 2; + +/// One task of the plan's checklist. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanTask { + /// The file the task changes (or a directory, ending in `/`). + pub path: String, + /// What the task does, as the plan wrote it. + pub task: String, + /// The task creates the file. + pub is_new: bool, + /// The plan says the task may be left out. + pub optional: bool, +} + +/// Words that mark a task the plan leaves to judgment: never a reason to +/// hold the pull request. +const OPTIONAL_MARKS: &[&str] = &[ + "(optional)", + "optional:", + "if needed", + "if necessary", + "if required", + "nice to have", + "nice-to-have", + "no change needed", + "no changes needed", + "verify only", + "read only", + "read-only", +]; + +fn is_optional(desc: &str) -> bool { + let d = desc.trim().to_lowercase(); + d.starts_with("optional") + || d.starts_with("consider ") + || d.starts_with("maybe ") + || OPTIONAL_MARKS.iter().any(|m| d.contains(m)) +} + +/// Every task of the checklist that names a file, in order. Lines that don't +/// follow the `- [ ] path: description` format are not tasks this check can +/// hold the change to, and are skipped. +pub fn plan_tasks(tasks_md: &str) -> Vec { + let mut out = Vec::new(); + for line in tasks_md.lines() { + let l = line.trim_start(); + let Some(rest) = l + .strip_prefix("- [ ]") + .or_else(|| l.strip_prefix("- [x]")) + .or_else(|| l.strip_prefix("- [X]")) + .or_else(|| l.strip_prefix("* [ ]")) + else { + continue; + }; + let Some((head, desc)) = rest.split_once(':') else { + continue; + }; + let path = head.trim().trim_matches(|c| c == '`' || c == '*').trim(); + let looks_like_path = !path.is_empty() + && path.len() < 300 + && !path.chars().any(char::is_whitespace) + && (path.contains('/') || path.contains('.')) + && !path.contains("://"); + if !looks_like_path { + continue; + } + let d = desc.to_lowercase(); + let is_new = d.contains("create") + || d.contains("new file") + || d.contains("(new)") + || d.trim_start().starts_with("new ") + || d.trim_start().starts_with("add new"); + out.push(PlanTask { + path: path.trim_start_matches("./").to_string(), + task: desc.trim().to_string(), + is_new, + optional: is_optional(desc), + }); + } + out +} + +/// Which planned tasks the branch did and which it didn't. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Coverage { + pub done: Vec, + pub missing: Vec, +} + +impl Coverage { + /// How many tasks the plan has. + pub fn total(&self) -> usize { + self.done.len() + self.missing.len() + } + + /// Tasks the plan needs that aren't done. + pub fn required_missing(&self) -> Vec<&PlanTask> { + self.missing.iter().filter(|t| !t.optional).collect() + } + + /// Tasks the plan marks optional that aren't done. + pub fn optional_missing(&self) -> Vec<&PlanTask> { + self.missing.iter().filter(|t| t.optional).collect() + } +} + +fn norm(p: &str) -> &str { + p.trim().trim_start_matches("./").trim_start_matches('/') +} + +/// Whether the branch changes the task's file (or, for a directory, a file +/// in it). A deleted file shows in the diff too, so a removal counts. +fn path_changed(path: &str, changed: &[String]) -> bool { + let path = norm(path); + if path.ends_with('/') { + return changed.iter().any(|c| norm(c).starts_with(path)); + } + changed.iter().any(|c| norm(c) == path) +} + +/// Each planned task, done when the branch changes its file. Structural, not +/// the coder's account: a task whose file the diff doesn't touch is not done +/// whatever the coder's summary says. +pub fn coverage(tasks: &[PlanTask], changed: &[String]) -> Coverage { + let mut cov = Coverage::default(); + for t in tasks { + if path_changed(&t.path, changed) { + cov.done.push(t.clone()); + } else { + cov.missing.push(t.clone()); + } + } + cov +} + +/// What follows a coverage check. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Next { + /// Every task is done (or the plan has no checklist to hold it to). + Complete, + /// Only tasks the plan marks optional are left: the pull request opens + /// and names them under Open items. + OpenWithOptional, + /// Run another implement round aimed at the missing tasks. + Round, + /// Tasks the plan needs are not done and this invocation has no round + /// left: continue in a fresh invocation, or stop without a pull request. + Unfinished, +} + +/// Decides what follows a coverage check. +pub fn next(cov: &Coverage, rounds_done: u32, has_time: bool) -> Next { + if cov.required_missing().is_empty() { + return if cov.optional_missing().is_empty() { + Next::Complete + } else { + Next::OpenWithOptional + }; + } + if rounds_done < MAX_ROUNDS && has_time { + Next::Round + } else { + Next::Unfinished + } +} + +fn task_line(t: &PlanTask) -> String { + format!("- [ ] `{}`: {}", t.path, t.task) +} + +/// What the coder is told in a round: exactly the tasks still to do. +pub fn round_feedback(cov: &Coverage) -> String { + let todo: Vec = cov.required_missing().into_iter().map(task_line).collect(); + let done: Vec = cov + .done + .iter() + .map(|t| format!("- [x] `{}`", t.path)) + .collect(); + format!( + "The plan is not done yet: the branch doesn't change the file of {} of its {} tasks. \ + Do these tasks now, in order, writing each task's files as soon as that task is done. \ + Read what is already on the branch first and build on it; don't redo finished tasks.\n\n\ + Still to do:\n{}\n\nAlready done on the branch:\n{}", + todo.len(), + cov.total(), + todo.join("\n"), + if done.is_empty() { + "(none)".to_string() + } else { + done.join("\n") + } + ) +} + +/// The run's status when it stops with planned work not done: plain, and +/// naming the tasks (the run record keeps up to 500 characters; the full +/// list is in [`progress_note`]). +pub fn stop_reason(cov: &Coverage, branch: &str) -> String { + let missing = cov.required_missing(); + let paths: Vec = missing.iter().map(|t| format!("`{}`", t.path)).collect(); + let mut list = String::new(); + for (i, p) in paths.iter().enumerate() { + if list.len() + p.len() > 280 { + list.push_str(&format!(" and {} more", paths.len() - i)); + break; + } + if i > 0 { + list.push_str(", "); + } + list.push_str(p); + } + format!( + "Stopped before opening a pull request: {} of {} planned tasks are not done ({list}). \ + The work so far is on branch `{branch}`; Retry continues from the plan.", + missing.len(), + cov.total(), + ) +} + +/// A progress note with every task and whether it's done. +pub fn progress_note(cov: &Coverage) -> String { + let mut lines = vec![format!( + "Plan check: {} of {} planned tasks done", + cov.done.len(), + cov.total() + )]; + for t in &cov.done { + lines.push(format!("- [x] {}", t.path)); + } + for t in &cov.missing { + let note = if t.optional { " (optional)" } else { "" }; + lines.push(format!("- [ ] {}{note}", t.path)); + } + lines.join("\n") +} + +/// The optional tasks left out, as Open items for a person, each with why. +pub fn optional_findings(cov: &Coverage) -> Vec { + cov.optional_missing() + .into_iter() + .map(|t| Finding { + point: "optional_task".to_string(), + detail: format!("`{}`: {}", t.path, t.task), + settle: "The plan marks this task optional, so the pull request opens without it; \ + do it here or in a follow-up if it's wanted." + .to_string(), + ..Default::default() + }) + .collect() +} + +/// The plan's checklist with only the done tasks checked: what the run page +/// and a retry read, instead of every task ticked when the pass ended. +pub fn checked_tasks_md(tasks_md: &str, cov: &Coverage) -> String { + tasks_md + .lines() + .map(|line| { + let done = plan_tasks(line) + .first() + .is_some_and(|t| cov.done.iter().any(|d| d.path == t.path)); + if done { + line.replacen("- [ ]", "- [x]", 1) + } else { + line.to_string() + } + }) + .collect::>() + .join("\n") +} + +/// The files the branch changes against its base, or `None` when GitHub +/// can't say (the check then can't hold the change and steps aside). +pub async fn changed_files( + github: &GitHubClient, + owner: &str, + repo: &str, + base: &str, + branch: &str, +) -> Option> { + match github.get_diff(owner, repo, base, branch).await { + Ok(d) => Some( + d["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| f["filename"].as_str().map(String::from)) + .collect() + }) + .unwrap_or_default(), + ), + Err(e) => { + warn!(error = %e, "Plan check could not read the branch's diff"); + None + } + } +} + +/// Everything a plan round needs, as the pipeline has it. +pub struct Work<'a> { + pub state: &'a WorkerState, + pub msg: &'a TicketMessage, + pub github: &'a GitHubClient, + /// The plan, with this repository's tasks. + pub plan: &'a PlanResult, + pub branch: &'a str, + pub rules: &'a [String], + pub repo_instructions: &'a str, + pub provider: &'a ModelProvider, + pub file_cache: &'a FileCache, + pub run_id: &'a str, + pub deadline: Option, +} + +/// Checks the plan against the branch and runs the implement rounds missing +/// tasks earn while there is time. Returns the coverage it ended with, or +/// `None` when the plan has no checklist or the diff can't be read. +/// `evidence` gains what the rounds looked up. +pub async fn close_gaps( + w: &Work<'_>, + evidence: &mut RunEvidence, + usage: &mut TokenUsage, + has_time: impl Fn() -> bool, +) -> Option { + let tasks = plan_tasks(&w.plan.tasks); + if tasks.is_empty() { + return None; + } + let mut rounds = 0; + loop { + let changed = changed_files( + w.github, + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await?; + let cov = coverage(&tasks, &changed); + info!( + run_id = w.run_id, + done = cov.done.len(), + missing = cov.missing.len(), + rounds, + "Plan check" + ); + if next(&cov, rounds, has_time()) != Next::Round { + return Some(cov); + } + rounds += 1; + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "{}\nWorking on the {} task(s) not done yet (round {rounds})", + progress_note(&cov), + cov.required_missing().len() + ), + ) + .await; + if super::check_cancelled(w.state, &w.msg.team_id, w.run_id) + .await + .is_err() + { + return Some(cov); + } + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; + let pass_start = std::time::Instant::now(); + let usage_before = usage.clone(); + let result = super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&round_feedback(&cov)), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + w.deadline, + // Planned files the PR doesn't change yet are exactly what this + // round must write. + false, + ) + .await; + super::write_pass_trace( + w.state, + &w.msg.team_id, + w.run_id, + "implement:plan_round", + pass_start, + &usage_before, + usage, + None, + ) + .await; + match result { + Ok(r) => { + let timed_out = r.timed_out; + evidence.merge(r.evidence); + if timed_out { + // No time for another round here; what it wrote counts. + rounds = MAX_ROUNDS; + } + } + Err(e) => { + warn!(run_id = w.run_id, error = %e, "Plan round failed"); + rounds = MAX_ROUNDS; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PLAN: &str = "## Tasks\n\ + - [ ] `src/blocks/gallery/index.ts`: Create the gallery block component (new file)\n\ + - [ ] `src/blocks/gallery/schema.ts`: Create the block's schema\n\ + - [ ] `src/blocks/gallery/tabs.tsx`: Add the tabs for each section\n\ + - [ ] `src/blocks/registry.ts`: Register the gallery block\n\ + - [ ] `src/blocks/gallery/index.test.ts`: Add tests for the block\n\ + - [ ] `docs/blocks.md`: (optional) Mention the block in the docs\n\ + - [ ] Run the type-check\n"; + + fn changed(paths: &[&str]) -> Vec { + paths.iter().map(|p| p.to_string()).collect() + } + + #[test] + fn reads_each_task_with_its_file_and_whether_it_is_optional() { + let tasks = plan_tasks(PLAN); + assert_eq!(tasks.len(), 6, "a line without a file is not a task here"); + assert_eq!(tasks[0].path, "src/blocks/gallery/index.ts"); + assert!(tasks[0].is_new); + assert!(!tasks[0].optional); + assert_eq!(tasks[3].task, "Register the gallery block"); + assert!(tasks[5].optional); + for opt in [ + "Optional: add a story", + "Update the README if needed", + "No change needed, just confirm the export", + "consider adding a cache", + ] { + assert!(is_optional(opt), "{opt}"); + } + assert!(!is_optional("Create the block's schema")); + } + + #[test] + fn a_pass_that_changed_one_file_of_a_six_task_plan_is_not_done() { + // The observed run: one file changed, the rest of the plan missing. + let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); + assert_eq!(cov.done.len(), 1); + assert_eq!(cov.required_missing().len(), 4); + assert_eq!(cov.optional_missing().len(), 1); + assert_eq!(next(&cov, 0, true), Next::Round); + assert_eq!(next(&cov, 1, true), Next::Round); + // Out of rounds or time: never "open the PR anyway". + assert_eq!(next(&cov, MAX_ROUNDS, true), Next::Unfinished); + assert_eq!(next(&cov, 0, false), Next::Unfinished); + } + + #[test] + fn only_optional_tasks_left_opens_with_them_named() { + let all_but_docs = changed(&[ + "src/blocks/gallery/index.ts", + "./src/blocks/gallery/schema.ts", + "src/blocks/gallery/tabs.tsx", + "src/blocks/registry.ts", + "src/blocks/gallery/index.test.ts", + ]); + let cov = coverage(&plan_tasks(PLAN), &all_but_docs); + assert_eq!(next(&cov, 0, true), Next::OpenWithOptional); + let items = optional_findings(&cov); + assert_eq!(items.len(), 1); + assert!(items[0].detail.contains("docs/blocks.md")); + assert!(items[0].settle.contains("optional")); + // An optional task is a person's to decide, never a fix round. + assert_eq!(items[0].settler(), crate::passes::proof::Settler::Owner); + + let mut everything = all_but_docs.clone(); + everything.push("docs/blocks.md".into()); + assert_eq!( + next(&coverage(&plan_tasks(PLAN), &everything), 0, true), + Next::Complete + ); + } + + #[test] + fn a_directory_task_is_done_by_any_file_in_it() { + let tasks = plan_tasks("- [ ] `src/blocks/gallery/`: Add the block's files\n"); + assert_eq!(tasks.len(), 1); + let cov = coverage(&tasks, &changed(&["src/blocks/gallery/a.ts"])); + assert!(cov.missing.is_empty()); + let cov = coverage(&tasks, &changed(&["src/blocks/other/a.ts"])); + assert_eq!(cov.missing.len(), 1); + } + + #[test] + fn the_round_is_told_exactly_what_is_left() { + let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); + let fb = round_feedback(&cov); + assert!(fb.contains("src/blocks/gallery/schema.ts")); + assert!(fb.contains("- [x] `src/blocks/registry.ts`")); + // Optional tasks are not pushed on the round. + assert!(!fb.contains("docs/blocks.md")); + assert!(fb.contains("as soon as that task is done")); + } + + #[test] + fn the_stop_status_names_the_missing_tasks_plainly() { + let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); + let r = stop_reason(&cov, "feature/gallery"); + assert!(r.starts_with("Stopped before opening a pull request: 4 of 6 planned tasks")); + assert!(r.contains("`src/blocks/gallery/index.ts`")); + assert!(r.contains("`feature/gallery`")); + assert!(!r.contains("docs/blocks.md")); + assert!(r.len() <= 500, "fits the run record's reason"); + let note = progress_note(&cov); + assert!(note.contains("1 of 6 planned tasks done")); + assert!(note.contains("- [ ] docs/blocks.md (optional)")); + } + + #[test] + fn a_long_list_is_cut_but_counted() { + let plan: String = (0..40) + .map(|i| format!("- [ ] `src/very/long/path/to/module_{i}/file_{i}.ts`: Create it\n")) + .collect(); + let cov = coverage(&plan_tasks(&plan), &[]); + let r = stop_reason(&cov, "b"); + assert!(r.contains("more)")); + assert!(r.len() <= 500); + } + + #[test] + fn only_done_tasks_are_checked_off() { + let cov = coverage(&plan_tasks(PLAN), &changed(&["src/blocks/registry.ts"])); + let md = checked_tasks_md(PLAN, &cov); + assert!(md.contains("- [x] `src/blocks/registry.ts`")); + assert!(md.contains("- [ ] `src/blocks/gallery/schema.ts`")); + assert!(md.contains("- [ ] Run the type-check")); + } +} diff --git a/services/worker/src/passes/proof.rs b/services/worker/src/passes/proof.rs index 2a196ae28..287396a19 100644 --- a/services/worker/src/passes/proof.rs +++ b/services/worker/src/passes/proof.rs @@ -341,8 +341,9 @@ pub struct Finding { /// `assumption`, `structured_field`, `survey`, `silent_fallback`, /// `fixtures`, `one_record`, `team_rule`, `ci_pending`, /// `manual_check`, `pattern_cited`, `end_to_end`, `environment`, - /// `env_unproven`, `near_match_unresolved` or `history_used`; or - /// `unrun_check`, which only [`classify`] sets. + /// `env_unproven`, `near_match_unresolved`, `history_used` or + /// `planned_work`; or `unrun_check`, which only [`classify`] sets, or + /// `optional_task`, which only the plan check sets. pub point: String, /// What is unverified, in one sentence. pub detail: String, @@ -395,7 +396,7 @@ impl Finding { match self.point.trim() { "ci_pending" => Settler::Ci, "manual_check" => Settler::Person, - "end_to_end" => Settler::Owner, + "end_to_end" | "optional_task" => Settler::Owner, _ => Settler::Proof, } } @@ -421,6 +422,8 @@ impl Finding { "env_unproven" => "Environment a lookup hit not proven", "near_match_unresolved" => "Close match not followed up", "history_used" => "Earlier pull requests not built on", + "planned_work" => "Planned work not done", + "optional_task" => "Optional task left out", other => other, } } @@ -678,6 +681,11 @@ pub const JUDGE_SYSTEM: &str = "You check a code change before its pull request 18. history_used: when the plan names earlier pull requests for this ticket, a miss when \ the diff repeats a change a reviewer turned down on one of them, or ignores what the plan \ says it reuses from them.\n\ + 19. planned_work: a task in the plan's task checklist (below the plan) that the diff doesn't \ + do, or does only in part (a file it creates as an empty shell, a step it skips). Name the \ + task and its file. Not a miss for a task the checklist marks optional. Planned work is \ + never a note for later: it is sent back to the coder, and the pull request doesn't open \ + without it.\n\ Many changes touch none of these: a change that relies on nothing outside its own code, \ changes no stored records and adds no logs passes all of them. Judge only what the evidence \ shows and do not invent concerns. A fact the lookups confirm is proven even when the notes \ @@ -686,7 +694,7 @@ pub const JUDGE_SYSTEM: &str = "You check a code change before its pull request exact field, records, log line, assumption or check); `settle` is ONE sentence on how to \ settle it (which connected source to read, what to count, which log to lower, which check \ result). No lists, no preamble, no repeating the rule's text.\n\ - Output ONLY a fenced ```json block: {\"findings\":[{\"point\":\"external_fact|impact|logging|assumption|structured_field|survey|silent_fallback|fixtures|one_record|team_rule|ci_pending|manual_check|pattern_cited|end_to_end|environment|env_unproven|near_match_unresolved|history_used\",\"detail\":\"one sentence\",\"settle\":\"one sentence\",\"check\":\"format|lint|typecheck|build|tests|plan|security, or empty\",\"command\":\"the command the check needs, or empty\",\"ci\":\"the CI command id (C1), or empty\"}]}. \ + Output ONLY a fenced ```json block: {\"findings\":[{\"point\":\"external_fact|impact|logging|assumption|structured_field|survey|silent_fallback|fixtures|one_record|team_rule|ci_pending|manual_check|pattern_cited|end_to_end|environment|env_unproven|near_match_unresolved|history_used|planned_work\",\"detail\":\"one sentence\",\"settle\":\"one sentence\",\"check\":\"format|lint|typecheck|build|tests|plan|security, or empty\",\"command\":\"the command the check needs, or empty\",\"ci\":\"the CI command id (C1), or empty\"}]}. \ An empty list when all pass."; /// The judge's prompt: the change and everything the run gathered. @@ -736,6 +744,9 @@ pub enum Next { FixRound, /// Gaps remain and no round is left: open the PR with them listed under Open items. OpenWithGaps, + /// Planned work is still not done and no round is left: the PR doesn't + /// open. Planned work is never downgraded to an Open item. + Unfinished, } /// Decides what follows a judgment. `None` is a judge that couldn't answer: @@ -745,10 +756,32 @@ pub fn next(findings: Option<&[Finding]>, rounds_done: u32, has_time: bool) -> N match findings.map_or(0, proof_gaps) { 0 => Next::Open, _ if rounds_done < MAX_FIX_ROUNDS && has_time => Next::FixRound, + _ if findings.is_some_and(|f| !planned_work(f).is_empty()) => Next::Unfinished, _ => Next::OpenWithGaps, } } +/// The findings that are planned work not done: never Open items. +pub fn planned_work(findings: &[Finding]) -> Vec<&Finding> { + findings + .iter() + .filter(|f| f.point.trim() == "planned_work") + .collect() +} + +/// Why the run stops when planned work is still not done after its rounds: +/// one plain sentence naming the tasks. +pub fn unfinished_reason(findings: &[Finding]) -> String { + let items: Vec = planned_work(findings) + .iter() + .map(|f| sentence(&f.detail, 120)) + .collect(); + format!( + "Stopped before opening a pull request: the check before it found planned work not done: {}", + items.join("; ") + ) +} + /// How many of `findings` are proof gaps. fn proof_gaps(findings: &[Finding]) -> usize { findings @@ -1166,7 +1199,8 @@ pub fn fix_feedback(findings: &[Finding]) -> String { back, count the affected records and name a few, lower per-record or per-run INFO logs \ to DEBUG, read the structured field instead of a name, survey the live records by \ shape, warn on unexpected shapes, build fixtures from real payloads, fix the rule instead \ - of the record, follow the team's instructions, or change the code so it no longer \ + of the record, follow the team's instructions, do the planned task a `Planned work not \ + done` item names (in full: every file the task needs), or change the code so it no longer \ depends on what you can't prove. When no \ connected source can answer, say which source is missing. Then write your `Evidence:` \ section again in full.\n\n{}", @@ -1252,6 +1286,11 @@ fn plan_context(plan: &PlanResult) -> String { if let Some(d) = &plan.fix { out.push_str(&super::fix_location::reviewer_context(d)); } + // The checklist the change is held to (point 19). + if !plan.tasks.trim().is_empty() { + out.push_str("\n\n### The plan's task checklist\n"); + out.push_str(common::truncate_str(plan.tasks.trim(), 8_000)); + } out } @@ -1337,6 +1376,8 @@ pub struct Work<'a> { pub provider: &'a ModelProvider, pub file_cache: &'a FileCache, pub run_id: &'a str, + /// When the fix round must wrap up (the invocation's deadline). + pub deadline: Option, } /// Judges the change, runs the fix round a gap earns, and judges again. @@ -1397,6 +1438,20 @@ pub async fn prove( // What CI or a person settles still reaches the PR. return findings.unwrap_or_default(); } + Next::Unfinished => { + let gaps = findings.unwrap_or_default(); + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Proof check: {} planned task(s) still not done; the pull request won't open without them", + planned_work(&gaps).len() + ), + ) + .await; + return gaps; + } Next::OpenWithGaps => { let gaps = findings.unwrap_or_default(); super::add_progress_note( @@ -1430,6 +1485,8 @@ pub async fn prove( let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); + // Planned work may need files the branch doesn't change yet. + let scoped = planned_work(&gaps).is_empty(); let fixed = super::implement::run( w.state, w.msg, @@ -1444,8 +1501,8 @@ pub async fn prove( usage, w.file_cache, Some(w.run_id), - None, - true, // bot-driven proof fix — scoped to the PR + w.deadline, + scoped, // bot-driven proof fix — scoped to the PR ) .await; super::write_pass_trace( @@ -2374,6 +2431,66 @@ mod tests { } } +#[cfg(test)] +mod planned_work_tests { + use super::*; + + fn f(point: &str, detail: &str) -> Finding { + Finding { + point: point.into(), + detail: detail.into(), + ..Default::default() + } + } + + #[test] + fn planned_work_gets_a_round_then_holds_the_pr() { + let gaps = vec![ + f( + "planned_work", + "The tabs in src/blocks/gallery/tabs.tsx are not built.", + ), + f("impact", "Records affected were not counted."), + ]; + assert_eq!(next(Some(&gaps), 0, true), Next::FixRound); + // No round left: never "open with the gaps listed". + assert_eq!(next(Some(&gaps), 1, true), Next::Unfinished); + assert_eq!(next(Some(&gaps), 0, false), Next::Unfinished); + // Other gaps alone still open with Open items. + assert_eq!(next(Some(&gaps[1..]), 1, true), Next::OpenWithGaps); + let why = unfinished_reason(&gaps); + assert!(why.starts_with("Stopped before opening a pull request")); + assert!(why.contains("tabs.tsx")); + assert!(!why.contains("Records affected")); + assert_eq!(gaps[0].settler(), Settler::Proof); + assert!(fix_feedback(&gaps).contains("Planned work not done")); + } + + #[test] + fn optional_tasks_are_open_items_for_a_person() { + let opt = f("optional_task", "`docs/x.md`: mention it"); + assert_eq!(opt.settler(), Settler::Owner); + let section = gaps_section(std::slice::from_ref(&opt)); + assert!(section.contains("Optional task left out")); + assert_eq!(next(Some(&[opt]), 1, true), Next::Open); + } + + #[test] + fn the_judge_sees_the_task_checklist() { + let plan = PlanResult { + proposal: "Add a gallery block.".into(), + tasks: "- [ ] `src/a.ts`: Create it".into(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + }; + let ctx = plan_context(&plan); + assert!(ctx.contains("The plan's task checklist")); + assert!(ctx.contains("`src/a.ts`")); + } +} + #[cfg(test)] mod env_near_history_tests { use super::*; @@ -2388,6 +2505,7 @@ mod env_near_history_tests { assert!(JUDGE_SYSTEM.contains("16. env_unproven")); assert!(JUDGE_SYSTEM.contains("17. near_match_unresolved")); assert!(JUDGE_SYSTEM.contains("18. history_used")); + assert!(JUDGE_SYSTEM.contains("19. planned_work")); assert!( JUDGE_SYSTEM.contains("environment|env_unproven|near_match_unresolved|history_used") ); diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index ea33728bb..c46933073 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -11,6 +11,7 @@ use crate::passes::{ attr_n, attr_s, implement, plan, review, save_checkpoint, write_pass_trace, FileCache, }; use crate::WorkerState; +use common::run_round; const MAX_CI_FIX_CYCLES: usize = 10; const MAX_LOG_CHARS: usize = 15_000; @@ -1068,6 +1069,14 @@ pub async fn run( return resume_multi_repo(state, &msg, &pr_urls, created_at).await; } + // A fix round parked for a fresh invocation runs first, with its whole + // budget: its own clock, never the run's. + if let Some(pending) = + run_round::Round::from_item(&run_record).filter(|r| r.state == run_round::State::Pending) + { + return run_pending_round(state, &msg, &run_record, pending, created_at, &start).await; + } + // Wall-clock backstop: the reschedule loop has no cycle cap of its own // (unlike CI fixes), so a check that never concludes would keep a run in // awaiting_ci forever. Past the cap, hand the PR to a human as-is. @@ -1525,71 +1534,28 @@ pub async fn run( return Ok(()); } - // Rehydrate the ticket's design mockups from the run record so the review - // pass (and review-fix implement) can check the code AGAINST the design — - // the empty vec here meant post-CI passes never saw the mockups. - let image_attachments: Vec = run_record - .get("image_attachments") - .and_then(|v| v.as_s().ok()) - .and_then(|s| serde_json::from_str(s).ok()) - .unwrap_or_default(); - - // Build a minimal TicketMessage for the implement/review passes - let ticket_msg = TicketMessage { - team_id: msg.team_id.clone(), - installation_id: msg.installation_id, - source: TicketSource::Github, - ticket_id, - title: title.clone(), - body: String::new(), - repo_owner: repo_owner.clone(), - repo_name: repo_name.clone(), - issue_number, - sender: String::new(), - requester: None, - base_branch: base_branch.clone(), - image_attachments, - continuation: 0, - continuation_run_id: None, - first_attempt_ms: 0, - model_retries: 0, - ticket_update_note: None, - ticket_history_note: None, - plan_cache_key: None, - // Loaded once here; the fix and review rounds below read it from - // the message. - team_instructions: super::load_team_instructions( - state, - &msg.team_id, - &repo_owner, - &repo_name, - ) - .await, - person_direction: None, - answers: Vec::new(), - new_run_id: None, - }; - - let provider = ModelProvider::load_for_team( - &state.dynamo, - &state.config.settings_table_name, - &msg.team_id, + let FixContext { + ticket_msg, + provider, + github, + mut usage, + rules, + repo_instructions, + } = fix_context( + state, + &msg, + &run_record, + &FixTarget { + owner: &repo_owner, + repo: &repo_name, + base_branch: &base_branch, + ticket_id: &ticket_id, + title: &title, + issue_number, + }, ) .await?; - let github = GitHubClient::new( - &state.secrets.github_app_id, - &state.secrets.github_private_key, - msg.installation_id, - &state.http, - )?; - - let mut usage = load_usage_from_checkpoint(state, &msg.team_id, &msg.run_id).await; - - // Load rules and repo instructions so CI fix / review fix have full context - let rules = super::load_rules(state, &ticket_msg).await; - let repo_instructions = super::load_repo_instructions(&github, &repo_owner, &repo_name).await; - // Collect any review feedback (comments on the PR) — useful for both CI fix and review paths let review_feedback = collect_review_feedback(&events); @@ -1891,6 +1857,41 @@ pub async fn run( Full logs:\n{logs}{review_context}{base_note}" ); + // The CI fix is a round of its own (common::run_round): its own + // budget, on the run record while it works, and parked for a fresh + // invocation when this one has too little left to finish it. + let ci_round = run_round::Round::start( + run_round::Kind::CiFix, + (cycle + 1).min(u32::MAX as usize) as u32, + branch_head.as_deref().unwrap_or(""), + &feedback, + review_feedback.is_empty(), + chrono::Utc::now(), + ); + let pr_ref = PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }; + if !super::round::may_start(start, std::time::Instant::now()) { + mark_events_processed(state, &msg.run_id, &events).await; + park_round( + state, + &msg, + (&ticket_msg, &usage), + &pr_ref, + &ci_round, + false, + created_at, + &start, + ) + .await?; + return Ok(()); + } + super::round::record(state, &msg.team_id, &msg.run_id, &ci_round).await; + // The tree before the fix: compared with the tree after it to tell a // fix that changed code from one that only rewrote the same bytes. let tree_before = github @@ -1912,14 +1913,73 @@ pub async fn run( &mut usage, &file_cache, Some(&msg.run_id), - None, + Some(super::round::deadline(start)), // Scope to the PR only when this cycle is purely CI-driven; if // human review comments ride along, the human's ask wins. review_feedback.is_empty(), ) .await { + Ok(result) if result.timed_out => { + // Out of its budget with work left: what it wrote is + // committed; the rest continues in a fresh step, or the run + // says the round didn't finish. + write_pass_trace( + state, + &msg.team_id, + &msg.run_id, + &format!("ci_fix:{}", cycle + 1), + pass_start, + &usage_before, + &usage, + None, + ) + .await; + mark_events_processed(state, &msg.run_id, &events).await; + if ci_round.may_continue() { + park_round( + state, + &msg, + (&ticket_msg, &usage), + &pr_ref, + &ci_round, + true, + created_at, + &start, + ) + .await?; + return Ok(()); + } + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }, + &ci_round, + &run_round::out_of_time(ci_round.kind, ci_round.attempt), + ) + .await; + complete_run_with_status( + state, + &ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + return Ok(()); + } Ok(result) => { + super::round::clear(state, &msg.team_id, &msg.run_id).await; info!( run_id = msg.run_id, files = result.files_modified.len(), @@ -1987,7 +2047,7 @@ pub async fn run( if requeue_after_model_error(state, &msg, &*e).await { return Ok(()); } - error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — completing with PR for human review"); + error!(run_id = msg.run_id, error = %e, "CI fix implementation failed — the PR stays open, the round is named as not finished"); super::webhooks::emit_ci_fix_completed(state, &ci_fix, "failed", 0).await; super::record_ci_outcome( state, @@ -1997,6 +2057,23 @@ pub async fn run( ) .await; mark_events_processed(state, &msg.run_id, &events).await; + // Not "failed", and not handed over as if done: the run says + // the round didn't finish and what it pushed; Resume runs it + // again. + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }, + &ci_round, + &run_round::errored(ci_round.kind, &common::run_fail::error_text(&*e)), + ) + .await; complete_run_with_status( state, &ticket_msg, @@ -2009,15 +2086,6 @@ pub async fn run( wall_clock_secs(created_at, &start), ) .await?; - mark_pr_ready( - state, - &msg.team_id, - &github, - &repo_owner, - &repo_name, - pr_number, - ) - .await; return Ok(()); } } @@ -2441,83 +2509,65 @@ pub async fn run( run_id = msg.run_id, "Review found issues — implementing fix" ); - super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; - let pass_start = std::time::Instant::now(); - let usage_before = usage.clone(); - - match implement::run( - state, - &ticket_msg, - &github, - &plan_result, - &branch, - &rules, - &repo_instructions, - Some(&review_result.summary), - "medium", - &provider, - &mut usage, - &file_cache, - Some(&msg.run_id), - None, + // The fix is a round of its own: its own budget, parked for a + // fresh invocation when the review used most of this one, and + // never a failed run when it can't finish. + let base_sha = + super::round::branch_head(&github, &repo_owner, &repo_name, &branch).await; + let fix_round = run_round::Round::start( + run_round::Kind::ReviewFix, + (cycle + 1).min(u32::MAX as usize) as u32, + &base_sha, + &review_result.summary, // Bot self-review fix — scoped, unless human comments were // folded into the review context. review_feedback.is_empty(), - ) - .await - { - Ok(result) => { - write_pass_trace( + chrono::Utc::now(), + ); + let mut ctx = FixContext { + ticket_msg, + provider, + github, + usage, + rules, + repo_instructions, + }; + let pr = PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }; + let end = + run_fix_round(state, &msg, &mut ctx, &pr, fix_round, created_at, &start).await?; + mark_events_processed(state, &msg.run_id, &events).await; + match end { + RoundEnd::Parked => return Ok(()), + RoundEnd::Incomplete => { + complete_run_with_status( state, - &msg.team_id, + &ctx.ticket_msg, &msg.run_id, - "implement:review_fix", - pass_start, - &usage_before, - &usage, - None, + "completed", + &pr_url, + pr_number, + &branch, + &ctx.usage, + wall_clock_secs(created_at, &start), ) - .await; - - if result.files_modified.is_empty() { - warn!( - run_id = msg.run_id, - "Review fix produced no changes — completing anyway" - ); - mark_pr_ready( - state, - &msg.team_id, - &github, - &repo_owner, - &repo_name, - pr_number, - ) - .await; - complete_run_with_status( - state, - &ticket_msg, - &msg.run_id, - "completed", - &pr_url, - pr_number, - &branch, - &usage, - wall_clock_secs(created_at, &start), - ) - .await?; - return Ok(()); - } + .await?; + return Ok(()); } - Err(e) => { - if requeue_after_model_error(state, &msg, &*e).await { - return Ok(()); - } - error!(run_id = msg.run_id, error = %e, "Review fix implementation failed"); - // Still mark PR ready, let human review + RoundEnd::Done { files: 0 } => { + warn!( + run_id = msg.run_id, + "Review fix produced no changes — completing anyway" + ); mark_pr_ready( state, &msg.team_id, - &github, + &ctx.github, &repo_owner, &repo_name, pr_number, @@ -2525,18 +2575,19 @@ pub async fn run( .await; complete_run_with_status( state, - &ticket_msg, + &ctx.ticket_msg, &msg.run_id, "completed", &pr_url, pr_number, &branch, - &usage, + &ctx.usage, wall_clock_secs(created_at, &start), ) .await?; return Ok(()); } + RoundEnd::Done { .. } => {} } // Back to awaiting_ci for the next CI run. Increment the shared @@ -2548,18 +2599,17 @@ pub async fn run( "pr", &branch, (cycle + 1).min(u8::MAX as usize) as u8, - &usage, + &ctx.usage, ) .await; - mark_events_processed(state, &msg.run_id, &events).await; let still_active = set_run_awaiting_ci( state, - &ticket_msg, + &ctx.ticket_msg, &msg.run_id, &pr_url, pr_number, &branch, - &usage, + &ctx.usage, wall_clock_secs(created_at, &start), ) .await?; @@ -2568,6 +2618,7 @@ pub async fn run( if still_active { send_delayed_resume(state, &msg, 120).await; } + return Ok(()); } } @@ -2603,6 +2654,508 @@ pub async fn run( Ok(()) } +/// What a fix round on the run's pull request works with. +struct FixContext { + ticket_msg: TicketMessage, + provider: ModelProvider, + github: GitHubClient, + usage: TokenUsage, + rules: Vec, + repo_instructions: String, +} + +/// The pull request's repository and ticket, read from the run record. +struct FixTarget<'a> { + owner: &'a str, + repo: &'a str, + base_branch: &'a str, + ticket_id: &'a str, + title: &'a str, + issue_number: u64, +} + +/// Loads what a fix round needs: the ticket (with its design mockups), the +/// team's model provider, GitHub, the run's usage so far, rules and the +/// repository's instructions. +async fn fix_context( + state: &WorkerState, + msg: &ResumeMessage, + run_record: &std::collections::HashMap, + t: &FixTarget<'_>, +) -> Result> { + // Rehydrate the ticket's design mockups from the run record so the review + // pass (and review-fix implement) can check the code AGAINST the design — + // the empty vec here meant post-CI passes never saw the mockups. + let image_attachments: Vec = run_record + .get("image_attachments") + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok()) + .unwrap_or_default(); + + // Build a minimal TicketMessage for the implement/review passes + let ticket_msg = TicketMessage { + team_id: msg.team_id.clone(), + installation_id: msg.installation_id, + source: TicketSource::Github, + ticket_id: t.ticket_id.to_string(), + title: t.title.to_string(), + body: String::new(), + repo_owner: t.owner.to_string(), + repo_name: t.repo.to_string(), + issue_number: t.issue_number, + sender: String::new(), + requester: None, + base_branch: t.base_branch.to_string(), + image_attachments, + continuation: 0, + continuation_run_id: None, + first_attempt_ms: 0, + model_retries: 0, + ticket_update_note: None, + ticket_history_note: None, + plan_cache_key: None, + // Loaded once here; the fix and review rounds read it from the + // message. + team_instructions: super::load_team_instructions(state, &msg.team_id, t.owner, t.repo) + .await, + person_direction: None, + answers: Vec::new(), + new_run_id: None, + }; + + let provider = ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + ) + .await?; + + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + + let usage = load_usage_from_checkpoint(state, &msg.team_id, &msg.run_id).await; + + // Load rules and repo instructions so CI fix / review fix have full context + let rules = super::load_rules(state, &ticket_msg).await; + let repo_instructions = super::load_repo_instructions(&github, t.owner, t.repo).await; + Ok(FixContext { + ticket_msg, + provider, + github, + usage, + rules, + repo_instructions, + }) +} + +/// The run's pull request, as a round needs it. +struct PrRef<'a> { + owner: &'a str, + repo: &'a str, + branch: &'a str, + number: u64, + url: &'a str, +} + +/// How a round's invocation ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RoundEnd { + /// The round's work is done; `files` changed. + Done { files: usize }, + /// Parked: it continues in a fresh invocation with its own budget. + Parked, + /// It can't finish: the run is completed with the round named as not + /// finished, and Resume can run it again. + Incomplete, +} + +/// Parks a round for a fresh invocation: the run waits (awaiting_ci) with +/// the round on its record, and a resume picks it up first thing. +#[allow(clippy::too_many_arguments)] +async fn park_round( + state: &WorkerState, + msg: &ResumeMessage, + ctx: (&TicketMessage, &TokenUsage), + pr: &PrRef<'_>, + round: &run_round::Round, + next_attempt: bool, + created_at: Option>, + start: &std::time::Instant, +) -> Result> { + let parked = round.parked(next_attempt); + super::round::record(state, &msg.team_id, &msg.run_id, &parked).await; + let note = if next_attempt { + format!( + "The {} (fix {}) used its time budget with work left; it continues in a fresh step with its own budget (step {} of {}).", + round.kind.label(), + round.number, + parked.attempt, + run_round::MAX_ATTEMPTS + ) + } else { + format!( + "The {} (fix {}) starts in a fresh step so it gets its whole time budget.", + round.kind.label(), + round.number + ) + }; + super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; + let still_active = set_run_awaiting_ci( + state, + ctx.0, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + ctx.1, + wall_clock_secs(created_at, start), + ) + .await?; + if still_active { + send_delayed_resume(state, msg, 5).await; + } + Ok(RoundEnd::Parked) +} + +/// Runs one fix round's implement inside its own budget. A round that would +/// start with too little of this invocation left, or that uses its budget +/// with work left, is parked for a fresh invocation (bounded by +/// `run_round::MAX_ATTEMPTS`); a round that can't finish leaves the run +/// completed with the pull request open and says what it pushed. +#[allow(clippy::too_many_arguments)] +async fn run_fix_round( + state: &WorkerState, + msg: &ResumeMessage, + ctx: &mut FixContext, + pr: &PrRef<'_>, + round: run_round::Round, + created_at: Option>, + start: &std::time::Instant, +) -> Result> { + if !super::round::may_start(*start, std::time::Instant::now()) { + return park_round( + state, + msg, + (&ctx.ticket_msg, &ctx.usage), + pr, + &round, + false, + created_at, + start, + ) + .await; + } + // A round resumed by a person starts from the branch as it is now. + let mut round = round; + if round.base_sha.is_empty() { + round.base_sha = super::round::branch_head(&ctx.github, pr.owner, pr.repo, pr.branch).await; + } + super::round::record(state, &msg.team_id, &msg.run_id, &round).await; + super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; + let feedback = if round.attempt > 1 { + format!( + "{}\n\n## CONTINUING THIS ROUND\nAn earlier step of this round ran out of time; \ + everything it wrote is already committed on the branch. Read the files you need \ + first, then finish only what is left.", + round.feedback + ) + } else { + round.feedback.clone() + }; + let plan_result = plan::PlanResult { + proposal: String::new(), + tasks: String::new(), + spec: String::new(), + design: String::new(), + repo_tasks: vec![], + fix: None, + }; + let pass_start = std::time::Instant::now(); + let usage_before = ctx.usage.clone(); + let result = implement::run( + state, + &ctx.ticket_msg, + &ctx.github, + &plan_result, + pr.branch, + &ctx.rules, + &ctx.repo_instructions, + Some(&feedback), + "medium", + &ctx.provider, + &mut ctx.usage, + &FileCache::default(), + Some(&msg.run_id), + Some(super::round::deadline(*start)), + round.scoped, + ) + .await; + write_pass_trace( + state, + &msg.team_id, + &msg.run_id, + &format!("{}:{}", round.kind.as_str(), round.number), + pass_start, + &usage_before, + &ctx.usage, + None, + ) + .await; + let gh = super::round::Pr { + github: &ctx.github, + owner: pr.owner, + repo: pr.repo, + branch: pr.branch, + }; + match result { + Ok(r) if r.timed_out => { + if round.may_continue() { + park_round( + state, + msg, + (&ctx.ticket_msg, &ctx.usage), + pr, + &round, + true, + created_at, + start, + ) + .await + } else { + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + &round, + &run_round::out_of_time(round.kind, round.attempt), + ) + .await; + Ok(RoundEnd::Incomplete) + } + } + Ok(r) => { + super::round::clear(state, &msg.team_id, &msg.run_id).await; + Ok(RoundEnd::Done { + files: r.files_modified.len(), + }) + } + Err(e) => { + let err: &(dyn std::error::Error + 'static) = &*e; + // A transient model failure is another step of the same round + // (bounded by its attempts), not the round failing. + if common::model_retry::is_transient_model_error(err) && round.may_continue() { + warn!(run_id = msg.run_id, error = %e, "Fix round hit a transient model error — continuing in a fresh step"); + return park_round( + state, + msg, + (&ctx.ticket_msg, &ctx.usage), + pr, + &round, + true, + created_at, + start, + ) + .await; + } + error!(run_id = msg.run_id, error = %e, "Fix round failed"); + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + &round, + &run_round::errored(round.kind, &common::run_fail::error_text(err)), + ) + .await; + Ok(RoundEnd::Incomplete) + } + } +} + +/// A parked round, picked up by a fresh invocation with its whole budget: +/// it runs before anything else the resume would do. +async fn run_pending_round( + state: &WorkerState, + msg: &ResumeMessage, + run_record: &std::collections::HashMap, + pending: run_round::Round, + created_at: Option>, + start: &std::time::Instant, +) -> Result<(), Box> { + let text = |k: &str| { + run_record + .get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let num = |k: &str| { + run_record + .get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0) + }; + let repo_full = text("repo"); + let (owner, repo) = repo_full.split_once('/').unwrap_or(("", "")); + let branch = text("branch"); + let pr_number = num("pr_number"); + let pr_url = text("pr_url"); + if owner.is_empty() || branch.is_empty() || pr_number == 0 { + warn!( + run_id = msg.run_id, + "Parked round on a run without its pull request — dropping it" + ); + super::round::clear(state, &msg.team_id, &msg.run_id).await; + return Ok(()); + } + // Claim the run, as every resume that works does. + let claimed = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(&msg.team_id)) + .key("run_id", attr_s(&msg.run_id)) + .update_expression( + "SET #s = :new_s, status_run_id = :sri, current_pass = :cp, updated_at = :t", + ) + .condition_expression("#s = :expected") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":expected", attr_s("awaiting_ci")) + .expression_attribute_values(":new_s", attr_s("running")) + .expression_attribute_values(":sri", attr_s(&format!("running#{}", msg.run_id))) + .expression_attribute_values(":cp", attr_s("implement")) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .send() + .await + .is_ok(); + if !claimed { + info!( + run_id = msg.run_id, + "Could not claim the run for its parked round, skipping" + ); + return Ok(()); + } + let base_branch = run_record + .get("base_branch") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_else(|| "main".to_string()); + let mut ctx = fix_context( + state, + msg, + run_record, + &FixTarget { + owner, + repo, + base_branch: &base_branch, + ticket_id: &text("ticket_id"), + title: &text("title"), + issue_number: num("issue_number"), + }, + ) + .await?; + let pr = PrRef { + owner, + repo, + branch: &branch, + number: pr_number, + url: &pr_url, + }; + info!( + run_id = msg.run_id, + kind = pending.kind.as_str(), + number = pending.number, + attempt = pending.attempt, + "Running a parked fix round with its own budget" + ); + let round = pending.resumed(chrono::Utc::now()); + let kind = round.kind; + let number = round.number; + match run_fix_round(state, msg, &mut ctx, &pr, round, created_at, start).await? { + RoundEnd::Parked => {} + RoundEnd::Incomplete => { + complete_run_with_status( + state, + &ctx.ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await?; + } + RoundEnd::Done { files: 0 } => { + if kind == run_round::Kind::CiFix { + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::HandedOff(super::GaveUp::NoChange), + ) + .await; + } + mark_pr_ready(state, &msg.team_id, &ctx.github, owner, repo, pr_number).await; + complete_run_with_status( + state, + &ctx.ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await?; + } + RoundEnd::Done { .. } => { + if kind == run_round::Kind::CiFix { + super::record_ci_outcome( + state, + &msg.team_id, + &msg.run_id, + super::CiOutcome::FixCommitted, + ) + .await; + } + save_checkpoint( + state, + &msg.team_id, + &msg.run_id, + "pr", + &branch, + number.min(u8::MAX as u32) as u8, + &ctx.usage, + ) + .await; + let still_active = set_run_awaiting_ci( + state, + &ctx.ticket_msg, + &msg.run_id, + &pr_url, + pr_number, + &branch, + &ctx.usage, + wall_clock_secs(created_at, start), + ) + .await?; + if still_active { + send_delayed_resume(state, msg, 120).await; + } + } + } + Ok(()) +} + async fn load_unprocessed_events( state: &WorkerState, run_id: &str, @@ -3113,11 +3666,13 @@ async fn set_run_awaiting_ci( tokens_in = :ti, tokens_out = :to, cache_read_tokens = :crt, cache_write_tokens = :cwt, \ cost_usd = :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri \ - REMOVE error_message, #err", + REMOVE error_message, #err, #inc", ) .condition_expression(common::run_status::not_ended("#s")) .expression_attribute_names("#s", "status") .expression_attribute_names("#err", "error") + // A round is being worked again: its earlier "didn't finish" is over. + .expression_attribute_names("#inc", run_round::INCOMPLETE_FIELD) .ended_values() .expression_attribute_values(":s", attr_s("awaiting_ci")) .expression_attribute_values(":pr", attr_s(pr_url)) diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs new file mode 100644 index 000000000..9064db73e --- /dev/null +++ b/services/worker/src/passes/round.rs @@ -0,0 +1,281 @@ +//! The worker's side of fix rounds (see `common::run_round`): each round on +//! an open pull request runs inside its own budget, is written on the run +//! record while it works, continues in a fresh invocation when it runs out +//! of time, and when it can't finish leaves the run completed with the pull +//! request open and a plain account of what the round pushed. + +use std::time::{Duration, Instant}; + +use common::run_round::{self, Incomplete, Kind, Round}; +use common::run_status::EndedValues; +use tracing::{info, warn}; + +use super::attr_s; +use crate::clients::github::GitHubClient; +use crate::WorkerState; + +/// When a round that starts in an invocation begun at `invocation_start` +/// must wrap up: its own budget, never the run's age. +pub(crate) fn deadline(invocation_start: Instant) -> Instant { + invocation_start + Duration::from_secs(run_round::BUDGET_SECS) +} + +/// Seconds left before that deadline. +pub(crate) fn secs_left(invocation_start: Instant, now: Instant) -> u64 { + deadline(invocation_start) + .saturating_duration_since(now) + .as_secs() +} + +/// Whether a round may start now, or should be parked for a fresh +/// invocation with its whole budget. +pub(crate) fn may_start(invocation_start: Instant, now: Instant) -> bool { + secs_left(invocation_start, now) >= run_round::MIN_START_SECS +} + +/// The branch head, for what a round pushes after it ("" when unknown). +pub(crate) async fn branch_head( + github: &GitHubClient, + owner: &str, + repo: &str, + branch: &str, +) -> String { + github + .get_ref(owner, repo, branch) + .await + .unwrap_or_default() +} + +/// Writes the round on the run record. A new round also clears an earlier +/// round's "didn't finish": it is being worked again. +pub(crate) async fn record(state: &WorkerState, team_id: &str, run_id: &str, round: &Round) { + let first = round.attempt <= 1; + let expr = if first { + "SET #round = :r, updated_at = :t REMOVE #inc" + } else { + "SET #round = :r, updated_at = :t" + }; + let mut req = 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(expr) + .condition_expression(common::run_status::not_ended("#s")) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#round", run_round::FIELD) + .expression_attribute_values(":r", round.to_attr()) + .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) + .ended_values(); + if first { + req = req.expression_attribute_names("#inc", run_round::INCOMPLETE_FIELD); + } + if let Err(e) = req.send().await { + if !common::run_fail::is_condition_failed(&e) { + warn!(run_id, error = %e, "Could not record the fix round"); + } + } +} + +/// Removes the round from the run record: it finished. +pub(crate) async fn clear(state: &WorkerState, team_id: &str, run_id: &str) { + let _ = 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("REMOVE #round") + .expression_attribute_names("#round", run_round::FIELD) + .send() + .await; +} + +/// What the round pushed since it started, read from the branch. +async fn pushed( + github: &GitHubClient, + owner: &str, + repo: &str, + base_sha: &str, + branch: &str, +) -> (Vec, Vec) { + if base_sha.is_empty() { + return (Vec::new(), Vec::new()); + } + match github.get_diff(owner, repo, base_sha, branch).await { + Ok(compare) => run_round::pushed_from_compare(&compare), + Err(e) => { + warn!(error = %e, "Could not read what the round pushed"); + (Vec::new(), Vec::new()) + } + } +} + +/// Where a round's pull request is. +pub(crate) struct Pr<'a> { + pub github: &'a GitHubClient, + pub owner: &'a str, + pub repo: &'a str, + pub branch: &'a str, +} + +/// Leaves the run completed with its pull request open, saying the round +/// didn't finish, why, and the commits it pushed. Never a failed run: the +/// pull request is there and Resume runs the round again. +pub(crate) async fn finish_incomplete( + state: &WorkerState, + team_id: &str, + run_id: &str, + pr: &Pr<'_>, + round: &Round, + reason: &str, +) -> Incomplete { + let now = chrono::Utc::now().to_rfc3339(); + let mut inc = Incomplete::of(round, reason, &now); + let (commits, files) = pushed(pr.github, pr.owner, pr.repo, &round.base_sha, pr.branch).await; + inc.pushed = commits; + inc.files = files; + // The caller completes the run (with its usage) and says so. + write_incomplete(state, team_id, run_id, &inc).await; + super::add_progress_note( + state, + team_id, + run_id, + &format!( + "{} {}", + inc.status_line(), + run_round::pushed_note(&inc.pushed, &inc.files) + ), + ) + .await; + warn!( + run_id, + reason, "Fix round didn't finish; the pull request stays open" + ); + inc +} + +/// The write: completed, with the round that didn't finish, never over a +/// run a person ended. +async fn write_incomplete( + state: &WorkerState, + team_id: &str, + run_id: &str, + inc: &Incomplete, +) -> bool { + let res = 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 #s = :s, status_run_id = :sri, #inc = :inc, current_pass = :cp, updated_at = :t \ + REMOVE #round, error_message, #err", + ) + .condition_expression(common::run_status::not_ended("#s")) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#inc", run_round::INCOMPLETE_FIELD) + .expression_attribute_names("#round", run_round::FIELD) + .expression_attribute_names("#err", "error") + .expression_attribute_values(":s", attr_s(common::run_status::COMPLETED)) + .expression_attribute_values( + ":sri", + attr_s(&format!("{}#{run_id}", common::run_status::COMPLETED)), + ) + .expression_attribute_values(":inc", inc.to_attr()) + .expression_attribute_values(":cp", attr_s("done")) + .expression_attribute_values(":t", attr_s(&inc.at)) + .ended_values() + .send() + .await; + match res { + Ok(_) => true, + Err(e) if common::run_fail::is_condition_failed(&e) => { + info!(run_id, "Run was ended by a person — leaving it"); + false + } + Err(e) => { + warn!(run_id, error = %e, "Could not record the unfinished round"); + false + } + } +} + +/// After a round's worker failed outright (an error the pass returned): +/// when the run has an open pull request, it is left completed with the +/// round named as not finished instead of failed. Returns false when the +/// run has no pull request (a real failure, for the caller to record) or +/// was ended already. +pub(crate) async fn end_unfinished( + state: &WorkerState, + team_id: &str, + run_id: &str, + kind: Kind, + error: &str, + only_running: bool, +) -> bool { + let item = match state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .consistent_read(true) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .send() + .await + { + Ok(r) => r.item.unwrap_or_default(), + Err(_) => return false, + }; + let num = |k: &str| { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0) + }; + let status = item + .get("status") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + if num("pr_number") == 0 + || (only_running && status != common::run_status::RUNNING) + || matches!( + status.as_str(), + "merged" | "cancelled" | "closed" | "retried" | "archived" | "failed" + ) + { + return false; + } + let round = Round::from_item(&item) + .unwrap_or_else(|| Round::start(kind, 0, "", "", true, chrono::Utc::now())); + let now = chrono::Utc::now().to_rfc3339(); + let inc = Incomplete::of(&round, &run_round::errored(round.kind, error), &now); + if write_incomplete(state, team_id, run_id, &inc).await { + super::webhooks::emit_run(state, team_id, run_id, "completed").await; + } + super::add_progress_note(state, team_id, run_id, &inc.status_line()).await; + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_round_starts_only_with_enough_of_its_budget_left() { + let start = Instant::now(); + assert!(may_start(start, start)); + assert_eq!(secs_left(start, start), run_round::BUDGET_SECS); + // After the review used most of the invocation, the fix round is + // parked for a fresh one instead of being killed half way. + let late = start + Duration::from_secs(run_round::BUDGET_SECS - 60); + assert!(!may_start(start, late)); + let edge = start + Duration::from_secs(run_round::BUDGET_SECS - run_round::MIN_START_SECS); + assert!(may_start(start, edge)); + // Past the deadline: nothing left, never a wrap-around. + assert_eq!(secs_left(start, start + Duration::from_secs(5_000)), 0); + } +} From 0d0488f7366f48b68da597b72cf68728bf846cee Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 12:35:17 -0400 Subject: [PATCH 2/5] Generated files are part of the change: regenerate before the PR, or block it A pull request in a web repository changed its CMS schema files but not the types generated from them; the repository has a type generation script and the reviewer had to point it out. generators.rs finds the generators a repository uses and what each reads and writes: package scripts named like typegen/codegen/generate/gen:types (mapped to the tool they run), Sanity typegen config, GraphQL codegen config (YAML or TS: schema, documents, generates), OpenAPI client generators (spec in, -o out), Prisma, buf/protobuf, and "regenerate after changing X" rules in AGENTS.md, CLAUDE.md or CONTRIBUTING. Before the pull request opens (single and multi-repo), each generator whose inputs the diff touches runs in the sandbox and its output is committed with the change, in the team's commit style. A generator still out of date (its known outputs not in the change, or its run failing) gets one fix round, then stops the run with a plain reason naming the files and the generator; the work is kept on the WIP branch. The coder's run_codegen tool falls back to every detected generator when the repo has no codegen script. Tests use small fixture repos per kind: npm-script typegen with Sanity config, GraphQL codegen in YAML and in TS through a nested script, OpenAPI, Prisma, buf and a documented rule. --- services/worker/src/passes/generators.rs | 1229 ++++++++++++++++++++++ services/worker/src/passes/implement.rs | 20 +- services/worker/src/passes/mod.rs | 61 ++ 3 files changed, 1308 insertions(+), 2 deletions(-) create mode 100644 services/worker/src/passes/generators.rs diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs new file mode 100644 index 000000000..8cc1d7b4b --- /dev/null +++ b/services/worker/src/passes/generators.rs @@ -0,0 +1,1229 @@ +//! Generated files are regenerated before the pull request opens. +//! +//! A pull request in a web repository changed its CMS schema files but not the +//! types generated from them; the repository has a type generation script, +//! and the reviewer had to point out the missing typegen. Generated output is +//! part of a complete change. +//! +//! This module finds the generators a repository uses ([`detect`]): package +//! scripts named like typegen/codegen/generate, Sanity typegen config, GraphQL +//! codegen config, OpenAPI client generators, Prisma, protobuf (buf), and any +//! rule the repository documents ("regenerate after changing X" in AGENTS.md +//! or CONTRIBUTING). Each comes with the inputs it reads and, where known, the +//! files it writes (globs). When the diff touches a generator's inputs, the +//! generator runs in the sandbox and its output is committed with the change +//! ([`gate`]). Before the pull request opens, a generator whose inputs changed +//! while its outputs did not (or whose run still changes tracked files) blocks +//! it with a plain reason, after one fix round. + +use std::collections::HashMap; + +use tracing::{info, warn}; + +use crate::clients::github::{FileOp, GitHubClient}; +use crate::passes::plan_coverage::Work; + +/// The tool a generator runs (a package script counts as the tool it runs). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GenKind { + Sanity, + GraphqlCodegen, + Prisma, + OpenApi, + Protobuf, + /// A rule the repository's docs state. + Documented, +} + +/// One generator, the files it reads and the files it writes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Generator { + pub kind: GenKind, + /// How a person reads it (`npm run typegen`, `graphql-codegen`). + pub name: String, + /// The command that regenerates, run from the repository root after the + /// dependencies are installed. + pub command: String, + /// Globs of the files it reads. + pub inputs: Vec, + /// Globs of the files it writes (empty when unknown). + pub outputs: Vec, +} + +// ── Globs ───────────────────────────────────────────────────────────────── + +fn expand_braces(p: &str) -> Vec { + let (Some(open), Some(close)) = (p.find('{'), p.find('}')) else { + return vec![p.to_string()]; + }; + if close < open { + return vec![p.to_string()]; + } + let (head, rest) = (&p[..open], &p[close + 1..]); + p[open + 1..close] + .split(',') + .flat_map(|alt| expand_braces(&format!("{head}{alt}{rest}"))) + .collect() +} + +fn seg_match(pat: &[char], s: &[char]) -> bool { + match (pat.first(), s.first()) { + (None, None) => true, + (Some('*'), _) => seg_match(&pat[1..], s) || (!s.is_empty() && seg_match(pat, &s[1..])), + (Some('?'), Some(_)) => seg_match(&pat[1..], &s[1..]), + (Some(a), Some(b)) if a == b => seg_match(&pat[1..], &s[1..]), + _ => false, + } +} + +fn parts_match(pat: &[&str], path: &[&str]) -> bool { + match pat.first() { + None => path.is_empty(), + Some(&"**") => (0..=path.len()).any(|i| parts_match(&pat[1..], &path[i..])), + Some(p) => { + !path.is_empty() + && seg_match( + &p.chars().collect::>(), + &path[0].chars().collect::>(), + ) + && parts_match(&pat[1..], &path[1..]) + } + } +} + +fn clean(p: &str) -> &str { + p.trim().trim_start_matches("./").trim_start_matches('/') +} + +/// Whether `path` matches the glob (`**`, `*`, `?`, `{a,b}`). A pattern that +/// names a directory (ends in `/`) matches everything under it. +pub fn glob_match(pattern: &str, path: &str) -> bool { + let path = clean(path); + expand_braces(clean(pattern)).iter().any(|p| { + let p = if p.ends_with('/') { + format!("{p}**") + } else { + p.clone() + }; + let pat: Vec<&str> = p.split('/').filter(|s| !s.is_empty()).collect(); + let parts: Vec<&str> = path.split('/').collect(); + parts_match(&pat, &parts) + }) +} + +fn any_match(globs: &[String], path: &str) -> bool { + globs.iter().any(|g| glob_match(g, path)) +} + +/// A glob relative to `dir` (a nested package's directory), as a path from +/// the repository root. +fn under(dir: &str, glob: &str) -> String { + let g = clean(glob); + if dir.is_empty() { + g.to_string() + } else { + format!("{dir}/{g}") + } +} + +// ── What the repository holds ─────────────────────────────────────────────── + +/// The repository's file list and the text of the files detection reads. +#[derive(Debug, Clone, Default)] +pub struct RepoFiles { + pub tree: Vec, + pub files: HashMap, +} + +const CODEGEN_CONFIGS: &[&str] = &[ + "codegen.yml", + "codegen.yaml", + "codegen.ts", + "codegen.js", + "codegen.json", + ".graphqlrc.yml", + ".graphqlrc.yaml", +]; +const DOC_FILES: &[&str] = &[ + "AGENTS.md", + "CLAUDE.md", + "CONTRIBUTING.md", + ".github/CONTRIBUTING.md", + "docs/CONTRIBUTING.md", +]; + +fn base_name(p: &str) -> &str { + p.rsplit('/').next().unwrap_or(p) +} + +fn dir_of(p: &str) -> &str { + p.rsplit_once('/').map(|(d, _)| d).unwrap_or("") +} + +/// The files of `tree` detection reads: package manifests (not under +/// node_modules, at most three folders deep), generator configs and the +/// contribution docs. +pub fn candidate_files(tree: &[String]) -> Vec { + tree.iter() + .filter(|p| !p.contains("node_modules/") && p.matches('/').count() <= 3) + .filter(|p| { + let b = base_name(p); + b == "package.json" + || b == "sanity-typegen.json" + || b == "schema.prisma" + || b == "buf.gen.yaml" + || b == "openapitools.json" + || CODEGEN_CONFIGS.contains(&b) + || DOC_FILES.contains(&p.as_str()) + }) + .cloned() + .collect() +} + +// ── Config readers (no YAML/TS parser: the few keys these configs use) ────── + +fn indent(line: &str) -> usize { + line.len() - line.trim_start().len() +} + +fn unquote(s: &str) -> String { + s.trim() + .trim_end_matches(',') + .trim() + .trim_matches(|c| c == '\'' || c == '"' || c == '`') + .to_string() +} + +/// The quoted strings in `text`. +fn quoted(text: &str) -> Vec { + let mut out = Vec::new(); + let mut cur: Option<(char, String)> = None; + for c in text.chars() { + match &mut cur { + Some((q, s)) if c == *q => { + out.push(std::mem::take(s)); + cur = None; + } + Some((_, s)) => s.push(c), + None if matches!(c, '\'' | '"' | '`') => cur = Some((c, String::new())), + None => {} + } + } + out +} + +/// The text of `key`'s value: what follows `key:` on its line and every more +/// indented line after it. +fn section<'a>(text: &'a str, key: &str) -> Option> { + let lines: Vec<&str> = text.lines().collect(); + for (i, line) in lines.iter().enumerate() { + let t = line.trim_start(); + let t = t.trim_start_matches(['\'', '"']); + let Some(rest) = t.strip_prefix(key) else { + continue; + }; + let rest = rest.trim_start_matches(['\'', '"']); + let Some(rest) = rest.strip_prefix(':') else { + continue; + }; + let ind = indent(line); + let mut out = vec![rest]; + for l in &lines[i + 1..] { + if l.trim().is_empty() { + continue; + } + if indent(l) <= ind && !l.trim_start().starts_with(['-', ']', '}']) { + break; + } + if indent(l) <= ind && l.trim_start().starts_with(['}', ']']) { + break; + } + out.push(l); + } + return Some(out); + } + None +} + +/// The values of a key that holds a path or a list of paths (YAML inline, +/// YAML list, or a JS/JSON string or array). +fn values(text: &str, key: &str) -> Vec { + let Some(sec) = section(text, key) else { + return Vec::new(); + }; + let joined = sec.join("\n"); + let mut out = quoted(&joined); + if out.is_empty() { + let first = unquote(sec[0]); + if !first.is_empty() && !first.starts_with(['[', '{']) { + out.push(first); + } + for l in &sec[1..] { + if let Some(v) = l.trim_start().strip_prefix("- ") { + out.push(unquote(v)); + } + } + } + out.into_iter() + .filter(|v| !v.is_empty() && !v.contains("://") && !v.contains(' ')) + .collect() +} + +/// The first-level keys under `key` (codegen's `generates:` map). +fn child_keys(text: &str, key: &str) -> Vec { + let Some(sec) = section(text, key) else { + return Vec::new(); + }; + let child_indent = sec[1..].iter().map(|l| indent(l)).min(); + let mut out = Vec::new(); + for l in &sec[1..] { + if Some(indent(l)) != child_indent { + continue; + } + let t = l.trim(); + let k = if t.starts_with(['\'', '"', '`']) { + quoted(t).into_iter().next() + } else { + t.split_once(':').map(|(k, _)| k.trim().to_string()) + }; + if let Some(k) = k.filter(|k| !k.is_empty() && (k.contains('/') || k.contains('.'))) { + out.push(k); + } + } + out +} + +// ── Detection ───────────────────────────────────────────────────────────── + +/// Script names that regenerate something. +fn is_generator_script(name: &str) -> bool { + let n = name.to_lowercase(); + matches!( + n.as_str(), + "typegen" + | "codegen" + | "generate" + | "gen" + | "gen:types" + | "generate:types" + | "types:generate" + ) || n.contains("typegen") + || n.contains("codegen") + || n.starts_with("generate:") + || n.starts_with("gen:") + || n.ends_with(":generate") + || n.ends_with(":codegen") +} + +fn sanity_globs(dir: &str, files: &HashMap) -> (Vec, Vec) { + let cfg = files.get(&under(dir, "sanity-typegen.json")); + let mut inputs: Vec = [ + "**/schemaTypes/**", + "**/schemas/**", + "**/schema/**", + "**/sanity.config.*", + ] + .iter() + .map(|g| under(dir, g)) + .collect(); + let mut outputs = vec![under(dir, "**/sanity.types.ts")]; + if let Some(v) = cfg.and_then(|c| serde_json::from_str::(c).ok()) { + if let Some(p) = v["path"].as_str() { + inputs.push(under(dir, p)); + } + if let Some(g) = v["generates"].as_str() { + outputs = vec![under(dir, g)]; + } + if let Some(s) = v["schema"].as_str() { + outputs.push(under(dir, s)); + } + } + (inputs, outputs) +} + +fn codegen_globs(path: &str, text: &str) -> (Vec, Vec) { + let dir = dir_of(path); + let mut inputs: Vec = values(text, "schema") + .iter() + .chain(values(text, "documents").iter()) + .map(|g| under(dir, g)) + .collect(); + inputs.push(path.to_string()); + let outputs = child_keys(text, "generates") + .iter() + .map(|g| under(dir, g)) + .collect(); + (inputs, outputs) +} + +fn prisma_globs(dir: &str, tree: &[String]) -> (Vec, Vec) { + let schemas: Vec = tree + .iter() + .filter(|p| base_name(p) == "schema.prisma" && (dir.is_empty() || p.starts_with(dir))) + .cloned() + .collect(); + let inputs = if schemas.is_empty() { + vec![under(dir, "**/schema.prisma")] + } else { + schemas + }; + (inputs, Vec::new()) +} + +/// Paths an OpenAPI generator's command names: its spec (input) and the +/// file or folder after `-o`/`--output` (output). +fn openapi_globs(dir: &str, cmd: &str) -> (Vec, Vec) { + let words: Vec<&str> = cmd.split_whitespace().collect(); + let mut inputs = Vec::new(); + let mut outputs = Vec::new(); + for (i, w) in words.iter().enumerate() { + let w = unquote(w); + let prev = if i > 0 { words[i - 1] } else { "" }; + if matches!(prev, "-o" | "--output" | "--out" | "-O") { + outputs.push(under(dir, &w)); + } else if (w.ends_with(".yaml") || w.ends_with(".yml") || w.ends_with(".json")) + && !w.contains("://") + { + inputs.push(under(dir, &w)); + } + } + (inputs, outputs) +} + +/// The inputs and outputs a script's command points to, by the tool it runs. +fn script_globs( + dir: &str, + cmd: &str, + repo: &RepoFiles, +) -> Option<(GenKind, Vec, Vec)> { + let c = cmd.to_lowercase(); + if c.contains("sanity") && (c.contains("typegen") || c.contains("schema extract")) { + let (i, o) = sanity_globs(dir, &repo.files); + return Some((GenKind::Sanity, i, o)); + } + if c.contains("graphql-codegen") || c.contains("gql-gen") { + let cfg = CODEGEN_CONFIGS + .iter() + .map(|n| under(dir, n)) + .find(|p| repo.files.contains_key(p))?; + let (i, o) = codegen_globs(&cfg, &repo.files[&cfg]); + return Some((GenKind::GraphqlCodegen, i, o)); + } + if c.contains("prisma generate") { + let (i, o) = prisma_globs(dir, &repo.tree); + return Some((GenKind::Prisma, i, o)); + } + if c.contains("openapi") || c.contains("orval") || c.contains("swagger") { + let (i, o) = openapi_globs(dir, cmd); + return (!i.is_empty()).then_some((GenKind::OpenApi, i, o)); + } + if c.contains("buf generate") || c.contains("protoc") { + return Some(( + GenKind::Protobuf, + vec![under(dir, "**/*.proto")], + Vec::new(), + )); + } + None +} + +/// A rule the docs state: a line that says to regenerate (or run a command) +/// after changing something, with the command and the paths in backticks. +fn documented(doc: &str) -> Vec { + let mut out = Vec::new(); + for line in doc.lines() { + let l = line.to_lowercase(); + let says = l.contains("regenerat") + || ((l.contains("run ") || l.contains("re-run")) + && (l.contains("after") + || l.contains("whenever") + || l.contains("when you change"))); + if !says { + continue; + } + let ticks: Vec = line + .split('`') + .enumerate() + .filter(|(i, _)| i % 2 == 1) + .map(|(_, t)| t.trim().to_string()) + .collect(); + let starts = [ + "npm ", + "pnpm ", + "yarn ", + "npx ", + "bun ", + "make ", + "buf ", + "go generate", + "just ", + ]; + let Some(command) = ticks + .iter() + .find(|t| starts.iter().any(|s| t.starts_with(s))) + .cloned() + else { + continue; + }; + let inputs: Vec = ticks + .iter() + .filter(|t| **t != command && !t.contains(' ') && (t.contains('/') || t.contains('*'))) + .map(|t| clean(t).to_string()) + .collect(); + if !inputs.is_empty() { + out.push(Generator { + kind: GenKind::Documented, + name: command.clone(), + command, + inputs, + outputs: Vec::new(), + }); + } + } + out +} + +/// The package manager's install and run words for the repository. +fn package_manager(tree: &[String]) -> (&'static str, &'static str) { + if tree.iter().any(|p| p == "pnpm-lock.yaml") { + ( + "corepack enable && pnpm install --frozen-lockfile", + "pnpm run", + ) + } else if tree.iter().any(|p| p == "yarn.lock") { + ("corepack enable && yarn install --frozen-lockfile", "yarn") + } else if tree.iter().any(|p| p == "bun.lockb" || p == "bun.lock") { + ("bun install --frozen-lockfile", "bun run") + } else { + ("npm ci --no-audit --no-fund", "npm run") + } +} + +/// The repository's generators, scripts first; a config a script already +/// runs is not counted twice. +pub fn detect(repo: &RepoFiles) -> Vec { + let (_, run) = package_manager(&repo.tree); + let mut out: Vec = Vec::new(); + let mut manifests: Vec<&String> = repo + .files + .keys() + .filter(|p| base_name(p) == "package.json") + .collect(); + manifests.sort(); + for path in manifests { + let Ok(pkg) = serde_json::from_str::(&repo.files[path]) else { + continue; + }; + let dir = dir_of(path); + let Some(scripts) = pkg["scripts"].as_object() else { + continue; + }; + let mut names: Vec<&String> = scripts.keys().collect(); + names.sort(); + for name in names { + if !is_generator_script(name) { + continue; + } + let cmd = scripts[name].as_str().unwrap_or(""); + let Some((kind, inputs, outputs)) = script_globs(dir, cmd, repo) else { + continue; + }; + let command = if dir.is_empty() { + format!("{run} {name}") + } else { + format!("cd {dir} && {run} {name}") + }; + // The kind is the tool the script runs, so its config isn't + // counted again below. + out.push(Generator { + kind, + name: command.clone(), + command, + inputs, + outputs, + }); + } + } + let covered = |out: &[Generator], kind: GenKind| out.iter().any(|g| g.kind == kind); + let mut configs: Vec<&String> = repo.files.keys().collect(); + configs.sort(); + for path in configs { + let dir = dir_of(path); + let text = &repo.files[path]; + let b = base_name(path); + if CODEGEN_CONFIGS.contains(&b) && !covered(&out, GenKind::GraphqlCodegen) { + let (inputs, outputs) = codegen_globs(path, text); + out.push(Generator { + kind: GenKind::GraphqlCodegen, + name: "graphql-codegen".into(), + command: format!("npx graphql-codegen --config {path}"), + inputs, + outputs, + }); + } else if b == "sanity-typegen.json" && !covered(&out, GenKind::Sanity) { + let (inputs, outputs) = sanity_globs(dir, &repo.files); + out.push(Generator { + kind: GenKind::Sanity, + name: "sanity typegen".into(), + command: if dir.is_empty() { + "npx sanity schema extract && npx sanity typegen generate".into() + } else { + format!("cd {dir} && npx sanity schema extract && npx sanity typegen generate") + }, + inputs, + outputs, + }); + } else if b == "schema.prisma" && !covered(&out, GenKind::Prisma) { + out.push(Generator { + kind: GenKind::Prisma, + name: "prisma generate".into(), + command: format!("npx prisma generate --schema {path}"), + inputs: vec![path.clone()], + outputs: Vec::new(), + }); + } else if b == "buf.gen.yaml" && !covered(&out, GenKind::Protobuf) { + out.push(Generator { + kind: GenKind::Protobuf, + name: "buf generate".into(), + command: if dir.is_empty() { + "npx --yes @bufbuild/buf generate".into() + } else { + format!("cd {dir} && npx --yes @bufbuild/buf generate") + }, + inputs: vec![under(dir, "**/*.proto")], + outputs: child_keys(text, "plugins") + .into_iter() + .chain(values(text, "out")) + .map(|o| under(dir, &format!("{}/", o.trim_end_matches('/')))) + .collect(), + }); + } else if DOC_FILES.contains(&path.as_str()) { + for g in documented(text) { + if !out.iter().any(|o| o.command == g.command) { + out.push(g); + } + } + } + } + out +} + +/// The full command for the sandbox: install, then the generator. +pub fn sandbox_command(tree: &[String], g: &Generator) -> String { + let (install, _) = package_manager(tree); + let needs_node = g.command.starts_with("npm ") + || g.command.starts_with("pnpm ") + || g.command.starts_with("yarn") + || g.command.starts_with("bun ") + || g.command.starts_with("npx ") + || g.command.contains("&& npx ") + || g.command.contains("&& npm ") + || g.command.contains("&& pnpm ") + || g.command.contains("&& yarn"); + if needs_node && tree.iter().any(|p| p == "package.json") { + format!("{install} && {}", g.command) + } else { + g.command.clone() + } +} + +/// One command that runs every generator the repository has, for the +/// coder's run_codegen tool: dependencies installed once, then each +/// generator in its own subshell from the repository root. `None` when it +/// has none. +pub fn all_command(repo: &RepoFiles) -> Option { + let gens = detect(repo); + if gens.is_empty() { + return None; + } + let (install, _) = package_manager(&repo.tree); + let runs: Vec = gens.iter().map(|g| format!("({})", g.command)).collect(); + let node = gens + .iter() + .any(|g| sandbox_command(&repo.tree, g) != g.command); + Some(if node { + format!("{install} && {}", runs.join(" && ")) + } else { + runs.join(" && ") + }) +} + +/// The generators whose inputs the change touches, with those files. A file +/// the generator itself writes is not an input change. +pub fn affected<'a>( + gens: &'a [Generator], + changed: &[String], +) -> Vec<(&'a Generator, Vec)> { + gens.iter() + .filter_map(|g| { + let hits: Vec = changed + .iter() + .filter(|c| any_match(&g.inputs, c) && !any_match(&g.outputs, c)) + .cloned() + .collect(); + (!hits.is_empty()).then_some((g, hits)) + }) + .collect() +} + +/// The generator's known outputs are not in the change. +pub fn outputs_missing(g: &Generator, changed: &[String]) -> bool { + !g.outputs.is_empty() && !changed.iter().any(|c| any_match(&g.outputs, c)) +} + +fn list(items: &[String], max: usize) -> String { + let mut s: Vec = items.iter().take(max).map(|i| format!("`{i}`")).collect(); + if items.len() > max { + s.push(format!("{} more", items.len() - max)); + } + s.join(", ") +} + +/// Why the pull request doesn't open, in a sentence. +pub fn block_reason(g: &Generator, inputs: &[String], why: &str) -> String { + format!( + "The change edits {} (read by `{}`), but {why}", + list(inputs, 3), + g.name + ) +} + +/// The one fix round's instructions. +pub fn fix_feedback(problems: &[(Generator, Vec, String)]) -> String { + let lines: Vec = problems + .iter() + .map(|(g, inputs, why)| { + format!( + "- `{}` reads {} and {why} Regenerate its output{}: call run_codegen when it is \ + offered, otherwise update the generated files ({}) exactly as the generator \ + would.", + g.name, + list(inputs, 3), + if g.outputs.is_empty() { + String::new() + } else { + format!(" ({})", list(&g.outputs, 3)) + }, + if g.outputs.is_empty() { + "the files it writes".to_string() + } else { + list(&g.outputs, 3) + } + ) + }) + .collect(); + format!( + "The change edits files a code generator reads, and the generated files are not up to \ + date. Generated output is part of the change:\n{}", + lines.join("\n") + ) +} + +// ── Async: read the repo, run, check ──────────────────────────────────────── + +/// Reads what detection needs from the repository at `git_ref`. +pub async fn load(github: &GitHubClient, owner: &str, repo: &str, git_ref: &str) -> RepoFiles { + let tree: Vec = match github.get_tree(owner, repo, git_ref).await { + Ok(t) => t + .into_iter() + .filter(|e| e.entry_type == "blob") + .map(|e| e.path) + .collect(), + Err(e) => { + warn!(error = %e, "Generator check could not read the tree"); + return RepoFiles::default(); + } + }; + let mut files = HashMap::new(); + for p in candidate_files(&tree).into_iter().take(40) { + if let Ok(text) = github.read_file(owner, repo, &p, git_ref).await { + files.insert(p, text); + } + } + RepoFiles { tree, files } +} + +/// What a sandbox run of a generator came to. +enum Ran { + /// It ran; these files changed (committed when there were any). + Regenerated(Vec), + Failed(String), + /// The sandbox isn't set up, is out of time, or the team's policy holds + /// the command. + NotRun(String), +} + +async fn run_in_sandbox(w: &Work<'_>, repo: &RepoFiles, g: &Generator, attempt: usize) -> Ran { + let state = w.state; + if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { + return Ran::NotRun("no sandbox".into()); + } + let cmd = sandbox_command(&repo.tree, g); + let gate = crate::agent::policy::gate( + state, + w.provider.scope.ctx(common::agent_policy::Agent::Coder), + w.deadline, + ); + match gate.check_command(&cmd, "Regenerate generated files").await { + common::agent_policy::Outcome::Run { .. } => {} + _ => return Ran::NotRun("the team's agent permissions hold this command".into()), + } + let sandbox = crate::clients::sandbox::SandboxClient::new( + &state.codebuild, + &state.s3, + &state.logs, + &state.config.sandbox_bucket_name, + &state.config.sandbox_project_name, + ) + .with_egress(crate::agent::policy::sandbox_egress(state, &w.msg.team_id).await); + if !sandbox.has_time(w.deadline) { + return Ran::NotRun("not enough time left".into()); + } + let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); + let head = match w.github.get_ref(owner, name, w.branch).await { + Ok(h) => h, + Err(e) => return Ran::NotRun(format!("branch head unreadable: {e}")), + }; + let source = match sandbox + .ensure_source(w.run_id, &head, || { + w.github.download_tarball(owner, name, &head) + }) + .await + { + Ok(s) => s, + Err(e) => return Ran::NotRun(format!("snapshot failed: {e}")), + }; + let node = super::detect_node_version(w.github, owner, name, w.branch).await; + let env = super::load_codegen_env(state, &w.msg.team_id, owner, name).await; + match sandbox + .run_codegen( + w.run_id, + 100 + attempt, + &source, + &cmd, + node.as_deref(), + &env, + w.deadline, + ) + .await + { + Ok(o) if o.ran && o.passed => { + if o.changed.is_empty() { + return Ran::Regenerated(Vec::new()); + } + let paths: Vec = o.changed.iter().map(|(p, _)| p.clone()).collect(); + let ops: Vec = o + .changed + .into_iter() + .map(|(path, content)| FileOp::Write { path, content }) + .collect(); + let conventions = + super::load_git_conventions(state, &w.msg.team_id, &w.msg.ticket_id).await; + let message = conventions.commit_message( + &super::ticket_tokens(w.msg), + &format!("Regenerate generated files ({})", g.name), + ); + match w + .github + .batch_write(owner, name, w.branch, &message, &ops) + .await + { + Ok(_) => Ran::Regenerated(paths), + Err(e) => Ran::Failed(format!("its output couldn't be committed ({e})")), + } + } + Ok(o) if o.ran => Ran::Failed(format!( + "running it failed: {}", + common::truncate_str(o.output.trim(), 300) + )), + Ok(o) => Ran::NotRun(o.output), + Err(e) => Ran::NotRun(e.to_string()), + } +} + +/// One pass over the affected generators: regenerate in the sandbox when it +/// can, and name each one still out of date. +async fn regenerate( + w: &Work<'_>, + attempt: usize, + notes: &mut Vec, +) -> Option, String)>> { + let repo = load(w.github, &w.msg.repo_owner, &w.msg.repo_name, w.branch).await; + let gens = detect(&repo); + if gens.is_empty() { + return None; + } + let mut changed = super::plan_coverage::changed_files( + w.github, + &w.msg.repo_owner, + &w.msg.repo_name, + &w.msg.base_branch, + w.branch, + ) + .await?; + let hits: Vec<(Generator, Vec)> = affected(&gens, &changed) + .into_iter() + .map(|(g, i)| (g.clone(), i)) + .collect(); + let mut problems = Vec::new(); + for (i, (g, inputs)) in hits.into_iter().enumerate() { + match run_in_sandbox(w, &repo, &g, attempt * 10 + i).await { + Ran::Regenerated(paths) => { + if paths.is_empty() { + notes.push(format!( + "`{}` ran; the generated files were already up to date", + g.name + )); + } else { + notes.push(format!( + "`{}` regenerated {} file(s) and they were committed", + g.name, + paths.len() + )); + changed.extend(paths); + } + } + Ran::Failed(why) => problems.push((g, inputs, format!("{why}."))), + Ran::NotRun(why) => { + info!(generator = %g.name, why, "Generator not run in the sandbox"); + if outputs_missing(&g, &changed) { + problems.push(( + g.clone(), + inputs, + format!( + "its generated files ({}) were not regenerated.", + list(&g.outputs, 3) + ), + )); + } else { + notes.push(format!( + "`{}` reads changed files and couldn't be run here ({why}); check its output", + g.name + )); + } + } + } + } + Some(problems) +} + +/// Before the pull request: generators whose inputs changed are run and +/// their output committed; one still out of date gets one fix round, then +/// blocks the pull request with a plain reason. Returns notes for the PR's +/// progress, or the reason. +pub async fn gate( + w: &Work<'_>, + usage: &mut crate::models::TokenUsage, +) -> Result, String> { + let mut notes = Vec::new(); + let Some(problems) = regenerate(w, 0, &mut notes).await else { + return Ok(notes); + }; + if problems.is_empty() { + return Ok(notes); + } + super::add_progress_note( + w.state, + &w.msg.team_id, + w.run_id, + &format!( + "Generated files out of date for {}: one fix round", + problems + .iter() + .map(|(g, _, _)| format!("`{}`", g.name)) + .collect::>() + .join(", ") + ), + ) + .await; + let _ = super::update_pass(w.state, &w.msg.team_id, w.run_id, "implement").await; + if let Err(e) = super::implement::run( + w.state, + w.msg, + w.github, + w.plan, + w.branch, + w.rules, + w.repo_instructions, + Some(&fix_feedback(&problems)), + "medium", + w.provider, + usage, + w.file_cache, + Some(w.run_id), + w.deadline, + // Generated files may not be in the PR yet. + false, + ) + .await + { + warn!(run_id = w.run_id, error = %e, "Generator fix round failed"); + } + let mut notes2 = Vec::new(); + let still = regenerate(w, 1, &mut notes2).await.unwrap_or_default(); + notes.extend(notes2); + match still.first() { + None => Ok(notes), + Some((g, inputs, why)) => Err(format!( + "Stopped before opening a pull request: {}", + block_reason(g, inputs, why) + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(files: &[(&str, &str)], extra_tree: &[&str]) -> RepoFiles { + let mut tree: Vec = files.iter().map(|(p, _)| p.to_string()).collect(); + tree.extend(extra_tree.iter().map(|p| p.to_string())); + RepoFiles { + tree, + files: files + .iter() + .map(|(p, t)| (p.to_string(), t.to_string())) + .collect(), + } + } + + fn changed(p: &[&str]) -> Vec { + p.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn globs() { + assert!(glob_match( + "**/schemaTypes/**", + "studio/schemaTypes/blocks/hero.ts" + )); + assert!(glob_match("src/**/*.{ts,tsx}", "src/a/b/c.tsx")); + assert!(!glob_match("src/**/*.{ts,tsx}", "src/a/b/c.js")); + assert!(glob_match("./schema.graphql", "schema.graphql")); + assert!(glob_match("src/gql/", "src/gql/graphql.ts")); + assert!(glob_match("**/*.proto", "api/v1/user.proto")); + assert!(!glob_match("*.ts", "src/a.ts")); + } + + /// The observed case: a CMS schema changed, the typegen script exists, + /// the generated types didn't change. + #[test] + fn npm_script_typegen_fixture() { + let r = repo( + &[ + ( + "package.json", + r#"{"scripts":{"dev":"next dev","typegen":"sanity schema extract && sanity typegen generate"}}"#, + ), + ( + "sanity-typegen.json", + r#"{"path":"./src/**/*.{ts,tsx}","schema":"schema.json","generates":"./src/sanity.types.ts"}"#, + ), + ], + &[ + "pnpm-lock.yaml", + "src/sanity.types.ts", + "studio/schemaTypes/blocks/gallery.ts", + ], + ); + let gens = detect(&r); + assert_eq!(gens.len(), 1, "{gens:?}"); + let g = &gens[0]; + assert_eq!(g.kind, GenKind::Sanity); + assert_eq!(g.command, "pnpm run typegen"); + assert_eq!( + sandbox_command(&r.tree, g), + "corepack enable && pnpm install --frozen-lockfile && pnpm run typegen" + ); + let diff = changed(&[ + "studio/schemaTypes/blocks/gallery.ts", + "studio/schemaTypes/index.ts", + ]); + let hit = affected(&gens, &diff); + assert_eq!(hit.len(), 1); + assert_eq!(hit[0].1.len(), 2); + assert!(outputs_missing(g, &diff)); + let why = block_reason(g, &hit[0].1, "its generated files were not regenerated."); + assert!(why.contains("`pnpm run typegen`")); + assert!(why.contains("gallery.ts")); + // Regenerated: nothing missing. + let mut with_types = diff.clone(); + with_types.push("src/sanity.types.ts".into()); + assert!(!outputs_missing(g, &with_types)); + // A change that touches no input affects nothing. + assert!(affected(&gens, &changed(&["README.md"])).is_empty()); + // Editing only the generated file is not an input change. + assert!(affected(&gens, &changed(&["src/sanity.types.ts"])).is_empty()); + } + + #[test] + fn graphql_codegen_yaml_fixture() { + let yml = "overwrite: true\nschema: \"schema.graphql\"\ndocuments:\n - \"src/**/*.graphql\"\n - \"src/queries/**/*.ts\"\ngenerates:\n src/gql/graphql.ts:\n plugins:\n - typescript\n ./src/gql/introspection.json:\n plugins:\n - introspection\n"; + let r = repo( + &[("codegen.yml", yml)], + &["schema.graphql", "package-lock.json"], + ); + let gens = detect(&r); + assert_eq!(gens.len(), 1); + let g = &gens[0]; + assert_eq!(g.kind, GenKind::GraphqlCodegen); + assert!( + g.inputs.contains(&"schema.graphql".to_string()), + "{:?}", + g.inputs + ); + assert!(g.inputs.contains(&"src/**/*.graphql".to_string())); + assert_eq!( + g.outputs, + vec!["src/gql/graphql.ts", "src/gql/introspection.json"] + ); + let diff = changed(&["src/queries/user.ts"]); + assert_eq!(affected(&gens, &diff).len(), 1); + assert!(outputs_missing(g, &diff)); + assert!(!outputs_missing( + g, + &changed(&["src/queries/user.ts", "src/gql/graphql.ts"]) + )); + assert!(sandbox_command(&r.tree, g).contains("npx graphql-codegen --config codegen.yml")); + } + + #[test] + fn graphql_codegen_ts_fixture_through_a_script() { + let ts = "import type { CodegenConfig } from '@graphql-codegen/cli';\n\nconst config: CodegenConfig = {\n schema: 'https://api.example.com/graphql',\n documents: ['app/**/*.tsx', 'lib/**/*.ts'],\n generates: {\n './lib/gql/': {\n preset: 'client',\n },\n },\n};\nexport default config;\n"; + let r = repo( + &[ + ( + "web/package.json", + r#"{"scripts":{"codegen":"graphql-codegen --config codegen.ts"}}"#, + ), + ("web/codegen.ts", ts), + ], + &[], + ); + let gens = detect(&r); + assert_eq!(gens.len(), 1, "{gens:?}"); + let g = &gens[0]; + assert_eq!(g.command, "cd web && npm run codegen"); + // A remote schema is not a file input; the documents are. + assert!( + g.inputs.contains(&"web/app/**/*.tsx".to_string()), + "{:?}", + g.inputs + ); + assert!(!g.inputs.iter().any(|i| i.contains("https"))); + assert_eq!(g.outputs, vec!["web/lib/gql/"]); + assert_eq!(affected(&gens, &changed(&["web/app/page.tsx"])).len(), 1); + assert!(!outputs_missing( + g, + &changed(&["web/app/page.tsx", "web/lib/gql/graphql.ts"]) + )); + } + + #[test] + fn prisma_openapi_protobuf_and_documented_rules() { + let r = repo( + &[ + ("package.json", r#"{"scripts":{"generate:api":"openapi-typescript spec/openapi.yaml -o src/api/schema.d.ts","db:generate":"prisma generate"}}"#), + ("prisma/schema.prisma", "model User { id Int @id }"), + ("proto/buf.gen.yaml", "version: v2\nplugins:\n - remote: buf.build/protocolbuffers/go\n out: gen/go\n"), + ("AGENTS.md", "## Rules\n- Regenerate the client with `make client` after changing `api/spec/**`.\n- Use tabs.\n"), + ], + &[], + ); + let gens = detect(&r); + let by = |k: GenKind| gens.iter().find(|g| g.kind == k).cloned(); + let api = gens + .iter() + .find(|g| g.command.contains("generate:api")) + .unwrap(); + assert_eq!(api.inputs, vec!["spec/openapi.yaml"]); + assert_eq!(api.outputs, vec!["src/api/schema.d.ts"]); + let prisma = gens + .iter() + .find(|g| g.command.contains("db:generate")) + .unwrap(); + assert_eq!(prisma.inputs, vec!["prisma/schema.prisma"]); + // The script already runs prisma: the schema file isn't a second one. + assert_eq!(gens.iter().filter(|g| g.kind == GenKind::Prisma).count(), 1); + let buf = by(GenKind::Protobuf).unwrap(); + assert_eq!(buf.inputs, vec!["proto/**/*.proto"]); + assert_eq!(buf.outputs, vec!["proto/gen/go/"]); + let doc = by(GenKind::Documented).unwrap(); + assert_eq!(doc.command, "make client"); + assert_eq!(doc.inputs, vec!["api/spec/**"]); + assert_eq!(affected(&gens, &changed(&["api/spec/users.yaml"])).len(), 1); + // Unknown outputs never block on their own; the sandbox run decides. + assert!(!outputs_missing(&doc, &changed(&["api/spec/users.yaml"]))); + assert_eq!(sandbox_command(&r.tree, &doc), "make client"); + } + + #[test] + fn scripts_that_generate_nothing_known_are_not_guessed() { + let r = repo( + &[( + "package.json", + r#"{"scripts":{"generate":"node scripts/sitemap.js","build":"next build"}}"#, + )], + &[], + ); + assert!(detect(&r).is_empty()); + assert!(is_generator_script("gen:types")); + assert!(is_generator_script("sanity:typegen")); + assert!(!is_generator_script("build")); + } + + #[test] + fn only_manifests_configs_and_docs_are_read() { + let tree = changed(&[ + "package.json", + "node_modules/x/package.json", + "apps/studio/package.json", + "apps/studio/sanity-typegen.json", + "codegen.yml", + "AGENTS.md", + "src/index.ts", + ]); + let c = candidate_files(&tree); + assert!(c.contains(&"apps/studio/sanity-typegen.json".to_string())); + assert!(!c.iter().any(|p| p.contains("node_modules"))); + assert!(!c.contains(&"src/index.ts".to_string())); + } + + #[test] + fn run_codegen_runs_every_generator_from_the_root() { + let r = repo( + &[ + ( + "codegen.yml", + "schema: schema.graphql\ngenerates:\n src/gql.ts:\n plugins: []\n", + ), + ("prisma/schema.prisma", "model A { id Int @id }"), + ], + &["package.json", "package-lock.json"], + ); + assert_eq!( + all_command(&r).unwrap(), + "npm ci --no-audit --no-fund && (npx graphql-codegen --config codegen.yml) && (npx prisma generate --schema prisma/schema.prisma)" + ); + assert!(all_command(&RepoFiles::default()).is_none()); + } + + #[test] + fn the_fix_round_names_the_generator_and_its_outputs() { + let g = Generator { + kind: GenKind::Documented, + name: "npm run typegen".into(), + command: "npm run typegen".into(), + inputs: vec!["schemas/**".into()], + outputs: vec!["sanity.types.ts".into()], + }; + let fb = fix_feedback(&[( + g, + vec!["schemas/a.ts".into()], + "its generated files were not regenerated.".into(), + )]); + assert!(fb.contains("`npm run typegen`")); + assert!(fb.contains("run_codegen")); + assert!(fb.contains("`sanity.types.ts`")); + } +} diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 008c1975f..17541531c 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -348,8 +348,24 @@ pub async fn run( None }; let codegen_cmd = if sandbox.is_some() { - super::detect_codegen_command(github, &msg.repo_owner, &msg.repo_name, &msg.base_branch) - .await + match super::detect_codegen_command( + github, + &msg.repo_owner, + &msg.repo_name, + &msg.base_branch, + ) + .await + { + Some(cmd) => Some(cmd), + // Generators found from their configs and the repo's docs + // (GraphQL codegen, Prisma, buf, documented rules): run_codegen + // runs every one of them. + None => { + let repo = + super::generators::load(github, &msg.repo_owner, &msg.repo_name, branch).await; + super::generators::all_command(&repo) + } + } } else { None }; diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index dbe0d62f1..30a3d6918 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -699,6 +699,7 @@ pub mod email_events; pub mod feedback; pub mod fix_location; pub mod formatter; +pub(crate) mod generators; pub mod github_history; pub mod health_check; pub mod hidden_suggest; @@ -4061,6 +4062,37 @@ async fn run_passes( // --- Proof check (before PR — what the change rests on is proven) --- check_cancelled(state, &msg.team_id, run_id).await?; update_pass(state, &msg.team_id, run_id, "review").await?; + // --- Generated files: regenerated with the change, or the PR waits --- + match generators::gate( + &plan_coverage::Work { + state, + msg, + github: &github, + plan: &plan_result, + branch: &branch_name, + rules: &rules, + repo_instructions: &repo_instructions, + provider: &provider, + file_cache: &file_cache, + run_id, + deadline: implement_deadline, + }, + usage, + ) + .await + { + Ok(notes) => { + for n in notes { + add_progress_note(state, &msg.team_id, run_id, &n).await; + } + } + Err(why) => { + let kept = + keep_wip_branch(&github, &msg.repo_owner, &msg.repo_name, &branch_name).await; + close_memory(state, agent_memory.take()).await; + return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); + } + } let mut evidence = impl_result.evidence.clone(); let work = proof::Work { state, @@ -4722,6 +4754,35 @@ async fn run_repo_pipeline( // --- Proof check --- check_cancelled(state, &msg.team_id, run_id).await?; + // Generated files: regenerated with the change, or this repo's PR waits. + match generators::gate( + &plan_coverage::Work { + state, + msg, + github, + plan: &repo_plan, + branch: branch_name, + rules, + repo_instructions, + provider, + file_cache, + run_id, + deadline: implement_deadline, + }, + usage, + ) + .await + { + Ok(notes) => { + for n in notes { + add_progress_note(state, &msg.team_id, run_id, &n).await; + } + } + Err(why) => { + let kept = keep_wip_branch(github, repo_owner, repo_name, branch_name).await; + return Err(format!("{why} The work so far is kept on branch `{kept}`.").into()); + } + } update_pass(state, &msg.team_id, run_id, "review").await?; let mut evidence = impl_result.evidence.clone(); let work = proof::Work { From e2c5175f192e5a1f25d0bd4234dc9fff68b0fda7 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 13:04:56 -0400 Subject: [PATCH 3/5] Codegen that fails for missing public values blocks the PR and names them Builds the generator gate on the worker's existing codegen path: package script generators run through detect_codegen_command (the root script or pnpm -r typegen/codegen) once, with the repository's public codegen environment from load_codegen_env. When a generator fails, the run no longer goes on to open the PR without regenerated files. common::codegen_env holds the rules for that environment (SETTINGS#CODEGEN_ENV#/): public values only; names and values that look like credentials are refused. A failed generator's missing values are the public names its configs read (sanity.cli/sanity.config/codegen configs: process.env and import.meta.env) or its output names, less those set. When any are missing, the run stops before the PR with a plain reason naming them and where to set them (Settings, Repositories, the repository's Codegen environment), and keeps them on the run as codegen_env_missing (in the API's Run, documented in OpenAPI). No fix round: a person sets them. Gateway: GET/PUT /api/repos/{owner}/{repo}/codegen-env for admins (the repos capability), validated by the same rules. --- docs/api/openapi.json | 49 ++++ services/common/src/codegen_env.rs | 298 +++++++++++++++++++++++ services/common/src/lib.rs | 3 + services/gateway/src/main.rs | 4 + services/gateway/src/permissions.rs | 4 +- services/gateway/src/routes/api.rs | 209 ++++++++++++++++ services/worker/src/passes/generators.rs | 202 ++++++++++++--- services/worker/src/passes/mod.rs | 2 +- 8 files changed, 732 insertions(+), 39 deletions(-) create mode 100644 services/common/src/codegen_env.rs diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 549b134eb..006ab0fd5 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -91,6 +91,44 @@ ], "type": "object" }, + "CodegenEnvMissing": { + "description": "The run stopped before its pull request because a code generator needed\npublic values the repository's codegen environment doesn't set.", + "properties": { + "command": { + "description": "The generator that failed.", + "examples": [ + "pnpm run typegen" + ], + "type": "string" + }, + "repo": { + "description": "The repository, `owner/name`.", + "examples": [ + "acme/web" + ], + "type": "string" + }, + "vars": { + "description": "The public variable names it needs that aren't set. Set them in the\ndashboard under Settings, Repositories, the repository's Codegen\nenvironment (public values only, never secrets), then retry the run.", + "examples": [ + [ + "SANITY_STUDIO_PROJECT_ID", + "SANITY_STUDIO_DATASET" + ] + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "repo", + "command", + "vars" + ], + "type": "object" + }, "CreateEndpointBody": { "description": "A new endpoint.", "properties": { @@ -2877,6 +2915,17 @@ "null" ] }, + "codegen_env_missing": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/CodegenEnvMissing", + "description": "Set when the run stopped before its pull request because a code\ngenerator needed public values the repository doesn't set. Null\notherwise." + } + ] + }, "continued_run_id": { "description": "The run that picked the answers up and continued the work.", "examples": [ diff --git a/services/common/src/codegen_env.rs b/services/common/src/codegen_env.rs new file mode 100644 index 000000000..6ea3440f9 --- /dev/null +++ b/services/common/src/codegen_env.rs @@ -0,0 +1,298 @@ +//! A repository's codegen environment: the PUBLIC values its code generators +//! need to run in the sandbox (a CMS project id and dataset, for example), +//! kept per repository at `SETTINGS#CODEGEN_ENV#/`. +//! +//! The sandbox holds no secrets, and these values cross into it: only values +//! that already ship in a client bundle belong here. Names and values that +//! look like credentials are refused ([`validate`]). +//! +//! When a generator fails because a value it reads is missing, the run stops +//! before its pull request and says exactly which names are missing and where +//! to set them ([`missing`], [`failure_reason`]), instead of opening the pull +//! request without the regenerated files. + +use std::collections::BTreeSet; + +/// The settings sort key for a repository's codegen environment. +pub fn sk(repo: &str) -> String { + format!("SETTINGS#CODEGEN_ENV#{repo}") +} + +/// Most variables a repository may keep. +pub const MAX_VARS: usize = 30; +/// Longest value kept. +pub const MAX_VALUE_CHARS: usize = 300; + +/// Where a person sets these, in the words the dashboard uses. +pub const WHERE: &str = "Settings, Repositories, the repository's Codegen environment"; + +/// Name prefixes frameworks reserve for values shipped to the browser. +const PUBLIC_PREFIXES: &[&str] = &[ + "SANITY_STUDIO_", + "NEXT_PUBLIC_", + "PUBLIC_", + "VITE_", + "NUXT_PUBLIC_", + "EXPO_PUBLIC_", + "REACT_APP_", + "GATSBY_", + "STORYBOOK_", +]; + +/// Words in a name that mark a credential. +const SECRET_WORDS: &[&str] = &[ + "TOKEN", + "SECRET", + "PASSWORD", + "PASSWD", + "PRIVATE", + "CREDENTIAL", + "API_KEY", + "APIKEY", + "ACCESS_KEY", + "AUTH", + "SESSION", + "COOKIE", + "SIGNING", + "WEBHOOK", +]; + +/// Whether a variable name looks like a credential. +pub fn name_looks_secret(name: &str) -> bool { + let n = name.to_ascii_uppercase(); + SECRET_WORDS.iter().any(|w| n.contains(w)) || n.ends_with("_KEY") || n == "KEY" +} + +/// Whether a value looks like a credential (a known token shape or a key). +pub fn value_looks_secret(value: &str) -> bool { + let v = value.trim(); + const PREFIXES: &[&str] = &[ + "ghp_", + "gho_", + "ghs_", + "github_pat_", + "glpat-", + "xox", + "sk-", + "sk_live_", + "sk_test_", + "rk_live_", + "AKIA", + "ASIA", + "AIza", + "eyJ", + "-----BEGIN", + ]; + PREFIXES.iter().any(|p| v.starts_with(p)) || v.contains("PRIVATE KEY") +} + +/// Whether a name is one a framework ships to the browser, or names the +/// kind of setting codegen reads (a project id, a dataset). +pub fn is_public_name(name: &str) -> bool { + let n = name.to_ascii_uppercase(); + !name_looks_secret(&n) + && (PUBLIC_PREFIXES.iter().any(|p| n.starts_with(p)) + || n.contains("PROJECT_ID") + || n.contains("DATASET") + || n.ends_with("_API_VERSION") + || n.ends_with("_ENDPOINT") + || n.ends_with("_URL")) +} + +/// Refuses what doesn't belong: a bad name, a credential-looking name or +/// value, a multi-line or long value, too many variables. +pub fn validate(vars: &[(String, String)]) -> Result<(), String> { + if vars.len() > MAX_VARS { + return Err(format!("At most {MAX_VARS} variables.")); + } + let mut seen = BTreeSet::new(); + for (name, value) in vars { + let ok = !name.is_empty() + && name.len() <= 100 + && name + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + if !ok { + return Err(format!( + "`{name}` isn't a variable name (letters, digits and _)." + )); + } + if !seen.insert(name.clone()) { + return Err(format!("`{name}` is listed twice.")); + } + if name_looks_secret(name) { + return Err(format!( + "`{name}` looks like a secret. Only public values (ones that already ship to the browser) belong here." + )); + } + if value_looks_secret(value) { + return Err(format!( + "The value of `{name}` looks like a token or key. Only public values belong here." + )); + } + if value.contains('\n') || value.chars().count() > MAX_VALUE_CHARS { + return Err(format!( + "The value of `{name}` must be one line of at most {MAX_VALUE_CHARS} characters." + )); + } + } + Ok(()) +} + +/// The environment variable names a config file's code reads +/// (`process.env.NAME`, `process.env["NAME"]`, `import.meta.env.NAME`). +pub fn env_refs(text: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + for marker in [ + "process.env.", + "import.meta.env.", + "process.env[", + "Deno.env.get(", + ] { + let mut rest = text; + while let Some(i) = rest.find(marker) { + rest = &rest[i + marker.len()..]; + let name: String = rest + .trim_start_matches(['"', '\'', '`']) + .chars() + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') + .collect(); + if name.len() >= 2 { + out.insert(name); + } + } + } + out +} + +/// Names in a generator's failure output that look like public settings +/// (`SANITY_STUDIO_PROJECT_ID is not set`). +pub fn named_in_output(output: &str) -> BTreeSet { + output + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .filter(|w| { + w.len() >= 4 + && w.chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_') + && w.contains('_') + && is_public_name(w) + }) + .map(String::from) + .collect() +} + +/// The public names a failed generator needs that the repository's codegen +/// environment doesn't set: what its configs read plus what its output +/// names, less the ones already set. Credential-looking names never appear +/// (they can't be set here). +pub fn missing( + config_refs: &BTreeSet, + output: &str, + set: &[(String, String)], +) -> Vec { + let have: BTreeSet<&str> = set + .iter() + .filter(|(_, v)| !v.trim().is_empty()) + .map(|(k, _)| k.as_str()) + .collect(); + let wanted: BTreeSet = config_refs + .iter() + .filter(|n| is_public_name(n)) + .cloned() + .chain(named_in_output(output)) + .collect(); + wanted + .into_iter() + .filter(|n| !have.contains(n.as_str())) + .collect() +} + +/// The run's status when codegen can't run for missing public values. +pub fn failure_reason(repo: &str, command: &str, missing: &[String]) -> String { + let names: Vec = missing.iter().map(|m| format!("`{m}`")).collect(); + format!( + "Stopped before opening a pull request: regenerating the generated files failed because \ + `{command}` needs public values the sandbox doesn't have: {}. Set them in {WHERE} \ + ({repo}), public values only, never secrets; then retry.", + names.join(", ") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(p: &[(&str, &str)]) -> Vec<(String, String)> { + p.iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect() + } + + #[test] + fn public_values_pass_secrets_are_refused() { + assert!(validate(&v(&[ + ("SANITY_STUDIO_PROJECT_ID", "abc123xy"), + ("SANITY_STUDIO_DATASET", "production") + ])) + .is_ok()); + for bad in [ + ("SANITY_AUTH_TOKEN", "x"), + ("STRIPE_SECRET", "x"), + ("DB_PASSWORD", "x"), + ("GOOGLE_API_KEY", "x"), + ("MY_KEY", "x"), + ] { + assert!(validate(&v(&[bad])).is_err(), "{bad:?}"); + } + assert!(validate(&v(&[("NEXT_PUBLIC_X", "ghp_abcdefghijklmnop")])).is_err()); + assert!(validate(&v(&[("NEXT_PUBLIC_X", "-----BEGIN RSA PRIVATE KEY-----")])).is_err()); + assert!(validate(&v(&[("1BAD", "x")])).is_err()); + assert!(validate(&v(&[("A_B", "x"), ("A_B", "y")])).is_err()); + assert!(validate(&v(&[("A_B", "line\nbreak")])).is_err()); + } + + #[test] + fn finds_what_a_failed_generator_needs() { + let cli = "import {defineCliConfig} from 'sanity/cli'\nexport default defineCliConfig({api: {projectId: process.env.SANITY_STUDIO_PROJECT_ID, dataset: process.env['SANITY_STUDIO_DATASET']}, token: process.env.SANITY_AUTH_TOKEN})"; + let refs = env_refs(cli); + assert!(refs.contains("SANITY_STUDIO_PROJECT_ID")); + assert!(refs.contains("SANITY_STUDIO_DATASET")); + assert!(refs.contains("SANITY_AUTH_TOKEN")); + let out = "Error: Configuration must contain `projectId`"; + // The token is never asked for: it can't be set here. + assert_eq!( + missing(&refs, out, &[]), + vec!["SANITY_STUDIO_DATASET", "SANITY_STUDIO_PROJECT_ID"] + ); + // One already set: only the other is missing. + assert_eq!( + missing(&refs, out, &v(&[("SANITY_STUDIO_PROJECT_ID", "abc")])), + vec!["SANITY_STUDIO_DATASET"] + ); + // Named only in the output. + assert_eq!( + missing( + &Default::default(), + "NEXT_PUBLIC_GRAPHQL_URL is not defined", + &[] + ), + vec!["NEXT_PUBLIC_GRAPHQL_URL"] + ); + let why = failure_reason("acme/web", "pnpm run typegen", &missing(&refs, out, &[])); + assert!(why.contains("`SANITY_STUDIO_PROJECT_ID`")); + assert!(why.contains("Codegen environment")); + assert!(why.contains("never secrets")); + assert_eq!(sk("acme/web"), "SETTINGS#CODEGEN_ENV#acme/web"); + } + + #[test] + fn the_worker_reads_the_same_key() { + let src = std::fs::read_to_string( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../worker/src/passes/mod.rs"), + ) + .unwrap(); + assert!(src.contains("common::codegen_env::sk(")); + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 1817af794..0703474fa 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -14,6 +14,9 @@ pub mod claim; /// The code graph's per-repo switch and build status (gateway and worker). pub mod code_graph; +/// A repository's public codegen environment: what may be kept, and what +/// a failed generator is missing. +pub mod codegen_env; /// Every delivery in and out (webhooks, relay forwards, notifications, /// email), with what happened, for the Deliveries page. pub mod deliveries; diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index bc6e3888e..98166fb14 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -378,6 +378,10 @@ async fn main() -> Result<(), Error> { post(routes::api::regenerate_repo), ) .route("/repos/:owner/:name/role", post(routes::api::set_repo_role)) + .route( + "/repos/:owner/:name/codegen-env", + get(routes::api::get_codegen_env).put(routes::api::put_codegen_env), + ) .route( "/integrations/jira/check", get(routes::api::get_jira_integration_check) diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 0324c1301..a10dd2a7a 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -378,11 +378,13 @@ pub const CAPABILITIES: &[Capability] = &[ }, Capability { key: "repos", - label: "Manage repositories: sync, turn on, roles, code graph (turn off, rebuild) and infrastructure scans", + label: "Manage repositories: sync, turn on, roles, codegen environment, code graph (turn off, rebuild) and infrastructure scans", min_role: "admin", handlers: &[ "api::sync_repos", "api::set_repo_role", + "api::get_codegen_env", + "api::put_codegen_env", "api::update_repo", "api::delete_repo", "api::regenerate_repo", diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 5f2fc4f00..b104c0074 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -909,6 +909,23 @@ pub struct RunNote { pub timestamp: Option, } +/// The run stopped before its pull request because a code generator needed +/// public values the repository's codegen environment doesn't set. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct CodegenEnvMissing { + /// The repository, `owner/name`. + #[schema(example = "acme/web")] + pub repo: String, + /// The generator that failed. + #[schema(example = "pnpm run typegen")] + pub command: String, + /// The public variable names it needs that aren't set. Set them in the + /// dashboard under Settings, Repositories, the repository's Codegen + /// environment (public values only, never secrets), then retry the run. + #[schema(example = json!(["SANITY_STUDIO_PROJECT_ID", "SANITY_STUDIO_DATASET"]))] + pub vars: Vec, +} + /// A commit a fix round pushed before it stopped. #[derive(serde::Serialize, utoipa::ToSchema)] pub struct PushedCommit { @@ -1096,6 +1113,32 @@ pub struct Run { /// otherwise. Resume it with `POST /api/runs/{run_id}/retry`. #[schema(example = json!(null))] pub round_incomplete: Option, + /// Set when the run stopped before its pull request because a code + /// generator needed public values the repository doesn't set. Null + /// otherwise. + #[schema(example = json!(null))] + pub codegen_env_missing: Option, +} + +/// The public values a run's code generator was missing, as the API shows them. +fn codegen_env_missing_of(item: &run_search::Item) -> Option { + let m = item.get("codegen_env_missing")?.as_m().ok()?; + let s = |k: &str| { + m.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() + }; + let vars: Vec = m + .get("vars") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default(); + (!vars.is_empty()).then(|| CodegenEnvMissing { + repo: s("repo"), + command: s("command"), + vars, + }) } /// The run's unfinished fix round, as the API shows it. @@ -1468,6 +1511,7 @@ fn run_of( answers_url: st("answers_url"), continued_run_id: st("continued_run_id"), round_incomplete: round_incomplete_of(item), + codegen_env_missing: codegen_env_missing_of(item), } } @@ -4317,6 +4361,118 @@ pub async fn update_repo_instructions( } /// Validate repo path parameter to prevent DynamoDB key injection. +/// GET /api/repos/:owner/:name/codegen-env — the repository's public +/// codegen environment (admins). Its values are public by rule, so they are +/// shown as kept. +pub async fn get_codegen_env( + State(state): State>, + Extension(claims): Extension, + axum::extract::Path((owner, name)): axum::extract::Path<(String, String)>, +) -> Result, StatusCode> { + claims.require_role(3)?; // admin+ + let repo = format!("{owner}/{name}"); + validate_repo_name(&repo)?; + let item = state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s(&common::codegen_env::sk(&repo))) + .send() + .await + .map_err(|e| { + error!("Failed to read the codegen environment for {repo}: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })? + .item; + let mut vars: Vec<(String, String)> = item + .and_then(|i| i.get("env").and_then(|v| v.as_m().ok()).cloned()) + .map(|m| { + m.into_iter() + .filter_map(|(k, v)| v.as_s().ok().map(|s| (k, s.clone()))) + .collect() + }) + .unwrap_or_default(); + vars.sort(); + Ok(Json(json!({ + "repo": repo, + "vars": vars.iter().map(|(n, v)| json!({"name": n, "value": v})).collect::>(), + }))) +} + +/// The variables a codegen environment write carries, checked +/// ([`common::codegen_env::validate`]): public values only. +fn codegen_vars(body: &Value) -> Result, String> { + let vars: Vec<(String, String)> = body["vars"] + .as_array() + .ok_or("Send `vars`: a list of {name, value}.")? + .iter() + .map(|v| { + ( + v["name"].as_str().unwrap_or("").trim().to_string(), + v["value"].as_str().unwrap_or("").trim().to_string(), + ) + }) + .filter(|(n, _)| !n.is_empty()) + .collect(); + common::codegen_env::validate(&vars)?; + Ok(vars) +} + +/// PUT /api/repos/:owner/:name/codegen-env — replace the repository's public +/// codegen environment (admins). Names or values that look like credentials +/// are refused with the reason; an empty list removes it. +pub async fn put_codegen_env( + State(state): State>, + Extension(claims): Extension, + axum::extract::Path((owner, name)): axum::extract::Path<(String, String)>, + Json(body): Json, +) -> Result, (StatusCode, Json)> { + let fail = |code: StatusCode, msg: &str| (code, Json(json!({ "error": msg }))); + // admin+ + let allowed = claims.require_role(3); + allowed.map_err(|c| fail(c, "Only admins can change the codegen environment."))?; + let repo = format!("{owner}/{name}"); + validate_repo_name(&repo).map_err(|c| fail(c, "Not a repository name."))?; + let vars = codegen_vars(&body).map_err(|m| fail(StatusCode::BAD_REQUEST, &m))?; + let key = common::codegen_env::sk(&repo); + let res = if vars.is_empty() { + state + .dynamo + .delete_item() + .table_name(&state.config.settings_table_name) + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s(&key)) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()) + } else { + state + .dynamo + .put_item() + .table_name(&state.config.settings_table_name) + .item("pk", attr_s(&claims.team_id)) + .item("sk", attr_s(&key)) + .item( + "env", + AttributeValue::M(vars.iter().map(|(n, v)| (n.clone(), attr_s(v))).collect()), + ) + .item("updated_at", attr_s(&chrono::Utc::now().to_rfc3339())) + .item("updated_by", attr_s(&claims.email)) + .send() + .await + .map(|_| ()) + .map_err(|e| e.to_string()) + }; + res.map_err(|e| { + error!("Failed to write the codegen environment for {repo}: {e}"); + fail(StatusCode::INTERNAL_SERVER_ERROR, "Could not save.") + })?; + info!(repo, count = vars.len(), "Codegen environment saved"); + Ok(Json(json!({ "repo": repo, "count": vars.len() }))) +} + fn validate_repo_name(repo: &str) -> Result<(), StatusCode> { if repo.is_empty() || repo.len() > 200 @@ -5967,6 +6123,59 @@ mod tests { assert_eq!(super::resume_route(&fb, now), super::ResumeRoute::Feedback); } + #[test] + fn codegen_env_writes_take_public_values_only() { + let ok = super::codegen_vars(&json!({"vars": [ + {"name": "SANITY_STUDIO_PROJECT_ID", "value": "abc123"}, + {"name": " ", "value": "ignored"} + ]})) + .unwrap(); + assert_eq!( + ok, + vec![("SANITY_STUDIO_PROJECT_ID".to_string(), "abc123".to_string())] + ); + assert!(super::codegen_vars( + &json!({"vars": [{"name": "SANITY_AUTH_TOKEN", "value": "x"}]}) + ) + .is_err()); + assert!(super::codegen_vars(&json!({})).is_err()); + assert!(super::codegen_vars(&json!({"vars": []})) + .unwrap() + .is_empty()); + } + + #[test] + fn a_run_stopped_for_missing_codegen_values_names_them() { + use aws_sdk_dynamodb::types::AttributeValue as A; + let item = std::collections::HashMap::from([ + ("status".to_string(), A::S("failed".into())), + ( + "codegen_env_missing".to_string(), + A::M(std::collections::HashMap::from([ + ("repo".to_string(), A::S("acme/web".into())), + ("command".to_string(), A::S("pnpm run typegen".into())), + ( + "vars".to_string(), + A::L(vec![A::S("SANITY_STUDIO_PROJECT_ID".into())]), + ), + ])), + ), + ]); + let usage = RunUsage { + tokens_in: 0, + tokens_out: 0, + cache_read: 0, + cache_write: 0, + cost_usd: 0.0, + }; + let run = serde_json::to_value(run_of(&item, "r", usage)).unwrap(); + assert_eq!( + run["codegen_env_missing"]["vars"][0], + "SANITY_STUDIO_PROJECT_ID" + ); + assert_eq!(run["codegen_env_missing"]["repo"], "acme/web"); + } + #[test] fn github_only_identities_are_never_platform_admins() { assert!(verified_identity("USER#Google_1234567890")); diff --git a/services/worker/src/passes/generators.rs b/services/worker/src/passes/generators.rs index 8cc1d7b4b..63e86c458 100644 --- a/services/worker/src/passes/generators.rs +++ b/services/worker/src/passes/generators.rs @@ -173,6 +173,8 @@ pub fn candidate_files(tree: &[String]) -> Vec { || b == "schema.prisma" || b == "buf.gen.yaml" || b == "openapitools.json" + || b.starts_with("sanity.cli.") + || b.starts_with("sanity.config.") || CODEGEN_CONFIGS.contains(&b) || DOC_FILES.contains(&p.as_str()) }) @@ -747,24 +749,30 @@ pub async fn load(github: &GitHubClient, owner: &str, repo: &str, git_ref: &str) enum Ran { /// It ran; these files changed (committed when there were any). Regenerated(Vec), - Failed(String), + /// It ran and failed: why, and its output. + Failed(String, String), /// The sandbox isn't set up, is out of time, or the team's policy holds /// the command. NotRun(String), } -async fn run_in_sandbox(w: &Work<'_>, repo: &RepoFiles, g: &Generator, attempt: usize) -> Ran { +async fn run_in_sandbox( + w: &Work<'_>, + g: &Generator, + cmd: &str, + env: &[(String, String)], + attempt: usize, +) -> Ran { let state = w.state; if state.config.sandbox_bucket_name.is_empty() || state.config.sandbox_project_name.is_empty() { return Ran::NotRun("no sandbox".into()); } - let cmd = sandbox_command(&repo.tree, g); let gate = crate::agent::policy::gate( state, w.provider.scope.ctx(common::agent_policy::Agent::Coder), w.deadline, ); - match gate.check_command(&cmd, "Regenerate generated files").await { + match gate.check_command(cmd, "Regenerate generated files").await { common::agent_policy::Outcome::Run { .. } => {} _ => return Ran::NotRun("the team's agent permissions hold this command".into()), } @@ -794,15 +802,14 @@ async fn run_in_sandbox(w: &Work<'_>, repo: &RepoFiles, g: &Generator, attempt: Err(e) => return Ran::NotRun(format!("snapshot failed: {e}")), }; let node = super::detect_node_version(w.github, owner, name, w.branch).await; - let env = super::load_codegen_env(state, &w.msg.team_id, owner, name).await; match sandbox .run_codegen( w.run_id, 100 + attempt, &source, - &cmd, + cmd, node.as_deref(), - &env, + env, w.deadline, ) .await @@ -829,49 +836,95 @@ async fn run_in_sandbox(w: &Work<'_>, repo: &RepoFiles, g: &Generator, attempt: .await { Ok(_) => Ran::Regenerated(paths), - Err(e) => Ran::Failed(format!("its output couldn't be committed ({e})")), + Err(e) => Ran::Failed( + format!("its output couldn't be committed ({e})"), + String::new(), + ), } } - Ok(o) if o.ran => Ran::Failed(format!( - "running it failed: {}", - common::truncate_str(o.output.trim(), 300) - )), + Ok(o) if o.ran => Ran::Failed( + format!( + "running it failed: {}", + common::truncate_str(o.output.trim(), 300) + ), + o.output, + ), Ok(o) => Ran::NotRun(o.output), Err(e) => Ran::NotRun(e.to_string()), } } +/// What one pass over the affected generators found. +enum Pass { + /// Generators still out of date (empty: all up to date). + Problems(Vec<(Generator, Vec, String)>), + /// A generator failed for public values the codegen environment lacks: + /// no fix round can settle that, a person sets them. + MissingEnv(String), +} + +/// Whether a generator runs through the repository's package scripts (the +/// worker's own codegen command already runs those). +fn is_script(g: &Generator) -> bool { + let c = g.command.trim_start(); + let c = c.split("&& ").last().unwrap_or(c); + ["npm run ", "pnpm run ", "yarn ", "bun run "] + .iter() + .any(|p| c.starts_with(p)) +} + /// One pass over the affected generators: regenerate in the sandbox when it -/// can, and name each one still out of date. -async fn regenerate( - w: &Work<'_>, - attempt: usize, - notes: &mut Vec, -) -> Option, String)>> { - let repo = load(w.github, &w.msg.repo_owner, &w.msg.repo_name, w.branch).await; +/// can, and name each one still out of date. Package-script generators run +/// through the worker's codegen command (`detect_codegen_command`), once, +/// with the repository's public codegen environment (`load_codegen_env`). +async fn regenerate(w: &Work<'_>, attempt: usize, notes: &mut Vec) -> Option { + let (owner, name) = (&w.msg.repo_owner, &w.msg.repo_name); + let repo = load(w.github, owner, name, w.branch).await; let gens = detect(&repo); if gens.is_empty() { return None; } - let mut changed = super::plan_coverage::changed_files( - w.github, - &w.msg.repo_owner, - &w.msg.repo_name, - &w.msg.base_branch, - w.branch, - ) - .await?; + let mut changed = + super::plan_coverage::changed_files(w.github, owner, name, &w.msg.base_branch, w.branch) + .await?; let hits: Vec<(Generator, Vec)> = affected(&gens, &changed) .into_iter() .map(|(g, i)| (g.clone(), i)) .collect(); + if hits.is_empty() { + return Some(Pass::Problems(Vec::new())); + } + let scripts_cmd = super::detect_codegen_command(w.github, owner, name, w.branch).await; + let env = super::load_codegen_env(w.state, &w.msg.team_id, owner, name).await; + let mut shared_run: Option = None; let mut problems = Vec::new(); for (i, (g, inputs)) in hits.into_iter().enumerate() { - match run_in_sandbox(w, &repo, &g, attempt * 10 + i).await { + let ran = match (&scripts_cmd, is_script(&g)) { + (Some(cmd), true) => match &shared_run { + // The shared run already counted its files. + Some(Ran::Regenerated(_)) => Ran::Regenerated(Vec::new()), + Some(Ran::Failed(a, b)) => Ran::Failed(a.clone(), b.clone()), + Some(Ran::NotRun(a)) => Ran::NotRun(a.clone()), + None => { + let r = run_in_sandbox(w, &g, cmd, &env, attempt * 10 + i).await; + shared_run = Some(match &r { + Ran::Regenerated(p) => Ran::Regenerated(p.clone()), + Ran::Failed(a, b) => Ran::Failed(a.clone(), b.clone()), + Ran::NotRun(a) => Ran::NotRun(a.clone()), + }); + r + } + }, + _ => { + let cmd = sandbox_command(&repo.tree, &g); + run_in_sandbox(w, &g, &cmd, &env, attempt * 10 + i).await + } + }; + match ran { Ran::Regenerated(paths) => { if paths.is_empty() { notes.push(format!( - "`{}` ran; the generated files were already up to date", + "`{}` ran; the generated files are up to date", g.name )); } else { @@ -883,7 +936,30 @@ async fn regenerate( changed.extend(paths); } } - Ran::Failed(why) => problems.push((g, inputs, format!("{why}."))), + Ran::Failed(why, output) => { + // Public values the generator reads that the repository's + // codegen environment doesn't set: a person's to add. + let refs: std::collections::BTreeSet = repo + .files + .iter() + .filter(|(p, _)| { + let b = base_name(p); + b.starts_with("sanity.cli.") + || b.starts_with("sanity.config.") + || CODEGEN_CONFIGS.contains(&b) + }) + .flat_map(|(_, t)| common::codegen_env::env_refs(t)) + .collect(); + let missing = common::codegen_env::missing(&refs, &output, &env); + if !missing.is_empty() { + let full = format!("{owner}/{name}"); + record_missing_env(w, &full, &g.name, &missing).await; + return Some(Pass::MissingEnv(common::codegen_env::failure_reason( + &full, &g.name, &missing, + ))); + } + problems.push((g, inputs, format!("{why}."))); + } Ran::NotRun(why) => { info!(generator = %g.name, why, "Generator not run in the sandbox"); if outputs_missing(&g, &changed) { @@ -904,7 +980,35 @@ async fn regenerate( } } } - Some(problems) + Some(Pass::Problems(problems)) +} + +/// Keeps on the run which public values codegen was missing, for the run +/// page to show with a link to where they're set. +async fn record_missing_env(w: &Work<'_>, repo: &str, command: &str, missing: &[String]) { + use aws_sdk_dynamodb::types::AttributeValue as A; + let value = A::M(HashMap::from([ + ("repo".to_string(), A::S(repo.to_string())), + ("command".to_string(), A::S(command.to_string())), + ( + "vars".to_string(), + A::L(missing.iter().map(|m| A::S(m.clone())).collect()), + ), + ])); + if let Err(e) = w + .state + .dynamo + .update_item() + .table_name(&w.state.config.runs_table_name) + .key("team_id", super::attr_s(&w.msg.team_id)) + .key("run_id", super::attr_s(w.run_id)) + .update_expression("SET codegen_env_missing = :m") + .expression_attribute_values(":m", value) + .send() + .await + { + warn!(run_id = w.run_id, error = %e, "Could not record the missing codegen values"); + } } /// Before the pull request: generators whose inputs changed are run and @@ -916,12 +1020,12 @@ pub async fn gate( usage: &mut crate::models::TokenUsage, ) -> Result, String> { let mut notes = Vec::new(); - let Some(problems) = regenerate(w, 0, &mut notes).await else { - return Ok(notes); + let problems = match regenerate(w, 0, &mut notes).await { + None => return Ok(notes), + Some(Pass::MissingEnv(why)) => return Err(why), + Some(Pass::Problems(p)) if p.is_empty() => return Ok(notes), + Some(Pass::Problems(p)) => p, }; - if problems.is_empty() { - return Ok(notes); - } super::add_progress_note( w.state, &w.msg.team_id, @@ -960,7 +1064,11 @@ pub async fn gate( warn!(run_id = w.run_id, error = %e, "Generator fix round failed"); } let mut notes2 = Vec::new(); - let still = regenerate(w, 1, &mut notes2).await.unwrap_or_default(); + let still = match regenerate(w, 1, &mut notes2).await { + Some(Pass::MissingEnv(why)) => return Err(why), + Some(Pass::Problems(p)) => p, + None => Vec::new(), + }; notes.extend(notes2); match still.first() { None => Ok(notes), @@ -1189,6 +1297,26 @@ mod tests { assert!(!c.contains(&"src/index.ts".to_string())); } + #[test] + fn package_script_generators_run_through_the_workers_codegen_command() { + let g = |c: &str| Generator { + kind: GenKind::Sanity, + name: c.into(), + command: c.into(), + inputs: vec![], + outputs: vec![], + }; + assert!(is_script(&g("pnpm run typegen"))); + assert!(is_script(&g("cd apps/studio && npm run codegen"))); + assert!(!is_script(&g("npx graphql-codegen --config codegen.yml"))); + assert!(!is_script(&g("make client"))); + // Sanity's own config files are read for the env values they need. + assert_eq!( + candidate_files(&["apps/studio/sanity.cli.ts".to_string()]).len(), + 1 + ); + } + #[test] fn run_codegen_runs_every_generator_from_the_root() { let r = repo( diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 30a3d6918..e1d61f736 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -7381,7 +7381,7 @@ pub(crate) async fn load_codegen_env( owner: &str, repo: &str, ) -> Vec<(String, String)> { - let sk = format!("SETTINGS#CODEGEN_ENV#{owner}/{repo}"); + let sk = common::codegen_env::sk(&format!("{owner}/{repo}")); let item = state .dynamo .get_item() From 7c58c00b859b1ab4896e185d333544301615f9a3 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 13:14:57 -0400 Subject: [PATCH 4/5] Fix rounds checkpoint on a WIP branch and land as one commit on the PR Every push to a pull request branch re-runs CI and, on repositories that dismiss stale approvals, dismisses them. A fix round now pushes to the pull request exactly once. - CI fix, review fix and feedback rounds write their checkpoint commits to coderhelm-wip/, opened at the PR head when the round starts (a continuing round reuses its own). - When the round is done, everything it changed since it started lands on the PR as ONE commit in the team's commit style (round::land: removals and renames included), and the WIP branch is deleted. If the PR changed the same files meanwhile, nothing lands and the round is left unfinished. - A round that times out, errors or is cancelled keeps its WIP branch; the run records it (round / round_incomplete.wip_branch and base_sha, also written by the stuck-run sweep), Resume continues from it, and nothing partial reaches the PR. The status note says the PR is unchanged. - API: RoundIncomplete.wip_branch (OpenAPI). The pre-PR stop copy is now coderhelm-wip/ too. --- docs/api/openapi.json | 12 +- lambda/stuck-run-cleanup/handler.py | 3 + lambda/tests/test_stuck_run_cleanup.py | 10 +- services/common/src/run_round.rs | 87 +++++++++-- services/gateway/src/routes/api.rs | 20 ++- services/worker/src/passes/feedback.rs | 133 +++++++++++++---- services/worker/src/passes/mod.rs | 4 +- services/worker/src/passes/resume.rs | 104 +++++++++++-- services/worker/src/passes/round.rs | 196 ++++++++++++++++++++++++- 9 files changed, 499 insertions(+), 70 deletions(-) diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 006ab0fd5..9ae5557c3 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -2016,7 +2016,7 @@ "type": "object" }, "PushedCommit": { - "description": "A commit a fix round pushed before it stopped.", + "description": "A checkpoint commit a fix round saved on its WIP branch before it stopped.", "properties": { "message": { "description": "Its subject line.", @@ -2768,7 +2768,7 @@ "type": "integer" }, "pushed": { - "description": "The commits the round pushed to the pull request's branch before it\nstopped, oldest first.", + "description": "The checkpoint commits the round saved on `wip_branch` before it\nstopped, oldest first (never on the pull request).", "items": { "$ref": "#/components/schemas/PushedCommit" }, @@ -2787,6 +2787,13 @@ "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row." ], "type": "string" + }, + "wip_branch": { + "description": "The branch the round's work so far is saved on. A round that didn't\nfinish never pushes to the pull request; Resume continues from here.", + "examples": [ + "coderhelm-wip/web-42-gallery" + ], + "type": "string" } }, "required": [ @@ -2795,6 +2802,7 @@ "summary", "pushed", "files", + "wip_branch", "at", "can_resume" ], diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 9cf8603fa..29e390ca7 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -166,6 +166,9 @@ def incomplete_record(run, pass_name, now_iso): "at": now_iso, "feedback": rnd.get("feedback", ""), "scoped": rnd.get("scoped", True), + # The round's work so far stays on its WIP branch, never the PR's. + "wip_branch": rnd.get("wip_branch", ""), + "base_sha": rnd.get("base_sha", ""), } diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index d64b81099..b6fd0557a 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -86,13 +86,21 @@ def test_a_stuck_run_with_an_open_pr_is_not_failed(self): run = { "pr_number": 41, "current_pass": "implement", - "round": {"kind": "review_fix", "number": 3, "feedback": "Add the tabs"}, + "round": { + "kind": "review_fix", + "number": 3, + "feedback": "Add the tabs", + "wip_branch": "coderhelm-wip/feature/x", + "base_sha": "abc", + }, } self.assertTrue(sweep.has_pull_request(run)) rec = sweep.incomplete_record(run, "implement", "2026-10-26T15:00:00+00:00") self.assertEqual(rec["kind"], "review_fix") self.assertEqual(rec["number"], 3) self.assertEqual(rec["feedback"], "Add the tabs") + self.assertEqual(rec["wip_branch"], "coderhelm-wip/feature/x") + self.assertEqual(rec["base_sha"], "abc") line = sweep.status_line(rec["reason"]) self.assertTrue(line.startswith("Pull request open; the last fix round didn't finish:")) self.assertNotIn("failed", line.lower()) diff --git a/services/common/src/run_round.rs b/services/common/src/run_round.rs index 5f76494e7..3c2250a51 100644 --- a/services/common/src/run_round.rs +++ b/services/common/src/run_round.rs @@ -21,6 +21,13 @@ //! - The round being worked is on the run record ([`FIELD`]) with its //! deadline, so the stuck-run sweep waits for that deadline (plus //! [`SWEEP_GRACE_SECS`]) before it calls the worker gone. +//! - A round works on its own branch, [`wip_branch`] (`coderhelm-wip/`), never the pull request's: every write is a checkpoint +//! commit there. When the round finishes, its changes land on the pull +//! request as ONE commit in the repository's commit style, so a round is +//! one push (one CI run; a repository that dismisses stale approvals +//! dismisses them once). A round that stops keeps its WIP branch, and +//! Resume continues from it; partial work never reaches the pull request. //! - A round that doesn't finish while the pull request is open never fails //! the run. The run is `completed` with [`INCOMPLETE_FIELD`] saying which //! round, why, and the commits it pushed; [`status_line`] is how a person @@ -144,6 +151,15 @@ pub struct Round { /// Whether the round may only change the files the pull request already /// changes (a bot-driven fix). pub scoped: bool, + /// The branch the round writes its checkpoints to (empty until it + /// starts working). + pub wip_branch: String, +} + +/// The branch a round on `pr_branch` keeps its checkpoints on: a branch of +/// its own, never the pull request's head. +pub fn wip_branch(pr_branch: &str) -> String { + format!("coderhelm-wip/{pr_branch}") } fn s(v: &str) -> AttributeValue { @@ -193,6 +209,7 @@ impl Round { base_sha: base_sha.to_string(), feedback: cut(feedback, MAX_FEEDBACK_CHARS), scoped, + wip_branch: String::new(), } } @@ -232,6 +249,7 @@ impl Round { ("base_sha".to_string(), s(&self.base_sha)), ("feedback".to_string(), s(&self.feedback)), ("scoped".to_string(), AttributeValue::Bool(self.scoped)), + ("wip_branch".to_string(), s(&self.wip_branch)), ])) } @@ -255,6 +273,7 @@ impl Round { .and_then(|v| v.as_bool().ok()) .copied() .unwrap_or(true), + wip_branch: get_s(m, "wip_branch"), }) } @@ -289,6 +308,10 @@ pub struct Incomplete { pub feedback: String, /// Whether the round was a bot-driven fix scoped to the PR's files. pub scoped: bool, + /// The branch holding the round's work so far (not the pull request's). + pub wip_branch: String, + /// The pull request's head when the round started. + pub base_sha: String, } impl Incomplete { @@ -303,6 +326,8 @@ impl Incomplete { at: now.to_string(), feedback: round.feedback.clone(), scoped: round.scoped, + wip_branch: round.wip_branch.clone(), + base_sha: round.base_sha.clone(), } } @@ -339,6 +364,8 @@ impl Incomplete { s(&cut(&self.feedback, MAX_FEEDBACK_CHARS)), ), ("scoped".to_string(), AttributeValue::Bool(self.scoped)), + ("wip_branch".to_string(), s(&self.wip_branch)), + ("base_sha".to_string(), s(&self.base_sha)), ])) } @@ -373,9 +400,27 @@ impl Incomplete { .and_then(|v| v.as_bool().ok()) .copied() .unwrap_or(true), + wip_branch: get_s(m, "wip_branch"), + base_sha: get_s(m, "base_sha"), }) } + /// The round to run again on Resume: parked, continuing from its WIP + /// branch and its starting point, with a fresh budget. + pub fn resume_round(&self, now: chrono::DateTime) -> Option { + let kind = self.kind?; + let mut r = Round::start( + kind, + self.number, + &self.base_sha, + &self.feedback, + self.scoped, + now, + ); + r.wip_branch = self.wip_branch.clone(); + Some(r.parked(false)) + } + /// The unfinished round on a run record, if any. pub fn from_item(item: &HashMap) -> Option { item.get(INCOMPLETE_FIELD).and_then(Incomplete::from_attr) @@ -450,18 +495,19 @@ pub fn pushed_from_compare(compare: &serde_json::Value) -> (Vec, Vec String { +/// One line for a progress note: what an unfinished round left, and where. +/// The pull request itself is never changed by a round that didn't finish. +pub fn pushed_note(pushed: &[Pushed], files: &[String], wip: &str) -> String { if pushed.is_empty() { - return "It pushed no commits before it stopped.".to_string(); + return "It saved no work before it stopped; the pull request is unchanged.".to_string(); } let shas: Vec = pushed .iter() .map(|p| p.sha.chars().take(7).collect()) .collect(); format!( - "It pushed {} commit(s) to the pull request branch before it stopped ({}), changing {} file(s).", + "Its work so far ({} checkpoint commit(s): {}, {} file(s)) is saved on branch `{wip}`; \ + the pull request is unchanged, and Resume continues from there.", pushed.len(), shas.join(", "), files.len() @@ -537,6 +583,24 @@ mod tests { assert_eq!(back, inc); } + #[test] + fn a_round_writes_to_its_own_branch_and_resume_continues_from_it() { + assert_eq!(wip_branch("feature/abc-7"), "coderhelm-wip/feature/abc-7"); + assert_ne!(wip_branch("x"), "x"); + let mut r = Round::start(Kind::ReviewFix, 2, "base1", "Add the tabs", true, now()); + r.wip_branch = wip_branch("feature/abc-7"); + let inc = Incomplete::of(&r, "out of time", "t"); + assert_eq!(inc.wip_branch, "coderhelm-wip/feature/abc-7"); + assert_eq!(inc.base_sha, "base1"); + let back = Incomplete::from_attr(&inc.to_attr()).unwrap(); + let again = back.resume_round(now()).unwrap(); + assert_eq!(again.state, State::Pending); + assert_eq!(again.wip_branch, "coderhelm-wip/feature/abc-7"); + assert_eq!(again.base_sha, "base1"); + assert_eq!(again.feedback, "Add the tabs"); + assert!(Incomplete::default().resume_round(now()).is_none()); + } + #[test] fn the_long_feedback_of_a_parked_round_is_cut() { let big = "x".repeat(MAX_FEEDBACK_CHARS * 2); @@ -584,14 +648,11 @@ mod tests { assert_eq!(pushed.len(), 2); assert_eq!(pushed[0].message, "Add the tabs"); assert_eq!(files, vec!["src/tabs.ts", "src/tabs.test.ts"]); - assert_eq!( - pushed_note(&pushed, &files), - "It pushed 2 commit(s) to the pull request branch before it stopped (aaaaaaa, bbbbbbb), changing 2 file(s)." - ); - assert_eq!( - pushed_note(&[], &[]), - "It pushed no commits before it stopped." - ); + let note = pushed_note(&pushed, &files, "coderhelm-wip/feature/x"); + assert!(note.contains("2 checkpoint commit(s): aaaaaaa, bbbbbbb, 2 file(s)")); + assert!(note.contains("`coderhelm-wip/feature/x`")); + assert!(note.contains("the pull request is unchanged")); + assert!(pushed_note(&[], &[], "w").contains("the pull request is unchanged")); } #[test] diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index b104c0074..fa9b6b53f 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -926,7 +926,7 @@ pub struct CodegenEnvMissing { pub vars: Vec, } -/// A commit a fix round pushed before it stopped. +/// A checkpoint commit a fix round saved on its WIP branch before it stopped. #[derive(serde::Serialize, utoipa::ToSchema)] pub struct PushedCommit { /// The commit's SHA. @@ -958,12 +958,16 @@ pub struct RoundIncomplete { example = "Pull request open; the last fix round didn't finish: the review fix round ran out of its time budget 3 times in a row." )] pub summary: String, - /// The commits the round pushed to the pull request's branch before it - /// stopped, oldest first. + /// The checkpoint commits the round saved on `wip_branch` before it + /// stopped, oldest first (never on the pull request). pub pushed: Vec, /// The files those commits changed. #[schema(example = json!(["src/blocks/gallery/tabs.tsx"]))] pub files: Vec, + /// The branch the round's work so far is saved on. A round that didn't + /// finish never pushes to the pull request; Resume continues from here. + #[schema(example = "coderhelm-wip/web-42-gallery")] + pub wip_branch: String, /// When it stopped (RFC 3339). #[schema(example = "2026-10-22T15:40:02Z")] pub at: String, @@ -1168,6 +1172,7 @@ fn round_incomplete_of(item: &run_search::Item) -> Option { }) .collect(), files: inc.files, + wip_branch: inc.wip_branch, at: inc.at, can_resume: common::run_round::may_resume(status, pr_number, true), }) @@ -2022,12 +2027,13 @@ fn resume_route( inc: &common::run_round::Incomplete, now: chrono::DateTime, ) -> ResumeRoute { - use common::run_round::{Kind, Round}; + use common::run_round::Kind; match inc.kind { Some(Kind::Feedback) => ResumeRoute::Feedback, - Some(kind) if !inc.feedback.trim().is_empty() => ResumeRoute::Parked( - Round::start(kind, inc.number, "", &inc.feedback, inc.scoped, now).parked(false), - ), + Some(_) if !inc.feedback.trim().is_empty() => match inc.resume_round(now) { + Some(r) => ResumeRoute::Parked(r), + None => ResumeRoute::Recheck, + }, _ => ResumeRoute::Recheck, } } diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index b66991476..8998baf62 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -671,30 +671,6 @@ Rules: s.record_applied(state).await; } - let executor = FeedbackToolExecutor { - github: &github, - owner: &msg.repo_owner, - repo: &msg.repo_name, - branch: &branch, - base_branch: &base, - files_modified: std::sync::Mutex::new(false), - description: DescriptionRequests::new(may_edit_description), - scope_guard, - history: Some(&history), - graphs: Some(&graphs), - ops: ops.as_ref(), - live: live.as_ref(), - skills: skills.as_ref(), - web: Some(&web), - state, - commits: (conventions, tokens), - }; - - let mut messages = vec![( - "user".to_string(), - vec![serde_json::json!({"type": "text", "text": prompt})], - )]; - // The round on the run record, with its deadline, while it works: the // stuck-run sweep waits for that deadline, not the run's age. if !super::round::may_start(start, std::time::Instant::now()) { @@ -705,9 +681,34 @@ Rules: return Ok(()); } } - let feedback_round = { - let base_sha = - super::round::branch_head(&github, &msg.repo_owner, &msg.repo_name, &branch).await; + // A continuing step keeps the round's starting point and its WIP branch. + let prior = if msg.round_attempt > 0 { + state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key( + "team_id", + aws_sdk_dynamodb::types::AttributeValue::S(msg.team_id.clone()), + ) + .key( + "run_id", + aws_sdk_dynamodb::types::AttributeValue::S(msg.run_id.clone()), + ) + .send() + .await + .ok() + .and_then(|r| r.item) + .and_then(|i| common::run_round::Round::from_item(&i)) + .filter(|r| r.kind == common::run_round::Kind::Feedback) + } else { + None + }; + let mut feedback_round = { + let base_sha = match prior.as_ref().map(|r| r.base_sha.clone()) { + Some(b) if !b.is_empty() => b, + _ => super::round::branch_head(&github, &msg.repo_owner, &msg.repo_name, &branch).await, + }; let mut r = common::run_round::Round::start( common::run_round::Kind::Feedback, 0, @@ -719,8 +720,42 @@ Rules: r.attempt = msg.round_attempt + 1; r }; + // The round writes its checkpoints to its own WIP branch; the pull + // request gets one commit when the round is done. + feedback_round.wip_branch = super::round::open_wip( + &github, + &msg.repo_owner, + &msg.repo_name, + &branch, + &prior.map(|r| r.wip_branch).unwrap_or_default(), + ) + .await?; super::round::record(state, &msg.team_id, &msg.run_id, &feedback_round).await; + let executor = FeedbackToolExecutor { + github: &github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + branch: &feedback_round.wip_branch, + base_branch: &base, + files_modified: std::sync::Mutex::new(false), + description: DescriptionRequests::new(may_edit_description), + scope_guard, + history: Some(&history), + graphs: Some(&graphs), + ops: ops.as_ref(), + live: live.as_ref(), + skills: skills.as_ref(), + web: Some(&web), + state, + commits: (conventions, tokens), + }; + + let mut messages = vec![( + "user".to_string(), + vec![serde_json::json!({"type": "text", "text": prompt})], + )]; + let model_id = provider.primary_model_id(); let response = provider::converse( state, @@ -808,7 +843,49 @@ Rules: // The description: rewritten when the code changed (so it stays true) // or when a person with write access asked for a change to it, even // with no code change. What changed goes on the reply. - let fix_pushed = *executor.files_modified.lock().unwrap(); + // The round's changes land on the pull request as one commit, one push. + let fix_pushed = if *executor.files_modified.lock().unwrap() { + let pr = super::round::Pr { + github: &github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + branch: &branch, + }; + let ticket_msg = crate::models::TicketMessage { + ticket_id: ticket.0.clone(), + title: ticket.1.clone(), + issue_number: ticket.2, + ..Default::default() + }; + let message = + super::round::round_message(state, &msg.team_id, &ticket_msg, &feedback_round).await; + match super::round::land( + &pr, + &feedback_round.wip_branch, + &feedback_round.base_sha, + &message, + ) + .await + { + super::round::Landed::Pushed { .. } => true, + super::round::Landed::Nothing => false, + super::round::Landed::Refused(why) => { + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &pr, + &feedback_round, + &format!("its changes couldn't land on the pull request: {why}"), + ) + .await; + super::webhooks::emit_run(state, &msg.team_id, &msg.run_id, "completed").await; + return Ok(()); + } + } + } else { + false + }; let asked = executor.description.taken(); let description_note = if fix_pushed || !asked.is_empty() { let changed = super::pr::refresh_description( diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index e1d61f736..0e8a753b0 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -4330,12 +4330,12 @@ async fn run_passes( Ok(()) } -/// Keeps a branch's commits on `-wip` when a run stops before its +/// Keeps a branch's commits on `coderhelm-wip/` when a run stops before its /// pull request: a later run of the ticket resets the run branch to its /// base, and the work must survive that. Returns the branch the work is on /// (the run branch itself when the copy can't be made). async fn keep_wip_branch(github: &GitHubClient, owner: &str, repo: &str, branch: &str) -> String { - let wip = format!("{branch}-wip"); + let wip = common::run_round::wip_branch(branch); match github.create_branch(owner, repo, &wip, branch).await { Ok(_) => wip, Err(e) => { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index c46933073..01dc3ed8b 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -1860,10 +1860,14 @@ pub async fn run( // The CI fix is a round of its own (common::run_round): its own // budget, on the run record while it works, and parked for a fresh // invocation when this one has too little left to finish it. - let ci_round = run_round::Round::start( + let round_base = match branch_head.as_deref() { + Some(h) if !h.is_empty() => h.to_string(), + _ => super::round::branch_head(&github, &repo_owner, &repo_name, &branch).await, + }; + let mut ci_round = run_round::Round::start( run_round::Kind::CiFix, (cycle + 1).min(u32::MAX as usize) as u32, - branch_head.as_deref().unwrap_or(""), + &round_base, &feedback, review_feedback.is_empty(), chrono::Utc::now(), @@ -1890,6 +1894,10 @@ pub async fn run( .await?; return Ok(()); } + // The fix writes its checkpoints to its own WIP branch; the pull + // request gets one commit when it's done. + ci_round.wip_branch = + super::round::open_wip(&github, &repo_owner, &repo_name, &branch, "").await?; super::round::record(state, &msg.team_id, &msg.run_id, &ci_round).await; // The tree before the fix: compared with the tree after it to tell a @@ -1904,7 +1912,7 @@ pub async fn run( &ticket_msg, &github, &plan_result, - &branch, + &ci_round.wip_branch, &rules, &repo_instructions, Some(&feedback), @@ -1978,7 +1986,47 @@ pub async fn run( .await?; return Ok(()); } - Ok(result) => { + Ok(mut result) => { + // One commit, one push: the fix lands on the pull request. + let message = + super::round::round_message(state, &msg.team_id, &ticket_msg, &ci_round).await; + let gh = super::round::Pr { + github: &github, + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + }; + match super::round::land(&gh, &ci_round.wip_branch, &ci_round.base_sha, &message) + .await + { + super::round::Landed::Pushed { .. } => {} + super::round::Landed::Nothing => result.files_modified.clear(), + super::round::Landed::Refused(why) => { + mark_events_processed(state, &msg.run_id, &events).await; + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + &ci_round, + &format!("its changes couldn't land on the pull request: {why}"), + ) + .await; + complete_run_with_status( + state, + &ticket_msg, + &msg.run_id, + "completed", + &pr_url, + pr_number, + &branch, + &usage, + wall_clock_secs(created_at, &start), + ) + .await?; + return Ok(()); + } + } super::round::clear(state, &msg.team_id, &msg.run_id).await; info!( run_id = msg.run_id, @@ -2854,13 +2902,19 @@ async fn run_fix_round( if round.base_sha.is_empty() { round.base_sha = super::round::branch_head(&ctx.github, pr.owner, pr.repo, pr.branch).await; } + // The round writes to its own WIP branch, never the pull request's: a + // continuing round picks up the one it has. + let continuing = !round.wip_branch.is_empty(); + round.wip_branch = + super::round::open_wip(&ctx.github, pr.owner, pr.repo, pr.branch, &round.wip_branch) + .await?; super::round::record(state, &msg.team_id, &msg.run_id, &round).await; super::update_pass(state, &msg.team_id, &msg.run_id, "implement").await?; - let feedback = if round.attempt > 1 { + let feedback = if round.attempt > 1 || continuing { format!( - "{}\n\n## CONTINUING THIS ROUND\nAn earlier step of this round ran out of time; \ - everything it wrote is already committed on the branch. Read the files you need \ - first, then finish only what is left.", + "{}\n\n## CONTINUING THIS ROUND\nAn earlier step of this round stopped before it \ + finished; everything it wrote is already committed on this branch. Read the files you \ + need first, then finish only what is left.", round.feedback ) } else { @@ -2881,7 +2935,7 @@ async fn run_fix_round( &ctx.ticket_msg, &ctx.github, &plan_result, - pr.branch, + &round.wip_branch, &ctx.rules, &ctx.repo_instructions, Some(&feedback), @@ -2938,11 +2992,33 @@ async fn run_fix_round( Ok(RoundEnd::Incomplete) } } - Ok(r) => { - super::round::clear(state, &msg.team_id, &msg.run_id).await; - Ok(RoundEnd::Done { - files: r.files_modified.len(), - }) + Ok(_) => { + // Done: the round's changes land on the pull request as one + // commit, one push. + let message = + super::round::round_message(state, &msg.team_id, &ctx.ticket_msg, &round).await; + match super::round::land(&gh, &round.wip_branch, &round.base_sha, &message).await { + super::round::Landed::Pushed { files } => { + super::round::clear(state, &msg.team_id, &msg.run_id).await; + Ok(RoundEnd::Done { files }) + } + super::round::Landed::Nothing => { + super::round::clear(state, &msg.team_id, &msg.run_id).await; + Ok(RoundEnd::Done { files: 0 }) + } + super::round::Landed::Refused(why) => { + super::round::finish_incomplete( + state, + &msg.team_id, + &msg.run_id, + &gh, + &round, + &format!("its changes couldn't land on the pull request: {why}"), + ) + .await; + Ok(RoundEnd::Incomplete) + } + } } Err(e) => { let err: &(dyn std::error::Error + 'static) = &*e; diff --git a/services/worker/src/passes/round.rs b/services/worker/src/passes/round.rs index 9064db73e..2c3ea582e 100644 --- a/services/worker/src/passes/round.rs +++ b/services/worker/src/passes/round.rs @@ -11,7 +11,7 @@ use common::run_status::EndedValues; use tracing::{info, warn}; use super::attr_s; -use crate::clients::github::GitHubClient; +use crate::clients::github::{FileOp, GitHubClient}; use crate::WorkerState; /// When a round that starts in an invocation begun at `invocation_start` @@ -133,7 +133,13 @@ pub(crate) async fn finish_incomplete( ) -> Incomplete { let now = chrono::Utc::now().to_rfc3339(); let mut inc = Incomplete::of(round, reason, &now); - let (commits, files) = pushed(pr.github, pr.owner, pr.repo, &round.base_sha, pr.branch).await; + // What it saved is on its WIP branch; the pull request is untouched. + let wip = if round.wip_branch.is_empty() { + pr.branch + } else { + round.wip_branch.as_str() + }; + let (commits, files) = pushed(pr.github, pr.owner, pr.repo, &round.base_sha, wip).await; inc.pushed = commits; inc.files = files; // The caller completes the run (with its usage) and says so. @@ -145,7 +151,7 @@ pub(crate) async fn finish_incomplete( &format!( "{} {}", inc.status_line(), - run_round::pushed_note(&inc.pushed, &inc.files) + run_round::pushed_note(&inc.pushed, &inc.files, wip) ), ) .await; @@ -260,10 +266,194 @@ pub(crate) async fn end_unfinished( true } +/// The round's WIP branch, ready to write to: the one it already has when +/// it continues (`reuse`), else a fresh one at the pull request's head. +/// Returns its name. +pub(crate) async fn open_wip( + github: &GitHubClient, + owner: &str, + repo: &str, + pr_branch: &str, + reuse: &str, +) -> Result> { + if !reuse.is_empty() && github.get_ref(owner, repo, reuse).await.is_ok() { + return Ok(reuse.to_string()); + } + let wip = run_round::wip_branch(pr_branch); + // A leftover WIP branch has no pull request, so this resets it to the + // pull request's head. + github.create_branch(owner, repo, &wip, pr_branch).await?; + Ok(wip) +} + +/// One file the round changed, from a compare of its start and its WIP head. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Changed { + pub path: String, + pub removed: bool, + /// The old path of a renamed file. + pub previous: Option, +} + +/// The files a compare (`base...wip`) says the round changed. +pub(crate) fn changed_from_compare(compare: &serde_json::Value) -> Vec { + compare["files"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|f| { + let path = f["filename"].as_str()?.to_string(); + let status = f["status"].as_str().unwrap_or(""); + Some(Changed { + path, + removed: status == "removed", + previous: (status == "renamed") + .then(|| f["previous_filename"].as_str().map(String::from)) + .flatten(), + }) + }) + .collect() + }) + .unwrap_or_default() +} + +/// Files the pull request changed since the round started (someone else's +/// push) that the round changed too: landing would overwrite them. +pub(crate) fn overlap(ours: &[Changed], theirs: &[String]) -> Vec { + ours.iter() + .flat_map(|c| std::iter::once(&c.path).chain(c.previous.iter())) + .filter(|p| theirs.contains(p)) + .cloned() + .collect() +} + +/// How landing a round went. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Landed { + /// One commit on the pull request carries the round's changes. + Pushed { files: usize }, + /// The round changed nothing. + Nothing, + /// Not landed (the WIP branch is kept): why. + Refused(String), +} + +/// Lands a finished round on the pull request: everything it changed on its +/// WIP branch since `base_sha`, as ONE commit with `message`, in one push. +/// Refuses (keeping the WIP branch) when the pull request changed the same +/// files meanwhile. The WIP branch is deleted once landed. +pub(crate) async fn land(pr: &Pr<'_>, wip: &str, base_sha: &str, message: &str) -> Landed { + let (github, owner, repo) = (pr.github, pr.owner, pr.repo); + if wip.is_empty() || wip == pr.branch || base_sha.is_empty() { + return Landed::Refused("the round has no WIP branch to land".into()); + } + let ours = match github.get_diff(owner, repo, base_sha, wip).await { + Ok(c) => changed_from_compare(&c), + Err(e) => return Landed::Refused(format!("its changes couldn't be read ({e})")), + }; + if ours.is_empty() { + let _ = github.delete_branch(owner, repo, wip).await; + return Landed::Nothing; + } + match github.get_ref(owner, repo, pr.branch).await { + Ok(head) if head != base_sha => { + let theirs: Vec = github + .get_diff(owner, repo, base_sha, &head) + .await + .map(|c| { + changed_from_compare(&c) + .into_iter() + .flat_map(|c| std::iter::once(c.path).chain(c.previous)) + .collect() + }) + .unwrap_or_default(); + let clash = overlap(&ours, &theirs); + if !clash.is_empty() { + return Landed::Refused(format!( + "the pull request changed the same files meanwhile ({})", + clash.join(", ") + )); + } + } + Ok(_) => {} + Err(e) => { + return Landed::Refused(format!("the pull request's head couldn't be read ({e})")) + } + } + let mut ops = Vec::new(); + for c in &ours { + if let Some(prev) = &c.previous { + ops.push(FileOp::Delete { path: prev.clone() }); + } + if c.removed { + ops.push(FileOp::Delete { + path: c.path.clone(), + }); + continue; + } + match github.read_file_live(owner, repo, &c.path, wip).await { + Ok(content) => ops.push(FileOp::Write { + path: c.path.clone(), + content, + }), + Err(e) => { + return Landed::Refused(format!( + "`{}` couldn't be read from the WIP branch ({e})", + c.path + )) + } + } + } + match github + .batch_write(owner, repo, pr.branch, message, &ops) + .await + { + Ok(_) => { + let _ = github.delete_branch(owner, repo, wip).await; + Landed::Pushed { files: ours.len() } + } + Err(e) => Landed::Refused(format!("the one commit couldn't be pushed ({e})")), + } +} + +/// The one commit message a round lands with, in the team's commit style. +pub(crate) async fn round_message( + state: &WorkerState, + team_id: &str, + ticket: &crate::models::TicketMessage, + round: &Round, +) -> String { + let summary = match round.kind { + Kind::CiFix => "Fix the failing checks", + Kind::ReviewFix => "Address the review", + Kind::Feedback => "Address the review comments", + }; + let conventions = super::load_git_conventions(state, team_id, &ticket.ticket_id).await; + conventions.commit_message(&super::ticket_tokens(ticket), summary) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_rounds_changes_are_read_from_its_wip_compare() { + let compare = serde_json::json!({"files": [ + {"filename": "src/tabs.tsx", "status": "added"}, + {"filename": "src/old.ts", "status": "removed"}, + {"filename": "src/new.ts", "status": "renamed", "previous_filename": "src/was.ts"}, + {"filename": "src/a.ts", "status": "modified"} + ]}); + let c = changed_from_compare(&compare); + assert_eq!(c.len(), 4); + assert!(c[1].removed); + assert_eq!(c[2].previous.as_deref(), Some("src/was.ts")); + // Someone pushed to the PR meanwhile: only the same files block. + assert!(overlap(&c, &["README.md".to_string()]).is_empty()); + assert_eq!(overlap(&c, &["src/a.ts".to_string()]), vec!["src/a.ts"]); + assert_eq!(overlap(&c, &["src/was.ts".to_string()]), vec!["src/was.ts"]); + } + #[test] fn a_round_starts_only_with_enough_of_its_budget_left() { let start = Instant::now(); From 2be1858fafcf8530adf42ee3a01167ca8bd6e434 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 27 Oct 2026 15:55:14 -0400 Subject: [PATCH 5/5] Re-run fix on an existing PR: one push, partial work kept off the PR A run that finds its ticket's PR open with failing checks or review comments fixed them by writing straight to the PR branch, one push per edit. It now works like the other fix rounds: checkpoints on coderhelm-wip/, one commit landed on the PR at the end in the team's commit style, and a fix that runs out of time or can't land keeps its work on the WIP branch and never reaches the PR. It also gets the run's implement deadline instead of none. Also updates the run_of tests for the trigger lookups argument main added. --- services/gateway/src/routes/api.rs | 7 ++-- services/worker/src/passes/mod.rs | 52 ++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index fa9b6b53f..13b4e32d7 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -6070,7 +6070,7 @@ mod tests { cache_write: 0, cost_usd: 0.0, }; - let run = serde_json::to_value(run_of(&item, "r1", usage)).unwrap(); + let run = serde_json::to_value(run_of(&item, "r1", usage, &Default::default())).unwrap(); let r = &run["round_incomplete"]; assert_eq!(run["status"], "completed"); assert_eq!(r["kind"], "review_fix"); @@ -6092,7 +6092,8 @@ mod tests { cost_usd: 0.0, }; assert!( - serde_json::to_value(run_of(&plain, "r2", usage)).unwrap()["round_incomplete"] + serde_json::to_value(run_of(&plain, "r2", usage, &Default::default())).unwrap() + ["round_incomplete"] .is_null() ); } @@ -6174,7 +6175,7 @@ mod tests { cache_write: 0, cost_usd: 0.0, }; - let run = serde_json::to_value(run_of(&item, "r", usage)).unwrap(); + let run = serde_json::to_value(run_of(&item, "r", usage, &Default::default())).unwrap(); assert_eq!( run["codegen_env_missing"]["vars"][0], "SANITY_STUDIO_PROJECT_ID" diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 0e8a753b0..7ccea7661 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -2628,12 +2628,21 @@ async fn run_passes( let pass_start = std::time::Instant::now(); let usage_before = usage.clone(); + // A fix round on an open PR: checkpoints go to its own WIP + // branch, and the PR gets one commit (one push) at the end. + let fix_base = + round::branch_head(&github, &msg.repo_owner, &msg.repo_name, &branch_name) + .await; + let fix_wip = + round::open_wip(&github, &msg.repo_owner, &msg.repo_name, &branch_name, "") + .await?; + match implement::run( state, msg, &github, &plan_result, - &branch_name, + &fix_wip, &[], "", Some(&feedback), @@ -2642,14 +2651,51 @@ async fn run_passes( usage, &file_cache, Some(run_id), - None, + implement_deadline, // Scoped only when purely CI-driven; human review comments // in the feedback mean the human's ask wins (unscoped). !has_review_feedback, ) .await - { + .and_then(|r| { + // Partial work never reaches the PR: it stays on the WIP + // branch, and the run starts over below. + if r.timed_out { + Err(format!("ran out of time; its work is kept on `{fix_wip}`").into()) + } else { + Ok(r) + } + }) { Ok(result) => { + let landed = round::land( + &round::Pr { + github: &github, + owner: &msg.repo_owner, + repo: &msg.repo_name, + branch: &branch_name, + }, + &fix_wip, + &fix_base, + &conventions.commit_message( + &tokens, + "Fix the pull request's checks and review comments", + ), + ) + .await; + if let round::Landed::Refused(why) = &landed { + warn!( + run_id, + why, + "Fix on re-run didn't land; its work is kept on the WIP branch" + ); + add_progress_note( + state, + &msg.team_id, + run_id, + &format!("The fix for PR #{pr_number} didn't land ({why}); its work is kept on `{fix_wip}`"), + ) + .await; + } write_pass_trace( state, &msg.team_id,