diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 903eb44e3..9e27a618e 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -325,6 +325,22 @@ "null" ] }, + "success_criteria": { + "description": "What done means for the whole plan: short checkable lines. Each task\nnames the ones it covers (`covers`); without a list, each task's\nacceptance criteria are the plan's.", + "examples": [ + [ + "The 11th login attempt within 15 minutes gets 429", + "The page says when to try again" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "tasks": { "description": "The plan's tasks, in order. Each starts as `draft`.", "examples": [ @@ -1737,6 +1753,76 @@ ], "type": "object" }, + "NeedsYou": { + "description": "Something a person has to do for the plan to go on (the shape of\n`common::plan_state::NeedsItem`, for the API document).", + "properties": { + "action": { + "description": "The button: `answer`, `open_pr`, `open_link`, `retry` or `approve`.", + "examples": [ + "open_pr" + ], + "type": "string" + }, + "ask": { + "description": "What to do, one line.", + "examples": [ + "Approve pull request #318" + ], + "type": "string" + }, + "detail": { + "description": "Why, or what is open.", + "examples": [ + "This repo's auto-merge setting requires an approving review from a person." + ], + "type": [ + "string", + "null" + ] + }, + "kind": { + "description": "`answer`, `review`, `approval`, `checks`, `merge`, `failed`,\n`closed_pr` or `approve_rest`.", + "examples": [ + "approval" + ], + "type": "string" + }, + "run_id": { + "description": "The run it comes from.", + "examples": [ + "01JB8X6F4M2C9QZ3T7V5W1K0HA" + ], + "type": [ + "string", + "null" + ] + }, + "task_id": { + "description": "The task it is about; empty for the plan's drafts.", + "examples": [ + "01JB8V0P8Q2S4U6W8Y0A2C4E6G" + ], + "type": "string" + }, + "url": { + "description": "Where to do it.", + "examples": [ + "https://github.com/acme/web/pull/318" + ], + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "task_id", + "kind", + "ask", + "action" + ], + "type": "object" + }, "NewPlanTask": { "description": "A task in a new plan.", "properties": { @@ -1750,6 +1836,21 @@ "null" ] }, + "covers": { + "description": "The plan's success criteria this task covers, by id (`C1` is the\nfirst of `success_criteria`).", + "examples": [ + [ + "C1" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "description": { "description": "How, in Markdown. The coder reads it as the ticket body.", "examples": [ @@ -1831,6 +1932,18 @@ "Plan": { "description": "A plan.", "properties": { + "attempts": { + "description": "Runs its tasks took, every attempt counted.", + "examples": [ + 6 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, "chat_id": { "description": "The plan chat it came from.", "examples": [ @@ -1841,6 +1954,28 @@ "null" ] }, + "cost_usd": { + "description": "What its tasks' runs cost so far, in US dollars, every attempt counted.", + "examples": [ + 18.4 + ], + "format": "double", + "type": [ + "number", + "null" + ] + }, + "counts": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/TaskCounts", + "description": "How many tasks are in each state." + } + ] + }, "created_at": { "description": "When it was made (RFC 3339).", "examples": [ @@ -1851,6 +1986,30 @@ "null" ] }, + "criteria_count": { + "description": "How many success criteria it has.", + "examples": [ + 5 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "criteria_met": { + "description": "Success criteria the work proved, of `criteria_count`.", + "examples": [ + 3 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, "description": { "description": "More about it, in Markdown.", "examples": [ @@ -1891,6 +2050,16 @@ "null" ] }, + "last_activity_at": { + "description": "When anything last happened on its tasks (RFC 3339).", + "examples": [ + "2026-10-23T09:12:00+00:00" + ], + "type": [ + "string", + "null" + ] + }, "mcp_servers": { "description": "MCP servers used while planning.", "examples": [ @@ -1906,6 +2075,15 @@ "null" ] }, + "needs_count": { + "description": "How many things wait on a person.", + "examples": [ + 1 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, "plan_id": { "description": "The plan's id.", "examples": [ @@ -1926,10 +2104,45 @@ "null" ] }, + "state": { + "description": "Where the plan stands, from its tasks' work: `drafting` (nothing\napproved yet), `running`, `needs_you` (a task asks a person\nsomething, failed, or drafts remain once the rest finished), `done`\n(every task merged or dropped) or `stalled` (open work and nothing\nmoved for 3 days).", + "examples": [ + "running" + ], + "type": [ + "string", + "null" + ] + }, "status": { - "description": "`draft`, `executing` or `completed`.", + "description": "The older status word, kept for older clients: `draft`, `executing`,\nor `done` once every task merged or was dropped. Read `state`.", + "examples": [ + "executing" + ], + "type": [ + "string", + "null" + ] + }, + "success_criteria": { + "description": "The plan's success criteria as written, when it has its own list.", + "examples": [ + [ + "The 11th login attempt within 15 minutes gets 429" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "summary": { + "description": "The count line: merged first, then the states with tasks in them.", "examples": [ - "draft" + "2 of 5 merged, 1 needs you, 1 in review, 1 working" ], "type": [ "string", @@ -1991,6 +2204,7 @@ } }, "required": [ + "needs_count", "task_count" ], "type": "object" @@ -2061,6 +2275,44 @@ "null" ] }, + "attempts": { + "description": "Runs it took, every attempt counted.", + "examples": [ + 2 + ], + "format": "int64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + }, + "cost_usd": { + "description": "What its runs cost, in US dollars.", + "examples": [ + 7.2 + ], + "format": "double", + "type": [ + "number", + "null" + ] + }, + "covers": { + "description": "The plan's success criteria it covers (`C1`, ...).", + "examples": [ + [ + "C1" + ] + ], + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, "created_at": { "description": "When it was made (RFC 3339).", "examples": [ @@ -2101,6 +2353,27 @@ "null" ] }, + "drift": { + "description": "Changes after the plan was approved, and work outside its scope:\n`{kind, detail, by, by_name, at}`, `kind` one of `added`, `changed`,\n`dropped`, `scope`; `by` is `agent` or `person`.", + "examples": [ + [ + { + "at": "2026-10-22T15:00:00+00:00", + "by": "person", + "by_name": "octocat", + "detail": "Added after the plan was approved", + "kind": "added" + } + ] + ], + "items": { + "type": "object" + }, + "type": [ + "array", + "null" + ] + }, "issue_number": { "description": "The GitHub issue it became.", "examples": [ @@ -2153,6 +2426,27 @@ "null" ] }, + "last_activity_at": { + "description": "When anything last happened on it (RFC 3339).", + "examples": [ + "2026-10-23T09:12:00+00:00" + ], + "type": [ + "string", + "null" + ] + }, + "needs": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/NeedsYou", + "description": "What it waits on a person for, when it does." + } + ] + }, "order": { "description": "Its place in the plan, from 0.", "examples": [ @@ -2173,7 +2467,7 @@ ] }, "pr_url": { - "description": "The pull request that run opened.", + "description": "The newest pull request (every one is in `prs`).", "examples": [ "https://github.com/acme/web/pull/318" ], @@ -2182,6 +2476,32 @@ "null" ] }, + "prs": { + "description": "Its pull requests, newest attempt first: `{number, url, repo, state,\nchecks, review, tone, additions, deletions, run_id}`. `tone` is the\ncolour: `ready`, `waiting`, `failing`, `merged` or `closed`.", + "examples": [ + [ + { + "additions": 120, + "checks": "running", + "deletions": 8, + "number": 318, + "repo": "acme/web", + "review": "none", + "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", + "state": "open", + "tone": "waiting", + "url": "https://github.com/acme/web/pull/318" + } + ] + ], + "items": { + "type": "object" + }, + "type": [ + "array", + "null" + ] + }, "rejected_at": { "description": "When it was rejected (RFC 3339).", "examples": [ @@ -2213,7 +2533,7 @@ ] }, "run_id": { - "description": "The run working on it.", + "description": "Its newest run (every attempt is in `runs`).", "examples": [ "01JB8X6F4M2C9QZ3T7V5W1K0HA" ], @@ -2222,10 +2542,60 @@ "null" ] }, + "runs": { + "description": "Every attempt, oldest first: `{run_id, status, created_at, cost_usd}`.", + "examples": [ + [ + { + "cost_usd": 3.6, + "created_at": "2026-10-22T14:02:11+00:00", + "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", + "status": "completed" + } + ] + ], + "items": { + "type": "object" + }, + "type": [ + "array", + "null" + ] + }, + "state": { + "description": "Where the task stands, from its runs and pull requests: `draft`,\n`queued`, `working`, `needs_you`, `failed`, `in_review`, `merged` or\n`dropped`.", + "examples": [ + "in_review" + ], + "type": [ + "string", + "null" + ] + }, + "state_detail": { + "description": "One line: what it is doing, what it waits on, or what blocks it.", + "examples": [ + "Checks are running on pull request #318" + ], + "type": [ + "string", + "null" + ] + }, + "state_reason": { + "description": "Why it failed (`failed` only).", + "examples": [ + null + ], + "type": [ + "string", + "null" + ] + }, "status": { - "description": "`draft`, `approved`, `rejected`, `queued`, `waiting` (on a task it\ndepends on), `running`, `completed` or `failed`.", + "description": "The task row's own word: `draft`, `approved`, `rejected`, `queued`,\n`waiting` (on a task it depends on), `running` (filing its ticket),\n`filed` (older tasks say `done`) or `failed` (the ticket could not be\nfiled). Filing the ticket finishes nothing: read `state`.", "examples": [ - "queued" + "filed" ], "type": [ "string", @@ -2242,6 +2612,16 @@ "null" ] }, + "ticket_filed": { + "description": "Its ticket was filed.", + "examples": [ + true + ], + "type": [ + "boolean", + "null" + ] + }, "title": { "description": "What to do.", "examples": [ @@ -2265,6 +2645,65 @@ }, { "properties": { + "criteria": { + "description": "The success criteria, each with the tasks that cover it and the\nevidence the work gave it: `{id, text, tasks, met, evidence: [{task_id,\nrun_id, state, words, by, tests}]}`. `state` is the criteria trace's\nproof: `proven`, `not_the_ticket`, `failing`, `missing`, `unverified`\nor `not_run`.", + "examples": [ + [ + { + "evidence": [ + { + "by": "tests with and without the change", + "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", + "state": "proven", + "task_id": "01JB8V0P8Q2S4U6W8Y0A2C4E6G", + "words": "proven" + } + ], + "id": "C1", + "met": true, + "tasks": [ + "01JB8V0P8Q2S4U6W8Y0A2C4E6G" + ], + "text": "The 11th login attempt within 15 minutes gets 429" + } + ] + ], + "items": { + "type": "object" + }, + "type": "array" + }, + "estimate": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/StartEstimate", + "description": "What starting the draft tasks, or retrying one, is expected to take,\nfrom the team's recent runs: `{tasks, runs_low, runs_high, cost_low,\ncost_high, per_run_low, per_run_high, sample}`. Null when nothing is\nleft to start or retry." + } + ] + }, + "needs": { + "description": "What waits on a person, in task order, each the exact ask:\n`{task_id, kind, ask, detail, url, run_id, action}`. `kind` is\n`answer`, `review`, `approval`, `checks`, `merge`, `failed`,\n`closed_pr` or `approve_rest`.", + "examples": [ + [ + { + "action": "open_pr", + "ask": "Approve pull request #318", + "detail": "This repo's auto-merge setting requires an approving review from a person.", + "kind": "approval", + "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", + "task_id": "01JB8V0P8Q2S4U6W8Y0A2C4E6G", + "url": "https://github.com/acme/web/pull/318" + } + ] + ], + "items": { + "type": "object" + }, + "type": "array" + }, "tasks": { "description": "The plan's tasks, in order.", "items": { @@ -2274,7 +2713,9 @@ } }, "required": [ - "tasks" + "tasks", + "criteria", + "needs" ], "type": "object" } @@ -6030,6 +6471,178 @@ ], "type": "object" }, + "StartEstimate": { + "description": "What starting tasks, or retrying one, is expected to take, from the\nteam's recent finished runs (the shape of `common::plan_sync::Estimate`).", + "properties": { + "cost_high": { + "description": "The high end of the cost, in US dollars.", + "examples": [ + 19.8 + ], + "format": "double", + "type": "number" + }, + "cost_low": { + "description": "The low end of the cost, in US dollars.", + "examples": [ + 6.3 + ], + "format": "double", + "type": "number" + }, + "per_run_high": { + "description": "One run's typical cost, high end.", + "examples": [ + 4.95 + ], + "format": "double", + "type": "number" + }, + "per_run_low": { + "description": "One run's typical cost, low end (a Retry or Start now).", + "examples": [ + 2.1 + ], + "format": "double", + "type": "number" + }, + "runs_high": { + "description": "Runs expected with the attempts a ticket took lately.", + "examples": [ + 4 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "runs_low": { + "description": "Runs expected: one per task.", + "examples": [ + 3 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "sample": { + "description": "Finished runs the numbers come from; 0 means no history yet.", + "examples": [ + 40 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "tasks": { + "description": "Tasks it would start.", + "examples": [ + 3 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "tasks", + "runs_low", + "runs_high", + "cost_low", + "cost_high", + "per_run_low", + "per_run_high", + "sample" + ], + "type": "object" + }, + "TaskCounts": { + "description": "How many tasks are in each state (the shape of\n`common::plan_state::Counts`, for the API document).", + "properties": { + "draft": { + "description": "Not approved yet.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "dropped": { + "description": "Dropped by a person.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "failed": { + "description": "Failed, with a reason.", + "examples": [ + 0 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "in_review": { + "description": "A pull request is open.", + "examples": [ + 1 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "merged": { + "description": "A pull request merged.", + "examples": [ + 2 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "needs_you": { + "description": "Its run asks a person for something.", + "examples": [ + 1 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "queued": { + "description": "Approved and waiting to start.", + "examples": [ + 1 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + }, + "working": { + "description": "Its run is working.", + "examples": [ + 1 + ], + "format": "int64", + "minimum": 0, + "type": "integer" + } + }, + "required": [ + "draft", + "queued", + "working", + "needs_you", + "failed", + "in_review", + "merged", + "dropped" + ], + "type": "object" + }, "Totals": { "description": "Headline numbers for one period.", "properties": { diff --git a/docs/incidents/pl_plan_follows_the_work.md b/docs/incidents/pl_plan_follows_the_work.md new file mode 100644 index 000000000..0349164a1 --- /dev/null +++ b/docs/incidents/pl_plan_follows_the_work.md @@ -0,0 +1,5 @@ +# pl. `pl_plan_follows_the_work` + +**What happened:** Two plans read wrong for weeks. In the first, a person approved one of three draft tasks from its row, as the page suggested. The worker filed its ticket, marked the task done and, with no task waiting on another, marked the plan done. The page hid the Approve buttons once a plan was not a draft, so the other two tasks stayed drafts with no way to start them, under a plan that said Done. In the second, all four tasks were filed and read done, and so did the plan, while one pull request merged, one closed unmerged, one run failed with no pull request, and one task took eleven runs and seven pull requests (about $130) without merging. No run or pull request was ever written back to a task. + +**The guarantee:** A task's state is derived from the runs of its ticket and their pull requests, never from filing the ticket (`common::plan_state`): Draft, Queued, Working, Needs you, Failed (with its reason), In review, Merged or Dropped. The plan's state comes from its tasks, and it is Done only when every task merged or was dropped. A refresh (`common::plan_sync`) links each run to its plan and task and writes the states; it runs on every run status change, on pull request events, on approval and on the plan page, and the plans list refreshes plans written before it (the backfill). Approving one task never ends the plan: the drafts left are listed as something a person has to approve or drop. diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 9fae91b4c..bb359671d 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -210,6 +210,8 @@ pub mod paged; pub mod placeholders; /// Which waiting plan tasks a merged run releases. pub mod plan_dependents; +pub mod plan_state; +pub mod plan_sync; /// Every body CoderHelm sends GitHub fits GitHub's limit. pub mod pr_body; pub mod pr_body_fit; diff --git a/services/common/src/plan_state.rs b/services/common/src/plan_state.rs new file mode 100644 index 000000000..dfe681a15 --- /dev/null +++ b/services/common/src/plan_state.rs @@ -0,0 +1,1499 @@ +//! Where a plan and each of its tasks stand, derived from the work itself. +//! +//! A plan's task used to be marked `done` the moment its ticket was filed, +//! and the plan `done` once no task waited on another. Nothing then wrote +//! the runs or pull requests back to the task, so a plan read "Done" while +//! most of its pull requests were still open, closed unmerged, or burning +//! attempt after attempt. Approving one task at a time ended the plan with +//! the other tasks still drafts and no way to approve them. +//! +//! The state of a task is now derived, every time, from the task row and +//! the runs of its ticket ([`task_view`]); the plan's from its tasks +//! ([`plan_view`]). Filing the ticket is a fact on the task, never a state. +//! +//! Task states, a small fixed set: +//! +//! | State | When | +//! | --- | --- | +//! | Draft | Not approved yet. | +//! | Queued | Approved, waiting: on the task it runs after, on its ticket, or on its run to start. | +//! | Working | Its newest run is working. | +//! | Needs you | Its newest run asks a person something (a question, a review, an approval, checks it can't fix). | +//! | Failed | Its newest run failed with no pull request left open, a person cancelled it, or its pull request closed unmerged. The reason is kept. | +//! | In review | A pull request is open and the next step is not a person's. | +//! | Merged | A pull request of the task merged. | +//! | Dropped | A person dropped the task, or closed its run on purpose. | +//! +//! Plan states: Drafting (nothing approved yet), Running, Needs you (a task +//! needs a person, failed, or drafts remain once the rest finished), Done +//! (every task Merged or Dropped), Stalled (work open and nothing moved for +//! [`STALE_HOURS`]). +//! +//! Everything here is pure: the store reads and writes are in +//! [`crate::plan_sync`]. + +use serde::{Deserialize, Serialize}; + +use crate::merge_standing::Standing; +use crate::run_wait::WaitingOn; +use crate::trace::{State as ProofState, Trace}; + +/// A plan with open work and no activity for this long reads Stalled. +pub const STALE_HOURS: i64 = 72; + +/// Where a task stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum TaskState { + #[default] + Draft, + Queued, + Working, + NeedsYou, + Failed, + InReview, + Merged, + Dropped, +} + +impl TaskState { + pub const ALL: [TaskState; 8] = [ + TaskState::Draft, + TaskState::Queued, + TaskState::Working, + TaskState::NeedsYou, + TaskState::Failed, + TaskState::InReview, + TaskState::Merged, + TaskState::Dropped, + ]; + + /// The stable code the API and the store use. + pub fn code(self) -> &'static str { + match self { + TaskState::Draft => "draft", + TaskState::Queued => "queued", + TaskState::Working => "working", + TaskState::NeedsYou => "needs_you", + TaskState::Failed => "failed", + TaskState::InReview => "in_review", + TaskState::Merged => "merged", + TaskState::Dropped => "dropped", + } + } + + pub fn from_code(code: &str) -> Option { + TaskState::ALL.into_iter().find(|s| s.code() == code) + } + + /// The words people see. + pub fn label(self) -> &'static str { + match self { + TaskState::Draft => "Draft", + TaskState::Queued => "Queued", + TaskState::Working => "Working", + TaskState::NeedsYou => "Needs you", + TaskState::Failed => "Failed", + TaskState::InReview => "In review", + TaskState::Merged => "Merged", + TaskState::Dropped => "Dropped", + } + } + + /// Nothing more happens on the task. + pub fn is_finished(self) -> bool { + matches!(self, TaskState::Merged | TaskState::Dropped) + } + + /// Approved and not finished: work is open on it. + pub fn is_open(self) -> bool { + !matches!( + self, + TaskState::Draft | TaskState::Merged | TaskState::Dropped + ) + } +} + +/// Where a plan stands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum PlanState { + #[default] + Drafting, + Running, + NeedsYou, + Done, + Stalled, +} + +impl PlanState { + pub fn code(self) -> &'static str { + match self { + PlanState::Drafting => "drafting", + PlanState::Running => "running", + PlanState::NeedsYou => "needs_you", + PlanState::Done => "done", + PlanState::Stalled => "stalled", + } + } + + pub fn from_code(code: &str) -> Option { + [ + PlanState::Drafting, + PlanState::Running, + PlanState::NeedsYou, + PlanState::Done, + PlanState::Stalled, + ] + .into_iter() + .find(|s| s.code() == code) + } + + pub fn label(self) -> &'static str { + match self { + PlanState::Drafting => "Drafting", + PlanState::Running => "Running", + PlanState::NeedsYou => "Needs you", + PlanState::Done => "Done", + PlanState::Stalled => "Stalled", + } + } + + /// The plan's older `status` word, kept for clients that read it. + pub fn legacy_status(self) -> &'static str { + match self { + PlanState::Drafting => "draft", + PlanState::Done => "done", + _ => "executing", + } + } +} + +/// A task row, as far as its state goes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct TaskFacts { + pub task_id: String, + pub title: String, + pub description: String, + pub acceptance_criteria: String, + /// The row's own word: `draft`, `approved`, `rejected`, `queued`, + /// `waiting`, `running` (filing its ticket), `filed` (older rows say + /// `done` or `issue_created`), `failed`. + pub status: String, + pub depends_on: String, + /// Why filing failed, when it did. + pub failure_reason: String, + pub created_at: String, + pub approved_at: String, + pub rejected_at: String, + pub rejected_by: String, + /// The last edit, when one was made after the task was written. + pub edited_at: String, + /// `person` or `agent`. + pub edited_by_kind: String, + pub edited_by: String, + /// Who wrote the task: `agent` (the plan chat) or `person`. + pub added_by_kind: String, + /// Criteria ids (`C1`) the task says it covers. + pub covers: Vec, +} + +/// One pull request of a run. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PrFacts { + pub repo: String, + pub number: u64, + pub url: String, + /// `merged`, `closed`, or empty while open. + pub outcome: String, +} + +/// A run of the task's ticket, as far as the task's state goes. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct RunFacts { + pub run_id: String, + pub status: String, + pub created_at: String, + pub updated_at: String, + pub cost_usd: f64, + pub current_pass: String, + pub error: String, + pub close_reason: String, + pub waiting_on: Option, + pub prs: Vec, + /// The record's own `pr_outcome` (its primary pull request). + pub pr_outcome: String, + /// `passed`, `failed`, or empty. + pub ci_last: String, + pub standing: Option, + /// The latest review a person gave on GitHub: `approved`, + /// `changes_requested`, or empty. + pub review: String, + pub additions: Option, + pub deletions: Option, + pub trace: Option, + /// The files the run's branch changed. + pub files: Vec, + /// Scope ledger items a round moved into scope: `(item, why)`. + pub scope_moved_in: Vec<(String, String)>, +} + +impl RunFacts { + fn merged(&self) -> bool { + self.status == "merged" + || self.pr_outcome == "merged" + || self.prs.iter().any(|p| p.outcome == "merged") + } + + fn open_pr(&self) -> Option<&PrFacts> { + if self.pr_outcome == "merged" || self.pr_outcome == "closed" { + return None; + } + self.prs.iter().find(|p| p.outcome.is_empty()) + } + + fn closed_pr(&self) -> Option<&PrFacts> { + if self.pr_outcome == "closed" { + return self.prs.first(); + } + self.prs.iter().find(|p| p.outcome == "closed") + } +} + +/// A pull request as a chip: its number, coloured by checks and review. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PrChip { + pub number: u64, + pub url: String, + pub repo: String, + /// `open`, `draft`, `merged` or `closed`. + pub state: String, + /// `passed`, `failed`, `running` or `unknown`. + pub checks: String, + /// `approved`, `changes_requested`, `waiting` or `none`. + pub review: String, + /// The colour: `ready` (green), `waiting` (yellow), `failing` (red), + /// `merged` (purple), `closed` (grey). + pub tone: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub additions: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub deletions: Option, + /// The run that opened it. + pub run_id: String, +} + +/// One run of a task, as listed on it. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct RunLine { + pub run_id: String, + pub status: String, + pub created_at: String, + pub cost_usd: f64, +} + +/// Something a person has to do for the plan to go on: the exact ask. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct NeedsItem { + pub task_id: String, + /// `answer`, `review`, `approval`, `checks`, `merge`, `failed`, + /// `closed_pr` or `approve_rest`. + pub kind: String, + /// What to do, one line. + pub ask: String, + /// Why, or what is open. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub detail: String, + /// Where to do it. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub url: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub run_id: String, + /// The button: `answer` (the run page), `open_pr`, `open_link`, + /// `retry` or `approve`. + pub action: String, +} + +/// A change to the plan after it was approved. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Drift { + /// `added`, `changed`, `dropped` or `scope`. + pub kind: String, + pub detail: String, + /// `agent`, `person`, or empty when not known. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub by: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub by_name: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub at: String, +} + +/// A task with where it stands. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TaskView { + pub state: TaskState, + /// One line: what it is doing, what it waits on, or what blocks it. + pub detail: String, + /// Why it failed (Failed only). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub reason: String, + /// Every attempt, oldest first. + pub runs: Vec, + pub prs: Vec, + pub attempts: usize, + pub cost_usd: f64, + #[serde(skip_serializing_if = "Option::is_none")] + pub needs: Option, + pub drift: Vec, + /// The ticket was filed (a fact, not a state). + pub ticket_filed: bool, + /// The newest time anything happened on the task. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub last_activity: String, +} + +/// The runs that count, oldest first. Archived runs are hidden from people +/// and say nothing about the work. +fn ordered(runs: &[RunFacts]) -> Vec<&RunFacts> { + let mut v: Vec<&RunFacts> = runs.iter().filter(|r| r.status != "archived").collect(); + v.sort_by(|a, b| { + a.created_at + .cmp(&b.created_at) + .then(a.run_id.cmp(&b.run_id)) + }); + v +} + +fn pass_words(pass: &str) -> String { + match pass.trim() { + "" => "working on it".into(), + "triage" => "reading the ticket".into(), + "plan" => "planning the change".into(), + "implement" => "writing the change".into(), + "test" => "running the tests".into(), + "security" => "checking security".into(), + "review" => "reviewing its own work".into(), + "feedback" => "taking review feedback".into(), + "pr" => "opening the pull request".into(), + other => other.replace('_', " "), + } +} + +fn one_line(s: &str, max: usize) -> String { + let s = s.split_whitespace().collect::>().join(" "); + crate::truncate_str(&s, max).to_string() +} + +/// The chip for one pull request of a run. +pub fn chip(run: &RunFacts, pr: &PrFacts) -> PrChip { + let merged = pr.outcome == "merged" + || (run.prs.len() <= 1 && (run.pr_outcome == "merged" || run.status == "merged")); + let closed = + !merged && (pr.outcome == "closed" || (run.prs.len() <= 1 && run.pr_outcome == "closed")); + let code = run.standing.as_ref().map(|s| s.code.as_str()).unwrap_or(""); + let draft = code == "draft"; + let checks = if code == "checks_failing" || (code.is_empty() && run.ci_last == "failed") { + "failed" + } else if code == "checks_running" || run.status == "awaiting_ci" { + "running" + } else if run.ci_last == "passed" + || matches!( + code, + "auto_merge_off" | "needs_person_approval" | "repo_requires_person_review" | "merging" + ) + { + "passed" + } else if run.ci_last == "failed" { + "failed" + } else { + "unknown" + }; + let review = match (run.review.as_str(), code) { + ("approved", _) | (_, "merging") => "approved", + ("changes_requested", _) | (_, "review_changes_requested") => "changes_requested", + (_, "needs_person_approval" | "repo_requires_person_review" | "reviewing") => "waiting", + _ => "none", + }; + let state = if merged { + "merged" + } else if closed { + "closed" + } else if draft { + "draft" + } else { + "open" + }; + let tone = match state { + "merged" => "merged", + "closed" => "closed", + _ if checks == "failed" || review == "changes_requested" => "failing", + _ if checks == "passed" + && !draft + && matches!(code, "merging" | "auto_merge_off" | "") + && review != "waiting" => + { + "ready" + } + _ => "waiting", + }; + PrChip { + number: pr.number, + url: pr.url.clone(), + repo: pr.repo.clone(), + state: state.into(), + checks: checks.into(), + review: review.into(), + tone: tone.into(), + additions: run.additions, + deletions: run.deletions, + run_id: run.run_id.clone(), + } +} + +/// Where a task stands, from its row and the runs of its ticket. +/// `waits_on` is the title of the task it runs after, when it has one. +pub fn task_view(task: &TaskFacts, runs: &[RunFacts], waits_on: Option<&str>) -> TaskView { + let runs = ordered(runs); + let mut v = TaskView { + runs: runs + .iter() + .map(|r| RunLine { + run_id: r.run_id.clone(), + status: r.status.clone(), + created_at: r.created_at.clone(), + cost_usd: r.cost_usd, + }) + .collect(), + attempts: runs.len(), + cost_usd: runs.iter().map(|r| r.cost_usd).sum(), + ticket_filed: !runs.is_empty() + || matches!(task.status.as_str(), "filed" | "done" | "issue_created"), + ..Default::default() + }; + // Every pull request any attempt opened, newest attempt first. + let mut seen = std::collections::HashSet::new(); + for r in runs.iter().rev() { + for pr in &r.prs { + if seen.insert((pr.repo.to_ascii_lowercase(), pr.number)) { + v.prs.push(chip(r, pr)); + } + } + } + v.last_activity = runs + .iter() + .map(|r| { + if r.updated_at.is_empty() { + r.created_at.clone() + } else { + r.updated_at.clone() + } + }) + .chain([ + task.approved_at.clone(), + task.rejected_at.clone(), + task.edited_at.clone(), + ]) + .max() + .unwrap_or_default(); + + let set = |v: &mut TaskView, state: TaskState, detail: String| { + v.state = state; + v.detail = detail; + }; + + // A person dropped it. + if task.status == "rejected" { + let by = if task.rejected_by.is_empty() { + String::new() + } else { + format!(" by {}", task.rejected_by) + }; + set(&mut v, TaskState::Dropped, format!("Dropped{by}")); + return v; + } + // Any attempt's pull request merged: the work is in. + if let Some(r) = runs.iter().rev().find(|r| r.merged()) { + let pr = r + .prs + .iter() + .find(|p| p.outcome == "merged") + .or(r.prs.first()); + let what = pr + .map(|p| format!("Pull request #{} merged", p.number)) + .unwrap_or_else(|| "Merged".into()); + set(&mut v, TaskState::Merged, what); + return v; + } + let Some(r) = runs.last().copied() else { + let (state, detail) = match task.status.as_str() { + "draft" | "" => (TaskState::Draft, "Waiting for approval".to_string()), + "failed" => { + v.reason = if task.failure_reason.trim().is_empty() { + "The ticket could not be filed.".into() + } else { + one_line(&task.failure_reason, 400) + }; + v.needs = Some(NeedsItem { + task_id: task.task_id.clone(), + kind: "failed".into(), + ask: format!("Task \"{}\" failed", one_line(&task.title, 120)), + detail: v.reason.clone(), + action: "retry".into(), + ..Default::default() + }); + (TaskState::Failed, v.reason.clone()) + } + "waiting" => ( + TaskState::Queued, + match waits_on { + Some(t) => format!("Waits for \"{}\" to merge", one_line(t, 120)), + None => "Waits for the task it runs after to merge".into(), + }, + ), + "filed" | "done" | "issue_created" => ( + TaskState::Queued, + "Ticket filed; waiting for its run to start".into(), + ), + "running" => (TaskState::Queued, "Filing its ticket".into()), + _ => (TaskState::Queued, "Waiting to file its ticket".into()), + }; + set(&mut v, state, detail); + return v; + }; + + let open = r.open_pr().cloned(); + let error = one_line(&r.error, 400); + let needs = |kind: &str, ask: String, detail: String, url: String, action: &str| NeedsItem { + task_id: task.task_id.clone(), + kind: kind.into(), + ask, + detail, + url, + run_id: r.run_id.clone(), + action: action.into(), + }; + match r.status.as_str() { + "pending" | "queued" => set(&mut v, TaskState::Queued, "Its run is queued".into()), + "retried" => set( + &mut v, + TaskState::Queued, + "A new attempt is starting".into(), + ), + "running" | "awaiting_setup" => { + let doing = pass_words(&r.current_pass); + set(&mut v, TaskState::Working, format!("Working: {doing}")); + } + "awaiting_ci" => match &open { + Some(pr) => set( + &mut v, + TaskState::InReview, + format!("Checks are running on pull request #{}", pr.number), + ), + None => set(&mut v, TaskState::Working, "Waiting on CI".into()), + }, + "needs_input" | "needs_outside_change" => { + let (ask, detail, url, kind) = match &r.waiting_on { + Some(w) => { + let kind = if w.questions > 0 { + "answer" + } else if w.action.to_ascii_lowercase().starts_with("review") { + "review" + } else { + "approval" + }; + (w.action.clone(), w.detail.clone(), w.url.clone(), kind) + } + None => ( + "Answer what the run asks on its page".into(), + error.clone(), + String::new(), + "answer", + ), + }; + let action = if kind == "review" && !url.is_empty() { + "open_pr" + } else { + "answer" + }; + set(&mut v, TaskState::NeedsYou, one_line(&ask, 200)); + v.needs = Some(needs(kind, ask, detail, url, action)); + } + "failed" => match &open { + Some(pr) if r.ci_last == "failed" => { + let ask = format!( + "Checks fail on pull request #{} and CoderHelm could not fix them", + pr.number + ); + set(&mut v, TaskState::NeedsYou, ask.clone()); + v.needs = Some(needs("checks", ask, error, pr.url.clone(), "open_pr")); + } + Some(pr) => { + let ask = format!( + "The run stopped with pull request #{} open; finish or close it", + pr.number + ); + set(&mut v, TaskState::NeedsYou, ask.clone()); + v.needs = Some(needs("review", ask, error, pr.url.clone(), "open_pr")); + } + None => { + v.reason = if error.is_empty() { + "The run failed and gave no reason.".into() + } else { + error.clone() + }; + let why = v.reason.clone(); + set(&mut v, TaskState::Failed, why); + v.needs = Some(needs( + "failed", + format!("Task \"{}\" failed", one_line(&task.title, 120)), + v.reason.clone(), + String::new(), + "retry", + )); + } + }, + "cancelled" => { + v.reason = "A person cancelled its run.".into(); + let why = v.reason.clone(); + set(&mut v, TaskState::Failed, why); + v.needs = Some(needs( + "failed", + format!("Task \"{}\" was cancelled", one_line(&task.title, 120)), + "Retry it, or drop the task.".into(), + String::new(), + "retry", + )); + } + "closed" => { + let why = one_line(&r.close_reason, 200); + let detail = if why.is_empty() { + "A person closed its run".to_string() + } else { + format!("A person closed its run: {why}") + }; + set(&mut v, TaskState::Dropped, detail); + } + "covered_by_pr" => { + let url = open.as_ref().map(|p| p.url.clone()).unwrap_or_default(); + let ask = "An open pull request already does this work; merge it or drop the task" + .to_string(); + set(&mut v, TaskState::NeedsYou, ask.clone()); + v.needs = Some(needs("review", ask, error, url, "open_pr")); + } + // Finished its work: the pull request decides. + "completed" | "success" => match (&open, r.closed_pr()) { + (Some(pr), _) => match r.standing.as_ref().filter(|s| s.needs_person) { + Some(s) => { + let kind = if s.code == "auto_merge_off" { + "merge" + } else { + "approval" + }; + let ask = if kind == "merge" { + format!("Merge pull request #{}", pr.number) + } else { + format!("Approve pull request #{}", pr.number) + }; + set(&mut v, TaskState::NeedsYou, ask.clone()); + v.needs = Some(needs(kind, ask, s.text.clone(), pr.url.clone(), "open_pr")); + } + None => { + let detail = r + .standing + .as_ref() + .map(|s| s.text.clone()) + .unwrap_or_else(|| { + format!("Pull request #{} is open for review", pr.number) + }); + set(&mut v, TaskState::InReview, detail); + } + }, + (None, Some(pr)) => { + v.reason = format!("Pull request #{} was closed without merging.", pr.number); + let why = v.reason.clone(); + set(&mut v, TaskState::Failed, why); + v.needs = Some(needs( + "closed_pr", + format!("Pull request #{} closed unmerged", pr.number), + "Retry the task, or drop it.".into(), + pr.url.clone(), + "retry", + )); + } + (None, None) => { + v.reason = if error.is_empty() { + "The run finished without a pull request.".into() + } else { + format!("The run finished without a pull request: {error}") + }; + let why = v.reason.clone(); + set(&mut v, TaskState::Failed, why); + v.needs = Some(needs( + "failed", + format!( + "Task \"{}\" has no pull request", + one_line(&task.title, 120) + ), + v.reason.clone(), + String::new(), + "retry", + )); + } + }, + other => set( + &mut v, + TaskState::Working, + format!("Working ({})", other.replace('_', " ")), + ), + } + v +} + +/// Changes to the task after its plan was approved, and work outside its +/// written scope. `started_at` is when the plan first ran ("" before). +pub fn task_drift( + task: &TaskFacts, + view: &TaskView, + runs: &[RunFacts], + started_at: &str, +) -> Vec { + let mut out = Vec::new(); + if !started_at.is_empty() { + let after = |t: &str| !t.is_empty() && t > started_at; + if after(&task.created_at) { + out.push(Drift { + kind: "added".into(), + detail: "Added after the plan was approved".into(), + by: task.added_by_kind.clone(), + at: task.created_at.clone(), + ..Default::default() + }); + } + if after(&task.edited_at) { + out.push(Drift { + kind: "changed".into(), + detail: "Changed after the plan was approved".into(), + by: task.edited_by_kind.clone(), + by_name: task.edited_by.clone(), + at: task.edited_at.clone(), + }); + } + if task.status == "rejected" && after(&task.rejected_at) { + out.push(Drift { + kind: "dropped".into(), + detail: "Dropped after the plan was approved".into(), + by: "person".into(), + by_name: task.rejected_by.clone(), + at: task.rejected_at.clone(), + }); + } + } + // Scope: the newest attempt that opened a pull request. + let Some(run) = ordered(runs).into_iter().rev().find(|r| !r.prs.is_empty()) else { + return out; + }; + let _ = view; + let outside = outside_scope( + &format!("{}\n{}", task.description, task.acceptance_criteria), + &run.files, + ); + if !outside.is_empty() { + let shown: Vec<&str> = outside.iter().take(3).map(String::as_str).collect(); + let more = outside.len().saturating_sub(shown.len()); + let mut detail = format!( + "The pull request changes files outside the task's planned scope: {}", + shown.join(", ") + ); + if more > 0 { + detail.push_str(&format!(" and {more} more")); + } + out.push(Drift { + kind: "scope".into(), + detail, + by: "agent".into(), + ..Default::default() + }); + } + for (item, why) in &run.scope_moved_in { + out.push(Drift { + kind: "scope".into(), + detail: format!( + "Scope widened during the run: {} ({})", + one_line(item, 120), + one_line(why, 160) + ), + by: "agent".into(), + ..Default::default() + }); + } + out +} + +/// The changed files outside what the task's text names. The task names +/// its scope by paths (`marks_of`, the scope ledger's reading of a text); +/// a file is inside when it is one of them or under one's folder. Tests, +/// docs and lockfiles go with any change. A task that names no path has no +/// written scope to be outside of. +pub fn outside_scope(task_text: &str, files: &[String]) -> Vec { + let paths: Vec = crate::scope_ledger::marks_of(task_text) + .into_iter() + .filter(|m| m.contains('/') || m.contains('.')) + .map(|m| { + m.trim_start_matches("./") + .trim_start_matches('/') + .to_string() + }) + .filter(|m| m.contains('/')) + .collect(); + if paths.is_empty() { + return Vec::new(); + } + let roots: Vec = paths + .iter() + .map(|p| { + let last = p.rsplit('/').next().unwrap_or(""); + if last.contains('.') { + p.rsplit_once('/') + .map(|(d, _)| d.to_string()) + .unwrap_or_default() + } else { + p.trim_end_matches('/').to_string() + } + }) + .filter(|r| !r.is_empty()) + .collect(); + files + .iter() + .filter(|f| { + let f = f.trim_start_matches("./"); + let lower = f.to_ascii_lowercase(); + let goes_along = crate::trace::is_test_path(f) + || lower.ends_with(".md") + || lower.ends_with(".lock") + || lower.ends_with("package-lock.json") + || lower.ends_with("pnpm-lock.yaml"); + !goes_along + && !paths.iter().any(|p| f == p) + && !roots + .iter() + .any(|r| f.starts_with(&format!("{r}/")) || f == r) + }) + .cloned() + .collect() +} + +/// One success criterion of a plan with the evidence the work gave it. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Criterion { + /// `C1`, `C2`, ... + pub id: String, + pub text: String, + /// The tasks that cover it. + pub tasks: Vec, + pub evidence: Vec, + /// Proven by the work. + pub met: bool, +} + +/// What the work shows for a criterion (the run's criteria trace). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Evidence { + pub task_id: String, + pub run_id: String, + /// The trace's proof state: `proven`, `not_the_ticket`, `failing`, + /// `missing`, `unverified` or `not_run`. + pub state: String, + /// The words for it. + pub words: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub by: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tests: Vec, +} + +/// The bullet lines of a criteria text, each one criterion. +pub fn bullets(text: &str) -> Vec { + let mut out = Vec::new(); + for line in text.lines() { + let l = line.trim(); + let item = l + .strip_prefix("- [ ] ") + .or_else(|| l.strip_prefix("- [x] ")) + .or_else(|| l.strip_prefix("- ")) + .or_else(|| l.strip_prefix("* ")) + .or_else(|| { + let (n, rest) = l.split_once(". ")?; + n.chars().all(|c| c.is_ascii_digit()).then_some(rest) + }); + if let Some(item) = item.map(str::trim).filter(|s| !s.is_empty()) { + out.push(item.to_string()); + } + } + if out.is_empty() && !text.trim().is_empty() { + out.push(one_line(text, 400)); + } + out +} + +fn words_of(s: &str) -> Vec { + s.split(|c: char| !c.is_alphanumeric()) + .filter(|w| w.len() > 2) + .map(|w| w.to_lowercase()) + .collect() +} + +/// Whether a trace row's criterion is this criterion: the same text, one +/// inside the other, or most of the shorter one's words shared. +pub fn same_criterion(a: &str, b: &str) -> bool { + let (na, nb) = (words_of(a).join(" "), words_of(b).join(" ")); + if na.is_empty() || nb.is_empty() { + return false; + } + if na == nb || na.contains(&nb) || nb.contains(&na) { + return true; + } + let (wa, wb) = (words_of(a), words_of(b)); + let (short, long) = if wa.len() <= wb.len() { + (&wa, &wb) + } else { + (&wb, &wa) + }; + let shared = short.iter().filter(|w| long.contains(w)).count(); + short.len() >= 3 && shared * 10 >= short.len() * 7 +} + +fn proof_code(s: ProofState) -> &'static str { + match s { + ProofState::Proven => "proven", + ProofState::NotTheTicket => "not_the_ticket", + ProofState::Failing => "failing", + ProofState::Missing => "missing", + ProofState::Unverified => "unverified", + ProofState::NotRun => "not_run", + } +} + +/// The plan's success criteria with their evidence. The plan's own list +/// when it has one (each task names what it covers, else it covers what its +/// acceptance criteria match); otherwise each task's acceptance criteria. +/// `tasks` pairs each task with the newest trace of its runs. +pub fn criteria( + plan_criteria: &[String], + tasks: &[(&TaskFacts, Option<&RunTrace>)], +) -> Vec { + let mut out: Vec = Vec::new(); + if plan_criteria.iter().any(|c| !c.trim().is_empty()) { + for (i, text) in plan_criteria + .iter() + .filter(|c| !c.trim().is_empty()) + .enumerate() + { + let id = format!("C{}", i + 1); + let covering: Vec<&TaskFacts> = tasks + .iter() + .map(|(t, _)| *t) + .filter(|t| { + if !t.covers.is_empty() { + t.covers.iter().any(|c| c.eq_ignore_ascii_case(&id)) + } else { + bullets(&t.acceptance_criteria) + .iter() + .any(|b| same_criterion(b, text)) + } + }) + .collect(); + out.push(Criterion { + id, + text: text.trim().to_string(), + tasks: covering.iter().map(|t| t.task_id.clone()).collect(), + ..Default::default() + }); + } + } else { + for (t, _) in tasks { + if t.status == "rejected" { + continue; + } + for b in bullets(&t.acceptance_criteria) { + out.push(Criterion { + id: format!("C{}", out.len() + 1), + text: b, + tasks: vec![t.task_id.clone()], + ..Default::default() + }); + } + } + } + for c in out.iter_mut() { + for (t, trace) in tasks { + if !c.tasks.contains(&t.task_id) { + continue; + } + let Some(rt) = trace else { continue }; + for row in rt + .trace + .rows + .iter() + .filter(|r| same_criterion(&r.criterion, &c.text)) + { + c.evidence.push(Evidence { + task_id: t.task_id.clone(), + run_id: rt.run_id.clone(), + state: proof_code(row.proof.state).into(), + words: row.proof.state.words().into(), + by: row.proof.by.clone(), + tests: row.tests.iter().take(4).cloned().collect(), + }); + } + } + c.met = !c.evidence.is_empty() && c.evidence.iter().all(|e| e.state == "proven"); + } + out +} + +/// A run's criteria trace with the run it came from. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RunTrace { + pub run_id: String, + pub trace: Trace, +} + +/// The newest trace among a task's runs. +pub fn newest_trace(runs: &[RunFacts]) -> Option { + ordered(runs).into_iter().rev().find_map(|r| { + r.trace.as_ref().map(|t| RunTrace { + run_id: r.run_id.clone(), + trace: t.clone(), + }) + }) +} + +/// How many tasks are in each state, and what the plan spent. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Counts { + pub draft: usize, + pub queued: usize, + pub working: usize, + pub needs_you: usize, + pub failed: usize, + pub in_review: usize, + pub merged: usize, + pub dropped: usize, +} + +impl Counts { + pub fn add(&mut self, s: TaskState) { + *self.slot(s) += 1; + } + + fn slot(&mut self, s: TaskState) -> &mut usize { + match s { + TaskState::Draft => &mut self.draft, + TaskState::Queued => &mut self.queued, + TaskState::Working => &mut self.working, + TaskState::NeedsYou => &mut self.needs_you, + TaskState::Failed => &mut self.failed, + TaskState::InReview => &mut self.in_review, + TaskState::Merged => &mut self.merged, + TaskState::Dropped => &mut self.dropped, + } + } + + pub fn get(&self, s: TaskState) -> usize { + match s { + TaskState::Draft => self.draft, + TaskState::Queued => self.queued, + TaskState::Working => self.working, + TaskState::NeedsYou => self.needs_you, + TaskState::Failed => self.failed, + TaskState::InReview => self.in_review, + TaskState::Merged => self.merged, + TaskState::Dropped => self.dropped, + } + } + + pub fn total(&self) -> usize { + TaskState::ALL.iter().map(|s| self.get(*s)).sum() + } +} + +/// A plan with where it stands. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct PlanView { + pub state: PlanState, + /// One line: the count line people read first. + pub summary: String, + pub counts: Counts, + pub cost_usd: f64, + pub attempts: usize, + /// Everything waiting on a person, in task order. + pub needs: Vec, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub last_activity: String, +} + +/// Where the plan stands, from its tasks' views (in task order). `now` and +/// the views' activity times are RFC 3339. +pub fn plan_view(tasks: &[(&TaskFacts, &TaskView)], now: &str) -> PlanView { + let mut p = PlanView::default(); + for (_, v) in tasks { + p.counts.add(v.state); + p.cost_usd += v.cost_usd; + p.attempts += v.attempts; + if let Some(n) = &v.needs { + p.needs.push(n.clone()); + } + if v.last_activity > p.last_activity { + p.last_activity = v.last_activity.clone(); + } + } + let c = &p.counts; + let total = c.total(); + let started = total - c.draft - c.dropped > 0 || c.merged > 0; + let open = c.queued + c.working + c.in_review; + p.state = if total == 0 || !started { + PlanState::Drafting + } else if c.merged + c.dropped == total { + PlanState::Done + } else if c.needs_you + c.failed > 0 || (open == 0 && c.draft > 0) { + // A task asks something or failed, or only drafts are left. + PlanState::NeedsYou + } else if open > 0 && stale(&p.last_activity, now) { + PlanState::Stalled + } else { + PlanState::Running + }; + // Drafts left once the plan started: they are approved from here. + if started && c.draft > 0 { + p.needs.push(NeedsItem { + kind: "approve_rest".into(), + ask: if c.draft == 1 { + "Approve or drop the 1 task still in draft".into() + } else { + format!("Approve or drop the {} tasks still in draft", c.draft) + }, + action: "approve".into(), + ..Default::default() + }); + } + p.summary = summary(c); + p +} + +fn stale(last: &str, now: &str) -> bool { + let (Ok(last), Ok(now)) = ( + chrono::DateTime::parse_from_rfc3339(last), + chrono::DateTime::parse_from_rfc3339(now), + ) else { + return false; + }; + (now - last).num_hours() >= STALE_HOURS +} + +/// "3 of 7 merged, 2 in review, 1 needs you": merged first, then each state +/// with tasks in it, in the order people act on them. +pub fn summary(c: &Counts) -> String { + let total = c.total(); + if total == 0 { + return "No tasks".into(); + } + // Nothing started yet: what is left to review. + if c.draft + c.dropped == total && c.draft > 0 { + let mut s = format!( + "{} task{} to review", + c.draft, + if c.draft == 1 { "" } else { "s" } + ); + if c.dropped > 0 { + s.push_str(&format!(", {} dropped", c.dropped)); + } + return s; + } + let mut parts = vec![format!("{} of {total} merged", c.merged)]; + for s in [ + TaskState::NeedsYou, + TaskState::Failed, + TaskState::InReview, + TaskState::Working, + TaskState::Queued, + TaskState::Draft, + TaskState::Dropped, + ] { + let n = c.get(s); + if n > 0 { + let word = match s { + TaskState::Draft => "in draft".to_string(), + other => other.label().to_lowercase(), + }; + parts.push(format!("{n} {word}")); + } + } + parts.join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn task(status: &str) -> TaskFacts { + TaskFacts { + task_id: "T1".into(), + title: "Limit login attempts".into(), + status: status.into(), + ..Default::default() + } + } + + fn run(id: &str, status: &str, at: &str) -> RunFacts { + RunFacts { + run_id: id.into(), + status: status.into(), + created_at: at.into(), + updated_at: at.into(), + cost_usd: 2.5, + ..Default::default() + } + } + + fn pr(n: u64, outcome: &str) -> PrFacts { + PrFacts { + repo: "example-org/web".into(), + number: n, + url: format!("https://github.com/example-org/web/pull/{n}"), + outcome: outcome.into(), + } + } + + #[test] + fn filing_the_ticket_is_never_done() { + // The row the worker writes once the ticket is filed, old and new. + for status in ["filed", "done", "issue_created"] { + let v = task_view(&task(status), &[], None); + assert_eq!(v.state, TaskState::Queued, "{status}"); + assert!(v.ticket_filed); + assert!(v.detail.contains("waiting for its run"), "{}", v.detail); + } + } + + #[test] + fn the_state_follows_the_run_and_its_pull_request() { + let t = task("filed"); + let mut r = run("R1", "running", "2026-11-01T10:00:00Z"); + r.current_pass = "implement".into(); + assert_eq!(task_view(&t, &[r.clone()], None).state, TaskState::Working); + + r.status = "completed".into(); + r.prs = vec![pr(12, "")]; + let v = task_view(&t, &[r.clone()], None); + assert_eq!(v.state, TaskState::InReview); + assert_eq!(v.prs[0].number, 12); + + r.ci_last = "failed".into(); + r.status = "failed".into(); + r.error = "lint fails".into(); + let v = task_view(&t, &[r.clone()], None); + assert_eq!(v.state, TaskState::NeedsYou); + assert_eq!(v.needs.as_ref().unwrap().kind, "checks"); + assert_eq!(v.prs[0].tone, "failing"); + + r.status = "completed".into(); + r.ci_last = "passed".into(); + r.standing = Some(crate::merge_standing::decide( + "example-org/web", + &crate::merge_standing::Facts { + auto_merge: true, + require_human_approval: true, + ..Default::default() + }, + )); + let v = task_view(&t, &[r.clone()], None); + assert_eq!(v.state, TaskState::NeedsYou); + assert_eq!(v.needs.as_ref().unwrap().ask, "Approve pull request #12"); + + r.pr_outcome = "merged".into(); + r.prs = vec![pr(12, "merged")]; + let v = task_view(&t, &[r.clone()], None); + assert_eq!(v.state, TaskState::Merged); + assert_eq!(v.prs[0].tone, "merged"); + + r.pr_outcome = "closed".into(); + r.prs = vec![pr(12, "closed")]; + r.standing = None; + let v = task_view(&t, &[r], None); + assert_eq!(v.state, TaskState::Failed); + assert!(v.reason.contains("closed without merging")); + } + + #[test] + fn a_failure_keeps_its_reason_and_counts_every_attempt() { + let t = task("filed"); + let mut a = run("R1", "retried", "2026-11-01T10:00:00Z"); + a.prs = vec![pr(1, "closed")]; + let mut b = run("R2", "failed", "2026-11-02T10:00:00Z"); + b.error = "Reached the maximum number of steps".into(); + let v = task_view(&t, &[b.clone(), a.clone()], None); + assert_eq!(v.state, TaskState::Failed); + assert_eq!(v.reason, "Reached the maximum number of steps"); + assert_eq!(v.attempts, 2); + assert!((v.cost_usd - 5.0).abs() < 1e-9); + assert_eq!(v.runs[0].run_id, "R1", "oldest first"); + let mut row = task("failed"); + row.failure_reason = "No Jira project is set for this task.".into(); + let v = task_view(&row, &[], None); + assert_eq!(v.reason, "No Jira project is set for this task."); + } + + #[test] + fn a_dropped_or_draft_task_says_so() { + assert_eq!( + task_view(&task("rejected"), &[], None).state, + TaskState::Dropped + ); + assert_eq!(task_view(&task("draft"), &[], None).state, TaskState::Draft); + let v = task_view(&task("waiting"), &[], Some("Add the table")); + assert_eq!(v.state, TaskState::Queued); + assert!(v.detail.contains("Add the table")); + } + + #[test] + fn one_approved_task_leaves_the_plan_open_with_the_rest_to_approve() { + let a = task("filed"); + let mut b = task("draft"); + b.task_id = "T2".into(); + let mut c = task("draft"); + c.task_id = "T3".into(); + let va = task_view(&a, &[run("R1", "running", "2026-11-01T10:00:00Z")], None); + let (vb, vc) = (task_view(&b, &[], None), task_view(&c, &[], None)); + let p = plan_view(&[(&a, &va), (&b, &vb), (&c, &vc)], "2026-11-01T11:00:00Z"); + assert_eq!(p.state, PlanState::Running); + assert!(p + .needs + .iter() + .any(|n| n.kind == "approve_rest" && n.ask.contains("2 tasks"))); + // Once the approved one merged, the drafts are what is left. + let mut done = run("R1", "merged", "2026-11-01T10:00:00Z"); + done.pr_outcome = "merged".into(); + let va = task_view(&a, &[done], None); + let p = plan_view(&[(&a, &va), (&b, &vb), (&c, &vc)], "2026-11-01T11:00:00Z"); + assert_eq!(p.state, PlanState::NeedsYou); + assert_ne!(p.state, PlanState::Done); + } + + #[test] + fn done_means_every_task_merged_or_dropped() { + let a = task("filed"); + let mut b = task("rejected"); + b.task_id = "T2".into(); + let mut m = run("R1", "completed", "2026-11-01T10:00:00Z"); + m.prs = vec![pr(4, "")]; + let open = task_view(&a, &[m.clone()], None); + let dropped = task_view(&b, &[], None); + let p = plan_view(&[(&a, &open), (&b, &dropped)], "2026-11-01T11:00:00Z"); + assert_eq!(p.state, PlanState::Running); + m.prs = vec![pr(4, "merged")]; + let merged = task_view(&a, &[m], None); + let p = plan_view(&[(&a, &merged), (&b, &dropped)], "2026-11-01T11:00:00Z"); + assert_eq!(p.state, PlanState::Done); + assert_eq!(p.summary, "1 of 2 merged, 1 dropped"); + let c = Counts { + draft: 3, + dropped: 1, + ..Default::default() + }; + assert_eq!(summary(&c), "3 tasks to review, 1 dropped"); + } + + #[test] + fn open_work_with_no_activity_is_stalled() { + let a = task("filed"); + let mut r = run("R1", "completed", "2026-11-01T10:00:00Z"); + r.prs = vec![pr(4, "")]; + let v = task_view(&a, &[r], None); + let p = plan_view(&[(&a, &v)], "2026-11-09T10:00:00Z"); + assert_eq!(p.state, PlanState::Stalled); + let p = plan_view(&[(&a, &v)], "2026-11-02T10:00:00Z"); + assert_eq!(p.state, PlanState::Running); + } + + #[test] + fn drift_marks_changes_after_approval_and_work_outside_scope() { + let mut t = task("filed"); + t.created_at = "2026-11-02T00:00:00Z".into(); + t.added_by_kind = "person".into(); + t.edited_at = "2026-11-03T00:00:00Z".into(); + t.edited_by_kind = "person".into(); + t.description = "Change `apps/web/src/login/limit.ts` only.".into(); + let mut r = run("R1", "completed", "2026-11-04T00:00:00Z"); + r.prs = vec![pr(9, "")]; + r.files = vec![ + "apps/web/src/login/limit.ts".into(), + "apps/web/src/login/limit.test.ts".into(), + "apps/web/src/billing/charge.ts".into(), + ]; + r.scope_moved_in = vec![("the audit log".into(), "criterion 2 asks for it".into())]; + let v = task_view(&t, &[r.clone()], None); + let d = task_drift(&t, &v, &[r], "2026-11-01T00:00:00Z"); + let kinds: Vec<&str> = d.iter().map(|d| d.kind.as_str()).collect(); + assert_eq!(kinds, ["added", "changed", "scope", "scope"]); + assert!(d[2].detail.contains("apps/web/src/billing/charge.ts")); + assert!(!d[2].detail.contains("limit.test.ts")); + // Before the plan ran, nothing is drift. + assert!(task_drift(&t, &v, &[], "").is_empty()); + // No paths named: no written scope to leave. + assert!(outside_scope("Make login safer", &["a/b.rs".into()]).is_empty()); + } + + #[test] + fn criteria_come_with_their_evidence() { + use crate::trace::{Proof, Row}; + let mut t = task("filed"); + t.acceptance_criteria = + "- The 11th attempt in 15 minutes gets a 429\n- The page shows when to retry".into(); + let tr = RunTrace { + run_id: "R1".into(), + trace: Trace { + head: "abc".into(), + rows: vec![Row { + criterion: "The 11th attempt in 15 minutes gets a 429".into(), + source: "ticket".into(), + proof: Proof { + state: ProofState::Proven, + by: "tests with and without the change".into(), + detail: String::new(), + }, + ..Default::default() + }], + }, + }; + let c = criteria(&[], &[(&t, Some(&tr))]); + assert_eq!(c.len(), 2); + assert!(c[0].met && c[0].evidence[0].state == "proven"); + assert!(!c[1].met && c[1].evidence.is_empty()); + // A plan's own list: tasks name what they cover. + t.covers = vec!["C2".into()]; + let c = criteria( + &[ + "Logins are limited".into(), + "People see when to retry".into(), + ], + &[(&t, None)], + ); + assert!(c[0].tasks.is_empty()); + assert_eq!(c[1].tasks, ["T1"]); + } + + #[test] + fn the_chip_colour_follows_checks_and_review() { + let mut r = run("R1", "completed", "t"); + r.prs = vec![pr(3, "")]; + r.ci_last = "passed".into(); + assert_eq!(chip(&r, &r.prs[0].clone()).tone, "ready"); + r.review = "changes_requested".into(); + assert_eq!(chip(&r, &r.prs[0].clone()).tone, "failing"); + r.review.clear(); + r.status = "awaiting_ci".into(); + r.ci_last.clear(); + assert_eq!(chip(&r, &r.prs[0].clone()).tone, "waiting"); + } +} diff --git a/services/common/src/plan_sync.rs b/services/common/src/plan_sync.rs new file mode 100644 index 000000000..2231fc5f7 --- /dev/null +++ b/services/common/src/plan_sync.rs @@ -0,0 +1,1207 @@ +//! Keeps a plan's tasks linked to their runs and their derived state +//! written down. +//! +//! Each task's runs are the runs of the ticket it filed: its Jira key, or +//! its GitHub issue (`GH-` in the issue's repository). A refresh +//! ([`refresh`]) reads them, stamps each run that does not say so yet with +//! its plan and task (`plan_id`, `plan_task_id`), writes the ticket's plan +//! link when it is missing (so later runs of the ticket carry the plan from +//! their first write), derives every task's state and the plan's +//! ([`crate::plan_state`]) and writes them on the task and plan rows when +//! they changed. +//! +//! It runs on the events that move a task: a run's status change (the +//! worker), a pull request opened, reviewed, checked, merged or closed (the +//! GitHub webhook), and an approval. The plan page refreshes the plan it +//! shows, and the plans list refreshes plans written before this existed +//! ([`DERIVED_VERSION`]), a bounded number per page: that is the backfill. +//! A refresh is idempotent: it only adds a missing link or stamp and +//! rewrites derived fields. + +use std::collections::HashMap; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::{Deserialize, Serialize}; + +use crate::plan_state::{ + self, Criterion, Drift, PlanState, PlanView, PrFacts, RunFacts, TaskFacts, TaskState, TaskView, +}; + +pub type Item = HashMap; + +/// Bumped when the derived fields change shape: plans written with an older +/// version are refreshed by the list. +pub const DERIVED_VERSION: u64 = 1; +/// Run ids kept on a task row. +const MAX_RUN_IDS: usize = 25; + +fn s(item: &Item, k: &str) -> String { + item.get(k) + .and_then(|v| v.as_s().ok()) + .cloned() + .unwrap_or_default() +} + +fn n_f64(item: &Item, k: &str) -> f64 { + item.get(k) + .and_then(|v| v.as_n().ok().or_else(|| v.as_s().ok())) + .and_then(|n| n.parse::().ok()) + .unwrap_or(0.0) +} + +fn n_u64(item: &Item, k: &str) -> Option { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .map(|f| f as u64) +} + +fn strings(item: &Item, k: &str) -> Vec { + item.get(k) + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) + .unwrap_or_default() +} + +/// A task row as the derivation reads it. +pub fn task_facts(item: &Item) -> TaskFacts { + TaskFacts { + task_id: s(item, "task_id"), + title: s(item, "title"), + description: s(item, "description"), + acceptance_criteria: s(item, "acceptance_criteria"), + status: s(item, "status"), + depends_on: s(item, "depends_on"), + failure_reason: s(item, "failure_reason"), + created_at: s(item, "created_at"), + approved_at: s(item, "approved_at"), + rejected_at: s(item, "rejected_at"), + rejected_by: s(item, "rejected_by"), + edited_at: s(item, "edited_at"), + edited_by_kind: s(item, "edited_by_kind"), + edited_by: s(item, "edited_by"), + added_by_kind: s(item, "added_by_kind"), + covers: strings(item, "covers"), + } +} + +/// A run record as the derivation reads it. +pub fn run_facts(item: &Item) -> RunFacts { + let prs = crate::run_prs::from_item(item) + .into_iter() + .map(|p| PrFacts { + repo: p.repo, + number: p.pr_number, + url: p.url, + outcome: p.outcome, + }) + .collect(); + let ledger = crate::scope_ledger::Ledger::from_json(&s(item, crate::scope_ledger::FIELD)); + RunFacts { + run_id: s(item, "run_id"), + status: s(item, "status"), + created_at: s(item, "created_at"), + updated_at: s(item, "updated_at"), + cost_usd: n_f64(item, "cost_usd"), + current_pass: s(item, "current_pass"), + error: { + let e = s(item, "error_message"); + if e.is_empty() { + s(item, "error") + } else { + e + } + }, + close_reason: s(item, "close_reason"), + waiting_on: crate::run_wait::WaitingOn::of_item(item), + prs, + pr_outcome: s(item, "pr_outcome"), + ci_last: s(item, "ci_last"), + standing: crate::merge_standing::Standing::from_json(&s( + item, + crate::merge_standing::FIELD, + )), + review: s(item, "pr_review"), + additions: n_u64(item, "pr_additions"), + deletions: n_u64(item, "pr_deletions"), + trace: crate::trace::Trace::from_json(&s(item, crate::trace::FIELD)), + files: strings(item, "files_modified"), + scope_moved_in: ledger + .entries + .iter() + .filter(|e| !e.is_out()) + .map(|e| (e.item.clone(), e.moved_in.clone())) + .collect(), + } +} + +/// The ticket a task filed, as runs record it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TaskTicket { + /// The runs' `ticket_id`: the Jira key, or `GH-`. + pub ticket_id: String, + /// For a GitHub issue, the repository its runs are in (lowercase). + pub repo: Option, + /// The settings-table link from the ticket to the task. + pub link_sk: String, +} + +/// The ticket a task row records, if it filed one. +pub fn task_ticket(item: &Item) -> Option { + let key = s(item, "jira_ticket_key"); + let key = key.trim(); + if !key.is_empty() && !key.eq_ignore_ascii_case("UNKNOWN") { + // A task linked to a live run's ticket records `GH-` here. + if let Some(n) = key + .to_ascii_uppercase() + .strip_prefix("GH-") + .and_then(|n| n.parse::().ok()) + { + let repo = s(item, "repo").to_lowercase(); + return Some(TaskTicket { + ticket_id: format!("GH-{n}"), + link_sk: crate::plan_dependents::github_link_sk(&repo, n), + repo: (!repo.is_empty()).then_some(repo), + }); + } + return Some(TaskTicket { + ticket_id: key.to_ascii_uppercase(), + repo: None, + link_sk: crate::plan_dependents::jira_link_sk(key), + }); + } + let url = s(item, "issue_url"); + let path = url.trim().split_once("://")?.1; + let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect(); + if let [_host, owner, repo, "issues", n] = parts.as_slice() { + let n: u64 = n.parse().ok().filter(|n| *n > 0)?; + let repo = format!("{owner}/{repo}").to_lowercase(); + return Some(TaskTicket { + ticket_id: format!("GH-{n}"), + link_sk: crate::plan_dependents::github_link_sk(&repo, n), + repo: Some(repo), + }); + } + None +} + +/// Where the plan rows, the runs and the links are read and written. +#[async_trait::async_trait] +pub trait Store: Send + Sync { + /// The plan row and its task rows; `None` when there is no plan. + async fn plan_rows( + &self, + team: &str, + plan_id: &str, + ) -> Result)>, String>; + /// Every run whose `ticket_id` is this one. + async fn runs_of_ticket(&self, team: &str, ticket_id: &str) -> Result, String>; + /// Sets the derived fields on a task row. + async fn write_task( + &self, + team: &str, + plan_id: &str, + task_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String>; + /// Sets the derived fields on the plan row. + async fn write_plan( + &self, + team: &str, + plan_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String>; + /// Marks a run as the task's, unless it already names a plan. + async fn stamp_run( + &self, + team: &str, + run_id: &str, + plan_id: &str, + task_id: &str, + plan_title: &str, + ) -> Result<(), String>; + /// Writes the ticket's plan link unless one exists. + async fn ensure_link( + &self, + team: &str, + link_sk: &str, + plan_id: &str, + task_id: &str, + plan_title: &str, + ) -> Result<(), String>; +} + +/// A task with everything the plan page shows for it. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct TaskDetail { + pub task_id: String, + #[serde(flatten)] + pub view: TaskView, + /// The criteria ids it covers. + pub covers: Vec, +} + +/// A refreshed plan: its view, its tasks' views and its criteria. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct Refreshed { + pub plan: PlanView, + pub tasks: Vec, + pub criteria: Vec, + /// Runs this refresh stamped with their plan and task. + pub runs_linked: usize, + /// Ticket links it wrote. + pub links_written: usize, +} + +/// Derives the plan's state and its tasks', links the runs, and writes what +/// changed. `None` when the plan does not exist. +pub async fn refresh( + store: &dyn Store, + team: &str, + plan_id: &str, + now: &str, +) -> Result, String> { + let Some((plan, mut tasks)) = store.plan_rows(team, plan_id).await? else { + return Ok(None); + }; + tasks.sort_by_key(|t| n_u64(t, "task_order").unwrap_or(0)); + let plan_title = crate::truncate_str(&s(&plan, "title"), 300).to_string(); + let plan_repo = s(&plan, "repo").to_lowercase(); + let started_at = s(&plan, "executed_at"); + let mut out = Refreshed::default(); + + let facts: Vec = tasks.iter().map(task_facts).collect(); + let titles: HashMap = facts + .iter() + .map(|t| (t.task_id.clone(), t.title.clone())) + .collect(); + let mut all_runs: Vec> = Vec::with_capacity(tasks.len()); + for (item, f) in tasks.iter().zip(&facts) { + let mut runs = Vec::new(); + if let Some(mut ticket) = task_ticket(item) { + if ticket.repo.is_none() && ticket.ticket_id.starts_with("GH-") && !plan_repo.is_empty() + { + ticket.repo = Some(plan_repo.clone()); + } + // Once per task: the worker writes the link for every ticket it + // files, so only tasks from before that need one. + let linked = item + .get("ticket_linked") + .and_then(|v| v.as_bool().ok()) + .copied() + .unwrap_or(false); + if !linked + && store + .ensure_link(team, &ticket.link_sk, plan_id, &f.task_id, &plan_title) + .await + .is_ok() + { + out.links_written += 1; + } + for r in store.runs_of_ticket(team, &ticket.ticket_id).await? { + if let Some(repo) = &ticket.repo { + if !s(&r, "repo").eq_ignore_ascii_case(repo) { + continue; + } + } + let named = s(&r, "plan_id"); + if !named.is_empty() && named != plan_id { + // Another plan's run of the same ticket. + continue; + } + if named.is_empty() || s(&r, "plan_task_id").is_empty() { + let run_id = s(&r, "run_id"); + if !run_id.is_empty() + && store + .stamp_run(team, &run_id, plan_id, &f.task_id, &plan_title) + .await + .is_ok() + { + out.runs_linked += 1; + } + } + runs.push(run_facts(&r)); + } + } + all_runs.push(runs); + } + + let mut views: Vec = Vec::with_capacity(tasks.len()); + for (f, runs) in facts.iter().zip(&all_runs) { + let waits = (!f.depends_on.is_empty()) + .then(|| titles.get(&f.depends_on).map(String::as_str)) + .flatten(); + let mut v = plan_state::task_view(f, runs, waits); + v.drift = plan_state::task_drift(f, &v, runs, &started_at); + views.push(v); + } + let pairs: Vec<(&TaskFacts, &TaskView)> = facts.iter().zip(views.iter()).collect(); + out.plan = plan_state::plan_view(&pairs, now); + + let traces: Vec> = all_runs + .iter() + .map(|r| plan_state::newest_trace(r)) + .collect(); + let with_traces: Vec<(&TaskFacts, Option<&plan_state::RunTrace>)> = facts + .iter() + .zip(traces.iter().map(Option::as_ref)) + .collect(); + let plan_criteria = strings(&plan, "criteria"); + out.criteria = plan_state::criteria(&plan_criteria, &with_traces); + + // Write what changed. + for ((item, f), v) in tasks.iter().zip(&facts).zip(&views) { + let mut fields = task_fields(v, now); + if task_ticket(item).is_some() { + fields.push(("ticket_linked".to_string(), AttributeValue::Bool(true))); + } + if fingerprint(&fields) != s(item, "derived_fp") { + let fp = fingerprint(&fields); + fields.push(("derived_fp".into(), AttributeValue::S(fp))); + store.write_task(team, plan_id, &f.task_id, fields).await?; + } + out.tasks.push(TaskDetail { + task_id: f.task_id.clone(), + view: v.clone(), + covers: covers_of(&f.task_id, &out.criteria), + }); + } + let fields = plan_fields(&out.plan, &out.criteria); + if fingerprint(&fields) != s(&plan, "derived_fp") + || n_u64(&plan, "derived_v") != Some(DERIVED_VERSION) + { + let mut fields = fields; + let fp = fingerprint(&fields); + fields.push(("derived_fp".into(), AttributeValue::S(fp))); + fields.push(("derived_at".into(), AttributeValue::S(now.to_string()))); + fields.push(( + "derived_v".into(), + AttributeValue::N(DERIVED_VERSION.to_string()), + )); + store.write_plan(team, plan_id, fields).await?; + } + Ok(Some(out)) +} + +fn covers_of(task_id: &str, criteria: &[Criterion]) -> Vec { + criteria + .iter() + .filter(|c| c.tasks.iter().any(|t| t == task_id)) + .map(|c| c.id.clone()) + .collect() +} + +fn json(v: &T) -> AttributeValue { + AttributeValue::S(serde_json::to_string(v).unwrap_or_default()) +} + +/// The derived fields of a task row. +fn task_fields(v: &TaskView, _now: &str) -> Vec<(String, AttributeValue)> { + let ids: Vec = v + .runs + .iter() + .rev() + .take(MAX_RUN_IDS) + .map(|r| AttributeValue::S(r.run_id.clone())) + .collect(); + let mut f = vec![ + ( + "state".to_string(), + AttributeValue::S(v.state.code().into()), + ), + ( + "state_detail".to_string(), + AttributeValue::S(v.detail.clone()), + ), + ( + "state_reason".to_string(), + AttributeValue::S(v.reason.clone()), + ), + ( + "attempts".to_string(), + AttributeValue::N(v.attempts.to_string()), + ), + ( + "cost_usd".to_string(), + AttributeValue::N(format!("{:.4}", v.cost_usd)), + ), + ("prs".to_string(), json(&v.prs)), + ( + "ticket_filed".to_string(), + AttributeValue::Bool(v.ticket_filed), + ), + ]; + if !ids.is_empty() { + f.push(("run_ids".to_string(), AttributeValue::L(ids))); + // The newest attempt and its pull request, for older readers. + if let Some(last) = v.runs.last() { + f.push(("run_id".to_string(), AttributeValue::S(last.run_id.clone()))); + } + } + if let Some(pr) = v.prs.first() { + f.push(("pr_url".to_string(), AttributeValue::S(pr.url.clone()))); + } + f +} + +/// The derived fields of a plan row: what the list shows without reading +/// the tasks. +fn plan_fields(p: &PlanView, criteria: &[Criterion]) -> Vec<(String, AttributeValue)> { + vec![ + ( + "state".to_string(), + AttributeValue::S(p.state.code().into()), + ), + // The older word, so a client that reads `status` is not told Done + // before the work merged. + ( + "status".to_string(), + AttributeValue::S(p.state.legacy_status().into()), + ), + ("summary".to_string(), AttributeValue::S(p.summary.clone())), + ("counts".to_string(), json(&p.counts)), + ( + "needs_count".to_string(), + AttributeValue::N(p.needs.len().to_string()), + ), + ( + "cost_usd".to_string(), + AttributeValue::N(format!("{:.4}", p.cost_usd)), + ), + ( + "attempts".to_string(), + AttributeValue::N(p.attempts.to_string()), + ), + ( + "last_activity_at".to_string(), + AttributeValue::S(p.last_activity.clone()), + ), + ( + "criteria_met".to_string(), + AttributeValue::N(criteria.iter().filter(|c| c.met).count().to_string()), + ), + ( + "criteria_count".to_string(), + AttributeValue::N(criteria.len().to_string()), + ), + ] +} + +fn fingerprint(fields: &[(String, AttributeValue)]) -> String { + use sha2::{Digest, Sha256}; + let mut h = Sha256::new(); + for (k, v) in fields { + h.update(k.as_bytes()); + h.update(format!("{v:?}").as_bytes()); + } + hex::encode(&h.finalize()[..12]) +} + +/// The list's numbers for a plan row, from its derived fields. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Stored { + pub state: Option, + pub summary: String, + pub counts: plan_state::Counts, + pub needs_count: u64, + pub cost_usd: f64, + pub attempts: u64, + pub last_activity_at: String, + pub criteria_met: u64, + pub criteria_count: u64, + /// The derived fields are current ([`DERIVED_VERSION`]). + pub current: bool, +} + +/// The derived fields a plan row holds. +pub fn stored(item: &Item) -> Stored { + Stored { + state: PlanState::from_code(&s(item, "state")), + summary: s(item, "summary"), + counts: serde_json::from_str(&s(item, "counts")).unwrap_or_default(), + needs_count: n_u64(item, "needs_count").unwrap_or(0), + cost_usd: n_f64(item, "cost_usd"), + attempts: n_u64(item, "attempts").unwrap_or(0), + last_activity_at: s(item, "last_activity_at"), + criteria_met: n_u64(item, "criteria_met").unwrap_or(0), + criteria_count: n_u64(item, "criteria_count").unwrap_or(0), + current: n_u64(item, "derived_v") == Some(DERIVED_VERSION), + } +} + +/// Whether the list should refresh a plan row before showing it: written +/// before the derived fields existed, or open work last derived more than +/// `stale_minutes` ago (a missed event never leaves it wrong for long). +pub fn needs_refresh(item: &Item, now: &str, stale_minutes: i64) -> bool { + let st = stored(item); + if !st.current { + return true; + } + let open = !matches!(st.state, Some(PlanState::Done) | Some(PlanState::Drafting)); + if !open { + return false; + } + let (Ok(at), Ok(now)) = ( + chrono::DateTime::parse_from_rfc3339(&s(item, "derived_at")), + chrono::DateTime::parse_from_rfc3339(now), + ) else { + return true; + }; + (now - at).num_minutes() >= stale_minutes +} + +/// The plan and task a run record names, when it is a plan's. +pub fn plan_of_run(item: &Item) -> Option<(String, String)> { + let plan = s(item, "plan_id"); + (!plan.is_empty()).then(|| (plan, s(item, "plan_task_id"))) +} + +/// What starting tasks is expected to take, from the team's recent runs. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Estimate { + /// Tasks it would start. + pub tasks: usize, + /// Runs expected: one per task, up to the attempts a ticket took lately. + pub runs_low: usize, + pub runs_high: usize, + pub cost_low: f64, + pub cost_high: f64, + /// One run's typical cost (a Retry or Force run). + pub per_run_low: f64, + pub per_run_high: f64, + /// Finished runs the numbers come from; 0 means no history yet. + pub sample: usize, +} + +/// The estimate for `tasks` tasks from recent finished runs: `(ticket_id, +/// cost)`. Per run: the middle half of the costs (25th to 75th +/// percentile); runs: one per task up to the average attempts per ticket. +pub fn estimate(tasks: usize, recent: &[(String, f64)]) -> Estimate { + let mut costs: Vec = recent + .iter() + .map(|(_, c)| *c) + .filter(|c| *c > 0.0) + .collect(); + costs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + let mut e = Estimate { + tasks, + runs_low: tasks, + runs_high: tasks, + sample: costs.len(), + ..Default::default() + }; + if costs.is_empty() { + return e; + } + let at = |q: f64| costs[((costs.len() - 1) as f64 * q).round() as usize]; + e.per_run_low = at(0.25); + e.per_run_high = at(0.75); + let tickets: std::collections::HashSet<&str> = recent.iter().map(|(t, _)| t.as_str()).collect(); + let per_ticket = if tickets.is_empty() { + 1.0 + } else { + (recent.len() as f64 / tickets.len() as f64).max(1.0) + }; + e.runs_high = ((tasks as f64) * per_ticket).ceil() as usize; + e.cost_low = e.per_run_low * tasks as f64; + e.cost_high = e.per_run_high * e.runs_high as f64; + e +} + +/// The tables in DynamoDB. +pub struct Dynamo { + pub dynamo: aws_sdk_dynamodb::Client, + pub plans_table: String, + pub runs_table: String, + pub settings_table: String, +} + +fn err( + e: aws_sdk_dynamodb::error::SdkError, +) -> String { + aws_sdk_dynamodb::error::DisplayErrorContext(&e).to_string() +} + +#[async_trait::async_trait] +impl Store for Dynamo { + async fn plan_rows( + &self, + team: &str, + plan_id: &str, + ) -> Result)>, String> { + let prefix = format!("PLAN#{plan_id}"); + let (items, _) = crate::paged::all_pages( + |start| { + let q = self + .dynamo + .query() + .table_name(&self.plans_table) + .key_condition_expression("pk = :pk AND begins_with(sk, :p)") + .expression_attribute_values(":pk", AttributeValue::S(team.to_string())) + .expression_attribute_values(":p", AttributeValue::S(prefix.clone())) + .set_exclusive_start_key(start); + async move { + let out = q.send().await.map_err(err)?; + Ok::<_, String>((out.items.unwrap_or_default(), out.last_evaluated_key)) + } + }, + 20, + ) + .await?; + let mut plan = None; + let mut tasks = Vec::new(); + for item in items { + let sk = s(&item, "sk"); + if sk == prefix { + plan = Some(item); + } else if sk.starts_with(&format!("{prefix}#TASK#")) { + tasks.push(item); + } + } + Ok(plan.map(|p| (p, tasks))) + } + + async fn runs_of_ticket(&self, team: &str, ticket_id: &str) -> Result, String> { + let (items, _) = crate::paged::all_pages( + |start| { + let q = self + .dynamo + .query() + .table_name(&self.runs_table) + .index_name("ticket-index") + .key_condition_expression("team_id = :t AND ticket_id = :k") + .expression_attribute_values(":t", AttributeValue::S(team.to_string())) + .expression_attribute_values(":k", AttributeValue::S(ticket_id.to_string())) + .set_exclusive_start_key(start); + async move { + let out = q.send().await.map_err(err)?; + Ok::<_, String>((out.items.unwrap_or_default(), out.last_evaluated_key)) + } + }, + 10, + ) + .await?; + // The index may project only some attributes: read each run whole. + let mut out = Vec::with_capacity(items.len()); + for i in items { + let run_id = s(&i, "run_id"); + if run_id.is_empty() { + continue; + } + let full = self + .dynamo + .get_item() + .table_name(&self.runs_table) + .key("team_id", AttributeValue::S(team.to_string())) + .key("run_id", AttributeValue::S(run_id)) + .send() + .await + .map_err(err)? + .item; + out.push(full.unwrap_or(i)); + } + Ok(out) + } + + async fn write_task( + &self, + team: &str, + plan_id: &str, + task_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String> { + self.set(&format!("PLAN#{plan_id}#TASK#{task_id}"), team, fields) + .await + } + + async fn write_plan( + &self, + team: &str, + plan_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String> { + self.set(&format!("PLAN#{plan_id}"), team, fields).await + } + + async fn stamp_run( + &self, + team: &str, + run_id: &str, + plan_id: &str, + task_id: &str, + plan_title: &str, + ) -> Result<(), String> { + let mut u = self + .dynamo + .update_item() + .table_name(&self.runs_table) + .key("team_id", AttributeValue::S(team.to_string())) + .key("run_id", AttributeValue::S(run_id.to_string())) + .condition_expression( + "attribute_exists(run_id) AND (attribute_not_exists(plan_id) OR plan_id = :p)", + ) + .expression_attribute_values(":p", AttributeValue::S(plan_id.to_string())) + .expression_attribute_values(":t", AttributeValue::S(task_id.to_string())); + let mut set = vec!["plan_id = :p", "plan_task_id = :t"]; + if !plan_title.is_empty() { + set.push("plan_title = if_not_exists(plan_title, :pt)"); + u = u.expression_attribute_values(":pt", AttributeValue::S(plan_title.to_string())); + } + u.update_expression(format!("SET {}", set.join(", "))) + .send() + .await + .map(|_| ()) + .map_err(err) + } + + async fn ensure_link( + &self, + team: &str, + link_sk: &str, + plan_id: &str, + task_id: &str, + plan_title: &str, + ) -> Result<(), String> { + let mut put = self + .dynamo + .put_item() + .table_name(&self.settings_table) + .item("pk", AttributeValue::S(team.to_string())) + .item("sk", AttributeValue::S(link_sk.to_string())) + .item("plan_id", AttributeValue::S(plan_id.to_string())) + .item("task_id", AttributeValue::S(task_id.to_string())) + .condition_expression("attribute_not_exists(sk)"); + if !plan_title.is_empty() { + put = put.item("plan_title", AttributeValue::S(plan_title.to_string())); + } + put.send().await.map(|_| ()).map_err(err) + } +} + +impl Dynamo { + async fn set( + &self, + sk: &str, + team: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String> { + if fields.is_empty() { + return Ok(()); + } + let mut u = self + .dynamo + .update_item() + .table_name(&self.plans_table) + .key("pk", AttributeValue::S(team.to_string())) + .key("sk", AttributeValue::S(sk.to_string())) + .condition_expression("attribute_exists(sk)"); + let mut parts = Vec::new(); + for (i, (k, v)) in fields.into_iter().enumerate() { + parts.push(format!("#f{i} = :v{i}")); + u = u + .expression_attribute_names(format!("#f{i}"), k) + .expression_attribute_values(format!(":v{i}"), v); + } + u.update_expression(format!("SET {}", parts.join(", "))) + .send() + .await + .map(|_| ()) + .map_err(err) + } +} + +/// The recent finished runs of a team, `(ticket_id, cost)`, newest first. +pub async fn recent_costs( + dynamo: &aws_sdk_dynamodb::Client, + runs_table: &str, + team: &str, +) -> Vec<(String, f64)> { + let out = dynamo + .query() + .table_name(runs_table) + .key_condition_expression("team_id = :t") + .expression_attribute_values(":t", AttributeValue::S(team.to_string())) + .projection_expression("ticket_id, cost_usd, #s") + .expression_attribute_names("#s", "status") + .scan_index_forward(false) + .limit(200) + .send() + .await; + let Ok(out) = out else { return Vec::new() }; + out.items() + .iter() + .filter(|i| { + matches!( + s(i, "status").as_str(), + "completed" | "success" | "merged" | "failed" | "closed" | "retried" + ) + }) + .map(|i| (s(i, "ticket_id"), n_f64(i, "cost_usd"))) + .collect() +} + +/// Plan rows and runs in memory (tests and the incident cases). +#[derive(Default)] +pub struct Memory { + pub plans: std::sync::Mutex>, + pub runs: std::sync::Mutex>, + pub links: std::sync::Mutex>, +} + +fn lock(m: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Memory { + pub fn put_row(&self, team: &str, item: Item) { + let sk = s(&item, "sk"); + lock(&self.plans).insert((team.to_string(), sk), item); + } + + pub fn put_run(&self, team: &str, item: Item) { + let id = s(&item, "run_id"); + let mut runs = lock(&self.runs); + runs.retain(|(t, r)| !(t == team && s(r, "run_id") == id)); + runs.push((team.to_string(), item)); + } + + pub fn run(&self, team: &str, run_id: &str) -> Option { + lock(&self.runs) + .iter() + .find(|(t, r)| t == team && s(r, "run_id") == run_id) + .map(|(_, r)| r.clone()) + } + + pub fn row(&self, team: &str, sk: &str) -> Option { + lock(&self.plans) + .get(&(team.to_string(), sk.to_string())) + .cloned() + } + + pub fn link(&self, team: &str, link_sk: &str) -> Option<(String, String)> { + lock(&self.links) + .get(&(team.to_string(), link_sk.to_string())) + .cloned() + } +} + +#[async_trait::async_trait] +impl Store for Memory { + async fn plan_rows( + &self, + team: &str, + plan_id: &str, + ) -> Result)>, String> { + let rows = lock(&self.plans); + let prefix = format!("PLAN#{plan_id}"); + let plan = rows.get(&(team.to_string(), prefix.clone())).cloned(); + let tasks = rows + .iter() + .filter(|((t, sk), _)| t == team && sk.starts_with(&format!("{prefix}#TASK#"))) + .map(|(_, v)| v.clone()) + .collect(); + Ok(plan.map(|p| (p, tasks))) + } + + async fn runs_of_ticket(&self, team: &str, ticket_id: &str) -> Result, String> { + Ok(lock(&self.runs) + .iter() + .filter(|(t, r)| t == team && s(r, "ticket_id").eq_ignore_ascii_case(ticket_id)) + .map(|(_, r)| r.clone()) + .collect()) + } + + async fn write_task( + &self, + team: &str, + plan_id: &str, + task_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String> { + let mut rows = lock(&self.plans); + let row = rows + .get_mut(&(team.to_string(), format!("PLAN#{plan_id}#TASK#{task_id}"))) + .ok_or("no task")?; + row.extend(fields); + Ok(()) + } + + async fn write_plan( + &self, + team: &str, + plan_id: &str, + fields: Vec<(String, AttributeValue)>, + ) -> Result<(), String> { + let mut rows = lock(&self.plans); + let row = rows + .get_mut(&(team.to_string(), format!("PLAN#{plan_id}"))) + .ok_or("no plan")?; + row.extend(fields); + Ok(()) + } + + async fn stamp_run( + &self, + team: &str, + run_id: &str, + plan_id: &str, + task_id: &str, + plan_title: &str, + ) -> Result<(), String> { + let mut runs = lock(&self.runs); + let (_, r) = runs + .iter_mut() + .find(|(t, r)| t == team && s(r, "run_id") == run_id) + .ok_or("no run")?; + let named = s(r, "plan_id"); + if !named.is_empty() && named != plan_id { + return Err("another plan's run".into()); + } + r.insert("plan_id".into(), AttributeValue::S(plan_id.into())); + r.insert("plan_task_id".into(), AttributeValue::S(task_id.into())); + if !plan_title.is_empty() { + r.entry("plan_title".into()) + .or_insert_with(|| AttributeValue::S(plan_title.into())); + } + Ok(()) + } + + async fn ensure_link( + &self, + team: &str, + link_sk: &str, + plan_id: &str, + task_id: &str, + _plan_title: &str, + ) -> Result<(), String> { + let mut links = lock(&self.links); + let key = (team.to_string(), link_sk.to_string()); + if links.contains_key(&key) { + return Err("exists".into()); + } + links.insert(key, (plan_id.to_string(), task_id.to_string())); + Ok(()) + } +} + +/// A task's state as stored, for readers that do not refresh. +pub fn stored_task_state(item: &Item) -> Option { + TaskState::from_code(&s(item, "state")) +} + +/// A task's drift marks as derived, for tests and readers. +pub fn drift_of(detail: &TaskDetail) -> &[Drift] { + &detail.view.drift +} + +#[cfg(test)] +mod tests { + use super::*; + + const TEAM: &str = "TEAM#1"; + + fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| { + let v = match *k { + "task_order" | "cost_usd" | "issue_number" => AttributeValue::N(v.to_string()), + _ => AttributeValue::S(v.to_string()), + }; + (k.to_string(), v) + }) + .collect() + } + + fn store() -> Memory { + let m = Memory::default(); + m.put_row( + TEAM, + item(&[ + ("sk", "PLAN#P1"), + ("plan_id", "P1"), + ("title", "Rate-limit the login form"), + ("repo", "example-org/web"), + ("status", "done"), + ("executed_at", "2026-11-01T00:00:00Z"), + ]), + ); + // Filed and marked done the moment its ticket was filed, the old way. + m.put_row( + TEAM, + item(&[ + ("sk", "PLAN#P1#TASK#T1"), + ("task_id", "T1"), + ("title", "Limit attempts"), + ("status", "done"), + ("task_order", "0"), + ("jira_ticket_key", "ENG-1"), + ]), + ); + m.put_row( + TEAM, + item(&[ + ("sk", "PLAN#P1#TASK#T2"), + ("task_id", "T2"), + ("title", "Show when to retry"), + ("status", "done"), + ("task_order", "1"), + ("issue_url", "https://github.com/example-org/web/issues/7"), + ("issue_number", "7"), + ]), + ); + m + } + + #[tokio::test] + async fn backfill_links_the_runs_and_recomputes_the_states() { + let m = store(); + m.put_run( + TEAM, + item(&[ + ("run_id", "R1"), + ("ticket_id", "ENG-1"), + ("repo", "example-org/web"), + ("status", "completed"), + ("created_at", "2026-11-01T01:00:00Z"), + ("pr_url", "https://github.com/example-org/web/pull/31"), + ("cost_usd", "3.5"), + ]), + ); + // The same issue number in another repository is not this task's. + m.put_run( + TEAM, + item(&[ + ("run_id", "RX"), + ("ticket_id", "GH-7"), + ("repo", "example-org/other"), + ("status", "merged"), + ("created_at", "2026-11-01T01:00:00Z"), + ]), + ); + let out = refresh(&m, TEAM, "P1", "2026-11-02T00:00:00Z") + .await + .unwrap() + .unwrap(); + assert_eq!(out.runs_linked, 1); + assert_eq!(out.links_written, 2); + assert_eq!(out.tasks[0].view.state, TaskState::InReview); + assert_eq!(out.tasks[1].view.state, TaskState::Queued); + assert_eq!( + out.plan.state, + PlanState::Running, + "never Done with nothing merged" + ); + let run = m.run(TEAM, "R1").unwrap(); + assert_eq!(s(&run, "plan_id"), "P1"); + assert_eq!(s(&run, "plan_task_id"), "T1"); + assert!(s(&m.run(TEAM, "RX").unwrap(), "plan_id").is_empty()); + let plan = m.row(TEAM, "PLAN#P1").unwrap(); + assert_eq!(s(&plan, "state"), "running"); + assert_eq!(s(&plan, "status"), "executing"); + let st = stored(&plan); + assert!(st.current && st.counts.in_review == 1 && st.counts.queued == 1); + assert!((st.cost_usd - 3.5).abs() < 1e-9); + assert_eq!( + s(&m.row(TEAM, "PLAN#P1#TASK#T1").unwrap(), "state"), + "in_review" + ); + assert_eq!( + m.link(TEAM, &crate::plan_dependents::jira_link_sk("ENG-1")), + Some(("P1".into(), "T1".into())) + ); + + // Idempotent: a second refresh links nothing new and changes nothing. + let again = refresh(&m, TEAM, "P1", "2026-11-02T00:00:00Z") + .await + .unwrap() + .unwrap(); + assert_eq!((again.runs_linked, again.links_written), (0, 0)); + assert_eq!( + s(&m.row(TEAM, "PLAN#P1").unwrap(), "derived_fp"), + s(&plan, "derived_fp") + ); + + // The PR merges and the other task's run appears: the plan moves. + let mut r1 = m.run(TEAM, "R1").unwrap(); + r1.insert("pr_outcome".into(), AttributeValue::S("merged".into())); + r1.insert("status".into(), AttributeValue::S("merged".into())); + m.put_run(TEAM, r1); + m.put_run( + TEAM, + item(&[ + ("run_id", "R2"), + ("ticket_id", "GH-7"), + ("repo", "example-org/web"), + ("status", "failed"), + ("error_message", "The tests time out"), + ("created_at", "2026-11-01T02:00:00Z"), + ]), + ); + let out = refresh(&m, TEAM, "P1", "2026-11-02T00:00:00Z") + .await + .unwrap() + .unwrap(); + assert_eq!(out.tasks[0].view.state, TaskState::Merged); + assert_eq!(out.tasks[1].view.state, TaskState::Failed); + assert_eq!(out.tasks[1].view.reason, "The tests time out"); + assert_eq!(out.plan.state, PlanState::NeedsYou); + assert_eq!(out.plan.needs.len(), 1); + assert_eq!(stored(&m.row(TEAM, "PLAN#P1").unwrap()).needs_count, 1); + } + + #[test] + fn the_list_refreshes_rows_written_before_and_stale_open_ones() { + let old = item(&[("sk", "PLAN#P1"), ("status", "done")]); + assert!(needs_refresh(&old, "2026-11-02T00:00:00Z", 10)); + let mut cur = old.clone(); + cur.insert( + "derived_v".into(), + AttributeValue::N(DERIVED_VERSION.to_string()), + ); + cur.insert("state".into(), AttributeValue::S("done".into())); + cur.insert( + "derived_at".into(), + AttributeValue::S("2026-11-01T00:00:00Z".into()), + ); + assert!(!needs_refresh(&cur, "2026-11-02T00:00:00Z", 10)); + cur.insert("state".into(), AttributeValue::S("running".into())); + assert!(needs_refresh(&cur, "2026-11-02T00:00:00Z", 10)); + assert!(!needs_refresh(&cur, "2026-11-01T00:05:00Z", 10)); + } + + #[test] + fn the_estimate_reads_recent_costs_and_attempts() { + let none = estimate(3, &[]); + assert_eq!((none.runs_low, none.sample), (3, 0)); + let recent: Vec<(String, f64)> = vec![ + ("A".into(), 2.0), + ("A".into(), 4.0), + ("B".into(), 6.0), + ("C".into(), 8.0), + ]; + let e = estimate(2, &recent); + assert_eq!(e.runs_low, 2); + assert_eq!(e.runs_high, 3, "4 runs over 3 tickets"); + assert!(e.per_run_low > 0.0 && e.per_run_high >= e.per_run_low); + assert!(e.cost_high >= e.cost_low); + } + + #[test] + fn a_task_names_its_ticket_by_key_or_by_issue() { + let t = task_ticket(&item(&[("jira_ticket_key", "eng-4")])).unwrap(); + assert_eq!(t.ticket_id, "ENG-4"); + let t = task_ticket(&item(&[( + "issue_url", + "https://github.com/Example-Org/Web/issues/12", + )])) + .unwrap(); + assert_eq!( + (t.ticket_id.as_str(), t.repo.as_deref()), + ("GH-12", Some("example-org/web")) + ); + assert!(task_ticket(&item(&[("jira_ticket_key", "UNKNOWN")])).is_none()); + let t = task_ticket(&item(&[("jira_ticket_key", "GH-3"), ("repo", "o/r")])).unwrap(); + assert_eq!(t.repo.as_deref(), Some("o/r")); + } +} diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index fa0c69f9f..a2576ed3d 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -471,6 +471,33 @@ async fn dispatch( // dismissal, a close over its change request) queues one judgment per PR. super::review_lessons::on_webhook(state, event_type, payload, installation_id, team_id).await; + let r = route_event( + state, + event_type, + payload, + installation_id, + team_id, + delivery_id, + ) + .await; + // A plan task's pull request moved: its plan's state follows. + if matches!( + event_type, + "pull_request" | "pull_request_review" | "check_suite" + ) { + super::plans::on_pr_event(state, team_id, event_type, payload).await; + } + r +} + +async fn route_event( + state: &AppState, + event_type: &str, + payload: &Value, + installation_id: u64, + team_id: &str, + delivery_id: &str, +) -> Result { match event_type { "issues" => handle_issue_event(state, payload, installation_id, team_id).await, "issue_comment" => handle_issue_comment(state, payload, installation_id, team_id).await, @@ -4886,7 +4913,7 @@ async fn lookup_run_by_pr( /// repo-index GSI), else one of a multi-repo run's PRs, matched by /// repository AND number (`pr_keys`). A number alone matched a PR of the /// same number in an unrelated repository. -async fn lookup_run_item_by_pr( +pub(super) async fn lookup_run_item_by_pr( state: &AppState, team_id: &str, owner: &str, diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index 4ac5fc438..ecb2d5507 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -85,6 +85,12 @@ pub async fn list_plans( }); let mut plans: Vec = Vec::new(); let mut next_cursor: Option = None; + // Rows written before the derived state existed, or open work last + // derived a while ago, are derived again here: this is the backfill, a + // few plans per page so the list stays fast. + let now = chrono::Utc::now().to_rfc3339(); + let store = plan_store(&state); + let mut refreshed = 0usize; 'pages: loop { let result = state .dynamo @@ -116,7 +122,21 @@ pub async fn list_plans( break 'pages; } next_cursor = Some(sk.to_string()); - plans.push(plan_of(item)); + let mut plan = plan_of(item); + if refreshed < LIST_REFRESHES + && common::plan_sync::needs_refresh(item, &now, LIST_STALE_MINUTES) + { + refreshed += 1; + let id = plan.plan_id.clone().unwrap_or_default(); + match common::plan_sync::refresh(&store, &claims.team_id, &id, &now).await { + Ok(Some(r)) => apply_view(&mut plan, &r), + Ok(None) => {} + Err(e) => { + warn!(plan_id = %id, error = %e, "Could not refresh the plan's state") + } + } + } + plans.push(plan); } match result.last_evaluated_key() { Some(key) => start = Some(key.clone()), @@ -135,6 +155,152 @@ pub async fn list_plans( })) } +/// Plans the list derives again per page, at most. +const LIST_REFRESHES: usize = 8; +/// An open plan last derived this long ago is derived again by the list. +const LIST_STALE_MINUTES: i64 = 10; + +/// Where plan state is read and written (`common::plan_sync`). +pub(crate) fn plan_store(state: &AppState) -> common::plan_sync::Dynamo { + common::plan_sync::Dynamo { + dynamo: state.dynamo.clone(), + plans_table: state.config.plans_table_name.clone(), + runs_table: state.config.runs_table_name.clone(), + settings_table: state.config.settings_table_name.clone(), + } +} + +/// Derives a plan's state again and writes it. Best effort. +pub(crate) async fn refresh_plan( + state: &AppState, + team_id: &str, + plan_id: &str, +) -> Option { + let now = chrono::Utc::now().to_rfc3339(); + match common::plan_sync::refresh(&plan_store(state), team_id, plan_id, &now).await { + Ok(r) => r, + Err(e) => { + warn!(plan_id, error = %e, "Could not refresh the plan's state"); + None + } + } +} + +/// A plan's numbers from a fresh derivation. +fn apply_view(plan: &mut Plan, r: &common::plan_sync::Refreshed) { + let v = &r.plan; + plan.state = Some(v.state.code().to_string()); + plan.status = Some(v.state.legacy_status().to_string()); + plan.summary = Some(v.summary.clone()); + plan.counts = Some(v.counts.clone()); + plan.needs_count = v.needs.len() as u64; + plan.cost_usd = Some(round_cents(v.cost_usd)); + plan.attempts = Some(v.attempts as u64); + plan.criteria_met = Some(r.criteria.iter().filter(|c| c.met).count() as u64); + plan.criteria_count = Some(r.criteria.len() as u64); + plan.last_activity_at = Some(v.last_activity.clone()).filter(|s| !s.is_empty()); +} + +fn round_cents(v: f64) -> f64 { + (v * 100.0).round() / 100.0 +} + +/// A GitHub pull request event moved a plan task's work: refresh its plan. +/// Pull requests opened, reviewed, checked, merged and closed all land +/// here (`github_webhook::dispatch`). Only runs that belong to a plan cost +/// more than the one lookup. +pub(crate) async fn on_pr_event( + state: &AppState, + team_id: &str, + event_type: &str, + payload: &Value, +) { + let repo = payload["repository"]["full_name"].as_str().unwrap_or(""); + let Some((owner, name)) = repo.split_once('/') else { + return; + }; + let numbers: Vec = match event_type { + "pull_request" | "pull_request_review" => payload["pull_request"]["number"] + .as_u64() + .into_iter() + .collect(), + "check_suite" if payload["action"].as_str() == Some("completed") => payload["check_suite"] + ["pull_requests"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|p| p["number"].as_u64()) + .take(5) + .collect() + }) + .unwrap_or_default(), + _ => Vec::new(), + }; + for number in numbers { + let Some(run) = + super::github_webhook::lookup_run_item_by_pr(state, team_id, owner, name, number).await + else { + continue; + }; + let Some((plan_id, _)) = common::plan_sync::plan_of_run(&run) else { + continue; + }; + let run_id = common::paged::run_id_of(&run).unwrap_or_default(); + let facts = pr_event_facts(event_type, payload); + if !run_id.is_empty() && !facts.is_empty() { + let mut u = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(&run_id)) + .condition_expression("attribute_exists(run_id)"); + let mut parts = Vec::new(); + for (i, (k, v)) in facts.into_iter().enumerate() { + parts.push(format!("{k} = :f{i}")); + u = u.expression_attribute_values(format!(":f{i}"), v); + } + if let Err(e) = u + .update_expression(format!("SET {}", parts.join(", "))) + .send() + .await + { + warn!(run_id, error = %e, "Could not record the pull request's facts on the run"); + } + } + refresh_plan(state, team_id, &plan_id).await; + } +} + +/// What a pull request event tells about the pull request, as run fields: +/// its size, and a person's review verdict. +pub(crate) fn pr_event_facts( + event_type: &str, + payload: &Value, +) -> Vec<(&'static str, aws_sdk_dynamodb::types::AttributeValue)> { + let mut out = Vec::new(); + let pr = &payload["pull_request"]; + if let (Some(a), Some(d)) = (pr["additions"].as_u64(), pr["deletions"].as_u64()) { + out.push(("pr_additions", attr_n(a))); + out.push(("pr_deletions", attr_n(d))); + } + if event_type == "pull_request_review" && payload["action"].as_str() == Some("submitted") { + let by_bot = payload["review"]["user"]["type"].as_str() == Some("Bot") + || payload["review"]["user"]["login"] + .as_str() + .is_some_and(|l| l.ends_with("[bot]") || l.contains("coderhelm")); + let verdict = match payload["review"]["state"].as_str().unwrap_or("") { + s if s.eq_ignore_ascii_case("approved") => Some("approved"), + s if s.eq_ignore_ascii_case("changes_requested") => Some("changes_requested"), + _ => None, + }; + if let (false, Some(v)) = (by_bot, verdict) { + out.push(("pr_review", attr_s(v))); + } + } + out +} + /// A plan's own row, as opposed to one of its task rows. fn is_plan_row(sk: &str) -> bool { sk.starts_with("PLAN#") && !sk.contains("#TASK#") @@ -174,6 +340,12 @@ pub struct CreatePlan { #[serde(default)] #[schema(example = json!([{"title": "Limit login attempts per IP", "description": "Allow 10 attempts per IP per 15 minutes; answer 429 after that.", "acceptance_criteria": "The 11th attempt within 15 minutes gets 429 and a Retry-After header."}]))] pub tasks: Option>, + /// What done means for the whole plan: short checkable lines. Each task + /// names the ones it covers (`covers`); without a list, each task's + /// acceptance criteria are the plan's. + #[serde(default)] + #[schema(example = json!(["The 11th login attempt within 15 minutes gets 429", "The page says when to try again"]))] + pub success_criteria: Option>, /// The plan chat it came from (dashboard only). #[serde(default)] #[schema(ignore)] @@ -218,6 +390,11 @@ pub struct NewPlanTask { #[serde(default)] #[schema(example = "WEB")] pub jira_project: Option, + /// The plan's success criteria this task covers, by id (`C1` is the + /// first of `success_criteria`). + #[serde(default)] + #[schema(example = json!(["C1"]))] + pub covers: Option>, } /// The plan that was made. @@ -291,6 +468,16 @@ pub async fn create_plan( if chat_id != "unsaved" { put = put.item("chat_id", attr_s(&chat_id)); } + // Tasks a plan chat wrote are CoderHelm's; tasks sent another way are + // the sender's (the drift marks say who wrote what). + let author = if chat_id != "unsaved" { + "agent" + } else { + "person" + }; + if let Some(list) = criteria_list(body.success_criteria.as_deref()) { + put = put.item("criteria", list); + } // Store which MCP servers were used during chat planning if let Some(servers) = &body.mcp_servers { @@ -346,6 +533,10 @@ pub async fn create_plan( if let Some(jp) = task.jira_project.as_deref() { put = put.item("jira_project", attr_s(jp)); } + put = put.item("added_by_kind", attr_s(author)); + if let Some(list) = criteria_list(task.covers.as_deref()) { + put = put.item("covers", list); + } put.send().await.map_err(|e| { error!("Failed to create task: {e}"); @@ -396,6 +587,25 @@ pub struct PlanWithTasks { pub plan: Plan, /// The plan's tasks, in order. pub tasks: Vec, + /// The success criteria, each with the tasks that cover it and the + /// evidence the work gave it: `{id, text, tasks, met, evidence: [{task_id, + /// run_id, state, words, by, tests}]}`. `state` is the criteria trace's + /// proof: `proven`, `not_the_ticket`, `failing`, `missing`, `unverified` + /// or `not_run`. + #[schema(value_type = Vec, example = json!([{"id": "C1", "text": "The 11th login attempt within 15 minutes gets 429", "tasks": ["01JB8V0P8Q2S4U6W8Y0A2C4E6G"], "met": true, "evidence": [{"task_id": "01JB8V0P8Q2S4U6W8Y0A2C4E6G", "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", "state": "proven", "words": "proven", "by": "tests with and without the change"}]}]))] + pub criteria: Vec, + /// What waits on a person, in task order, each the exact ask: + /// `{task_id, kind, ask, detail, url, run_id, action}`. `kind` is + /// `answer`, `review`, `approval`, `checks`, `merge`, `failed`, + /// `closed_pr` or `approve_rest`. + #[schema(value_type = Vec, example = json!([{"task_id": "01JB8V0P8Q2S4U6W8Y0A2C4E6G", "kind": "approval", "ask": "Approve pull request #318", "detail": "This repo's auto-merge setting requires an approving review from a person.", "url": "https://github.com/acme/web/pull/318", "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", "action": "open_pr"}]))] + pub needs: Vec, + /// What starting the draft tasks, or retrying one, is expected to take, + /// from the team's recent runs: `{tasks, runs_low, runs_high, cost_low, + /// cost_high, per_run_low, per_run_high, sample}`. Null when nothing is + /// left to start or retry. + #[schema(value_type = Option)] + pub estimate: Option, } /// GET /api/plans/:plan_id — get plan with all tasks. @@ -460,11 +670,86 @@ pub async fn get_plan( } } - let plan = plan_data.ok_or(StatusCode::NOT_FOUND)?; + let mut plan = plan_data.ok_or(StatusCode::NOT_FOUND)?; // Sort tasks by order tasks.sort_by_key(|t| t.order); - Ok(Json(PlanWithTasks { plan, tasks })) + // Where each task stands, from its runs and pull requests now. + let mut criteria = Vec::new(); + let mut needs = Vec::new(); + if let Some(r) = refresh_plan(&state, &claims.team_id, &plan_id).await { + apply_view(&mut plan, &r); + for task in tasks.iter_mut() { + let id = task.task_id.clone().unwrap_or_default(); + if let Some(d) = r.tasks.iter().find(|d| d.task_id == id) { + apply_task_view(task, d); + } + } + criteria = r.criteria; + needs = r.plan.needs; + } + let to_start = tasks + .iter() + .filter(|t| matches!(t.state.as_deref(), Some("draft"))) + .count(); + let to_retry = tasks + .iter() + .any(|t| matches!(t.state.as_deref(), Some("failed"))); + let estimate = if to_start > 0 || to_retry { + let recent = common::plan_sync::recent_costs( + &state.dynamo, + &state.config.runs_table_name, + &claims.team_id, + ) + .await; + Some(common::plan_sync::estimate(to_start, &recent)) + } else { + None + }; + + Ok(Json(PlanWithTasks { + plan, + tasks, + criteria, + needs, + estimate, + })) +} + +/// A task's state from a fresh derivation. +fn apply_task_view(task: &mut PlanTask, d: &common::plan_sync::TaskDetail) { + let v = &d.view; + task.state = Some(v.state.code().to_string()); + task.state_detail = Some(v.detail.clone()); + task.state_reason = Some(v.reason.clone()).filter(|s| !s.is_empty()); + task.attempts = Some(v.attempts as u64); + task.cost_usd = Some(round_cents(v.cost_usd)); + task.runs = Some(v.runs.clone()); + task.prs = Some(v.prs.clone()); + task.needs = v.needs.clone(); + task.drift = Some(v.drift.clone()); + task.covers = Some(d.covers.clone()); + task.ticket_filed = Some(v.ticket_filed); + task.last_activity_at = Some(v.last_activity.clone()).filter(|s| !s.is_empty()); + if let Some(last) = v.runs.last() { + task.run_id = Some(last.run_id.clone()); + } + if let Some(pr) = v.prs.first() { + task.pr_url = Some(pr.url.clone()); + } +} + +/// A list of short lines as a DynamoDB list, blank lines dropped; `None` +/// when nothing is left. +fn criteria_list(lines: Option<&[String]>) -> Option { + let list: Vec = lines? + .iter() + .map(|l| l.trim()) + .filter(|l| !l.is_empty()) + .take(50) + .map(|l| attr_s(common::truncate_str(l, 600))) + .collect(); + (!list.is_empty()).then_some(aws_sdk_dynamodb::types::AttributeValue::L(list)) } /// PUT /api/plans/:plan_id — update plan metadata. @@ -502,6 +787,18 @@ pub async fn update_plan( expr_values.push((":dest".to_string(), attr_s(dest))); } } + if let Some(list) = body["success_criteria"].as_array() { + let lines: Vec = list + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect(); + update_parts.push("criteria = :crit".to_string()); + expr_values.push(( + ":crit".to_string(), + criteria_list(Some(&lines)) + .unwrap_or(aws_sdk_dynamodb::types::AttributeValue::L(Vec::new())), + )); + } let update_expr = format!("SET {}", update_parts.join(", ")); @@ -655,11 +952,22 @@ pub async fn add_task( .item("acceptance_criteria", attr_s(acceptance_criteria)) .item("status", attr_s("draft")) .item("task_order", attr_n(order)) - .item("created_at", attr_s(&now)); + .item("created_at", attr_s(&now)) + .item("added_by_kind", attr_s("person")) + .item("added_by", attr_s(&claims.display_name())); if !task_repo.is_empty() { put = put.item("repo", attr_s(task_repo)); } + if let Some(list) = body["covers"].as_array() { + let ids: Vec = list + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect(); + if let Some(l) = criteria_list(Some(&ids)) { + put = put.item("covers", l); + } + } if let Some(dest) = body["destination"].as_str() { put = put.item("destination", attr_s(dest)); } @@ -756,9 +1064,43 @@ pub async fn update_task( } } + if let Some(list) = body["covers"].as_array() { + let ids: Vec = list + .iter() + .filter_map(|v| v.as_str().map(str::to_string)) + .collect(); + update_parts.push("covers = :cov"); + expr_values.push(( + ":cov", + criteria_list(Some(&ids)) + .unwrap_or(aws_sdk_dynamodb::types::AttributeValue::L(Vec::new())), + )); + } + if update_parts.is_empty() { return Ok(StatusCode::OK); } + // A change to what the task says is marked with who made it, so the + // plan page can show what moved after approval. + let what_changed = [ + "title", + "description", + "acceptance_criteria", + "repo", + "depends_on", + ] + .iter() + .any(|k| body.get(*k).is_some_and(|v| v.is_string())); + let now = chrono::Utc::now().to_rfc3339(); + let by = claims.display_name(); + if what_changed { + update_parts.push("edited_at = :ea"); + expr_values.push((":ea", attr_s(&now))); + update_parts.push("edited_by = :eb"); + expr_values.push((":eb", attr_s(&by))); + update_parts.push("edited_by_kind = :ek"); + expr_values.push((":ek", attr_s("person"))); + } let update_expr = format!("SET {}", update_parts.join(", ")); @@ -833,7 +1175,9 @@ pub async fn delete_task( Ok(StatusCode::OK) } -/// POST /api/plans/:plan_id/tasks/:task_id/approve — approve a task and immediately dispatch it. +/// POST /api/plans/:plan_id/tasks/:task_id/approve — approve a task and +/// start it now. The plan runs with its approved tasks and stays open for +/// the rest: approving one task never finishes the plan. pub async fn approve_task( State(state): State>, Extension(claims): Extension, @@ -844,11 +1188,19 @@ pub async fn approve_task( claims.require_role(1)?; validate_plan_id(&plan_id)?; validate_plan_id(&task_id)?; + // A task starts a paid run, like any other start. + if super::github_webhook::check_run_budget(&state, &claims.team_id) + .await + .is_some() + { + return Err(StatusCode::TOO_MANY_REQUESTS); + } let task_sk = format!("PLAN#{plan_id}#TASK#{task_id}"); let now = chrono::Utc::now().to_rfc3339(); - // 1. Mark task as approved + // 1. Approve it and queue it, before the message that starts it: the + // worker never finds a task it is filing still marked approved. let out = state .dynamo .update_item() @@ -857,14 +1209,25 @@ pub async fn approve_task( .key("sk", attr_s(&task_sk)) .update_expression("SET #st = :s, approved_at = :now, approved_by = :by") .expression_attribute_names("#st", "status") - .expression_attribute_values(":s", attr_s("approved")) + .expression_attribute_values(":s", attr_s("queued")) .expression_attribute_values(":now", attr_s(&now)) .expression_attribute_values(":by", attr_s(&claims.display_name())) - .condition_expression("attribute_exists(pk)") + // Only a task that has not started: approving a filed task again + // would file a second ticket and start a second run. + .condition_expression("attribute_exists(pk) AND #st IN (:draft, :rejected, :approved)") + .expression_attribute_values(":draft", attr_s("draft")) + .expression_attribute_values(":rejected", attr_s("rejected")) + .expression_attribute_values(":approved", attr_s("approved")) .return_values(aws_sdk_dynamodb::types::ReturnValue::AllNew) .send() .await .map_err(|e| { + if aws_sdk_dynamodb::error::DisplayErrorContext(&e) + .to_string() + .contains("ConditionalCheckFailed") + { + return StatusCode::CONFLICT; + } error!("Failed to approve task: {e}"); StatusCode::INTERNAL_SERVER_ERROR })?; @@ -879,48 +1242,84 @@ pub async fn approve_task( ) .await; - // 2. Mark plan as executing (idempotent — may already be executing) - let plan_sk = format!("PLAN#{plan_id}"); + // 2. The plan is running; when it first ran is kept (drift counts from + // it). Its state is derived from its tasks below, never set to done. + mark_plan_running(&state, &claims, &plan_id, &now).await; + + // 3. Start this one task. + let plan_msg = WorkerMessage::PlanExecute(PlanExecuteMessage { + team_id: claims.team_id.clone(), + plan_id: plan_id.clone(), + triggered_by: claims.display_name(), + tasks: vec![task_id.clone()], + }); + if let Err(code) = send_plan_message(&state, &plan_msg).await { + // Not started: back to approved, so Approve and start picks it up. + set_task_word(&state, &claims.team_id, &plan_id, &task_id, "approved").await; + return Err(code); + } + + info!(plan_id, task_id, "Task approved and dispatched to worker"); + refresh_plan(&state, &claims.team_id, &plan_id).await; + + Ok(Json(json!({ "dispatched": true, "task_id": task_id }))) +} + +/// Marks a plan running; keeps when and by whom it first ran. +async fn mark_plan_running(state: &AppState, claims: &Claims, plan_id: &str, now: &str) { let _ = state .dynamo .update_item() .table_name(&state.config.plans_table_name) .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(&plan_sk)) - .update_expression("SET #st = :s, executed_at = :now, executed_by = :by, updated_at = :now") + .key("sk", attr_s(&format!("PLAN#{plan_id}"))) + .condition_expression("attribute_exists(sk)") + .update_expression( + "SET #st = :s, executed_at = if_not_exists(executed_at, :now), \ + executed_by = if_not_exists(executed_by, :by), updated_at = :now", + ) .expression_attribute_names("#st", "status") .expression_attribute_values(":s", attr_s("executing")) - .expression_attribute_values(":now", attr_s(&now)) + .expression_attribute_values(":now", attr_s(now)) .expression_attribute_values(":by", attr_s(&claims.display_name())) .send() .await; +} - // 3. Immediately dispatch this single task to the worker - let plan_msg = WorkerMessage::PlanExecute(PlanExecuteMessage { - team_id: claims.team_id.clone(), - plan_id: plan_id.clone(), - triggered_by: claims.display_name(), - tasks: vec![task_id.clone()], - }); - +/// Sends a plan message to the worker's queue. +async fn send_plan_message(state: &AppState, msg: &WorkerMessage) -> Result<(), StatusCode> { + let body = serde_json::to_string(msg).map_err(|e| { + error!("Failed to serialize plan message: {e}"); + StatusCode::INTERNAL_SERVER_ERROR + })?; state .sqs .send_message() .queue_url(&state.config.ticket_queue_url) - .message_body(serde_json::to_string(&plan_msg).map_err(|e| { - error!("Failed to serialize plan message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?) + .message_body(body) .send() .await + .map(|_| ()) .map_err(|e| { - error!("Failed to send task to queue: {e}"); + error!("Failed to send plan message: {e}"); StatusCode::INTERNAL_SERVER_ERROR - })?; - - info!(plan_id, task_id, "Task approved and dispatched to worker"); + }) +} - Ok(Json(json!({ "dispatched": true, "task_id": task_id }))) +/// Sets a task row's own word (`status`). +async fn set_task_word(state: &AppState, team_id: &str, plan_id: &str, task_id: &str, word: &str) { + let _ = state + .dynamo + .update_item() + .table_name(&state.config.plans_table_name) + .key("pk", attr_s(team_id)) + .key("sk", attr_s(&format!("PLAN#{plan_id}#TASK#{task_id}"))) + .condition_expression("attribute_exists(sk)") + .update_expression("SET #st = :s") + .expression_attribute_names("#st", "status") + .expression_attribute_values(":s", attr_s(word)) + .send() + .await; } /// A plan task approved or rejected, as a reward signal for the planner. @@ -1030,6 +1429,12 @@ pub async fn approve_all_and_execute( // agent runs or delete the team's plans. claims.require_role(1)?; validate_plan_id(&plan_id)?; + if super::github_webhook::check_run_budget(&state, &claims.team_id) + .await + .is_some() + { + return Err(StatusCode::TOO_MANY_REQUESTS); + } let result = state .dynamo @@ -1101,49 +1506,10 @@ pub async fn approve_all_and_execute( } task_ids.sort_by_key(|t| t.1); + let ids: Vec = task_ids.iter().map(|(tid, _)| tid.clone()).collect(); - // Mark plan as executing - let plan_sk = format!("PLAN#{plan_id}"); - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(&plan_sk)) - .update_expression("SET #st = :s, executed_at = :now, executed_by = :by, updated_at = :now") - .expression_attribute_names("#st", "status") - .expression_attribute_values(":s", attr_s("executing")) - .expression_attribute_values(":now", attr_s(&now)) - .expression_attribute_values(":by", attr_s(&claims.display_name())) - .send() - .await - .map_err(|e| { - error!("Failed to update plan status: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - - // Send SQS message - let plan_msg = WorkerMessage::PlanExecute(PlanExecuteMessage { - team_id: claims.team_id.clone(), - plan_id: plan_id.clone(), - triggered_by: claims.display_name(), - tasks: task_ids.iter().map(|(tid, _)| tid.clone()).collect(), - }); - - state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(serde_json::to_string(&plan_msg).map_err(|e| { - error!("Failed to serialize plan message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?) - .send() - .await - .map_err(|e| { - error!("Failed to send plan execute message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; + mark_plan_running(&state, &claims, &plan_id, &now).await; + start_tasks(&state, &claims, &plan_id, &ids).await?; super::webhooks::emit_plan_approved( &state, @@ -1153,23 +1519,7 @@ pub async fn approve_all_and_execute( task_ids.len(), ) .await; - - // Mark tasks as queued - for (task_id, _) in &task_ids { - let task_sk = format!("PLAN#{plan_id}#TASK#{task_id}"); - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(&task_sk)) - .update_expression("SET #st = :s") - .expression_attribute_names("#st", "status") - .expression_attribute_values(":s", attr_s("queued")) - .send() - .await - .ok(); - } + refresh_plan(&state, &claims.team_id, &plan_id).await; Ok(Json(PlanExecution { status: "executing".into(), @@ -1188,6 +1538,12 @@ pub async fn force_run_task( claims.require_role(1)?; validate_plan_id(&plan_id)?; validate_plan_id(&task_id)?; + if super::github_webhook::check_run_budget(&state, &claims.team_id) + .await + .is_some() + { + return Err(StatusCode::TOO_MANY_REQUESTS); + } // Verify task is in "waiting" status let task_sk = format!("PLAN#{plan_id}#TASK#{task_id}"); @@ -1223,7 +1579,7 @@ pub async fn force_run_task( .table_name(&state.config.plans_table_name) .key("pk", attr_s(&claims.team_id)) .key("sk", attr_s(&task_sk)) - .update_expression("SET #s = :s") + .update_expression("SET #s = :s REMOVE failure_reason") .expression_attribute_names("#s", "status") .expression_attribute_values(":s", attr_s("waiting")) .send() @@ -1329,76 +1685,48 @@ pub async fn execute_plan( // Sort by order approved_task_ids.sort_by_key(|t| t.1); - - // Mark plan as executing - let plan_sk = format!("PLAN#{plan_id}"); + let ids: Vec = approved_task_ids + .iter() + .map(|(tid, _)| tid.clone()) + .collect(); let now = chrono::Utc::now().to_rfc3339(); + mark_plan_running(&state, &claims, &plan_id, &now).await; + start_tasks(&state, &claims, &plan_id, &ids).await?; + refresh_plan(&state, &claims.team_id, &plan_id).await; - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(&plan_sk)) - .update_expression("SET #st = :s, executed_at = :now, executed_by = :by, updated_at = :now") - .expression_attribute_names("#st", "status") - .expression_attribute_values(":s", attr_s("executing")) - .expression_attribute_values(":now", attr_s(&now)) - .expression_attribute_values(":by", attr_s(&claims.display_name())) - .send() - .await - .map_err(|e| { - error!("Failed to update plan status: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; + Ok(Json(json!({ + "status": "executing", + "tasks_queued": approved_task_ids.len(), + }))) +} - // Send SQS message for plan execution (worker creates issues + queues runs) - let plan_msg = WorkerMessage::PlanExecute(PlanExecuteMessage { +/// Queues approved tasks, then sends the one message that starts them. The +/// tasks are marked queued first: the worker files their tickets and moves +/// them on, and a `queued` written after the message could land on a task +/// the worker had already filed. When the message can't be sent, they go +/// back to approved, so starting again finds them. +async fn start_tasks( + state: &AppState, + claims: &Claims, + plan_id: &str, + ids: &[String], +) -> Result<(), StatusCode> { + for id in ids { + set_task_word(state, &claims.team_id, plan_id, id, "queued").await; + } + let msg = WorkerMessage::PlanExecute(PlanExecuteMessage { team_id: claims.team_id.clone(), - plan_id: plan_id.clone(), + plan_id: plan_id.to_string(), triggered_by: claims.display_name(), - tasks: approved_task_ids - .iter() - .map(|(tid, _)| tid.clone()) - .collect(), + tasks: ids.to_vec(), }); - - state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(serde_json::to_string(&plan_msg).map_err(|e| { - error!("Failed to serialize plan message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?) - .send() - .await - .map_err(|e| { - error!("Failed to send plan execute message: {e}"); - StatusCode::INTERNAL_SERVER_ERROR - })?; - - // Mark each approved task as "queued" - for (task_id, _) in &approved_task_ids { - let task_sk = format!("PLAN#{plan_id}#TASK#{task_id}"); - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", attr_s(&claims.team_id)) - .key("sk", attr_s(&task_sk)) - .update_expression("SET #st = :s") - .expression_attribute_names("#st", "status") - .expression_attribute_values(":s", attr_s("queued")) - .send() - .await - .ok(); + if let Err(code) = send_plan_message(state, &msg).await { + for id in ids { + set_task_word(state, &claims.team_id, plan_id, id, "approved").await; + } + return Err(code); } - - Ok(Json(json!({ - "status": "executing", - "tasks_queued": approved_task_ids.len(), - }))) + Ok(()) } /// A plan that started running. @@ -1448,9 +1776,44 @@ pub struct Plan { /// The repository its tasks work in, `owner/name`. #[schema(example = "acme/web")] pub repo: Option, - /// `draft`, `executing` or `completed`. - #[schema(example = "draft")] + /// The older status word, kept for older clients: `draft`, `executing`, + /// or `done` once every task merged or was dropped. Read `state`. + #[schema(example = "executing")] pub status: Option, + /// Where the plan stands, from its tasks' work: `drafting` (nothing + /// approved yet), `running`, `needs_you` (a task asks a person + /// something, failed, or drafts remain once the rest finished), `done` + /// (every task merged or dropped) or `stalled` (open work and nothing + /// moved for 3 days). + #[schema(example = "running")] + pub state: Option, + /// The count line: merged first, then the states with tasks in them. + #[schema(example = "2 of 5 merged, 1 needs you, 1 in review, 1 working")] + pub summary: Option, + /// How many tasks are in each state. + #[schema(value_type = Option)] + pub counts: Option, + /// How many things wait on a person. + #[schema(example = 1)] + pub needs_count: u64, + /// What its tasks' runs cost so far, in US dollars, every attempt counted. + #[schema(example = 18.4)] + pub cost_usd: Option, + /// Runs its tasks took, every attempt counted. + #[schema(example = 6)] + pub attempts: Option, + /// Success criteria the work proved, of `criteria_count`. + #[schema(example = 3)] + pub criteria_met: Option, + /// How many success criteria it has. + #[schema(example = 5)] + pub criteria_count: Option, + /// When anything last happened on its tasks (RFC 3339). + #[schema(example = "2026-10-23T09:12:00+00:00")] + pub last_activity_at: Option, + /// The plan's success criteria as written, when it has its own list. + #[schema(example = json!(["The 11th login attempt within 15 minutes gets 429"]))] + pub success_criteria: Option>, /// How many tasks it has. #[schema(example = 3)] pub task_count: u64, @@ -1483,6 +1846,99 @@ pub struct Plan { pub executed_by: Option, } +/// How many tasks are in each state (the shape of +/// `common::plan_state::Counts`, for the API document). +#[derive(utoipa::ToSchema)] +#[allow(dead_code)] +pub struct TaskCounts { + /// Not approved yet. + #[schema(example = 0)] + draft: u64, + /// Approved and waiting to start. + #[schema(example = 1)] + queued: u64, + /// Its run is working. + #[schema(example = 1)] + working: u64, + /// Its run asks a person for something. + #[schema(example = 1)] + needs_you: u64, + /// Failed, with a reason. + #[schema(example = 0)] + failed: u64, + /// A pull request is open. + #[schema(example = 1)] + in_review: u64, + /// A pull request merged. + #[schema(example = 2)] + merged: u64, + /// Dropped by a person. + #[schema(example = 0)] + dropped: u64, +} + +/// Something a person has to do for the plan to go on (the shape of +/// `common::plan_state::NeedsItem`, for the API document). +#[derive(utoipa::ToSchema)] +#[allow(dead_code)] +pub struct NeedsYou { + /// The task it is about; empty for the plan's drafts. + #[schema(example = "01JB8V0P8Q2S4U6W8Y0A2C4E6G")] + task_id: String, + /// `answer`, `review`, `approval`, `checks`, `merge`, `failed`, + /// `closed_pr` or `approve_rest`. + #[schema(example = "approval")] + kind: String, + /// What to do, one line. + #[schema(example = "Approve pull request #318")] + ask: String, + /// Why, or what is open. + #[schema( + example = "This repo's auto-merge setting requires an approving review from a person." + )] + detail: Option, + /// Where to do it. + #[schema(example = "https://github.com/acme/web/pull/318")] + url: Option, + /// The run it comes from. + #[schema(example = "01JB8X6F4M2C9QZ3T7V5W1K0HA")] + run_id: Option, + /// The button: `answer`, `open_pr`, `open_link`, `retry` or `approve`. + #[schema(example = "open_pr")] + action: String, +} + +/// What starting tasks, or retrying one, is expected to take, from the +/// team's recent finished runs (the shape of `common::plan_sync::Estimate`). +#[derive(utoipa::ToSchema)] +#[allow(dead_code)] +pub struct StartEstimate { + /// Tasks it would start. + #[schema(example = 3)] + tasks: u64, + /// Runs expected: one per task. + #[schema(example = 3)] + runs_low: u64, + /// Runs expected with the attempts a ticket took lately. + #[schema(example = 4)] + runs_high: u64, + /// The low end of the cost, in US dollars. + #[schema(example = 6.3)] + cost_low: f64, + /// The high end of the cost, in US dollars. + #[schema(example = 19.8)] + cost_high: f64, + /// One run's typical cost, low end (a Retry or Start now). + #[schema(example = 2.1)] + per_run_low: f64, + /// One run's typical cost, high end. + #[schema(example = 4.95)] + per_run_high: f64, + /// Finished runs the numbers come from; 0 means no history yet. + #[schema(example = 40)] + sample: u64, +} + /// A task in a plan. #[derive(serde::Serialize, utoipa::ToSchema)] pub struct PlanTask { @@ -1501,10 +1957,54 @@ pub struct PlanTask { /// How to tell it is done. #[schema(example = "The 11th attempt within 15 minutes gets 429 and a Retry-After header.")] pub acceptance_criteria: Option, - /// `draft`, `approved`, `rejected`, `queued`, `waiting` (on a task it - /// depends on), `running`, `completed` or `failed`. - #[schema(example = "queued")] + /// The task row's own word: `draft`, `approved`, `rejected`, `queued`, + /// `waiting` (on a task it depends on), `running` (filing its ticket), + /// `filed` (older tasks say `done`) or `failed` (the ticket could not be + /// filed). Filing the ticket finishes nothing: read `state`. + #[schema(example = "filed")] pub status: Option, + /// Where the task stands, from its runs and pull requests: `draft`, + /// `queued`, `working`, `needs_you`, `failed`, `in_review`, `merged` or + /// `dropped`. + #[schema(example = "in_review")] + pub state: Option, + /// One line: what it is doing, what it waits on, or what blocks it. + #[schema(example = "Checks are running on pull request #318")] + pub state_detail: Option, + /// Why it failed (`failed` only). + #[schema(example = json!(null))] + pub state_reason: Option, + /// Runs it took, every attempt counted. + #[schema(example = 2)] + pub attempts: Option, + /// What its runs cost, in US dollars. + #[schema(example = 7.2)] + pub cost_usd: Option, + /// Every attempt, oldest first: `{run_id, status, created_at, cost_usd}`. + #[schema(value_type = Option>, example = json!([{"run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA", "status": "completed", "created_at": "2026-10-22T14:02:11+00:00", "cost_usd": 3.6}]))] + pub runs: Option>, + /// Its pull requests, newest attempt first: `{number, url, repo, state, + /// checks, review, tone, additions, deletions, run_id}`. `tone` is the + /// colour: `ready`, `waiting`, `failing`, `merged` or `closed`. + #[schema(value_type = Option>, example = json!([{"number": 318, "url": "https://github.com/acme/web/pull/318", "repo": "acme/web", "state": "open", "checks": "running", "review": "none", "tone": "waiting", "additions": 120, "deletions": 8, "run_id": "01JB8X6F4M2C9QZ3T7V5W1K0HA"}]))] + pub prs: Option>, + /// What it waits on a person for, when it does. + #[schema(value_type = Option)] + pub needs: Option, + /// Changes after the plan was approved, and work outside its scope: + /// `{kind, detail, by, by_name, at}`, `kind` one of `added`, `changed`, + /// `dropped`, `scope`; `by` is `agent` or `person`. + #[schema(value_type = Option>, example = json!([{"kind": "added", "detail": "Added after the plan was approved", "by": "person", "by_name": "octocat", "at": "2026-10-22T15:00:00+00:00"}]))] + pub drift: Option>, + /// The plan's success criteria it covers (`C1`, ...). + #[schema(example = json!(["C1"]))] + pub covers: Option>, + /// Its ticket was filed. + #[schema(example = true)] + pub ticket_filed: Option, + /// When anything last happened on it (RFC 3339). + #[schema(example = "2026-10-23T09:12:00+00:00")] + pub last_activity_at: Option, /// Its repository, when not the plan's. #[schema(example = "acme/web")] pub repo: Option, @@ -1517,10 +2017,10 @@ pub struct PlanTask { /// That issue's address. #[schema(example = "https://github.com/acme/web/issues/412")] pub issue_url: Option, - /// The run working on it. + /// Its newest run (every attempt is in `runs`). #[schema(example = "01JB8X6F4M2C9QZ3T7V5W1K0HA")] pub run_id: Option, - /// The pull request that run opened. + /// The newest pull request (every one is in `prs`). #[schema(example = "https://github.com/acme/web/pull/318")] pub pr_url: Option, /// When it was approved (RFC 3339). @@ -1573,6 +2073,7 @@ fn plan_of(item: &PlanItem) -> Plan { .and_then(|v| v.as_l().ok()) .map(|list| list.iter().filter_map(|v| v.as_s().ok().cloned()).collect()) .unwrap_or_default(); + let stored = common::plan_sync::stored(item); Plan { plan_id: item_str(item, "plan_id"), title: item_str(item, "title"), @@ -1583,6 +2084,19 @@ fn plan_of(item: &PlanItem) -> Plan { tokens_in: item_u64(item, "total_tokens_in"), tokens_out: item_u64(item, "total_tokens_out"), destination: item_str(item, "destination"), + state: stored.state.map(|s| s.code().to_string()), + summary: Some(stored.summary.clone()).filter(|s| !s.is_empty()), + counts: stored.state.map(|_| stored.counts.clone()), + needs_count: stored.needs_count, + cost_usd: stored.state.map(|_| round_cents(stored.cost_usd)), + attempts: stored.state.map(|_| stored.attempts), + criteria_met: stored.state.map(|_| stored.criteria_met), + criteria_count: stored.state.map(|_| stored.criteria_count), + last_activity_at: Some(stored.last_activity_at.clone()).filter(|s| !s.is_empty()), + success_criteria: item + .get("criteria") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()), mcp_servers: (!mcp_servers.is_empty()).then_some(mcp_servers), chat_id: item_str(item, "chat_id"), created_at: item_str(item, "created_at"), @@ -1600,6 +2114,30 @@ fn task_of(item: &PlanItem) -> PlanTask { description: item_str(item, "description"), acceptance_criteria: item_str(item, "acceptance_criteria"), status: item_str(item, "status"), + state: item_str(item, "state"), + state_detail: item_str(item, "state_detail"), + state_reason: item_str(item, "state_reason") + .filter(|s| !s.is_empty()) + .or_else(|| item_str(item, "failure_reason")), + attempts: item_u64(item, "attempts"), + cost_usd: item + .get("cost_usd") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .map(round_cents), + runs: None, + prs: item_str(item, "prs").and_then(|s| serde_json::from_str(&s).ok()), + needs: None, + drift: None, + covers: item + .get("covers") + .and_then(|v| v.as_l().ok()) + .map(|l| l.iter().filter_map(|v| v.as_s().ok().cloned()).collect()), + ticket_filed: item + .get("ticket_filed") + .and_then(|v| v.as_bool().ok()) + .copied(), + last_activity_at: None, repo: item_str(item, "repo"), order: item_u64(item, "task_order").unwrap_or(0), issue_number: item_u64(item, "issue_number"), @@ -4262,3 +4800,92 @@ mod stream_block_tests { assert_eq!(raw, "{\"a\":1}"); } } + +#[cfg(test)] +mod start_tests { + /// The body of `pub async fn ` in this file. + fn body(name: &str) -> String { + let src = include_str!("plans.rs"); + let start = src + .find(&format!("pub async fn {name}(")) + .unwrap_or_else(|| panic!("{name} not found")); + let rest = &src[start..]; + let end = rest[1..] + .find("\npub async fn ") + .map(|i| i + 1) + .unwrap_or(rest.len()); + rest[..end].to_string() + } + + /// Every route that starts a task's work. + const STARTS: [&str; 4] = [ + "approve_task", + "approve_all_and_execute", + "execute_plan", + "force_run_task", + ]; + + #[test] + fn every_route_that_starts_work_checks_the_run_budget() { + for name in STARTS { + let b = body(name); + assert!( + b.contains("check_run_budget"), + "{name} starts paid runs without checking the team's run budget" + ); + let check = b.find("check_run_budget").unwrap(); + let send = ["start_tasks(", "send_plan_message(", ".send_message()"] + .iter() + .filter_map(|s| b.find(s)) + .min() + .unwrap_or_else(|| panic!("{name} starts nothing")); + assert!(check < send, "{name} checks the budget after starting"); + } + } + + #[test] + fn tasks_are_queued_before_the_message_that_starts_them() { + // `queued` written after the message could land on a task the worker + // had already filed. + let helper = body("approve_task"); + let queued = helper.find(r#"attr_s("queued")"#).expect("queued"); + let sent = helper.find("send_plan_message(").expect("sent"); + assert!(queued < sent); + let src = include_str!("plans.rs"); + let start = src.find("async fn start_tasks(").unwrap(); + let st = &src[start..start + src[start..].find("\n}\n").unwrap()]; + assert!(st.find(r#""queued""#).unwrap() < st.find("send_plan_message(").unwrap()); + for name in ["approve_all_and_execute", "execute_plan"] { + let b = body(name); + assert!(b.contains("start_tasks("), "{name}"); + assert!(!b.contains(".send_message()"), "{name} sends on its own"); + } + } + + #[test] + fn approving_a_task_never_finishes_the_plan() { + for name in STARTS { + let b = body(name); + assert!(!b.contains(r#"attr_s("done")"#), "{name} writes done"); + } + assert!(body("approve_task").contains("mark_plan_running(")); + } + + #[test] + fn a_review_or_size_on_a_pr_event_is_kept_on_the_run() { + let p = serde_json::json!({ + "action": "submitted", + "pull_request": {"number": 4, "additions": 120, "deletions": 8}, + "review": {"state": "approved", "user": {"login": "someone", "type": "User"}}, + }); + let f = super::pr_event_facts("pull_request_review", &p); + let keys: Vec<&str> = f.iter().map(|(k, _)| *k).collect(); + assert_eq!(keys, ["pr_additions", "pr_deletions", "pr_review"]); + let bot = serde_json::json!({ + "action": "submitted", + "pull_request": {"number": 4}, + "review": {"state": "changes_requested", "user": {"login": "coderhelm[bot]", "type": "Bot"}}, + }); + assert!(super::pr_event_facts("pull_request_review", &bot).is_empty()); + } +} diff --git a/services/worker/src/passes/incidents/pl_plan_follows_the_work.rs b/services/worker/src/passes/incidents/pl_plan_follows_the_work.rs new file mode 100644 index 000000000..d00a856a6 --- /dev/null +++ b/services/worker/src/passes/incidents/pl_plan_follows_the_work.rs @@ -0,0 +1,275 @@ +//! pl. Two plans read wrong for weeks. +//! +//! The stranded plan: three draft tasks. A person approved the first one +//! from its row, the way the page suggested. The worker filed its ticket, +//! marked the task `done` and, with no task waiting on another, marked the +//! plan `done`. The page hid the Approve buttons of a plan that was not a +//! draft, so the two other tasks stayed drafts with no way to start them, +//! under a plan that said Done. +//! +//! The false-Done plan: four tasks, all filed, all `done`, the plan `done`. +//! Its runs said otherwise: one pull request merged, one closed unmerged, +//! one run failed with no pull request, and one task took eleven runs and +//! seven pull requests, none merged, about $130, while it read done the +//! whole time. No run or pull request was ever written back to a task. +//! +//! Guarantee: a task's state is derived from the runs of its ticket and +//! their pull requests (`common::plan_state`), never from filing the +//! ticket; the plan's from its tasks, Done only when every task merged or +//! was dropped. A refresh (`common::plan_sync`) links each run to its task +//! and runs on every run status change and pull request event; the plans +//! list refreshes rows written before it, which is the backfill. Approving +//! one task never ends the plan: the drafts left are asked for by name. + +use aws_sdk_dynamodb::types::AttributeValue; +use common::plan_state::{PlanState, TaskState}; +use common::plan_sync::{refresh, stored, Item, Memory}; + +const TEAM: &str = "TEAM#example"; + +fn item(pairs: &[(&str, &str)]) -> Item { + pairs + .iter() + .map(|(k, v)| { + let v = match *k { + "task_order" | "cost_usd" | "issue_number" => AttributeValue::N(v.to_string()), + _ => AttributeValue::S(v.to_string()), + }; + (k.to_string(), v) + }) + .collect() +} + +fn plan(m: &Memory, id: &str, status: &str) { + m.put_row( + TEAM, + item(&[ + ("sk", &format!("PLAN#{id}")), + ("plan_id", id), + ("title", "Report handled errors in the mobile app"), + ("repo", "example-org/mobile"), + ("status", status), + ("executed_at", "2026-04-22T17:16:00Z"), + ]), + ); +} + +fn task(m: &Memory, plan_id: &str, id: &str, order: &str, status: &str, key: &str) { + let mut pairs = vec![ + ("sk".to_string(), format!("PLAN#{plan_id}#TASK#{id}")), + ("plan_id".to_string(), plan_id.to_string()), + ("task_id".to_string(), id.to_string()), + ("title".to_string(), format!("Task {order}")), + ("status".to_string(), status.to_string()), + ("task_order".to_string(), order.to_string()), + ("created_at".to_string(), "2026-04-21T19:04:00Z".to_string()), + ]; + if !key.is_empty() { + pairs.push(("jira_ticket_key".into(), key.into())); + } + let refs: Vec<(&str, &str)> = pairs + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + m.put_row(TEAM, item(&refs)); +} + +#[allow(clippy::too_many_arguments)] +fn run( + m: &Memory, + id: &str, + key: &str, + status: &str, + at: &str, + pr: Option<(u64, &str)>, + cost: &str, + error: &str, +) { + let mut r = item(&[ + ("run_id", id), + ("ticket_id", key), + ("repo", "example-org/mobile"), + ("status", status), + ("created_at", at), + ("updated_at", at), + ("cost_usd", cost), + ]); + if let Some((n, outcome)) = pr { + r.insert( + "pr_url".into(), + AttributeValue::S(format!("https://github.com/example-org/mobile/pull/{n}")), + ); + if !outcome.is_empty() { + r.insert("pr_outcome".into(), AttributeValue::S(outcome.into())); + } + } + if !error.is_empty() { + r.insert("error_message".into(), AttributeValue::S(error.into())); + } + m.put_run(TEAM, r); +} + +#[tokio::test] +async fn approving_one_task_leaves_the_plan_open_with_the_rest_to_approve() { + let m = Memory::default(); + // The rows as the old worker left them: the one approved task `done` + // the moment its ticket was filed, and the plan `done` with it. + plan(&m, "P1", "done"); + task(&m, "P1", "T1", "0", "done", "MOB-1"); + task(&m, "P1", "T2", "1", "draft", ""); + task(&m, "P1", "T3", "2", "draft", ""); + + let out = refresh(&m, TEAM, "P1", "2026-04-22T18:00:00Z") + .await + .unwrap() + .unwrap(); + assert_eq!( + out.tasks[0].view.state, + TaskState::Queued, + "filed is not done" + ); + assert_eq!(out.tasks[1].view.state, TaskState::Draft); + assert_eq!(out.tasks[2].view.state, TaskState::Draft); + assert_eq!(out.plan.state, PlanState::Running); + let rest = out + .plan + .needs + .iter() + .find(|n| n.kind == "approve_rest") + .expect("the drafts left are asked for"); + assert_eq!(rest.ask, "Approve or drop the 2 tasks still in draft"); + // The plan row no longer says done. + let row = m.row(TEAM, "PLAN#P1").unwrap(); + assert_eq!(stored(&row).state, Some(PlanState::Running)); + assert_eq!( + row.get("status").and_then(|v| v.as_s().ok()).unwrap(), + "executing" + ); + + // Its run merges: two drafts are left, so it needs a person, not Done. + run( + &m, + "R1", + "MOB-1", + "merged", + "2026-04-22T17:20:00Z", + Some((854, "merged")), + "4.1", + "", + ); + let out = refresh(&m, TEAM, "P1", "2026-04-23T09:00:00Z") + .await + .unwrap() + .unwrap(); + assert_eq!(out.tasks[0].view.state, TaskState::Merged); + assert_eq!(out.plan.state, PlanState::NeedsYou); +} + +#[tokio::test] +async fn a_plan_is_done_only_when_its_work_merged() { + let m = Memory::default(); + plan(&m, "P2", "done"); + for (i, key) in ["OPS-1", "OPS-2", "OPS-3", "OPS-4"].iter().enumerate() { + task(&m, "P2", &format!("T{i}"), &i.to_string(), "done", key); + } + run( + &m, + "A1", + "OPS-1", + "merged", + "2026-04-22T17:30:00Z", + Some((101, "merged")), + "6.0", + "", + ); + run( + &m, + "B1", + "OPS-2", + "completed", + "2026-04-22T17:30:00Z", + Some((102, "closed")), + "9.5", + "", + ); + run( + &m, + "C1", + "OPS-3", + "failed", + "2026-04-22T17:30:00Z", + None, + "3.2", + "Run timed out (exceeded execution time limit).", + ); + // Eleven runs and seven pull requests on one task, none merged. + for i in 0..11u64 { + let status = if i < 10 { "retried" } else { "completed" }; + let pr = (i < 6).then_some((200 + i, "closed")); + let pr = if i == 10 { Some((300, "")) } else { pr }; + run( + &m, + &format!("D{i:02}"), + "OPS-4", + status, + &format!("2026-04-23T{:02}:00:00Z", 10 + i), + pr, + "11.8", + "", + ); + } + + let out = refresh(&m, TEAM, "P2", "2026-05-04T12:00:00Z") + .await + .unwrap() + .unwrap(); + let states: Vec = out.tasks.iter().map(|t| t.view.state).collect(); + assert_eq!( + states, + [ + TaskState::Merged, + TaskState::Failed, + TaskState::Failed, + TaskState::InReview + ] + ); + assert!(out.tasks[1].view.reason.contains("closed without merging")); + assert_eq!( + out.tasks[2].view.reason, + "Run timed out (exceeded execution time limit)." + ); + let heavy = &out.tasks[3].view; + assert_eq!(heavy.attempts, 11); + assert_eq!(heavy.prs.len(), 7); + assert!((heavy.cost_usd - 129.8).abs() < 0.01, "{}", heavy.cost_usd); + assert_ne!(out.plan.state, PlanState::Done); + assert_eq!(out.plan.state, PlanState::NeedsYou); + assert_eq!(out.plan.summary, "1 of 4 merged, 2 failed, 1 in review"); + // Every run is now linked to its task. + assert_eq!(out.runs_linked, 14); + assert_eq!( + m.run(TEAM, "D03") + .unwrap() + .get("plan_task_id") + .and_then(|v| v.as_s().ok()) + .unwrap(), + "T3" + ); +} + +#[test] +fn filing_a_ticket_writes_no_done() { + // The worker files tickets and leaves every state to the derivation: + // no `done` is written on a task or on the plan. + let src = include_str!("../plan_execute.rs"); + let code: String = src + .lines() + .filter(|l| !l.trim_start().starts_with("//")) + .collect::>() + .join("\n"); + assert!( + !code.contains(r#"AttributeValue::S("done""#), + "a done write is back" + ); + assert!(code.contains("plan_sync::refresh")); +} diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 888fd206d..309281eea 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -1360,6 +1360,7 @@ pub mod plan_execute; mod plan_judge; pub(crate) mod plan_sections; mod plan_shape; +pub mod plan_sync; /// Plugin runs, publishing, source sync and results. pub mod plugins; mod pr; @@ -8903,10 +8904,13 @@ async fn create_run_record( _ => None, }; if let Some(ticket) = plan_ticket { - if let Some((plan_id, title, by)) = + if let Some((plan_id, title, by, task_id)) = plan_execute::plan_of_ticket(state, &msg.team_id, &ticket).await { put = put.item("plan_id", attr_s(&plan_id)); + if !task_id.is_empty() { + put = put.item("plan_task_id", attr_s(&task_id)); + } if !title.is_empty() { put = put.item("plan_title", attr_s(&title)); } diff --git a/services/worker/src/passes/plan_execute.rs b/services/worker/src/passes/plan_execute.rs index 115e1eac0..bcda3c613 100644 --- a/services/worker/src/passes/plan_execute.rs +++ b/services/worker/src/passes/plan_execute.rs @@ -66,7 +66,10 @@ pub async fn run( // the whole PlanExecute message — without this, already-completed // tasks were re-run, creating duplicate GitHub issues/Jira tickets // (each duplicate then triggering a full duplicate agent run). - if matches!(task.status.as_str(), "running" | "done" | "issue_created") { + if matches!( + task.status.as_str(), + "running" | "done" | "issue_created" | FILED + ) { info!(task_id, status = %task.status, "Task already processed — skipping (redelivery)"); continue; } @@ -94,13 +97,14 @@ pub async fn run( if project_key.is_empty() { error!(task_id, "No Jira project configured for task"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_JIRA_PROJECT) + .await?; continue; } let Some(ref url) = jira_create_url else { error!(task_id, "No Jira create-ticket URL configured"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_JIRA_APP).await?; continue; }; @@ -164,11 +168,14 @@ pub async fn run( let status = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); error!(task_id, status, body = %body, "Failed to create Jira ticket"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = jira_refused(status, &body); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } Err(e) => { error!(task_id, error = %e, "Failed to call Forge create-ticket"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = + format!("CoderHelm could not reach the Jira app to file the ticket: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } } } else { @@ -180,7 +187,7 @@ pub async fn run( .unwrap_or(&plan_repo); if task_repo.is_empty() { error!(task_id, "No repo configured for task or plan"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_REPO).await?; continue; } @@ -235,7 +242,8 @@ pub async fn run( .await { error!(task_id, issue_number, error = %e, "Failed to add coderhelm label — issue won't auto-run"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed") + let reason = format!("Issue #{issue_number} was opened, but GitHub refused the coderhelm label that starts its run: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason) .await?; continue; } @@ -255,64 +263,18 @@ pub async fn run( } Err(e) => { error!(task_id, error = %e, "Failed to create GitHub issue"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = format!("GitHub refused the issue for this task: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } } } } - // Query all tasks in this plan to see if any are waiting - let all_tasks_result = state - .dynamo - .query() - .table_name(&state.config.plans_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :sk_prefix)") - .expression_attribute_values(":pk", AttributeValue::S(msg.team_id.clone())) - .expression_attribute_values( - ":sk_prefix", - AttributeValue::S(format!("PLAN#{}#TASK#", msg.plan_id)), - ) - .send() - .await?; - - let any_waiting = all_tasks_result.items().iter().any(|item| { - item.get("status") - .and_then(|v| v.as_s().ok()) - .map(|s| s == "waiting") - .unwrap_or(false) - }); - - if any_waiting { - // Mark plan as "waiting" instead of "done" — tasks are blocked on dependencies - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", AttributeValue::S(msg.team_id.clone())) - .key("sk", AttributeValue::S(format!("PLAN#{}", msg.plan_id))) - .update_expression("SET #s = :s") - .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S("waiting".to_string())) - .send() - .await?; - info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "Plan has waiting tasks — not marking done"); - } else { - // Mark plan as done - let now = chrono::Utc::now().to_rfc3339(); - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", AttributeValue::S(msg.team_id.clone())) - .key("sk", AttributeValue::S(format!("PLAN#{}", msg.plan_id))) - .update_expression("SET #s = :s, executed_at = :ea, executed_by = :eb") - .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S("done".to_string())) - .expression_attribute_values(":ea", AttributeValue::S(now)) - .expression_attribute_values(":eb", AttributeValue::S(msg.triggered_by.clone())) - .send() - .await?; - info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "Plan execution complete"); + // The plan's state follows its tasks' work: filing tickets ends + // nothing (see `common::plan_state`). + super::plan_sync::refresh(state, &msg.team_id, &msg.plan_id).await; + if let Err(e) = mark_started(state, &msg.team_id, &msg.plan_id, &msg.triggered_by).await { + error!(plan_id = %msg.plan_id, error = %e, "Could not record when the plan started"); } Ok(()) } @@ -405,12 +367,13 @@ async fn link_to_live_run( Ok(()) } -/// The plan a run's ticket came from: `(plan_id, plan_title, plan_by)`. +/// The plan a run's ticket came from: `(plan_id, plan_title, plan_by, +/// task_id)`. pub(crate) async fn plan_of_ticket( state: &WorkerState, team_id: &str, ticket: &PlanTicket<'_>, -) -> Option<(String, String, String)> { +) -> Option<(String, String, String, String)> { let item = state .dynamo .get_item() @@ -428,7 +391,7 @@ pub(crate) async fn plan_of_ticket( .unwrap_or_default() }; let plan_id = s("plan_id"); - (!plan_id.is_empty()).then(|| (plan_id, s("plan_title"), s("plan_by"))) + (!plan_id.is_empty()).then(|| (plan_id, s("plan_title"), s("plan_by"), s("task_id"))) } /// Records that a ticket came from a plan's task, so the runs it starts say @@ -519,8 +482,9 @@ async fn link_ticket_to_plan( .key("team_id", AttributeValue::S(team_id.to_string())) .key("run_id", AttributeValue::S(run_id.to_string())) .condition_expression("attribute_exists(run_id)") - .expression_attribute_values(":p", AttributeValue::S(plan_id.to_string())); - let mut set = vec!["plan_id = :p"]; + .expression_attribute_values(":p", AttributeValue::S(plan_id.to_string())) + .expression_attribute_values(":t", AttributeValue::S(task_id.to_string())); + let mut set = vec!["plan_id = :p", "plan_task_id = :t"]; if !title.is_empty() { set.push("plan_title = :pt"); update = update.expression_attribute_values(":pt", AttributeValue::S(title.clone())); @@ -624,6 +588,79 @@ async fn get_task( })) } +/// A task whose ticket is filed. Its state comes from the ticket's runs +/// from here on (`common::plan_state`); filing it finishes nothing. Older +/// rows say `done`. +pub(crate) const FILED: &str = "filed"; + +const NO_JIRA_PROJECT: &str = + "No Jira project is set for this task or as the team's default, so its ticket could not be filed."; +const NO_JIRA_APP: &str = + "The CoderHelm Jira app is not connected (no create-ticket address), so the ticket could not be filed."; +const NO_REPO: &str = + "Neither the task nor the plan names a repository, so no issue could be opened."; + +/// Why the Jira app refused the ticket, in words. +fn jira_refused(status: u16, body: &str) -> String { + let body = body.split_whitespace().collect::>().join(" "); + let body = common::truncate_str(&body, 300); + if body.is_empty() { + format!("The Jira app refused the ticket (HTTP {status}).") + } else { + format!("The Jira app refused the ticket (HTTP {status}): {body}") + } +} + +/// A task that could not be filed, with why. +async fn set_task_failed( + state: &WorkerState, + team_id: &str, + plan_id: &str, + task_id: &str, + reason: &str, +) -> Result<(), Box> { + state + .dynamo + .update_item() + .table_name(&state.config.plans_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key( + "sk", + AttributeValue::S(format!("PLAN#{plan_id}#TASK#{task_id}")), + ) + .update_expression("SET #s = :s, failure_reason = :r") + .expression_attribute_names("#s", "status") + .expression_attribute_values(":s", AttributeValue::S("failed".to_string())) + .expression_attribute_values(":r", AttributeValue::S(reason.to_string())) + .send() + .await?; + Ok(()) +} + +/// Records who started the plan and when it first ran (kept from the first +/// time: drift is measured from it). +async fn mark_started( + state: &WorkerState, + team_id: &str, + plan_id: &str, + by: &str, +) -> Result<(), Box> { + let now = chrono::Utc::now().to_rfc3339(); + state + .dynamo + .update_item() + .table_name(&state.config.plans_table_name) + .key("pk", AttributeValue::S(team_id.to_string())) + .key("sk", AttributeValue::S(format!("PLAN#{plan_id}"))) + .condition_expression("attribute_exists(sk)") + .update_expression("SET executed_at = if_not_exists(executed_at, :ea), executed_by = if_not_exists(executed_by, :eb)") + .expression_attribute_values(":ea", AttributeValue::S(now)) + .expression_attribute_values(":eb", AttributeValue::S(by.to_string())) + .send() + .await?; + Ok(()) +} + async fn set_task_status( state: &WorkerState, team_id: &str, @@ -666,9 +703,11 @@ async fn update_task_with_issue( "sk", AttributeValue::S(format!("PLAN#{plan_id}#TASK#{task_id}")), ) - .update_expression("SET #s = :s, issue_number = :in, issue_url = :iu, completed_at = :ca") + .update_expression( + "SET #s = :s, issue_number = :in, issue_url = :iu, filed_at = :ca REMOVE failure_reason", + ) .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S("done".to_string())) + .expression_attribute_values(":s", AttributeValue::S(FILED.to_string())) .expression_attribute_values(":in", AttributeValue::N(issue_number.to_string())) .expression_attribute_values(":iu", AttributeValue::S(issue_url.to_string())) .expression_attribute_values(":ca", AttributeValue::S(now)) @@ -769,10 +808,10 @@ async fn update_task_with_jira( AttributeValue::S(format!("PLAN#{plan_id}#TASK#{task_id}")), ) .update_expression( - "SET #s = :s, jira_ticket_key = :jk, jira_ticket_url = :ju, completed_at = :ca", + "SET #s = :s, jira_ticket_key = :jk, jira_ticket_url = :ju, filed_at = :ca REMOVE failure_reason", ) .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S("done".to_string())) + .expression_attribute_values(":s", AttributeValue::S(FILED.to_string())) .expression_attribute_values(":jk", AttributeValue::S(ticket_key.to_string())) .expression_attribute_values(":ju", AttributeValue::S(ticket_url.to_string())) .expression_attribute_values(":ca", AttributeValue::S(now)) @@ -845,13 +884,14 @@ pub async fn continue_tasks( if project_key.is_empty() { error!(task_id, "No Jira project configured for task"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_JIRA_PROJECT) + .await?; continue; } let Some(ref url) = jira_create_url else { error!(task_id, "No Jira create-ticket URL configured"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_JIRA_APP).await?; continue; }; @@ -912,11 +952,14 @@ pub async fn continue_tasks( let status = resp.status().as_u16(); let body = resp.text().await.unwrap_or_default(); error!(task_id, status, body = %body, "Failed to create Jira ticket for waiting task"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = jira_refused(status, &body); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } Err(e) => { error!(task_id, error = %e, "Failed to call Forge create-ticket for waiting task"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = + format!("CoderHelm could not reach the Jira app to file the ticket: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } } } else { @@ -927,7 +970,7 @@ pub async fn continue_tasks( .unwrap_or(&plan_repo); if task_repo.is_empty() { error!(task_id, "No repo configured for task or plan"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, NO_REPO).await?; continue; } @@ -981,7 +1024,8 @@ pub async fn continue_tasks( .await { error!(task_id, issue_number, error = %e, "Failed to add coderhelm label"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed") + let reason = format!("Issue #{issue_number} was opened, but GitHub refused the coderhelm label that starts its run: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason) .await?; continue; } @@ -1001,49 +1045,14 @@ pub async fn continue_tasks( } Err(e) => { error!(task_id, error = %e, "Failed to create GitHub issue for waiting task"); - set_task_status(state, &msg.team_id, &msg.plan_id, task_id, "failed").await?; + let reason = format!("GitHub refused the issue for this task: {e}"); + set_task_failed(state, &msg.team_id, &msg.plan_id, task_id, &reason).await?; } } } } - // Check if all plan tasks are now complete (no more waiting) - let all_tasks_result = state - .dynamo - .query() - .table_name(&state.config.plans_table_name) - .key_condition_expression("pk = :pk AND begins_with(sk, :sk_prefix)") - .expression_attribute_values(":pk", AttributeValue::S(msg.team_id.clone())) - .expression_attribute_values( - ":sk_prefix", - AttributeValue::S(format!("PLAN#{}#TASK#", msg.plan_id)), - ) - .send() - .await?; - - let any_still_waiting = all_tasks_result.items().iter().any(|item| { - item.get("status") - .and_then(|v| v.as_s().ok()) - .map(|s| s == "waiting") - .unwrap_or(false) - }); - - if !any_still_waiting { - let now = chrono::Utc::now().to_rfc3339(); - state - .dynamo - .update_item() - .table_name(&state.config.plans_table_name) - .key("pk", AttributeValue::S(msg.team_id.clone())) - .key("sk", AttributeValue::S(format!("PLAN#{}", msg.plan_id))) - .update_expression("SET #s = :s, executed_at = :ea") - .expression_attribute_names("#s", "status") - .expression_attribute_values(":s", AttributeValue::S("done".to_string())) - .expression_attribute_values(":ea", AttributeValue::S(now)) - .send() - .await?; - info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "All plan tasks complete — plan marked done"); - } + super::plan_sync::refresh(state, &msg.team_id, &msg.plan_id).await; Ok(()) } diff --git a/services/worker/src/passes/plan_sync.rs b/services/worker/src/passes/plan_sync.rs new file mode 100644 index 000000000..42099dc07 --- /dev/null +++ b/services/worker/src/passes/plan_sync.rs @@ -0,0 +1,45 @@ +//! Keeps a plan's task states following the work (`common::plan_sync`): +//! every run status the worker writes refreshes the plan the run belongs to. + +use aws_sdk_dynamodb::types::AttributeValue; +use tracing::warn; + +use crate::WorkerState; + +/// The tables the plan state lives in. +pub fn store(state: &WorkerState) -> common::plan_sync::Dynamo { + common::plan_sync::Dynamo { + dynamo: state.dynamo.clone(), + plans_table: state.config.plans_table_name.clone(), + runs_table: state.config.runs_table_name.clone(), + settings_table: state.config.settings_table_name.clone(), + } +} + +/// Re-derives a plan's state and its tasks'. Best effort: a failure is +/// logged and the next event or page view derives it again. +pub async fn refresh(state: &WorkerState, team_id: &str, plan_id: &str) { + let now = chrono::Utc::now().to_rfc3339(); + if let Err(e) = common::plan_sync::refresh(&store(state), team_id, plan_id, &now).await { + warn!(team_id, plan_id, error = %e, "Could not refresh the plan's state"); + } +} + +/// A run's status changed: refresh its plan, when it has one. +pub async fn on_run(state: &WorkerState, team_id: &str, run_id: &str) { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .key("team_id", AttributeValue::S(team_id.into())) + .key("run_id", AttributeValue::S(run_id.into())) + .projection_expression("plan_id") + .send() + .await + .ok() + .and_then(|r| r.item); + let Some((plan_id, _)) = item.as_ref().and_then(common::plan_sync::plan_of_run) else { + return; + }; + refresh(state, team_id, &plan_id).await; +} diff --git a/services/worker/src/passes/webhooks.rs b/services/worker/src/passes/webhooks.rs index a87371e59..c81927378 100644 --- a/services/worker/src/passes/webhooks.rs +++ b/services/worker/src/passes/webhooks.rs @@ -92,6 +92,8 @@ pub fn run_event_for(status: &str) -> Option<&'static str> { /// Emits a `run.*` event for a run, read back from its record so every run /// event carries the same fields. `status` is what the work just wrote. pub async fn emit_run(state: &WorkerState, team_id: &str, run_id: &str, status: &str) { + // The run's plan task follows its status (`common::plan_state`). + super::plan_sync::on_run(state, team_id, run_id).await; let Some(event_type) = run_event_for(status) else { return; };