diff --git a/docs/api/openapi.json b/docs/api/openapi.json index b74103f49..b47881ec0 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -3874,6 +3874,17 @@ "string", "null" ] + }, + "waiting_on": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RunWaitingOn", + "description": "Set while the run is `needs_input`: what it waits for from a person\n(its questions, or a named action such as reviewing its pull\nrequest). A run never waits on a person for nothing." + } + ] } }, "required": [ @@ -4382,6 +4393,50 @@ ], "type": "object" }, + "RunWaitingOn": { + "description": "What a run waiting on a person (`needs_input`) is waiting for: the\nquestions to answer, or one named action.", + "properties": { + "action": { + "description": "What to do, in plain words.", + "examples": [ + "Review pull request #318" + ], + "type": "string" + }, + "detail": { + "description": "Why, or what is still open. May be empty.", + "examples": [ + "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + ], + "type": "string" + }, + "since": { + "description": "When the wait started (RFC 3339).", + "examples": [ + "2026-10-22T14:15:25Z" + ], + "type": [ + "string", + "null" + ] + }, + "url": { + "description": "Where to do it (the pull request, the ticket), when known.", + "examples": [ + "https://github.com/acme/web/pull/318" + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "action", + "detail" + ], + "type": "object" + }, "RunsPage": { "description": "A page of runs.", "properties": { diff --git a/infra/lib/monitoring-stack.ts b/infra/lib/monitoring-stack.ts index 6a74ae9cf..9b622819b 100644 --- a/infra/lib/monitoring-stack.ts +++ b/infra/lib/monitoring-stack.ts @@ -155,6 +155,32 @@ export class MonitoringStack extends cdk.Stack { metricName: "RunLoopStopped", metricValue: "1", }); + // Each run the stuck-run sweep found waiting on a person with nothing + // asked (services/common/src/run_wait.rs): the worker can no longer + // write one, so any is a bug, and an alarm says so. + const cleanupLogs = logs.LogGroup.fromLogGroupName( + this, + "StuckRunCleanupLogs", + `/aws/lambda/${prefix}-stuck-run-cleanup` + ); + const unaskedMetric = new logs.MetricFilter(this, "RunWaitingUnaskedFilter", { + logGroup: cleanupLogs, + filterPattern: logs.FilterPattern.literal('"run_waiting_unasked"'), + metricNamespace: "CoderHelm/Runs", + metricName: "RunWaitingUnasked", + metricValue: "1", + }).metric({ period: cdk.Duration.hours(1), statistic: "Sum" }); + const unaskedAlarm = new cloudwatch.Alarm(this, "RunWaitingUnaskedAlarm", { + alarmName: `${prefix}-run-waiting-unasked`, + alarmDescription: + "A run waited on a person with nothing asked. The stuck-run sweep named its wait and notified the team; find the write that set needs_input without one.", + metric: unaskedMetric, + threshold: 1, + evaluationPeriods: 1, + comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD, + treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING, + }); + unaskedAlarm.addAlarmAction(new actions.SnsAction(alertTopic)); const modelRequeuedMetric = new logs.MetricFilter(this, "ModelErrorRequeuedFilter", { logGroup: workerLogs, filterPattern: logs.FilterPattern.literal('"model_error_requeued"'), diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index 0467ad6b0..f9b3ba539 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -531,10 +531,14 @@ export class WorkerStack extends cdk.Stack { // The last pass a stuck run reached when its record names none. TRACES_TABLE_NAME: props.tracesTable.tableName, CHECKPOINTS_TABLE_NAME: props.checkpointsTable.tableName, + // A run waiting on a person: its reminder, and the notice for a + // wait the sweep named, go to the worker as `run_waiting`. + TICKET_QUEUE_URL: props.ticketQueue.queueUrl, }, }); runsTable.grantReadWriteData(cleanupFunction); + props.ticketQueue.grantSendMessages(cleanupFunction); props.tracesTable.grantReadData(cleanupFunction); props.checkpointsTable.grantReadData(cleanupFunction); // The runs table is CMK-encrypted; grantReadWriteData on a fromTableName diff --git a/lambda/stuck-run-cleanup/handler.py b/lambda/stuck-run-cleanup/handler.py index 409b80a8f..df6de033a 100644 --- a/lambda/stuck-run-cleanup/handler.py +++ b/lambda/stuck-run-cleanup/handler.py @@ -21,8 +21,21 @@ 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. + +Runs waiting on a person (services/common/src/run_wait.rs): a `needs_input` +run always names what it waits for (`waiting_on`: its questions, or one +action such as reviewing its pull request). The sweep reads every +`needs_input` run too: +- one that names nothing (written before that rule, or by hand) is reported + (`run_waiting_unasked` in the log, counted by the monitoring stack) and + given a named wait: the review of its pull request when it has one, else + a Retry with the reason it stopped. The worker then sends the usual + `run.needs_input` notification for it; +- one still waiting WAIT_REMIND_AFTER_HOURS after its wait started gets one + reminder through the same notification. """ +import json import logging import os from datetime import datetime, timezone, timedelta @@ -42,6 +55,17 @@ # closed) is never swept, and neither is any other finished run. SWEPT_STATUSES = ("running", "awaiting_ci") +# Runs waiting on a person. Mirrors services/common/src/run_wait.rs (a test +# there reads these lines). +NEEDS_INPUT = "needs_input" +WAITING_ON_FIELD = "waiting_on" +REMINDED_FIELD = "wait_reminded_at" +WAIT_REMIND_AFTER_HOURS = 24 +QUESTIONS_FIELD = "questions" +# The worker's queue: the reminder and the notice for a named wait go out as +# a `run_waiting` message (services/common/contract/worker_messages.json). +TICKET_QUEUE_URL = os.environ.get("TICKET_QUEUE_URL", "") + # Values of current_pass that name a state, not a pass the run was doing. NOT_A_PASS = {"", "unknown", "cancelled", "closed", "done", "awaiting_ci"} BEFORE_FIRST_PASS = "before its first pass" @@ -76,6 +100,7 @@ } _dynamodb = None +_sqs = None def _db(): @@ -87,6 +112,151 @@ def _db(): return _dynamodb +def _queue(): + global _sqs + if _sqs is None: + import boto3 + + _sqs = boto3.client("sqs") + return _sqs + + +def _json(value): + try: + return json.loads(value) if isinstance(value, str) and value else None + except ValueError: + return None + + +def asks_something(run): + """True when a run record names what it waits for: questions to answer + or a named action (the same test as run_wait::asks_something).""" + asked = _json(run.get(QUESTIONS_FIELD)) or {} + questions = asked.get("questions") if isinstance(asked, dict) else None + if any( + isinstance(q, dict) and str(q.get("question") or "").strip() + for q in (questions or []) + ): + return True + wait = _json(run.get(WAITING_ON_FIELD)) + return isinstance(wait, dict) and bool(str(wait.get("action") or "").strip()) + + +def named_wait(run, now_iso): + """The wait for a needs_input run that named none: its pull request's + review when it has one (it did its work), else a Retry with its reason. + The words mirror WaitingOn::review_pr and mark_run_stopped_by_guard.""" + reason = " ".join(str(run.get("error_message") or "").split()) + if has_pull_request(run): + try: + number = int(run.get("pr_number") or 0) + except (TypeError, ValueError): + number = 0 + action = f"Review pull request #{number}" if number > 0 else "Review the pull request" + if reason: + detail = ( + f"Open on the pull request: {reason.rstrip('.')}. Mark it ready once that is dealt " + "with, push a fix or comment on it, and CoderHelm picks it up from there." + ) + else: + detail = ( + "The work is on the pull request. Review it, push a fix or comment on it, and " + "CoderHelm picks it up from there." + ) + return { + "action": action, + "detail": detail, + "url": str(run.get("pr_url") or ""), + "since": now_iso, + } + return { + "action": "Read why CoderHelm stopped this run, then press Retry or close it", + "detail": reason or "It stopped waiting on a person without saying what for.", + "since": now_iso, + } + + +def wait_since(run): + """When the current wait started: its waiting_on, else the last update.""" + wait = _json(run.get(WAITING_ON_FIELD)) or {} + since = _parse_time(wait.get("since")) if isinstance(wait, dict) else None + return since or _parse_time(run.get("updated_at") or run.get("created_at")) + + +def reminder_due(run, now): + """One reminder, WAIT_REMIND_AFTER_HOURS into the wait (run_wait::reminder_due).""" + since = wait_since(run) + if since is None or now - since < timedelta(hours=WAIT_REMIND_AFTER_HOURS): + return False + reminded = _parse_time(run.get(REMINDED_FIELD)) + return not (reminded is not None and reminded >= since) + + +def waiting_message(run, why): + """The worker message that sends the notification (contract: run_waiting).""" + return {"type": "run_waiting", "team_id": run["team_id"], "run_id": run["run_id"], "why": why} + + +def _send_waiting(run, why): + if not TICKET_QUEUE_URL: + logger.warning(f"No TICKET_QUEUE_URL: the {why} notice for {run['run_id']} isn't sent") + return False + try: + _queue().send_message( + QueueUrl=TICKET_QUEUE_URL, MessageBody=json.dumps(waiting_message(run, why)) + ) + return True + except Exception as e: + logger.error(f"Could not queue the {why} notice for {run['run_id']}: {e}") + return False + + +def settle_waiting(runs_table, run, now): + """A needs_input run: name its wait when it names none, or remind once. + Returns "named", "reminded" or "".""" + run_id = run["run_id"] + key = {"team_id": run["team_id"], "run_id": run_id} + now_iso = now.isoformat() + try: + if not asks_something(run): + wait = named_wait(run, now_iso) + # The metric filter in the monitoring stack counts this text. + logger.warning( + f"run_waiting_unasked: {run_id} waited on a person with nothing asked " + f"(since {run.get('updated_at', 'N/A')}); now waits for: {wait['action']}" + ) + runs_table.update_item( + Key=key, + UpdateExpression="SET #w = :w", + ExpressionAttributeNames={"#s": "status", "#w": WAITING_ON_FIELD}, + ExpressionAttributeValues={":w": json.dumps(wait), ":ni": NEEDS_INPUT}, + ConditionExpression="#s = :ni", + ) + _send_waiting(run, "named") + return "named" + if reminder_due(run, now): + since = wait_since(run) + runs_table.update_item( + Key=key, + UpdateExpression="SET #r = :now", + ExpressionAttributeNames={"#s": "status", "#r": REMINDED_FIELD}, + ExpressionAttributeValues={ + ":now": now_iso, + ":ni": NEEDS_INPUT, + ":since": since.isoformat(), + }, + # Once per wait, even when two sweeps overlap. + ConditionExpression="#s = :ni AND (attribute_not_exists(#r) OR #r < :since)", + ) + _send_waiting(run, "reminder") + return "reminded" + except _db().meta.client.exceptions.ConditionalCheckFailedException: + logger.info(f"Run {run_id} moved on or was reminded already") + except Exception as e: + logger.error(f"Could not settle the waiting run {run_id}: {e}") + return "" + + def last_known_pass(run, checkpoint_pass="", trace_pass=""): """The last pass the run is known to have reached, or "" if none.""" current = (run.get("current_pass") or "").strip() @@ -197,15 +367,23 @@ def over_ceiling_update(run_id, code, reason, now_iso): return ( "SET #s = :new, status_run_id = :sri, error_message = :err, current_pass = :cp, " "updated_at = :now, guard_open = :yes, loop_stop_reason = :code, " - "loop_stop_detail = :err, loop_stopped_at = :now", + "loop_stop_detail = :err, loop_stopped_at = :now, waiting_on = :wo", { - ":new": "needs_input", - ":sri": f"needs_input#{run_id}", + ":new": NEEDS_INPUT, + ":sri": f"{NEEDS_INPUT}#{run_id}", ":err": reason, ":cp": "done", ":now": now_iso, ":yes": True, ":code": code, + # Waiting on a person, by name: never for nothing. + ":wo": json.dumps( + { + "action": "Read why CoderHelm ended this run, then press Retry or close it", + "detail": reason, + "since": now_iso, + } + ), }, ) @@ -361,26 +539,38 @@ def handler(event, context): # before, so awaiting_ci runs sat forever. stuck_runs = [] over_count = 0 + waiting = {"named": 0, "reminded": 0} scan_kwargs = { - "FilterExpression": "#s = :running OR #s = :awaiting", + "FilterExpression": "#s = :running OR #s = :awaiting OR #s = :ni", "ExpressionAttributeNames": {"#s": "status"}, "ExpressionAttributeValues": { ":running": SWEPT_STATUSES[0], ":awaiting": SWEPT_STATUSES[1], + ":ni": NEEDS_INPUT, }, "ProjectionExpression": ( "team_id, run_id, created_at, updated_at, title, current_pass, pass_history, #s, " "step_queued_at, ceil_passes, ceil_continuations, ceil_worked_secs, ceil_spend_usd, " - "#round, pr_number, pr_url" + "#round, pr_number, pr_url, error_message, #q, #w, #r" ), } scan_kwargs["ExpressionAttributeNames"]["#round"] = ROUND_FIELD + scan_kwargs["ExpressionAttributeNames"]["#q"] = QUESTIONS_FIELD + scan_kwargs["ExpressionAttributeNames"]["#w"] = WAITING_ON_FIELD + scan_kwargs["ExpressionAttributeNames"]["#r"] = REMINDED_FIELD while True: resp = runs_table.scan(**scan_kwargs) for item in resp.get("Items", []): updated = item.get("updated_at", item.get("created_at", "")) status = item.get("status", "") + if status == NEEDS_INPUT: + # Waiting on a person: never failed or completed here, only + # named when it names nothing, and reminded once. + done = settle_waiting(runs_table, item, now) + if done: + waiting[done] += 1 + continue cutoff = running_cutoff if status == "running" else awaiting_cutoff # First, whatever else is true of the run: its ceiling isn't a # question of how long ago it last moved. @@ -404,7 +594,12 @@ def handler(event, context): if not stuck_runs: logger.info("No stuck runs found") - return {"stuck_count": 0, "over_ceiling": over_count} + return { + "stuck_count": 0, + "over_ceiling": over_count, + "waiting_named": waiting["named"], + "waiting_reminded": waiting["reminded"], + } logger.info(f"Found {len(stuck_runs)} stuck runs") @@ -493,4 +688,6 @@ def handler(event, context): "stuck_count": len(stuck_runs), "unstuck_count": failed_count, "over_ceiling": over_count, + "waiting_named": waiting["named"], + "waiting_reminded": waiting["reminded"], } diff --git a/lambda/tests/test_stuck_run_cleanup.py b/lambda/tests/test_stuck_run_cleanup.py index 2cff6ad63..cd9fe8d68 100644 --- a/lambda/tests/test_stuck_run_cleanup.py +++ b/lambda/tests/test_stuck_run_cleanup.py @@ -218,3 +218,112 @@ def test_a_step_queued_too_long_is_swept(self): def test_no_step_queued(self): self.assertFalse(sweep.step_queued({"updated_at": self.at(30)}, self.NOW)) + + +class WaitingOnAPerson(unittest.TestCase): + """A needs_input run never waits for nothing (services/common/src/run_wait.rs).""" + + NOW = sweep.datetime(2026, 11, 5, 15, 0, tzinfo=sweep.timezone.utc) + + def _sweep(self, runs): + updates, sent = [], [] + + class Table: + def scan(self, **kw): + return {"Items": runs} + + def update_item(self, **kw): + updates.append(kw) + + class Db: + class meta: + class client: + class exceptions: + ConditionalCheckFailedException = KeyError + + def Table(self, _name): + return Table() + + class Sqs: + def send_message(self, **kw): + sent.append(sweep.json.loads(kw["MessageBody"])) + + sweep._dynamodb, sweep._sqs = Db(), Sqs() + old_url, sweep.TICKET_QUEUE_URL = sweep.TICKET_QUEUE_URL, "https://sqs/q" + try: + out = sweep.handler({}, None) + finally: + sweep._dynamodb, sweep._sqs, sweep.TICKET_QUEUE_URL = None, None, old_url + return out, updates, sent + + def test_a_stalled_run_with_its_pull_request_is_found_and_handed_to_review(self): + # It did its work, opened a draft pull request with a check's finding + # as its open item, and waited with no question for three days. + run = { + "team_id": "T", + "run_id": "R", + "status": "needs_input", + "updated_at": "2026-11-02T10:00:00+00:00", + "pr_number": 7, + "pr_url": "https://github.com/o/r/pull/7", + "error_message": "The new-feature rules blocked the pull request: new items aren't registered", + "questions": '{"questions":[],"asked_at":""}', + } + self.assertFalse(sweep.asks_something(run)) + out, updates, sent = self._sweep([run]) + self.assertEqual(out["waiting_named"], 1) + self.assertEqual(out["stuck_count"], 0) + self.assertEqual(len(updates), 1) + wait = sweep.json.loads(updates[0]["ExpressionAttributeValues"][":w"]) + self.assertEqual(wait["action"], "Review pull request #7") + self.assertIn("new items aren't registered", wait["detail"]) + self.assertEqual(wait["url"], "https://github.com/o/r/pull/7") + self.assertEqual(updates[0]["ConditionExpression"], "#s = :ni") + self.assertEqual(sent, [{"type": "run_waiting", "team_id": "T", "run_id": "R", "why": "named"}]) + # Never failed or completed: still waiting, now for something named. + self.assertNotIn(":new", updates[0]["ExpressionAttributeValues"]) + + def test_without_a_pull_request_it_waits_for_a_retry(self): + wait = sweep.named_wait({"error_message": "stopped"}, "now") + self.assertIn("Retry", wait["action"]) + self.assertEqual(wait["detail"], "stopped") + + def test_one_reminder_after_the_wait(self): + wait = sweep.json.dumps({"action": "Review pull request #7", "since": "2026-11-04T16:00:00+00:00"}) + run = {"team_id": "T", "run_id": "R", "status": "needs_input", "waiting_on": wait} + self.assertTrue(sweep.asks_something(run)) + self.assertFalse(sweep.reminder_due(run, self.NOW)) + later = self.NOW + sweep.timedelta(hours=2) + self.assertTrue(sweep.reminder_due(run, later)) + reminded = dict(run, wait_reminded_at="2026-11-05T16:30:00+00:00") + self.assertFalse(sweep.reminder_due(reminded, later + sweep.timedelta(days=3))) + + old = dict(run, waiting_on=sweep.json.dumps({"action": "Answer", "since": "2026-11-01T00:00:00+00:00"})) + out, updates, sent = self._sweep([old]) + self.assertEqual(out["waiting_reminded"], 1) + self.assertIn("attribute_not_exists(#r)", updates[0]["ConditionExpression"]) + self.assertEqual(sent[0]["why"], "reminder") + + def test_a_run_with_questions_and_a_fresh_wait_is_left_alone(self): + run = { + "team_id": "T", + "run_id": "R", + "status": "needs_input", + "updated_at": self.NOW.isoformat(), + "questions": '{"questions":[{"id":"q1","question":"Which one?"}]}', + } + self.assertTrue(sweep.asks_something(run)) + self.assertFalse(sweep.reminder_due(run, self.NOW)) + + def test_the_message_is_one_the_worker_reads(self): + contract = sweep.json.loads( + (HANDLER.parents[2] / "services/common/contract/worker_messages.json").read_text() + ) + sample = contract["scheduled"]["run_waiting"] + msg = sweep.waiting_message({"team_id": "T", "run_id": "R"}, "reminder") + self.assertEqual(set(msg), set(sample)) + self.assertEqual(msg["type"], sample["type"]) + + def test_over_its_ceiling_it_waits_for_something_named(self): + _, values = sweep.over_ceiling_update("R1", "ceiling_spend", "why", "now") + self.assertIn("Retry", sweep.json.loads(values[":wo"])["action"]) diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index 02ff787a8..de52e104d 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -43,6 +43,7 @@ "log_autofix": {"type":"log_autofix"}, "aws_permissions_sweep": {"type":"aws_permissions_sweep"}, "agent_resume_sweep": {"type":"agent_resume_sweep"}, + "run_waiting": {"type":"run_waiting","team_id":"TEAM#team-a","run_id":"r1","why":"reminder"}, "knowledge_sync_sweep": {"type":"knowledge_sync_sweep"}, "knowledge_sync": {"type":"knowledge_sync","team_id":"TEAM#team-a","kb_id":"kb1","source_id":"src1"}, "plugin_sweep": {"type":"plugin_sweep"}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 91eb66b7f..8bff3a9eb 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -66,6 +66,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "aws_permissions_sweep", // Resumes agent work kept while a team's agents were paused. "agent_resume_sweep", + // A run waiting on a person: its reminder (from the stuck-run sweep). + "run_waiting", // A model call's usage, held because its counters couldn't be written. "usage_record", // Knowledge sources: the scheduled sweep, and one source's sync. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 1620d0ac8..79ed01a1f 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -133,6 +133,8 @@ pub mod run_questions; pub mod run_round; /// Run statuses; which ones a person set; closing and reopening a run. pub mod run_status; +/// What a run waiting on a person is waiting for: never nothing. +pub mod run_wait; #[cfg(test)] mod selfhost_links; pub mod skill_apply; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 87c40cf40..a9fdaa8b4 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -176,6 +176,12 @@ pub enum WorkerMessage { /// passing needs nobody to click anything). #[serde(rename = "agent_resume_sweep")] AgentResumeSweep, + /// A run waiting on a person, from the stuck-run sweep: its one + /// reminder, or the notice for a wait the sweep just named (a run left + /// `needs_input` with nothing asked). Sent as the usual + /// `run.needs_input` event (`common::run_wait`). + #[serde(rename = "run_waiting")] + RunWaiting(RunWaitingMessage), /// One plugin run: a brief, a schedule or a release (see /// `plugins::run`). #[serde(rename = "plugin_run")] @@ -413,6 +419,7 @@ impl WorkerMessage { | WorkerMessage::DlqCleanup | WorkerMessage::KnowledgeSyncSweep | WorkerMessage::AgentResumeSweep + | WorkerMessage::RunWaiting(_) | WorkerMessage::LogAutofix | WorkerMessage::AwsPermissionsSweep | WorkerMessage::HybridNameCheck @@ -483,6 +490,7 @@ impl WorkerMessage { | WorkerMessage::RewardOutcome(_) | WorkerMessage::JiraComment(_) | WorkerMessage::AgentResumeSweep + | WorkerMessage::RunWaiting(_) | WorkerMessage::PluginRun(_) | WorkerMessage::PluginPublish(_) | WorkerMessage::PluginSync(_) @@ -672,6 +680,18 @@ pub struct WebhookEmitMessage { pub event: crate::webhooks::Event, } +/// A run waiting on a person that the stuck-run sweep found: tell the team +/// again what it waits for. +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct RunWaitingMessage { + pub team_id: String, + pub run_id: String, + /// `reminder`: still waiting after `run_wait::REMIND_AFTER_HOURS`. + /// `named`: it waited for nothing, and the sweep just named what for. + #[serde(default)] + pub why: String, +} + /// One webhook delivery to try (again). #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] pub struct WebhookSendMessage { diff --git a/services/common/src/run_wait.rs b/services/common/src/run_wait.rs new file mode 100644 index 000000000..b628a738e --- /dev/null +++ b/services/common/src/run_wait.rs @@ -0,0 +1,411 @@ +//! What a run waiting on a person (`needs_input`) is waiting for. +//! +//! A run did its work, opened a draft pull request with a check's finding as +//! its open item, and was set to `needs_input` with no question: nothing +//! asked anyone anything, the run page said it needed "more detail", and the +//! run sat for days while its pull request only needed a review. Waiting on +//! a person is now always for something named: +//! +//! - every `needs_input` write carries a [`WaitingOn`] (`waiting_on`): the +//! questions to answer on the run page, or one named action (review pull +//! request #n, answer an approval, add the missing detail to the ticket), +//! with where to do it. The only way to write the status is +//! [`NeedsInput::needs_input`], which takes one; a test reads the +//! services' sources so no write sets the status any other way; +//! - the run page shows it and the `run.needs_input` event carries it; +//! - a run still waiting [`REMIND_AFTER_HOURS`] after it started waiting +//! gets one reminder through the same event (the stuck-run sweep); +//! - the stuck-run sweep reports and settles any `needs_input` run with +//! neither (written before this, or by hand). + +use std::collections::HashMap; + +use aws_sdk_dynamodb::operation::update_item::builders::UpdateItemFluentBuilder; +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +use crate::run_questions::{Asked, Question, FIELD_QUESTIONS}; +use crate::run_status::NEEDS_INPUT; + +/// Run attribute holding the [`WaitingOn`] JSON. +pub const FIELD_WAITING_ON: &str = "waiting_on"; +/// Run attribute: when the one reminder for the current wait was sent. +pub const FIELD_REMINDED_AT: &str = "wait_reminded_at"; +/// A run waiting on a person this long gets one reminder. Mirrored in +/// lambda/stuck-run-cleanup/handler.py (a test here reads that line). +pub const REMIND_AFTER_HOURS: i64 = 24; + +const MAX_ACTION_CHARS: usize = 200; +const MAX_DETAIL_CHARS: usize = 1_500; + +/// The one thing a waiting run needs from a person. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct WaitingOn { + /// What to do, in plain words ("Review pull request #12"). + pub action: String, + /// Why, or what is open, in plain words. May be empty. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub detail: String, + /// Where to do it (the pull request, the ticket), when known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + /// How many questions the run page asks, when the action is to answer + /// them. + #[serde(default, skip_serializing_if = "is_zero")] + pub questions: usize, + /// When the wait started (RFC 3339): the reminder counts from here. + #[serde(default)] + pub since: String, +} + +fn is_zero(n: &usize) -> bool { + *n == 0 +} + +fn one_line(s: &str, max: usize) -> String { + let s = s.split_whitespace().collect::>().join(" "); + crate::truncate_str(&s, max).to_string() +} + +fn bounded(s: &str, max: usize) -> String { + crate::truncate_str(s.trim(), max).to_string() +} + +fn now() -> String { + chrono::Utc::now().to_rfc3339() +} + +impl WaitingOn { + /// A named action. `None` when `action` is blank: a wait is never for + /// nothing. + pub fn action(action: &str, detail: &str, url: &str) -> Option { + let action = one_line(action, MAX_ACTION_CHARS); + (!action.is_empty()).then(|| WaitingOn { + action, + detail: bounded(detail, MAX_DETAIL_CHARS), + url: url.trim().to_string(), + questions: 0, + since: now(), + }) + } + + /// A named action written in the code (never blank). + pub fn fixed(action: &'static str, detail: &str, url: &str) -> Self { + debug_assert!(!action.trim().is_empty()); + WaitingOn { + action: action.to_string(), + detail: bounded(detail, MAX_DETAIL_CHARS), + url: url.trim().to_string(), + questions: 0, + since: now(), + } + } + + /// The questions when there are any, else `fallback`. + pub fn answer_or(questions: &[Question], where_asked: Option<&str>, fallback: Self) -> Self { + Self::answer(questions, where_asked).unwrap_or(fallback) + } + + /// Answer the questions on the run page. `None` when there are none. + pub fn answer(questions: &[Question], where_asked: Option<&str>) -> Option { + let asked: Vec<&Question> = questions + .iter() + .filter(|q| !q.question.trim().is_empty()) + .collect(); + if asked.is_empty() { + return None; + } + let action = if asked.len() == 1 { + "Answer CoderHelm's question on the run page".to_string() + } else { + format!( + "Answer CoderHelm's {} questions on the run page", + asked.len() + ) + }; + let mut w = Self::action(&action, &asked[0].question, where_asked.unwrap_or(""))?; + w.questions = asked.len(); + Some(w) + } + + /// Review the run's pull request: the run did its work and is waiting + /// for review, with what is still open on the pull request. `None` when + /// there is no pull request to point at. + pub fn review_pr(number: u64, url: &str, open: &str) -> Option { + if number == 0 && url.trim().is_empty() { + return None; + } + let action = if number > 0 { + format!("Review pull request #{number}") + } else { + "Review the pull request".to_string() + }; + let detail = if open.trim().is_empty() { + "The work is on the pull request. Review it, push a fix or comment on it, and \ + CoderHelm picks it up from there." + .to_string() + } else { + format!( + "Open on the pull request: {}. Mark it ready once that is dealt with, push a fix \ + or comment on it, and CoderHelm picks it up from there.", + one_line(open, MAX_DETAIL_CHARS - 160).trim_end_matches('.') + ) + }; + Self::action(&action, &detail, url) + } + + /// The wait in one line, for a notification or a list. + pub fn line(&self) -> String { + let mut s = self.action.clone(); + if !self.detail.is_empty() { + s.push_str(": "); + s.push_str(&one_line(&self.detail, 600)); + } + s + } + + /// The attribute value it is stored as. + pub fn to_attr(&self) -> AttributeValue { + AttributeValue::S(serde_json::to_string(self).unwrap_or_default()) + } + + /// Read back from a run record. `None` when absent, unreadable or blank. + pub fn of_item(item: &HashMap) -> Option { + let w: WaitingOn = item + .get(FIELD_WAITING_ON) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str(s).ok())?; + (!w.action.trim().is_empty()).then_some(w) + } +} + +/// Whether a run record names what it waits for: questions to answer, or a +/// named action. A `needs_input` run without either is stalled. +pub fn asks_something(item: &HashMap) -> bool { + let asked = item + .get(FIELD_QUESTIONS) + .and_then(|v| v.as_s().ok()) + .and_then(|s| serde_json::from_str::(s).ok()) + .is_some_and(|a| a.questions.iter().any(|q| !q.question.trim().is_empty())); + asked || WaitingOn::of_item(item).is_some() +} + +/// The one way to write `needs_input`: with what the run waits for. +pub trait NeedsInput { + /// Sets `:s` to `needs_input`, `:sri` to its `status_run_id` and `:wo` + /// to `wait`. The update expression names them: + /// `#s = :s, status_run_id = :sri, waiting_on = :wo`. + fn needs_input(self, run_id: &str, wait: &WaitingOn) -> Self; +} + +impl NeedsInput for UpdateItemFluentBuilder { + fn needs_input(self, run_id: &str, wait: &WaitingOn) -> Self { + self.expression_attribute_values(":s", AttributeValue::S(NEEDS_INPUT.into())) + .expression_attribute_values( + ":sri", + AttributeValue::S(format!("{NEEDS_INPUT}#{run_id}")), + ) + .expression_attribute_values(":wo", wait.to_attr()) + } +} + +/// Whether a run waiting since `since` is due its one reminder at `now`: +/// waiting [`REMIND_AFTER_HOURS`] or more, and not reminded since it started +/// waiting. +pub fn reminder_due( + since: &str, + reminded_at: Option<&str>, + now: chrono::DateTime, +) -> bool { + let parse = |s: &str| { + chrono::DateTime::parse_from_rfc3339(s) + .ok() + .map(|t| t.with_timezone(&chrono::Utc)) + }; + let Some(since) = parse(since) else { + return false; + }; + if now - since < chrono::Duration::hours(REMIND_AFTER_HOURS) { + return false; + } + !reminded_at.and_then(parse).is_some_and(|r| r >= since) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), AttributeValue::S(v.to_string()))) + .collect() + } + + #[test] + fn a_wait_is_never_for_nothing() { + assert_eq!(WaitingOn::action(" ", "detail", ""), None); + assert_eq!(WaitingOn::answer(&[], None), None); + let blank = Question { + id: "q1".into(), + question: " ".into(), + ..Default::default() + }; + assert_eq!(WaitingOn::answer(&[blank], None), None); + assert_eq!(WaitingOn::review_pr(0, " ", "x"), None); + } + + #[test] + fn a_stopped_run_with_a_pull_request_waits_for_its_review() { + let w = WaitingOn::review_pr( + 12, + "https://github.com/o/r/pull/12", + "The new-feature rules: new items aren't registered", + ) + .unwrap(); + assert_eq!(w.action, "Review pull request #12"); + assert!(w.detail.contains("new items aren't registered")); + assert_eq!(w.url, "https://github.com/o/r/pull/12"); + assert!(!w.since.is_empty()); + let back = WaitingOn::of_item(&item(&[( + FIELD_WAITING_ON, + &serde_json::to_string(&w).unwrap(), + )])) + .unwrap(); + assert_eq!(back, w); + assert!(w + .line() + .starts_with("Review pull request #12: Open on the pull request")); + } + + #[test] + fn questions_wait_for_answers() { + let q = Question { + id: "q1".into(), + question: "Per key or per team?".into(), + ..Default::default() + }; + let w = WaitingOn::answer(&[q], Some("https://x/1")).unwrap(); + assert_eq!(w.questions, 1); + assert!(w.action.contains("question")); + } + + #[test] + fn a_record_with_neither_asks_nothing() { + assert!(!asks_something(&item(&[("status", "needs_input")]))); + assert!(!asks_something(&item(&[( + FIELD_QUESTIONS, + r#"{"questions":[],"asked_at":""}"# + )]))); + assert!(!asks_something(&item(&[( + FIELD_WAITING_ON, + r#"{"action":" "}"# + )]))); + assert!(asks_something(&item(&[( + FIELD_QUESTIONS, + r#"{"questions":[{"id":"q1","question":"Which?"}],"asked_at":""}"# + )]))); + assert!(asks_something(&item(&[( + FIELD_WAITING_ON, + r#"{"action":"Review pull request #3","since":""}"# + )]))); + } + + #[test] + fn one_reminder_after_the_wait() { + let t = |s: &str| { + chrono::DateTime::parse_from_rfc3339(s) + .unwrap() + .with_timezone(&chrono::Utc) + }; + let since = "2026-11-02T10:00:00Z"; + assert!(!reminder_due(since, None, t("2026-11-03T09:59:00Z"))); + assert!(reminder_due(since, None, t("2026-11-03T10:00:00Z"))); + assert!(!reminder_due( + since, + Some("2026-11-03T10:05:00Z"), + t("2026-11-05T10:00:00Z") + )); + // A reminder for an earlier wait doesn't count for this one. + assert!(reminder_due( + since, + Some("2026-11-01T10:00:00Z"), + t("2026-11-03T11:00:00Z") + )); + assert!(!reminder_due("", None, t("2026-11-03T11:00:00Z"))); + } + + #[test] + fn the_sweep_reminds_after_the_same_time() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let py = std::fs::read_to_string(root.join("lambda/stuck-run-cleanup/handler.py")).unwrap(); + assert!( + py.contains(&format!("WAIT_REMIND_AFTER_HOURS = {REMIND_AFTER_HOURS}\n")), + "handler.py must mirror REMIND_AFTER_HOURS" + ); + assert!(py.contains(&format!("WAITING_ON_FIELD = \"{FIELD_WAITING_ON}\""))); + assert!(py.contains(&format!("REMINDED_FIELD = \"{FIELD_REMINDED_AT}\""))); + } + + fn sources() -> Vec<(std::path::PathBuf, String)> { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .canonicalize() + .unwrap(); + let mut out = Vec::new(); + let mut stack = vec![root.join("worker/src"), root.join("gateway/src")]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push((p.clone(), std::fs::read_to_string(&p).unwrap_or_default())); + } + } + } + out + } + + /// The code before the file's tests. + fn non_test(text: &str) -> &str { + text.find("#[cfg(test)]") + .map(|i| &text[..i]) + .unwrap_or(text) + } + + #[test] + fn no_write_sets_needs_input_without_what_it_waits_for() { + let mut bad = Vec::new(); + for (path, text) in sources() { + let code = non_test(&text); + let squashed: String = code.split_whitespace().collect(); + for needle in [ + "attr_s(\"needs_input\")", + "attr_s(NEEDS_INPUT)", + "attr_s(run_status::NEEDS_INPUT)", + "attr_s(common::run_status::NEEDS_INPUT)", + "AttributeValue::S(\"needs_input\".into())", + "attr_s(&format!(\"needs_input#", + ] { + if squashed.contains(needle) { + bad.push(format!("{}: {needle}", path.display())); + } + } + if code.contains(".needs_input(") && !code.contains("waiting_on = :wo") { + bad.push(format!( + "{}: calls .needs_input( without `waiting_on = :wo` in its update", + path.display() + )); + } + } + assert!( + bad.is_empty(), + "write needs_input only with run_wait::NeedsInput::needs_input:\n{}", + bad.join("\n") + ); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 3d627b817..53e8ef131 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -909,6 +909,36 @@ pub struct RunNote { pub timestamp: Option, } +/// What a run waiting on a person (`needs_input`) is waiting for: the +/// questions to answer, or one named action. +#[derive(serde::Serialize, utoipa::ToSchema)] +pub struct RunWaitingOn { + /// What to do, in plain words. + #[schema(example = "Review pull request #318")] + pub action: String, + /// Why, or what is still open. May be empty. + #[schema( + example = "Open on the pull request: the link check couldn't reach /pricing. Mark it ready once that is dealt with, push a fix or comment on it, and CoderHelm picks it up from there." + )] + pub detail: String, + /// Where to do it (the pull request, the ticket), when known. + #[schema(example = "https://github.com/acme/web/pull/318")] + pub url: Option, + /// When the wait started (RFC 3339). + #[schema(example = "2026-10-22T14:15:25Z")] + pub since: Option, +} + +fn waiting_on_of(item: &run_search::Item) -> Option { + let w = common::run_wait::WaitingOn::of_item(item)?; + Some(RunWaitingOn { + action: w.action, + detail: w.detail, + url: Some(w.url).filter(|u| !u.is_empty()), + since: Some(w.since).filter(|s| !s.is_empty()), + }) +} + /// 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)] @@ -1139,6 +1169,11 @@ pub struct Run { /// otherwise. #[schema(example = json!(null))] pub codegen_env_missing: Option, + /// Set while the run is `needs_input`: what it waits for from a person + /// (its questions, or a named action such as reviewing its pull + /// request). A run never waits on a person for nothing. + #[schema(example = json!(null))] + pub waiting_on: Option, } /// The public values a run's code generator was missing, as the API shows them. @@ -1590,6 +1625,11 @@ fn run_of( continued_run_id: st("continued_run_id"), round_incomplete: round_incomplete_of(item), codegen_env_missing: codegen_env_missing_of(item), + waiting_on: if st("status").as_deref() == Some(common::run_status::NEEDS_INPUT) { + waiting_on_of(item) + } else { + None + }, } } diff --git a/services/gateway/src/routes/run_close.rs b/services/gateway/src/routes/run_close.rs index b72d828e9..027323649 100644 --- a/services/gateway/src/routes/run_close.rs +++ b/services/gateway/src/routes/run_close.rs @@ -246,6 +246,25 @@ pub fn plan_reopen(item: Option<&Item>) -> ReopenPlan { } } +/// What a run reopened as `needs_input` waits for: what it waited for before +/// it was closed, else a Retry. +pub fn reopened_wait(item: Option<&Item>) -> common::run_wait::WaitingOn { + use common::run_wait::WaitingOn; + let asked = item + .and_then(|i| i.get(common::run_questions::FIELD_QUESTIONS)) + .and_then(|v| v.as_s().ok()) + .and_then(|j| serde_json::from_str::(j).ok()); + item.and_then(WaitingOn::of_item) + .or_else(|| asked.and_then(|a| WaitingOn::answer(&a.questions, a.comment_url.as_deref()))) + .unwrap_or_else(|| { + WaitingOn::fixed( + "Press Retry to run it again, or close it", + "It was reopened after being closed, and nothing is running on it.", + "", + ) + }) +} + /// The status-index sort key of a reopened run. A failed run keeps the /// reason and pass it failed with; its key is the one `run_fail` writes. fn reopened_status_run_id(to: &str, run_id: &str) -> String { @@ -752,19 +771,34 @@ pub async fn reopen_run( ReopenPlan::Reopen { to } => to, }; let now = chrono::Utc::now().to_rfc3339(); - let res = state + let update = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .set_key(Some(run_key(&claims.team_id, &run_id))) - .update_expression( - "SET #s = :to, status_run_id = :sri, updated_at = :t, reopened_at = :t, reopened_by = :by \ - REMOVE closed_at, closed_by, closed_by_name, closed_from, close_reason", - ) .condition_expression("#s = :closed") - .expression_attribute_names("#s", "status") - .expression_attribute_values(":to", attr_s(to)) - .expression_attribute_values(":sri", attr_s(&reopened_status_run_id(to, &run_id))) + .expression_attribute_names("#s", "status"); + // Reopened as waiting on a person: for what it waited on before, else + // for a Retry by name (a run closed while it worked asked nothing). + let update = if to == run_status::NEEDS_INPUT { + use common::run_wait::NeedsInput; + update + .update_expression( + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, updated_at = :t, \ + reopened_at = :t, reopened_by = :by \ + REMOVE closed_at, closed_by, closed_by_name, closed_from, close_reason", + ) + .needs_input(&run_id, &reopened_wait(item.as_ref())) + } else { + update + .update_expression( + "SET #s = :to, status_run_id = :sri, updated_at = :t, reopened_at = :t, reopened_by = :by \ + REMOVE closed_at, closed_by, closed_by_name, closed_from, close_reason", + ) + .expression_attribute_values(":to", attr_s(to)) + .expression_attribute_values(":sri", attr_s(&reopened_status_run_id(to, &run_id))) + }; + let res = update .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":by", attr_s(&claims.email)) .expression_attribute_values(":closed", attr_s(run_status::CLOSED)) diff --git a/services/worker/src/agent/policy.rs b/services/worker/src/agent/policy.rs index 9a620c451..4ea43e849 100644 --- a/services/worker/src/agent/policy.rs +++ b/services/worker/src/agent/policy.rs @@ -441,19 +441,41 @@ pub async fn end_run_for_stop(state: &WorkerState, team_id: &str, run_id: &str, Stop::TimedOut { approval } => approval.id.clone(), Stop::Paused { .. } => String::new(), }; - let r = state + use common::run_wait::{NeedsInput, WaitingOn}; + let update = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", AttributeValue::S(team_id.to_string())) .key("run_id", AttributeValue::S(run_id.to_string())) - .update_expression( - "SET #s = :s, status_run_id = :sri, policy_note = :n, policy_approval = :a, updated_at = :t", - ) - .condition_expression(format!("attribute_exists(run_id) AND {}", common::run_status::not_ended("#s"))) - .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S(status.to_string())) - .expression_attribute_values(":sri", AttributeValue::S(format!("{status}#{run_id}"))) + .condition_expression(format!( + "attribute_exists(run_id) AND {}", + common::run_status::not_ended("#s") + )) + .expression_attribute_names("#s", "status"); + let update = match stop { + // Waiting on a person: for the approval, by name. + Stop::TimedOut { .. } => update + .update_expression( + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, policy_note = :n, \ + policy_approval = :a, updated_at = :t", + ) + .needs_input( + run_id, + &WaitingOn::fixed( + "Answer the approval request this run is waiting on, then press Retry", + &stop.note(), + "", + ), + ), + Stop::Paused { .. } => update + .update_expression( + "SET #s = :s, status_run_id = :sri, policy_note = :n, policy_approval = :a, updated_at = :t", + ) + .expression_attribute_values(":s", AttributeValue::S(status.to_string())) + .expression_attribute_values(":sri", AttributeValue::S(format!("{status}#{run_id}"))), + }; + let r = update .expression_attribute_values(":n", AttributeValue::S(stop.note())) .expression_attribute_values(":a", AttributeValue::S(approval_id)) .expression_attribute_values(":t", AttributeValue::S(chrono::Utc::now().to_rfc3339())) diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index c37098a51..0c2513be9 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -735,6 +735,9 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) let sent = common::agent_policy::pause::sweep(&*store, &SqsResender(&state)).await; info!(sent, "Paused agent work sweep done"); } + models::WorkerMessage::RunWaiting(msg) => { + passes::webhooks::run_waiting(&state, &msg).await; + } // Handled in `handle_sqs`, where a failure fails the message. models::WorkerMessage::UsageRecord(_) => {} } diff --git a/services/worker/src/passes/feature/registration.rs b/services/worker/src/passes/feature/registration.rs index 570c71d9d..e19ce6cf3 100644 --- a/services/worker/src/passes/feature/registration.rs +++ b/services/worker/src/passes/feature/registration.rs @@ -19,13 +19,22 @@ //! 3. a place is a registry when it names the siblings by path or as a //! whole string (an import, an `exports` key, a list of ids); a code file //! that only mentions them as words is a maybe; -//! 4. an item that isn't of the siblings' kind (the siblings all import a -//! package the new file doesn't) has no places; +//! 4. a new file is an item of the siblings' kind only when its structure +//! says so, never because of the folder it sits in ([`kind_of`]): it has +//! the export shape the siblings share (a default export, a call to the +//! same definer such as `defineType(...)`, the same base class or trait) +//! and the shape the registries import them by (a registry that imports +//! each sibling's default export needs one from the new file too). A +//! helper, validator, utility, types or generated file next to them is +//! another kind and has no places. When the structure can't tell (the +//! file or too few siblings couldn't be read, or the siblings share no +//! shape), its places are only noted, never a block; //! 5. every place must name the new item on the run's branch. //! //! What a registry is missing goes back to the coder once with the list, and //! blocks the pull request if still missing. A maybe never blocks: it is -//! noted in the pull request for a person to check. +//! noted in the pull request for a person to check. And a block never stops +//! the run: it is an Open item on the pull request (see `feature::gate`). use std::collections::BTreeSet; @@ -95,12 +104,23 @@ fn is_test(p: &str) -> bool { || l.contains(".stories.") } +/// Type declarations and generated files: never items of their own (a +/// generated file is regenerated, it is not registered). +fn is_generated_or_types(p: &str) -> bool { + let l = p.to_lowercase(); + l.ends_with(".d.ts") + || l.contains(".generated.") + || l.contains(".gen.") + || l.contains("/generated/") + || l.contains("/__generated__/") +} + /// The items the added files make. `added` are the paths the change adds; /// `tree` is the default branch's file list. pub fn new_items(added: &[String], tree: &[String]) -> Vec { let mut out: Vec = Vec::new(); for p in added { - if skipped(p) || is_test(p) { + if skipped(p) || is_test(p) || is_generated_or_types(p) { continue; } let (dir, file) = split_path(p); @@ -149,7 +169,7 @@ pub fn siblings(item: &NewItem, tree: &[String], recorded: Option<&str>) -> Vec< let Some(rest) = t.strip_prefix(&prefix) else { continue; }; - if skipped(t) || is_test(t) { + if skipped(t) || is_test(t) || is_generated_or_types(t) { continue; } if item.folder { @@ -421,6 +441,292 @@ pub fn other_kind(new_text: &str, sibling_texts: &[String]) -> bool { common.is_disjoint(&mine) } +/// What a file exports, by structure: what makes two files the same kind of +/// item, whatever the framework. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Shape { + /// A default export (`export default ...`, `module.exports = ...`). + pub default_export: bool, + /// What its exports are built with: the function a top-level export + /// calls (`defineType` in `export default defineType({...})`), a base + /// class (`class:Model`), a trait it implements (`impl:Block`) or a + /// decorator (`@register`). + pub definers: BTreeSet, +} + +const NOT_DEFINERS: &[&str] = &[ + "function", "class", "async", "new", "await", "typeof", "return", "if", "for", "while", +]; + +/// The dotted name at the start of `s` and what follows it. +fn lead_name(s: &str) -> (&str, &str) { + let end = s + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '.')) + .unwrap_or(s.len()); + (&s[..end], &s[end..]) +} + +/// The definer a value expression is built with: `defineType({...})` gives +/// `defineType`, `z.object<...>(...)` gives `z.object`; a literal gives none. +fn called(expr: &str) -> Option { + let (name, rest) = lead_name(expr.trim_start()); + let rest = rest.trim_start(); + (!name.is_empty() + && !name.starts_with(|c: char| c.is_ascii_digit()) + && !NOT_DEFINERS.contains(&name) + && (rest.starts_with('(') || rest.starts_with('<'))) + .then(|| name.to_string()) +} + +/// The base class after `extends`, if any. +fn extends(rest: &str) -> Option { + let at = rest.find(" extends ")?; + let (name, _) = lead_name(rest[at + 9..].trim_start()); + (!name.is_empty()).then(|| format!("class:{name}")) +} + +/// The file's [`Shape`], read from its top-level lines (comments left out). +pub fn shape(path: &str, text: &str) -> Shape { + let text = without_comments(path, text); + let mut out = Shape::default(); + // `const author = defineType(...)` then `export default author`. + let mut locals: Vec<(String, String)> = Vec::new(); + let mut exported: Vec = Vec::new(); + for line in text.lines() { + if line.starts_with(char::is_whitespace) { + continue; + } + let l = line.trim_end(); + if let Some(rest) = l + .strip_prefix("export default ") + .or_else(|| l.strip_prefix("module.exports =")) + .or_else(|| l.strip_prefix("export =")) + { + out.default_export = true; + let rest = rest.trim_start(); + if let Some(d) = called(rest) { + out.definers.insert(d); + } else if let Some(b) = extends(rest) { + out.definers.insert(b); + } else { + let (name, _) = lead_name(rest); + if !name.is_empty() { + exported.push(name.to_string()); + } + } + continue; + } + if let Some(list) = l.strip_prefix("export {") { + for part in list.trim_end_matches(['}', ';', ' ']).split(',') { + let mut words = part.split_whitespace(); + let name = words.next().unwrap_or(""); + if words.next() == Some("as") && words.next() == Some("default") { + out.default_export = true; + } + exported.push(name.to_string()); + } + continue; + } + let (is_export, decl) = match l.strip_prefix("export ") { + Some(d) => (true, d.trim_start()), + None => (false, l), + }; + let decl = decl.strip_prefix("declare ").unwrap_or(decl); + if let Some(rest) = ["const ", "let ", "var "] + .iter() + .find_map(|k| decl.strip_prefix(k)) + { + let (name, after) = lead_name(rest); + if let Some((_, value)) = after.split_once('=') { + if let Some(d) = called(value) { + if is_export { + out.definers.insert(d.clone()); + } + locals.push((name.to_string(), d)); + } + } + continue; + } + if let Some(rest) = decl.strip_prefix("class ") { + if let Some(b) = extends(&format!(" {rest}")) { + if is_export { + out.definers.insert(b); + } + } else if let Some((_, bases)) = rest.split_once('(') { + // Python: `class Article(Model):`. + let (base, _) = lead_name(bases.trim_start()); + if !base.is_empty() && rest.trim_end().ends_with(':') { + out.definers.insert(format!("class:{base}")); + } + } + continue; + } + if let Some(rest) = l.strip_prefix("impl") { + // Rust: `impl Block for Quote`, `impl Block for Quote`. + let rest = rest.trim_start(); + let rest = if rest.starts_with('<') { + rest.split_once('>') + .map(|(_, r)| r) + .unwrap_or("") + .trim_start() + } else { + rest + }; + if let Some((tr, _)) = rest.split_once(" for ") { + let (name, _) = lead_name(tr.trim()); + if !name.is_empty() { + out.definers.insert(format!("impl:{name}")); + } + } + continue; + } + if let Some(rest) = l.strip_prefix('@') { + // A top-level decorator (`@register`, `@app.route(...)`). + let (name, _) = lead_name(rest); + if !name.is_empty() { + out.definers.insert(format!("@{name}")); + } + } + } + for name in exported { + if let Some((_, d)) = locals.iter().find(|(n, _)| *n == name) { + out.definers.insert(d.clone()); + } + } + out +} + +/// Whether `text` imports the sibling's default export: `import author from +/// './author'` (a registry that does needs one from every item it lists). +pub fn imports_default(text: &str, sib: &str) -> bool { + let forms = variants(sib); + let mut from = 0; + while let Some(i) = text[from..].find("import ") { + let at = from + i; + from = at + 7; + if at > 0 && !text[..at].ends_with(|c: char| c.is_whitespace() || c == ';') { + continue; + } + let rest = text[from..].trim_start(); + let rest = rest.strip_prefix("type ").unwrap_or(rest).trim_start(); + let (name, after) = lead_name(rest); + if name.is_empty() || name.contains('.') || name == "from" { + continue; + } + let Some(spec_at) = after.find(" from ") else { + continue; + }; + // The import clause is the default binding, optionally `, { ... }`. + let clause = &after[..spec_at]; + if !(clause.trim().is_empty() || clause.trim_start().starts_with(',')) { + continue; + } + let spec = after[spec_at + 6..].trim_start(); + let Some(q) = spec.chars().next().filter(|c| *c == '"' || *c == '\'') else { + continue; + }; + let Some(end) = spec[1..].find(q) else { + continue; + }; + let last = spec[1..1 + end].rsplit('/').next().unwrap_or(""); + let stem = last.split('.').next().unwrap_or(last); + if forms.iter().any(|f| f == stem) { + return true; + } + } + false +} + +/// Whether a new file is the same kind of item as its siblings. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Kind { + /// It has the shape the siblings share: its places must name it. + Same, + /// Another kind (a helper or validator beside them): it has no places. + Other(String), + /// Can't tell: its places are noted for a person, never a block. + Unknown(String), +} + +/// Whether the new file (`new`: path and text, `None` when it couldn't be +/// read) is the siblings' kind, judged by structure: the export shape the +/// read siblings all share, and the shape the registries import them by +/// (`registries`: their texts). Never by the folder. +pub fn kind_of( + new: Option<(&str, &str)>, + sibling_files: &[(String, String)], + registries: &[&str], + sibs: &[String], +) -> Kind { + let Some((new_path, new_text)) = new else { + return Kind::Unknown("its file couldn't be read to compare".to_string()); + }; + if sibling_files.len() < 2 { + return Kind::Unknown("too few of its siblings could be read to compare".to_string()); + } + let texts: Vec = sibling_files.iter().map(|(_, t)| t.clone()).collect(); + if other_kind(new_text, &texts) { + return Kind::Other("it imports none of the packages its siblings all import".to_string()); + } + let shapes: Vec = sibling_files.iter().map(|(p, t)| shape(p, t)).collect(); + let all_default = shapes.iter().all(|s| s.default_export); + let common: BTreeSet = shapes + .iter() + .skip(1) + .fold(shapes[0].definers.clone(), |acc, s| { + acc.intersection(&s.definers).cloned().collect() + }); + let imported_default = registries + .iter() + .any(|r| sibs.iter().any(|s| imports_default(r, s))); + if !all_default && !imported_default && common.is_empty() { + return Kind::Unknown("its siblings share no export shape to compare it with".to_string()); + } + let mine = shape(new_path, new_text); + if (all_default || imported_default) && !mine.default_export { + return Kind::Other(if imported_default { + "it has no default export, and the registries import each sibling's default export" + .to_string() + } else { + "it has no default export, which every sibling has".to_string() + }); + } + if !common.is_empty() && mine.definers.is_disjoint(&common) { + let names = common + .iter() + .map(|d| format!("`{d}`")) + .collect::>() + .join(", "); + return Kind::Other(format!( + "its exports aren't built with {names}, as every sibling's are" + )); + } + Kind::Same +} + +/// What the new item is missing, once its kind is known: nothing for +/// another kind, and only notes when the kind can't be told. +pub fn judge( + item: &NewItem, + sibs: &[String], + kind: &Kind, + places: &[(String, String, bool)], + on_branch: &dyn Fn(&str) -> Option, +) -> Vec { + match kind { + Kind::Other(_) => Vec::new(), + Kind::Same => missing(item, sibs, places, on_branch), + Kind::Unknown(why) => missing(item, sibs, places, on_branch) + .into_iter() + .map(|mut m| { + m.registry = false; + m.unsure = Some(why.clone()); + m + }) + .collect(), + } +} + /// A sibling's own file on the default branch: `parent/.`, or its /// folder's index-like file. fn sibling_file(item: &NewItem, sib: &str, tree: &[String]) -> Option { @@ -511,6 +817,9 @@ pub struct Missing { /// A registry (names the siblings as paths or whole strings): missing /// from it blocks. Else a maybe, only noted. pub registry: bool, + /// Set when the structure couldn't tell whether the new file is the + /// siblings' kind: why. Only noted. + pub unsure: Option, } impl Missing { @@ -522,6 +831,13 @@ impl Missing { .map(|s| format!("`{s}`")) .collect::>() .join(", "); + if let Some(why) = &self.unsure { + return format!( + "`{}` may need registering in `{}` (it names {names}); couldn't tell whether it is \ + the same kind of item ({why}); check by hand", + self.item, self.path + ); + } if self.registry { format!( "`{}` isn't registered in `{}` (it names {names})", @@ -561,6 +877,7 @@ pub fn missing( .cloned() .collect(), registry: *registry, + unsure: None, }); } } @@ -621,21 +938,29 @@ pub async fn check( } else { Some(item.path.clone()) }; - if let Some(own) = own_path { - if let Ok(own_text) = github.read_file(owner, repo, &own, branch).await { - let mut sib_texts = Vec::new(); - for s in sibs.iter().take(3) { - if let Some(f) = sibling_file(&item, s, tree) { - if let Ok(t) = github.read_file(owner, repo, &f, base).await { - sib_texts.push(t); - } - } - } - if other_kind(&own_text, &sib_texts) { - continue; + let own = match own_path { + Some(p) => github + .read_file(owner, repo, &p, branch) + .await + .ok() + .map(|t| (p, t)), + None => None, + }; + let mut sib_files: Vec<(String, String)> = Vec::new(); + for s in sibs.iter().take(3) { + if let Some(f) = sibling_file(&item, s, tree) { + if let Ok(t) = github.read_file(owner, repo, &f, base).await { + sib_files.push((f, t)); } } } + // Another kind by its imports alone: no need to search for places. + if let Some((_, t)) = &own { + let texts: Vec = sib_files.iter().map(|(_, t)| t.clone()).collect(); + if other_kind(t, &texts) { + continue; + } + } let mut candidates: Vec = Vec::new(); for s in sibs.iter().take(3) { if let Ok(hits) = github.search_code(owner, repo, base, s).await { @@ -663,6 +988,21 @@ pub async fn check( .map(|(_, registry)| (p, t, *registry)) }) .collect(); + let registries: Vec<&str> = places + .iter() + .filter(|(_, _, registry)| *registry) + .map(|(_, t, _)| t.as_str()) + .collect(); + let kind = kind_of( + own.as_ref().map(|(p, t)| (p.as_str(), t.as_str())), + &sib_files, + ®istries, + &sibs, + ); + if let Kind::Other(why) = &kind { + tracing::info!(item = %item.path, why, "Not a new item of its siblings' kind"); + continue; + } checked += places.len(); let mut on_branch: Vec<(String, Option)> = Vec::new(); for (p, _, _) in &places { @@ -677,7 +1017,7 @@ pub async fn check( .find(|(q, _)| q == p) .and_then(|(_, t)| t.clone()) }; - for m in missing(&item, &sibs, &places, &lookup) { + for m in judge(&item, &sibs, &kind, &places, &lookup) { if !out.iter().any(|x| x.item == m.item && x.path == m.path) { out.push(m); } @@ -923,6 +1263,257 @@ mod tests { ); } + // A content studio's schema folder: three registered document schemas, + // a documents index that imports each one's default export, and a + // structure file that lists them by name. + fn studio_tree() -> Vec { + [ + "studio/schemaTypes/documents/author.ts", + "studio/schemaTypes/documents/blog.ts", + "studio/schemaTypes/documents/blog-index.ts", + "studio/schemaTypes/documents/index.ts", + "studio/structure.ts", + ] + .iter() + .map(|s| s.to_string()) + .collect() + } + + fn studio_doc(name: &str) -> String { + format!( + "import {{defineField, defineType}} from 'cms-kit'\n\nexport default defineType({{\n \ + name: '{name}',\n type: 'document',\n fields: [defineField({{name: 'title', type: 'string'}})],\n}})\n" + ) + } + + fn studio_places() -> Vec<(String, String)> { + vec![ + ( + "studio/schemaTypes/documents/index.ts".to_string(), + "import author from './author'\nimport blog from './blog'\nimport blogIndex from './blog-index'\n\nexport const documents = [author, blog, blogIndex]\n".to_string(), + ), + ( + "studio/structure.ts".to_string(), + "export const structure = (S) =>\n S.list().items([\n S.documentTypeListItem('author'),\n S.documentTypeListItem('blog'),\n S.documentTypeListItem('blog-index'),\n ])\n".to_string(), + ), + ] + } + + /// The whole check after its reads, as `check` runs it. + fn run_rule(new_path: &str, new_text: &str) -> Vec { + let tree = studio_tree(); + let item = &new_items(&[new_path.to_string()], &tree)[0]; + let sibs = siblings(item, &tree, None); + assert_eq!(sibs, vec!["author", "blog", "blog-index"]); + let sib_files: Vec<(String, String)> = sibs + .iter() + .map(|s| (sibling_file(item, s, &tree).unwrap(), studio_doc(s))) + .collect(); + let files = studio_places(); + let keep = registration_places(item, &sibs, &files); + let places: Vec<(String, String, bool)> = files + .into_iter() + .filter_map(|(p, t)| keep.iter().find(|(k, _)| *k == p).map(|(_, r)| (p, t, *r))) + .collect(); + assert_eq!(places.len(), 2, "both registries are places"); + let registries: Vec<&str> = places + .iter() + .filter(|(_, _, r)| *r) + .map(|(_, t, _)| t.as_str()) + .collect(); + let kind = kind_of(Some((new_path, new_text)), &sib_files, ®istries, &sibs); + // The branch registers nothing new. + let unchanged: Vec<(String, String)> = studio_places(); + let lookup = |p: &str| { + unchanged + .iter() + .find(|(q, _)| q == p) + .map(|(_, t)| t.clone()) + }; + judge(item, &sibs, &kind, &places, &lookup) + } + + #[test] + fn a_validation_helper_beside_schema_documents_is_not_a_new_item() { + // A standalone module of validation predicates next to the schema + // documents: it imports the same package (types only), but exports + // no schema. It was blocked as an unregistered document. + let helper = "import type {ValidationContext} from 'cms-kit'\n\n\ + export function endsAfterStart(value: unknown, context: ValidationContext) {\n \ + return true\n}\n\n\ + export const requireCode = (rule: any) => rule.custom((v: string) => !!v)\n"; + let m = run_rule( + "studio/schemaTypes/documents/promotion-validation.ts", + helper, + ); + assert!(m.is_empty(), "{m:?}"); + assert!(blocking(&m).is_empty()); + } + + #[test] + fn a_real_new_schema_document_not_registered_is_still_flagged() { + let m = run_rule( + "studio/schemaTypes/documents/promotion.ts", + &studio_doc("promotion"), + ); + let b = blocking(&m); + assert_eq!(b.len(), 2, "{m:?}"); + assert!(b + .iter() + .any(|x| x.path == "studio/schemaTypes/documents/index.ts")); + assert!(b.iter().any(|x| x.path == "studio/structure.ts")); + // Declared, then exported by name: the same kind. + let later = "import {defineType} from 'cms-kit'\n\nconst promotion = defineType({name: 'promotion'})\n\nexport default promotion\n"; + assert_eq!( + blocking(&run_rule( + "studio/schemaTypes/documents/promotion.ts", + later + )) + .len(), + 2 + ); + } + + #[test] + fn when_the_structure_cant_tell_the_places_are_only_noted() { + let tree = studio_tree(); + let item = &new_items( + &["studio/schemaTypes/documents/promotion.ts".to_string()], + &tree, + )[0]; + let sibs = siblings(item, &tree, None); + // The new file couldn't be read. + let sib_files: Vec<(String, String)> = sibs + .iter() + .map(|s| (format!("{s}.ts"), studio_doc(s))) + .collect(); + let kind = kind_of(None, &sib_files, &[], &sibs); + assert!(matches!(kind, Kind::Unknown(_))); + // Siblings with nothing in common to compare. + let loose = vec![ + ("a.ts".to_string(), "export const a = 1\n".to_string()), + ("b.ts".to_string(), "export function b() {}\n".to_string()), + ]; + assert!(matches!( + kind_of(Some(("n.ts", "export const n = 2\n")), &loose, &[], &sibs), + Kind::Unknown(_) + )); + let places: Vec<(String, String, bool)> = studio_places() + .into_iter() + .map(|(p, t)| (p, t, true)) + .collect(); + let m = judge(item, &sibs, &kind, &places, &|p: &str| { + studio_places() + .into_iter() + .find(|(q, _)| q == p) + .map(|(_, t)| t) + }); + assert_eq!(m.len(), 2); + assert!(blocking(&m).is_empty()); + assert!(m[0].line().contains("check by hand")); + assert!(m[0].line().contains("couldn't tell")); + } + + #[test] + fn shapes_are_read_by_structure_in_any_language() { + let s = shape("x.ts", "export default defineType({name: 'a'})\n"); + assert!(s.default_export); + assert!(s.definers.contains("defineType")); + let s = shape("x.tsx", "export default class Hero extends Block {}\n"); + assert!(s.definers.contains("class:Block")); + let s = shape("x.js", "module.exports = createRoute('/a')\n"); + assert!(s.default_export && s.definers.contains("createRoute")); + let s = shape( + "x.ts", + "// export default defineType()\nexport function helper() {}\n", + ); + assert_eq!(s, Shape::default()); + let s = shape("m.py", "@register\nclass Article(Model):\n pass\n"); + assert!(s.definers.contains("class:Model")); + assert!(s.definers.contains("@register")); + let s = shape("q.rs", "pub struct Quote;\nimpl Block for Quote {}\n"); + assert!(s.definers.contains("impl:Block")); + + // Python models beside a helper module: the helper is another kind. + let models = vec![ + ( + "app/models/user.py".to_string(), + "from django.db import models\n\nclass User(models.Model):\n pass\n".to_string(), + ), + ( + "app/models/order.py".to_string(), + "from django.db import models\n\nclass Order(models.Model):\n pass\n" + .to_string(), + ), + ]; + let helper = "from django.db import models\n\ndef money(v):\n return round(v, 2)\n"; + assert!(matches!( + kind_of(Some(("app/models/money.py", helper)), &models, &[], &[]), + Kind::Other(_) + )); + let model = "from django.db import models\n\nclass Coupon(models.Model):\n pass\n"; + assert_eq!( + kind_of(Some(("app/models/coupon.py", model)), &models, &[], &[]), + Kind::Same + ); + } + + #[test] + fn a_registry_that_imports_defaults_needs_a_default_export() { + assert!(imports_default( + "import blogIndex from './blog-index'", + "blog-index" + )); + assert!(imports_default( + "import Hero, { heroQuery } from \"@/blocks/Hero\"", + "Hero" + )); + assert!(!imports_default("import { Hero } from './Hero'", "Hero")); + assert!(!imports_default("import * as Hero from './Hero'", "Hero")); + assert!(!imports_default("import x from './HeroBanner'", "Hero")); + // Siblings share nothing but the registry imports their defaults. + let sibs = vec!["a".to_string(), "b".to_string()]; + let files = vec![ + ( + "a.ts".to_string(), + "const a = {}\nexport default a\n".to_string(), + ), + ( + "b.ts".to_string(), + "export default function b() {}\n".to_string(), + ), + ]; + let registry = "import a from './a'\nimport b from './b'\n"; + assert!(matches!( + kind_of( + Some(("n.ts", "export const n = 1\n")), + &files, + &[registry], + &sibs + ), + Kind::Other(_) + )); + assert_eq!( + kind_of( + Some(("n.ts", "export default {}\n")), + &files, + &[registry], + &sibs + ), + Kind::Same + ); + } + + #[test] + fn types_and_generated_files_are_never_items() { + let added = vec![ + "src/blocks/types.d.ts".to_string(), + "src/blocks/schema.generated.ts".to_string(), + "src/__generated__/blocks.ts".to_string(), + ]; + assert!(new_items(&added, &tree()).is_empty()); + } + #[test] fn path_names_match_whole_segments_only() { assert!(names_as_path( diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 09549a901..a7b29f94d 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1,4 +1,5 @@ use common::run_status::EndedValues; +use common::run_wait::{NeedsInput, WaitingOn}; use std::collections::HashMap; use std::sync::Arc; use std::time::Instant; @@ -2818,7 +2819,8 @@ async fn run_passes( .await; // Mark the run as needs_input so a comment can re-trigger it - mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids).await; + let wait = wait_on_ticket(msg, &questions, detail); + mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids, &wait).await; close_memory(state, agent_memory.take()).await; return Ok(()); @@ -4451,18 +4453,21 @@ async fn run_passes( .collect::>() .join("\n") ); + let asked = run_end::questions_from(&qs); ask_on_ticket( state, msg, run_id, &github, - &run_end::questions_from(&qs), + &asked, &text, &text, "A decision is needed", ) .await; - mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids).await; + let wait = wait_on_ticket(msg, &asked, &text); + mark_run_needs_input(state, msg, run_id, usage, start, &used_mcp_ids, &wait) + .await; close_memory(state, agent_memory.take()).await; return Ok(()); } @@ -4523,6 +4528,7 @@ async fn run_passes( let duration = start.elapsed().as_secs(); let delta = usage.unrecorded(); let now = chrono::Utc::now().to_rfc3339(); + let wait = wait_on_ticket(msg, &questions, raw_clarification); let usage_res = state .dynamo .update_item() @@ -4530,14 +4536,13 @@ async fn run_passes( .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #status = :s, status_run_id = :sri, error_message = :em, \ + "SET #status = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp", ) .expression_attribute_names("#status", "status") - .expression_attribute_values(":s", attr_s("needs_input")) - .expression_attribute_values(":sri", attr_s(&format!("needs_input#{run_id}"))) + .needs_input(run_id, &wait) .expression_attribute_values(":em", attr_s(raw_clarification)) .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) @@ -6992,10 +6997,8 @@ async fn finish_without_code( jira_title, ) .await; - } - - if !outside { - mark_run_needs_input(state, msg, run_id, usage, start, mcp_ids).await; + let wait = wait_on_ticket(msg, &questions, &report); + mark_run_needs_input(state, msg, run_id, usage, start, mcp_ids, &wait).await; } let status = if outside { fix_location::STATUS_OUTSIDE @@ -7444,6 +7447,32 @@ async fn report_questions( } } +/// What a run that asked on its ticket waits for: the questions it asked, +/// else the missing detail on the ticket (`what`: what it said there). +fn wait_on_ticket( + msg: &TicketMessage, + questions: &[common::run_questions::Question], + what: &str, +) -> WaitingOn { + let ticket = if matches!(msg.source, TicketSource::Github) && msg.issue_number > 0 { + format!( + "https://github.com/{}/{}/issues/{}", + msg.repo_owner, msg.repo_name, msg.issue_number + ) + } else { + String::new() + }; + WaitingOn::answer_or( + questions, + None, + WaitingOn::fixed( + "Add the missing detail to the ticket, then press Retry", + what, + &ticket, + ), + ) +} + /// Mark a run `needs_input` (a comment or re-run can pick it up again) and /// count it in the analytics, the way every needs_input stop is recorded. async fn mark_run_needs_input( @@ -7453,6 +7482,7 @@ async fn mark_run_needs_input( usage: &TokenUsage, start: &std::time::Instant, mcp_ids: &[String], + wait: &WaitingOn, ) { let duration = start.elapsed().as_secs(); let delta = usage.unrecorded(); @@ -7464,19 +7494,18 @@ async fn mark_run_needs_input( .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #status = :s, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ + "SET #status = :s, waiting_on = :wo, tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ cost_usd = if_not_exists(cost_usd, :uzero) + :c, \ duration_s = :d, updated_at = :t, current_pass = :cp, \ status_run_id = :sri, mcp_servers = :mcp", ) .expression_attribute_names("#status", "status") - .expression_attribute_values(":s", attr_s("needs_input")) + .needs_input(run_id, wait) .usage_values(&delta) .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) - .expression_attribute_values(":sri", attr_s(&format!("needs_input#{run_id}"))) .expression_attribute_values( ":mcp", AttributeValue::L(mcp_ids.iter().map(|s| attr_s(s)).collect()), @@ -7519,13 +7548,20 @@ pub(crate) async fn mark_run_stopped_by_guard( .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #s = :s, status_run_id = :sri, error_message = :em, updated_at = :t, current_pass = :cp", + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ + updated_at = :t, current_pass = :cp", ) .condition_expression(common::run_status::not_ended("#s")) .ended_values() .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", attr_s(common::run_status::NEEDS_INPUT)) - .expression_attribute_values(":sri", attr_s(&format!("needs_input#{run_id}"))) + .needs_input( + run_id, + &WaitingOn::fixed( + "Read why CoderHelm stopped this run, then press Retry or close it", + reason, + "", + ), + ) .expression_attribute_values(":em", attr_s(reason)) .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) .expression_attribute_values(":cp", attr_s("done")) @@ -7567,7 +7603,12 @@ async fn stop_run_repo_not_enabled( warn!(run_id, error = %e, "Could not post the repo-not-turned-on Jira comment"); } } - mark_run_needs_input(state, msg, run_id, usage, start, &[]).await; + let wait = WaitingOn::fixed( + "Turn the repository on for runs in CoderHelm, then press Retry", + message, + "", + ); + mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait).await; } /// Append a timestamped progress note to the run record for live activity display. @@ -8406,7 +8447,8 @@ async fn stop_for_open_pr( &pr.key(), ) .await; - mark_run_needs_input(state, msg, run_id, usage, start, &[]).await; + let wait = wait_on_ticket(msg, std::slice::from_ref(&question), ¬e); + mark_run_needs_input(state, msg, run_id, usage, start, &[], &wait).await; } async fn post_jira_comment( diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index e1ca956a2..57730d0b3 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -1,5 +1,6 @@ use aws_sdk_dynamodb::types::AttributeValue; use common::run_status::EndedValues; +use common::run_wait::{NeedsInput, WaitingOn}; use serde_json::Value; use tracing::{error, info, warn}; @@ -3873,11 +3874,12 @@ async fn after_planned_round( super::add_progress_note(state, &msg.team_id, &msg.run_id, &reason).await; // Not completed: the run waits on a person, says which tasks and // why, and the pull request stays a draft. - complete_run_with_status( + debug_assert_eq!(status, common::run_status::NEEDS_INPUT); + wait_for_review( state, &ctx.ticket_msg, &msg.run_id, - status, + &reason, pr.url, pr.number, pr.branch, @@ -4880,20 +4882,43 @@ async fn stop_on_own_findings( pr_number, "Own review findings still open — the PR stays a draft" ); super::add_progress_note(state, &msg.team_id, run_id, reason).await; - complete_run_with_status( + wait_for_review( + state, msg, run_id, reason, pr_url, pr_number, branch, usage, duration, + ) + .await +} + +/// The run stops with its work on its pull request and something open on +/// it: it waits on a person (`needs_input`), named as the pull request's +/// review with `reason` as what is open (never a wait for nothing). +#[allow(clippy::too_many_arguments)] +async fn wait_for_review( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + reason: &str, + pr_url: &str, + pr_number: u64, + branch: &str, + usage: &TokenUsage, + duration: u64, +) -> Result<(), Box> { + let wait = super::stop_pr::review_wait(pr_number, pr_url, reason); + end_run( state, msg, run_id, common::run_status::NEEDS_INPUT, - pr_url, - pr_number, - branch, + Some(&wait), + (pr_url, pr_number, branch), usage, duration, ) .await } +/// Ends the run as `status`. A wait on a person goes through +/// [`wait_for_review`], which names what it waits for. #[allow(clippy::too_many_arguments)] async fn complete_run_with_status( state: &WorkerState, @@ -4905,27 +4930,70 @@ async fn complete_run_with_status( branch: &str, usage: &TokenUsage, duration: u64, +) -> Result<(), Box> { + debug_assert_ne!( + status, + common::run_status::NEEDS_INPUT, + "use wait_for_review" + ); + end_run( + state, + msg, + run_id, + status, + None, + (pr_url, pr_number, branch), + usage, + duration, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn end_run( + state: &WorkerState, + msg: &TicketMessage, + run_id: &str, + status: &str, + wait: Option<&WaitingOn>, + (pr_url, pr_number, branch): (&str, u64, &str), + usage: &TokenUsage, + duration: u64, ) -> Result<(), Box> { let now = chrono::Utc::now().to_rfc3339(); let delta = usage.unrecorded(); - - let res = state + // Waiting on a person is always for something named. + let wait = (status == common::run_status::NEEDS_INPUT).then(|| { + wait.cloned() + .unwrap_or_else(|| super::stop_pr::review_wait(pr_number, pr_url, "")) + }); + let set_status = if wait.is_some() { + "#s = :s, status_run_id = :sri, waiting_on = :wo" + } else { + "#s = :s, status_run_id = :sri" + }; + let update = state .dynamo .update_item() .table_name(&state.config.runs_table_name) .key("team_id", attr_s(&msg.team_id)) .key("run_id", attr_s(run_id)) - .update_expression( - "SET #s = :s, pr_url = :pr, pr_number = :pn, branch = :b, \ + .update_expression(format!( + "SET {set_status}, pr_url = :pr, pr_number = :pn, branch = :b, \ tokens_in = if_not_exists(tokens_in, :uzero) + :ti, tokens_out = if_not_exists(tokens_out, :uzero) + :to, \ cache_read_tokens = if_not_exists(cache_read_tokens, :uzero) + :crt, cache_write_tokens = if_not_exists(cache_write_tokens, :uzero) + :cwt, \ - cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp, \ - status_run_id = :sri \ + cost_usd = if_not_exists(cost_usd, :uzero) + :c, duration_s = :d, updated_at = :t, current_pass = :cp \ REMOVE error_message, #err", - ) + )) .expression_attribute_names("#s", "status") - .expression_attribute_names("#err", "error") - .expression_attribute_values(":s", attr_s(status)) + .expression_attribute_names("#err", "error"); + let update = match &wait { + Some(w) => update.needs_input(run_id, w), + None => update + .expression_attribute_values(":s", attr_s(status)) + .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))), + }; + let res = update .expression_attribute_values(":pr", attr_s(pr_url)) .expression_attribute_values(":pn", attr_n(pr_number)) .expression_attribute_values(":b", attr_s(branch)) @@ -4933,7 +5001,6 @@ async fn complete_run_with_status( .expression_attribute_values(":d", attr_n(duration)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) - .expression_attribute_values(":sri", attr_s(&format!("{status}#{run_id}"))) // Cancel is terminal: never overwrite a cancelled run with a completion. .condition_expression(common::run_status::not_ended("#s")) .ended_values() diff --git a/services/worker/src/passes/run_guard.rs b/services/worker/src/passes/run_guard.rs index 9d45595a1..3138870dc 100644 --- a/services/worker/src/passes/run_guard.rs +++ b/services/worker/src/passes/run_guard.rs @@ -40,6 +40,7 @@ use std::sync::Mutex; use aws_sdk_dynamodb::types::{AttributeValue, ReturnValue}; use common::run_status::{self, EndedValues}; +use common::run_wait::NeedsInput; use serde::{Deserialize, Serialize}; use tracing::{info, warn}; @@ -633,6 +634,9 @@ pub async fn settle_open_pr(state: &WorkerState, team_id: &str, run_id: &str) -> return false; }; let now = chrono::Utc::now().to_rfc3339(); + // It has its pull request: it waits for that pull request's review. + let (number, url) = run_pr(state, team_id, run_id).await; + let wait = super::stop_pr::review_wait(number, &url, &reason); if let Err(e) = state .dynamo .update_item() @@ -640,17 +644,13 @@ pub async fn settle_open_pr(state: &WorkerState, team_id: &str, run_id: &str) -> .key("team_id", attr_s(team_id)) .key("run_id", attr_s(run_id)) .update_expression( - "SET #s = :s, status_run_id = :sri, error_message = :em, updated_at = :t, \ - current_pass = :cp", + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, error_message = :em, \ + updated_at = :t, current_pass = :cp", ) .condition_expression(run_status::not_ended("#s")) .ended_values() .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", attr_s(run_status::NEEDS_INPUT)) - .expression_attribute_values( - ":sri", - attr_s(&format!("{}#{run_id}", run_status::NEEDS_INPUT)), - ) + .needs_input(run_id, &wait) .expression_attribute_values(":em", attr_s(&reason)) .expression_attribute_values(":t", attr_s(&now)) .expression_attribute_values(":cp", attr_s("done")) @@ -665,6 +665,33 @@ pub async fn settle_open_pr(state: &WorkerState, team_id: &str, run_id: &str) -> true } +/// The run's pull request (number, address), from its record. +async fn run_pr(state: &WorkerState, team_id: &str, run_id: &str) -> (u64, String) { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("pr_number, pr_url") + .send() + .await + .ok() + .and_then(|r| r.item) + .unwrap_or_default(); + let number = item + .get("pr_number") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0); + let url = item + .get("pr_url") + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default(); + (number, url) +} + // ── What the checks found, across steps ──────────────────────────────────── /// One check's fix rounds and last result, for the whole run. diff --git a/services/worker/src/passes/stop_pr.rs b/services/worker/src/passes/stop_pr.rs index 42c84cf9c..8d1aaa018 100644 --- a/services/worker/src/passes/stop_pr.rs +++ b/services/worker/src/passes/stop_pr.rs @@ -11,13 +11,15 @@ //! Now any error after implementation started, with work on the branch //! (beyond the plan files CoderHelm commits beside it), opens a draft pull //! request that says why the run stopped, as its open item; the run waits -//! for input instead of failing. A stop for agent permissions (paused, an +//! for that pull request's review instead of failing, and says so by name +//! (`common::run_wait`): "Review pull request #n", with the open item. A stop for agent permissions (paused, an //! approval nobody answered) still ends the run as it did. use crate::clients::github::GitHubClient; use crate::models::{TicketMessage, TicketSource}; use crate::WorkerState; use common::run_status::EndedValues; +use common::run_wait::{NeedsInput, WaitingOn}; type BoxError = Box; @@ -153,6 +155,9 @@ pub async fn open_with( } }; let now = chrono::Utc::now().to_rfc3339(); + // The work is done and on the pull request: the run waits for its + // review, named, never for "more detail" nobody was asked for. + let wait = review_wait(number, &url, reason); let _ = state .dynamo .update_item() @@ -160,16 +165,15 @@ pub async fn open_with( .key("team_id", super::attr_s(&msg.team_id)) .key("run_id", super::attr_s(run_id)) .update_expression( - "SET #s = :s, status_run_id = :sri, pr_url = :pu, pr_number = :pn, branch = :b, \ - error_message = :em, updated_at = :t, current_pass = :cp", + "SET #s = :s, status_run_id = :sri, waiting_on = :wo, pr_url = :pu, pr_number = :pn, \ + branch = :b, error_message = :em, updated_at = :t, current_pass = :cp", ) // Never over a run a person ended. .condition_expression(common::run_status::not_ended("#s")) .ended_values() .expression_attribute_names("#s", "status") .expression_attribute_values(":cp", super::attr_s("done")) - .expression_attribute_values(":s", super::attr_s("needs_input")) - .expression_attribute_values(":sri", super::attr_s(&format!("needs_input#{run_id}"))) + .needs_input(run_id, &wait) .expression_attribute_values(":pu", super::attr_s(&url)) .expression_attribute_values(":pn", super::attr_n(number)) .expression_attribute_values(":b", super::attr_s(branch)) @@ -197,6 +201,14 @@ pub async fn open_with( Ok(url) } +/// What a stopped run with a pull request waits for: its review, with the +/// reason as what is open on it. +pub fn review_wait(number: u64, url: &str, reason: &str) -> WaitingOn { + WaitingOn::review_pr(number, url, reason) + .or_else(|| WaitingOn::action("Review the work on the run's branch", reason, "")) + .unwrap_or_default() +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/worker/src/passes/webhooks.rs b/services/worker/src/passes/webhooks.rs index 768859e65..50c5d140d 100644 --- a/services/worker/src/passes/webhooks.rs +++ b/services/worker/src/passes/webhooks.rs @@ -64,7 +64,14 @@ pub fn run_data(item: &HashMap, status: &str, app: &str) "pr_number": pr, "pr_url": if pr.is_some() { opt("pr_url") } else { None }, "branch": opt("branch"), - "error": if matches!(status, "failed" | "needs_input") { error } else { None }, + // Waiting on a person: what for, by name (its question or action). + "error": match status { + "failed" => error, + "needs_input" => common::run_wait::WaitingOn::of_item(item) + .map(|w| w.line()) + .or(error), + _ => None, + }, "url": format!("{}/runs/detail/?id={}", app.trim_end_matches('/'), urlencoding::encode(&run_id)), "created_at": created.clone(), "updated_at": opt("updated_at").unwrap_or(created), @@ -122,6 +129,47 @@ pub async fn emit_run(state: &WorkerState, team_id: &str, run_id: &str, status: .await; } +/// A run waiting on a person, from the stuck-run sweep (`run_waiting`): the +/// team hears again what it waits for, through the usual `run.needs_input` +/// event, and the run page notes it. Nothing is sent once the run moved on. +pub async fn run_waiting(state: &WorkerState, msg: &common::messages::RunWaitingMessage) { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(msg.team_id.clone())) + .key("run_id", AttributeValue::S(msg.run_id.clone())) + .send() + .await + .ok() + .and_then(|r| r.item) + .unwrap_or_default(); + let status = item.get("status").and_then(|v| v.as_s().ok()); + if status.map(String::as_str) != Some(common::run_status::NEEDS_INPUT) { + info!(run_id = %msg.run_id, "Run no longer waits on a person; no reminder"); + return; + } + let what = common::run_wait::WaitingOn::of_item(&item) + .map(|w| w.line()) + .unwrap_or_else(|| "its questions on the run page".to_string()); + let note = if msg.why == "named" { + format!("This run was waiting with nothing asked; it now waits for: {what}") + } else { + format!( + "Reminder: still waiting after {} hours for: {what}", + common::run_wait::REMIND_AFTER_HOURS + ) + }; + super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; + emit_run( + state, + &msg.team_id, + &msg.run_id, + common::run_status::NEEDS_INPUT, + ) + .await; +} + /// `pull_request.opened`'s `data` (pure). pub fn pr_opened_data( run_id: &str, @@ -578,6 +626,21 @@ mod tests { assert_eq!(done["pr_number"], 318); let failed = run_data(&rec, "failed", "https://app.example.com"); assert_eq!(failed["error"], "boom"); + // Waiting on a person: the event says what for. + let wait = common::run_wait::WaitingOn::review_pr( + 318, + "https://github.com/example-org/api/pull/318", + "a check is open", + ) + .unwrap(); + let mut waiting = rec.clone(); + waiting.insert(common::run_wait::FIELD_WAITING_ON.into(), wait.to_attr()); + let d = run_data(&waiting, "needs_input", "https://app.example.com"); + assert!(conforms(&schema("run.needs_input"), &d), "{d}"); + assert!(d["error"] + .as_str() + .unwrap() + .starts_with("Review pull request #318: Open on the pull request: a check is open")); // A fresh run: no PR yet, nothing optional set. let fresh = run_data( &item(&[("run_id", "r"), ("created_at", "t")]),