From cf89339e804dfacae60028c8b7fc03c371866716 Mon Sep 17 00:00:00 2001 From: Kirk Marple Date: Wed, 18 Nov 2026 23:32:26 -0800 Subject: [PATCH 1/8] Route Pendulum supervision and issue admission before implementation (#649) --- bench/skills.json | 24 ++++++++++++------------ docs/USAGE.md | 2 +- plugin/skills/pendulum-file/SKILL.md | 12 +++++++----- plugin/skills/pendulum-file/reference.md | 6 ++++-- plugin/skills/pendulum-run/SKILL.md | 10 ++++++---- plugin/skills/pendulum-serve/SKILL.md | 10 ++++++++-- 6 files changed, 38 insertions(+), 26 deletions(-) diff --git a/bench/skills.json b/bench/skills.json index 6355f5da..1fd61ba4 100644 --- a/bench/skills.json +++ b/bench/skills.json @@ -31,14 +31,14 @@ } }, "pendulum-file": { - "sha256": "adb4a849f35b2ae82dc64b948f28307ffc9cea9636b39ecba61d83e045baeab7", - "lines": 46, - "words": 698, + "sha256": "ce0048077bf7e354cee950dfcecd617a460556fa9271109d98f2d4246e8fd258", + "lines": 48, + "words": 689, "files": { "reference.md": { - "sha256": "0fe89a54b00271a37ca5a88370cc0cb780e54982e4f12cc0c07845ccd020726a", - "lines": 65, - "words": 1315 + "sha256": "06b3858e1559922eef5039dbc680927785e537cc508fa9e03f6ca51ab49844e9", + "lines": 67, + "words": 1374 } } }, @@ -147,9 +147,9 @@ } }, "pendulum-run": { - "sha256": "f3c10fe6bbd65f65eed377bddee3cc892b8a13f464e1521eb48e75c7e83cf409", - "lines": 51, - "words": 697, + "sha256": "c4159d5e9963a1f89f67e7a4b90ef712a3a9a38af1f15448cfd2ede5f6ed035e", + "lines": 53, + "words": 685, "files": { "reference.md": { "sha256": "f2108baad9ce2f7c8e223fab1af4648c562cd10a3b16f7cdda430ba44a9921bf", @@ -171,9 +171,9 @@ } }, "pendulum-serve": { - "sha256": "0e096df2718d379c7b7aa42cf7362caa06568235d1684136e539d4dc58c50c1d", - "lines": 31, - "words": 611, + "sha256": "2aaf29789252ab8f338ff17d39048b08b608be824422d0c5b8c281cc39030e1b", + "lines": 37, + "words": 672, "files": { "reference.md": { "sha256": "77f3d282e3f1b96115b51261f19fbe1aa287c172711fed774f5d38862d322d7e", diff --git a/docs/USAGE.md b/docs/USAGE.md index 62ccafa3..712c6cb9 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -112,7 +112,7 @@ Each step is one action on GitHub. Where a skill is named, a plain-words request - **Draft.** An issue with the `pendulum:draft` label is a draft: Pendulum never runs it, on any route, even with `pendulum:objective` on it too (the draft label wins: the dispatcher's log lists it as a draft, and a launch, `pendulum run` or a session's `pendulum issue` refuses it). Nothing is dispatched, claimed or spent for it. The pendulum-file skill offers it beside starting at once: it shows the issue and asks whether to start it now, save it as a draft, or keep discussing. "Let's keep working on Pendulum Objective #12" (the same skill) loads the draft from GitHub to refine it with you and saves the changes back to the issue only on your yes. Edit a draft freely: before its first plan, an edit is simply the text the run starts from. -- **Start.** Applying `pendulum:objective` starts the Objective: the dispatcher picks it up on the label's own event, else on its ten-minute cron, and in local mode on `pendulum serve`'s next tick. To start a draft, take `pendulum:draft` off and apply `pendulum:objective`, or ask "Start Pendulum Objective #12" (the pendulum-file skill): on your yes it does both, after the trust check a new Objective gets (its author, its last editor and its latest title renamer can push, or are maintainers the workflow names; otherwise it refuses and says who). Starting a draft counts as re-applying the label, whichever way it is done: an edit made while it was a draft, even after an earlier plan, is planned from. A draft started, then edited, follows the edit rules below once its plan exists. +- **Start.** Applying `pendulum:objective` admits the Objective to the queue. The dispatcher starts eligible work when there is capacity. It checks on the label's event or its ten-minute cron on Actions, and on `pendulum serve`'s next tick locally. When you ask a session to hand an existing issue to Pendulum, the filing skill checks the issue and its readiness first. The worker handles code discovery and implementation after dispatch. To start a draft, take `pendulum:draft` off and apply `pendulum:objective`, or ask "Start Pendulum Objective #12". On your yes, the filing skill does both after the trust check. The issue's author, last editor and latest title renamer must be able to push or be maintainers the workflow names. Starting a draft counts as re-applying the label. The next plan uses edits made while it was a draft. Once that plan exists, the edit rules below apply. - **Edit.** Edit the issue freely until the first work stage reads it. After its plan, an edit that only fixes typos, formatting or wording keeps the plan; any other edit Blocks the Objective at its next stage, and re-applying `pendulum:objective` plans again from the new text (Edit an Objective, below). diff --git a/plugin/skills/pendulum-file/SKILL.md b/plugin/skills/pendulum-file/SKILL.md index aa2f993d..6cd6e2c7 100644 --- a/plugin/skills/pendulum-file/SKILL.md +++ b/plugin/skills/pendulum-file/SKILL.md @@ -1,11 +1,13 @@ --- name: pendulum-file -description: "Write, refine and start Pendulum Objectives: turn what the user wants built into a GitHub issue with a goal and acceptance entries, created on the user's yes started (pendulum:objective) or as a draft (pendulum:draft); or, by issue number, refine or start a draft. Use when the user asks to file, draft, refine, keep working on or start a Pendulum Objective, or asks Pendulum to build something. Not for starting over one that already ran (pendulum-restart), resuming a Blocked one (pendulum-status) or running one on this machine (pendulum-run)." +description: "Read issue readiness before source discovery, then draft, refine or admit an Objective on the user's yes. Use when the user wants Pendulum to build something or take an existing GitHub issue, even without naming a skill. Not for executing an admitted Objective or resuming a run." --- # /pendulum:pendulum-file [issue] -An Objective is a GitHub issue that is the whole specification: the worker cannot ask anything while it runs. Write the issue, show it, and write to GitHub only on a yes. `` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node /scripts/local.mjs` instead. +The issue is the whole specification. Read its text, labels and readiness before source discovery. Ask only for what the Objective needs. The dispatched worker plans the change, owns its branch and edits, and delegates implementation. Write to GitHub only on a yes. + +`` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node /scripts/local.mjs` instead. ## Write the issue @@ -25,7 +27,7 @@ Ask only for what the issue cannot be written without. Where the user left a cho ## Create it -Show the title, body and labels, and offer: +Show the title, body and labels. Offer: - **Start it now:** write the line `pendulum zone` prints (this machine's zone, for the Objective's times), a blank line and the body to a temporary file, and run `gh issue create --repo OWNER/NAME --title "" --body-file <file> --label pendulum:objective`. Add `--label pendulum:local` for the user's own machine's loop, and `P0`, `P1` or `P2` for a priority. One that must follow another Objective gets the label only after its dependency (reference.md, Blocking Objectives). - **Save it as a draft:** the same command with `--label pendulum:draft` in its place; Pendulum never runs a draft. A missing label: reference.md, The draft label. @@ -38,8 +40,8 @@ Create any harness, model or host label first (`gh label create <label> --repo O Run `gh issue view <issue> --repo OWNER/NAME --json number,title,body,state,labels` and show it. Closed: say so and stop. Do what the user asked: - **Refine it:** as Write the issue, keeping the text that still fits; save it back on a yes ([reference.md](reference.md), Refine a draft). A started one (`pendulum:objective`, no `pendulum:draft`) Blocks on an edit after its plan: say so first. -- **Start it:** a draft, or an issue with neither label, after the trust check ([reference.md](reference.md), Start a draft). One started already: pendulum-status resumes a Blocked one or answers a Question; pendulum-restart starts it over. +- **Start it:** admit a draft or unlabelled issue after the trust check ([reference.md](reference.md), Start a draft). Keep open dependencies in place. Follow admitted work through its dispatcher or existing run. Use pendulum-status for a Blocked one or a Question, and pendulum-restart only on request. ## After -Print the issue's URL. Started: its progress comment shows where it is until it merges, Blocks or asks; pendulum-status says where it stands. A draft: "Let's keep working on Pendulum Objective <number>" or "Start Pendulum Objective <number>" comes back here. +Print the issue's URL. Admission puts it in the queue. Report it as running once Pendulum records the start, and point to the run, progress comment or verified active claim. Use pendulum-status to follow it or pendulum-serve for the existing local queue. A draft comes back here to refine or start. diff --git a/plugin/skills/pendulum-file/reference.md b/plugin/skills/pendulum-file/reference.md index 14035f28..5e06cf6e 100644 --- a/plugin/skills/pendulum-file/reference.md +++ b/plugin/skills/pendulum-file/reference.md @@ -51,6 +51,8 @@ Starting a draft takes `pendulum:draft` off and applies `pendulum:objective`; th **Check the issue.** `pendulum:objective` without `pendulum:draft`: it is started already; do not start it again. Say so and point to the next step that fits: the pendulum-status skill resumes a Blocked one or answers a Question, and the pendulum-restart skill starts one over from its issue's current text. No `pendulum:draft`: not a draft, but starting it is the same step. No goal or no acceptance entries (SKILL.md's shape): say so, and offer to refine it first. +Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/dependencies/blocked_by --jq '.[] | select(.state == "open") | .number'`. On a GitHub host without issue dependencies, use the body fallback described under Blocking Objectives. Report the dependency as a queue condition and preserve the link. + **Check trust.** Pendulum acts on an issue only when its author, its last editor once the body was edited, and whoever made the latest rename once the title was renamed, is a person who can push to the repository or a maintainer the workflow names (`PENDULUM_NOTIFY` or `PENDULUM_MAINTAINERS` in `.github/workflows/pendulum.yml`, as `login#id`). Otherwise the run Blocks before any model reads the text, so check first: 1. `gh api graphql -f query='query($o:String!,$n:String!,$i:Int!){repository(owner:$o,name:$n){issue(number:$i){lastEditedAt author{__typename login} editor{__typename login} title timelineItems(itemTypes:[RENAMED_TITLE_EVENT],last:1){nodes{...on RenamedTitleEvent{actor{__typename login} currentTitle}}}}}}' -f o=OWNER -f n=NAME -F i=<issue>`. The body was edited when `lastEditedAt` or `editor` is set; then the editor counts too, and an editor that reads as null (a deleted account) fails. The title was renamed when `timelineItems` has a node; then its actor counts too, and one that reads as null, or a `currentTitle` other than `title`, fails. @@ -59,6 +61,6 @@ Starting a draft takes `pendulum:draft` off and applies `pendulum:objective`; th When a check fails, or a login cannot be read, do not start it. Say who and why: an author who fails means a person who can push files it again as a new issue; a last editor who fails means a person who can push reads the body and saves it, becoming its last editor; a renamer who fails means a person who can push reads the title and changes it (the same title records no rename). -**Ask.** Show the number, title and labels, the people the trust check read, and what starting does: the run starts within seconds on Actions (on the ten-minute cron at the latest; in local mode on `pendulum serve`'s next tick), and one comment on the issue shows its progress. An edit after its plan is made Blocks it at its next stage ([Edit an Objective](https://github.com/clockgrove/pendulum/blob/v0.10.0/docs/USAGE.md#edit-an-objective)). Ask for a yes. +**Ask.** Show the number, title and labels, the people the trust check read, and what starting does. Applying the label admits the issue. The dispatcher checks it on the label event or cron on Actions, or on `pendulum serve`'s next tick locally. It still waits for any open dependency and for capacity. One comment on the issue shows the run's progress. An edit after its plan is made Blocks it at its next stage ([Edit an Objective](https://github.com/clockgrove/pendulum/blob/v0.10.0/docs/USAGE.md#edit-an-objective)). Ask for a yes. -**Start it.** On a yes, when the issue carries `pendulum:objective` too, first run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:objective`, so the start applies the label afresh. Then run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:draft --add-label pendulum:objective`; for an issue without `pendulum:draft`, drop `--remove-label pendulum:draft`, since `gh` refuses to remove a label the repository does not have. Say it is started and print its URL. +**Start it.** On a yes, when the issue carries `pendulum:objective` too, first run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:objective`, so the start applies the label afresh. Then run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:draft --add-label pendulum:objective`; for an issue without `pendulum:draft`, drop `--remove-label pendulum:draft`, since `gh` refuses to remove a label the repository does not have. Print its URL and report its observed state as described in SKILL.md. diff --git a/plugin/skills/pendulum-run/SKILL.md b/plugin/skills/pendulum-run/SKILL.md index bae0782d..cb84bbff 100644 --- a/plugin/skills/pendulum-run/SKILL.md +++ b/plugin/skills/pendulum-run/SKILL.md @@ -1,12 +1,14 @@ --- name: pendulum-run -description: "Run one Pendulum Objective of the current repository on this machine by issue number, on the user's yes: by default in local mode (`pendulum run <issue> --wait`: sandboxed, the Action's worker, reviewer and merge), or with --here in this session itself, handing the branch to Pendulum to push only on a second yes. Use when the user asks to run, work or build one Pendulum Objective on their machine. Not for working the whole queue (pendulum-serve) or kicking the Action's dispatcher (pendulum-kick)." +description: "Run one admitted Pendulum Objective by issue number on the user's yes. Use when explicitly asked for a sandboxed local run or in-session --here run. Get a second yes before --here delivery. Not for admitting an issue (pendulum-file) or working the queue (pendulum-serve)." --- # /pendulum:pendulum-run <issue> [--here] `<plugin root>` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node <plugin root>/scripts/local.mjs` instead. +Read the issue and its Pendulum state before opening source files or preparing a branch. For a draft or an issue without `pendulum:objective`, use pendulum-file to admit it first. If Pendulum already owns an active or paused run, follow it or use its supported resume operation. + ## Local mode (the default) ### Ask @@ -23,12 +25,12 @@ On a yes, run `pendulum run <issue> --wait` from the repository's clone. It need ## In this session (--here) -Work the Objective here, unsandboxed, when the user wants to watch or steer. +Work the Objective here, unsandboxed, when the user explicitly selects this route. Start implementation after the preconditions and task-card setup. ### Preconditions +- The issue is open, carries `pendulum:objective`, has no `pendulum:draft` or [open dependency](../pendulum-file/reference.md#start-a-draft), and has no active or paused run. Check before preparing a branch. - The current directory is a clone of the target repository with its toolchain installed, and either local mode's token or a `gh` login for `pendulum deliver`. When `.github/workflows/pendulum.yml` exists, read its `env:` block: `PENDULUM_VALIDATION`, `PENDULUM_BUDGET_COMMAND`, `PENDULUM_PROTECTED_PATHS`, `PENDULUM_MAX_USD`, `PENDULUM_TIMEOUT_MINUTES`, `PENDULUM_CI_CHECKS`. Otherwise ask once for whatever is missing, before the run starts. Say the budget (`PENDULUM_MAX_USD`, else the user's): this session keeps to it itself. -- The issue carries `pendulum:objective` and is open; else stop and say so. - Never on Pendulum's own repository (`clockgrove/pendulum`); stop and say so. ### Set up @@ -41,7 +43,7 @@ The rendered task card is your instructions, `$PENDULUM_IN/issue.md` verbatim th ### Hand off to Pendulum -Show the user the branch's commits (`git log --oneline origin/<default branch>..HEAD`), the PR title (the first line of `$PENDULUM_OUT/pr.md`) and the exit record, and say what `pendulum deliver <issue>` does: it runs the trust check again (a refusal Blocks, nothing pushed), refuses a branch that touches a protected path, pushes `pendulum/<issue>`, posts the plan, the PR, the replies and the note as the user, and applies the exit record: a delivered PR is marked ready and labelled `pendulum:review`, which, when `.github/workflows/pendulum.yml` exists, fires the Action's review job (with `auto_merge` on, the Action merges it once green). Ask for a yes. +Show the commits (`git log --oneline origin/<default branch>..HEAD`), PR title (first line of `$PENDULUM_OUT/pr.md`) and exit record. Explain that `pendulum deliver <issue>` rechecks trust and protected paths, pushes `pendulum/<issue>`, posts the PR and hand-off records, and applies the exit. A delivered PR becomes ready with `pendulum:review`. The Action reviews it and merges once green if `auto_merge` is on. Ask for a yes. On a yes, run `pendulum deliver <issue>` from the clone. Without the workflow, say that the PR waits for the pendulum-review-here skill and a human merge. diff --git a/plugin/skills/pendulum-serve/SKILL.md b/plugin/skills/pendulum-serve/SKILL.md index 8f0e5cba..c5fcc904 100644 --- a/plugin/skills/pendulum-serve/SKILL.md +++ b/plugin/skills/pendulum-serve/SKILL.md @@ -1,11 +1,17 @@ --- name: pendulum-serve -description: "Start Pendulum's local loop for the current repository on this machine (`pendulum serve`) on the user's yes: it takes the Objectives labelled pendulum:local (every one where no Action is active), works, reviews and merges them in sandboxes on this machine's harness login, and resumes its own paused work first; also supervises the queue with `pendulum wait`. Use when the user asks to run Pendulum locally, serve, or work the queue on their machine. Not for one Objective by number (pendulum-run) or kicking the Action's dispatcher (pendulum-kick)." +description: "Supervise Pendulum's local queue and leave implementation to its dispatched worker. Use when asked to keep the queue moving, use spare capacity, pick up eligible work, or run `pendulum serve` locally on the user's yes. Not for admitting an issue (pendulum-file), running one Objective (pendulum-run), or kicking Actions." --- # /pendulum:pendulum-serve -Start local mode's loop for the repository whose clone is the current directory. `<plugin root>` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node <plugin root>/scripts/local.mjs` instead. It applies the dispatcher's rules every 30 seconds (order, caps, blocking, send-backs, Done) and runs the picks here, as many as the machine's stage budget, its load and `PENDULUM_LOCAL_MAX_CONCURRENT` allow, reviews before new work and this machine's paused Objectives before both. +The loop checks the current repository every 30 seconds. It resumes this machine's paused Objectives first, then reviews, then new work, within the machine's capacity and `PENDULUM_LOCAL_MAX_CONCURRENT`. `<plugin root>` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node <plugin root>/scripts/local.mjs` instead. + +## Supervise the queue + +- Use pendulum-status and the loop's output. For a draft or an open dependency, name what keeps the issue ineligible and look for eligible work. Use pendulum-file for requested admission. `pendulum:local` selects the route. +- Leave eligible work with the existing dispatcher. Cite a recorded stage start, Pendulum run or progress comment, or verified active claim before reporting that work began. A Running label alone can precede the claim. Follow active work or use the supported lifecycle operation for paused work. +- Limit supervision to issue and queue operations. Leave source discovery, branches, edits and delegation to the worker with a rendered task card. Use pendulum-run for an explicit single-Objective run, including `--here` when the user selects it and its preconditions pass. ## Start From fdd4c1dc1d51279f0b700d94ffa84be6219d1846 Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Wed, 18 Nov 2026 23:34:42 -0800 Subject: [PATCH 2/8] Preserve queue readiness and ownership during skill handoff (#649) --- bench/skills.json | 14 +++++++------- plugin/skills/pendulum-file/reference.md | 2 +- plugin/skills/pendulum-run/SKILL.md | 6 +++--- plugin/skills/pendulum-run/reference.md | 8 +++++++- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/bench/skills.json b/bench/skills.json index 1fd61ba4..5e51e967 100644 --- a/bench/skills.json +++ b/bench/skills.json @@ -36,9 +36,9 @@ "words": 689, "files": { "reference.md": { - "sha256": "06b3858e1559922eef5039dbc680927785e537cc508fa9e03f6ca51ab49844e9", + "sha256": "36be69ca498e7b5c168674210b8b8fbb5a972a68162466c348f6234a0987717c", "lines": 67, - "words": 1374 + "words": 1356 } } }, @@ -147,14 +147,14 @@ } }, "pendulum-run": { - "sha256": "c4159d5e9963a1f89f67e7a4b90ef712a3a9a38af1f15448cfd2ede5f6ed035e", + "sha256": "df1eca1d80fc1b27306633f143c5a409bcf3fe37d292a233bdf809df0598686f", "lines": 53, - "words": 685, + "words": 672, "files": { "reference.md": { - "sha256": "f2108baad9ce2f7c8e223fab1af4648c562cd10a3b16f7cdda430ba44a9921bf", - "lines": 17, - "words": 266 + "sha256": "3c68ad93139560ddd7e07f3e698b2ddd61ba5edbf8695402644ffd0930ad1ba8", + "lines": 23, + "words": 370 } } }, diff --git a/plugin/skills/pendulum-file/reference.md b/plugin/skills/pendulum-file/reference.md index 5e06cf6e..4d038d06 100644 --- a/plugin/skills/pendulum-file/reference.md +++ b/plugin/skills/pendulum-file/reference.md @@ -49,7 +49,7 @@ Then offer the next step: keep working on it, leave it as a draft, or start it ( Starting a draft takes `pendulum:draft` off and applies `pendulum:objective`; the dispatcher then picks it up like a new Objective. A draft is never run, on any route, even with `pendulum:objective` on it too. Confirm first: a started Objective runs unattended and spends model budget. -**Check the issue.** `pendulum:objective` without `pendulum:draft`: it is started already; do not start it again. Say so and point to the next step that fits: the pendulum-status skill resumes a Blocked one or answers a Question, and the pendulum-restart skill starts one over from its issue's current text. No `pendulum:draft`: not a draft, but starting it is the same step. No goal or no acceptance entries (SKILL.md's shape): say so, and offer to refine it first. +**Check the issue.** `pendulum:objective` without `pendulum:draft` means already admitted. Keep the labels as they are, check dependencies and readiness, then follow the configured dispatcher or existing run. Use pendulum-status for a Blocked one or a Question, and pendulum-restart only for a requested restart. A draft or unlabelled issue without a goal or acceptance entries needs refinement first (SKILL.md). Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/dependencies/blocked_by --jq '.[] | select(.state == "open") | .number'`. On a GitHub host without issue dependencies, use the body fallback described under Blocking Objectives. Report the dependency as a queue condition and preserve the link. diff --git a/plugin/skills/pendulum-run/SKILL.md b/plugin/skills/pendulum-run/SKILL.md index cb84bbff..a3352a69 100644 --- a/plugin/skills/pendulum-run/SKILL.md +++ b/plugin/skills/pendulum-run/SKILL.md @@ -7,7 +7,7 @@ description: "Run one admitted Pendulum Objective by issue number on the user's `<plugin root>` is `${CLAUDE_PLUGIN_ROOT}` in Claude Code, elsewhere two directories above this SKILL.md; where `pendulum` is not on PATH (only Claude Code puts the plugin's `bin/` there), run `node <plugin root>/scripts/local.mjs` instead. -Read the issue and its Pendulum state before opening source files or preparing a branch. For a draft or an issue without `pendulum:objective`, use pendulum-file to admit it first. If Pendulum already owns an active or paused run, follow it or use its supported resume operation. +Read the issue and its state before exploring source or preparing a branch. Follow an active or paused run through its existing lifecycle. For a draft or unlabelled issue, use pendulum-file when the user wants dispatcher admission. ## Local mode (the default) @@ -29,7 +29,7 @@ Work the Objective here, unsandboxed, when the user explicitly selects this rout ### Preconditions -- The issue is open, carries `pendulum:objective`, has no `pendulum:draft` or [open dependency](../pendulum-file/reference.md#start-a-draft), and has no active or paused run. Check before preparing a branch. +- Verify eligibility and ownership using [In-session readiness](reference.md#in-session-readiness) before preparing a branch. - The current directory is a clone of the target repository with its toolchain installed, and either local mode's token or a `gh` login for `pendulum deliver`. When `.github/workflows/pendulum.yml` exists, read its `env:` block: `PENDULUM_VALIDATION`, `PENDULUM_BUDGET_COMMAND`, `PENDULUM_PROTECTED_PATHS`, `PENDULUM_MAX_USD`, `PENDULUM_TIMEOUT_MINUTES`, `PENDULUM_CI_CHECKS`. Otherwise ask once for whatever is missing, before the run starts. Say the budget (`PENDULUM_MAX_USD`, else the user's): this session keeps to it itself. - Never on Pendulum's own repository (`clockgrove/pendulum`); stop and say so. @@ -45,7 +45,7 @@ The rendered task card is your instructions, `$PENDULUM_IN/issue.md` verbatim th Show the commits (`git log --oneline origin/<default branch>..HEAD`), PR title (first line of `$PENDULUM_OUT/pr.md`) and exit record. Explain that `pendulum deliver <issue>` rechecks trust and protected paths, pushes `pendulum/<issue>`, posts the PR and hand-off records, and applies the exit. A delivered PR becomes ready with `pendulum:review`. The Action reviews it and merges once green if `auto_merge` is on. Ask for a yes. -On a yes, run `pendulum deliver <issue>` from the clone. Without the workflow, say that the PR waits for the pendulum-review-here skill and a human merge. +On a yes, recheck that no Pendulum run owns the issue, then run `pendulum deliver <issue>` from the clone. Without the workflow, say that the PR waits for the pendulum-review-here skill and a human merge. ### After diff --git a/plugin/skills/pendulum-run/reference.md b/plugin/skills/pendulum-run/reference.md index 159d6075..380200d7 100644 --- a/plugin/skills/pendulum-run/reference.md +++ b/plugin/skills/pendulum-run/reference.md @@ -1,4 +1,10 @@ -# Render the task card and the hand-off directories +# In-session readiness + +Check that the issue is open, carries `pendulum:objective`, and has neither `pendulum:draft` nor an [open dependency](../pendulum-file/reference.md#start-a-draft). Applying the Objective label admits it to the dispatcher. For a draft or unlabelled issue, report its state and use pendulum-file only if the user wants that dispatcher handoff. + +Check issue state with pendulum-status and the configured route's dispatcher records. Follow an active or paused run. If the configured loop or Action can pick up the issue during this session, leave it to that dispatcher. An eligible issue with no recorded claim yet can still be picked up. In-session setup does not reserve the Objective. + +## Render the task card and the hand-off directories Read `<plugin root>/templates/task-card.md` and fill the placeholders: From fa2ca1fe399fbffae2204b4a88d4f22a919eb6bb Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Wed, 18 Nov 2026 23:35:05 -0800 Subject: [PATCH 3/8] Use current start evidence when supervising the queue (#649) --- bench/skills.json | 12 ++++++------ plugin/skills/pendulum-file/reference.md | 4 ++-- plugin/skills/pendulum-run/SKILL.md | 2 +- plugin/skills/pendulum-serve/SKILL.md | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/bench/skills.json b/bench/skills.json index 5e51e967..0fdad552 100644 --- a/bench/skills.json +++ b/bench/skills.json @@ -36,9 +36,9 @@ "words": 689, "files": { "reference.md": { - "sha256": "36be69ca498e7b5c168674210b8b8fbb5a972a68162466c348f6234a0987717c", + "sha256": "4c38ea64c67b736af863ca8d38a503b0344eede6632af9b4be4532e06cf57134", "lines": 67, - "words": 1356 + "words": 1364 } } }, @@ -147,9 +147,9 @@ } }, "pendulum-run": { - "sha256": "df1eca1d80fc1b27306633f143c5a409bcf3fe37d292a233bdf809df0598686f", + "sha256": "baa4bd811618416dd11be7882856482525944ffb09c15a3f0ff822cd4f7cceb4", "lines": 53, - "words": 672, + "words": 668, "files": { "reference.md": { "sha256": "3c68ad93139560ddd7e07f3e698b2ddd61ba5edbf8695402644ffd0930ad1ba8", @@ -171,9 +171,9 @@ } }, "pendulum-serve": { - "sha256": "2aaf29789252ab8f338ff17d39048b08b608be824422d0c5b8c281cc39030e1b", + "sha256": "8bc302bb5e8c7640043bb5382998e65f8023b7b372f3d10309563fe42c8c7853", "lines": 37, - "words": 672, + "words": 675, "files": { "reference.md": { "sha256": "77f3d282e3f1b96115b51261f19fbe1aa287c172711fed774f5d38862d322d7e", diff --git a/plugin/skills/pendulum-file/reference.md b/plugin/skills/pendulum-file/reference.md index 4d038d06..f2bc6a2a 100644 --- a/plugin/skills/pendulum-file/reference.md +++ b/plugin/skills/pendulum-file/reference.md @@ -16,7 +16,7 @@ An Objective's sandboxes reach GitHub, the npm and Yarn registries and the hosts ## Blocking Objectives -When the work must follow another Objective `<N>`, make `<N>` block it as a GitHub issue dependency before the issue carries `pendulum:objective`: that label starts it at once, and the dispatcher reads the dependency, not the body (a `Blocked by #N` line counts only on a host without dependencies). In this order: +When the work must follow another Objective `<N>`, make `<N>` block it as a GitHub issue dependency before applying `pendulum:objective`. The label admits it to the queue. The dispatcher reads the dependency, not the body (a `Blocked by #N` line counts only on a host without dependencies). In this order: 1. Create the issue with the "Start it now" command less `--label pendulum:objective` (a draft keeps `--label pendulum:draft`). 2. Add the dependency: `gh api -X POST repos/OWNER/NAME/issues/<new>/dependencies/blocked_by -F issue_id=$(gh api repos/OWNER/NAME/issues/<N> --jq .id)`. @@ -51,7 +51,7 @@ Starting a draft takes `pendulum:draft` off and applies `pendulum:objective`; th **Check the issue.** `pendulum:objective` without `pendulum:draft` means already admitted. Keep the labels as they are, check dependencies and readiness, then follow the configured dispatcher or existing run. Use pendulum-status for a Blocked one or a Question, and pendulum-restart only for a requested restart. A draft or unlabelled issue without a goal or acceptance entries needs refinement first (SKILL.md). -Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/dependencies/blocked_by --jq '.[] | select(.state == "open") | .number'`. On a GitHub host without issue dependencies, use the body fallback described under Blocking Objectives. Report the dependency as a queue condition and preserve the link. +Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/dependencies/blocked_by --jq '.[] | select(.state == "open") | .number'`. On a GitHub host without issue dependencies, use the body fallback described under Blocking Objectives. If the read fails, report that readiness is unknown. Report any open dependency as a queue condition and preserve the link. **Check trust.** Pendulum acts on an issue only when its author, its last editor once the body was edited, and whoever made the latest rename once the title was renamed, is a person who can push to the repository or a maintainer the workflow names (`PENDULUM_NOTIFY` or `PENDULUM_MAINTAINERS` in `.github/workflows/pendulum.yml`, as `login#id`). Otherwise the run Blocks before any model reads the text, so check first: diff --git a/plugin/skills/pendulum-run/SKILL.md b/plugin/skills/pendulum-run/SKILL.md index a3352a69..4e748474 100644 --- a/plugin/skills/pendulum-run/SKILL.md +++ b/plugin/skills/pendulum-run/SKILL.md @@ -45,7 +45,7 @@ The rendered task card is your instructions, `$PENDULUM_IN/issue.md` verbatim th Show the commits (`git log --oneline origin/<default branch>..HEAD`), PR title (first line of `$PENDULUM_OUT/pr.md`) and exit record. Explain that `pendulum deliver <issue>` rechecks trust and protected paths, pushes `pendulum/<issue>`, posts the PR and hand-off records, and applies the exit. A delivered PR becomes ready with `pendulum:review`. The Action reviews it and merges once green if `auto_merge` is on. Ask for a yes. -On a yes, recheck that no Pendulum run owns the issue, then run `pendulum deliver <issue>` from the clone. Without the workflow, say that the PR waits for the pendulum-review-here skill and a human merge. +On a yes, recheck eligibility and ownership, then run `pendulum deliver <issue>` from the clone. Without the workflow, say that the PR waits for the pendulum-review-here skill and a human merge. ### After diff --git a/plugin/skills/pendulum-serve/SKILL.md b/plugin/skills/pendulum-serve/SKILL.md index c5fcc904..358caa94 100644 --- a/plugin/skills/pendulum-serve/SKILL.md +++ b/plugin/skills/pendulum-serve/SKILL.md @@ -9,8 +9,8 @@ The loop checks the current repository every 30 seconds. It resumes this machine ## Supervise the queue -- Use pendulum-status and the loop's output. For a draft or an open dependency, name what keeps the issue ineligible and look for eligible work. Use pendulum-file for requested admission. `pendulum:local` selects the route. -- Leave eligible work with the existing dispatcher. Cite a recorded stage start, Pendulum run or progress comment, or verified active claim before reporting that work began. A Running label alone can precede the claim. Follow active work or use the supported lifecycle operation for paused work. +- Use pendulum-status and the loop's output. For a draft or an [open dependency](../pendulum-file/reference.md#start-a-draft), name what keeps the issue ineligible and look for eligible work. Use pendulum-file for requested admission. `pendulum:local` selects the route. +- Leave eligible work with the existing dispatcher. Cite a recorded stage start, Pendulum run or current progress comment, or verified active claim before reporting that work began. A tick pick or Running label can precede the claim. Follow active work or use the supported lifecycle operation for paused work. - Limit supervision to issue and queue operations. Leave source discovery, branches, edits and delegation to the worker with a rendered task card. Use pendulum-run for an explicit single-Objective run, including `--here` when the user selects it and its preconditions pass. ## Start From 58487ac6d086c299072038fbebd9ab8c00071492 Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Wed, 18 Nov 2026 23:48:15 -0800 Subject: [PATCH 4/8] Keep Objective identity when holding or releasing Drafts (#649) --- README.md | 16 +++--- bench/skills.json | 32 +++++------ docs/INSTALL.md | 4 +- docs/LOCAL.md | 20 ++++--- docs/PLAN.md | 26 ++++----- docs/REPORT.md | 8 +-- docs/USAGE.md | 66 +++++++++++----------- plugin/skills/pendulum-file/SKILL.md | 14 ++--- plugin/skills/pendulum-file/reference.md | 16 +++--- plugin/skills/pendulum-restart/SKILL.md | 8 +-- plugin/skills/pendulum-run/reference.md | 2 +- plugin/skills/pendulum-status/SKILL.md | 12 ++-- plugin/skills/pendulum-status/reference.md | 19 +++++-- plugin/skills/pendulum-stop/SKILL.md | 12 ++-- 14 files changed, 133 insertions(+), 122 deletions(-) diff --git a/README.md b/README.md index dc5f041e..0c594a8d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ <h1 align="center">Clockgrove Pendulum</h1> -<p align="center"><strong>Label a GitHub issue, walk away, come back to a reviewed pull request.</strong></p> +<p align="center"><strong>Hand off a GitHub issue, walk away, come back to a reviewed pull request.</strong></p> <p align="center"> <a href="https://github.com/clockgrove/pendulum/releases"><img src="https://img.shields.io/github/v/release/clockgrove/pendulum" alt="Release"></a> @@ -12,7 +12,7 @@ <a href="LICENSE"><img src="https://img.shields.io/github/license/clockgrove/pendulum" alt="License: MIT"></a> </p> -Clockgrove Pendulum turns a GitHub issue into a pull request (PR), using the coding agent you choose: Claude Code, Codex or GitHub Copilot CLI. You write what you want and what "done" means, and label the issue `pendulum:objective`. The coding agent plans and builds the change, Pendulum opens the PR, and a separate agent run reviews it. Then you merge it yourself, or, with auto-merge on, Pendulum merges it once your required CI checks pass. +Clockgrove Pendulum turns a GitHub issue into a pull request (PR), using the coding agent you choose: Claude Code, Codex or GitHub Copilot CLI. You write what you want and what "done" means. Keep `pendulum:objective` on the issue and remove `pendulum:draft` when it is ready to run. The coding agent plans and builds the change, Pendulum opens the PR, and a separate agent run reviews it. Then you merge it yourself, or, with auto-merge on, Pendulum merges it once your required CI checks pass. It is for maintainers of a GitHub repository with CI on pull requests who want to hand whole features to a coding agent, from a change that fits in one PR to an epic delivered as a series of PRs, and keep their own issues, checks and merge queue as the workflow. It runs on GitHub Actions or on your own machine and keeps all its state in GitHub, so there is no server or database to host. @@ -156,7 +156,7 @@ The session writes the issue in the shape Pendulum reads and shows it to you. It - No new dependencies. ``` -It asks whether to start it now (it adds the `pendulum:objective` label), save it as a draft issue (`pendulum:draft`, which Pendulum never runs), or keep discussing. Start it. +It asks whether to start it now, save it as a draft issue, or keep discussing. It files the issue with both `pendulum:objective` and `pendulum:draft`. Start it by letting the session remove `pendulum:draft`. ### 5. Watch it, then merge @@ -177,7 +177,7 @@ Runs take from a few minutes to a few hours. When its run ends, a finish card on ## How it works -1. **You label an issue `pendulum:objective`.** The issue is now an Objective, and its text is the whole specification. +1. **You file an Objective and take it out of Draft.** The issue keeps `pendulum:objective` throughout its lifecycle. When you remove `pendulum:draft`, it can enter the queue. Its text is the whole specification. 2. **A worker plans and builds.** The worker is the coding agent, on a strong model. It writes a plan, which Pendulum posts on the issue, hands the plan's items to implementer sub-agents, usually on a cheaper model and side by side where they touch separate files, then integrates their work in its own checkout, and Pendulum opens a PR. A large Objective arrives as a series of PRs, one open at a time, each part starting once the one before has merged (up to six by default, `max_parts`). 3. **Your CI decides.** The worker waits for your required checks. When one fails, it keeps fixing while each pass makes progress, within the job's spending and time limits, then the Objective is Blocked. 4. **A reviewer comments.** The reviewer is a separate agent run that compares the change with the issue and judges each Acceptance entry. The worker must answer each comment: fix it, or explain why the issue or the repository's rules already settle it. @@ -232,7 +232,7 @@ The worker asks you something only when the work depends on a decision that shou | "Add team invitations." | Goal: a workspace admin can invite people by email, and an invitee joins with one link. Acceptance: an invitation emails a link valid for 7 days; following it after sign-up adds the user to that workspace as a member; an expired or used link shows an error page; admins can list and revoke pending invitations; tests cover each path. Context: use the existing mailer; the sign-up form does not change. | | "Rebuild reporting." | Split the epic where it has a natural order: one Objective for the report export API, and one for the page that uses it, marked as blocked by the first. | -**For an epic with an order,** file several Objectives and link them with GitHub's issue dependencies (blocked by), added before an issue gets its `pendulum:objective` label: Pendulum starts each one once the issues it waits on are closed. Objectives without an order run side by side, up to `max_concurrent`; where two edit the same files, Pendulum rebases or holds back the later one so their changes do not collide ([Siblings that touch the same files](docs/USAGE.md#siblings-that-touch-the-same-files)). +**For an epic with an order,** file draft Objectives and link them with GitHub's issue dependencies (blocked by) before removing `pendulum:draft`. Pendulum starts each one once the issues it waits on are closed. Objectives without an order run side by side, up to `max_concurrent`. Where two edit the same files, Pendulum rebases or holds back the later one so their changes do not collide. [Siblings that touch the same files](docs/USAGE.md#siblings-that-touch-the-same-files) **Quick fixes are better as a direct PR.** Pendulum's planning, review and CI loop is worth its cost on feature-sized work. @@ -245,11 +245,11 @@ A run that goes well needs nothing from you. When one needs you, Pendulum does a | Situation | What you do | | --- | --- | | PR ready for review (auto-merge off) | Read it and merge it through your usual process. | -| **Blocked:** Pendulum could not finish, for example a check still fails or a spending limit was reached. One comment on the issue gives the reason, and the PR becomes a draft | Fix what the comment names, then label the issue `pendulum:objective` again. It resumes from its branch and PR. | +| **Blocked:** Pendulum could not finish, for example a check still fails or a spending limit was reached. One comment on the issue gives the reason, and the PR becomes a draft | Fix what the comment names. To resume from the existing branch and PR, add `pendulum:draft` if absent, then remove it once the previous run has stopped. | | **Question** in a draft PR: the work depends on a decision that should be yours, such as changing a public interface | Comment your decision on the issue or the PR, then mark the PR ready. | -| **Question** on the issue: the work needs another repository | Split it into one Objective per repository and label them, or comment how to do it in this repository alone: the next run picks up your answer, with no relabelling. | +| **Question** on the issue: the work needs another repository | Split it into one Objective per repository, or comment how to do it in this repository alone. The next run picks up that answer automatically. | | The work needs a workflow change | Pendulum leaves the change in a comment on the issue, labelled `pendulum:handover`. After the PR merges, ask "Apply the Pendulum workflow hand-over for Objective 12" ([Workflow changes](docs/USAGE.md#workflow-changes)). | -| Stop one Objective | Remove its `pendulum:objective` label, close its issue, or ask "Stop Pendulum Objective 12". A run in progress ends within about two minutes with its spend recorded; label it again to resume. | +| Stop one Objective | Add `pendulum:draft`, close its issue, or ask "Stop Pendulum Objective 12". A run in progress normally ends within two minutes with its spend recorded. To resume a held issue, remove Draft after the stop has settled. | | Start over from revised text | Label the issue `pendulum:restart`, or ask "Restart Pendulum Objective 12". The earlier PR is closed and its branch deleted. | | Stop everything | `gh workflow disable pendulum.yml` and cancel any runs in the Actions tab. In local mode, stop `pendulum serve` with Ctrl-C. With the cloud sandbox, also stop the Objective's sandboxes in your Vercel project. | diff --git a/bench/skills.json b/bench/skills.json index 0fdad552..650293ab 100644 --- a/bench/skills.json +++ b/bench/skills.json @@ -31,14 +31,14 @@ } }, "pendulum-file": { - "sha256": "ce0048077bf7e354cee950dfcecd617a460556fa9271109d98f2d4246e8fd258", - "lines": 48, - "words": 689, + "sha256": "fc2686110ede525203de594c0e9a2a146ffc03ae97390326978bd5e4430045d6", + "lines": 46, + "words": 617, "files": { "reference.md": { - "sha256": "4c38ea64c67b736af863ca8d38a503b0344eede6632af9b4be4532e06cf57134", + "sha256": "baa3254e2d546ce969fd8ef234141ddebc488abada0dc96094cac49b23dfce05", "lines": 67, - "words": 1364 + "words": 1303 } } }, @@ -113,9 +113,9 @@ } }, "pendulum-restart": { - "sha256": "024f7c1771559a35af1cb4cb27ae20d8ce68f458b9ca91fcfd99355aaec7696f", + "sha256": "ff194bf1bfb423176d4b140aca09ff852751f99f837d25367cbe750b30ba3942", "lines": 31, - "words": 503 + "words": 466 }, "pendulum-review-here": { "sha256": "e2f838041dc541e9ddae7dcfdcf30336c173075ed898ba3629e024ac8896d526", @@ -152,9 +152,9 @@ "words": 668, "files": { "reference.md": { - "sha256": "3c68ad93139560ddd7e07f3e698b2ddd61ba5edbf8695402644ffd0930ad1ba8", + "sha256": "7b417884528fa46a397433909e8490e111e9f5f7480b924ad507b1117da9cfbd", "lines": 23, - "words": 370 + "words": 368 } } }, @@ -200,21 +200,21 @@ } }, "pendulum-status": { - "sha256": "8e3ebb1612da3f034b6948b6799771371ad7c6590781bf51ccda21118beefd1b", + "sha256": "d6284876e370c596cc37e59a5ba76d3ad41daf63826c538272f995b63cc2eeaf", "lines": 40, - "words": 692, + "words": 626, "files": { "reference.md": { - "sha256": "03d8ddd00f6a2ffe7ba4b7beef905c8546f32676031adb506c7f831610673d70", - "lines": 46, - "words": 879 + "sha256": "a5c20e94c2bf22dce21da23411c2e91a42a6dfcd487a81b62c19ded3341833f0", + "lines": 55, + "words": 968 } } }, "pendulum-stop": { - "sha256": "d29e0447f3d681856d11a70b36eb461d2c5e71e516e89195fe5838b702702417", + "sha256": "6d2377a327e8a697efc404836f6483cbd0b738a0ad9bfde83de0753710ff43f5", "lines": 30, - "words": 457 + "words": 404 } } } diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 4ee34e5e..f4261e83 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -35,7 +35,7 @@ What each credential can do: - **The job token:** `contents: read`, `issues: write`, `actions: read` (usage artifacts and the CI workflow's triggers), and on the jobs that tick the dispatcher `actions: write` (work and review also use it to rerun flaky CI jobs); it never writes code. Your repository's default workflow token must be read-only, which doctor requires and setup's `default-token` step sets (below). - **The harness:** it holds no GitHub write access: on Actions it runs as its own uid with a read-only token (the runner needs passwordless sudo, as GitHub's hosted runners have); Pendulum makes every write. - **Secrets:** they are scrubbed from every non-harness child and masked in the uploaded event log. -- **Cost:** `max_usd` caps each job ($25 by default). `daily_usd` ($100 by default) gates new stages: once the UTC day's spend reaches it, the dispatcher starts and relaunches no stage until the next day, while running stages, review stages and answer passes go on, so a day can end above it. Every stage, on every route, writes its spend so far into its progress comment, and that line is what the day, the finish card and `max_objective_usd` count; a usage artifact is read for its dollars only for a stage whose comment has no spend line, and the finish card reads one for its model alone for a stage whose harness line names none (Copilot at its default model). `max_objective_usd` (unset by default: no cap) caps one Objective across all its stages and parts: every work and review stage checks it before any pass, and once the Objective's known spend reaches it, the stage starts nothing and the Objective Blocks naming the cap and the total (cause `max-objective-usd`); raise or unset it, then re-apply `pendulum:objective`. It counts, since the Objective's last `pendulum:restart` or reopening (a restart starts the count over), the known dollars of every stage of Pendulum's on the issue (its spend line, else its own workflow run's usage artifact), the cloud sandbox's vendor cost, and the decision calls made outside any stage that Pendulum's comments on the issue record (a line in a comment written since then, or dated after that day). A stage on another route Pendulum cannot match to itself, and every run of unknown cost, count nothing. A stage's own spend counts once its spend line is written, so the stage that crosses the cap finishes. `max_concurrent` is 3 and `timeout_minutes` 240 unless set; setup's `--preset first-run` sets `max_usd` 5, `max_concurrent` 1 and `auto_merge` false for a first run; Claude (`--max-budget-usd`) and Copilot (`--max-ai-credits`) enforce the per-job cap inside the run; Codex is checked after each run. A job's passes get `max_usd` less its drift reserve (10% of `max_usd`, at least $0.30, at most `max_usd`), which only the drift advisory spends (`decision_route` below). The caps count only spend a harness, Copilot, the AI Gateway or the sandbox vendor reported (or API-reported tokens at the published rate). A run whose cost was not reported (killed or crashed before it reported, a zeroed Claude result, a resumed Claude Code session before 2.1.277, a Codex model with no price row, a Copilot run whose AI credits were not reported, a relayed gateway call or a gateway decision call the gateway never priced) is shown as unknown, "plus N runs of unknown cost", in the progress comment, the exit line, `result.json`, the day's total and the scorecard; it is not counted against `max_usd`, `daily_usd` or `max_objective_usd` and the job goes on, so a cap can be exceeded by unreported spend. Only the provider's own budget or limit bounds that. Each figure also says how it is billed (`billing` and `usdByBilling` in `result.json` and the spend line), decided on a positive sign only, from the environment the harness gets and what the harness reports: +- **Cost:** `max_usd` caps each job ($25 by default). `daily_usd` ($100 by default) gates new stages: once the UTC day's spend reaches it, the dispatcher starts and relaunches no stage until the next day, while running stages, review stages and answer passes go on, so a day can end above it. Every stage, on every route, writes its spend so far into its progress comment, and that line is what the day, the finish card and `max_objective_usd` count; a usage artifact is read for its dollars only for a stage whose comment has no spend line, and the finish card reads one for its model alone for a stage whose harness line names none (Copilot at its default model). `max_objective_usd` (unset by default: no cap) caps one Objective across all its stages and parts: every work and review stage checks it before any pass, and once the Objective's known spend reaches it, the stage starts nothing and the Objective Blocks naming the cap and the total (cause `max-objective-usd`); raise or unset it, then resume through Draft as described in [An Objective's lifecycle](USAGE.md#an-objectives-lifecycle). It counts, since the Objective's last `pendulum:restart` or reopening (a restart starts the count over), the known dollars of every stage of Pendulum's on the issue (its spend line, else its own workflow run's usage artifact), the cloud sandbox's vendor cost, and the decision calls made outside any stage that Pendulum's comments on the issue record (a line in a comment written since then, or dated after that day). A stage on another route Pendulum cannot match to itself, and every run of unknown cost, count nothing. A stage's own spend counts once its spend line is written, so the stage that crosses the cap finishes. `max_concurrent` is 3 and `timeout_minutes` 240 unless set; setup's `--preset first-run` sets `max_usd` 5, `max_concurrent` 1 and `auto_merge` false for a first run; Claude (`--max-budget-usd`) and Copilot (`--max-ai-credits`) enforce the per-job cap inside the run; Codex is checked after each run. A job's passes get `max_usd` less its drift reserve (10% of `max_usd`, at least $0.30, at most `max_usd`), which only the drift advisory spends (`decision_route` below). The caps count only spend a harness, Copilot, the AI Gateway or the sandbox vendor reported (or API-reported tokens at the published rate). A run whose cost was not reported (killed or crashed before it reported, a zeroed Claude result, a resumed Claude Code session before 2.1.277, a Codex model with no price row, a Copilot run whose AI credits were not reported, a relayed gateway call or a gateway decision call the gateway never priced) is shown as unknown, "plus N runs of unknown cost", in the progress comment, the exit line, `result.json`, the day's total and the scorecard; it is not counted against `max_usd`, `daily_usd` or `max_objective_usd` and the job goes on, so a cap can be exceeded by unreported spend. Only the provider's own budget or limit bounds that. Each figure also says how it is billed (`billing` and `usdByBilling` in `result.json` and the spend line), decided on a positive sign only, from the environment the harness gets and what the harness reports: - **Billed per use, shown bare:** an Anthropic API key (`ANTHROPIC_API_KEY`, an `apiKeyHelper`, a Console login), workload identity federation, a bearer token to a gateway or proxy (`ANTHROPIC_AUTH_TOKEN`), Bedrock or Vertex (`CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`), a Codex API key or API auth mode, the AI Gateway key (its decision calls, in a stage or outside one), and a relayed worker key's calls. - **"API-equivalent at list prices, on the subscription":** Claude Code's `total_cost_usd` on `credential: plan` (`CLAUDE_CODE_OAUTH_TOKEN`) or on a local login whose Claude Code reports a subscription's rate-limit windows, and Codex tokens priced from the API table on a ChatGPT auth mode (or a local login whose rollout carries a ChatGPT plan's rate limits). - **"Copilot AI credits, billed to the seat":** Copilot's credits at `copilot_credit_usd`. @@ -265,7 +265,7 @@ The accounts are rendered into the workflow, so adding, removing or reordering o 1. Read the release notes between your tag and the new one. 2. Re-render the workflow with that release's setup: in your repository's clone, `node <pendulum clone at vX.Y.Z>/plugin/scripts/setup.mjs --repo OWNER/NAME --apply workflow --action clockgrove/pendulum@vX.Y.Z --yes`. It keeps your settings, moves the pin and brings the template's jobs to that release. Re-render on every upgrade: the template belongs to its release, and an older file misses jobs the new Action expects (doctor names some, such as `merge ticks`). -3. Commit the file on the default branch, then run doctor. A running `pendulum serve` started from a release takes a later pin at its next stage boundary, without a restart (LOCAL.md, Settings and repins while `serve` runs); to go back to an older release, start `serve` from it yourself. Until then the file lacks the newer jobs' events: a file from before the lifecycle labels, for one, ticks the dispatcher on a removed `pendulum:objective`, an applied `pendulum:restart` or a changed `pendulum:draft` only on its ten-minute cron. +3. Commit the file on the default branch, then run doctor. A running `pendulum serve` started from a release takes a later pin at its next stage boundary, without a restart (LOCAL.md, Settings and repins while `serve` runs); to go back to an older release, start `serve` from it yourself. Until then the file lacks the newer jobs' events: a file from before the lifecycle labels, for one, waits for its ten-minute cron to see a change to `pendulum:draft`, an applied `pendulum:restart` or a legacy Objective-label removal. 4. If you accepted setup's offer to commit Pendulum's skills into the repository, copy them again from the new release: committed copies never update, and they override the plugin's. 5. Update the plugin on each machine whose sessions or `pendulum serve` work this repository, then start a new session: Claude Code `claude plugin marketplace update clockgrove && claude plugin update pendulum@clockgrove`, Codex `codex plugin marketplace upgrade clockgrove && codex plugin add pendulum@clockgrove`, Copilot `copilot plugin update pendulum@clockgrove`. Doctor and `pendulum serve` warn while the installed plugin is older than the pin. diff --git a/docs/LOCAL.md b/docs/LOCAL.md index 49f3c264..1a3ae353 100644 --- a/docs/LOCAL.md +++ b/docs/LOCAL.md @@ -177,20 +177,20 @@ The next `serve` on the same machine resumes them first, before reviews and new - Running work starts a fresh work pass in the Objective's clone, on the branch as GitHub has it (a killed pass's session and unpushed commits are not carried over). Other machines and the Action leave a paused Objective alone. -The dispatcher Blocks one only after the claim pause away (`claim_pause_hours`, a day by default), and re-applying its label brings it back. +The dispatcher Blocks one only after the claim pause away (`claim_pause_hours`, a day by default). Once the cause is fixed, resume it through Draft after the previous stage has stopped. [An Objective's lifecycle](USAGE.md#an-objectives-lifecycle) ### Stopping one Objective -Removing its `pendulum:objective` label (applying `pendulum:draft`, or closing its issue) is not a pause. +Apply `pendulum:draft` to stop an Objective and keep its `pendulum:objective` identity. Closing the issue also stops it. This is separate from pausing a process by stopping the local loop. Its stage here reads the issue once a minute, ends its harness's process group, records its spend line and exits with `exit: stopped`. The loop drops its claim, does not resume it, and starts no review of its PR, which the stage leaves a draft. A validation or setup command running at the stop is not in the harness's group: it runs to its end after the stage exits, and the stage starts no command, push or PR change after the stop. -`serve`'s next tick tidies a stopped one no stage holds (USAGE.md, An Objective's lifecycle). +`serve`'s next tick tidies a stopped one no stage holds. Once the stage has stopped and released its claim, remove `pendulum:draft` to return the Objective to the queue. [An Objective's lifecycle](USAGE.md#an-objectives-lifecycle) ### Drafts -An issue with `pendulum:draft` is never run here: `serve` neither picks, resumes nor reviews it, and `pendulum run`, `pendulum issue` and `pendulum deliver` refuse it before any claim, naming how to start it. +File a draft with both `pendulum:objective` and `pendulum:draft`. While Draft is on the issue, `serve` skips it for new work, resumes and reviews. `pendulum run`, `pendulum issue` and `pendulum deliver` refuse it before any claim. Removing `pendulum:draft` lets the next tick consider it on its configured route. ### Restarting one Objective @@ -203,20 +203,22 @@ It forgets this loop's failed starts and lapses of it, and the next work stage p An Objective whose stage ends on this machine with a Question or a Block waits for you. No `serve` tick takes it again while its stage runs, or after it ends on a GitHub read that does not show the stop yet. It starts again only after a trusted answer, the same as on the Action: -- **Re-applying its label.** +- **Removing `pendulum:draft` after the cause is resolved.** Add Draft first if it is absent. Leave `pendulum:objective` in place. - **A comment answering a Question asked on the issue** (one with no PR, or the plan-time Question; its notice on the issue says to answer there). The next `serve` tick reads the comments made since the Question by people who can push, Pendulum's own marked comments not among them though they post as your login. It runs the worker again with the answer, once the answer check reads the comments as a decision on the Question (PLAN.md, Exit: question). - **Marking the PR ready, for a Question its draft PR asks** (its notice says to mark the PR ready). The next `serve` tick reviews that PR, and the review applies the answer; with none since the Question, the PR goes back to a Question. -A label re-applied since the Question by someone who can push (USAGE.md, who applied a label counts) wins over a ready mark beside it: the next tick runs the worker, its `pendulum:question` label taken off, and starts no review of that PR. +A trusted Draft removal since the Question takes precedence over marking the PR ready. The next tick clears `pendulum:question` and starts the worker without starting a review of that PR. [Who applied a label counts](USAGE.md#choose-the-harness-and-models) Marking a plan-time Question's PR ready starts a review that can merge the part done so far, as its notice warns: answer that one on the issue. If the stop never reached GitHub (a fresh read of the issue shows it Queued), it runs again, as on the Action, and the tick line names every Objective it holds. ### Waiting on the queue +When a session supervises the queue, it checks the issue's readiness and follows the existing dispatcher. The assigned worker handles source discovery and implementation. A loop pick or Running label can appear before work begins. Use a recorded stage start or current claim to confirm it. + `pendulum wait` is for an agent that supervises the queue: started in the background, it exits when something needs a look. It reads GitHub, not this machine, so it tells every route's Objectives (the Action's, a cloud sandbox's, any machine's `serve`), with or without a `serve` here. It needs no sandbox, harness or App, and reads with the local token, else your `gh` login. @@ -365,7 +367,7 @@ It resumes a paused Objective once the host it could not reach answers a probe, **Twelve hours.** An Objective paused on one outage for twelve hours or more is Blocked instead, with the External cause `outage`, naming the host and since when. - That happens on `serve`'s first tick that GitHub answers, whether or not that host answers yet (a model provider that stays unreachable while GitHub works ends here too); the notice says whether the host answers again or is still unreachable. - Re-apply its label to run it again. + Resume it through Draft once the cause is resolved. - An outage that begins within fifteen minutes of `serve` resuming the Objective counts as the same one. Pauses on GitHub's spent rate limit one after another, with no other end between, count as one however long the runs between them last. Either holds only while nothing was done between them: a stage whose provider served a harness pass (its `result.json`'s `servedPasses`; a decision call Pendulum made through the harness is none) before it paused made progress, so its pause counts from its own start. @@ -799,7 +801,7 @@ No sandbox can read it; it must be a regular file of yours, with one link, that The scorecard also gives each account's stages, dollars and usage-limit pauses for the Objective. No path, credential or token reaches GitHub or a log. - **Checked at every stage start, every account:** a bad one stops `serve` from starting, and Blocks a stage (cause `setup`), naming only the account; the loop's log says why, without a path. - Fix the file, then re-apply `pendulum:objective`. + Fix the file, then resume the Objective through Draft. Pendulum never creates an account folder. These are bad: - an invalid or repeated name, or another harness's name; @@ -934,7 +936,7 @@ For one Objective's stages alone they also reach the hosts its approved `pendulu `*.` over a public suffix or a name with one below, such as `*.github.io` or `*.amazonaws.com`, is refused, but a name that resolves to a loopback or link-local address is not. Doctor's `objective hosts` row lists them. - A worker that stops because a sandbox denied a host it needs names the host in its exit record (`deniedHosts`). - The Blocked comment names it with both fixes: a `pendulum:host:<host>` label for this Objective, or the host in `PENDULUM_LOCAL_DOMAINS` for every Objective (`serve` reads it when it starts), then re-apply `pendulum:objective`. + The Blocked comment names it with both fixes: a `pendulum:host:<host>` label for this Objective, or the host in `PENDULUM_LOCAL_DOMAINS` for every Objective (`serve` reads it when it starts), then resume through Draft. Allowing it stays your decision. ### Git LFS media is uploaded by Pendulum, not the sandbox diff --git a/docs/PLAN.md b/docs/PLAN.md index 39e7a3be..c5eed811 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,6 +1,6 @@ # Pendulum: design and contracts -Pendulum is a GitHub Action, a harness plugin and a bench, sharing one set of skills and a short task card. An adopter adds one workflow file, a GitHub App and a model credential, and labels an issue `pendulum:objective`; a worker builds it, a reviewer comments on it, and Pendulum merges it through the adopter's own required checks and merge queue. The human reads the Project board's Blocked column and, when they choose, the merged diffs. This page is the design as it is now; git holds its history. +Pendulum is a GitHub Action, a harness plugin and a bench, sharing one set of skills and a short task card. An adopter adds one workflow file, a GitHub App and a model credential, and files an issue with `pendulum:objective` and `pendulum:draft`. Removing Draft makes it eligible to run. A worker builds it, a reviewer comments on it, and Pendulum merges it through the adopter's own required checks and merge queue. The human reads the Project board's Blocked column and, when they choose, the merged diffs. This page is the design as it is now; git holds its history. ## Design rules @@ -46,7 +46,7 @@ Job one: file an Objective, walk away, and come back to correct, merged work at | Measure | Job-one part | Taken from | | --- | --- | --- | -| Walk-away: merged with zero human input after the label | Operator walks away | Three buckets. Walk-away: merged with no human push, comment or edit on the branch or issue after the label. External: every stop was a Block outside Pendulum and outside the work (Pendulum's `max_usd` cap, the AI Gateway's budget or credits, a provider's quota, plan limit or billing: the model provider, GitHub's Git LFS storage, GitHub's API rate limit or the sandbox vendor's plan; a provider or GitHub outage Pendulum handled by its rules), and the only human input answered those Blocks. Miss: anything else, a Blocked card of any other cause included. Each Block records its cause as a code (bench/README.md, Block causes), so the bucket is decided on structure. | +| Walk-away: merged with zero human input after activation | Operator walks away | Three buckets. Walk-away: merged with no human push, comment or edit on the branch or issue after activation. External: every stop was a Block outside Pendulum and outside the work (Pendulum's `max_usd` cap, the AI Gateway's budget or credits, a provider's quota, plan limit or billing: the model provider, GitHub's Git LFS storage, GitHub's API rate limit or the sandbox vendor's plan; a provider or GitHub outage Pendulum handled by its rules), and the only human input answered those Blocks. Miss: anything else, a Blocked card of any other cause included. Each Block records its cause as a code (bench/README.md, Block causes), so the bucket is decided on structure. | | Solution quality | Correct work | The bench's blind pairwise judge where there is a comparison; the owner's read of the merged diff when they choose to read it; escapes found after merge count against it. | | Operator minutes | Operator walks away | Minutes spent on Blocked cards and on re-filing, from a stopwatch; zero on a clean merge. | | Dollars per merged Objective | Reasonable cost | Per harness: Claude's headless output carries total\_cost\_usd and per-model usage with sub-agents included; Codex's JSONL carries the thread's running token counts (a resumed pass counts only its own share), priced from a table, with each sub-agent thread's own counts read from its rollout and priced at its model; Copilot bills GitHub AI Credits and its usage file reports them per run, so its column is those credits at GitHub's published $0.01 each (configurable), with the premium requests beside them. Runner minutes beside it. Wall time reported, never alone. | @@ -185,13 +185,13 @@ One worker, three routes: a GitHub runner (the default), the developer's own mac ## How an Objective flows -1. **File.** A writer opens an issue stating the Objective (goal, acceptance entries under an Acceptance heading, sources, context, recorded decisions) and a maintainer applies `pendulum:objective`. The Project card is Queued. An issue with `pendulum:draft` is a draft: no route runs it, its Objective label on or not, until a person takes the draft label off and applies `pendulum:objective`. `lib/stop.mjs` decides it: the dispatcher, the launcher, the worker, the review job, the merge pass and the local loop's resumes and reviews read `stopCause`; `pendulum run`, `pendulum issue` and `pendulum deliver` refuse on `isDraft`. A work stage plans by the later of the label's last application and the draft label's last removal (`objective-trust.mjs` `startedAt`), so a draft edited after an earlier plan is planned again once started. Blocked-by relations on the issue are the only dependency graph; an issue closed by any route counts as done. +1. **File.** A writer opens an issue stating the Objective (goal, acceptance entries under an Acceptance heading, sources, context, recorded decisions) and a maintainer files it with `pendulum:objective` and `pendulum:draft`. The issue keeps its Objective identity for its entire lifecycle. The Project card is Queued. Every route skips drafts. The maintainer removes `pendulum:draft` to activate the Objective. `lib/stop.mjs` decides it: the dispatcher, the launcher, the worker, the review job, the merge pass and the local loop's resumes and reviews read `stopCause`; `pendulum run`, `pendulum issue` and `pendulum deliver` refuse on `isDraft`. A work stage plans by the latest trusted activation (`objective-trust.mjs` `startedAt`), so a draft edited after an earlier plan is planned again once started. Older Objective-label events remain readable. Blocked-by relations on the issue are the only dependency graph; an issue closed by any route counts as done. 2. **Dispatch.** The dispatcher, ticked by events (any issue closing among them, since it may block an Objective) and by Pendulum's own jobs, with GitHub's `*/10` cron as the backstop, picks ready Objectives by priority label and starts work up to `max_concurrent`, stopping at `daily_usd`. A pick whose known files (its open PR's changed files, its plan comment's `Files:` lines) overlap an active sibling's starts all the same, saying so on its issue: it has work of its own to write, and waiting would hold that whole stage where starting costs at most one rebase. What waits is the hand-off: a head no review has seen that conflicts with the head of a sibling ahead of it (In review, or through its own wait and rebasing, or waiting since earlier), by a trial merge of the two heads against the default branch (git merge-tree in a scratch mirror), when Pendulum merges, gets its review label only once no such sibling is ahead (for 6 hours at most from the Objective's first wait), after its rebase if it conflicts by then. Waiting PRs go one at a time in the order they began waiting, so each rebases once and two such PRs are never reviewed or queued at once (`lib/overlap.mjs`; `docs/USAGE.md` "Siblings that touch the same files"). The card moves to Running. 3. **Work.** The worker checks out the default branch, runs `setup`, installs the versions the lockfile pins (online, with no credential in its environment; npm, pnpm and yarn skip install scripts), renders the task card and starts the harness with the issue text verbatim. The harness writes its plan, implements, rebases, validates and commits, and leaves its plan, PR text and exit record as files. Pendulum posts the plan, pushes `pendulum/<issue>` and opens the one PR. With required checks configured (`ci_checks`) and a work pass that ended well, Pendulum does not wait for the checks on that head: once the push is done (on the local route, once its validation commands are green on the machine), it marks the PR ready with a hand-off marker (`<!-- pendulum:<issue>:handed-off:<sha> -->`) instead of the validated one and applies the review label, so the review starts while the head's first required-check run is still going. A send-back's rebase, and a pass whose harness ended in an error (green checks are what outweigh it), wait for the checks in the work stage. With cross-OS CI on (`cross_os_workflow`, `cross_os_checks`; INSTALL.md, Cross-OS CI), the work stage then dispatches the repository's named CI workflow on the branch (in a cloud sandbox, through its launcher job, which dispatches only that workflow on the stage's own branch and head and hands the run's id back) and waits, within `cross_os_wait_minutes`, for the macOS and Windows legs it lists, on every route; a red leg goes to the fix pass as any validation red does, a head a fix pass made gets the other validation again first, and only once the legs are green does the hand-off or the validated marker follow (`lib/cross-os.mjs`). The card moves to In review. 4. **Review.** The reviewer posts findings as PR review comments. On a head handed off with its checks running, the review stage waits for the checks beside the reviewer (Review and merge, below). The worker gets the comments once, with any red the checks showed, and addresses or rebuts each in a reply file; Pendulum pushes its commits, posts the replies, and validation runs again. -5. **Merge.** Pendulum merges the reviewed head once its required checks are green, through the merge queue where there is one. A red integrated run whose failure is in the PR's own change gets one fix pass, as a red PR check does, before any Block: one per failure class and two in all per re-entry, so the same failure red again after its fix pass Blocks. A red integrated run that is a flake, GitHub's side or the default branch's, or that cannot be read or (with triage off) named as the PR's, and any other drop, goes back to the queue once; a second is Blocked (Review and merge, below). So a repository may run a light check on the PR and its full suite only in the merge queue. A PR that conflicts because other PRs merged (when its review reaches the merge, or in the merge queue) is sent back to the worker for a rebase each time the default branch has moved since its last rebase: a new base is progress. When Pendulum merges, the PRs that conflict go back in the release order (priority, then number): one whose head conflicts, by a trial merge, with that of a sibling ahead of it in that order that will merge first (In review, or rebasing after its review) waits for that merge, since a rebase now would be undone by it, for 6 hours at most counted with any hand-off wait before it, with a record on the PR and a note on the issue (`lib/overlap.mjs` sendBackOrder). Each send-back is its own work stage, with its own `max_usd`; its notice on the PR says which rebase of the 24-hour bound it is, and its progress comment carries a `<!-- pendulum:rebase-cost -->` line (its known dollars, 0 for a clean rebase, its runs of unknown cost as its spend line carries them, and whether it was a conflict pass) beside the Objective's rebase total so far. It Blocks, as the work's, only when rebasing cannot progress, or at the bound. The worker records each rebase of Pendulum's that conflicts on the PR (the head it started from, the base and the files), and before anything of its conflict pass is pushed it checks the checkout: a rebase, merge or cherry-pick left in progress, a head that does not contain that base, or a change of the branch missing from it Blocks naming the files and each path whose change is missing (with the branch's commits that changed it, and why), with nothing pushed. That is decided on the branch's net change, its merge base with the base to its head, merges included, never on commit ids, authors or subjects, so a rebased or squashed branch, or one with a commit of the worker's joining it to the default branch, goes out when it keeps the work. The net change is replayed onto the base (`git merge-tree`, with git's rename detection, so a file the default branch renamed is checked under its new name) and merged into the head: every path that replay conflicts on and every path that merge would still change is checked, and nothing else is the branch's. Such a path is kept when the head has exactly the branch's version of it, content and file mode. The file mode is decided on its own: a mode the branch's change sets and the head lacks is named, whatever the content. A binary or Git LFS file, a submodule or symlink, and a file git cannot merge the branch's change into (one the head moved or removed, or kept with edits where the branch deletes it) are decided exactly, never by the model. A change of the branch with no hunk is decided exactly too: two different blobs (git reads one as binary, the base included) are named, a file the branch only puts under a name (one side of a rename) or adds empty is named when the head has no file there, an empty file it deletes is named when the head keeps it, and a name the branch's change does not have is no loss. Any other text file goes to the decision model (with a key, `triage_model`; else the stage's harness: Red-check triage below), four files at a time. The branch's change is, for a file the replay conflicted on, its side from their base; for a file where merging the branch's change into the head conflicts, its side of that merge; for any other, what that merge would still change there. Its hunks, whatever the size of the whole diff, go in one question with the file as the head has it: whole, or, over 32 KiB, for each hunk the 60 lines either side of where its lines are in the head (from the first line, for a file the base did not have), reaching past every line its new side has. A question holds at most 64 KiB: more goes in groups of hunks packed in order up to that, each group with the file or its hunks' lines, the groups asked at once (four questions at a time across the check). The question is whether every hunk's effect is still in the file, as written or adapted to the default branch's code, other changes and additions allowed; each part is delimited, with the path, as untrusted data the model is told not to follow. `kept` at the confidence floor or more (Red-check triage, below) keeps the file. Anything else, for a question of several hunks, asks each of its hunks alone, sent with the file or its lines again, in order, and names the file with the first hunk not kept; no further group starts. When every hunk alone is kept, the question's hunks are kept after an unsure answer for them together (`kept` or `lost` under the floor, or none), and the file still named after a `lost` at the floor or more. A hunk whose own question (the hunk with the file, or with its lines around it) is over 64 KiB is not judged: the file is named with each such hunk, and its other hunks are not asked. The Block names the fix for a generated file: declare it. A path the default branch's `.gitattributes` gives the `pendulum-generated` attribute, in a repository with a `regenerate` command, is never judged: the conflict pass takes the default branch's version, the command writes the file again, and Pendulum's regeneration check runs the command before each validation, in any stage, of a head whose change touches a declared path, green only when it exits 0, writes again each such file (removed first), changes nothing outside the declared paths and leaves each declared path as committed (INSTALL.md, Generated files). A path past the first 40 or the check's 3 minutes names the file. On the local route, a conflict pass the check stops is kept on the branch `pendulum/<issue>-conflict-pass` of the Objective's clone, `.pendulum/<issue>/repo` (the last one only: a later push of the branch removes it, and so does a later Block with nothing to keep, which says so), and the Block gives its full sha and how to deliver it: check that it keeps the Objective's change and touches no secret or protected path, since Pendulum's push checks did not run on it, then `git push --force-with-lease origin pendulum/<issue>-conflict-pass:pendulum/<issue>` in that clone and re-apply the Objective's label; the stages after it validate and review that head like any other. A file the branch's commits changed and then undid, which the head changes anyway, is no loss: when the branch goes out, a line on the progress comment says so for the review. With no decider (`decision_route` off, or `gateway` with no key), a path not exactly the branch's falls back to matching the branch's commits in the head by author, author time and subject (a commit git dropped because the base already has its change is no loss), as does a stage with no decider whose git is older than 2.40; with a key, such a git Blocks naming its version. The check asks whether the branch's change is still there; whether the joined code still works (a call to something the default branch renamed, a semantic clash that keeps every line) is for validation, CI and the reviewer. As a fallback, the dispatcher Blocks, naming the files, a PR that still conflicts while the default branch is the base the last pushed rebase was made onto. The bound is 5 rebases in 24 hours by default (`rebase_limit`), so two Objectives cannot chase each other forever; a batch of five parallel Objectives has at most four siblings merging ahead of one. Only Pendulum's own markers and records count, and a tick that cannot read them, or the Objective label's time, holds the PR until the next. A PR that only fell behind and whose update-branch GitHub fails for now waits for the next tick; one GitHub refuses goes to the worker under these rules. A PR the merge queue takes out for a conflict with a PR ahead of it counts as no drop: Pendulum puts it back once no PR in the queue conflicts with it, by a trial merge of the two heads against the default branch (git merge-tree in a scratch mirror), and at once when a trial merge cannot be computed (the queue then answers). Each time it goes back in, Pendulum records on the issue the queue's state then (the default branch's head and every entry's head); taken out for a conflict again, it goes back in only once that state has changed, so a conflict pairwise trials cannot see (one with the queue's merge group) never loops. This is the same on every route and harness: nothing is enqueued for a conflicting PR, it stays delivered, and the send-back takes it (`pendulum run --wait` does the send-back itself). The card moves to Done and the issue closes. -6. **Blocked.** The PR becomes a draft, the card moves to Blocked, and one comment states the reason (validation failed twice, reviewer findings unaddressed, dollar or time cap reached, worker died twice, rebasing makes no progress or reached its bound). The queue does not wait. A human fixes it by pushing to the branch or editing the issue and re-applying the label; a local Block on hosts the sandbox denied names them and its own fix (Exit: blocked, below). -7. **Stopped.** A person removes `pendulum:objective`, applies `pendulum:draft` or closes the issue. Nothing lists a stopped Objective for a start (the dispatcher, the local loop's resumes and reviews, the sandbox launcher, the review job). A running stage reads its issue once a minute and on the stop ends every harness pass (`lib/stop.mjs`), records the spend so far and exits with `exit: stopped`; from the stop on it starts no pass, command, push or PR change, and it writes its usage and spend line before any other GitHub call (at two minutes it writes what it knows at once and exits). A pass ended before it reported dollars, or still running, is a run of unknown cost, as on the spend line. A cloud sandbox stage that its launcher process ends instead (its wall clock) records the stage as a run of unknown cost too (`stage.mjs` `killedUsage`), never `max_usd` or another bound, so `daily_usd` names it without counting it. A stop racing the stage's own exit (one being applied, or its merge) ends nothing, and the merge pass reads the issue before any merge, so a stopped Objective never merges; its PR leaves the merge queue and becomes a draft without `pendulum:review`, and its state label and card go back to Queued. The dispatcher does the same for a stopped Objective In review, and for a Running one ten minutes after the stop. Re-applying the label continues it, as after a Block. +5. **Merge.** Pendulum merges the reviewed head once its required checks are green, through the merge queue where there is one. A red integrated run whose failure is in the PR's own change gets one fix pass, as a red PR check does, before any Block: one per failure class and two in all per re-entry, so the same failure red again after its fix pass Blocks. A red integrated run that is a flake, GitHub's side or the default branch's, or that cannot be read or (with triage off) named as the PR's, and any other drop, goes back to the queue once; a second is Blocked (Review and merge, below). So a repository may run a light check on the PR and its full suite only in the merge queue. A PR that conflicts because other PRs merged (when its review reaches the merge, or in the merge queue) is sent back to the worker for a rebase each time the default branch has moved since its last rebase: a new base is progress. When Pendulum merges, the PRs that conflict go back in the release order (priority, then number): one whose head conflicts, by a trial merge, with that of a sibling ahead of it in that order that will merge first (In review, or rebasing after its review) waits for that merge, since a rebase now would be undone by it, for 6 hours at most counted with any hand-off wait before it, with a record on the PR and a note on the issue (`lib/overlap.mjs` sendBackOrder). Each send-back is its own work stage, with its own `max_usd`; its notice on the PR says which rebase of the 24-hour bound it is, and its progress comment carries a `<!-- pendulum:rebase-cost -->` line (its known dollars, 0 for a clean rebase, its runs of unknown cost as its spend line carries them, and whether it was a conflict pass) beside the Objective's rebase total so far. It Blocks, as the work's, only when rebasing cannot progress, or at the bound. The worker records each rebase of Pendulum's that conflicts on the PR (the head it started from, the base and the files), and before anything of its conflict pass is pushed it checks the checkout: a rebase, merge or cherry-pick left in progress, a head that does not contain that base, or a change of the branch missing from it Blocks naming the files and each path whose change is missing (with the branch's commits that changed it, and why), with nothing pushed. That is decided on the branch's net change, its merge base with the base to its head, merges included, never on commit ids, authors or subjects, so a rebased or squashed branch, or one with a commit of the worker's joining it to the default branch, goes out when it keeps the work. The net change is replayed onto the base (`git merge-tree`, with git's rename detection, so a file the default branch renamed is checked under its new name) and merged into the head: every path that replay conflicts on and every path that merge would still change is checked, and nothing else is the branch's. Such a path is kept when the head has exactly the branch's version of it, content and file mode. The file mode is decided on its own: a mode the branch's change sets and the head lacks is named, whatever the content. A binary or Git LFS file, a submodule or symlink, and a file git cannot merge the branch's change into (one the head moved or removed, or kept with edits where the branch deletes it) are decided exactly, never by the model. A change of the branch with no hunk is decided exactly too: two different blobs (git reads one as binary, the base included) are named, a file the branch only puts under a name (one side of a rename) or adds empty is named when the head has no file there, an empty file it deletes is named when the head keeps it, and a name the branch's change does not have is no loss. Any other text file goes to the decision model (with a key, `triage_model`; else the stage's harness: Red-check triage below), four files at a time. The branch's change is, for a file the replay conflicted on, its side from their base; for a file where merging the branch's change into the head conflicts, its side of that merge; for any other, what that merge would still change there. Its hunks, whatever the size of the whole diff, go in one question with the file as the head has it: whole, or, over 32 KiB, for each hunk the 60 lines either side of where its lines are in the head (from the first line, for a file the base did not have), reaching past every line its new side has. A question holds at most 64 KiB: more goes in groups of hunks packed in order up to that, each group with the file or its hunks' lines, the groups asked at once (four questions at a time across the check). The question is whether every hunk's effect is still in the file, as written or adapted to the default branch's code, other changes and additions allowed; each part is delimited, with the path, as untrusted data the model is told not to follow. `kept` at the confidence floor or more (Red-check triage, below) keeps the file. Anything else, for a question of several hunks, asks each of its hunks alone, sent with the file or its lines again, in order, and names the file with the first hunk not kept; no further group starts. When every hunk alone is kept, the question's hunks are kept after an unsure answer for them together (`kept` or `lost` under the floor, or none), and the file still named after a `lost` at the floor or more. A hunk whose own question (the hunk with the file, or with its lines around it) is over 64 KiB is not judged: the file is named with each such hunk, and its other hunks are not asked. The Block names the fix for a generated file: declare it. A path the default branch's `.gitattributes` gives the `pendulum-generated` attribute, in a repository with a `regenerate` command, is never judged: the conflict pass takes the default branch's version, the command writes the file again, and Pendulum's regeneration check runs the command before each validation, in any stage, of a head whose change touches a declared path, green only when it exits 0, writes again each such file (removed first), changes nothing outside the declared paths and leaves each declared path as committed (INSTALL.md, Generated files). A path past the first 40 or the check's 3 minutes names the file. On the local route, a conflict pass the check stops is kept on the branch `pendulum/<issue>-conflict-pass` of the Objective's clone, `.pendulum/<issue>/repo` (the last one only: a later push of the branch removes it, and so does a later Block with nothing to keep, which says so), and the Block gives its full sha and how to deliver it: check that it keeps the Objective's change and touches no secret or protected path, since Pendulum's push checks did not run on it, then `git push --force-with-lease origin pendulum/<issue>-conflict-pass:pendulum/<issue>` in that clone and resume through Draft; the stages after it validate and review that head like any other. A file the branch's commits changed and then undid, which the head changes anyway, is no loss: when the branch goes out, a line on the progress comment says so for the review. With no decider (`decision_route` off, or `gateway` with no key), a path not exactly the branch's falls back to matching the branch's commits in the head by author, author time and subject (a commit git dropped because the base already has its change is no loss), as does a stage with no decider whose git is older than 2.40; with a key, such a git Blocks naming its version. The check asks whether the branch's change is still there; whether the joined code still works (a call to something the default branch renamed, a semantic clash that keeps every line) is for validation, CI and the reviewer. As a fallback, the dispatcher Blocks, naming the files, a PR that still conflicts while the default branch is the base the last pushed rebase was made onto. The bound is 5 rebases in 24 hours by default (`rebase_limit`), so two Objectives cannot chase each other forever; a batch of five parallel Objectives has at most four siblings merging ahead of one. Only Pendulum's own markers and records count, and a tick that cannot read them, or the Objective label's time, holds the PR until the next. A PR that only fell behind and whose update-branch GitHub fails for now waits for the next tick; one GitHub refuses goes to the worker under these rules. A PR the merge queue takes out for a conflict with a PR ahead of it counts as no drop: Pendulum puts it back once no PR in the queue conflicts with it, by a trial merge of the two heads against the default branch (git merge-tree in a scratch mirror), and at once when a trial merge cannot be computed (the queue then answers). Each time it goes back in, Pendulum records on the issue the queue's state then (the default branch's head and every entry's head); taken out for a conflict again, it goes back in only once that state has changed, so a conflict pairwise trials cannot see (one with the queue's merge group) never loops. This is the same on every route and harness: nothing is enqueued for a conflicting PR, it stays delivered, and the send-back takes it (`pendulum run --wait` does the send-back itself). The card moves to Done and the issue closes. +6. **Blocked.** The PR becomes a draft, the card moves to Blocked, and one comment states the reason (validation failed twice, reviewer findings unaddressed, dollar or time cap reached, worker died twice, rebasing makes no progress or reached its bound). The queue does not wait. A human fixes it by pushing to the branch or editing the issue and resuming through Draft; a local Block on hosts the sandbox denied names them and its own fix (Exit: blocked, below). +7. **Stopped.** A person applies `pendulum:draft` or closes the issue. Removing `pendulum:objective` also stops an issue for backward compatibility. Nothing lists a stopped Objective for a start (the dispatcher, the local loop's resumes and reviews, the sandbox launcher, the review job). A running stage reads its issue once a minute and on the stop ends every harness pass (`lib/stop.mjs`), records the spend so far and exits with `exit: stopped`; from the stop on it starts no pass, command, push or PR change, and it writes its usage and spend line before any other GitHub call (at two minutes it writes what it knows at once and exits). A pass ended before it reported dollars, or still running, is a run of unknown cost, as on the spend line. A cloud sandbox stage that its launcher process ends instead (its wall clock) records the stage as a run of unknown cost too (`stage.mjs` `killedUsage`), never `max_usd` or another bound, so `daily_usd` names it without counting it. A stop racing the stage's own exit (one being applied, or its merge) ends nothing, and the merge pass reads the issue before any merge, so a stopped Objective never merges; its PR leaves the merge queue and becomes a draft without `pendulum:review`, and its state label and card go back to Queued. The dispatcher does the same for a stopped Objective In review, and for a Running one ten minutes after the stop. A trusted Draft removal continues it after the stop or Block. 8. **Restarted.** A person who can push (or a named maintainer) applies `pendulum:restart`, in any state; anyone else's label comes off with a comment. A running stage stops as in 7; one that missed the label learns of the restart from its record, newer than its start, at its watch and before it pushes or writes its exit. The dispatcher of the Objective's route holds it while a stage of it may run, whatever its state (an Actions work or review job, a sandbox lease, a local loop's live claim; a read that fails counts as may run), for at most 10 minutes from the label; no merge or send-back touches it, and the merge pass reads the issue before any merge. Then it writes a restart record on the issue (the label's time, who applied it, the earlier PR and the branch's last commit, kept across a retry), which says first what the restart discards: the PR with its review, the branch's commits with the command that restores them, and the spend on them; takes the earlier PR out of the queue, deletes `pendulum/<issue>` (read back: a ruleset that keeps it Blocks the Objective with the fix), comments on and closes the PR, renames the plan comment's and the parts record's markers, removes the state labels and then the restart label, and queues the Objective: the next run starts from the default branch and the issue's current text. A maintainer comment, a plan comment or a parts record made before the label's time is read by no stage any more (`logic.mjs` `maintainerDecisions`, `handoff.mjs` `planOf`, `partsRecord`). Every retry and rebase count starts over with the new PR and Running stint. Until then nothing starts it: the dispatcher holds it, and the launcher, the review job, the worker and the local loop skip it. ## The task card and the skills @@ -207,8 +207,8 @@ The worker's instructions are a short task card (`plugin/templates/task-card.md` | Allowed | Any file not on the protected list (`.github/`, `CODEOWNERS`, `.agents/skills/`, `.claude/`, `.codex/`, the files the `setup` command names, plus the repository's `protected_paths`), and anything else but what the `setup` command runs (ADAPTERS.md, Setup is trusted like CI). Any command the runner allows. Sub-agents on the pinned model. Network: the hosts the harness's sandbox allows (GitHub, the npm and Yarn registries, plus `allowed_domains`; locally `PENDULUM_LOCAL_DOMAINS`). | | Not allowed | Asking. Editing a test to pass it unless the issue asks. Touching a protected path (the job refuses the commit, Pendulum refuses to push it); a change under `.github/workflows/` is handed over instead (Workflow hand-over, below). A stage answers only for what changes after it starts: what a maintainer pushed to the branch before it, and what a rebase takes from the default branch, are not its own; reverting a maintainer's change is. In a fix pass (after a red, or the answer pass after the review), changing toolchain, lockfile or CI configuration (version pins, package-manager config, including a `pnpm-workspace.yaml` change other than to its `packages` list alone, or one that does not parse, lockfiles, CI files outside `.github/`, containers and devcontainers, git hook managers, a path on the repository's `toolchain_paths`, a file the `setup` or an explicit `install` command names, other than a manifest, lockfile or requirements file it reads, a `package.json` script either runs, and, when either may run a file Pendulum cannot name, any file) that the branch had not changed before the stage's first fix pass, that the plan as it stood then does not name (the plan is read once per stage: a fix pass that edits it widens a later stage's scope, never its own stage's), and that the issue, a maintainer decision, the red's failure window or the comment answered does not name either (a lockfile is in scope when its own manifest beside it is: changed before, named, or changed by the same pass, as when the fix adds a dependency, so `package.json` brings `package-lock.json`, `pnpm-lock.yaml` or `yarn.lock`, `pyproject.toml` brings `uv.lock` or `poetry.lock`, `Cargo.toml` brings `Cargo.lock` (`lib/logic.mjs` `LOCK_PAIRS` lists every pair), and nothing else; in a workspace, a member's manifest changed before or by the same pass brings the workspace's root lockfile, and only it: `pnpm-lock.yaml` for a `pnpm-workspace.yaml`, the npm, yarn or bun lockfile for `package.json` `workspaces`, `uv.lock` for `[tool.uv.workspace]`, `Cargo.lock` for Cargo `[workspace]`, members as that declaration listed them when the fix passes began, exclusions honoured; a lockfile changed without its manifest or a member's in scope is refused), unless the fence check (`lib/fence-check.mjs`), a decision call given the failing checks' lead lines, the comments answered, the plan and the pass's textual diff to the file (up to 32 KiB), judges that file's change part of fixing the red rather than weakening or sidestepping the check. It is asked only about a lockfile that exists as a regular file both before the fix passes and at the pass's head (one the pass creates or deletes can change which install `install: auto` runs), at most 10 files each time the fence is read, and no file again in a stage once it has been refused twice (the same change is never asked about twice); a lockfile the setup command's install reads is judged too, as its manifest beside it in scope already lets it go. It is never asked about anything else (version pins, CI files, git hook managers, containers and devcontainers, build-tool wrappers, package-manager configuration, a `toolchain_paths` file, a protected path, or what the `setup` or `install` command names or runs), nor about a binary or empty change; it reads its verdict at the confidence floor, never under 0.7 whatever `triage_min_confidence` says; and with no decider, no answer or any other verdict the file stays refused: the pass gets one turn to put those files back, and what it keeps is refused (Pendulum pushes none of it, posts no PR body, reply or thread resolution from that pass, and the stage Blocks with the files named, as Pendulum's or an outage's when the fence check gave no answer on every one of them). A turn that puts them back and asks a Question in its exit record ends the stage with that Question; no further fix pass runs. Any write to GitHub: no push, PR, comment, reply or label. | | Exit: delivered | PR open and not a draft; validation green, or (the work stage, with required checks) its head handed to the review with its checks running; reviewer pass done. The merge queue takes it. | -| Exit: question | The worker hit an assumption that would change or remove an existing public contract, contradict a recorded decision or grant new access (a permission, a credential, a newly exposed service); any other addition that leaves every existing use working is an assumption. Each question in the exit record names its test (`contract`, `decision` or `access`) and the existing contract, the decision or the access granted; a question exit that names none is checked once by the harness, which keeps what meets a test and records the rest as assumptions. The PR stays a draft with the question in its body; everything else is finished. The card moves to In review with a question marker; the queue continues. A human answers in a comment, review or line comment on the PR or the issue and marks the PR ready; the review job runs, and its answer pass applies what was said since the question even when the PR was already reviewed, and the commits it makes for it get a reviewer pass before the merge; with nothing new, the PR goes back to a Question. On Actions, when a maintainer both answers and marks the PR ready while the review job that raised the Question is still running, that job leaves the PR ready, and the review job the ready mark started applies the answer. Comments by people with write access reach every worker, reviewer and answer pass as the maintainers' decisions. One Question comes before the work: Pendulum works in one repository per Objective, so a plan that needs a change in another repository (its `Needs-Repository: OWNER/NAME` line) stops after the plan (Pendulum stops the harness when the line appears in its plan.md, read every two minutes), and Pendulum runs no validation or fix pass and asks on the issue, naming the repository and how to answer: split the Objective into one per repository and re-apply the label, or say in a comment on the issue how to do the work in this repository alone (not by marking a PR ready). A maintainer's comment on the issue after a Question asked there (one with no PR, or the plan-time Question) puts the Objective back in the queue at the dispatcher's next tick on every route (`dispatch.mjs`; on the cloud sandbox the comment's own launch does it first), and the worker runs again with it, when the answer check lets it through (`lib/answer-check.mjs`). The answer check is a decision call (below): given the Question as Pendulum's notice on the issue asked it and each writer comment since, oldest first, do the comments give a decision on the question asked, so that the work can continue? Only `no_decision` at the confidence floor or more (Red-check triage, below) keeps the Question open; a decision, a lower confidence, no answer or no decider resumes the work, as a writer's comment always did. The newest comment's version (an edit is a new one) is what is judged, and each verdict is kept on the issue by Pendulum's own login: a decision as a short record, a no decision as a notice saying the comment does not answer, itself a Question notice. So no version is judged twice, on any route, and one judged no decision never resumes the Question. The dispatcher and the launcher have no stage harness, so they ask only with an AI Gateway key (on Actions the dispatch job never has one; the launch job does), and a comment that does not answer then starts no stage. Otherwise the work stage the comment resumes asks first thing, once its decider exists and before its branch, its Running mark, setup, install, the hand-off or the relay, on its own decider (the gateway with a key, else its harness); on a no decision it puts the Objective back to Question and posts that notice, or says the one already kept again, dated after the label, and a notice that cannot be written Blocks. A stage that resumes no Question (a send-back, a delivered or Blocked Objective, a re-applied label: a person's go) asks nothing. A Question its PR asks is still answered by the comment and the ready mark together, unjudged. Which of the two forms a Question has is one decision (`logic.mjs` `questionForm`): it chooses the notice's instruction and is written in the notice's marker, from which the dispatcher reads it. A person's ready mark on the PR while the Objective is Queued or Running starts no review: its work stage owns the branch. An issue body that names another repository for Pendulum to change (its `Pendulum-Repository: OWNER/NAME` line) is asked before any harness runs, and is answered only by taking the line out of the body: while it stays, each rerun asks again, with no harness started. A value that is no OWNER/NAME (`none`, `N/A`, a parenthesis) is no need, and a repository the plan needs is not asked about again once the maintainers' comments since Pendulum asked answer how to handle it. That is the plan-answer check (`lib/plan-answer.mjs`), a decision call (below) on triage's model and confidence floor (Red-check triage, below), given Pendulum's question line for the repository and each maintainer comment since the ask: `answered` at the floor or more answers it, `open` at the floor or more leaves it asked; with no verdict or no decider, a comment that names the repository answers it. | -| Exit: blocked | Validation red after a fix pass that made no progress (`lib/fix-progress.mjs`; no fixed count of passes: the loop goes on while each fix pass makes progress, within `max_usd` and the stage's wall clock). A red triage reads as a flake is rerun first (Red-check triage, below), so only a red that stands is judged. After a fix pass, the next red is judged against the red the pass was handed. Its failing set is the failed check runs (a roll-up required check with no failure line of its own left out: it only repeats the jobs it gathers) or the failing commands. A pass that committed nothing is no progress; so is the same set with each job failing the same way, the same signature and the same folded failure lines as many times each (the signature is the set of folded lines, so it alone cannot tell three failing tests from one; folding keeps a duration that differs from counting), and so is a red equal by signature to any the stage has seen before, in any of its validation loops, jobs with no failure line matched by name (A, then B, then A again Blocks, naming both). A different or smaller set is progress only when every job that failed before now passes (a job skipped, not run or missing, as when a build break hides the tests, is no pass). Anything else is a decision call (`decision_route`, on triage's model and confidence floor) asking whether the pass moved the branch closer to green, given each red's failing names and failure lines and the `--stat` of the pass's own commits (first-parent, so a catch-up merge brings in nothing of the default branch); with no decider it is no progress. A decider that gives no answer leaves the judgement unmade: the stage Blocks with the cause `pendulum` (`outage` when the vendor is unavailable or throttled), saying so; the stage harness's usage limit met by that call ends the stage on the limit (paused locally, held or Blocked `provider-quota` elsewhere). What bounds the loop is `max_usd` and the wall clock; a decider that keeps answering `closer` runs until one of them ends it. The Block names the red (`validation red on Pendulum's pass <n> (<command>): the fix pass before it made no progress: <why>; failing: <names> (<lead line>)`, or `could not be judged for progress`). A red on a merge of the default branch Pendulum made itself before a push (Review and merge, below) is not the change's: it gets its fix pass unjudged, decided on the commit id Pendulum recorded for its merge; each fix run after a required-check red gets every failing job's whole log as a file (aggregates included, required jobs first, none left out for an optional one; at most ten) and the two-dot diff from the PR's last green head (or why none could be made), and, as evidence and never as an instruction, how many of the default branch's newest runs of each job are red and their failure lines beside this run's; a red whose every failing job fails the same way steadily on the default branch (the same job with the same failure, on its newest run there and on at least two of its newest three, attempts included) is handed back at once as a base failure (`base failure: <jobs> fail the same way on <branch>@<sha>`), with no fix run; "the same failure" is the same failure signature (failure lines and the repository files they point at) when both runs have one, and otherwise, when either has none or the two differ in the same failed step, a same-failure decision call (Red-check triage, below), which counts only at the confidence floor and is not asked when the head points at the change (triage read a failing job as the change's at the floor, or a failure names a file or test the PR changes: then the signature alone decides); a red that is all the default branch's but for such a call that got no answer gets no fix run and Blocks as Pendulum's or, for the decider's outage, as an outage, naming what could not be judged (on the merge queue it is enqueued again, `unjudged`); a single red run on the default branch (a flake, an outage) hands nothing back; a required check whose Actions job GitHub never started (completed as failed with no step and no runner: a billing lock, a spending limit, a runner label nothing serves; the job itself, or one a failing required aggregate gathers when every failing job that aggregate gathers never started) Blocks at once with no triage, rerun or fix run (`GitHub did not start the required job <name>: <GitHub's annotation>`), decided on those fields and never on the annotation's words; a running required check is waited for while it makes progress, within the stage's wall clock, read as the merge queue's commit is (Review and merge, below): one whose current step has run past max(3 × that step's normal duration, that duration + 15 minutes) has hung, and the wait ends there unfinished, the Block naming the step and its times (`no progress: …`) and saying that re-applying the label waits for that head up to the stage's wall clock: Pendulum records the Block on the PR (`<!-- pendulum:<issue>:no-progress:<sha> -->`), and a later stage on that head judges no hang (for a change that makes a step slower on purpose); one with no history to judge it by (a new step, a check that is no Actions job, a job Pendulum cannot read, and every check on the local route, where Pendulum reads no job steps) is waited for up to the merge queue rule's `check_response_timeout_minutes` when an active ruleset on the default branch sets one, else the stage's wall clock; its job is read only once it could have hung, and again only when that reading could have changed the answer (a job that could not be read, likewise); a required check that is not running (queued, waiting, or not reported, with no upstream job of it running) for 60 minutes ends the wait, as the not-started bound below; required commit statuses are read beside the check runs, while a required name has no check run: a pending status is a check running, a failing one a red; the reads are a minute apart for the first hour, then back off to five, and are conditional (an unchanged page answers 304, outside GitHub's rate limit); a wait on the required checks that ends with none failed and some not finished is no red at all: no triage, no fix run and no pass counted; read on structure from the head's check runs and workflow runs, a required check not started yet (its check run still queued with no runner, in a workflow run still going or one that completed; or, with no check run, the workflow that produces it queued on the head, or never created) is waited for in the stage, on every route, up to 60 minutes or the stage's wall clock less 5 minutes, the reads backing off from one minute to five; one that starts during that wait and is still running at its end is waited for as any running check; still not started, the stage Blocks naming the run, how long it sat and who has not started it: GitHub (`GitHub has not started the required check(s) <names> on <sha>: workflow run <name> (run <id>) queued <N> min with no job started (infrastructure, not this change)`), the service whose app owns the check run (`<app> has not started …`), or a run `pending` behind the repository's own concurrency group (`The repository's concurrency group holds …`); the workflow that produces a check is the one of the repository's workflows (read at the head) with a job reporting that name (its `name`, a `${{ }}` in it standing for any text, else its id; a matrix job adds ` (…)`; a job calling a reusable workflow reports `<caller> / <callee's job>`, read from this repository, any name under the caller for another repository's), else the workflow of that check's run on the PR's last green head or the default branch's newest commits; a queued run of another workflow is not that check's; a check is filtered out, and Blocks at once naming the filter (`run the check on every change, or stop requiring it`), only when that is certain: every workflow that produces it has an `on.pull_request` `paths` or `paths-ignore` that skips the PR's changed files (read, and not none), `pull_request` is the only trigger that can start it on the head (beside `merge_group`, `schedule`, `workflow_call`, `workflow_run` and `release`), and its patterns use only `*`, `**` and `!` (GitHub's `?`, `+` and `[…]` are not guessed at); anything less certain, a companion `paths-ignore` workflow of the same check included, is waited for, and the Block's reason says the path filter may skip the change; each workflow file is read once per stage; a failed read of the check runs keeps the last good reading once one has succeeded, and the wait goes on to its own deadline (with none yet, it ends at the first 15 minutes as before); a check whose producing workflow run ended `startup_failure`, or was cancelled before the job that reports it existed, Blocks naming that run and its conclusion, never the check names, as soon as every workflow run on the head has completed and each run that produces the check ended so (cancelled counts only with no check run in its suite); a check no workflow on the head produces (`check the required check names`, naming each run on the head and how it ended), or whose workflow's path filter skips the change, Blocks as soon as every workflow run on the head has completed, when nothing else may still report it: the default branch's ruleset binds the check to Actions, or binds it to no app and no check suite on the head of any app but Actions is still going (suites that cannot be read count as going; a check bound to another app never ends the wait early); a name older commits got as a commit status (read from the PR's last green head and the default branch's newest commits, as for check runs) is that status's service's to post, and is waited for as not started (`the service posting it has not started …`); no workflow at the head runs `on: workflow_run` (a workflow file that cannot be read, or a reusable workflow it calls through `uses: ./…` that cannot be read, counts as one); and no triage rerun is awaited; otherwise the 60 minutes with nothing running end the wait; the reading is classified again only when the head's runs or suites read differently; a check waiting for a deployment approval, one still running, and one no workflow on the head produces (`check the required check names`) Block at once with that reason, never as validation red; a last red whose triage read every failing job as a flake but whose rerun GitHub refused Blocks saying so, with triage's verdicts, the refusal and the remedy (rerun the failed jobs, or give the token Actions write: the workflow's `actions: write` on Actions, the local token's Actions read and write); a fix pass that commits nothing leaves the red head as it was, so its checks are not read again as a second red and no pass is counted: the failed jobs are rerun once for that head (no question asked, with or without a decider) only when nothing reads the red as the change's (no `change_caused` verdict on that head, no failure naming what the PR changes, no failure signature already rerun on the Objective, at most ten jobs) and each failing job either got a model verdict on that head or failed on GitHub's side (below), and when a rerun is not made for any of those reasons, already made on that head or red again and the red is the work's (not one whose every failed job failed on GitHub's side, below, before and after the head's rerun), the Objective gets one fresh worker pass before it Blocks. The red it is given is the one as it stands after the head's rerun, when one was made (it can fail another way than the red the fix pass had): read like any red, so one the default branch fails the same way is handed back as a base failure with no fresh pass, and the pass's scope fence names it as a fix pass's does. The pass is a new session, never a resume, given the task card, that red's failing jobs' own failure lines and outputs as a fix pass gets them, and the fix pass's last message as evidence; it runs once per head in a stage and is not counted as a pass. It runs only when what is left can carry it, read after the rerun's red: with `max_usd` set, at least what the fix pass cost (Codex has no in-run cap, so a smaller remainder would be overspent), and wall clock for the fix pass's own time, the head's checks' wait and two minutes for the exit (a minute at least). The progress comment says it ran, or why not. What it commits is validated as the next pass, judged for progress against the red it was handed, and the stage's session stays the fresh pass's; a Block for validation red after it then names it (`…; a fresh worker pass followed the fix pass that changed nothing on <sha>`). A fresh pass that commits nothing, read on the checkout's HEAD before and after it, hands the stage's session back to the worker's thread, a capped one included. A rerun refused, a red on GitHub's side, a fresh pass that commits nothing or one not given Blocks (`the fix pass changed nothing, so the red on <sha> is unchanged (<the failure's lead line>); …`, `the fix pass and the fresh worker pass after it changed nothing, …` when one ran, then the refusal or the remedy, and `; no fresh worker pass: <why>` when none was given); a fresh pass that reaches its dollar or time cap Blocks the same way, the work's, ending `; the fresh worker pass after it reached the dollar cap` (or `time cap`), unless it committed: then the Block says `the fix pass changed nothing on <sha> (<lead>); the fresh worker pass committed <sha'> and reached the dollar cap; not validated`, the stage pushes that commit unvalidated and its session stays the fresh pass's; the Block's quoted output leads with the red required checks (`PENDULUM_CI_CHECKS`, else the ruleset's), each named `<check> (required check)` with its own failure lines; a required roll-up with none of its own (an aggregate) is quoted from a failing job it gathers (`<check> (required check), from <job>`): the jobs its job `needs` in its workflow file at the run's head, directly or through jobs between them (a skipped one included), a run `<caller> / …` counting as the job that calls a reusable workflow, else (no file, or none of those with a failure line) every failing job of its run, one whose job cannot fail without failing the run first (its `continue-on-error`, a `${{ }}` expression of at most 1 KB evaluated over the leg's matrix values (the leg found by its check name: its values in a ` (…)` suffix, or a job name with `${{ }}` evaluated the same way for each leg) with GitHub's own expression library, `@actions/expressions`; unknown when it reads any other context or calls a function); the other failing jobs follow, each one no required check counts marked `not required`: a required check, a roll-up or not, counts the failing jobs of its own run that its job needs (read from that same file when its run has other failing jobs), less those that may fail without failing the run, and when the file cannot say, none of its run's jobs is called not required; reviewer findings still open after the answer rounds (Review and merge, below); the answer to a review pass on commits the answer gate held, held again (Review and merge, below); a send-back's rebase that makes no progress or reached its bound (Merge, above); dollar or time cap reached; worker process died twice; the model provider refused a harness call outright (a 4xx other than a timeout, conflict, too early or rate limit, or a quota, billing, authentication or permission type or code, read from the harness's own structured error: Claude Code's result `api_error_status`, Codex's `turn.failed` JSON error body, Copilot's `session.error`; never from the message's words), which is never counted as a death and Blocks at once (a resumed pass refused with a 400, 413 or 422 and no such type or code first runs once as a fresh session with the full card, where the pass has one, since its session's own request may be what was refused; the fresh pass's refusal stands) naming the harness, the status, type and code and the provider's message shortened (`<harness> was refused by its provider (HTTP 400 <type> <code>): …`), the fix being the credential's account or the settings; doctor's `--probe` fails on the same refusal. Draft PR, card to Blocked, one comment with the reason, the fix, and whether to resume or restart, decided on the Block's cause: any cause but `work` says resume (re-apply `pendulum:objective`, which goes on from the branch and PR), not restart; `work` says resume once the cause is fixed and restart only when the work itself must be redone; each names what a restart discards (the PR, delivered or not, with its review, the branch's commits and the spend on them). A restart that could not finish says how to keep the work instead, and an untrusted author's Block says neither gets past it. A worker's own reason, like a Question's, is shortened past 200 characters on a word boundary and ends in `…`. A worker that stops because its sandbox denied a host it cannot do without lists the host names in its exit record's `deniedHosts` (values that are not a DNS host name are dropped; at most ten); in local mode the comment names each host the sandboxes do not already allow and gives that fix instead of a push or an edit: add them to `PENDULUM_LOCAL_DOMAINS`, then re-apply `pendulum:objective`. Pendulum never allows a host itself. | +| Exit: question | The worker hit an assumption that would change or remove an existing public contract, contradict a recorded decision or grant new access (a permission, a credential, a newly exposed service); any other addition that leaves every existing use working is an assumption. Each question in the exit record names its test (`contract`, `decision` or `access`) and the existing contract, the decision or the access granted; a question exit that names none is checked once by the harness, which keeps what meets a test and records the rest as assumptions. The PR stays a draft with the question in its body; everything else is finished. The card moves to In review with a question marker; the queue continues. A human answers in a comment, review or line comment on the PR or the issue and marks the PR ready; the review job runs, and its answer pass applies what was said since the question even when the PR was already reviewed, and the commits it makes for it get a reviewer pass before the merge; with nothing new, the PR goes back to a Question. On Actions, when a maintainer both answers and marks the PR ready while the review job that raised the Question is still running, that job leaves the PR ready, and the review job the ready mark started applies the answer. Comments by people with write access reach every worker, reviewer and answer pass as the maintainers' decisions. One Question comes before the work: Pendulum works in one repository per Objective, so a plan that needs a change in another repository (its `Needs-Repository: OWNER/NAME` line) stops after the plan (Pendulum stops the harness when the line appears in its plan.md, read every two minutes), and Pendulum runs no validation or fix pass and asks on the issue, naming the repository and how to answer: split the Objective into one per repository and resume through Draft, or say in a comment on the issue how to do the work in this repository alone (not by marking a PR ready). A maintainer's comment on the issue after a Question asked there (one with no PR, or the plan-time Question) puts the Objective back in the queue at the dispatcher's next tick on every route (`dispatch.mjs`; on the cloud sandbox the comment's own launch does it first), and the worker runs again with it, when the answer check lets it through (`lib/answer-check.mjs`). The answer check is a decision call (below): given the Question as Pendulum's notice on the issue asked it and each writer comment since, oldest first, do the comments give a decision on the question asked, so that the work can continue? Only `no_decision` at the confidence floor or more (Red-check triage, below) keeps the Question open; a decision, a lower confidence, no answer or no decider resumes the work, as a writer's comment always did. The newest comment's version (an edit is a new one) is what is judged, and each verdict is kept on the issue by Pendulum's own login: a decision as a short record, a no decision as a notice saying the comment does not answer, itself a Question notice. So no version is judged twice, on any route, and one judged no decision never resumes the Question. The dispatcher and the launcher have no stage harness, so they ask only with an AI Gateway key (on Actions the dispatch job never has one; the launch job does), and a comment that does not answer then starts no stage. Otherwise the work stage the comment resumes asks first thing, once its decider exists and before its branch, its Running mark, setup, install, the hand-off or the relay, on its own decider (the gateway with a key, else its harness); on a no decision it puts the Objective back to Question and posts that notice, or says the one already kept again, dated after the label, and a notice that cannot be written Blocks. A stage that resumes no Question (a send-back, a delivered or Blocked Objective, or a person's Draft removal) asks nothing. A Question its PR asks is still answered by the comment and the ready mark together, unjudged. Which of the two forms a Question has is one decision (`logic.mjs` `questionForm`): it chooses the notice's instruction and is written in the notice's marker, from which the dispatcher reads it. A person's ready mark on the PR while the Objective is Queued or Running starts no review: its work stage owns the branch. An issue body that names another repository for Pendulum to change (its `Pendulum-Repository: OWNER/NAME` line) is asked before any harness runs, and is answered only by taking the line out of the body: while it stays, each rerun asks again, with no harness started. A value that is no OWNER/NAME (`none`, `N/A`, a parenthesis) is no need, and a repository the plan needs is not asked about again once the maintainers' comments since Pendulum asked answer how to handle it. That is the plan-answer check (`lib/plan-answer.mjs`), a decision call (below) on triage's model and confidence floor (Red-check triage, below), given Pendulum's question line for the repository and each maintainer comment since the ask: `answered` at the floor or more answers it, `open` at the floor or more leaves it asked; with no verdict or no decider, a comment that names the repository answers it. | +| Exit: blocked | Validation red after a fix pass that made no progress (`lib/fix-progress.mjs`; no fixed count of passes: the loop goes on while each fix pass makes progress, within `max_usd` and the stage's wall clock). A red triage reads as a flake is rerun first (Red-check triage, below), so only a red that stands is judged. After a fix pass, the next red is judged against the red the pass was handed. Its failing set is the failed check runs (a roll-up required check with no failure line of its own left out: it only repeats the jobs it gathers) or the failing commands. A pass that committed nothing is no progress; so is the same set with each job failing the same way, the same signature and the same folded failure lines as many times each (the signature is the set of folded lines, so it alone cannot tell three failing tests from one; folding keeps a duration that differs from counting), and so is a red equal by signature to any the stage has seen before, in any of its validation loops, jobs with no failure line matched by name (A, then B, then A again Blocks, naming both). A different or smaller set is progress only when every job that failed before now passes (a job skipped, not run or missing, as when a build break hides the tests, is no pass). Anything else is a decision call (`decision_route`, on triage's model and confidence floor) asking whether the pass moved the branch closer to green, given each red's failing names and failure lines and the `--stat` of the pass's own commits (first-parent, so a catch-up merge brings in nothing of the default branch); with no decider it is no progress. A decider that gives no answer leaves the judgement unmade: the stage Blocks with the cause `pendulum` (`outage` when the vendor is unavailable or throttled), saying so; the stage harness's usage limit met by that call ends the stage on the limit (paused locally, held or Blocked `provider-quota` elsewhere). What bounds the loop is `max_usd` and the wall clock; a decider that keeps answering `closer` runs until one of them ends it. The Block names the red (`validation red on Pendulum's pass <n> (<command>): the fix pass before it made no progress: <why>; failing: <names> (<lead line>)`, or `could not be judged for progress`). A red on a merge of the default branch Pendulum made itself before a push (Review and merge, below) is not the change's: it gets its fix pass unjudged, decided on the commit id Pendulum recorded for its merge; each fix run after a required-check red gets every failing job's whole log as a file (aggregates included, required jobs first, none left out for an optional one; at most ten) and the two-dot diff from the PR's last green head (or why none could be made), and, as evidence and never as an instruction, how many of the default branch's newest runs of each job are red and their failure lines beside this run's; a red whose every failing job fails the same way steadily on the default branch (the same job with the same failure, on its newest run there and on at least two of its newest three, attempts included) is handed back at once as a base failure (`base failure: <jobs> fail the same way on <branch>@<sha>`), with no fix run; "the same failure" is the same failure signature (failure lines and the repository files they point at) when both runs have one, and otherwise, when either has none or the two differ in the same failed step, a same-failure decision call (Red-check triage, below), which counts only at the confidence floor and is not asked when the head points at the change (triage read a failing job as the change's at the floor, or a failure names a file or test the PR changes: then the signature alone decides); a red that is all the default branch's but for such a call that got no answer gets no fix run and Blocks as Pendulum's or, for the decider's outage, as an outage, naming what could not be judged (on the merge queue it is enqueued again, `unjudged`); a single red run on the default branch (a flake, an outage) hands nothing back; a required check whose Actions job GitHub never started (completed as failed with no step and no runner: a billing lock, a spending limit, a runner label nothing serves; the job itself, or one a failing required aggregate gathers when every failing job that aggregate gathers never started) Blocks at once with no triage, rerun or fix run (`GitHub did not start the required job <name>: <GitHub's annotation>`), decided on those fields and never on the annotation's words; a running required check is waited for while it makes progress, within the stage's wall clock, read as the merge queue's commit is (Review and merge, below): one whose current step has run past max(3 × that step's normal duration, that duration + 15 minutes) has hung, and the wait ends there unfinished, the Block naming the step and its times (`no progress: …`) and saying that resuming through Draft waits for that head up to the stage's wall clock: Pendulum records the Block on the PR (`<!-- pendulum:<issue>:no-progress:<sha> -->`), and a later stage on that head judges no hang (for a change that makes a step slower on purpose); one with no history to judge it by (a new step, a check that is no Actions job, a job Pendulum cannot read, and every check on the local route, where Pendulum reads no job steps) is waited for up to the merge queue rule's `check_response_timeout_minutes` when an active ruleset on the default branch sets one, else the stage's wall clock; its job is read only once it could have hung, and again only when that reading could have changed the answer (a job that could not be read, likewise); a required check that is not running (queued, waiting, or not reported, with no upstream job of it running) for 60 minutes ends the wait, as the not-started bound below; required commit statuses are read beside the check runs, while a required name has no check run: a pending status is a check running, a failing one a red; the reads are a minute apart for the first hour, then back off to five, and are conditional (an unchanged page answers 304, outside GitHub's rate limit); a wait on the required checks that ends with none failed and some not finished is no red at all: no triage, no fix run and no pass counted; read on structure from the head's check runs and workflow runs, a required check not started yet (its check run still queued with no runner, in a workflow run still going or one that completed; or, with no check run, the workflow that produces it queued on the head, or never created) is waited for in the stage, on every route, up to 60 minutes or the stage's wall clock less 5 minutes, the reads backing off from one minute to five; one that starts during that wait and is still running at its end is waited for as any running check; still not started, the stage Blocks naming the run, how long it sat and who has not started it: GitHub (`GitHub has not started the required check(s) <names> on <sha>: workflow run <name> (run <id>) queued <N> min with no job started (infrastructure, not this change)`), the service whose app owns the check run (`<app> has not started …`), or a run `pending` behind the repository's own concurrency group (`The repository's concurrency group holds …`); the workflow that produces a check is the one of the repository's workflows (read at the head) with a job reporting that name (its `name`, a `${{ }}` in it standing for any text, else its id; a matrix job adds ` (…)`; a job calling a reusable workflow reports `<caller> / <callee's job>`, read from this repository, any name under the caller for another repository's), else the workflow of that check's run on the PR's last green head or the default branch's newest commits; a queued run of another workflow is not that check's; a check is filtered out, and Blocks at once naming the filter (`run the check on every change, or stop requiring it`), only when that is certain: every workflow that produces it has an `on.pull_request` `paths` or `paths-ignore` that skips the PR's changed files (read, and not none), `pull_request` is the only trigger that can start it on the head (beside `merge_group`, `schedule`, `workflow_call`, `workflow_run` and `release`), and its patterns use only `*`, `**` and `!` (GitHub's `?`, `+` and `[…]` are not guessed at); anything less certain, a companion `paths-ignore` workflow of the same check included, is waited for, and the Block's reason says the path filter may skip the change; each workflow file is read once per stage; a failed read of the check runs keeps the last good reading once one has succeeded, and the wait goes on to its own deadline (with none yet, it ends at the first 15 minutes as before); a check whose producing workflow run ended `startup_failure`, or was cancelled before the job that reports it existed, Blocks naming that run and its conclusion, never the check names, as soon as every workflow run on the head has completed and each run that produces the check ended so (cancelled counts only with no check run in its suite); a check no workflow on the head produces (`check the required check names`, naming each run on the head and how it ended), or whose workflow's path filter skips the change, Blocks as soon as every workflow run on the head has completed, when nothing else may still report it: the default branch's ruleset binds the check to Actions, or binds it to no app and no check suite on the head of any app but Actions is still going (suites that cannot be read count as going; a check bound to another app never ends the wait early); a name older commits got as a commit status (read from the PR's last green head and the default branch's newest commits, as for check runs) is that status's service's to post, and is waited for as not started (`the service posting it has not started …`); no workflow at the head runs `on: workflow_run` (a workflow file that cannot be read, or a reusable workflow it calls through `uses: ./…` that cannot be read, counts as one); and no triage rerun is awaited; otherwise the 60 minutes with nothing running end the wait; the reading is classified again only when the head's runs or suites read differently; a check waiting for a deployment approval, one still running, and one no workflow on the head produces (`check the required check names`) Block at once with that reason, never as validation red; a last red whose triage read every failing job as a flake but whose rerun GitHub refused Blocks saying so, with triage's verdicts, the refusal and the remedy (rerun the failed jobs, or give the token Actions write: the workflow's `actions: write` on Actions, the local token's Actions read and write); a fix pass that commits nothing leaves the red head as it was, so its checks are not read again as a second red and no pass is counted: the failed jobs are rerun once for that head (no question asked, with or without a decider) only when nothing reads the red as the change's (no `change_caused` verdict on that head, no failure naming what the PR changes, no failure signature already rerun on the Objective, at most ten jobs) and each failing job either got a model verdict on that head or failed on GitHub's side (below), and when a rerun is not made for any of those reasons, already made on that head or red again and the red is the work's (not one whose every failed job failed on GitHub's side, below, before and after the head's rerun), the Objective gets one fresh worker pass before it Blocks. The red it is given is the one as it stands after the head's rerun, when one was made (it can fail another way than the red the fix pass had): read like any red, so one the default branch fails the same way is handed back as a base failure with no fresh pass, and the pass's scope fence names it as a fix pass's does. The pass is a new session, never a resume, given the task card, that red's failing jobs' own failure lines and outputs as a fix pass gets them, and the fix pass's last message as evidence; it runs once per head in a stage and is not counted as a pass. It runs only when what is left can carry it, read after the rerun's red: with `max_usd` set, at least what the fix pass cost (Codex has no in-run cap, so a smaller remainder would be overspent), and wall clock for the fix pass's own time, the head's checks' wait and two minutes for the exit (a minute at least). The progress comment says it ran, or why not. What it commits is validated as the next pass, judged for progress against the red it was handed, and the stage's session stays the fresh pass's; a Block for validation red after it then names it (`…; a fresh worker pass followed the fix pass that changed nothing on <sha>`). A fresh pass that commits nothing, read on the checkout's HEAD before and after it, hands the stage's session back to the worker's thread, a capped one included. A rerun refused, a red on GitHub's side, a fresh pass that commits nothing or one not given Blocks (`the fix pass changed nothing, so the red on <sha> is unchanged (<the failure's lead line>); …`, `the fix pass and the fresh worker pass after it changed nothing, …` when one ran, then the refusal or the remedy, and `; no fresh worker pass: <why>` when none was given); a fresh pass that reaches its dollar or time cap Blocks the same way, the work's, ending `; the fresh worker pass after it reached the dollar cap` (or `time cap`), unless it committed: then the Block says `the fix pass changed nothing on <sha> (<lead>); the fresh worker pass committed <sha'> and reached the dollar cap; not validated`, the stage pushes that commit unvalidated and its session stays the fresh pass's; the Block's quoted output leads with the red required checks (`PENDULUM_CI_CHECKS`, else the ruleset's), each named `<check> (required check)` with its own failure lines; a required roll-up with none of its own (an aggregate) is quoted from a failing job it gathers (`<check> (required check), from <job>`): the jobs its job `needs` in its workflow file at the run's head, directly or through jobs between them (a skipped one included), a run `<caller> / …` counting as the job that calls a reusable workflow, else (no file, or none of those with a failure line) every failing job of its run, one whose job cannot fail without failing the run first (its `continue-on-error`, a `${{ }}` expression of at most 1 KB evaluated over the leg's matrix values (the leg found by its check name: its values in a ` (…)` suffix, or a job name with `${{ }}` evaluated the same way for each leg) with GitHub's own expression library, `@actions/expressions`; unknown when it reads any other context or calls a function); the other failing jobs follow, each one no required check counts marked `not required`: a required check, a roll-up or not, counts the failing jobs of its own run that its job needs (read from that same file when its run has other failing jobs), less those that may fail without failing the run, and when the file cannot say, none of its run's jobs is called not required; reviewer findings still open after the answer rounds (Review and merge, below); the answer to a review pass on commits the answer gate held, held again (Review and merge, below); a send-back's rebase that makes no progress or reached its bound (Merge, above); dollar or time cap reached; worker process died twice; the model provider refused a harness call outright (a 4xx other than a timeout, conflict, too early or rate limit, or a quota, billing, authentication or permission type or code, read from the harness's own structured error: Claude Code's result `api_error_status`, Codex's `turn.failed` JSON error body, Copilot's `session.error`; never from the message's words), which is never counted as a death and Blocks at once (a resumed pass refused with a 400, 413 or 422 and no such type or code first runs once as a fresh session with the full card, where the pass has one, since its session's own request may be what was refused; the fresh pass's refusal stands) naming the harness, the status, type and code and the provider's message shortened (`<harness> was refused by its provider (HTTP 400 <type> <code>): …`), the fix being the credential's account or the settings; doctor's `--probe` fails on the same refusal. Draft PR, card to Blocked, one comment with the reason, the fix, and whether to resume or restart, decided on the Block's cause: any cause but `work` says resume (resume through Draft to continue from the branch and PR), not restart; `work` says resume once the cause is fixed and restart only when the work itself must be redone; each names what a restart discards (the PR, delivered or not, with its review, the branch's commits and the spend on them). A restart that could not finish says how to keep the work instead, and an untrusted author's Block says neither gets past it. A worker's own reason, like a Question's, is shortened past 200 characters on a word boundary and ends in `…`. A worker that stops because its sandbox denied a host it cannot do without lists the host names in its exit record's `deniedHosts` (values that are not a DNS host name are dropped; at most ten); in local mode the comment names each host the sandboxes do not already allow and gives that fix instead of a push or an edit: add them to `PENDULUM_LOCAL_DOMAINS`, then resume through Draft. Pendulum never allows a host itself. | The Question exit does not stop the Objective's other work or the queue, and costs the worker nothing to raise, so it is raised only when the card's test is met. @@ -223,7 +223,7 @@ Workflow hand-over. Pendulum never pushes a change under `.github/workflows/`, o Trust. Pendulum acts on an Objective's text only when the issue's author, its last editor once the body was edited, and the person who made its latest rename once the title was renamed (that rename naming the title now) can push or are pinned maintainers. The worker and the review job check it before any harness on every route (Actions, local mode, a cloud-sandbox stage), acting on the title and body read with those people; a session reads the issue only through `pendulum issue`, and `deliver` and `post-review` check it again. Otherwise the stage Blocks before a harness sees the text. Pendulum acts on a marker (validated, rebase, review, spend, decisions-read, a local claim) only from its own login or from a person with push access. Its own login comes from its token, never from a comment's author: the App's bot on Actions, the token's owner in local mode. No other App counts, the job token's `github-actions[bot]` included. The workflow's `notify` and `maintainers` are written `login#id` and trusted by the numeric id, so a login renamed away is a stranger; doctor warns about a bare one and names the id to add. -Edits. The plan comment records the Objective text its plan was made from, on its marker line, written only by Pendulum: the SHA-256 of the title and body (line ends as LF, trailing whitespace dropped, so a save that changes nothing else is no edit), the time of the latest `pendulum:objective` label event, read before the text, when a work stage last started from that text, the text itself (title, body and harness, model and host labels: an edit's before) and the edit check's verdict for each later text, by its hash, as GitHub's 65,536-character limit leaves room for them, counted in UTF-8 bytes: the verdicts go first (they are asked again), the text only when it does not fit alone. In the record, `<` and `>` are JSON escapes, so no text in it closes the comment. A write of the plan comment keeps the verdicts another process wrote on it for the same text since this one read it. The plan comment read is the newest written by Pendulum's own login or a person who can push (local mode writes as its developer). No other App's comment counts, `github-actions[bot]` included: it never stands in for that comment. Only when there is none, the earliest App comment carrying the marker (Pendulum's App, read from a local process) counts for its time, so the stage decides on edit times (below) instead of on no plan; its text and any record in it are never read. After the trust check, each work stage and review job compares the text it read with that record before anything is set up for it, and the merge pass compares the text as it stands before it merges or enqueues, and while the PR waits in the merge queue (it is taken out of it). The same text goes on. A changed text is first judged by the edit check (`lib/edit-check.mjs`), a decision call asked once per distinct new text, its verdict written on the record: given the title and body before and after, does the edit change what has to be built? `wording` (typos, formatting, rewording only) at the confidence floor (Red-check triage, below) keeps the plan and the code: the stage goes on as on the same text, says so in one line on its progress comment (the verdict, the decider that gave it and its confidence), and the record still names the text the plan was made from, so the next edit is judged against that text too, and a work pass paused in local mode is held to that text (`lib/continue.mjs`) and continues. Any other answer, or none, is the rule below. A harness, model or host label added, removed or changed is a changed requirement as it stands, never asked about. The edit check is asked only on text that passed the trust check (its author, last editor and latest title renamer). A record without its text (one written before the record kept it, or one too long for the comment), a text whose hash is not the record's, a text too long to show the decider whole, or no decider (`decision_route` off, or `gateway` with no key) is never judged; with `decision_route` off a verdict the record keeps is not used either, and any verdict is used only after the same checks on the text now. A work stage started by the Objective label applied after its plan's record asks nothing and makes the plan again, a kept edit or not: the label is a person's own word. Where it is asked: a work or review stage asks at its start, once its harness, account and credential checks pass and before anything acts on the text, on the stage's decider (the gateway with a key, else its own harness on a credential read of its own, masked in what the stage saves: a federated key comes with no expiry, so the passes read theirs as they start, never one minted before setup and install); the merge pass, which has no stage harness, asks the gateway when its process holds the key (local mode's `~/.config/pendulum/ai-gateway-key`) and the route allows, and says a kept edit on a progress comment of its own; else, when another process may judge it (a stage's harness on `auto`, or on Actions a stage job's key on `gateway`), it puts the review label back on so the review stage's start judges it (on Actions the dispatcher's job holds no key, so it always does), and otherwise (`gateway` with no key, locally) Blocks; a session's `pendulum issue` and `post-review` ask the gateway only and write no verdict, and `deliver` writes the plan with the plan's own record when the edit was kept. Otherwise a changed text Blocks (cause `work`: an edit is a person's action) and the PR becomes a draft, unless the stage is a work stage and the label was applied again after the recorded time: then the plan is made again from the new text, the earlier plan comment is not handed to the harness, and the branch and PR carry over. A plan comment whose record cannot be read (none, one that does not parse, another App's) is decided on GitHub's edit times instead: a body edit (`lastEditedAt`) or a title change after the comment was posted is a change, and the label applied after that edit plans again. There a save that changed nothing still counts as an edit, since only a record's hash can tell; a plan comment without a record gets one at the next work stage. With no plan comment, a stage uses the text as it is, and a stage that knows no record never erases one. Comments are never edits. Pendulum's own login must be known for any of this; when it cannot be read, the stage stops. On a session's route, `pendulum issue` writes `plan.md` beside `issue.md` only when the plan was made from the current text (or the edit check read the edit as wording only), `deliver` delivers nothing when the issue changed after `pendulum issue` gave it to the session and records the text it gave with the plan, and `post-review` posts nothing on an Objective edited since its plan. +Edits. The plan comment records the Objective text its plan was made from, on its marker line, written only by Pendulum: the SHA-256 of the title and body (line ends as LF, trailing whitespace dropped, so a save that changes nothing else is no edit), the time of the latest trusted activation, read before the text, when a work stage last started from that text, the text itself (title, body and harness, model and host labels: an edit's before) and the edit check's verdict for each later text, by its hash, as GitHub's 65,536-character limit leaves room for them, counted in UTF-8 bytes: the verdicts go first (they are asked again), the text only when it does not fit alone. In the record, `<` and `>` are JSON escapes, so no text in it closes the comment. A write of the plan comment keeps the verdicts another process wrote on it for the same text since this one read it. The plan comment read is the newest written by Pendulum's own login or a person who can push (local mode writes as its developer). No other App's comment counts, `github-actions[bot]` included: it never stands in for that comment. Only when there is none, the earliest App comment carrying the marker (Pendulum's App, read from a local process) counts for its time, so the stage decides on edit times (below) instead of on no plan; its text and any record in it are never read. After the trust check, each work stage and review job compares the text it read with that record before anything is set up for it, and the merge pass compares the text as it stands before it merges or enqueues, and while the PR waits in the merge queue (it is taken out of it). The same text goes on. A changed text is first judged by the edit check (`lib/edit-check.mjs`), a decision call asked once per distinct new text, its verdict written on the record: given the title and body before and after, does the edit change what has to be built? `wording` (typos, formatting, rewording only) at the confidence floor (Red-check triage, below) keeps the plan and the code: the stage goes on as on the same text, says so in one line on its progress comment (the verdict, the decider that gave it and its confidence), and the record still names the text the plan was made from, so the next edit is judged against that text too, and a work pass paused in local mode is held to that text (`lib/continue.mjs`) and continues. Any other answer, or none, is the rule below. A harness, model or host label added, removed or changed is a changed requirement as it stands, never asked about. The edit check is asked only on text that passed the trust check (its author, last editor and latest title renamer). A record without its text (one written before the record kept it, or one too long for the comment), a text whose hash is not the record's, a text too long to show the decider whole, or no decider (`decision_route` off, or `gateway` with no key) is never judged; with `decision_route` off a verdict the record keeps is not used either, and any verdict is used only after the same checks on the text now. A trusted activation after a plan's record requests a new plan. The work stage makes it even if the edit check kept the prior plan. Where it is asked: a work or review stage asks at its start, once its harness, account and credential checks pass and before anything acts on the text, on the stage's decider (the gateway with a key, else its own harness on a credential read of its own, masked in what the stage saves: a federated key comes with no expiry, so the passes read theirs as they start, never one minted before setup and install); the merge pass, which has no stage harness, asks the gateway when its process holds the key (local mode's `~/.config/pendulum/ai-gateway-key`) and the route allows, and says a kept edit on a progress comment of its own; else, when another process may judge it (a stage's harness on `auto`, or on Actions a stage job's key on `gateway`), it puts the review label back on so the review stage's start judges it (on Actions the dispatcher's job holds no key, so it always does), and otherwise (`gateway` with no key, locally) Blocks; a session's `pendulum issue` and `post-review` ask the gateway only and write no verdict, and `deliver` writes the plan with the plan's own record when the edit was kept. Otherwise a changed text Blocks (cause `work`: an edit is a person's action) and the PR becomes a draft, unless the stage is a work stage and the Objective was activated again after the recorded time: then the plan is made again from the new text, the earlier plan comment is not handed to the harness, and the branch and PR carry over. A plan comment whose record cannot be read (none, one that does not parse, another App's) is decided on GitHub's edit times instead: a body edit (`lastEditedAt`) or a title change after the comment was posted is a change, and a trusted activation after the edit plans again. There a save that changed nothing still counts as an edit, since only a record's hash can tell; a plan comment without a record gets one at the next work stage. With no plan comment, a stage uses the text as it is, and a stage that knows no record never erases one. Comments are never edits. Pendulum's own login must be known for any of this; when it cannot be read, the stage stops. On a session's route, `pendulum issue` writes `plan.md` beside `issue.md` only when the plan was made from the current text (or the edit check read the edit as wording only), `deliver` delivers nothing when the issue changed after `pendulum issue` gave it to the session and records the text it gave with the plan, and `post-review` posts nothing on an Objective edited since its plan. Split Objectives. A part's exit record lists the checklist items left; its PR says `Refs #N` instead of `Closes #N`, and Pendulum records the part on the issue. When it merges and the issue stays open, the dispatcher deletes `pendulum/N` and queues the Objective again; the next part starts from the default branch with the plan and the merged parts' PRs in `$PENDULUM_IN`. One PR is open at a time, and an Objective that needs more than six parts (`max_parts`) Blocks; the cap bounds how many PRs, not the spend (each part's work and review jobs, its rebases, re-reviews and resumed stages are each capped by `max_usd`), and the task card names it, so a worker whose plan needs more parts Blocks before it builds any. @@ -235,15 +235,15 @@ Pendulum merges on its own (`auto_merge`, on by default); the gate is CI green o The reviewer is one model call per PR on the top model, and one more for each chunk of commits written after it (below), on a head whose validation is green or still running. A head without the validated marker (handed off by the worker, pushed or marked ready by a person) gets Pendulum's validation in the review stage. With required checks and a reviewer to run, the reviewer starts at the first reading that shows a check run on the head (CI has started) and no required check red, once the PR's mergeable state reads no conflict, and the wait goes on beside it: a head that conflicts, whose checks never start, or whose reading already shows a required check red gets no reviewer pass yet, but its fix passes first, as does every head when the reviewer does not run or validation is the commands alone, and a red that stays red Blocks before any review. A head handed off from the local route is not given its commands again on that first pass. A red the checks show while the reviewer runs, or after it (after triage's rerun and the base-failure check, as any red), gets no fix pass of its own: once the reviewer is done, the answer pass takes it with the reviewer's comments, its failures in the prompt and their whole logs in `$PENDULUM_IN/checks/`, and runs even when the review has no comment. A conflict, a check that never starts or a base failure ends the stage as before, ending a reviewer call still running, and its review is not posted, so the next review stage reviews the head it works on. The validated marker goes on the head the checks were green on; when the PR's head moved meanwhile (a person's push), the stage posts nothing and puts the review label back on for the new head. The reviewer's rerun and the foundation pass finish the review that started. The progress comment shows the overlap: the reviewer's line ends `beside the required checks on <sha>`, the pass's own lines meanwhile start `during the reviewer:`, and the checks' end is `required checks on <sha> green|red|settled while the reviewer runs`, or, when they outlast the reviewer, `waiting for required checks on <sha> after the reviewer`; the scorecard counts each minute once, the overlap as review beside CI (bench/README.md). It gets the Objective text, the diff and the PR body, and it posts review comments tied to lines, each naming the acceptance entry or repository rule it concerns, with assumptions that change behaviour flagged explicitly. It also judges every acceptance entry, met or not, with the line that shows it: Pendulum lists the issue's entries in the prompt, puts the judgments in the review body, names any entry left unjudged, and turns an entry judged not met into a comment the worker must answer. On a split part that leaves work for the next, the prompt says it is part N and not the last: an entry the PR body assigns to a later part is judged deferred and gets no comment, while one the body claims and the diff does not deliver is still a finding. The last part and a one-PR Objective are judged against every entry. Reason: otherwise every earlier part re-raises the entries later parts deliver, and the worker rebuts each one. An entry a maintainer's recorded decision assigns outside the PR (to the owner after the merge, to another issue) is judged not met with that decision's key, and gets no comment: Pendulum keeps the judgment only when the key is exactly one of the stage's trusted decisions (authors with write access), lists the entry in the review body as assigned by that decision, with its author and link, and never counts it met; any other key is a plain not met. Before each reviewer call Pendulum writes `$PENDULUM_IN/decisions.md` with every trusted decision, uncut and under its key, so the decisions the prompt cuts for length are there to read. An entry whose finding from an earlier review is still open on the PR gets no second comment, unless the last stage's finding check got no verdict on that finding's answer: the stage judges it again after the review goes up (below) and may resolve it, so the entry gets its comment in the review (two open threads for one entry when the check then leaves that finding open). A review with no line comment beside such an entry, or one a decision assigns, has a placeholder that says there are no new line findings and points to the body. Reason: a decision the reviewer cannot read or cannot cite turns the entry into a finding every round, which no change on the branch can answer. A call that fails (a crash, a non-zero exit, a cap) or an answer that holds no JSON or judges none of the entries is a missed pass: it reruns once in a fresh session on every harness, on the fallback reviewer where the harness has one. A provider's refusal is not rerun, a subscription's usage limit included (below): the fallback model draws on the same subscription. When neither call produced a review, nothing is posted and the Objective Blocks with how each call ended: no placeholder stands in for a review that did not happen, and Pendulum never merges past the review. A rerun that answered but judged none of the entries is posted, and its placeholder says it is not a clean pass. Entries left unjudged are recorded on the review, not enforced: they do not hold the merge. It has no verdict and no refuse path: a reviewer that can stop a run turns every false positive into a hold. An Objective labelled `pendulum:foundation` (trusted as the harness and model labels are, and outside the plan's record, since it changes only the review) gets a second call after that one, the foundation pass: it checks each shared contract the diff adds or changes against its callers in the repository, and shared test fixtures against isolation, and returns line-tied comments only, which go up in the same review. It runs within the job's `max_usd` like any call, reruns once when it misses, and when it cannot run or never answers nothing is posted and the stage Blocks, as for the first pass. The review that includes it carries a second marker (`<!-- pendulum:<issue>:foundation -->`): a PR reviewed before the label was added gets the foundation pass alone at its next review stage, and a rebased PR keeps its review only when that marker is there. Reason: a defect in a contract later work builds on (a mapping that folds new error codes into an old one, a fixture that writes the developer's real state) passes a review of the diff alone, and every later Objective inherits it. The worker gets the comments once and addresses or rebuts each; Pendulum pushes, posts the replies, and validation runs again; rebutted findings stay visible on the merged PR. Each finding the answer pass replied to (Pendulum's reviewer's, a named reviewer's, code scanning's) then goes to the finding check (`lib/finding-check.mjs`), before another answer round is spent on it. A reply that says the finding is fixed and names a test that fails without the fix (replies.json's `fixed` and `test`: one of the validation commands exactly as listed, a single simple command, and the arguments that run only that test, at least one of them no option; the answer pass is offered `test` only when there are validation commands) has that test run through the stage's own validation path (`runValidation`: its sandbox and env), each argument shell-quoted, in the checkout itself: first on the PR's head, then, when the commit the finding was raised on (else the head the stage's review covers) is known green (Pendulum's validated marker on it, and no red the stage held there: a command that runs more than the test fails on a red commit for any red it had), on that commit's tree with the head's copy of each argument that names a file put back, after which the checkout is reset to the head and its HEAD and tracked files checked. Each run gets the stage's time left less a reserve for the exit, and none starts with under a minute of it. Failing without the fix and passing with it resolves the finding; failing on the head leaves it open (`test failed`) with no decision call. A test that passes both ways is no evidence, and one that cannot be run so is not checkable (a command that is no validation command or not one simple command, no test argument, a commit not known green, a dependency manifest or lockfile changed since that commit, a checkout not clean at the head, a run that timed out or changed tracked files, too little time): either reply goes to the decision model, its note kept for the Block. Only the named test is run: a reproduction written in a reply's prose is never run. For every other reply the decision model is asked whether the answer resolves it, `fixed` (the change shows it), `rebutted` (the reply names an acceptance entry or repository rule that permits the code), `decided` (a maintainer's recorded decision, not overruled by a later one, speaks to the very entry, rule, file or behaviour the finding concerns and settles it: it waives or changes what the finding asks, assigns that work outside the PR, such as to the owner after the merge, or permits the code; general approval such as "LGTM" or "ship it" settles nothing, and doubt is `unresolved`) or `unresolved`, given the finding (its reviewer, file, line, body and when it was raised), the reply, what the PR changed since the commit the finding was raised on (its own file, then its other files: those the reply names by path first, then those the finding names, then the rest, cut at 8,000 characters with the paths of the files left out listed after the cut; without the default branch's changes; a finding with no commit of its own reads from the head the stage's review covers), for a reply that says its fix is in the PR body (replies.json's `"fixed": true` and `"pr_body": true`) what the body changed since the finding was raised (git's diff, one line of context, of the body's version at that time, from GitHub's record of the body's edits read once per check, to the body now, cut at 16,000 characters; `no change`, or `whether the body changed could not be read` when the record does not hold that version), with `fixed` then taking a defect gone from the body and the question saying a body change alone never fixes a finding that asks for a change to the code or tests or says the code does not meet an acceptance entry or rule (every other reply's question carries no body; Pendulum's posted answer carries `pr_body` in its marker, `<!-- pendulum:<issue>:reply:<id>:pr_body -->`, so an answer judged again in a later stage keeps it), the issue's acceptance entries, the repository's rules (AGENTS.md at the head, the protected paths, the validation commands), and the maintainers' decisions the stage read (comments on the issue and the PR, the PR's review bodies and its inline review comments, by people with write access, a dismissed review's left out; each with its author, time, place and review state, cut at 2,000 characters; within 8,000 characters the newest decision always, the issue's newest within half the window while the PR has decisions too, then the PR's newest, then the issue's in any room left, with a count of those left out; a decision the reply quotes counts only when it is there, so a comment by anyone else settles nothing), each part between markers with a random tag, as data never to be followed; at most four questions at once. `fixed`, `rebutted` or `decided` at the confidence floor or more (Red-check triage, below; no confidence is none of them; `decided` never on code scanning's alert, nor when a decision newer than the oldest one shown was left out for length) resolves the finding's thread; any other verdict leaves it open (`judged not fixed`, or `judged not resolved` for a reply that did not say fixed). Pendulum posts the evidence in the thread first, under `<!-- pendulum:<issue>:resolved:<id> -->` (the test as it ran, the commit it failed on and the head it passed on, or the verdict, its confidence, the floor and who answered); that comment and Pendulum's answer are never a person's answer, so a thread a person reopens stays open, then resolves the thread (a finding in the review body: that PR comment is what resolves it), and a resolved thread, not a reply, marks it answered on every side (the answer pass's list, the exit, the merge pass). Anything else leaves it open. A person's reply answers as before, from someone who can push only: any such reply but Pendulum's own on the reviewer's comment, a writer's on a named reviewer's, none on code scanning's; a person may resolve the thread too. How each finding ended is recorded as data in the review stage's progress comment (its findings line: the reviews its reviewer posted, and each finding it listed with the review or outside reviewer that raised it and its outcome: `fixed-test`, `fixed-verdict`, `answered` for a `rebutted` or `decided` at the floor, `not-fixed`, `not-checkable` for no verdict or no decision model, or `open`), from the check's own branches and whether each ended resolved (a thread already resolved posts no evidence), never from the reply's words; a later stage's listed `open` never replaces a judgement, and a report reads only records written before its period ends; `pendulum report` counts the findings and outcomes per Objective, reviewer model and review stage beside those stages' dollars ([REPORT.md](REPORT.md)). Reason: findings per dollar and a reviewer's quality are then exact counts, not readings of prose. Findings still open after the answer pass (unanswered, or read as not resolved), when the rest of the exit is delivered, take another answer round: the review label goes back on, and the next stage's answer pass gets them again, each with Pendulum's earlier answer (`earlier`). A Question the answer pass raised stands with findings open: it carries them. The rounds per re-entry (the Objective label applied again, a restart or a Block) are at most two, shared with code scanning's rounds at the merge (below) and counted in Pendulum's record on the issue (`<!-- pendulum:<issue>:answer-rounds -->`); past them the stage Blocks (cause `work`) naming each open finding, with what the check found on it (`test failed`, `judged not fixed` or `judged not resolved`, after `not evidence` or `not checkable` for a named test that proved nothing), and how to clear it: a fix on the branch, a reply by someone who can push or a resolved thread, or for a finding in the review body that resolved marker by someone who can push. An answer the gateway gave no verdict on (a failed call, a refused key, an answer outside the choices; once the key is refused no further question is asked in the stage) costs no answer round: it goes to no worker pass, the review label goes back on, and the next stage judges it again first (when that stage was started only for this, an answer it then reads as not resolved waits for the answer round its exit takes); the second stage in a row without a verdict Blocks naming the decider's error code (cause `setup` for a refused key, `provider-quota` for a rate limit or spent credits, else `outage`). With no decider (`decision_route` off, or `gateway` with no key) the decision model's part is off: a reply answers its finding as before unless a test it names proves the fix or fails on the head, the progress comment says `finding check: off (<code>)` once per stage, and doctor's `finding check` line warns. The reviewer reads each chunk of work once. The answer pass's and the fix passes' commits are the review's answer and get no review of their own when they do only what the review's findings and the failing checks asked. The answer gate decides it: Pendulum asks the decision model red-check triage uses (the same key, `triage_model`, below) one question, `only_asked` or `more_than_asked`, giving it the diff they wrote since the head the review read, with the default branch's changes left out (the replay below), then each finding the answer pass answered (path, line, body) and the failure lines and output's end of each red the fix passes and the answer pass were given, at most 32 KiB in one question (`ANSWER_INPUT_BYTES`). A diff too large for one question is asked about in parts, each with the findings and failures and each within that size: whole files packed in order, and a file too large alone split into its hunks, packed in order the same way, each part with the file's header; four parts at a time, none started once one is held. Only every part covered covers them, and the first part held is named (`part <n> of <m> … (<files or hunks>)`); a single hunk too large for a question is not judged, named in the hold, and no part is asked, even with no decider. Before each question, the first included, the stage's `max_usd` (in known dollars: a price still settling counts nothing) and its wall clock are read: once either is reached, that part and every later one are not judged, each named in the hold, and never covered. The question says a failing check asks only that it pass with the smallest change, so new behaviour or a feature is more than asked even when a check's output mentions it. The diff, the findings and the failures go as data (fenced, or JSON strings), with no worker secret in them. Pendulum records the head they leave in its own comment on the PR (`<!-- pendulum:<issue>:covered:<sha> -->`, edited in place), and the later of that record and its last review's `commit_id` is the head the review covers. Only `only_asked` at the confidence floor (Red-check triage, below) covers them. Anything else holds the PR: a lower or missing confidence, `more_than_asked`, a call that fails, times out or answers outside the two choices, no key, a hunk too large for a question, a diff over 16 MiB (not read whole), a file git diffs as binary (its numstat `-`, or `Binary files … differ`: a text file with one NUL byte is one, and the model would see none of it; no question is asked), or a diff that cannot be told apart. Then the record stays on the head the review read, marked as an answer's (`:answer` after the sha), the review label goes back on, and the next review stage's pass reads those commits. That pass's own answer is gated too: held again, the stage Blocks (cause `work`) naming why, the record staying on the head that pass read, and a person reviews those commits, so the gate never loops. The gate's answer goes to the job log (`answer gate (<model>): <verdict> <confidence> → …`, with `(in <m> parts)` after the confidence for a diff asked about in parts). The review goes up on the head the reviewer read (its `commit_id`), which is the head Pendulum's checkout was on when the reviewer started; when GitHub's head is no longer Pendulum's by then (someone else pushed), nothing is posted and the review label goes back on for the new head. A pass on new commits that finds nothing leaves the earlier reviews' open findings to the answer pass. A review stage whose head is that head, or only a rebase of it (the covered head's own change, replayed with `git merge-tree` onto the head's merge base with the default branch, gives exactly the head's tree: a clean rebase, GitHub's update-branch merge, Pendulum's merge of a default branch), runs no reviewer and goes on to validation and the merge. Commits written after it (the work stage's answer to a Question, a maintainer's push, a resolved conflict) get a reviewer pass before the merge, on the diff from that replay to the head, so neither the reviewed code nor the default branch's changes are in it; when the replay conflicts, the pass gets the whole PR. The prompt and the posted review name the head it follows on; the pass judges every acceptance entry as a first pass does, and a foundation Objective's foundation pass runs on the same diff. An answer pass that applied maintainers' decisions (a Question's answer, a comment no pass had read) in new commits does not merge: the stage covers the head before it (the head the review read, marked as an answer's, when the answer gate holds what the stage wrote before it), puts the review label back on, and the next review stage reviews those commits. Reason: the one-pass rule keeps the same code from being reviewed twice, and code written after the review was never reviewed. -A repository may also name third-party reviewers, reviewer Apps outside Pendulum, by login (`third_party_reviewers`, such as `greptile-apps[bot]`; `lib/third-party-review.mjs`). Their review is part of the PR's review. After Pendulum's reviewer posts, the review stage reads the PR's reviews once for each named reviewer's submitted review whose `commit_id` is the head Pendulum's reviewer read. While one is missing, the stage does not wait in place: it records the wait on the PR (a comment, marker `<!-- pendulum:<issue>:third-party {"sha", "logins", "at", "minutes"} -->`, counted only when Pendulum or someone who can push wrote it, since a local loop writes as its developer; the bound the dispatcher, `serve` and `run` wake the review at is its `minutes`, the `third_party_wait_minutes` setting of the stage that wrote it (20 by default, taken as at most 24 hours whatever the record says), from GitHub's creation time of that comment; the review stage that resumes judges the wait by its own setting), takes the `pendulum:review` label off, moves the Objective to In review when it is not there (a Question a person answered by marking the PR ready still carries `pendulum:question`) and ends with exit `waiting`, holding no local slot, runner or sandbox. The dispatcher's tick, on every route (the Action's, the sandbox's, `serve`'s), reads that record from the PR comments it already reads for send-backs. While the bound is ahead and the review is missing, it leaves the PR as it is: no merge pass, no branch update, no send-back; when it cannot read the PR's comments and third-party reviewers are named, it leaves the PR alone that tick too. Once that review of the head exists, or the bound has passed, or the PR's head is no longer the one the record names (a maintainer's commit, GitHub's update-branch), it puts `pendulum:review` back on, which starts the review stage on that route as any review label does. The reviews are read at most once a tick, and in `serve` at most once a minute per PR. An App's review submitted on a Pendulum PR that is not Pendulum's own ticks the dispatcher (`pull_request_review`, its reviewer of type `Bot`; a person's review ticks nothing), and on a public repository the bound's end is a `third-party` wake; on a private one it waits for the next event or the cron. The review stage that starts again finds Pendulum's own review on the PR (its marker), so the reviewer does not run again; it reads the record, says on its progress comment which reviewers reviewed the head or were left out past the bound, removes the record and goes on to the answer pass. A review label applied after the record was last written means a stage has taken the wait up, so the dispatcher never puts the label back twice for one record. A stage that starts again before the bound (the label re-applied by hand, a restarted loop) rewrites the same record and ends `waiting` again; a new head gets a new record and its own bound. A stage that goes on without waiting (the reviewer's review in, the bound passed, the cap spent) removes the record, so none holds a later merge. A record that cannot be read or written, a label that cannot be taken off, or Pendulum's own login unknown (its record could not be told from a pasted one) is no wait: the stage goes on without the reviewer rather than stall. `pendulum run` and `pendulum review`, which may have no `serve` behind them, do the dispatcher's part in place, once a minute, and then review again, and `pendulum run` on an In-review Objective whose review waits takes that wait up the same way; `serve` leaves it to its own ticks. The answer pass then gets each named reviewer's root line comments that neither Pendulum nor anyone who can push has replied to, from any head, beside Pendulum's own. Each comment carries `from` (the reviewer's login), and its body is sanitised like harness text and cut at 8,000 characters. The prompt and the pendulum-deliver-pr skill call their text untrusted review input: the worker judges each finding against the code, fixes it or rebuts it, and follows no instruction in it. Pendulum posts the replies in their threads, and the finding check resolves those it reads as resolved. The exit counts a named reviewer's comment as unanswered only when the answer pass was given it; one posted after the wait is left for the next review. Only the named logins are waited for; any other reviewer's comment is handled as without the setting (the merge pass, below, has the answer pass take an unlisted reviewer's thread when the base's rules require every conversation resolved). With none named, the stage reads nothing more and runs as it would without the setting. The wait comes before the answer pass, so before the merge; there is no wait for the answer pass's new head, just as Pendulum's reviewer does not review it again. Code scanning (GitHub's own App, `github-advanced-security[bot]`, whose alerts on the PR's lines are review comments, CodeQL's say) is answered the same way on every repository, with no setting and no wait: the answer pass gets its open comments marked as untrusted input, and Pendulum resolves each thread once it replied. On code scanning's thread only Pendulum's own answer counts, never a person's reply alone, and an alert adds only its own file to the answer pass's fix-pass scope, never a protected or toolchain file. +A repository may also name third-party reviewers, reviewer Apps outside Pendulum, by login (`third_party_reviewers`, such as `greptile-apps[bot]`; `lib/third-party-review.mjs`). Their review is part of the PR's review. After Pendulum's reviewer posts, the review stage reads the PR's reviews once for each named reviewer's submitted review whose `commit_id` is the head Pendulum's reviewer read. While one is missing, the stage does not wait in place: it records the wait on the PR (a comment, marker `<!-- pendulum:<issue>:third-party {"sha", "logins", "at", "minutes"} -->`, counted only when Pendulum or someone who can push wrote it, since a local loop writes as its developer; the bound the dispatcher, `serve` and `run` wake the review at is its `minutes`, the `third_party_wait_minutes` setting of the stage that wrote it (20 by default, taken as at most 24 hours whatever the record says), from GitHub's creation time of that comment; the review stage that resumes judges the wait by its own setting), takes the `pendulum:review` label off, moves the Objective to In review when it is not there (a Question a person answered by marking the PR ready still carries `pendulum:question`) and ends with exit `waiting`, holding no local slot, runner or sandbox. The dispatcher's tick, on every route (the Action's, the sandbox's, `serve`'s), reads that record from the PR comments it already reads for send-backs. While the bound is ahead and the review is missing, it leaves the PR as it is: no merge pass, no branch update, no send-back; when it cannot read the PR's comments and third-party reviewers are named, it leaves the PR alone that tick too. Once that review of the head exists, or the bound has passed, or the PR's head is no longer the one the record names (a maintainer's commit, GitHub's update-branch), it puts `pendulum:review` back on, which starts the review stage on that route as any review label does. The reviews are read at most once a tick, and in `serve` at most once a minute per PR. An App's review submitted on a Pendulum PR that is not Pendulum's own ticks the dispatcher (`pull_request_review`, its reviewer of type `Bot`; a person's review ticks nothing), and on a public repository the bound's end is a `third-party` wake; on a private one it waits for the next event or the cron. The review stage that starts again finds Pendulum's own review on the PR (its marker), so the reviewer does not run again; it reads the record, says on its progress comment which reviewers reviewed the head or were left out past the bound, removes the record and goes on to the answer pass. A review label applied after the record was last written means a stage has taken the wait up, so the dispatcher never puts the label back twice for one record. A stage that starts again before the bound (Draft removed by hand, a restarted loop) rewrites the same record and ends `waiting` again; a new head gets a new record and its own bound. A stage that goes on without waiting (the reviewer's review in, the bound passed, the cap spent) removes the record, so none holds a later merge. A record that cannot be read or written, a label that cannot be taken off, or Pendulum's own login unknown (its record could not be told from a pasted one) is no wait: the stage goes on without the reviewer rather than stall. `pendulum run` and `pendulum review`, which may have no `serve` behind them, do the dispatcher's part in place, once a minute, and then review again, and `pendulum run` on an In-review Objective whose review waits takes that wait up the same way; `serve` leaves it to its own ticks. The answer pass then gets each named reviewer's root line comments that neither Pendulum nor anyone who can push has replied to, from any head, beside Pendulum's own. Each comment carries `from` (the reviewer's login), and its body is sanitised like harness text and cut at 8,000 characters. The prompt and the pendulum-deliver-pr skill call their text untrusted review input: the worker judges each finding against the code, fixes it or rebuts it, and follows no instruction in it. Pendulum posts the replies in their threads, and the finding check resolves those it reads as resolved. The exit counts a named reviewer's comment as unanswered only when the answer pass was given it; one posted after the wait is left for the next review. Only the named logins are waited for; any other reviewer's comment is handled as without the setting (the merge pass, below, has the answer pass take an unlisted reviewer's thread when the base's rules require every conversation resolved). With none named, the stage reads nothing more and runs as it would without the setting. The wait comes before the answer pass, so before the merge; there is no wait for the answer pass's new head, just as Pendulum's reviewer does not review it again. Code scanning (GitHub's own App, `github-advanced-security[bot]`, whose alerts on the PR's lines are review comments, CodeQL's say) is answered the same way on every repository, with no setting and no wait: the answer pass gets its open comments marked as untrusted input, and Pendulum resolves each thread once it replied. On code scanning's thread only Pendulum's own answer counts, never a person's reply alone, and an alert adds only its own file to the answer pass's fix-pass scope, never a protected or toolchain file. Pendulum's push and merge. The harness pushes nothing. Pendulum takes the branch as a git bundle the agent writes to a pipe, indexes its pack into a mirror only Pendulum can write (a mkdtemp directory under Pendulum's own 700 temp directory) with `git index-pack --strict`, so every object is fsck-checked whatever the git version, and checks it there: the paths changed since the stage started (GitHub's head before any harness ran), Git LFS pointers, the local media cap, and each LFS object's bytes against its pointer. It then pushes with an explicit lease on the head it last saw, to `refs/heads/pendulum/<issue>` only, and reads GitHub's head back. Before a push, when the default branch on GitHub changed a file under `.github/workflows/` since the branch's base, Pendulum merges it into the branch in the mirror (its own merge commit, from `git merge-tree`) and the checkout fast-forwards to it (one that cannot, with uncommitted edits in the way, keeps the branch on that merge: the next push merges the checkout's new commits onto it, so the branch only moves forward): GitHub refuses a token without the Workflows permission, the App's or the local one, a branch whose workflow file is a version no branch has any more, which is what a run cut before such a change carries. A new branch that conflicts with that merge is not pushed; the harness resolves the conflict once, as a send-back's conflict pass does, and Pendulum pushes again. That pass answers like the work pass: a cap it reaches Blocks with that cap, and a death, or a rebase or merge it leaves in progress in the checkout, Blocks with nothing pushed. A push GitHub refuses for a workflow file Blocks with that cause, in Pendulum's words; any other refused push Blocks with git's status word and the exit code, and GitHub's own text goes to the job log only. A fetch, Git LFS upload or push of the mirror's that got no answer from the remote (a dropped connection, DNS, TLS, an HTTP 5xx, 408 or 429: anything but the remote's answer, which is the push's porcelain line for the ref, other than git's `[remote failure]`, or an HTTP 4xx refusal; `lib/outbox.mjs` gitTransport) is tried again up to four times within a minute and the stage's real end (its deadline plus the 15 minutes kept for the exit, so a timed-out stage's last push retries too); a push whose answer was lost but whose head GitHub now has counts as pushed, and is not sent again. A refusal (a ref line in git's porcelain, an HTTP 4xx) is never retried; one git reports with no status (a missing ref, a failed authentication) stands once those tries are spent. GitHub's head is read back up to five times over about 30 seconds, and at least three times. A refused or rejected push, or a head that is not the one checked, Blocks. Nothing is armed for later: the review job records the head it reviewed and validated as mergeable, and merges exactly that head (the merge endpoint's `sha`, or enqueue with `expectedHeadOid` on a merge queue) once its required checks are green, the review is done and no maintainer decision is unread, or the unread ones ask for nothing (the comment check: the decision model, given the issue, the PR and every unread writer comment whole with what it is, reads them as asking nothing at the 0.7 floor, and a fresh read after the call finds nothing new; a writer's review requesting changes always holds the merge; they are then recorded as read on a progress comment of the merge pass's own); otherwise the dispatcher's merge pass does it on a later tick. Just before the merge, on every route, the merge pass reads the PR's review threads: it resolves the ones Pendulum handles (its reviewer's, the named reviewers' and code scanning's, and under a rule below the unlisted reviewers') that a person answered; a code scanning comment still open (posted after the answer pass, or answered and not resolved by the finding check) puts `pendulum:review` back on, so the answer pass takes it, within the answer rounds (above: at most two per re-entry, counted in `<!-- pendulum:<issue>:answer-rounds -->`), and past them Blocks (cause `work`) naming each open alert's file and line. When branch protection or an active ruleset on the base requires every conversation resolved, a named reviewer's open thread no person answered (posted after the answer pass, or answered and not resolved by the finding check) goes back the same way, and so does an unlisted reviewer's: one nobody named whose root comment is by someone who can push or by a GitHub App (a `[bot]` login, which can comment only through an installation on the repository). So under that rule every App installed with pull-request write on the repository or its organization, reviewing or not, can put text before the answer pass's model, always as untrusted data. The review stage reads the same rule on the PR's base (`lib/third-party-review.mjs` `unlistedRule`, read only when such a comment is on the PR) and takes the same threads, classified once by `github.mjs` `reviewThreads` for both passes (REST and GraphQL name some Apps differently: Copilot's reviewer is `Copilot` in one and `copilot-pull-request-reviewer[bot]` in the other). An App's comment goes to the answer pass beside the named reviewers', with `from` its author, sanitised and marked as untrusted review input, and a person's reply answers it as it does a named reviewer's. A writer's comment among the stage's kept decisions (its author's write access checked) is a maintainer's decision: the answer pass gets it with `writer` its author, its text once (under the decisions when they show it); one that is not (an author association of MEMBER or COLLABORATOR can be read-only) is untrusted input with `from`, as an App's is. Every such body is one JSON string in the prompt's list. Only the finding check's yes or a person resolving the thread settles a thread its opener's association counts as a writer's, never a reply. The finding check, the answer rounds and the thread's resolution are otherwise a named reviewer's. When a thread no answer pass takes is open too, the merge pass Blocks at once rather than spend a round. Under that rule any other unresolved thread (a stranger's; `github-actions[bot]`'s, which every workflow run in the repository posts as, one a stranger's comment or pull request starts included, so it stands for no installation and counts as a stranger; or an answered one Pendulum could not resolve) never reaches a model and Blocks (cause `work`) with a reason naming each thread's author, file and line. Without such a rule, no unlisted reviewer's thread is read for the answer pass or holds the merge. A merge GitHub refuses just after the pass resolved threads is tried once more after a moment. That is read from the threads and the rules, before the merge and again after a refusal, never from GitHub's words. Threads or rules that cannot be read leave the merge to GitHub's own rule. A merge or enqueue GitHub refuses because another pass already merged the PR, or queued it at the reviewed head, counts as done; that is read from the PR again, never from GitHub's words. The dispatcher's tick comes from events, never only from GitHub's cron: CI finishing on a Pendulum PR's head (the launch gate's merge tick on the sandbox route; the dispatcher's own `workflow_run` and `check_suite` triggers without one), a Pendulum PR merging, the queue dropping one (`pull_request` `dequeued`), and the queue watch. A PR the queue drops unmerged (its checks failed or timed out on the queue's commit) is enqueued once more, and the issue gets one line saying so with the queue's code and time; dropped again, the Objective Blocks with the queue's reason codes, read from the PR's timeline; when the queue's jobs ran and failed, the Block names the failed jobs of its newest failed run and each one's first failure line, with the cause and advice of what the review stage read the red drops as (below): GitHub's side is an `outage`, the default branch's own failure says to fix it there, a flake read each time says to steady that test, and anything else is the work's. A drop whose newest removal is a red run on the queue's commit (`failed_checks`) goes to the review stage first, once per drop: the merge pass records it on the issue (marker `<!-- pendulum:<issue>:queue-red:<time> -->`, its JSON record `{at, state, head, after, kind, sigs, tries, reads}`, `head` the PR head the drop was of) and puts `pendulum:review` back on; a record still `handed` is handed again on a later pass. Records count from Pendulum or anyone who can push, since a merge pass and a review stage of one Objective can run under different logins (`serve --all` beside the Action's dispatcher). The review stage takes the newest record when it is `handed`; one of another head than the PR's now is `superseded` and left. It reads the PR's `merge_group` runs of any status (the queue drops a PR at its first failed required job while the run's other jobs go on) created after the removal before the drop, or the drop count's bound, and at most six hours back (one page, newest first): the newest created by the drop is this drop's, never an earlier drop's. With no such run listed yet, or no failed check on it while it still runs, nothing is decided: the record stays `handed` and the next review stage reads it again; after two such stages (a failing check no Actions run carries) it is not known to be the PR's (`none`). On that run's commit it reads the failed check runs, and decides as for a red PR check: a required job GitHub never started (`not-started`), every failed job failing on GitHub's side (`infra`), triage's flaky verdict (`flaky`, asked as for a PR check, nothing rerun) and every failing job failing the same way on the default branch (`base`) are not the PR's change; a run or job logs it cannot read (`none`), and, with triage off, a failure that names no file or test the PR changes (`unclassified`), are not known to be. The record says so (`requeued`) and the merge enqueues it again or Blocks under the rule above. Anything else is the PR's own change, a deterministic failure in a job the PR's checks do not run (another OS, say) included: triage reads each job's log, not its name, and a failure that names a file or test the PR changes is never a flake. Its answer pass gets the failing jobs' lines and whole logs, marked as the queue's integrated commit, then validation runs on its new head and the merge enqueues it, whose drops count from that head. The record turns `fixed` only once that pass itself committed (the checkout's HEAD before and after it, not a merge Pendulum makes at the push) and the push went up; until then it stays `handed` with `tries` counted, so a stage that ends first (a crash, a stop, a pause, a cap, a wait for a third-party reviewer) leaves it to the next. The bound is progress, since the Objective's last re-entry (its label, `pendulum:restart` or a Block): each record keeps its failing jobs and their failure signatures, and a red after a fix pass is judged against the red that pass was handed, with every red fixed since the re-entry as the ones seen, as in the stage's own fix loop (`lib/fix-progress.mjs`, Exit: blocked, below); each record keeps its failing jobs (each one's signature and the digest of its folded failure lines with their counts) and their failure lines for the decision call, which is also given the fix pass's own commits; each stage try's end is recorded on the drop (`committed`, or `idle` when its pass ran, its harness started and returned, ok or not, and committed nothing; a try whose pass never ran, was stopped, or asked a Question records none and does not count, as the stage's own bounds cover those); no progress, or a try that ran and committed nothing, Blocks the stage (`blocked`), as the work's (an unmade judgement as Pendulum's or the outage's), naming the failure. There is no count of the queue's fix passes: while the decision model keeps reading each as closer to green, `daily_usd`, the owner's limit, is what stops them. Only drops after the latest of the review the merge rests on, the head's commit (GitHub keeps no push time for a branch push) and the issue's last re-entry or Block count, so a re-entry starts the count over even when its head keeps the earlier review. When GitHub never started the required job on a dropped entry's merge_group commit (no step, no runner: a billing lock, a spending limit), the Block says so as infrastructure, quoting GitHub's annotation, as validation does, rather than pointing at the checks. A queue commit on which CI never begins in 10 minutes (`queue_stall_minutes`) counts as a drop too, and so does one on which CI began but a required check makes no progress. Progress is read from the check's Actions job: its steps, each one starting and completing (a running job's log is not readable, so it is not used). The job is stalled when the step running now has run past max(3 × that step's normal duration, that duration + 15 minutes) (`step_stall_factor`, `step_stall_floor_minutes`), so never under 15 minutes (16 for a step that normally takes 1); the normal duration is the longest the same step of the same job took in the workflow's last 15 green runs on the default branch or in the merge queue, read with the job token once per dispatcher tick or queue watch, and only once a step has run 15 minutes. A step with no history, a running step GitHub gives no start time (counted from the check run's start), a check that is no Actions job, or a job Pendulum cannot read falls back to a time bound from the job's own start: the queue's check timeout (`check_response_timeout_minutes`, from the ruleset; setup's 60 when unread) less 10 minutes, at least half of it and at least 20 minutes, so 50 minutes at 60. A job queued or waiting for a runner, or with no steps yet, is never stalled. A required check not reported at all (an aggregate behind `needs:`) is judged by its upstream jobs' progress, and by the fallback from CI's first start when nothing runs there. The notice names the stuck step and its times, e.g. `` `Quality` / `Run scripts/ci/setup.sh` running 16 min, normally ~1 min ``. On the local route the Pendulum App has no Actions permission, so Pendulum reads no job steps or history there and the hung rule is the time fallback only, read once per merge pass. Pendulum takes the PR out and puts it back once, which restarts CI, and the second time Blocks naming the check. A removal for a hung step counts toward that only when the step really hung: its record holds each step judged hung (the required check's name, the job's id, the step's name and number, its times) and the queue's own deadline for that commit (the commit's time plus `check_response_timeout_minutes`, read once per merge pass with the hung bound; no deadline when it is unread, and such a removal always counts). When the drops would Block, Pendulum reads those jobs (with the job token; never on the local route), oldest removal first: a removal is cleared, and counts toward no try, when the judged step finished green and its job, the required check the queue waited on, concluded `success` by that deadline, so the queue would have taken that check's result. A job that failed later (a later step red), finished after the deadline, or was cancelled counts. One removal at most is cleared since the count's start; past that, every hung removal counts, so a step that is slow on every try still Blocks. While a judged job is still running before its deadline, or cannot be read then, the PR stays out of the queue and the decision waits, never past that deadline: Pendulum records that removal on the issue, and the run's end, a retry wake for a failed read, or the next tick brings the next pass. A person's removal and every other drop count as above. A removal Pendulum made reads its reason back from Pendulum's own requeue comment on the issue, which records it, since GitHub's timeline cannot say why Pendulum removed a PR. CI has begun once a check run or status named like a required check exists on it, or a check run or suite from the integration that provides the required checks (Actions when the ruleset names none), so an aggregate required job behind `needs:` that starts late is not a stall; another app's run, such as code scanning's, does not count. Any run from that integration counts, required or not (a `push` workflow that fires on the queue's branch, another `merge_group` workflow, a startup failure); one that never produces the required check is bounded by that rule and the drop handling. When the required checks cannot be read, any check run, any status, or any suite with a run counts. The queue-watch job, started by the dispatcher whenever its merge pass leaves a PR in the queue, reads the entry every 30 seconds until the PR leaves the queue, merged or dropped, or stalls there, and then ticks the dispatcher with its own `workflow_dispatch`; after 12 minutes it ticks anyway, and that run starts a new watch. Recovery from a drop never depends on the `dequeued` run: GitHub attributes that event to `github-merge-queue[bot]` and, under a strict approval policy for outside contributors, holds it for approval, while a `workflow_dispatch` by the job token is never held. The `dequeued` run stays a faster path where it runs; the merge pass reads the queue and the PR's timeline each time, so the two never enqueue a PR twice. Local mode's loop runs the merge pass every interval itself. A person's own removal from the queue is a hold, not a drop: Pendulum leaves the PR out until they enqueue it again, or it is reviewed again, gets a new head or re-enters. Doctor names an installed workflow rendered before these ticks (re-run `setup --apply workflow`), and, with a merge queue, warns when the repository's approval policy can hold the `dequeued` run (or cannot be read, which needs admin), saying recovery runs from the queue watch. The squash commit carries the PR's title and Pendulum's closing line, never the branch's commit messages; on a merge queue, setup sets the repository's squash default to the PR's title and body, and doctor checks it. A PR that fell behind gets GitHub's update-branch merge; that new head is accepted only when it is a merge of the recorded head and a default-branch commit, committed and signed by GitHub's web-flow key, with exactly the tree Pendulum's own `git merge-tree` of the two gives. Any other new head goes back to review. Pendulum's git runs only in its mirror, with hooks off and no global or system config; the agent's checkout gets the default branch, the branch and Pendulum's own clean rebase as bundles, and every git command there runs in the agent's sandbox. Only the commit Pendulum's rebase made, and only when it rebases the head Pendulum's review covers with nothing more, keeps the review and merges from the work stage; any other head (one the harness made: a resolved conflict, a fix; a rebase Pendulum then merged a workflow change into before pushing; a rebase of commits written after the review) goes back to the review stage, whose reviewer reads what it adds beyond a rebase of the covered head (above). GitHub failing for now is retried inside Pendulum's API client (`lib/github.mjs`), on every route: a 5xx, a 429 or secondary rate limit, or no answer at all (GitHub's primary rate limit spent is waited out to its reset in the stages and `serve`: below). Up to four tries per call, waiting what GitHub asks (`Retry-After`, a minute for a rate limit that names none) or 2, 4 and 8 seconds, each spread by up to 30% (a wait GitHub asked for only upward), at most 90 seconds in all and never past a deadline the caller passes; a longer ask is not waited out, and the caller sees the error. A caller that handles a rate limit itself (the dispatcher's blocked-by reads, the five-minute launch jobs) gets it at once. Only a call that means the same sent twice is retried: a read; a PUT, PATCH or DELETE that sets a state (not a merge or an update-branch); and adding labels to an issue or PR, which keeps the ones it has. A create (any other POST: a comment, a review, a PR, a repository label, a dispatch, a rerun; a GraphQL mutation) goes again only when it provably did not land: the connection was never made, or GitHub's rate limit turned it away (a 429, or a 403 with the rate-limit headers or message; a 5xx or 422 with those headers is no rate limit); or when a read finds it absent: the caller's, or for a comment on an issue or PR a read of the comments updated since just before the call, which finds one with the same body (line ends and trailing blanks aside) by Pendulum's login, or by anyone when the body carries a Pendulum marker (a notice is posted with the notice App's token), so a comment GitHub made before its 5xx is not posted twice; after a 502 or 504 that read waits ten seconds at least, and it keeps the call's deadline. Each retry is logged once with its cause and try number. A 5xx that is still GitHub's answer once the tries are spent (or a comment whose read for it fails) is an outage of GitHub, below: its code is the status (`HTTP 500`), and the stage ends on it, never on a crash Block. A refusal (a 4xx that is no rate limit) is not retried and stays the caller's error. -This machine's own network being down is not GitHub failing (`lib/network.mjs`). In a work or review stage, and in local mode's `serve`, a request that never left the machine (DNS, a refused or unreachable connect, a connect that timed out, or, behind a proxy, the proxy's 5xx to its CONNECT; read from Node's error code, never its message, except the proxy's status, which undici gives only in its one fixed tunnel message and which is read from that exact text) is no try: Pendulum probes that host, one request at a time after 5, 10, 20 and 30 seconds and then every minute, and sends the request again once the host gives any answer, a create included since it did nothing. Every other request to that host waits on the same probe rather than being sent, and the log has one line when the host is lost and one when it answers again; a host lost again within a minute of answering is the same outage, its first loss and its limit carried over and no new line logged unless it then stays down past a minute, when it gets one line then and one when it answers. Once a stage has stopped waiting, a request to a host it gave up on fails at once as that outage (its host, code and first loss), so the stage's end names it whichever call met it first. A Block that came from an outage ends on the outage instead, on any route, as below: a GitHub step of the exit (the split record, the review label, the mergeable record, the maintainers' comments read before a merge, the merge itself, the PR's first opening) that failed because its host did not answer, or because GitHub's core REST quota was spent (a spent GraphQL or search quota is no outage of a write). Any other Block stands, an outage or not: protected paths, a cap, validation, an exit record the harness wrote. While a host the stage gave up on still fails a probe, a harness pass cut off by its provider or the network (below) is no death and does not run again, and a run left with no exit record ends on the outage without the harness being asked, so its own account of a run the outage cut off never stands in for it; once the host answers again, such a pass runs again as above, and the harness is asked as ever. The App token's mint waits the same way. Any HTTP answer, a 5xx included, is the host answering and goes through the retries above, with no probe; a 5xx that outlasts them ends the stage on GitHub's outage at once, as one past the wait does (paused on the local route, where `serve` resumes it after a doubling wait for as long as GitHub's status page reports an incident: LOCAL.md; an `outage` Block elsewhere), and its reason names the request and says GitHub answered that status to every try since the first. A git fetch or push of the mirror that fails in transport while the remote's host does not answer a probe waits the same way, and its retry count starts again after. Pendulum's own git (the mirror's fetch and push, and its scratch repositories') reaches the network as its GitHub client does: through the proxy the stage process's own environment names when `NODE_USE_ENV_PROXY` is 1, else directly, and never through a proxy from git's own config or any other variable (`lib/network.mjs` `gitProxyEnv`). The settings are resolved as Node's fetch resolves them and given to git in the forms curl reads: `https_proxy` before `HTTPS_PROXY`, an https remote through the http proxy when no https one is set, and `NO_PROXY`'s entries (split on commas and white space, `*.` and a leading `.` dropped, a `host:port` entry kept only for the remote's port, `*` alone covering every host) rewritten as plain comma-separated hosts. An https remote goes through the proxy as a CONNECT tunnel carrying TLS, so its token reaches the proxy only encrypted. A proxy URL with a user and no password fails closed for git: git asks for the proxy's password, has no helper or prompt to answer it, and stops before connecting, while Node's fetch goes through the proxy with no proxy credentials. The repository's setup and install that fail while this machine's network is down run once more after it is back (`lib/checkout.mjs` `throughOutages`). Down is decided on exact facts only: an outage the stage recorded on any host while the step ran, GitHub's origin not answering a check on a fresh connection (no pooled socket stands in for it) that reaches the network as Pendulum's GitHub client does: through the proxy the stage process's own environment names when `NODE_USE_ENV_PROXY` is 1 (local mode's stages), else directly with its own DNS lookup, or one of the stage's own allowed hosts (the sandbox's built-in list, `PENDULUM_LOCAL_DOMAINS` or `allowed_domains`, and the Objective's approved `pendulum:host:` labels, as the route resolved them, those not GitHub's own first, lookups only) failing its lookup with `EAI_AGAIN`, as a resolver that still serves GitHub's names from its cache fails the rest. Nothing the step printed and nothing its checkout configures is ever probed or looked up, since the model edits both. The check connects only to GitHub's origin, the operator's own (`GITHUB_API_URL`, which may be a GitHub Enterprise Server on a private network); through a proxy, the proxy's failure to reach it (a tunnel it could not open, or its 502 for an http origin) is that origin unreached. The step waits for this machine's network, the same check, whichever host the outage was met on; such a failure is no try (an install's clean reinstall is not spent on it), a second failure while the network is down ends the stage on the outage, and so does the wait running out. A failure with the network up Blocks as before, its reason saying the network was up, that the step ran behind the local sandbox's proxy when it did, and that its first run met an outage when one did; it names no host. A harness pass whose model provider answered busy (`usage.mjs` `providerBusy`: HTTP 408, 425, 429 or a 5xx, 529 included, or with no status the AI Gateway's bare 5xx types `service_unavailable_error`, `overloaded_error` and `internal_server_error`; with no refusal type or code: a 5xx with an auth, permission, quota or billing type or code is that refusal; read from the same structured error as a refusal below, `providerError`) is no death and no network loss. Copilot's weekly and global rate limits (`user_weekly_rate_limited`, `user_global_rate_limited`) are not busy: they are usage limits with no reset reported, as its quota is. In a stage the pass waits 1, 2, 4… minutes doubling up to 30, or, when the error itself gave a time to go again and that is later, until that time: a 429's only, from its own fields (Claude Code's API error `api_error_params.rate_limit_info.resetsAt`; Copilot's `auto_mode_switch.requested` after the error with the same `errorCode`, its `retryAfterSeconds`), never an earlier or unrelated event. It then runs again from its own session (a reviewer's from its prompt) on what is left of its budget; the stage's time bounds it, not a count. A provider's time over an hour away goes through a usage limit's gate on a route with automatic account choice: another account free ends the stage as a usage limit, so the Objective moves there; else the stage's account is held until that time while it waits, so no other Objective starts on it. A wait that would end past the stage's in-place bound (fifteen minutes from the first busy answer on the local route, the work deadline elsewhere) or leave the pass under five minutes ends the stage: with the provider's time five minutes or more away, as a usage limit that resets then (its account held until that time, as any usage limit's is: paused locally, the holds record or a `provider-quota` Block elsewhere); else on the provider's host with the status as its code, as GitHub's 5xx does (paused locally, where `serve` resumes it on the same doubling; an `outage` Block elsewhere, which the dispatcher relaunches). A harness pass that fails (no cap, stop, provider refusal or busy answer) on a provider or network failure its harness reports with no status is no death: a server-error type (Claude Code's API error message `error: server_error`, which it gives a connection it could not make or a request that timed out), read from the same structured error (`providerError`), never the words. A pass whose harness reported a 4xx is no cut, whatever the network did while it ran: the provider answered and said why. Any other pass is judged on exact facts instead: one with no structured error at all (Codex prints a 5xx and a lost connection as prose only; a crash), and one whose structured error has no status and names no outage (a Copilot `session.error` with no `statusCode`, Claude Code's `unknown`). It is a cut when, between the pass's start and its end, this process met an outage of any kind on its provider's host (lost, or answering busy) or lost any host to this machine's network (a connect-level failure; a GitHub 5xx or another host's answer is none), or when its provider's API does not answer a probe now; otherwise it failed on its own. A cut pass waits, while its provider's API does not answer, as a request does; then, or at once when it answers, it runs again, from its own session when it has one (a reviewer's pass, and one with no session yet, as it was first run), on what is left of its budget and wall clock, at most twice, and its record carries every run's spend once. A stage's first steps (its token, the writers, the PR a review reads) end on an outage the same way as the rest. A stage waits in place up to fifteen minutes on the local route, where it then ends `paused` for `serve` to resume (LOCAL.md), and up to its work deadline on the Action and a cloud sandbox: still unreachable then, it stops waiting and Blocks with the External cause `outage`, naming the host, the error code and since when, if GitHub takes that one write, in a notice that mentions no one, since the dispatcher relaunches it. **A stage lost to a network failure on the Action and a cloud sandbox is relaunched** (`lib/relaunch.mjs`), being almost always transient. Two losses count. One is an `outage` Block that is the Objective's newest Blocked notice and was written after the Objective last became Running (GitHub's clock, from the issue's timeline, which the dispatcher already reads for every Blocked Objective and which carries the comments too); an older one never counts, so a later Block whose own notice did not land is not taken for it. The other is a stage that vanished with no exit because its runner or sandbox could not report: a Running Objective with no work job alive, or on the sandbox no stage within its lease, 15 minutes after its Running stint began. Those 15 minutes are for a job GitHub has not started yet: on the Action, a stint whose `work (<n>)` job GitHub's jobs API shows completed after the stint began (cancelled mid-harness, or gone with no exit) is judged at once, on the tick its job's last step fires, provided the timeline still shows the stint Running, a fresh read of the issue shows it open, `pendulum:running` and in no other state, and no restart is waiting. A job still queued or running, none shown yet, a job read that failed, or only an earlier stint's job (completed before this stint began) waits, and the dispatcher's wake ticks at the 15 minutes' end (`job-grace`), so a job that ended with no tick of its own is judged then. A stint a relaunch began has its job in the relaunch's run alone (the run its record names, when that stint began with the first Running label after the record was written). A tick that lists a live work job whose final tick step has started arms a `retry` wake, since that step's tick may read the job before GitHub marks it ended. A work job that dies after a tick saw it alive, with no final tick of its own, is judged by the next tick after GitHub ends it (at the latest its `timeout-minutes`), with the cron behind it. The stint's job is read at most once a tick per Objective, and only for one with no work job alive; the tick reads each run's jobs once, and one runs listing serves every stint that began within 15 minutes of another. A vanished stage that left a sign the network was not what ended it is not relaunched (`endedNotLost`, read from the stint's `work (<n>)` job as GitHub's jobs API gives it, its `conclusion` and `steps[]`, never a log): on the Action that job concluded `cancelled` or `timed_out` (a person, or the job's timeout: a stop, which keeps the vanished Block), or it failed before Pendulum ran, which is relaunched once (a checkout's or a token mint's 5xx, a runner not acquired, may pass), the step kept on the relaunch record, and Blocks with the cause `setup` naming the step when the relaunch's job fails at the same step (GitHub never started it: no step and no runner; or GitHub's `Set up job` failed; or a step failed before Pendulum's own work step, the step that `uses: clockgrove/pendulum@…` with `mode: work`, placed by reading the workflow file at the job's commit, one read only for a job that failed after its set-up: `Set up job` is step 1 and the job's steps follow in order, whatever they are named); on the sandbox its record says the stage ended. A job with no failed step of its own (its runner went away), whose Pendulum step failed with no exit written, or whose failed step cannot be placed because the workflow file cannot be read (the log says so) is lost. The dispatcher starts the work again as re-applying the label would: the Objective goes Running again, a new stint, and a work stage resumes its branch and PR (on a cloud sandbox, in the Objective's recorded sandbox), within `max_usd` like any stage. A relaunch spends like a pick: none starts while today's spend has reached `daily_usd` (it waits, unblocked, for the UTC day's turn, its `daily-cap` wake, or for a spend that can be read) or while `max_concurrent` is reached, and relaunches go before new picks. At most twice since a person last started the Objective (applied its label, started its draft, or restarted it), counted in a record Pendulum owns on the issue (marker `<!-- pendulum:<n>:relaunch -->`, each try naming that start), so a dispatcher that restarts keeps the count and a person's start begins a new one. So one start can spend up to 3 × `max_usd` on stages lost this way before the person is mentioned. Past that it Blocks, whatever the caps, and the notice says how many relaunches were tried: cause `outage`, the person mentioned, when the stage ended on one; a vanished stage gets the vanished Block (`worker job vanished`, cause `pendulum`) with the count. A write the relaunch needs that fails (its record, its labels, the Block) is tried again on the next tick, never turned into a Block. An Objective whose timeline the dispatcher cannot read is left as it is until a read succeeds: a vanished one stays Running, as any Running Objective whose Running time is unread does, and an outage-Blocked one stays Blocked on its stage's notice, which mentions no one; there is no fallback Block for that. On the Action, the stint's `work (<n>)` job is looked up in the run the relaunch record names (each relaunch records its dispatcher's run), else among the 10 newest runs created in the hour up to the stint's start; one not found is no sign either way, so the stage is relaunched. A stopped or draft Objective is never relaunched, nor is a restarting one (a vanished one gets the vanished Block, and its restart goes ahead). A Block whose newest notice is anything but a stage's `outage` notice is never relaunched. Every other command (the Action's dispatcher, doctor, setup, the launcher) keeps the client's bound above. +This machine's own network being down is not GitHub failing (`lib/network.mjs`). In a work or review stage, and in local mode's `serve`, a request that never left the machine (DNS, a refused or unreachable connect, a connect that timed out, or, behind a proxy, the proxy's 5xx to its CONNECT; read from Node's error code, never its message, except the proxy's status, which undici gives only in its one fixed tunnel message and which is read from that exact text) is no try: Pendulum probes that host, one request at a time after 5, 10, 20 and 30 seconds and then every minute, and sends the request again once the host gives any answer, a create included since it did nothing. Every other request to that host waits on the same probe rather than being sent, and the log has one line when the host is lost and one when it answers again; a host lost again within a minute of answering is the same outage, its first loss and its limit carried over and no new line logged unless it then stays down past a minute, when it gets one line then and one when it answers. Once a stage has stopped waiting, a request to a host it gave up on fails at once as that outage (its host, code and first loss), so the stage's end names it whichever call met it first. A Block that came from an outage ends on the outage instead, on any route, as below: a GitHub step of the exit (the split record, the review label, the mergeable record, the maintainers' comments read before a merge, the merge itself, the PR's first opening) that failed because its host did not answer, or because GitHub's core REST quota was spent (a spent GraphQL or search quota is no outage of a write). Any other Block stands, an outage or not: protected paths, a cap, validation, an exit record the harness wrote. While a host the stage gave up on still fails a probe, a harness pass cut off by its provider or the network (below) is no death and does not run again, and a run left with no exit record ends on the outage without the harness being asked, so its own account of a run the outage cut off never stands in for it; once the host answers again, such a pass runs again as above, and the harness is asked as ever. The App token's mint waits the same way. Any HTTP answer, a 5xx included, is the host answering and goes through the retries above, with no probe; a 5xx that outlasts them ends the stage on GitHub's outage at once, as one past the wait does (paused on the local route, where `serve` resumes it after a doubling wait for as long as GitHub's status page reports an incident: LOCAL.md; an `outage` Block elsewhere), and its reason names the request and says GitHub answered that status to every try since the first. A git fetch or push of the mirror that fails in transport while the remote's host does not answer a probe waits the same way, and its retry count starts again after. Pendulum's own git (the mirror's fetch and push, and its scratch repositories') reaches the network as its GitHub client does: through the proxy the stage process's own environment names when `NODE_USE_ENV_PROXY` is 1, else directly, and never through a proxy from git's own config or any other variable (`lib/network.mjs` `gitProxyEnv`). The settings are resolved as Node's fetch resolves them and given to git in the forms curl reads: `https_proxy` before `HTTPS_PROXY`, an https remote through the http proxy when no https one is set, and `NO_PROXY`'s entries (split on commas and white space, `*.` and a leading `.` dropped, a `host:port` entry kept only for the remote's port, `*` alone covering every host) rewritten as plain comma-separated hosts. An https remote goes through the proxy as a CONNECT tunnel carrying TLS, so its token reaches the proxy only encrypted. A proxy URL with a user and no password fails closed for git: git asks for the proxy's password, has no helper or prompt to answer it, and stops before connecting, while Node's fetch goes through the proxy with no proxy credentials. The repository's setup and install that fail while this machine's network is down run once more after it is back (`lib/checkout.mjs` `throughOutages`). Down is decided on exact facts only: an outage the stage recorded on any host while the step ran, GitHub's origin not answering a check on a fresh connection (no pooled socket stands in for it) that reaches the network as Pendulum's GitHub client does: through the proxy the stage process's own environment names when `NODE_USE_ENV_PROXY` is 1 (local mode's stages), else directly with its own DNS lookup, or one of the stage's own allowed hosts (the sandbox's built-in list, `PENDULUM_LOCAL_DOMAINS` or `allowed_domains`, and the Objective's approved `pendulum:host:` labels, as the route resolved them, those not GitHub's own first, lookups only) failing its lookup with `EAI_AGAIN`, as a resolver that still serves GitHub's names from its cache fails the rest. Nothing the step printed and nothing its checkout configures is ever probed or looked up, since the model edits both. The check connects only to GitHub's origin, the operator's own (`GITHUB_API_URL`, which may be a GitHub Enterprise Server on a private network); through a proxy, the proxy's failure to reach it (a tunnel it could not open, or its 502 for an http origin) is that origin unreached. The step waits for this machine's network, the same check, whichever host the outage was met on; such a failure is no try (an install's clean reinstall is not spent on it), a second failure while the network is down ends the stage on the outage, and so does the wait running out. A failure with the network up Blocks as before, its reason saying the network was up, that the step ran behind the local sandbox's proxy when it did, and that its first run met an outage when one did; it names no host. A harness pass whose model provider answered busy (`usage.mjs` `providerBusy`: HTTP 408, 425, 429 or a 5xx, 529 included, or with no status the AI Gateway's bare 5xx types `service_unavailable_error`, `overloaded_error` and `internal_server_error`; with no refusal type or code: a 5xx with an auth, permission, quota or billing type or code is that refusal; read from the same structured error as a refusal below, `providerError`) is no death and no network loss. Copilot's weekly and global rate limits (`user_weekly_rate_limited`, `user_global_rate_limited`) are not busy: they are usage limits with no reset reported, as its quota is. In a stage the pass waits 1, 2, 4… minutes doubling up to 30, or, when the error itself gave a time to go again and that is later, until that time: a 429's only, from its own fields (Claude Code's API error `api_error_params.rate_limit_info.resetsAt`; Copilot's `auto_mode_switch.requested` after the error with the same `errorCode`, its `retryAfterSeconds`), never an earlier or unrelated event. It then runs again from its own session (a reviewer's from its prompt) on what is left of its budget; the stage's time bounds it, not a count. A provider's time over an hour away goes through a usage limit's gate on a route with automatic account choice: another account free ends the stage as a usage limit, so the Objective moves there; else the stage's account is held until that time while it waits, so no other Objective starts on it. A wait that would end past the stage's in-place bound (fifteen minutes from the first busy answer on the local route, the work deadline elsewhere) or leave the pass under five minutes ends the stage: with the provider's time five minutes or more away, as a usage limit that resets then (its account held until that time, as any usage limit's is: paused locally, the holds record or a `provider-quota` Block elsewhere); else on the provider's host with the status as its code, as GitHub's 5xx does (paused locally, where `serve` resumes it on the same doubling; an `outage` Block elsewhere, which the dispatcher relaunches). A harness pass that fails (no cap, stop, provider refusal or busy answer) on a provider or network failure its harness reports with no status is no death: a server-error type (Claude Code's API error message `error: server_error`, which it gives a connection it could not make or a request that timed out), read from the same structured error (`providerError`), never the words. A pass whose harness reported a 4xx is no cut, whatever the network did while it ran: the provider answered and said why. Any other pass is judged on exact facts instead: one with no structured error at all (Codex prints a 5xx and a lost connection as prose only; a crash), and one whose structured error has no status and names no outage (a Copilot `session.error` with no `statusCode`, Claude Code's `unknown`). It is a cut when, between the pass's start and its end, this process met an outage of any kind on its provider's host (lost, or answering busy) or lost any host to this machine's network (a connect-level failure; a GitHub 5xx or another host's answer is none), or when its provider's API does not answer a probe now; otherwise it failed on its own. A cut pass waits, while its provider's API does not answer, as a request does; then, or at once when it answers, it runs again, from its own session when it has one (a reviewer's pass, and one with no session yet, as it was first run), on what is left of its budget and wall clock, at most twice, and its record carries every run's spend once. A stage's first steps (its token, the writers, the PR a review reads) end on an outage the same way as the rest. A stage waits in place up to fifteen minutes on the local route, where it then ends `paused` for `serve` to resume (LOCAL.md), and up to its work deadline on the Action and a cloud sandbox: still unreachable then, it stops waiting and Blocks with the External cause `outage`, naming the host, the error code and since when, if GitHub takes that one write, in a notice that mentions no one, since the dispatcher relaunches it. **A stage lost to a network failure on the Action and a cloud sandbox is relaunched** (`lib/relaunch.mjs`), being almost always transient. Two losses count. One is an `outage` Block that is the Objective's newest Blocked notice and was written after the Objective last became Running (GitHub's clock, from the issue's timeline, which the dispatcher already reads for every Blocked Objective and which carries the comments too); an older one never counts, so a later Block whose own notice did not land is not taken for it. The other is a stage that vanished with no exit because its runner or sandbox could not report: a Running Objective with no work job alive, or on the sandbox no stage within its lease, 15 minutes after its Running stint began. Those 15 minutes are for a job GitHub has not started yet: on the Action, a stint whose `work (<n>)` job GitHub's jobs API shows completed after the stint began (cancelled mid-harness, or gone with no exit) is judged at once, on the tick its job's last step fires, provided the timeline still shows the stint Running, a fresh read of the issue shows it open, `pendulum:running` and in no other state, and no restart is waiting. A job still queued or running, none shown yet, a job read that failed, or only an earlier stint's job (completed before this stint began) waits, and the dispatcher's wake ticks at the 15 minutes' end (`job-grace`), so a job that ended with no tick of its own is judged then. A stint a relaunch began has its job in the relaunch's run alone (the run its record names, when that stint began with the first Running label after the record was written). A tick that lists a live work job whose final tick step has started arms a `retry` wake, since that step's tick may read the job before GitHub marks it ended. A work job that dies after a tick saw it alive, with no final tick of its own, is judged by the next tick after GitHub ends it (at the latest its `timeout-minutes`), with the cron behind it. The stint's job is read at most once a tick per Objective, and only for one with no work job alive; the tick reads each run's jobs once, and one runs listing serves every stint that began within 15 minutes of another. A vanished stage that left a sign the network was not what ended it is not relaunched (`endedNotLost`, read from the stint's `work (<n>)` job as GitHub's jobs API gives it, its `conclusion` and `steps[]`, never a log): on the Action that job concluded `cancelled` or `timed_out` (a person, or the job's timeout: a stop, which keeps the vanished Block), or it failed before Pendulum ran, which is relaunched once (a checkout's or a token mint's 5xx, a runner not acquired, may pass), the step kept on the relaunch record, and Blocks with the cause `setup` naming the step when the relaunch's job fails at the same step (GitHub never started it: no step and no runner; or GitHub's `Set up job` failed; or a step failed before Pendulum's own work step, the step that `uses: clockgrove/pendulum@…` with `mode: work`, placed by reading the workflow file at the job's commit, one read only for a job that failed after its set-up: `Set up job` is step 1 and the job's steps follow in order, whatever they are named); on the sandbox its record says the stage ended. A job with no failed step of its own (its runner went away), whose Pendulum step failed with no exit written, or whose failed step cannot be placed because the workflow file cannot be read (the log says so) is lost. The dispatcher starts the work again as a trusted Draft removal would: the Objective goes Running again, a new stint, and a work stage resumes its branch and PR (on a cloud sandbox, in the Objective's recorded sandbox), within `max_usd` like any stage. A relaunch spends like a pick: none starts while today's spend has reached `daily_usd` (it waits, unblocked, for the UTC day's turn, its `daily-cap` wake, or for a spend that can be read) or while `max_concurrent` is reached, and relaunches go before new picks. At most twice since a person last started the Objective (applied its label, started its draft, or restarted it), counted in a record Pendulum owns on the issue (marker `<!-- pendulum:<n>:relaunch -->`, each try naming that start), so a dispatcher that restarts keeps the count and a person's start begins a new one. So one start can spend up to 3 × `max_usd` on stages lost this way before the person is mentioned. Past that it Blocks, whatever the caps, and the notice says how many relaunches were tried: cause `outage`, the person mentioned, when the stage ended on one; a vanished stage gets the vanished Block (`worker job vanished`, cause `pendulum`) with the count. A write the relaunch needs that fails (its record, its labels, the Block) is tried again on the next tick, never turned into a Block. An Objective whose timeline the dispatcher cannot read is left as it is until a read succeeds: a vanished one stays Running, as any Running Objective whose Running time is unread does, and an outage-Blocked one stays Blocked on its stage's notice, which mentions no one; there is no fallback Block for that. On the Action, the stint's `work (<n>)` job is looked up in the run the relaunch record names (each relaunch records its dispatcher's run), else among the 10 newest runs created in the hour up to the stint's start; one not found is no sign either way, so the stage is relaunched. A stopped or draft Objective is never relaunched, nor is a restarting one (a vanished one gets the vanished Block, and its restart goes ahead). A Block whose newest notice is anything but a stage's `outage` notice is never relaunched. Every other command (the Action's dispatcher, doctor, setup, the launcher) keeps the client's bound above. -GitHub's primary rate limit spent is an outage of one quota whose end GitHub states (`lib/network.mjs`, on the same wait): a 403 or 429, or GraphQL's `RATE_LIMITED`, with `x-ratelimit-remaining: 0`, an `x-ratelimit-reset` and no `Retry-After`, when GitHub's own count of that quota, read at once from `GET /rate_limit` with the same token (not counted against the primary rate limit, though it can count toward the secondary one, so it is not read again while the process holds that quota spent until the answer's reset or later), has none remaining; its reset is the count's. The quota read is the one the answer names (`x-ratelimit-resource`). A count with some remaining is no primary limit, whatever the answer says (a secondary limit, or a 403 for another reason on the last quota point), and keeps the retries above, as a `Retry-After` does; when the count cannot be read, the answer's own headers stand, as GitHub documents them. A quota is the host, GitHub's resource for the request (REST's core, GraphQL, search, code search, read from its path) and the token, so a spent GraphQL quota holds no REST call, and the notice App's or the agent's token none of the local token's. The reset is read on this machine's clock through the answer's `Date` header. In every process the error carries the code `RATE_LIMIT_SPENT` and the reset time; the process's record of a quota's reset is its latest answer, gone once the quota answers. In a work or review stage and in `serve`, the request that meets it is no try: it, and every other request against that quota, waits until the reset plus one to ten seconds, one sleep for all callers and no probe, with one log line when the limit is met and one when it has reset; then each goes again, a create included, since the refusal did nothing. A refusal that comes after the stated reset has passed here waits 5, 10, 20, 40 and then 60 seconds instead; one within a minute of a reset whose new reset is that near is the same wait, unlogged, while a quota spent again until a later reset is a new wait with its own two lines. A reset past the stage's in-place bound (fifteen minutes on the local route, its work deadline elsewhere) is not waited for: requests against that quota fail at once until the reset, its other quotas go on, and the stage ends on the first call that cannot go on without it. On the local route it ends `paused` with the reset in its `result.json`, and `serve` resumes it once the reset has passed, without a probe (LOCAL.md). On the Action and a cloud sandbox it Blocks with the External cause `provider-quota`, naming the reset; the Block is a GitHub write too, so a stage whose reset comes before its deadline plus twelve minutes (the job keeps fifteen after its deadline, which also pay for the steps before and the upload after) waits for it first, and with a later reset the Block's one write fails, and the dispatcher, once the reset lets it read GitHub again, relaunches the stage as one lost with no exit (`lib/relaunch.mjs`, above). A `provider-quota` Block is never relaunched: it mentions the person, who re-applies the label after the reset. The App token's mint carries the same code, only when the count, read with the App's JWT, says none remaining: with no count its answer is a rate limit with no stated end, since a refusal of the mint can meet the last quota point. A spent rate limit cuts no harness pass off. `serve` waits for the reset of a quota its own reads meet with no bound, so its ticks read, resume and start nothing until then. Every other command keeps the client's bound and gets the error with its code: the Action's dispatcher then starts nothing that tick, logs one line (`GitHub's API rate limit is spent until <time>; no new stage starts until then`) and arms a `retry` wake a minute after the reset; picks it already wrote stand. A tick that met its token's REST quota spent in a read it went on without starts nothing either. +GitHub's primary rate limit spent is an outage of one quota whose end GitHub states (`lib/network.mjs`, on the same wait): a 403 or 429, or GraphQL's `RATE_LIMITED`, with `x-ratelimit-remaining: 0`, an `x-ratelimit-reset` and no `Retry-After`, when GitHub's own count of that quota, read at once from `GET /rate_limit` with the same token (not counted against the primary rate limit, though it can count toward the secondary one, so it is not read again while the process holds that quota spent until the answer's reset or later), has none remaining; its reset is the count's. The quota read is the one the answer names (`x-ratelimit-resource`). A count with some remaining is no primary limit, whatever the answer says (a secondary limit, or a 403 for another reason on the last quota point), and keeps the retries above, as a `Retry-After` does; when the count cannot be read, the answer's own headers stand, as GitHub documents them. A quota is the host, GitHub's resource for the request (REST's core, GraphQL, search, code search, read from its path) and the token, so a spent GraphQL quota holds no REST call, and the notice App's or the agent's token none of the local token's. The reset is read on this machine's clock through the answer's `Date` header. In every process the error carries the code `RATE_LIMIT_SPENT` and the reset time; the process's record of a quota's reset is its latest answer, gone once the quota answers. In a work or review stage and in `serve`, the request that meets it is no try: it, and every other request against that quota, waits until the reset plus one to ten seconds, one sleep for all callers and no probe, with one log line when the limit is met and one when it has reset; then each goes again, a create included, since the refusal did nothing. A refusal that comes after the stated reset has passed here waits 5, 10, 20, 40 and then 60 seconds instead; one within a minute of a reset whose new reset is that near is the same wait, unlogged, while a quota spent again until a later reset is a new wait with its own two lines. A reset past the stage's in-place bound (fifteen minutes on the local route, its work deadline elsewhere) is not waited for: requests against that quota fail at once until the reset, its other quotas go on, and the stage ends on the first call that cannot go on without it. On the local route it ends `paused` with the reset in its `result.json`, and `serve` resumes it once the reset has passed, without a probe (LOCAL.md). On the Action and a cloud sandbox it Blocks with the External cause `provider-quota`, naming the reset; the Block is a GitHub write too, so a stage whose reset comes before its deadline plus twelve minutes (the job keeps fifteen after its deadline, which also pay for the steps before and the upload after) waits for it first, and with a later reset the Block's one write fails, and the dispatcher, once the reset lets it read GitHub again, relaunches the stage as one lost with no exit (`lib/relaunch.mjs`, above). A `provider-quota` Block is never relaunched: it mentions the person, who resumes through Draft after the reset. The App token's mint carries the same code, only when the count, read with the App's JWT, says none remaining: with no count its answer is a rate limit with no stated end, since a refusal of the mint can meet the last quota point. A spent rate limit cuts no harness pass off. `serve` waits for the reset of a quota its own reads meet with no bound, so its ticks read, resume and start nothing until then. Every other command keeps the client's bound and gets the error with its code: the Action's dispatcher then starts nothing that tick, logs one line (`GitHub's API rate limit is spent until <time>; no new stage starts until then`) and arms a `retry` wake a minute after the reset; picks it already wrote stand. A tick that met its token's REST quota spent in a read it went on without starts nothing either. A harness pass that ends on its subscription's usage limit is no crash and nothing wrong with the Objective (`lib/usage.mjs` `providerRefusal`, `lib/harness.mjs` `runHarness`). It is read from the harness's structured fields, never its words: Claude Code's result with `is_error` and `api_error: usage_limit_reached`, its reset from the API error message's `api_error_params.rate_limit_info.resetsAt`, else from the last `rate_limit_event` whose status is `rejected`, of the error's own window (`rateLimitType`) when it names one; a Copilot quota refusal (`session.error` with a quota type or HTTP 402), which reports no reset. Codex's `exec --json` stream reports its usage limit as prose only (an `error` event's `message`, exit 1 as for any failure), and neither `exec` nor its exit code carries a code or a reset, so the limit is read from the thread's rollout instead: when the ChatGPT backend refuses with `usage_limit_reached`, Codex records that answer's rate-limit snapshot as a `token_count` event there. A Codex run whose stream ended on an error is at its usage limit when the last such snapshot of the subscription's own limit group (`limit_id` `codex` or absent) stamped since the pass started names a `rate_limit_reached_type` or holds a window (`primary`, `secondary`) at `used_percent` 100 or more, and shows no credits to go on; a workspace's credits or spend cap counts whatever its credits show. The reset is the latest `resets_at` of the full windows (of any window when a type is named and none is full), and a workspace's credits or spend cap has none. Reason for the credits rule: on credits Codex runs on past its windows, so an unrelated failure then would otherwise hold every Codex Objective until a weekly reset. Reason: Codex's app-server protocol carries the code (`codexErrorInfo: usageLimitExceeded`), but `exec` drops it, and driving the app-server instead is a different harness integration; the snapshot is structure Codex already writes where Pendulum reads each run's usage. A limit met during compaction records no snapshot, and an API key or the AI Gateway gets no ChatGPT rate-limit headers: those failures stay what the stream says. No other model runs the pass, the reviewer's fallback included, since every model of the subscription draws on the same limit. In a work or review stage with the reset known, the pass waits for it (plus a minute) in place when that falls within the stage's in-place bound with five minutes of the pass's wall clock left after it, and then runs again on the same model, from its own session when it has one, at most twice (`usage_limit_waits`): the bound is fifteen minutes on the local route (`PENDULUM_LOCAL_WAIT_MINUTES`) and the work deadline on the Action and a cloud sandbox. A wait never runs the pass again past the dollar cap: with the cap spent, the pass ends there. Past that bound, after its two waits, or with too little wall clock left, the local route ends the stage `paused` with the reset in its `result.json`, for `serve` to resume after it, a work pass continuing on its kept clone and session when the branch on GitHub, the newest restart record, the Running stint and the Objective's text are as at the pause (`lib/continue.mjs`, LOCAL.md), and the Action and a cloud sandbox Block with the External cause `provider-quota`, naming the reset. With no reset reported, the stage Blocks with `provider-quota` at once, unless automatic account choice picked its account and another is free: the account is then passed over for a guessed while and the Objective moves to a free one (LOCAL.md and INSTALL.md, automatic choice). @@ -255,7 +255,7 @@ The merge queue is GitHub's. It serializes merges and re-runs CI on the integrat The design target is dozens of Objectives queued and in flight with nobody watching. It is not yet drilled at that size and is not among the 0.9 claims. -- **The dispatcher is the only scheduler logic.** Ready = labeled, not blocked by an open issue, not Running, In review, Blocked, Question or Done. Order = `P0`, `P1`, `P2`, then issue number. Start up to `max_concurrent`; stop for the day at `daily_usd`. +- **The dispatcher is the only scheduler logic.** Ready Objectives carry `pendulum:objective`, have Draft off and have no open dependency or Running, In review, Blocked, Question or Done state. Order = `P0`, `P1`, `P2`, then issue number. Start up to `max_concurrent`; stop for the day at `daily_usd`. - **Pendulum owns its ticks; GitHub's cron is only the backstop.** GitHub fires a schedule late or not at all under load: on the scratch repositories the `*/10` cron fired for under 3% of its slots over a week, hours apart. So every wait has an owner that ticks the dispatcher with `workflow_dispatch` (the job token's, never held for approval): an event (a label, an issue closing, a merge, CI finishing, a queue drop, an App's review on a Pendulum PR that is not Pendulum's own; a closed issue that was no Objective and blocks none ends its run after minting the token and at most one listing, so it costs a job start and seconds), the job that freed a slot or failed a launch, or, for a wait only time ends, the `wake` job. Each dispatcher run lists its deadlines (`{issue, kind, at}`, in its log) and arms one wake for the earliest of eight kinds: a sandbox stage's lease end plus a minute (a stage that died silently), a quota retry the launcher handed over, the next try of a failed start (2, 4, 8, 16, then every 30 minutes; a vendor's refusals never Block and hold the route's new picks for at most four in a row, three real failures or three cut-offs in a row Block; every attempt ends as a stored entry, docs/ADAPTERS.md), the next 00:00 UTC when `daily_usd` held Queued work back, one quick retry of a read that failed or of a work job whose final tick may have read it before it ended (never two in a row), the bound of a review stage's wait for a third-party reviewer (`third-party`, Review and merge), the bound of a hand-off's wait for a sibling on the same files (`sibling-wait`, Dispatch), and the end of a Running stint's 15-minute grace on the runners with no work job alive (`job-grace`, the vanished stage in Review and merge). The other kinds it lists (`launch-grace`, `review-grace`, `checks-grace`, `answer-grace`, `local-pause`) are their event's or the local loop's, with the cron behind them. A wake arms only when no wake already queued or sleeping fires before its deadline or within a minute after it (read from the `wake (<kind> <iso>)` job names), joins no concurrency group, and is never cancelled, so a duplicate only ticks twice; a run a wake started never arms that same deadline again, and dry runs and runs named for one issue arm none. Which kinds a repository arms follows its visibility, read from the event's repository payload (one repository read only when a schedule run has a long wait to decide; unknown counts as private). Cost: a wake sleeps on a hosted runner and holds one of the account's concurrent-job slots while it sleeps. - **Public repository:** Actions minutes are free, so it arms all eight kinds. On the sandbox route a lease wake sleeps through each stage (the heartbeat moves the lease on), and a capped day's turn is reached in hops of up to 350 minutes, each a plain tick. - **Private repository:** each sleeper bills about $0.36 an hour (a 2-core Linux runner at $0.006 a minute), so it arms only `quota`, `start-retry`, `retry` and `job-grace`, minutes each: about 5 to 20 billed minutes per quota retry, 2 to 30 per failed start, 2 per read retry, and up to 15 per Running stint a tick saw with no work job alive before its grace ended. Each launch the dispatcher names also arms a `start-retry` wake for its marker's expiry, about 10 billed minutes (about $0.06) per named launch unless an earlier wake covers it, so a normal Objective costs about 10 to 20 sleeper minutes (its work and its review). A stage's lease end, the day's turn and a third-party wait's bound stay in `deadlines[]` and wait for events and the cron (a sleeper to the bound would bill the minutes the wait frees); doctor says so on a private repository. diff --git a/docs/REPORT.md b/docs/REPORT.md index 2ef19bcc..25e9971e 100644 --- a/docs/REPORT.md +++ b/docs/REPORT.md @@ -25,7 +25,7 @@ pendulum report --compare-label wave-6 --compare-label wave-7 # any two labels - **Arms.** `--compare` takes two experiment names (the part after `pendulum:experiment:`), joined by a comma or as the flag twice; `--compare-label` takes two label names. Each arm is every issue with its label, read whole: `--since` and `--until` are refused with them, since a period would cut a merged Objective's dollars to the stages in it. An issue both arms count for is in neither, listed in `comparison.inBoth`. - **Who applied the label.** An arm's label counts for an issue only when the person who last applied it, by the issue's timeline, can push or is a maintainer the workflow names, as for the harness and model labels: a label applied by anyone else, by a bot or through an App is not counted (`untrusted`, missing code `label-untrusted`), nor one whose labeller's permission the token may not read (a 403: `unverifiable`, missing code `label-unverifiable`). An issue both arms list counts only once each arm's check of it ended. A `--label` that is an experiment label follows the same rule. The check reads each listed issue's timeline once, and each labeller's permission once, before any other record of it; the other labels a `--label` names are read as GitHub has them. -- **Per arm:** n (its Objectives) and their outcomes; then, over its merged Objectives, the median and p25..p75 of the dollars per merged Objective of each billing kind, the model minutes (every harness pass of each stage's per-pass ledger, from its progress comment's ledger line or its usage record; for a merged Objective read from its finish card, the summary's `modelMinutes`, as are its fix passes and its wall clock, `passes.fix` and `labelledWallMs`, the same figures), the wall clock (from the Objective's start to the merge, the scorer's rule: its first `pendulum:objective` or `pendulum:running` label, or for one filed as a draft the start that led to its first Running), the review rounds (`reviewRounds`, below; for a merged Objective read from its finish card, its summary's stages marked `noPass`, or whose spend line says so, are none: a card from before `noPass` was on its summary falls back to the spend line) and the fix passes; and its runs of unknown cost with their reasons. A kind's median counts every measured merged Objective, so one billed at another kind counts as $0 in it. A merged Objective with a run of unknown cost is left out of every dollar measure, and one whose measure was not recorded out of that measure (model minutes and fix passes: a stage with no ledger, or a stage comment Pendulum cannot attribute to itself; wall clock: no start event, or a label event from before the rename, on its stages and on its finish card alike, whenever the card was written: Before the rename, above); each is counted as `leftOut`. A merged Objective with stages from before the rename to Pendulum (`legacyStages`) has figures that leave those stages out, so it is left out of every measure, counted as `leftOut` and listed in the arm's `legacy`; an Objective of the arm with such stages is left out of its review findings too. The medians and quartiles interpolate between the closest ranks, the same computation as the bench's baseline line. +- **Per arm:** n (its Objectives) and their outcomes; then, over its merged Objectives, the median and p25..p75 of the dollars per merged Objective of each billing kind, the model minutes (every harness pass of each stage's per-pass ledger, from its progress comment's ledger line or its usage record; for a merged Objective read from its finish card, the summary's `modelMinutes`, as are its fix passes and its wall clock, `passes.fix` and `labelledWallMs`, the same figures), the wall clock (from the Objective's start to the merge, the scorer's rule: the first activation, or an older Objective's first `pendulum:running` label when its start event is unavailable), the review rounds (`reviewRounds`, below; for a merged Objective read from its finish card, its summary's stages marked `noPass`, or whose spend line says so, are none: a card from before `noPass` was on its summary falls back to the spend line) and the fix passes; and its runs of unknown cost with their reasons. A kind's median counts every measured merged Objective, so one billed at another kind counts as $0 in it. A merged Objective with a run of unknown cost is left out of every dollar measure, and one whose measure was not recorded out of that measure (model minutes and fix passes: a stage with no ledger, or a stage comment Pendulum cannot attribute to itself; wall clock: no start event, or a label event from before the rename, on its stages and on its finish card alike, whenever the card was written: Before the rename, above); each is counted as `leftOut`. A merged Objective with stages from before the rename to Pendulum (`legacyStages`) has figures that leave those stages out, so it is left out of every measure, counted as `leftOut` and listed in the arm's `legacy`; an Objective of the arm with such stages is left out of its review findings too. The medians and quartiles interpolate between the closest ranks, the same computation as the bench's baseline line. - **No claims.** The figures stand alone: no difference between the arms, no test of significance, no total across kinds or across arms. Every measure carries its n, and the Markdown shows each arm's rows under the table. The Markdown shows the comparison and the source only; the JSON's `totals`, `breakdowns`, `objectives` and `hotSpots` cover both arms together. ## Rate ratios @@ -61,7 +61,7 @@ The JSON's `schema` is `pendulum-report/2`. A change that renames, removes or re | `unknown` | `runs`; `decisionCalls` (the decision calls among them) and `unsplitRuns` (those no record says are decision calls or not); `stages` (the stages with runs of unknown cost: a decision record, or a vendor comment with no stage of its own, is an item but no stage); `reasons`: `{code, stages, runs, text}` per reason code, `stages` the stages (and decision records) naming it and `runs` its runs where no stage gives it with another reason, else null; `items`: `{issue, stage, runs, decisionCalls, unsplitRuns, why}` per stage with unknown cost (`stage` null for the comments of an Objective the call budget left unread) | | `breakdowns` | `stage` (`work`, `rebase`, `review`, `decisions`: the decision calls outside a stage; null: an Objective's comments the call budget left unread), `pass` (by pass label: the ledger label without its count, `work-2` as `work`; from the ledgers; `decision` the decision records' row, whose `passes` is 0), `model` (one name per model: an OpenAI model the Codex price table lists by the table's id, after any provider prefix and through the table's aliases, a dated snapshot suffix kept, so `openai/gpt-6.1-sol` is `gpt-6.1-sol` and `gpt-5.6` is `gpt-5.6-sol`; a Claude model's other name that `plugin/scripts/lib/claude-models.json` lists (a GitHub Copilot catalog id) by the Anthropic API id it maps it to, so `claude-sonnet-5.5` is `claude-sonnet-5-5`; any other id as recorded; by the model each pass ran on, below), `harness`, `version` (the Pendulum release that ran the stage), `route` (the route each stage ran on, as its spend line records it, `route`: `actions`, `local` or `sandbox`, the stage's progress comment's line, else its vendor comment's, which is always `sandbox`; every line a stage writes records it, the lines written while it runs too, so a stage killed or stopped before its end has it; `decisions` for the decision calls outside a stage; null for a stage whose line records none (a line written before Pendulum recorded it, or no spend line: `route-unrecorded`), a stage Pendulum cannot attribute, a record that names no stage and a run the call budget stopped before; never inferred from who posted a comment), `day` (the UTC date each stage started, its progress comment's, else its vendor comment's, else its record's start; each comment's decision-spend lines of one day summed and rounded once; each decision-spend line's own day for the decision calls outside a stage; null for a comment of decision lines Pendulum cannot attribute and a run the call budget stopped before; oldest first, null last; `stages` counts stages alone). A `decisions` row of `route` counts one stage per comment of decision-spend lines, as `stage` and the other breakdowns do; `day` counts none for them. An Objective read from its finish card's summary alone, its stage comments gone, has its stages under a null `day` and `route`: those come from the stage comments, which the summary does not carry), and `account` with `--by account`. Each row: `key` (null where no record names it), `stages`, `cost`, `tokens`. A `pass` row has `passes` (its harness passes) and `decisionRecords` in place of `stages`, and `modelMinutes`: the model minutes of its harness passes that have their times, null for none (the `decision` row's). A `model` row's split of its runs of unknown cost follows its parts: a decision record booked by pass brings its decision calls with it, and the rest of the stage's split stays with what is booked by stage. A `model` row also has `basis`: `pass` and `stage`, each `{stages, cost, tokens}` (null where none was booked so), the row split by how its figures were booked; and `usdPerModelMinute`, as an Objective's (below), over the priced harness passes that ran on the model, each pass under the model its ledger names, as its dollars are booked (a stage's passes under its own model where they are booked by stage; a pass's whole dollars under the model the pass ran on, so in a Claude stage whose `cost` books its sub-agents under their own models, a pass's sub-agents' dollars count toward its own model's ratio). Every breakdown covers the totals' dollars and runs of unknown cost. `pass` has a row per pass label from the ledgers, with `modelMinutes` and `spendLineStages`: a stage with no ledger whose spend line names its dollars by pass kind (`usdByPass`: `work`, `review`, `answer`, `fix`, `conflict`, `decision`) puts those dollars under that kind, with no pass counted, its runs of unknown cost with its own reasons, and counts in that row's `spendLineStages`; then one row with `key`, `passes` and `decisionRecords` null, the dollars no pass names (decision calls outside a stage, stages with no passes known, and what a stage's figure holds beyond its passes': its cloud sandbox, runs of unknown cost), present when any is not zero, whose `tokens` are those of the stages with no ledger. It is never negative: a stage whose passes name more dollars of a kind, or more runs of unknown cost, than its own figure (`ledger-overruns`) keeps its passes, tokens and minutes counted in their pass rows, and only its dollars and runs of unknown cost move from them to this row, the stage's whole figure | | `findings` | The review findings and their outcomes (below): `outcomes` (the outcome codes, in order), `totals`, `byReviewer`, `byStage` | -| `objectives` | One row per Objective: `issue`, `title`, `url`, `outcome` (`blocked` or `question` by its state label; else `open` while the issue is open; else `merged` when the newest PR on `pendulum/<n>` from the repository itself, not a fork, merged, or `closed-unmerged`; null when its issue, or for a closed one its PRs, could not be read), `stages` (`work`, `rebase`, `review` counts), `reviewRounds` (its review stages that ran a pass: one whose spend line, else the usage record read for it, says `noPass` is none), `passes` (harness passes: `total`, `answer`, `fix`; null without a ledger for every stage), `decisionRecords` (null as `passes` is), `cost`, `tokens`, `modelMinutes` (the model minutes of every harness pass, to a hundredth; null unless every stage has its ledger, none is a stage Pendulum cannot attribute, and every harness pass has its start and end: the finish card summary's `modelMinutes` and the arms' rule; stages from before the rename are not read, so with `legacyStages` it is the minutes of the stages read, as every figure of the row is), `usdPerModelMinute` (per billing kind with dollars, over the harness passes with times whose dollars were all reported: `{usd, pricedMinutes, pricedPasses, usdPerModelMinute}`, their dollars of that kind, their model minutes to a millionth, their count, and the dollars over those minutes as shown, to a millionth; the same passes for every kind, never summed across kinds; null without a ledger for every stage, `{}` with no priced minutes), `unpricedPasses` (the harness passes with times whose dollars were not all reported), `legacyStages` (its stages from before the rename to Pendulum in the period, not read: Before the rename, above; 0 for none), `findings` (its review findings, as `findings.totals` counts them; null with no findings record, zero counts with its records all outside the period); `asked` and `churn` (Where the dollars went, below); `started` (the scorer's start of its clock, its first `pendulum:objective` label, from its newest finish card's summary, `labelled`, else from its timeline where the report read it, an arm's label check), `merged` (for a merged Objective, its last merge: that card's merge or the last merge of a PR on its branch, whichever is later; a reopened Objective merged again has a card per merge, and its newest clocks it, on both paths, whichever card its figures are read from), `wallMinutes` (from its first labelled start to that last merge), `clockWhy` (null with all three, else why not: `not-merged`, `outcome-unread`, `no-card`, a merged Objective with no finish card summary of Pendulum's own, `no-label`, no label event, `renamed`, an issue labelled before the rename to Pendulum, whose start the report cannot trust: its newest finish card records it (`clockWhy` `renamed`), or, for a card from before that was recorded, its timeline shows it, read for that card or by an arm's label check, in every scope alike; or `timeline-unread`, such an older card whose timeline the call budget stopped the report before reading, or GitHub refused: never a short clock); `route` (the route its stages' spend lines record, as `breakdowns.route` names each: one, `mixed` for more than one, null when a stage's is not recorded and the rest name at most one: a stage Pendulum cannot attribute, an `unmatched` usage record or one that names no stage leaves it null, a vendor comment someone else wrote of no stage does not), `blockedNotices` (Pendulum's own Blocked notices on the issue written in the period; a Block that repeats one condition upserts its one notice, so it counts once), `running` (it carries the Running state label as its issue was read; null when the issue was not read) | +| `objectives` | One row per Objective: `issue`, `title`, `url`, `outcome` (`blocked` or `question` by its state label; else `open` while the issue is open; else `merged` when the newest PR on `pendulum/<n>` from the repository itself, not a fork, merged, or `closed-unmerged`; null when its issue, or for a closed one its PRs, could not be read), `stages` (`work`, `rebase`, `review` counts), `reviewRounds` (its review stages that ran a pass: one whose spend line, else the usage record read for it, says `noPass` is none), `passes` (harness passes: `total`, `answer`, `fix`; null without a ledger for every stage), `decisionRecords` (null as `passes` is), `cost`, `tokens`, `modelMinutes` (the model minutes of every harness pass, to a hundredth; null unless every stage has its ledger, none is a stage Pendulum cannot attribute, and every harness pass has its start and end: the finish card summary's `modelMinutes` and the arms' rule; stages from before the rename are not read, so with `legacyStages` it is the minutes of the stages read, as every figure of the row is), `usdPerModelMinute` (per billing kind with dollars, over the harness passes with times whose dollars were all reported: `{usd, pricedMinutes, pricedPasses, usdPerModelMinute}`, their dollars of that kind, their model minutes to a millionth, their count, and the dollars over those minutes as shown, to a millionth; the same passes for every kind, never summed across kinds; null without a ledger for every stage, `{}` with no priced minutes), `unpricedPasses` (the harness passes with times whose dollars were not all reported), `legacyStages` (its stages from before the rename to Pendulum in the period, not read: Before the rename, above; 0 for none), `findings` (its review findings, as `findings.totals` counts them; null with no findings record, zero counts with its records all outside the period); `asked` and `churn` (Where the dollars went, below); `started` (the scorer's first activation, from its newest finish card's `labelled` field or from its timeline when the report reads it for an arm's label check), `merged` (for a merged Objective, its last merge: that card's merge or the last merge of a PR on its branch, whichever is later; a reopened Objective merged again has a card per merge, and its newest clocks it, on both paths, whichever card its figures are read from), `wallMinutes` (from its first activation to that last merge), `clockWhy` (null with all three, else why not: `not-merged`, `outcome-unread`, `no-card`, a merged Objective with no finish card summary of Pendulum's own, `no-label`, no activation event, `renamed`, an issue labelled before the rename to Pendulum, whose start the report cannot trust: its newest finish card records it (`clockWhy` `renamed`), or, for a card from before that was recorded, its timeline shows it, read for that card or by an arm's label check, in every scope alike; or `timeline-unread`, such an older card whose timeline the call budget stopped the report before reading, or GitHub refused: never a short clock); `route` (the route its stages' spend lines record, as `breakdowns.route` names each: one, `mixed` for more than one, null when a stage's is not recorded and the rest name at most one: a stage Pendulum cannot attribute, an `unmatched` usage record or one that names no stage leaves it null, a vendor comment someone else wrote of no stage does not), `blockedNotices` (Pendulum's own Blocked notices on the issue written in the period; a Block that repeats one condition upserts its one notice, so it counts once), `running` (it carries the Running state label as its issue was read; null when the issue was not read) | | `hotSpots` | Each `{rankBy, items}`, ranked by `rankBy`, largest first: `reviewLoops` (per Objective with a review round: `issue`, `reviews` its `reviewRounds`, `reviewerPasses` its reviewer's passes, the `review` passes of its ledgers, null as its `modelMinutes` is for a stage with no ledger or one Pendulum cannot attribute), `answerAndFixPasses` (answer and fix passes per Objective; `unrecorded` lists the Objectives with no ledger), `cacheWriteShare` (per pass label: `passLabel`, `passes`, `written`, `input`, `share`), `costPerModelMinute` (per model and billing kind, from `breakdowns.model`: `model`, `billing`, `usd`, `pricedMinutes`, `pricedPasses`, `usdPerModelMinute`), `blockedOrUnmergedSpend` (the Objectives that ended Blocked or closed unmerged, with their `stages` and `cost`), `blockedStages` (per Objective, its stages whose spend line records they ended Blocked, `exit` `blocked`: `stages`, `keys` (`{stage, key}`) and their `cost`; `unrecorded` lists the Objectives with a stage whose records do not say how it ended: no spend line, a line written while the stage ran (the last line of a stage killed or stopped before its end: only its final line records the exit), a spend line from before Pendulum recorded its exit, or a stage Pendulum cannot attribute) | | `comparison` | Null without `--compare` or `--compare-label`. Else `inBoth` (issues both labels count for, in neither arm) and `arms`, two, in the order given: `label`, `experiment` (its name, or null for another label), `n`, `outcomes` (a count per outcome, `unread` for null), `merged`, `usdPerMerged` (per cost kind), `modelMinutes`, `wallMinutes`, `reviewRounds`, `fixPasses`, each `{median, p25, p75, n, leftOut}` over the merged Objectives (null where none has the measure); `findings` (counts over the arm's Objectives with a findings record: `objectives`, `findings`, `outcomes`, `reviewStages`, `unnamed`; Review findings, below); `unknown` (`runs`, `objectives`, `reasons`: `{code, objectives, text}`); `untrusted`, `unverifiable` and `unchecked` (issues with the label not counted: its last applier cannot push, its applier's permission could not be read, or the call budget stopped before the check); `legacy` (its Objectives with stages from before the rename to Pendulum, `legacyStages`: left out of its review findings, and when merged of every measure); `objectives` (per Objective: `issue`, `outcome`, `usd` per kind, `unknownRuns`, `modelMinutes`, `wallMinutes`, `reviewRounds`, `fixPasses`, `findings`: its review findings, null without a record, `legacyStages`) | | `rates` | Null without `--rates`. Else `words` (what a ratio is, to label it with exactly), `usable` (false when no ratio could be weighed at all: `skipped` then says why for every model and candidate), `candidates` (the models named, an alias once), `basis` (the tables and their dates the ratios read, or null with none), `tables` (`{vendor, file, date}` per published rate table), `items` (`{model, rateOf, candidate, candidateRateOf, vendor, mix, long, ratio}`: the model, as `breakdowns.model` names it, and the table row it read, the candidate and its row, their vendor, `mix` the recorded tokens and `long` their long-context share, each as `{uncached, cached, written, output}`, and `ratio` the candidate's rates over the model's on that mix, to a millionth) and `skipped` (`{model, candidate, why, text}` for each model, candidate or pair with no ratio: `no-rate-table`, `price-ended`, `other-vendor`, `same-model`, `no-tokens`, `sub-agents`, `pass-models`, `long-context`; `model` or `candidate` null where the reason is the other's alone) | @@ -90,13 +90,13 @@ Each finish card ([USAGE.md](USAGE.md#the-finish-card)) carries one hidden line | Field | What it holds | | --- | --- | | `v`, `pendulum`, `issue` | The summary's version, the Pendulum release that posted the card, and the issue | -| `started`, `merged`, `wallMs` | The card's clock (the label that started the run), the merge, and the wall clock between them: null when the issue has a label event from before the rename to Pendulum (Before the rename, above), which the card says instead of a wall clock that would start too late | +| `started`, `merged`, `wallMs` | The card's clock (activation within the run), the merge, and the wall clock between them: null when the issue has a label event from before the rename to Pendulum (Before the rename, above), which the card says instead of a wall clock that would start too late | | `workMs`, `waitMs`, `waits` | The wall clock's two parts as the card shows them, and the recorded waits behind them. `waits`, oldest first: `{kind, why, start, end, blockers}`, `kind` what recorded it (`blocked-by`: the issue's blocked-by relation, from its `blocked_by_added` event or the clock, whichever is later, to the blocking issue's close or the relation's removal, only when that came by the first stage's start; `paused`: a stage whose spend line or usage record says it ended paused on a usage limit or an outage, from its last write to the next stage's start; `blocked`, `question`: Pendulum's notice, to the next stage's start), `why` one of `blocked-by`, `usage-limit`, `outage`, `you`, or null when the record names none, and `blockers` the blocking issues of a `blocked-by` wait (`#12`, or `owner/name#12` in another repository, the one its event names). A wait with no recorded start and end is not in the list, and no time is in two waits: one that begins inside an earlier one starts at that one's end, and is left out when nothing of it is left. `waitMs` is the time those waits cover inside the clock; `workMs` is the rest of `wallMs`, null when `wallMs` is. A card from before waits were recorded has none of the three, and reads as `waits` null: not recorded, never no wait. `pendulum report` reads them back with the summary and shows none of them | | `prs`, `commits`, `additions`, `deletions`, `files` | The merged PRs and their change, every part of a split Objective added up | | `checks`, `reviews` | `{passed, failed, required}` of the checks that gated the merge, and `{count, findings}` of Pendulum's reviews; each null for none | | `stageCounts` | `{work, rebase, review}` as the report counts stages: a build and a split part are `work` | | `passes`, `decisionRecords`, `modelMinutes`, `tokens` | The Objective's harness passes `{total, answer, fix}` (null unless every stage's are known: each of Pendulum's stages has its ledger, and none is a stage Pendulum cannot attribute), its stages' decision records, which are no pass and are counted apart as the report's `passes` and `decisionRecords` are (null as `passes` is; a card with no such field counts them in `passes.total`, and a reader takes them back out of it from `stages[].passes`, or, where that card carries no stage's passes, reads the total as written and no count of them), the minutes of every harness pass (null unless its passes are known and each harness pass has its times), and every stage's tokens summed | -| `labelled`, `labelledWallMs`, `clockWhy` | The scorer's start of the clock (the first `pendulum:objective` label, with no restart window) and the wall clock from it to the merge; null with no label event, and `labelledWallMs` null as `wallMs` is for a label event from before the rename, which `clockWhy` then records as `renamed` (null otherwise). A card from before `clockWhy` was recorded has no such field | +| `labelled`, `labelledWallMs`, `clockWhy` | The scorer's first activation, with no restart window, and the wall clock from it to the merge. An Objective filed as a draft starts at `pendulum:draft` removal. Older Objectives can start at `pendulum:objective` application. With no activation the start is null. For an Objective from before the rename, `labelledWallMs` is null and `clockWhy` records `renamed` (null otherwise). A card from before `clockWhy` was recorded has no such field | | `cost` | `{usd, cents, unknown, why, byBilling}`: the known dollars, the runs of unknown cost with their reason codes, and the dollars by billing kind; the cloud sandbox's dollars are in it, and apart below | | `sandbox` | The cloud sandbox's own cost `{usd, cents, unknown, why, foreign}`, or null: `why` is `sandbox` for a stage's own vendor comment whose usage the vendor did not report and `unattributed` for one Pendulum cannot attribute; `foreign` the stage kind (`work`, `review`) of each vendor comment Pendulum cannot attribute of no stage with a progress comment, one each | | `stages` | In time order: `kind` (`build`, `part`, `work`, `rebase`, `review`), `key` (its progress comment's run key, as its usage record and findings record name it), `part`, `model`, `harness`, `version` (the Pendulum release that ran it), `ms` (null for a stage with no progress comment), `usd` (null: none known), `cents`, `unknown`, `why`, `byBilling`, `sandbox` (its own vendor comment's `{usd, unknown}`, or null), `churn` (its churn rows' codes), `tokens` (`{input, output, cached, written}`, a count left out where none is reported), `passes`, `noPass` (true for a stage whose spend line or usage record says it ran no pass of a kind: no review round) and `unattributed` (true for a stage Pendulum cannot attribute) | diff --git a/docs/USAGE.md b/docs/USAGE.md index 712c6cb9..cc3c7fa3 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -6,7 +6,8 @@ How to write an Objective, what you see while it runs, and what to do when Pendu The Pendulum terms used across the README, this page and [LOCAL.md](LOCAL.md): -- **Objective:** a GitHub issue labelled `pendulum:objective`. Its text is the whole specification of the work (Write an Objective, below). +- **Objective:** a GitHub issue identified by its `pendulum:objective` label throughout its lifecycle. Its text is the whole specification of the work (Write an Objective, below). +- **Draft:** an Objective held by `pendulum:draft`. Add Draft to hold or stop an Objective and remove it to start or resume it. - **Harness:** the coding agent that runs the model: Claude Code, Codex or GitHub Copilot CLI. The workflow's `PENDULUM_HARNESS` picks it, and a `pendulum:harness:<name>` label overrides that for one Objective (Choose the harness and models, below). - **Stage:** one job of an Objective's run. The work stage plans, builds and delivers the PR. The review stage runs the reviewer, and the worker answers its comments. Each stage runs in a sandbox, and `max_usd` caps each one on the spend its coding agent reported. A run whose cost was not reported (killed or crashed before it reported) is shown as a run of unknown cost and not counted against the cap, so a stage can pass `max_usd` by it. - **Route:** where a stage runs: GitHub Actions (the default), local mode on your own machine, or a cloud sandbox. Every route keeps the Objective's state in GitHub. @@ -18,14 +19,15 @@ The Pendulum terms used across the README, this page and [LOCAL.md](LOCAL.md): - **Blocked (a Block):** Pendulum could not finish and hands the Objective back to you. One comment on the issue gives the reason, the issue carries `pendulum:blocked`, and the PR, if any, becomes a draft (Blocked and Question, below). - **Question:** the work depends on a decision that should be yours. The worker finishes the rest and asks in the draft PR, or on the issue before any code. The issue carries `pendulum:question` (Blocked and Question, below). - **Hand-over:** a change under `.github/workflows/` that Pendulum never pushes. Pendulum posts the exact change on the issue and labels it `pendulum:handover`, and you apply it with `pendulum handover <issue>` (Workflow changes, below). -- **Walk-away:** an Objective that merged with no human input after its label: no push, comment, review, edit or draft/ready toggle by a person on the branch or the issue. It is the scorecard's first number ([bench/README.md](../bench/README.md)). +- **Walk-away:** an Objective that merged with no human input after its first activation. A push, comment, review, edit or later Draft or PR-ready change by a person on the branch or issue counts as input. [Bench scorecard](../bench/README.md) ## Write an Objective An Objective is a GitHub issue with the `pendulum:objective` label: a feature or an epic, which the worker plans, splits across implementer sub-agents and delivers as one or more pull requests. A quick fix is better as a direct pull request. The issue is the whole specification: write everything the work needs into it. The worker asks you something only when the work depends on a decision that should be yours (a Question, below). Ask a session to file one for you ("File a Pendulum Objective: ...", the pendulum-file skill), which starts it or saves it as a draft to refine and start later (An Objective's lifecycle, below), or write the issue yourself: - **State the goal and what must be true when it is done.** Put the acceptance entries in a list under a heading that is exactly `Acceptance` (any level; lists under its sub-headings count too, so out-of-scope notes go in another section). The reviewer judges each entry, met or not, with the line that shows it. Without that heading, the reviewer names the entries from the issue text itself. -- **Order it after another Objective** by adding a GitHub issue dependency (blocked by) before the issue carries `pendulum:objective`, which starts it at once: the dispatcher then starts it once that issue is closed. A `Blocked by #N` line in the body is read only where GitHub's issue dependencies are unavailable. +- **File it with both `pendulum:objective` and `pendulum:draft`.** Remove Draft when the issue is ready to enter the queue. Keep `pendulum:objective` on it. +- **Order it after another Objective** by adding a GitHub issue dependency (blocked by) before removing `pendulum:draft`. The dispatcher can start it once the issue that blocks it is closed. A `Blocked by #N` line in the body is read only where GitHub's issue dependencies are unavailable. - **Say what you have decided.** Where the issue admits more than one reading, the worker takes the simplest one that satisfies every acceptance entry and records it as an assumption in its plan and in the PR. - **File it yourself, or have someone who can push file it.** Pendulum acts on an issue only when its author, its last editor once the body was edited, and whoever made its latest rename once the title was renamed, can push to the repository or are maintainers the workflow names. Otherwise the run Blocks before any model sees the text. A maintainer labelling someone else's issue is not enough: the author is checked on every run, so such an issue needs refiling by someone who can push. - **Keep it to one repository** (below). @@ -61,13 +63,13 @@ The workflow file's `PENDULUM_HARNESS`, `PENDULUM_MODEL`, `PENDULUM_SUBAGENT_MOD | `pendulum:subagent-model:<id>` | `PENDULUM_SUBAGENT_MODEL`: the implementer sub-agents. | | `pendulum:reviewer-model:<id>` | `PENDULUM_REVIEWER_MODEL`: the reviewer. | -- **Apply them when you file the issue,** with `pendulum:objective` (`gh issue create … --label pendulum:objective --label pendulum:model:claude-sonnet-5-5`; `gh label create <name>` first makes a label the repository lacks). The pendulum-file skill offers them. -- **Who applied a label counts.** Pendulum acts on one only when the person who last applied it, by the issue's timeline, can push or is a maintainer the workflow names, since GitHub lets anyone with triage access apply labels. Otherwise the Objective Blocks before any spend, naming the label. Starting an Objective is checked the same way, with another outcome: `pendulum:objective` applied (the first time, again after a stop, or re-applied to a Blocked, Question or In-review Objective), a draft started by taking `pendulum:draft` off, and `pendulum:restart` each count only from a person (never a bot or an App) who can push or is a maintainer the workflow names. Anyone else's changes nothing: the Objective stays as it was and does not run on it, one comment on the issue says it was not taken, and a refused `pendulum:restart` is taken off. Taking a label off is not checked, since GitHub does not ask who may: before the plan, a label anyone with triage access removes sends the Objective back to the repository's default; after the plan, a removal Blocks it as an edit (below). +- **Apply them when you file the issue,** with `pendulum:objective` and `pendulum:draft` (`gh issue create … --label pendulum:objective --label pendulum:draft --label pendulum:model:claude-sonnet-5-5`). Use `gh label create <name>` first for a label the repository lacks. The pendulum-file skill offers these choices. +- **Who applied a label counts.** Pendulum acts on one only when the person who last applied it, by the issue's timeline, can push or is a maintainer the workflow names, since GitHub lets anyone with triage access apply labels. Otherwise the Objective Blocks before any spend, naming the label. Removing `pendulum:draft` to start or resume and applying `pendulum:restart` count only when done by a person who can push or a maintainer the workflow names. Bots and Apps cannot start or restart an Objective through these label changes. This also applies to legacy `pendulum:objective` start events. Pendulum records a refused start on the issue and does not run it. A refused `pendulum:restart` is taken off. Before the plan, removing a harness or model label sends the Objective back to the repository default. After the plan, removing one Blocks it as an edit. - **A choice it cannot run Blocks before any spend,** naming the label and the fix: two labels of one kind, a harness Pendulum does not run, or a model the harness cannot run. Claude Code takes any id, since whether its login serves the model is Anthropic's answer. A main session's model (`pendulum:model:`, and `pendulum:reviewer-model:` for the review) is refused before any token is billed; a sub-agent's (`pendulum:subagent-model:`, or `pendulum:reviewer-model:` for a reviewer sub-agent) when that sub-agent first starts, where the stage stops the run, with the main model's spend so far billed. Either way the stage Blocks naming it. Codex runs a model with a row in Pendulum's Codex price table (`plugin/scripts/lib/codex-prices.json`), since without one `max_usd` could not stop its runs; a provider prefix (`openai/`) is taken only with the AI Gateway key, and Pendulum adds it itself. Copilot's model names come from its own catalog, which varies by account and which Pendulum cannot read before a run, so Pendulum checks only the form (no provider prefix or spaces): a name the account's Copilot does not offer is not caught before Copilot starts. `max_usd` and `daily_usd` apply whatever the model. - **GitHub caps a label name at 50 characters,** so an id fits in 35 characters after `pendulum:model:` and in 26 after `pendulum:subagent-model:` or `pendulum:reviewer-model:`. Every model in Pendulum's price tables and defaults fits; GitHub refuses a longer name, so use the model's id without its date suffix, or make it the repository's default. -- **Every route honours it.** The Action's work and review jobs read the harness label before they install a harness, and install that one; the workflow hands each job every harness's secret, so the chosen harness needs its own secret (a missing one Blocks the Objective, naming it). The cloud-sandbox launcher hands the stage that harness's credential and the repository's defaults, so the stage reads the labels again, and Blocks before any sandbox call when the launch job holds none. `harness_version` pins the harness the workflow's env block names only: a harness a label, a run's override or a repository variable chooses installs its latest. Local mode (`pendulum serve`, `pendulum run`) runs another harness than its own when this machine can (its CLI and its sandbox, and for Copilot its token, as `pendulum serve` checks its own at start), else Blocks the Objective, and the loop's log names what is missing. A stage that finds its labels name another harness than the one its job, sandbox or loop prepared for Blocks; re-apply `pendulum:objective`. `/pendulum:pendulum-run --here` runs in your own session, on its harness and model, whatever the labels say. +- **Every route honours it.** The Action's work and review jobs read the harness label before they install a harness, and install that one; the workflow hands each job every harness's secret, so the chosen harness needs its own secret (a missing one Blocks the Objective, naming it). The cloud-sandbox launcher hands the stage that harness's credential and the repository's defaults, so the stage reads the labels again, and Blocks before any sandbox call when the launch job holds none. `harness_version` pins the harness the workflow's env block names only: a harness a label, a run's override or a repository variable chooses installs its latest. Local mode (`pendulum serve`, `pendulum run`) runs another harness than its own when this machine can (its CLI and its sandbox, and for Copilot its token, as `pendulum serve` checks its own at start), else Blocks the Objective, and the loop's log names what is missing. A stage that finds its labels name another harness than the one its job, sandbox or loop prepared for Blocks. Resume through Draft once the route and harness are ready. `/pendulum:pendulum-run --here` runs in your own session, on its harness and model, whatever the labels say. - **A manual run's `harness` input** (`gh workflow run pendulum.yml -f issue=<number> -f harness=codex`) overrides the default for that run; a harness label on the issue wins over it. -- **A label added, removed or changed after the plan is an edit** (Edit an Objective, below): the next stage Blocks, re-applying `pendulum:objective` plans again on the new choice, and `pendulum:restart` starts over with it. +- **A label added, removed or changed after the plan is an edit** (Edit an Objective, below): the next stage Blocks. Resume through Draft to plan again on the new choice, or use `pendulum:restart` to start over with it. - **What ran is on the record:** the progress comment's harness line, the usage record's `ran` and the scorecard's Harness column name the harness, the worker, sub-agent and reviewer models, and the labels that chose them, and the account each stage ran on (LOCAL.md, Accounts; INSTALL.md, Several accounts). - **The account too:** `pendulum:account:<name>` moves an Objective to another account of its harness: in local mode one the machine that runs it declares, for instance when a usage limit pauses it (LOCAL.md, Accounts); on Actions and the cloud sandbox one the workflow declares (INSTALL.md, Several accounts), where with none declared it does nothing and the progress comment says so. It is trusted like the labels above, but it is no edit: adding or removing it after the plan Blocks nothing. @@ -108,24 +110,24 @@ While a job runs, one comment on the issue (edited in place, one per run) reads ## An Objective's lifecycle -Each step is one action on GitHub. Where a skill is named, a plain-words request to your agent takes that action after asking you. +`pendulum:objective` identifies the issue throughout its lifecycle. `pendulum:draft` controls whether it can run. Where a skill is named, ask your agent in plain words and confirm the proposed change. -- **Draft.** An issue with the `pendulum:draft` label is a draft: Pendulum never runs it, on any route, even with `pendulum:objective` on it too (the draft label wins: the dispatcher's log lists it as a draft, and a launch, `pendulum run` or a session's `pendulum issue` refuses it). Nothing is dispatched, claimed or spent for it. The pendulum-file skill offers it beside starting at once: it shows the issue and asks whether to start it now, save it as a draft, or keep discussing. "Let's keep working on Pendulum Objective #12" (the same skill) loads the draft from GitHub to refine it with you and saves the changes back to the issue only on your yes. Edit a draft freely: before its first plan, an edit is simply the text the run starts from. +- **Draft.** File the issue with both `pendulum:objective` and `pendulum:draft`, even if you plan to start it right away. While Draft is on, every route skips it for dispatch and refuses commands that would start it. The pendulum-file skill shows the issue and asks whether to start it now, save it as a draft or keep discussing. "Let's keep working on Pendulum Objective #12" loads the draft for you to refine and saves any changes on your yes. Edits while it is held are used for its next plan. -- **Start.** Applying `pendulum:objective` admits the Objective to the queue. The dispatcher starts eligible work when there is capacity. It checks on the label's event or its ten-minute cron on Actions, and on `pendulum serve`'s next tick locally. When you ask a session to hand an existing issue to Pendulum, the filing skill checks the issue and its readiness first. The worker handles code discovery and implementation after dispatch. To start a draft, take `pendulum:draft` off and apply `pendulum:objective`, or ask "Start Pendulum Objective #12". On your yes, the filing skill does both after the trust check. The issue's author, last editor and latest title renamer must be able to push or be maintainers the workflow names. Starting a draft counts as re-applying the label. The next plan uses edits made while it was a draft. Once that plan exists, the edit rules below apply. +- **Start.** Remove `pendulum:draft` while keeping `pendulum:objective` on the issue. The dispatcher starts eligible work when there is capacity. It checks on the Draft removal event or the ten-minute cron on Actions, and on `pendulum serve`'s next tick locally. "Start Pendulum Objective #12" uses the filing skill, which checks the issue and its readiness first and removes Draft on your yes. The worker handles code discovery and implementation after dispatch. The issue's author, last editor and latest title renamer must be able to push or be maintainers the workflow names. For an old draft that lacks `pendulum:objective`, add that identity while Draft is still on, then remove Draft. -- **Edit.** Edit the issue freely until the first work stage reads it. After its plan, an edit that only fixes typos, formatting or wording keeps the plan; any other edit Blocks the Objective at its next stage, and re-applying `pendulum:objective` plans again from the new text (Edit an Objective, below). +- **Edit.** Edit the issue freely until the first work stage reads it. After its plan, an edit that only fixes typos, formatting or wording keeps the plan. Any other edit Blocks the Objective at its next stage. Resume through Draft to plan from the new text. [Edit an Objective](#edit-an-objective) -- **Restart.** Apply `pendulum:restart` to start over from the issue's current text, in any state: Queued, Running, In review, Blocked or a Question ("Restart Pendulum Objective #12", the pendulum-restart skill, applies it on your yes). Only someone who can push, or a maintainer the workflow names, restarts an Objective: anyone else's label is taken off with a comment (a running stage may already have stopped on seeing it; re-applying `pendulum:objective` resumes the Objective). A running stage stops first, as for a stop, its spend so far recorded, and nothing merges or starts meanwhile. Then the dispatcher writes a restart record on the issue (when the label was applied, who applied it, and what the restart discards: the earlier PR with its review, and the deleted branch's commits, whose last one `git push origin <sha>:refs/heads/pendulum/<issue>` restores), deletes the `pendulum/<issue>` branch, closes the earlier PR with a comment linking the record (its commits and review stay readable on it), sets the earlier plan and a split's part record aside, removes the state labels and the restart label, and queues the Objective; it starts from the default branch, and comments made before the label was applied do not feed it. When a ruleset keeps GitHub from deleting the branch, the Objective is Blocked with the fix instead: nothing is discarded, and its earlier PR, plan and comments stay as they were. The retry and rebase counts start over, and the scorecard counts the restart as a human action. On a stopped Objective the restart waits until `pendulum:objective` is back. A workflow file rendered before this release sees a restart only on the ten-minute cron until it is re-rendered ([INSTALL.md](INSTALL.md), Upgrade). To go on after a fix or an answer instead, re-apply `pendulum:objective`: that continues from the branch and PR. +- **Restart.** Apply `pendulum:restart` to start over from the issue's current text, in any state: Queued, Running, In review, Blocked or a Question ("Restart Pendulum Objective #12", the pendulum-restart skill, applies it on your yes). Only someone who can push, or a maintainer the workflow names, restarts an Objective: anyone else's label is taken off with a comment (a running stage may already have stopped on seeing it, in which case you can resume through Draft). A running stage stops first, as for a stop, its spend so far recorded, and nothing merges or starts meanwhile. Then the dispatcher writes a restart record on the issue (when the label was applied, who applied it, and what the restart discards: the earlier PR with its review, and the deleted branch's commits, whose last one `git push origin <sha>:refs/heads/pendulum/<issue>` restores), deletes the `pendulum/<issue>` branch, closes the earlier PR with a comment linking the record (its commits and review stay readable on it), sets the earlier plan and a split's part record aside, removes the state labels and the restart label, and queues the Objective; it starts from the default branch, and comments made before the label was applied do not feed it. When a ruleset keeps GitHub from deleting the branch, the Objective is Blocked with the fix instead: nothing is discarded, and its earlier PR, plan and comments stay as they were. The retry and rebase counts start over, and the scorecard counts the restart as a human action. On a held Objective the restart waits for Draft to be removed. A workflow file rendered before this release sees a restart only on the ten-minute cron until it is re-rendered ([INSTALL.md](INSTALL.md), Upgrade). To continue from the branch and PR after a fix or answer, use Resume below. -- **Stop.** Remove the `pendulum:objective` label, or close the issue ("Stop Pendulum Objective #12", the pendulum-stop skill, removes the label on your yes). No dispatcher tick, local loop or sandbox launch picks up a stopped Objective, and your other Objectives keep running. What happens depends on its state: - - **Running, or a review running:** the stage reads its issue once a minute. On the stop it ends its harness run, records the spend so far in its usage record (locally and in a cloud sandbox also in its progress comment's spend line, as every stage does) and exits, normally within two minutes; its progress comment's last line reads `exit: stopped`. Its PR, if it has one, becomes a draft without the `pendulum:review` label; its state label comes off and its card goes back to Queued. With the cloud sandbox the launcher then stops the sandbox. A Running Objective whose stage died before it saw the stop is tidied the same way by the dispatcher, ten minutes after the label came off. - - **In review with no stage running:** on its next tick the dispatcher takes the PR out of the merge queue, makes it a draft without the `pendulum:review` label, removes the state label and moves the card to Queued, so neither a review nor the merge queue takes it. On Actions the label's removal ticks it (a workflow file rendered before this release waits for the ten-minute cron until it is re-rendered: [INSTALL.md](INSTALL.md), Upgrade); locally `pendulum serve` ticks every 30 seconds. - - **Queued, Blocked or a Question:** it stays as it is. +- **Stop.** Add `pendulum:draft`, or close the issue. "Stop Pendulum Objective #12" uses the pendulum-stop skill to add Draft on your yes. No dispatcher tick, local loop or sandbox launch picks up a stopped Objective. Your other Objectives keep running. The current state determines how the stop settles. + - **Running, or a review running:** the stage reads its issue once a minute. On the stop it ends its harness run, records the spend so far in its usage record (locally and in a cloud sandbox also in its progress comment's spend line, as every stage does) and exits, normally within two minutes. Its progress comment's last line reads `exit: stopped`. Its PR, if it has one, becomes a draft without the `pendulum:review` label. Its state label comes off and its card goes back to Queued. With the cloud sandbox the launcher then stops the sandbox. The dispatcher tidies a Running Objective whose stage died before it saw the stop ten minutes after Draft was applied. + - **In review with no stage running:** on its next tick the dispatcher takes the PR out of the merge queue, makes it a draft without the `pendulum:review` label, removes the state label and moves the card to Queued. Draft changes tick Actions. Workflow files from before lifecycle events were added rely on the cron until re-rendered. Locally `pendulum serve` ticks every 30 seconds. [Upgrade](INSTALL.md#upgrade) + - **Queued, Blocked or a Question:** Draft holds the issue immediately. A stage that was already ending still needs time to finish. - Applying `pendulum:draft` to an Objective stops it the same way, whatever its state, and keeps it a draft until it is started again. +- **Resume.** Resolve the cause and confirm the previous stage has stopped. If you held a running Objective, check its progress comment and confirm any PR has left the merge queue. Add `pendulum:draft` if it is absent, then remove it. The dispatcher can continue from the existing branch and PR. Keep `pendulum:objective` in place throughout. - Re-apply the label to start it again: it continues from its branch and PR, as after a Block. Closing the issue stops it the same way and then counts as done: the dispatcher's Done pass removes its state label, moves its card to Done and makes a PR it left open a draft, and with the cloud sandbox the sweep destroys its sandbox. + Closing the issue stops it and counts as done. The dispatcher's Done pass removes its state label, moves its card to Done and makes a PR it left open a draft. With the cloud sandbox the sweep destroys its sandbox. Older Objective-label stop and start events continue to work for compatibility. ## Edit an Objective @@ -133,11 +135,11 @@ Edit the issue as much as you like until the worker reads it: the first work sta - The stage running when you edit finishes on the text it read. The next one (the review, the merge, or a work stage Pendulum starts on its own, such as a rebase) first asks the decision model whether an edit to the title or body changes what has to be built, once per new text. A typo, formatting or wording-only edit keeps the plan and the code, the run goes on, and the stage's progress comment says so (`edit judged wording-only by <decider> (<confidence>); plan kept`). A harness, model or host label added, removed or changed always counts as a changed requirement. Any other edit, or one the model cannot judge (no decider: `decision_route` off, or `gateway` with no key), stops the Objective as Blocked, saying the Objective changed after its plan was made, and the PR, if there is one, becomes a draft. A PR already in the merge queue is taken out of it. Nothing goes on with a plan made from one text and an issue that says another. - Saving the issue without changing it is no edit: line endings and trailing spaces do not count. That needs the record of its text Pendulum keeps on the plan comment: a plan comment without one (an older plan) gets it at the next work stage, and until then any save after the plan counts as an edit. -- Re-apply `pendulum:objective` to work from the new text: the work stage that starts after it makes its plan again from the text as it then is, on the same branch and PR. That holds after a kept edit too: re-applying the label is your word that the plan should be made again. An edit made while the Objective is Blocked or has a Question is used the same way once you re-apply the label. Only the label counts: starting the Objective by hand (`gh workflow run pendulum.yml -f issue=<number>`, or `pendulum run <number>` in local mode) after such an edit Blocks it again. To start over from the new text instead, with the earlier PR closed and a new branch from the default one, apply `pendulum:restart` (An Objective's lifecycle, above). +- Resume through Draft to work from the new text on the same branch and PR. The work stage plans again from the text as it stands, even after a wording-only edit that Pendulum kept. This also applies to edits made while the Objective is Blocked or has a Question. A manual run (`gh workflow run pendulum.yml -f issue=<number>` or `pendulum run <number>`) after a substantive edit Blocks again until a trusted Draft removal records the new start. To start over from the new text instead, with the earlier PR closed and a new branch from the default one, apply `pendulum:restart` (An Objective's lifecycle, above). - Comments are not edits. A comment that answers a Question, or records a decision, leaves the plan as it is. - A comment by someone who can push that no pass has read holds a reviewed PR's merge: the review stage applies it first. A review that requests changes always holds it. Otherwise, when the decision model reads the unread comments as asking for nothing (an approval, thanks, an acknowledgement), and none arrived or changed while it read them, the PR merges, and the merge's progress comment says so (`comment check: ... read as asking nothing by <decider> (<confidence>)`). With no decider, every such comment holds the merge. - An edit is checked like the text you first wrote: when its editor cannot push and is not a maintainer the workflow names, the run Blocks (above), before any edit check. -- So is a rename: when whoever last renamed the title cannot push and is not a maintainer the workflow names, the next work or review stage Blocks on the trust check, before or after the plan, with this fix; a merge pass that comes first never judges such a rename and Blocks it as a change after the plan. A person who can push fixes it by changing the title (saving the same title records no rename), then re-applies `pendulum:objective`. +- So is a rename: when whoever last renamed the title cannot push and is not a maintainer the workflow names, the next work or review stage Blocks on the trust check, before or after the plan, with this fix; a merge pass that comes first never judges such a rename and Blocks it as a change after the plan. A person who can push fixes it by changing the title (saving the same title records no rename), then resumes through Draft. - A harness, model or host label change is never judged wording only: it counts as an edit, as above. ## Blocked and Question @@ -149,10 +151,10 @@ A run that goes well needs nothing from you. When one needs you, Pendulum does a What to do with each ("Why is Pendulum Objective 12 Blocked?", the pendulum-status skill, reads the notice and offers the step on your yes): -- **Blocked:** fix what the comment names, then re-apply `pendulum:objective` to run the Objective again: that resumes from its branch and PR. When your fix was an edit to the issue, the worker makes its plan again from the new text. Apply `pendulum:restart` only when the work itself must be redone: it discards the PR, its review, the branch's commits and the spend on them. The comment says which fits: resume whenever the stop was outside the work. When the red was CI's, its quoted output leads with the required checks that are red, by name; failing jobs no required check counts are marked `not required`. -- **Red checks a fix pass could not change:** when a fix pass commits nothing and the required checks stay red for a reason in the code, Pendulum first gives the Objective one fresh worker pass: a new session handed the failing output, once per head in a stage, and only when what is left of `max_usd` covers what the fix pass cost and the stage has time for another pass and its checks. A Block that names both passes means a fresh session could not fix it either. One that says `no fresh worker pass` or that the fresh pass reached a cap gives the reason. Read the failing job on GitHub, fix the cause on the branch, then re-apply the label. -- **Lost to the network:** on GitHub Actions and the cloud sandbox, a stage whose runner or sandbox lost its network (its outage notice, which mentions no one, names the host) or vanished without a word is relaunched on its own, at most twice since you last started the Objective, its work resuming from its branch and PR; a Pendulum comment on the issue counts them. A relaunch waits while today's spend has reached `daily_usd` or `max_concurrent` Objectives run, and each stage spends within `max_usd`, so a start can spend up to three times `max_usd` before you hear of it. Only then is it Blocked, the notice saying how many relaunches were tried; re-apply the label once the network is back, and the count starts over. A stage cancelled on Actions (by a person or its timeout), or a sandbox stage that recorded its end, is not a network loss: it is Blocked, not relaunched. A work job that failed at a step before Pendulum's own (a checkout, GitHub's job set-up) or that GitHub never started is relaunched once; when the relaunch fails at the same step, it Blocks with the cause `setup`, naming the step. The local route pauses and resumes such a stage instead ([LOCAL.md](LOCAL.md)). -- **Question:** comment the decision on the issue or the PR (a review or a line comment works too) and mark the PR ready: the review job applies it, and with no answer since the question the PR goes back to a Question rather than merging. A Question asked on the issue (one with no PR, or the plan-time Question; its notice says to answer on the issue) needs only the comment on the issue: on every route the Objective goes back to the queue at the dispatcher's next tick (local mode: `serve`'s), and the worker runs again with the answer. A decision model reads whether your comments since the Question decide it (the answer check, PLAN.md): one that does not, such as "I'll look tomorrow", leaves the Question open, and Pendulum says so once on the issue; edit the comment or write another to answer. With no decision model (`decision_route` off, or `gateway` with no key), any comment resumes it. Re-applying `pendulum:objective` instead reruns the worker with it, unjudged, and wins over a ready mark beside it: the mark starts no review (on the Action, its review job ends at once). A review that was already under way when the label came runs to its end first, and the worker never starts beside it; re-apply the label after it if the worker should still run. +- **Blocked:** fix what the comment names, then resume through Draft to continue from the existing branch and PR. When your fix was an edit to the issue, the worker makes its plan again from the new text. Apply `pendulum:restart` only when the work itself must be redone: it discards the PR, its review, the branch's commits and the spend on them. The comment says which fits: resume whenever the stop was outside the work. When the red was CI's, its quoted output leads with the required checks that are red, by name; failing jobs no required check counts are marked `not required`. +- **Red checks a fix pass could not change:** when a fix pass commits nothing and the required checks stay red for a reason in the code, Pendulum first gives the Objective one fresh worker pass: a new session handed the failing output, once per head in a stage, and only when what is left of `max_usd` covers what the fix pass cost and the stage has time for another pass and its checks. A Block that names both passes means a fresh session could not fix it either. One that says `no fresh worker pass` or that the fresh pass reached a cap gives the reason. Read the failing job on GitHub, fix the cause on the branch, then resume through Draft. +- **Lost to the network:** on GitHub Actions and the cloud sandbox, a stage whose runner or sandbox lost its network (its outage notice, which mentions no one, names the host) or vanished without a word is relaunched on its own, at most twice since you last started the Objective, its work resuming from its branch and PR; a Pendulum comment on the issue counts them. A relaunch waits while today's spend has reached `daily_usd` or `max_concurrent` Objectives run, and each stage spends within `max_usd`, so a start can spend up to three times `max_usd` before you hear of it. Only then is it Blocked, the notice saying how many relaunches were tried; resume through Draft once the network is back, and the count starts over. A stage cancelled on Actions (by a person or its timeout), or a sandbox stage that recorded its end, is not a network loss: it is Blocked, not relaunched. A work job that failed at a step before Pendulum's own (a checkout, GitHub's job set-up) or that GitHub never started is relaunched once; when the relaunch fails at the same step, it Blocks with the cause `setup`, naming the step. The local route pauses and resumes such a stage instead ([LOCAL.md](LOCAL.md)). +- **Question:** comment the decision on the issue or the PR (a review or a line comment works too) and mark the PR ready: the review job applies it, and with no answer since the question the PR goes back to a Question rather than merging. A Question asked on the issue (one with no PR, or the plan-time Question; its notice says to answer on the issue) needs only the comment on the issue: on every route the Objective goes back to the queue at the dispatcher's next tick (local mode: `serve`'s), and the worker runs again with the answer. A decision model reads whether your comments since the Question decide it (the answer check, PLAN.md): one that does not, such as "I'll look tomorrow", leaves the Question open, and Pendulum says so once on the issue; edit the comment or write another to answer. With no decision model (`decision_route` off, or `gateway` with no key), any comment resumes it. A trusted Draft removal reruns the worker with the answer unjudged and takes precedence over marking the PR ready. If a review is already running, keep Draft in place until the previous stage has stopped before resuming. A comment counts when its author has write access to the repository or is a maintainer the workflow names (`notify`, and the optional `maintainers` list), since an App cannot always see an organization member's access. @@ -174,13 +176,13 @@ One card per Objective, written in place as the run ends again: every Block or Q Every figure comes from a record, never an estimate. The card trusts Pendulum's markers only on Pendulum's own comments: its login on this route, or its App matched by id (the Action's `app_id`, or a local loop's `PENDULUM_LOCAL_APP_ID`); no other App or bot, `github-actions[bot]` included. A stage comment written by someone else who can push, or through a GitHub App other than GitHub Actions (another route's login or App, after an Objective moved between routes, including the Action's App when a local loop has no `PENDULUM_LOCAL_APP_ID` to match it by), counts as a run of unknown cost: its stage shows, never its dollars, and the total says "+ unknown". Their plan, review, notice and finish markers count for nothing, and anyone else's count for nothing at all. When the card finds no stage at all, its cost shows as unknown, never $0: -- **Times:** the clock starts at the `pendulum:objective` label (as the scorecard's does) and stops at the merge, or at the Block, the Question or the close. Each stage's bar runs from its progress comment's first write to its last; each merge queue entry from its addition to its removal or the merge; time on hold from Pendulum's Blocked or Question notice to the next stage's start (a notice no stage follows yet holds nothing). A stage that ended paused on a usage limit or an outage (its spend line records it: `limitPaused`, `outagePaused`; else its usage artifact's `usageLimit` or `outage`) is on hold from its last write to the next stage's start, whichever account or reset let it go on; the pause notice's words are never read. An issue that blocked this one before its first stage is a wait from the blocked-by relation's `blocked_by_added` event on the issue's timeline, or from the label when the relation was already there, to the blocking issue's close (one read of that issue at the card's write) or the relation's `blocked_by_removed` event, whichever came first, and only when that came by the first stage's start: a `Blocked by #N` line in the issue's body has no recorded time, and a blocker Pendulum cannot read, or one closed again after the first stage began, shows no wait. No time is in two waits: one that begins inside an earlier one (a Block while another issue still blocked the Objective) starts at that one's end, so each cause's time adds up to the waiting total. A blocking issue is read in the repository its event names, and only for a relation added before the first stage. Waiting is the time those waits cover, and working is the rest of the time from the label to the end: a gap with no such record (a stage that never started because its account was already held, a loop that was not running) is never called a wait. Times are in the Objective's zone (INSTALL.md, Time zone), whose short name the timeline's heading and the run log carry, with dates when the run crosses midnight; the summary line keeps them in UTC. The timeline's bars use the zone's offset at the Objective's start throughout, so across a daylight-saving change the later bars' clock reads an hour off while every bar keeps its true length. +- **Times:** the clock starts at the first activation within the run, usually the removal of `pendulum:draft`. Older runs can start at application of `pendulum:objective`. The clock stops at the merge, Block, Question or close. Each stage's bar runs from its progress comment's first write to its last; each merge queue entry from its addition to its removal or the merge; time on hold from Pendulum's Blocked or Question notice to the next stage's start (a notice no stage follows yet holds nothing). A stage that ended paused on a usage limit or an outage (its spend line records it: `limitPaused`, `outagePaused`; else its usage artifact's `usageLimit` or `outage`) is on hold from its last write to the next stage's start, whichever account or reset let it go on; the pause notice's words are never read. An issue that blocked this one before its first stage is a wait from the blocked-by relation's `blocked_by_added` event on the issue's timeline, or from activation when the relation was already there, to the blocking issue's close (one read of that issue at the card's write) or the relation's `blocked_by_removed` event, whichever came first, and only when that came by the first stage's start: a `Blocked by #N` line in the issue's body has no recorded time, and a blocker Pendulum cannot read, or one closed again after the first stage began, shows no wait. No time is in two waits: one that begins inside an earlier one (a Block while another issue still blocked the Objective) starts at that one's end, so each cause's time adds up to the waiting total. A blocking issue is read in the repository its event names, and only for a relation added before the first stage. Waiting is the time those waits cover, and working is the rest of the time from activation to the end. A gap with no such record (a stage that never started because its account was already held, a loop that was not running) is never called a wait. Times are in the Objective's zone (INSTALL.md, Time zone), whose short name the timeline's heading and the run log carry, with dates when the run crosses midnight; the summary line keeps them in UTC. The timeline's bars use the zone's offset at the Objective's start throughout, so across a daylight-saving change the later bars' clock reads an hour off while every bar keeps its true length. - **Stages:** named from their records only: the Objective's first work stage is its build ("Plan + build" with a plan comment), the first after a split part merged is that part ("Part 2"), one with a rebase line is a rebase, any other work stage is "Work", and a review stage is a review; a name that repeats is numbered ("Review 2"). A stage ended Blocked or on a Question when Pendulum's notice of it falls within its span. Past 20 stage rows, like stages in a row (kind, model, result) fold into one ("Review ×3"), each stage listed in Run details; past 20 timeline rows the chart is left out. Over GitHub's 65,536 characters the card leaves out its run log, then that list, then the cost chart. - **Dollars:** each stage's own figure: the spend line in its progress comment, which every stage writes on every route, else its usage artifact (`pendulum-usage-<issue>` and `-review`, read with the job token's `actions: read` for a stage with no spend line, and for the model alone of a stage whose harness line names none (Copilot at its default model) and that has no per-pass ledger line beside its spend line to name it ([REPORT.md](REPORT.md), The per-pass ledger), and only that stage's own workflow run's, matched by the run id its progress comment names; a run on another repository's code, a fork's pull request, is never read). A stage with neither (an artifact that cannot be downloaded included), or one whose harness did not report its cost, shows as unknown, and the totals say "+ unknown"; a stage that ran no harness pass is $0. A cloud sandbox's own cost is a row of its own, its vendor comment counted whenever it was written; a sandbox whose usage the vendor did not report is a run of unknown cost, its dollars or none; a vendor comment someone else wrote of one of the Objective's stages is that stage's, and one of no stage is a run of unknown cost; a sandbox stage that wrote no progress comment is a row too. The rows' cents add up to the total's, so a row can be a cent off its stage's own figure, which its progress comment and the run log show: the notes line under the money says so once on a card where one is. A row under a cent reads "<$0.01", never $0.00. Your CI minutes are not included. What the dollars are comes from the usage records' and spend lines' dollars by billing (`usdByBilling`), said once on the headline's second line; a mix gives each kind's share. Dollars whose billing was not recorded (the `unknown` kind, or a record or sandbox cost that names none) read "billing not recorded", never as API-equivalent. - **Where the money went:** shown for a split Objective, for any overhead, or when a stage ran answer or fix passes. A bar chart of the recorded dollars (one amber series, each bar's figure in its label; a row with only unknown cost gets no bar, and the notes line names what is not drawn) above two tables, their rows' cents adding up to the total's. Every item comes from a stage's own record, never from what the card works out: - *What the issue asked for*, per split part ("Part 2: review"; a stage is in the part after the PRs merged before it started) and per kind: work, review, answering the review, fixing CI, AI judge calls. A stage's dollars by pass kind come from its spend line or usage artifact (`usdByPass`, each pass named by its label: `work-<n>`, the reviewer's passes, `answer`, a validation loop's fix passes; its decision calls under `decision`); the rest of the stage (its exit record) stays under the stage's own kind. A stage whose kinds do not fit inside its own figure, or whose figure is unknown, stays whole. The cloud sandbox's own cost is a row of its own. - *Overhead Pendulum caused*, with how many stages each came from: a send-back's rebase after other PRs merged, the whole stage (its rebase line; conflict or clean, by the line's `conflict`); a work stage's catch-up pass after the default branch changed a workflow during the run (its `conflict` passes); the runs a stage records it ran again after a Block (its `rerun`: the first stage after one of Pendulum's Blocked notices records the notice and, for a work stage that ran its prompt in a fresh session over the PR an earlier stage made, that prompt; a review runs its reviewer once per PR, so it names none); and a review stage that records it was started only to judge answers already made (its `judgeOnly`, from the answer-rounds record of its own PR since the last re-entry), all of it but its answer and fix passes. A Blocked notice or an answer-rounds record on the issue names nothing by itself; anything else stays in its stage, as that stage, never as overhead. -- **People:** "You wrote the issue and added the label" when the issue's author applied the label that started the clock; otherwise each is named. +- **People:** the card says who wrote and who started the Objective, using the label event that started the clock. - **The change:** commits, lines added and removed and files changed, from the merged PR (every merged part of a split Objective, added up); said as what Pendulum opened when Pendulum's login opened the PRs, else as what the PRs have. - **CI checks:** the check runs on the commit that gated the merge (the merge queue's merge commit, or without a queue the PR's head): for each app and name, the latest attempt completed by the merge; when the default branch requires checks, those alone. For a split Objective, the last part's. - **Review:** Pendulum's reviews of the PR and their findings: its line comments that open a thread and the findings set out in a review body; its "no findings" placeholder counts none. @@ -205,7 +207,7 @@ Putting `pendulum:review` on a waiting PR yourself starts its review now, and so ## One repository per Objective -Pendulum works in one repository per Objective. An Objective that needs a change in another repository stops with a Question on the issue before any code is written (after its plan, or before the worker starts when the issue names another repository on a `Pendulum-Repository:` line): split it into one Objective per repository and re-apply the label. When the Question came from the plan, you can instead answer in a comment on the issue how to do the work in this repository alone: the next tick runs it again with that answer. +Pendulum works in one repository per Objective. An Objective that needs a change in another repository stops with a Question on the issue before any code is written (after its plan, or before the worker starts when the issue names another repository on a `Pendulum-Repository:` line): split it into one Objective per repository and resume through Draft. When the Question came from the plan, you can instead answer in a comment on the issue how to do the work in this repository alone: the next tick runs it again with that answer. ## Workflow changes @@ -220,21 +222,21 @@ To have Pendulum build on a workflow change instead, land that change yourself f ## Commands -Pendulum is a plugin of [Agent Skills](https://agentskills.io): one folder per skill under [`plugin/skills/`](../plugin/skills/), each a `SKILL.md` that Claude Code, Codex and GitHub Copilot CLI load the same way. With the plugin installed, ask in plain words: each request below loads the Pendulum skill that does it. If your agent takes "Pendulum" for something else of that name, such as the Python date-time library, use the command instead. In Claude Code each skill is also a slash command, `/pendulum:<skill>`; Codex and Copilot list them among their own skills. Each command below links to its skill. +Pendulum is a plugin of [Agent Skills](https://agentskills.io): one folder per skill under [`plugin/skills/`](../plugin/skills/), each a `SKILL.md` that Claude Code, Codex and GitHub Copilot CLI load the same way. With the plugin installed, use the requests below to select a Pendulum skill. Use the command if your session picks the wrong workflow. In Claude Code each skill is also a slash command, `/pendulum:<skill>`; Codex and Copilot list them among their own skills. Each command below links to its skill. | Say | Command | What it does | | --- | --- | --- | | "Set up Pendulum for this repository." | [`/pendulum:pendulum-setup`](../plugin/skills/pendulum-setup/SKILL.md) | Installs Pendulum one consented step at a time, and opens the pull request that adds the workflow file | | "Is Pendulum set up correctly here?" | [`/pendulum:pendulum-doctor`](../plugin/skills/pendulum-doctor/SKILL.md) | Checks the repository, its settings, the credential and the runner; changes nothing | -| "File a Pendulum Objective: ..." | [`/pendulum:pendulum-file`](../plugin/skills/pendulum-file/SKILL.md) | Writes what you describe as an Objective issue, shows it, and on your yes creates it started (`pendulum:objective`) or as a draft (`pendulum:draft`) | +| "File a Pendulum Objective: ..." | [`/pendulum:pendulum-file`](../plugin/skills/pendulum-file/SKILL.md) | Writes what you describe as an Objective issue, shows it, and on your yes files it with both labels and either keeps or removes `pendulum:draft` | | "Let's keep working on Pendulum Objective 12." | `/pendulum:pendulum-file <issue>` | Loads the draft from GitHub to refine it with you, and saves the changes back on your yes | -| "Start Pendulum Objective 12." | `/pendulum:pendulum-file <issue>` | Starts a draft on your yes, after the trust check: takes `pendulum:draft` off and applies `pendulum:objective` | +| "Start Pendulum Objective 12." | `/pendulum:pendulum-file <issue>` | Removes `pendulum:draft` on your yes after the trust check, keeping `pendulum:objective` in place | | "What is Pendulum doing here?", "Why is Pendulum Objective 12 Blocked?" | [`/pendulum:pendulum-status`](../plugin/skills/pendulum-status/SKILL.md) `[issue]` | Shows each Objective's state; for a Blocked one or a Question, the reason and the way on (resume, answer or restart), taken on your yes (Blocked and Question, above) | -| "Stop Pendulum Objective 12." | [`/pendulum:pendulum-stop`](../plugin/skills/pendulum-stop/SKILL.md) `<issue>` | Removes the Objective's label on your yes: its running stage ends and nothing picks it up again (An Objective's lifecycle, above) | +| "Stop Pendulum Objective 12." | [`/pendulum:pendulum-stop`](../plugin/skills/pendulum-stop/SKILL.md) `<issue>` | Adds `pendulum:draft` on your yes. The stage stops and the issue stays held until Draft is removed. (An Objective's lifecycle, above) | | "Restart Pendulum Objective 12." | [`/pendulum:pendulum-restart`](../plugin/skills/pendulum-restart/SKILL.md) `<issue>` | Applies `pendulum:restart` on your yes: the Objective starts over from the issue's current text (An Objective's lifecycle, above) | | "Run Pendulum Objective 42 here." | [`/pendulum:pendulum-run`](../plugin/skills/pendulum-run/SKILL.md) `<issue>` | Runs one Objective on this machine, in local mode or in the session itself | | "Review Pendulum PR 57." | [`/pendulum:pendulum-review-here`](../plugin/skills/pendulum-review-here/SKILL.md) `<pr>` | Runs the reviewer on one Pendulum PR in your session | -| "Start the Pendulum local loop." | [`/pendulum:pendulum-serve`](../plugin/skills/pendulum-serve/SKILL.md) | Starts the local loop ([LOCAL.md](LOCAL.md)) | +| "Start the Pendulum local loop." | [`/pendulum:pendulum-serve`](../plugin/skills/pendulum-serve/SKILL.md) | Starts or supervises the local loop and follows recorded work ([LOCAL.md](LOCAL.md)) | | "Kick the Pendulum dispatcher." | [`/pendulum:pendulum-kick`](../plugin/skills/pendulum-kick/SKILL.md) `[issue]` | Runs the Action's dispatcher now, which starts the Objectives that are ready, or one Objective | | "Apply the Pendulum workflow hand-over for Objective 12." | [`/pendulum:pendulum-handover`](../plugin/skills/pendulum-handover/SKILL.md) `<issue>` | Puts the workflow change Pendulum handed over on a new branch and shows it; pushes it and opens its PR only after you read it and say yes | | "Show the Pendulum scorecard." | [`/pendulum:pendulum-score`](../plugin/skills/pendulum-score/SKILL.md) | Prints the scorecard: whether each Objective merged with no one stepping in, quality, operator minutes, cost | diff --git a/plugin/skills/pendulum-file/SKILL.md b/plugin/skills/pendulum-file/SKILL.md index 6cd6e2c7..753b6513 100644 --- a/plugin/skills/pendulum-file/SKILL.md +++ b/plugin/skills/pendulum-file/SKILL.md @@ -1,6 +1,6 @@ --- name: pendulum-file -description: "Read issue readiness before source discovery, then draft, refine or admit an Objective on the user's yes. Use when the user wants Pendulum to build something or take an existing GitHub issue, even without naming a skill. Not for executing an admitted Objective or resuming a run." +description: "Read issue readiness before source discovery. File, refine or start a Pendulum Objective on the user's yes. Use when asked to hand new work or an existing issue to Pendulum, even in plain language. Not for executing an Objective or resuming a Blocked run." --- # /pendulum:pendulum-file [issue] @@ -27,21 +27,19 @@ Ask only for what the issue cannot be written without. Where the user left a cho ## Create it -Show the title, body and labels. Offer: +Show the title, body and labels. On a yes to save as a draft or start, prefix the body with `pendulum zone` and a blank line. Create the issue with both labels: -- **Start it now:** write the line `pendulum zone` prints (this machine's zone, for the Objective's times), a blank line and the body to a temporary file, and run `gh issue create --repo OWNER/NAME --title "<title>" --body-file <file> --label pendulum:objective`. Add `--label pendulum:local` for the user's own machine's loop, and `P0`, `P1` or `P2` for a priority. One that must follow another Objective gets the label only after its dependency (reference.md, Blocking Objectives). -- **Save it as a draft:** the same command with `--label pendulum:draft` in its place; Pendulum never runs a draft. A missing label: reference.md, The draft label. -- **Keep discussing:** nothing goes to GitHub; revise and show it again. +`gh issue create --repo OWNER/NAME --title "<title>" --body-file <file> --label pendulum:objective --label pendulum:draft` -Create any harness, model or host label first (`gh label create <label> --repo OWNER/NAME --force`), then add it: one added after the plan is an edit. +Add `pendulum:local` for the local loop if chosen, and any agreed priority, harness, model or host labels. Create missing labels first. Add dependencies while Draft is on ([reference.md](reference.md), Blocking Objectives). To start, follow Start a draft. To save a draft, leave both labels on. To keep discussing, revise without writing to GitHub. ## An existing issue (given its number) Run `gh issue view <issue> --repo OWNER/NAME --json number,title,body,state,labels` and show it. Closed: say so and stop. Do what the user asked: - **Refine it:** as Write the issue, keeping the text that still fits; save it back on a yes ([reference.md](reference.md), Refine a draft). A started one (`pendulum:objective`, no `pendulum:draft`) Blocks on an edit after its plan: say so first. -- **Start it:** admit a draft or unlabelled issue after the trust check ([reference.md](reference.md), Start a draft). Keep open dependencies in place. Follow admitted work through its dispatcher or existing run. Use pendulum-status for a Blocked one or a Question, and pendulum-restart only on request. +- **Start it:** remove Draft after the trust check ([reference.md](reference.md), Start a draft). Keep `pendulum:objective` and any dependencies. Follow work already in the queue through its dispatcher or existing run. Use pendulum-status for Blocked work or Questions, and pendulum-restart only on request. ## After -Print the issue's URL. Admission puts it in the queue. Report it as running once Pendulum records the start, and point to the run, progress comment or verified active claim. Use pendulum-status to follow it or pendulum-serve for the existing local queue. A draft comes back here to refine or start. +Print the issue's URL and state. Draft removal queues the Objective. Cite a run, current progress comment or verified active claim before reporting that work began. Use pendulum-status or pendulum-serve to follow it. diff --git a/plugin/skills/pendulum-file/reference.md b/plugin/skills/pendulum-file/reference.md index f2bc6a2a..7ba971fd 100644 --- a/plugin/skills/pendulum-file/reference.md +++ b/plugin/skills/pendulum-file/reference.md @@ -16,12 +16,12 @@ An Objective's sandboxes reach GitHub, the npm and Yarn registries and the hosts ## Blocking Objectives -When the work must follow another Objective `<N>`, make `<N>` block it as a GitHub issue dependency before applying `pendulum:objective`. The label admits it to the queue. The dispatcher reads the dependency, not the body (a `Blocked by #N` line counts only on a host without dependencies). In this order: +When the work must follow another Objective `<N>`, record the GitHub issue dependency while Draft is on. The dispatcher reads that dependency. A `Blocked by #N` line counts only on a host without dependencies. In this order: -1. Create the issue with the "Start it now" command less `--label pendulum:objective` (a draft keeps `--label pendulum:draft`). +1. Create the issue with both `pendulum:objective` and `pendulum:draft`. 2. Add the dependency: `gh api -X POST repos/OWNER/NAME/issues/<new>/dependencies/blocked_by -F issue_id=$(gh api repos/OWNER/NAME/issues/<N> --jq .id)`. 3. Check it: `gh api repos/OWNER/NAME/issues/<new>/dependencies/blocked_by --jq '.[].number'` prints `<N>`. If not, stop and say so. -4. Start it: `gh issue edit <new> --repo OWNER/NAME --add-label pendulum:objective`. A draft stays a draft until it is started (Start a draft). +4. To start it, follow Start a draft. Keep both labels while the user wants it held. The dispatcher then starts it only once `<N>` is closed. @@ -41,15 +41,15 @@ Refine it as SKILL.md writes an Objective: the title, `## Goal`, `## Acceptance` 1. Read the issue again. When its title or body changed on GitHub since you loaded it, show that change and ask which text to keep. 2. Check that `gh api repos/OWNER/NAME --jq .permissions.push` prints `true`: whoever saves the body becomes its last editor, and whoever changes the title its latest renamer, and Pendulum acts on an issue only when both can push. Otherwise say a maintainer has to save it. -3. Write the body to a temporary file, run `gh issue edit <issue> --repo OWNER/NAME --title "<title>" --body-file <file>`, and delete the file. +3. Write the body to a temporary file, run `gh issue edit <issue> --repo OWNER/NAME --title "<title>" --body-file <file>`, and delete the file. If an older managed draft lacks `pendulum:objective`, verify Draft is still on before restoring its Objective label. Leave Draft on when saving a draft. Then offer the next step: keep working on it, leave it as a draft, or start it (Start a draft). ## Start a draft -Starting a draft takes `pendulum:draft` off and applies `pendulum:objective`; the dispatcher then picks it up like a new Objective. A draft is never run, on any route, even with `pendulum:objective` on it too. Confirm first: a started Objective runs unattended and spends model budget. +`pendulum:objective` stays on the issue as its identity. Removing `pendulum:draft` queues it for the dispatcher. Confirm before releasing the hold because processing spends model budget. -**Check the issue.** `pendulum:objective` without `pendulum:draft` means already admitted. Keep the labels as they are, check dependencies and readiness, then follow the configured dispatcher or existing run. Use pendulum-status for a Blocked one or a Question, and pendulum-restart only for a requested restart. A draft or unlabelled issue without a goal or acceptance entries needs refinement first (SKILL.md). +**Check the issue.** An Objective without Draft is already released to its configured route. Check dependencies and follow its dispatcher or existing run. Use pendulum-status for a Blocked one or a Question. A draft or unlabelled issue without a goal or acceptance entries needs refinement first (SKILL.md). When Draft was applied to stop work, wait for the old stage to exit and the PR to leave the merge queue before removing it. Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/dependencies/blocked_by --jq '.[] | select(.state == "open") | .number'`. On a GitHub host without issue dependencies, use the body fallback described under Blocking Objectives. If the read fails, report that readiness is unknown. Report any open dependency as a queue condition and preserve the link. @@ -61,6 +61,6 @@ Read open dependencies with `gh api --paginate repos/OWNER/NAME/issues/<issue>/d When a check fails, or a login cannot be read, do not start it. Say who and why: an author who fails means a person who can push files it again as a new issue; a last editor who fails means a person who can push reads the body and saves it, becoming its last editor; a renamer who fails means a person who can push reads the title and changes it (the same title records no rename). -**Ask.** Show the number, title and labels, the people the trust check read, and what starting does. Applying the label admits the issue. The dispatcher checks it on the label event or cron on Actions, or on `pendulum serve`'s next tick locally. It still waits for any open dependency and for capacity. One comment on the issue shows the run's progress. An edit after its plan is made Blocks it at its next stage ([Edit an Objective](https://github.com/clockgrove/pendulum/blob/v0.10.0/docs/USAGE.md#edit-an-objective)). Ask for a yes. +**Ask.** Show the issue, labels, dependencies and people the trust check read. Explain that removing Draft queues the Objective for its configured dispatcher, subject to dependency and capacity checks. Confirm the start if the user has not already approved this exact issue and its start. -**Start it.** On a yes, when the issue carries `pendulum:objective` too, first run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:objective`, so the start applies the label afresh. Then run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:draft --add-label pendulum:objective`; for an issue without `pendulum:draft`, drop `--remove-label pendulum:draft`, since `gh` refuses to remove a label the repository does not have. Print its URL and report its observed state as described in SKILL.md. +**Start it.** For an unlabelled issue or legacy draft missing `pendulum:objective`, add `pendulum:draft` if absent and verify it before adding `pendulum:objective`. Verify both labels before starting. Apply any approved route or dependency updates while Draft is on. Run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:draft`. Print its URL and observed state as described in SKILL.md. diff --git a/plugin/skills/pendulum-restart/SKILL.md b/plugin/skills/pendulum-restart/SKILL.md index 8e73968b..6e1d51c3 100644 --- a/plugin/skills/pendulum-restart/SKILL.md +++ b/plugin/skills/pendulum-restart/SKILL.md @@ -9,9 +9,9 @@ Restarting an Objective is applying the `pendulum:restart` label to its issue, i ## Check the issue -Run `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels`. A closed issue is not restarted: say so and stop. Note its state from its labels (`pendulum:running`, `pendulum:in-review`, `pendulum:blocked`, `pendulum:question`, or none: Queued). When it carries no `pendulum:objective` label it is stopped: the restart waits until that label is back, so offer to apply both. A draft (`pendulum:draft`) is not restarted until it is started (the pendulum-file skill): say so. +Run `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels`. A closed issue cannot restart. Keep `pendulum:objective` on managed issues. If an older stopped Objective lacks it, use the filing skill's Draft-first steps to restore the identity while it is held. A restart requested while Draft is on waits for its removal. -When the user only wants it to go on after a fix or an answer, a restart is not needed: re-applying `pendulum:objective` continues from its branch and pull request. Say so if that is what they described. +For continuing after a fix or an answer, follow pendulum-status. Resuming via Draft keeps the existing branch and pull request. ## Ask @@ -25,6 +25,6 @@ Ask for a yes, saying the label is created first when the repository lacks it. P ## Restart it -On a yes, run `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:restart` (with `--add-label pendulum:objective` too for a stopped one). When GitHub says the label does not exist (setup's labels step makes it), create it with `gh label create pendulum:restart --repo OWNER/NAME --color 5319E7 --description "Restart this Objective from the issue's current text (any state)"`, then apply it. +On a yes, run `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:restart`. When GitHub says the label does not exist, create it with `gh label create pendulum:restart --repo OWNER/NAME --color 5319E7 --description "Restart this Objective from the issue's current text (any state)"`, then apply it. -Say it is restarting: the label comes off once the dispatcher has restarted it, and the issue's progress comment shows the new run. +Report the restart request. If Draft is on, it still holds the issue. Use pendulum-file to remove Draft when the user approves running it. The restart label comes off after the dispatcher restarts it. diff --git a/plugin/skills/pendulum-run/reference.md b/plugin/skills/pendulum-run/reference.md index 380200d7..ad47bd82 100644 --- a/plugin/skills/pendulum-run/reference.md +++ b/plugin/skills/pendulum-run/reference.md @@ -1,6 +1,6 @@ # In-session readiness -Check that the issue is open, carries `pendulum:objective`, and has neither `pendulum:draft` nor an [open dependency](../pendulum-file/reference.md#start-a-draft). Applying the Objective label admits it to the dispatcher. For a draft or unlabelled issue, report its state and use pendulum-file only if the user wants that dispatcher handoff. +Check that the issue is open, carries `pendulum:objective`, and has neither `pendulum:draft` nor an [open dependency](../pendulum-file/reference.md#start-a-draft). Removing Draft releases it to the dispatcher. For a draft or unlabelled issue, report its state and use pendulum-file only if the user wants that dispatcher handoff. Check issue state with pendulum-status and the configured route's dispatcher records. Follow an active or paused run. If the configured loop or Action can pick up the issue during this session, leave it to that dispatcher. An eligible issue with no recorded claim yet can still be picked up. In-session setup does not reserve the Objective. diff --git a/plugin/skills/pendulum-status/SKILL.md b/plugin/skills/pendulum-status/SKILL.md index 438144bb..13cfbb40 100644 --- a/plugin/skills/pendulum-status/SKILL.md +++ b/plugin/skills/pendulum-status/SKILL.md @@ -10,7 +10,7 @@ Read GitHub and report; change nothing. A way on is one of Pendulum's labels or ## Read the queue 1. `gh issue list --repo OWNER/NAME --state open --label pendulum:objective --json number,title,labels,createdAt --limit 100`, and the same with `--label pendulum:draft`, merged by number (a draft may carry both). Given an issue number, `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels` alone. -2. Each one's state from its labels ([reference.md](reference.md), States). A closed issue is done. `pendulum:draft` wins over every other label: a draft, never run. An open issue without `pendulum:objective` is stopped. `pendulum:restart` on it: a restart is under way. +2. Read state from its labels ([reference.md](reference.md), States). A closed issue is done. Draft holds processing. An issue without `pendulum:objective` is unadmitted or stopped under the older flow. `pendulum:restart` records a restart request. 3. Its route: `pendulum:local`, the local loop's; any other, the Action's (the local loop's where no Action is active). 4. For a Running one, the steps table in Pendulum's progress comment on the issue: its last row, marked **Now**, is the step in progress and for how long; with no **Now** row the stage is between steps, and the rows above say what has run. @@ -20,9 +20,9 @@ Show one line per Objective, oldest first: number, title, state, route, and for Read the issue's comments (`gh issue view <issue> --repo OWNER/NAME --comments`) and take Pendulum's latest Blocked notice: its first line is the marker `<!-- pendulum:<issue>:blocked:` and its text says `Blocked (<stage>):`. Relay its reason, its fix and its last paragraph, and offer only the way on that paragraph names; an older notice without one, its cause's ([reference.md](reference.md), Block causes; no cause line: `work`): -- **"Resume, don't restart"** (`resume`): the notice's fix first (a push to `pendulum/<issue>`, an issue edit, a secret, a setting; pendulum-doctor checks setup), then re-apply the label: `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:objective`, then `--add-label pendulum:objective`. It goes on from its branch and PR. Never offer a restart. -- **"Resume once the cause is fixed"** (`work`): the same resume. A restart (the pendulum-restart skill) only when the user says the work must be redone: it discards the PR, its review, the branch's commits and their spend. -- **"To keep the work instead of restarting"**: a restart could not finish. After its fix, the pendulum-restart skill applies it again; or re-apply the label to keep the work. +- **"Resume, don't restart"** (`resume`): apply the notice's fix, then [resume through Draft](reference.md#resume-through-draft). It goes on from its branch and PR. +- **"Resume once the cause is fixed"** (`work`): resume through Draft. Restart only when the user wants to redo the work. +- **"To keep the work instead of restarting"**: apply the fix, then retry the requested restart with pendulum-restart or resume through Draft to keep the work. - **"Neither a resume nor a restart gets past this"**: its author cannot push. Offer that someone who can push files it again (the pendulum-file skill). ## Question @@ -32,8 +32,8 @@ Read Pendulum's Question: its notice on the issue (first line `<!-- pendulum:<is - **On the issue** (no open PR, or the notice's marker ends `:issue`): the user's decision as a comment on the issue. Never mark the PR ready. - **On the PR** (otherwise): the decision as a comment on the issue or the PR, then the PR marked ready (`gh pr ready <pr> --repo OWNER/NAME`). -Write the answer with the user and post it (`gh issue comment` or `gh pr comment`) on their yes; a comment that decides nothing ("I'll look tomorrow") may leave it open. Re-applying `pendulum:objective` instead reruns the worker with it unjudged. +Post the user's approved answer with `gh issue comment` or `gh pr comment`. A comment without a decision may leave it open. A requested worker rerun uses Draft instead of sending the answer to the review job. ## Who can act -Pendulum takes a re-applied label, an answer or a restart only from someone who can push or a maintainer the workflow names: unless `gh api repos/OWNER/NAME --jq .permissions.push` prints `true`, say a maintainer has to. When `gh` fails, relay its message. +Pendulum takes a Draft removal, an answer or a restart only from someone who can push or a maintainer the workflow names. Check `gh api repos/OWNER/NAME --jq .permissions.push`. When `gh` fails, relay its message. diff --git a/plugin/skills/pendulum-status/reference.md b/plugin/skills/pendulum-status/reference.md index ae5b5ee5..3f099e16 100644 --- a/plugin/skills/pendulum-status/reference.md +++ b/plugin/skills/pendulum-status/reference.md @@ -4,9 +4,9 @@ Detail for the pendulum-status skill. SKILL.md says when to load each section; e ## States -Pendulum keeps each Objective's state in one label (and, on a repository an organization owns, the Project board's column beside it). Re-applying `pendulum:objective` is taking it off and putting it back; only someone who can push, or a maintainer the workflow names, makes it count. +Pendulum keeps each Objective's state in one label and, for an organization repository, its Project column. The `pendulum:objective` label identifies the issue. Draft holds it until a writer or named maintainer removes Draft. -| Label | State | What happens next | Re-applying `pendulum:objective` resumes it | +| Label | State | What happens next | Removing Draft queues a new work stage | | --- | --- | --- | --- | | none | Queued | The dispatcher starts it once a slot is free (`max_concurrent`), the day's spend is under `daily_usd` and every issue that blocks it is closed, `P0` first, then `P1`, `P2`, then by issue number. | no | | `pendulum:running` | Running | A stage works it; its progress comment says what it is doing. Taking the label off stops it. | no | @@ -14,11 +14,20 @@ Pendulum keeps each Objective's state in one label (and, on a repository an orga | `pendulum:blocked` | Blocked | Waits for a person: its Blocked notice names the reason, the fix and whether to resume or restart. | yes | | `pendulum:question` | Question | Waits for the decision it asks: answer it (Questions). | yes | -Beside these: `pendulum:draft` (a draft, never run, whatever else is on it), no `pendulum:objective` on an open issue (stopped), `pendulum:restart` (a restart under way: the label comes off once the dispatcher has restarted it) and `pendulum:handover` (a workflow change waits for a person: the pendulum-handover skill applies it). +Beside these: `pendulum:draft` (held until removed), no `pendulum:objective` on an open issue (unadmitted or stopped under the older label flow), `pendulum:restart` (request pending until the dispatcher restarts it) and `pendulum:handover` (the pendulum-handover skill applies the waiting workflow change). + +## Resume through Draft + +Use this after resolving the cause of a Block, or when the user wants the worker to take a Question again. Get the user's approval for the resume. Keep `pendulum:objective` on the issue. + +1. If Draft is absent, run `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:draft`. Verify Draft is on. If an old stage or queued merge is still active, follow pendulum-stop until it has settled. +2. Run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:draft`. Report the queue state. Cite current start evidence before reporting that it is running. + +For an older stopped issue missing the Objective label, use the filing skill's Draft-first steps to restore it safely. ## Block causes -A Blocked notice's last line records its cause as `<!-- pendulum:block {"cause":"<cause>"} -->`. The notice's own last paragraph says the way on; this table is what each cause gives when the notice is older or the user asks why. `resume`: the stop is outside the work, so once its cause is fixed or has passed, re-apply the label; a restart would discard the work and gain nothing. `work`: the work itself stopped, so resume once the cause is fixed, and restart only when the work must be redone from the issue's text. External causes are outside Pendulum and the work: the scorecard does not count them against it. +A Blocked notice's last line records its cause as `<!-- pendulum:block {"cause":"<cause>"} -->`. The notice's own last paragraph says the way on; this table is what each cause gives when the notice is older or the user asks why. `resume`: the stop is outside the work, so once its cause is fixed or has passed, resume through Draft. `work`: the work itself stopped, so resume once the cause is fixed, and restart only when the work must be redone from the issue's text. External causes are outside Pendulum and the work: the scorecard does not count them against it. | Cause | External | Way on | What stopped it | | --- | --- | --- | --- | @@ -42,4 +51,4 @@ Pendulum's Question notice on the issue starts with the marker `<!-- pendulum:<i | `issue` | on the issue: before any code (the plan-time Question), or with no open PR | A comment on the issue. The Objective goes back to the queue at the dispatcher's next tick, on every route. Marking the PR ready would start its review and merge the part done so far. | | `pr` | in the draft PR's body, as `QUESTION:` items | A comment on the issue or the PR (a review or a line comment works too), then the PR marked ready: the review job applies the answer, and with no answer since the Question the PR goes back to a Question rather than merging. | -A decision model reads whether the comments since the Question decide it; with none (`decision_route` off, or `gateway` with no key), any comment resumes it. Re-applying `pendulum:objective` instead reruns the worker with the answer unjudged, and wins over a ready mark beside it. +A decision model reads whether the comments since the Question decide it. With no model (`decision_route` off, or `gateway` with no key), any comment resumes it. Resuming through Draft instead reruns the worker with the answer unjudged and takes precedence over a ready mark beside it. diff --git a/plugin/skills/pendulum-stop/SKILL.md b/plugin/skills/pendulum-stop/SKILL.md index 893b03a7..14e65759 100644 --- a/plugin/skills/pendulum-stop/SKILL.md +++ b/plugin/skills/pendulum-stop/SKILL.md @@ -1,15 +1,15 @@ --- name: pendulum-stop -description: "Stop one Pendulum Objective on the user's yes: removes the issue's pendulum:objective label, which ends its running stage and keeps every tick and loop from picking it up; its branch and pull request stay. Use when the user asks to stop, halt or cancel one Pendulum Objective, or says one should not run. Not for starting one over from its issue's current text (pendulum-restart)." +description: "Stop one Pendulum Objective on the user's yes by applying pendulum:draft. Keep its Objective label, branch and pull request. Use when asked to stop, hold or halt an Objective. Not for starting over from its current text (pendulum-restart)." --- # /pendulum:pendulum-stop <issue> -Stopping an Objective is removing its `pendulum:objective` label. Nothing else needs doing, on any route (Actions, local mode, the cloud sandbox), and the other Objectives keep running. Confirm first: a running stage ends without finishing its work. +Apply `pendulum:draft` to stop the Objective on its current route. Keep `pendulum:objective` on the issue. Confirm first because a running stage ends without finishing its work. ## Check the issue -Run `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels`. When it is closed, carries no `pendulum:objective` label, or is a draft (`pendulum:draft`, which Pendulum never runs), it is stopped already: say so and stop. Otherwise note its state from its labels: `pendulum:running`, `pendulum:in-review`, `pendulum:blocked`, `pendulum:question`, or none (Queued). +Run `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels`. A closed issue or an issue without `pendulum:objective` cannot run. If Draft is already on, check whether its old stage is still stopping and report what you find. Otherwise note its state using pendulum-status. ## Ask @@ -17,13 +17,13 @@ Show the issue's number, title and state, and say what the stop does: - A running stage reads its issue once a minute: it ends its harness run, records the spend so far and exits, normally within two minutes. - Its pull request, if it has one, leaves the merge queue and becomes a draft without the `pendulum:review` label, so nothing merges it and no review starts. A Running or In-review Objective goes back to Queued on the board; a Blocked one or a Question stays as it is. -- Nothing picks it up again until the label is re-applied, which continues from its branch and pull request. To start over from the issue's current text instead, the pendulum-restart skill applies `pendulum:restart`. +- While Draft is on, nothing picks it up. Removing Draft after the stop settles queues it with its branch and pull request. Use pendulum-restart to start over from the issue's current text. - Closing the issue stops it too, and is the way to drop it for good. -Ask for a yes. Removing a label needs triage or write access to the repository; when `gh` reports no access, say a maintainer has to do it. Starting it again is not the same: Pendulum takes the re-applied label only from someone who can push or a maintainer its workflow names, so a triager's re-apply on a Blocked or Question Objective, or on a stopped one, is refused with a comment. +Ask for a yes. If GitHub refuses the label edit, relay the refusal. Pendulum takes a Draft removal that queues work only from someone who can push or a maintainer its workflow names. ## Stop it -On a yes, run `gh issue edit <issue> --repo OWNER/NAME --remove-label pendulum:objective`. Say it is stopped, and that `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:objective` starts it again. +On a yes, run `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:draft`. Report that Draft is on. When there was an active stage or queued merge, follow the existing stop until the stage exits and the PR leaves the queue. Use pendulum-file to remove Draft once it has stopped and the user wants it queued again. To stop every Objective at once instead, the user disables the workflow (`gh workflow disable pendulum.yml`) and cancels its runs in the Actions tab; with the cloud sandbox, also the Objectives' sandboxes in the Vercel project, since a stage running there is no Actions run; in local mode, `pendulum serve` stops with Ctrl-C. From d5c8b80d657c685448fe7bb1cb5b738348c3829f Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Thu, 19 Nov 2026 00:05:15 -0800 Subject: [PATCH 5/8] Honor trusted Draft activation across Pendulum runtime and clocks (#649) --- bench/README.md | 4 +- bench/drill.mjs | 10 +- bench/lib/collect.mjs | 46 +++++--- bench/lib/objective.mjs | 116 ++++++++++++--------- bench/lib/streak.mjs | 6 +- bench/score.mjs | 6 +- bench/test/score.test.mjs | 98 ++++++++++++++++- bench/test/streak.test.mjs | 26 ++++- plugin/scripts/dispatch.mjs | 74 ++++++++----- plugin/scripts/launch.mjs | 35 +++++-- plugin/scripts/lib/accounts.mjs | 2 +- plugin/scripts/lib/activation.mjs | 47 +++++++++ plugin/scripts/lib/answer-check.mjs | 19 ++-- plugin/scripts/lib/choice.mjs | 16 +-- plugin/scripts/lib/continue.mjs | 2 +- plugin/scripts/lib/cross-os.mjs | 44 ++++---- plugin/scripts/lib/finish-card.mjs | 83 +++++++++------ plugin/scripts/lib/logic.mjs | 20 ++-- plugin/scripts/lib/objective-cap.mjs | 2 +- plugin/scripts/lib/objective-trust.mjs | 32 +++--- plugin/scripts/lib/one-repo.mjs | 8 +- plugin/scripts/lib/progress-card.mjs | 3 +- plugin/scripts/lib/report.mjs | 8 +- plugin/scripts/lib/session.mjs | 87 +++++++++------- plugin/scripts/lib/stop.mjs | 98 ++++++++++++----- plugin/scripts/lib/triage.mjs | 8 +- plugin/scripts/lib/worker-relay.mjs | 2 +- plugin/scripts/lib/worker-secrets.mjs | 2 +- plugin/scripts/local.mjs | 44 ++++---- plugin/scripts/review.mjs | 21 ++-- plugin/scripts/worker.mjs | 2 +- plugin/test/account-move.test.mjs | 2 +- plugin/test/draft.test.mjs | 74 ++++++++++++- plugin/test/edit-after-plan.test.mjs | 2 +- plugin/test/exit.test.mjs | 2 +- plugin/test/finding-check.test.mjs | 21 ++-- plugin/test/finish-card.test.mjs | 43 +++++++- plugin/test/fixtures/finish-ends.snap.json | 4 +- plugin/test/merge-conflict.test.mjs | 8 +- plugin/test/objective-hosts.test.mjs | 2 +- plugin/test/objective-trust.test.mjs | 31 +++++- plugin/test/one-repo.test.mjs | 2 +- plugin/test/outbox.test.mjs | 2 +- plugin/test/question-answer.test.mjs | 51 ++++++++- plugin/test/question-ready.test.mjs | 12 +++ plugin/test/relaunch.test.mjs | 20 ++++ plugin/test/report-compare.test.mjs | 19 ++++ plugin/test/serve-hold.test.mjs | 2 +- plugin/test/stuck-checks.test.mjs | 4 +- plugin/test/triage.test.mjs | 6 +- 50 files changed, 922 insertions(+), 356 deletions(-) create mode 100644 plugin/scripts/lib/activation.mjs diff --git a/bench/README.md b/bench/README.md index 34f32e3b..4a302e06 100644 --- a/bench/README.md +++ b/bench/README.md @@ -8,7 +8,7 @@ One row per Objective, read from the issue, the PR on `pendulum/<issue>`, the jo | Number | What the row says | Taken from | | --- | --- | --- | -| Walk-away | `yes`, or `no` with the first human action | Binary. The clock starts at the first `pendulum:objective` label. Any human push, comment, review, edit or draft/ready toggle on the branch or the issue after it breaks it. Edits of the issue and PR bodies are every edit GraphQL lists (`userContentEdits`), each by its own editor, so a later edit never hides an earlier one; Pendulum's own login's edits (the finish block on the merged PR's body) are not input. A person's `workflow_dispatch` or re-run of the Pendulum workflow (`--workflow`, default `pendulum.yml`) between the clock and the merge is input too: one whose jobs name Objectives counts for those, one that names none (a hand-started dispatcher tick) for every Objective in flight then. The adopter drill's own dispatch (`drill.mjs --dispatch`) is not input for the Objectives it filed: the drill records the run id GitHub returned on each of them (`<!-- pendulum:N:drill {"dispatch": ID} -->`, posted by the issue's author), and that run's first attempt, started by the same login, is the drill's. A re-run of it, or any other dispatch, still counts. A Blocked card (label or marker comment) is a miss; an answered Question is a miss, named as such, even when the answer is nowhere the scorer reads (Pendulum resumed after its Question). A workflow hand-over is scored by `--handover` (Workflow hand-over, below): by default it is normal work, an owner step shown apart, never input. `*[bot]` actors never count; `--bot LOGIN` adds another. Each human action is also split: *asked for* when it follows a Question, Blocked notice or review request Pendulum made and comes before Pendulum's next `pendulum:running` label, else *unprompted* (an owner's note, scope added after the label). The row carries `walkAway.interventions` (`asked`, `unprompted`, Pendulum's `requests`) and `walkAway.askedOnly`, walk-away counting only asked-for actions; the table shows both, and the line under it sums them. A merge that sat idle longer than the stall threshold (`--stall-minutes`, default 60) between Pendulum's acts is a stall, not a walk-away (`walkAway.stall`; every merged row carries `walkAway.longestIdleMinutes`): the rule, what counts as Pendulum's acts and as idle, is the pendulum-score skill's, in `plugin/skills/pendulum-score/reference.md` (Stalls). Pendulum's posts are told from a person's by their `<!-- pendulum:... -->` markers (in local mode Pendulum posts as the operator's login, and an unmarked comment, a label other than Pendulum's state labels and Pendulum's own `pendulum:handover` (applied with its hand-over comment on the issue or inside a run; removed inside a run only as its drop: the comment then carries no patch, or Pendulum applies the label again; any other removal is the person's mark that they applied it), or removing `pendulum:blocked` without a re-applied Objective label is the operator's). The PR closed by its merge, its branch deleted and the issue closed right after it are the merge's, never acts of their own. | +| Walk-away | `yes`, or `no` with the first human action | Binary. The clock starts at the first removal of `pendulum:draft`, or the first legacy Objective label applied outside Draft. Any human push, comment, review, edit or draft/ready toggle on the branch or the issue after it breaks it. Edits of the issue and PR bodies are every edit GraphQL lists (`userContentEdits`), each by its own editor, so a later edit never hides an earlier one; Pendulum's own login's edits (the finish block on the merged PR's body) are not input. A person's `workflow_dispatch` or re-run of the Pendulum workflow (`--workflow`, default `pendulum.yml`) between the clock and the merge is input too: one whose jobs name Objectives counts for those, one that names none (a hand-started dispatcher tick) for every Objective in flight then. The adopter drill's own dispatch (`drill.mjs --dispatch`) is not input for the Objectives it filed: the drill records the run id GitHub returned on each of them (`<!-- pendulum:N:drill {"dispatch": ID} -->`, posted by the issue's author), and that run's first attempt, started by the same login, is the drill's. A re-run of it, or any other dispatch, still counts. A Blocked card (label or marker comment) is a miss; an answered Question is a miss, named as such, even when the answer is nowhere the scorer reads (Pendulum resumed after its Question). A workflow hand-over is scored by `--handover` (Workflow hand-over, below): by default it is normal work, an owner step shown apart, never input. `*[bot]` actors never count; `--bot LOGIN` adds another. Each human action is also split: *asked for* when it follows a Question, Blocked notice or review request Pendulum made and comes before Pendulum's next `pendulum:running` label, else *unprompted* (an owner's note, scope added after the label). The row carries `walkAway.interventions` (`asked`, `unprompted`, Pendulum's `requests`) and `walkAway.askedOnly`, walk-away counting only asked-for actions; the table shows both, and the line under it sums them. A merge that sat idle longer than the stall threshold (`--stall-minutes`, default 60) between Pendulum's acts is a stall, not a walk-away (`walkAway.stall`; every merged row carries `walkAway.longestIdleMinutes`): the rule, what counts as Pendulum's acts and as idle, is the pendulum-score skill's, in `plugin/skills/pendulum-score/reference.md` (Stalls). Pendulum's posts are told from a person's by their `<!-- pendulum:... -->` markers (in local mode Pendulum posts as the operator's login, and an unmarked comment, a label other than Pendulum's state labels and Pendulum's own `pendulum:handover` (applied with its hand-over comment on the issue or inside a run; removed inside a run only as its drop: the comment then carries no patch, or Pendulum applies the label again; any other removal is the person's mark that they applied it), or removing `pendulum:blocked` without a re-applied Objective label is the operator's). The PR closed by its merge, its branch deleted and the issue closed right after it are the merge's, never acts of their own. | | Solution quality | `pending` with the pair for the judge | The judge's, never the scorecard's. With `--baseline REF` the row carries the `judge.mjs` command for the merged head against it; without, the owner's read of the merged diff. The row also carries a `grade-auto.mjs` command for the merged head against the PR's own base commit. Escapes found after merge go in `quality.escapes`: an issue labelled P1, opened after the merge, that references the merged PR is filled in, a P1 Objective filed to fix it included; add others by hand. `--append` keeps the hand-filled ones (once per `owner/name#N` they name) and replaces the found ones with this run's, so one whose P1 label was removed drops out. | | Operator minutes | `0`, a number, or `unknown` | `--minutes <issue>=<n>` from a stopwatch; `0` on a clean merge; otherwise `unknown`, never estimated. A workflow hand-over's owner step has its own minutes, apart from these (Workflow hand-over, below). | | Cost | dollars with unit and basis | Claude: `usd` from `total_cost_usd` + `modelUsage` (sub-agents in). Codex: `usd` from its tokens priced from `plugin/scripts/lib/codex-prices.json` (the worker's own table), OpenAI's Standard rates as its pricing page and model pages give them, with the date and sources (a project on the Fast Service Tier pays 2× them (2.5× on gpt-5.5, 1.8× on gpt-5-mini), which Codex does not report); a model matches by its exact id (a provider prefix such as `openai/` stripped), a dated snapshot of it, or an alias OpenAI documents (`gpt-5.6`), else its runs are of unknown cost; a promotional rate (`until`) prices only a record that ended before that day, and a later one or one with no `ended` is of unknown cost (a stage's record ends with its latest pass or call); the tokens of a request over 272K input tokens are at the model's long-context rates, which the worker reads request by request from the thread's rollout into the record's `tokens.long`, and a record past 272K without that share (one the worker could not read, or written before it did) is of unknown cost for a model with such rates; a stage's Codex sub-agent threads (`subAgents` in its record) are priced at their own models and the rest of its tokens at the stage's; a run with no completed turn reports no tokens, so its dollars are unknown and its basis says that (`unknown: no Codex turn completed, so Codex reported no tokens`, the worker's record and the exit line alike), never a missing price; the unit stays `tokens` only while unpriced. Copilot: `usd` from the AI credits its `--usage-output-file` reports, at the run's `copilot_credit_usd` (GitHub's published $0.01 per credit by default), with the premium requests beside them (`cost.premiumRequests`, `cost.aiCredits`); an artifact without credits is of unknown cost. How the dollars are billed comes from each record's or spend line's `usdByBilling` and `billing`, which the worker writes on a positive sign only (docs/PLAN.md), never from the figure (`cost.usdByBilling`; a re-priced Codex part takes its record's `billing`): billed per use on a key is the bare figure; Claude Code's `total_cost_usd` or Codex tokens on a subscription are "API-equivalent at list prices, on the subscription"; Copilot's are "Copilot AI credits, billed to the seat"; anything else is "billing not recorded"; an Objective that mixes them shows each part in the cell and the basis. A record from before Pendulum named billing carries none and reads bare. Reviewer artifacts are summed with the worker's. A stage that ran in a cloud sandbox carries the vendor's cost in its record (`vendor`, at the vendor's dated list rates, docs/ADAPTERS.md "Vendor cost"); it is summed beside the model's dollars as `cost.vendorUsd`, with `cost.totalUsd` for both, and the cell reads `model + sandbox = total`; a stage whose usage the vendor did not report is a run of unknown cost there, never its session's ceiling. The dollars are every stage's on every route, each once: the usage artifacts (GitHub Actions, the cloud sandbox) and the `<!-- pendulum:spend -->` lines in Pendulum's own progress comments (local mode uploads no artifact), as the worker priced them; a progress comment of a record's own stage (work or review) that the record names counts as that record, whatever order the records come in: by its `progressRun` (the comment's key; null when the stage had no comment), else, for a record from before `progressRun`, by the sandbox stage's claim (`vendor.claim`, the key's `-<claim>`) or the workflow run that uploaded the artifact (the key's `<run>` or `<run>-<attempt>`), else, for a local `result.json` with no `progressRun` field on an account, that account's comments of its stage. A record Pendulum wrote for a stage whose own process wrote none (`standIn`) gives way to the stage's comment, or, when the stage's own record took it, gives that record its sandbox cost and is dropped. A record that names no comment counts beside the comments, but never doubles a figure: one with no `progressRun` field (a local `result.json` from before records named their comment) beside an unnamed comment of its stage with dollars may be that stage, so its dollars are unknown there (`unmatched`) and the comment's count once. The cost of this exactness is an unknown run, never a known figure twice: such a record and its comment show the comment's dollars plus one run of unknown cost, and a local stage killed before it wrote its `result.json`, scored with `--usage`, adds a run of unknown cost beside its comment. Beside artifacts, a stage's comment with no artifact and no spend line (an artifact that expired) is a run of unknown cost. A relayed worker key's dollars are inside each line's `usd` (broken out as `workerKeyUsd`, counted once), and a stage without a line is a run of unknown cost; a line's `usdUnknown` (runs whose spend no harness or vendor reported: killed, crashed or hung passes, a zeroed result, a model with no price row) is carried into the total; a sandbox stage's vendor dollars are the spend line of its vendor comment (`<!-- pendulum:<n>:vendor:<stage>:<key> -->`), beside its progress comment's. AI Gateway decision calls: a stage's are in its record's `usd` (apart as `gatewayDecisionUsd`, kept as the gateway reported them when a Codex stage's tokens are priced again), and those made outside a stage (the dispatcher's, the launcher's, a local loop's answer, comment, edit and lapse checks) are the `<!-- pendulum:decision-spend {...} -->` lines in Pendulum's own comments on the issue (a notice or record the check wrote, or a role's `<!-- pendulum:<n>:decisions:<role> -->` comment), added to the row on every route, as `api` (billed to the gateway key). Spend that a harness or vendor did not report is shown as unknown, as "plus N runs of unknown cost" beside the known dollars (`cost.usdUnknown`, its reasons in the basis), never as $0, an estimate or a bound; it is not counted against `max_usd` or `daily_usd` either, so a cap can be exceeded by it. Runner minutes and wall time (label to merge) sit beside it; wall time is never alone. | @@ -90,7 +90,7 @@ node bench/drill.mjs --repo OWNER/SCRATCH --set medium --count 5 --dispatch # node bench/drill.mjs --repo OWNER/SCRATCH --set conflict --dispatch # conflict: two Objectives that edit one README section, so the second is sent back to rebase ``` -A Question or Blocked exit ends the drill's wait for that Objective. The drill then waits (`--usage-wait-minutes`, default 10) for the usage artifact of each stage Pendulum ran, which can land after the label, downloads every one, and scores Blocked and merged Objectives alike; an artifact that never came is named in the report's `usageMissing` and its row says `missing: usage artifact`. An Objective still running when `--wait-minutes` runs out is not waited for, but its finished stages' artifacts are downloaded and scored, and its running stage is named in `usageMissing` as `(still running)`: its dollars are a floor. The drill files Objectives on a scratch repository (never Pendulum's own, never a product repository), lets the Action take them, waits, and scores them. The medium set is the instrument for changes to the worker's skills; the reviewer's is `bench/review-replay.mjs` against the private replay set. +A Question or Blocked exit ends the drill's wait for that Objective. The drill then waits (`--usage-wait-minutes`, default 10) for the usage artifact of each stage Pendulum ran, which can land after the label, downloads every one, and scores Blocked and merged Objectives alike; an artifact that never came is named in the report's `usageMissing` and its row says `missing: usage artifact`. An Objective still running when `--wait-minutes` runs out is not waited for, but its finished stages' artifacts are downloaded and scored, and its running stage is named in `usageMissing` as `(still running)`: its dollars are a floor. The drill files both labels on a scratch repository (never Pendulum's own, never a product repository) and removes Draft when each issue is ready. It follows the dispatcher, waits, and scores the Objectives. The medium set is the instrument for changes to the worker's skills; the reviewer's is `bench/review-replay.mjs` against the private replay set. ## Sandbox check diff --git a/bench/drill.mjs b/bench/drill.mjs index 6984a59c..185fb9fc 100644 --- a/bench/drill.mjs +++ b/bench/drill.mjs @@ -2,7 +2,7 @@ /** * `node bench/drill.mjs --repo OWNER/NAME --count N`: the adopter drill. Files N small, * fresh Objectives on a scratch repository (each a one-function addition over the - * repository's `greet`, named uniquely), lets the Action take them (the opened-issue tick, + * repository's `greet`, named uniquely). Removes Draft after filing so the Action takes them (the Draft-removal tick, * or `--dispatch` to fire one manually), waits until every one is closed or Blocked, then * scores them with bench/score.mjs. Exit 0 when every Objective merged with no human * input; 1 otherwise; 64 usage. @@ -17,7 +17,7 @@ * unit and database tests, suffixed so repeated runs never collide; every one changes * the scratch adopter alone * --count N Objectives to file (default 2 for small, 5 for medium) - * --dispatch dispatch pendulum.yml after filing (when the opened tick is not trusted); the run's id + * --dispatch dispatch pendulum.yml after activation (when the label tick is not trusted); the run's id * is recorded on each filed Objective, so the scorer reads it as the drill's, not input * --local also label each Objective pendulum:local, so a local loop (plugin/scripts/local.mjs serve) * takes it and the Actions path leaves it alone @@ -40,6 +40,7 @@ import { join, resolve } from "node:path"; import { parseArgs } from "node:util"; import { promisify } from "node:util"; import { awaitUsage } from "./lib/collect.mjs"; +import { DRAFT_LABEL } from "../plugin/scripts/lib/activation.mjs"; import { ghApi } from "./lib/gh.mjs"; import { mediumObjectives } from "./lib/medium.mjs"; import { drillRecord } from "./lib/objective.mjs"; @@ -134,14 +135,15 @@ for (const o of objectives) { writeFileSync(file, o.body); let url; try { - url = await gh("issue", "create", "-R", repo, "--title", o.title, "--body-file", file, "--label", "pendulum:objective", "--label", "P1", ...(values.local ? ["--label", "pendulum:local"] : [])); + url = await gh("issue", "create", "-R", repo, "--title", o.title, "--body-file", file, "--label", "pendulum:objective", "--label", DRAFT_LABEL, "--label", "P1", ...(values.local ? ["--label", "pendulum:local"] : [])); } finally { rmSync(dir, { recursive: true, force: true }); } const number = Number(url.split("/").pop()); await setType(number); filed.push({ number, title: o.title, url, filedAt: new Date().toISOString() }); - process.stderr.write(`filed #${number} ${o.title}\n`); + await gh("issue", "edit", String(number), "-R", repo, "--remove-label", DRAFT_LABEL); + process.stderr.write(`filed and activated #${number} ${o.title}\n`); } // The drill's own tick: dispatched through the API, which returns the run's id, recorded on each Objective it filed // (objective.mjs drillRecord) so the scorer reads that run as the drill's and not as operator input. A dispatch whose diff --git a/bench/lib/collect.mjs b/bench/lib/collect.mjs index 7431eef2..36d944b5 100644 --- a/bench/lib/collect.mjs +++ b/bench/lib/collect.mjs @@ -16,7 +16,8 @@ import { basename } from "node:path"; import { findFile } from "./gh.mjs"; import { ownRunArtifact } from "../../plugin/scripts/lib/github.mjs"; import { parseUsageText, sessionsOf } from "./cost.mjs"; -import { OBJECTIVE_LABEL } from "./objective.mjs"; +import { DRAFT_LABEL } from "../../plugin/scripts/lib/activation.mjs"; +import { labelTime, OBJECTIVE_LABEL } from "./objective.mjs"; import { bySelf, pendulumLogin } from "./phases.mjs"; const PER_PAGE = "per_page=100"; @@ -30,21 +31,31 @@ export const REVIEW_ARTIFACT = (issue) => `pendulum-usage-${issue}-review`; /** * The Objectives worth a row: issues with the label that closed at or after * `since` (ISO date), plus open ones carrying a Pendulum state label (Blocked, - * Question, In review, Running), so the misses that never merged are rows too. + * Question, In review, Running), so the misses that never merged are rows too. A draft that already ran is kept + * after its state labels have been cleared by stopping it. Closing a draft before activation does not create a row. * With `since`, also every issue whose label was removed at or after it (a * parked Objective, waiting on other work) and that Pendulum picked up then (a * state label applied at or after `since`): it ran and cost money, whatever its * labels are now, after the labelled ones. */ -export async function listObjectives(api, repoFull, { since, label = OBJECTIVE_LABEL, state = "all" } = {}) { +export async function listObjectives(api, repoFull, { since, label = OBJECTIVE_LABEL, state = "all", app = null } = {}) { const query = [`labels=${encodeURIComponent(label)}`, `state=${state}`, since ? `since=${encodeURIComponent(since)}` : null, "sort=updated", "direction=desc", PER_PAGE].filter(Boolean).join("&"); + const from = since ? Date.parse(since) : -Infinity; const issues = await api(`repos/${repoFull}/issues?${query}`, { paginate: true }); - const numbers = new Set( - issues - .filter((i) => !i.pull_request) - .filter((i) => (i.state === "closed" ? !since || Date.parse(i.closed_at ?? i.updated_at) >= Date.parse(since) : labelNames(i).some((n) => STATE_LABELS.includes(n)))) - .map((i) => i.number), - ); + const numbers = new Set(); + for (const issue of issues.filter((i) => !i.pull_request)) { + const closed = issue.state === "closed"; + if (closed && since && !(Date.parse(issue.closed_at ?? issue.updated_at) >= from)) continue; + const labels = labelNames(issue); + if (labels.some((name) => STATE_LABELS.includes(name)) || (closed && !labels.includes(DRAFT_LABEL))) { + numbers.add(issue.number); + } else if (labels.includes(DRAFT_LABEL)) { + const events = await api(`repos/${repoFull}/issues/${issue.number}/${closed ? "timeline" : "events"}?${PER_PAGE}`, { paginate: true }); + const worked = events.some((e) => e.event === "labeled" && STATE_LABELS.includes(e.label?.name) && (closed || Date.parse(e.created_at) >= from)); + const self = pendulumLogin(events, app); + if (worked || (closed && labelTime(issue, events, label, null, { mine: (c) => bySelf(c, self) }))) numbers.add(issue.number); + } + } if (since) for (const n of await parkedSince(api, repoFull, { since, label, skip: new Set(issues.map((i) => i.number)) })) numbers.add(n); return [...numbers]; } @@ -207,17 +218,18 @@ const JOB_ISSUE = /^(?:work|launch|merge tick) \((\d+)\)$|^review \(pendulum\/(\ /** * The runs of Pendulum's workflow a person started (`workflow_dispatch`) or re-ran (attempt 2 and up) while the - * Objective was live: from its first Objective or Running label to its merge (or its close, or now). Bots' runs are + * Objective was live: from its first activation to its merge (or its close, or now). Bots' runs are * left out here already. Each is `{id, event, attempt, created_at, run_started_at, by, issues}`, `issues` being the * Objectives its jobs name (`work (N)`, `launch (N)`, `merge tick (N)`, `review (pendulum/N)`), empty for a run tied to * none (a dispatcher tick). Throws when the runs cannot be read, or when GitHub's 1,000-run cap on a `created` filter - * may have cut the list. A re-run of a run created before the first label is not listed (the filter is on creation). + * may have cut the list. A re-run of a run created before activation is not listed (the filter is on creation). */ -export async function humanWorkflowRuns(api, repoFull, issueData, timeline, pulls, { workflow = PENDULUM_WORKFLOW } = {}) { - const starts = (timeline || []).filter((e) => e.event === "labeled" && (e.label?.name === OBJECTIVE_LABEL || e.label?.name === "pendulum:running")).map((e) => Date.parse(e.created_at)).filter(Number.isFinite); - if (!starts.length) return []; +export async function humanWorkflowRuns(api, repoFull, issueData, timeline, pulls, { workflow = PENDULUM_WORKFLOW, label = OBJECTIVE_LABEL, comments = [], app = null } = {}) { + const self = pendulumLogin(timeline, app); + const started = labelTime(issueData, timeline, label, null, { comments, mine: (c) => bySelf(c, self) }); + if (!started) return []; const iso = (t) => new Date(t).toISOString().replace(/\.\d{3}Z$/, "Z"); - const from = iso(Math.min(...starts)); + const from = iso(Date.parse(started)); const merged = (pulls || []).map((p) => Date.parse(p.merged_at)).filter(Number.isFinite); const endMs = merged.length ? Math.max(...merged) : Date.parse(issueData.closed_at) || null; const range = endMs ? `${from}..${iso(endMs)}` : `>=${from}`; @@ -250,7 +262,7 @@ export async function humanWorkflowRuns(api, repoFull, issueData, timeline, pull * (lib/gh.mjs's downloadArtifact bound to a token) or is null offline. * `usage` is a list of records read from --usage <dir> when given. */ -export async function collectObjective(api, repoFull, issue, { download = null, usage = null, jobs: wantJobs = true, graphql = null, app = null, workflow = PENDULUM_WORKFLOW } = {}) { +export async function collectObjective(api, repoFull, issue, { download = null, usage = null, jobs: wantJobs = true, graphql = null, app = null, workflow = PENDULUM_WORKFLOW, label = OBJECTIVE_LABEL } = {}) { const base = `repos/${repoFull}`; const issueData = await api(`${base}/issues/${issue}`); const [issueTimeline, issueComments, pullsOpen, pullsClosed] = await Promise.all([ @@ -326,7 +338,7 @@ export async function collectObjective(api, repoFull, issue, { download = null, } let workflowRuns = null; try { - workflowRuns = await humanWorkflowRuns(api, repoFull, issueData, issueTimeline, pulls, { workflow }); + workflowRuns = await humanWorkflowRuns(api, repoFull, issueData, issueTimeline, pulls, { workflow, label, comments: issueComments, app }); } catch { workflowRuns = null; // not readable with this token (actions: read): the row says so } diff --git a/bench/lib/objective.mjs b/bench/lib/objective.mjs index ebcd1f59..89fa8423 100644 --- a/bench/lib/objective.mjs +++ b/bench/lib/objective.mjs @@ -3,8 +3,8 @@ // "Job one and how 0.6 is measured"). Pure: takes the collected facts // (lib/collect.mjs online, a fixture offline) and returns the row. // -// walkAway binary. The clock starts at the first `pendulum:objective` -// label. Any human push, comment, review, edit, draft toggle or +// walkAway binary. The clock starts at the first activation, when Draft comes off or an old Objective label is +// applied outside Draft. Any human push, comment, review, edit, draft toggle or // merge on the branch or the issue after it breaks it; a Blocked // card (the pendulum:blocked label or the blocked marker comment) // is a miss. A Question answered by a human is a miss too. @@ -22,13 +22,14 @@ // ownerStep a posted workflow hand-over a person applies after the merge: // its minutes from --owner-minutes, apart from the operator's. // cost lib/cost.mjs (the plugin's cost-join.mjs), with unit and basis per harness. -// wall filed (label) to merged; runner minutes from the job log. -import { dispatchLatency, pendulumLogin, phaseMinutes, setupSeconds, stageLastWrite } from "./phases.mjs"; +// wall activation to merged; runner minutes from the job log. +import { bySelf, dispatchLatency, pendulumLogin, phaseMinutes, setupSeconds, stageLastWrite } from "./phases.mjs"; import { ACCOUNT, accountUse, costOf, decisionSpendRecords, stageHarnessOf, stageOf, stageSpendRecords, withLines } from "./cost.mjs"; import { BLOCK_CAUSES, blockCauseOf, rebaseTally, spendText } from "../../plugin/scripts/lib/logic.mjs"; import { billingText, unknownText } from "../../plugin/scripts/lib/usage.mjs"; import { HANDOVER_LABEL, carriesHandover, handoverMarker, handoverOf } from "../../plugin/scripts/lib/handover.mjs"; -import { clockRenamed, labelTime } from "../../plugin/scripts/lib/finish-card.mjs"; +import { activationEvents, DRAFT_LABEL, latestDraftEvent } from "../../plugin/scripts/lib/activation.mjs"; +import { clockRenamed, clockStart } from "../../plugin/scripts/lib/finish-card.mjs"; export const ROW_VERSION = 1; @@ -37,7 +38,6 @@ export { accountUse, stageHarnessOf, withLines }; const BRANCH = (issue) => `pendulum/${issue}`; export const RUNNING_LABEL = "pendulum:running"; export const OBJECTIVE_LABEL = "pendulum:objective"; -const DRAFT_LABEL = "pendulum:draft"; const BLOCKED_LABEL = "pendulum:blocked"; /** * The stall threshold's default, in minutes: a merged Objective idle longer than this after Pendulum's last action @@ -82,12 +82,8 @@ function commitActor(commit) { return { login: name || email || "unknown", type: "User", unlinked: true }; } -/** - * The clock: the first `labeled pendulum:objective` event, or null; a draft's start for a draft. With `clockAfter`, the - * first such event at or after that date: an issue that an earlier Pendulum already ran under the same label starts its - * clock there. The finish card starts its clock the same way, so the rule lives with it (plugin finish-card.mjs). - */ -export { labelTime }; +/** The finish card and scorer share an Objective's first activation. */ +export { labelTime } from "../../plugin/scripts/lib/finish-card.mjs"; /** * Minutes of the wall clock spent waiting rather than working: from the clock to Pendulum's first @@ -95,7 +91,8 @@ export { labelTime }; * next Running label (a human's turn). Null without a merge; the basis says what counted. */ export function waitingMinutes(timeline, since, mergedAt) { - if (!since || !mergedAt) return { minutes: null, basis: "not merged" }; + if (!mergedAt) return { minutes: null, basis: "not merged" }; + if (!since) return { minutes: null, basis: "clock start not recorded" }; const labels = (timeline || []).filter((e) => e.event === "labeled" && e.label?.name && ms(e.created_at) >= ms(since)).sort((a, b) => ms(a.created_at) - ms(b.created_at)); let total = 0; const parts = []; @@ -134,7 +131,7 @@ export function decisionsOf(actions) { * - labels: only the pendulum state labels the local loop sets (running, in-review, blocked, question, review) are * Pendulum's, and removing pendulum:restart once it restarted the Objective. Any other label, applying * pendulum:restart and re-applying pendulum:objective among them, is a person's. Removing pendulum:blocked is - * Pendulum's only after a re-applied Objective label (the recovery it answers); without one it is a person's + * Pendulum's only after a new activation (the recovery it answers); without one it is a person's * manual un-block. * - comments: Pendulum's comments all carry a `<!-- pendulum:... -->` marker. One without a marker is a person's, even * inside a run (an answer to a Question typed while the stage was running). @@ -180,10 +177,12 @@ export function localPendulumActions(collected, { label = OBJECTIVE_LABEL } = {} const handoverLabel = (at) => handoverBodies.length > 0 || inRun(at); const dropped = handoverBodies.some((b) => handoverOf(b.slice(mark.length)) === null); const relabeled = (at) => labels.some((e) => e.label?.name === HANDOVER_LABEL && (e.actor?.login ?? e.actor?.name) === login && ms(e.created_at) > ms(at) && handoverLabel(e.created_at)); - // Pendulum lifts its own Blocked only on recovery: the Objective label re-applied after the latest block. + // Pendulum lifts its own Blocked only on a new activation after the latest block. + const timeline = collected.issueTimeline || []; + const starts = activationEvents(timeline, label, { assumeObjective: true }); const recovered = (at) => { const block = labels.filter((e) => e.label?.name === BLOCKED_LABEL && ms(e.created_at) <= ms(at)).at(-1); - return !!block && labels.some((e) => e.label?.name === label && ms(e.created_at) >= ms(block.created_at) && ms(e.created_at) <= ms(at)); + return !!block && starts.some((e) => ms(e.created_at) <= ms(at) && (ms(e.created_at) > ms(block.created_at) || (ms(e.created_at) === ms(block.created_at) && timeline.indexOf(e) > timeline.indexOf(block)))); }; return (at, actor, kind, id = null) => { if (tidied(at, actor, kind, id)) return true; @@ -325,31 +324,36 @@ function triageReruns(collected, login) { } /** The human actions after `since` on the issue and its PRs, oldest first: each {at, where, kind, by, detail}. */ -export function humanActions(collected, since, { bots = new Set(), label = OBJECTIVE_LABEL } = {}) { +export function humanActions(collected, since, { bots = new Set(), label = OBJECTIVE_LABEL, start = clockStart(collected.issueTimeline, label, since) } = {}) { const out = []; - const after = (at) => Number.isFinite(ms(at)) && ms(at) > ms(since); + const sinceMs = ms(since); + const timeline = collected.issueTimeline || []; + const startIndex = ms(start?.created_at) === sinceMs ? timeline.indexOf(start) : -1; const pendulumLocal = localPendulumActions(collected, { label }); - const push = (at, where, kind, actor, detail = "", id = null) => { - if (after(at) && isHuman(actor, bots) && !pendulumLocal(at, actor, kind, id)) out.push({ at, where, kind, by: actor.login ?? actor.name ?? "unknown", detail }); + const push = (at, where, kind, actor, detail = "", id = null, timelineIndex = -1) => { + const atMs = ms(at); + const after = atMs > sinceMs || (atMs === sinceMs && startIndex >= 0 && timelineIndex > startIndex); + if (after && isHuman(actor, bots) && !pendulumLocal(at, actor, kind, id)) out.push({ at, where, kind, by: actor.login ?? actor.name ?? "unknown", detail }); }; const issue = `#${collected.issue.number}`; + const author = collected.issue.user?.login; + const filedAt = ms(collected.issue.created_at); const branch = branchPulls(collected); const mergedTimes = branch.filter((pr) => pr.merged_at).map((pr) => ms(pr.merged_at)); - for (const e of collected.issueTimeline || []) { + for (const [i, e] of timeline.entries()) { if (mergeConsequence(e.event, e.created_at, mergedTimes)) continue; // Passive events (mentioned, subscribed, cross-referenced from elsewhere) and bookkeeping (issue type, // milestone, pin, project card) are not input to the Objective's work. if (PASSIVE_EVENTS.has(e.event)) continue; - if (e.event === "labeled" && e.label?.name === label && e.created_at === since) continue; // the clock itself - if (e.event === "unlabeled" && e.label?.name === DRAFT_LABEL && e.created_at === since) continue; // a draft's start: the clock - // Labels the issue's author applies while filing it (a priority, the type's labels) are part of filing, not input. - if (e.event === "labeled" && (e.actor?.login ?? null) === (collected.issue.user?.login ?? undefined) && ms(e.created_at) - ms(collected.issue.created_at) <= 60_000) continue; + // Legacy direct starts could bundle filing metadata with the Objective label. A Draft hold is always input. + if (start?.label?.name === label && e.event === "labeled" && e.label?.name !== DRAFT_LABEL && author && e.actor?.login === author && + ms(e.created_at) >= filedAt && ms(e.created_at) - filedAt <= 60_000) continue; if (e.event === "commented") { if (/<!-- pendulum:/.test(e.body || "")) continue; // Pendulum's own protocol (plan, progress, hold, blocked markers), whoever posted it - push(e.created_at, issue, "comment", e.user ?? e.actor, (e.body || "").slice(0, 80)); + push(e.created_at, issue, "comment", e.user ?? e.actor, (e.body || "").slice(0, 80), null, i); continue; } - push(e.created_at, issue, e.event === "labeled" || e.event === "unlabeled" ? `${e.event} ${e.label?.name ?? ""}` : e.event, e.actor, "", e.id ?? null); + push(e.created_at, issue, e.event === "labeled" || e.event === "unlabeled" ? `${e.event} ${e.label?.name ?? ""}` : e.event, e.actor, "", e.id ?? null, i); } for (const c of collected.issueComments || []) if (!/<!-- pendulum:/.test(c.body || "")) push(c.created_at, issue, "comment", c.user, (c.body || "").slice(0, 80)); for (const pr of collected.pulls || []) { @@ -637,8 +641,8 @@ export function questionAt(collected, since) { const n = collected.issue.number; const plan = `<!-- pendulum:${n}:plan -->`; for (const e of collected.issueTimeline || []) if (e.event === "labeled" && e.label?.name === QUESTION_LABEL && ms(e.created_at) >= ms(since)) return { at: e.created_at, source: "label" }; - for (const pr of collected.pulls || []) if (/\bQUESTION\b/.test(pr.body || "")) return { at: pr.created_at, source: `PR #${pr.number} body` }; - for (const c of collected.issueComments || []) if ((c.body || "").includes(plan) && /\bQUESTION\b/.test(c.body || "")) return { at: c.created_at, source: "plan comment" }; + for (const pr of collected.pulls || []) if (ms(pr.created_at) >= ms(since) && /\bQUESTION\b/.test(pr.body || "")) return { at: pr.created_at, source: `PR #${pr.number} body` }; + for (const c of collected.issueComments || []) if (ms(c.created_at) >= ms(since) && (c.body || "").includes(plan) && /\bQUESTION\b/.test(c.body || "")) return { at: c.created_at, source: "plan comment" }; return null; } @@ -810,9 +814,20 @@ export function scoreObjective(collected, opts = {}) { // read: the owner's read of the merged diff ("ok", "defect" or "unread"), given with --read, kept across --append. const issue = collected.issue; const missing = []; - let since = labelTime(issue, collected.issueTimeline, label, clockAfter); - let sinceBasis = clockAfter ? `first "${label}" label at or after ${clockAfter}` : `first "${label}" label`; - if (!since) { + const self = pendulumLogin(collected.issueTimeline, app); + const start = clockStart(collected.issueTimeline, label, clockAfter, { issue: issue.number, comments: collected.issueComments, mine: (c) => bySelf(c, self) }); + const labels = issue.labels?.map((l) => (typeof l === "string" ? l : l?.name)); + const draft = labels?.includes(DRAFT_LABEL); + const noStart = !start && (draft || latestDraftEvent(collected.issueTimeline) !== null); + let since = start?.created_at ?? null; + let sinceBasis = start?.label.name === DRAFT_LABEL ? `first removal of "${DRAFT_LABEL}"` + : start?.label.name === RUNNING_LABEL ? `first "${RUNNING_LABEL}" label` + : `first "${label}" label`; + if (clockAfter) sinceBasis += ` at or after ${clockAfter}`; + if (noStart) { + sinceBasis = "Draft has no recorded activation"; + missing.push("Draft activation event"); + } else if (!since) { since = clockAfter && ms(issue.created_at) < ms(clockAfter) ? clockAfter : issue.created_at; sinceBasis = clockAfter && since === clockAfter ? `--clock-after (no "${label}" label event at or after it)` : `issue created (no "${label}" label event found)`; missing.push("label event"); @@ -829,17 +844,16 @@ export function scoreObjective(collected, opts = {}) { const open = pulls.find((pr) => !pr.merged_at && pr.state === "open") ?? null; const blocked = blockedAt(collected, since); const question = questionAt(collected, since); - let actions = humanActions(collected, since, { bots, label }); + let actions = humanActions(collected, since, { bots, label, start }); const waiting = waitingMinutes(collected.issueTimeline, since, merged?.merged_at ?? null); const exit = merged ? "merged" : blocked ? "blocked" : question ? "question" : open ? (open.draft ? "draft" : "in review") : pulls.length ? "closed unmerged" : "no PR"; - // Parked: open, its label removed after Pendulum took it (it waits on other work). Its exit still says where it + // Parked: open, made a draft or its identity label removed after activation. Its exit still says where it // stopped; it is never a walk-away (not merged) and the streak counts it only once it ended (lib/streak.mjs endedAt). - const parked = issue.state === "open" && !missing.includes("label event") && Array.isArray(issue.labels) && !issue.labels.some((l) => (typeof l === "string" ? l : l?.name) === label); + const parked = issue.state === "open" && !!start && !!labels && (draft || !labels.includes(label)); const pendulumLocal = localPendulumActions(collected); // Every body edit after the clock by a person, oldest first: never Pendulum's own login (its App's finish block on the // merged PR's body, plugin finish-card.mjs), nor, in local mode, what localPendulumActions says is Pendulum's. - const self = pendulumLogin(collected.issueTimeline, app); const bodyEdit = [...(collected.bodyEdits || [])].sort((a, b) => ms(a.at) - ms(b.at)).find((e) => ms(e.at) > ms(since) && isHuman(e.by, bots) && !(self && e.by?.login === self) && !pendulumLocal(e.at, e.by, "body edit")) ?? null; if (bodyEdit) actions.unshift({ at: bodyEdit.at, where: bodyEdit.where, kind: "body edit", by: bodyEdit.by.login, detail: "" }); if (collected.bodyEdits === null) missing.push("body edits (GraphQL unavailable)"); // undefined: not attempted (a fixture or a snapshot) @@ -877,7 +891,7 @@ export function scoreObjective(collected, opts = {}) { const stall = idle?.stalled ? { minutes: idle.minutes, from: idle.from, until: idle.until, thresholdMinutes: idle.thresholdMinutes } : null; const stallReason = stall ? `stalled ${stall.minutes} min after Pendulum's last action (${stall.from} to ${stall.until}; threshold ${stall.thresholdMinutes} min)` : null; const walkAway = { - value: Boolean(merged) && !blocked && actions.length === 0 && !stall, + value: Boolean(merged) && !blocked && !noStart && actions.length === 0 && !stall, // The rule this row scored a workflow hand-over by (HANDOVER_SCORING). handover, since, @@ -895,10 +909,11 @@ export function scoreObjective(collected, opts = {}) { }; walkAway.blocks = blockStops(collected, since, { bots }); walkAway.bucket = walkAwayBucket({ value: walkAway.value, blocks: walkAway.blocks, question, actions: split, stall, unseen }); + const walkAwayReason = `merged with no human action after ${start?.label.name === DRAFT_LABEL ? "Draft removal" : "the label"}${ownerNote}`; walkAway.reason = walkAway.value - ? `merged with no human action after the label${ownerNote}` - : !merged - ? `not merged (${exit}${blocked?.reason ? `: ${blocked.reason}` : ""})` + ? walkAwayReason + : !merged || noStart + ? (merged ? "merged with no recorded activation" : `not merged (${exit}${blocked?.reason ? `: ${blocked.reason}` : ""})`) : blocked ? `Blocked at ${blocked.at}${blocked.reason ? `: ${blocked.reason}` : ""}` : actions.length @@ -907,8 +922,8 @@ export function scoreObjective(collected, opts = {}) { // Walk-away counting only what Pendulum asked for: a merge with no Blocked and no human action answering a request. // Unprompted actions (an owner's note, scope added after the label) are left out of this one, never out of `value`. walkAway.askedOnly = { - value: Boolean(merged) && !blocked && asked.length === 0 && !stall, - reason: !merged + value: Boolean(merged) && !blocked && !noStart && asked.length === 0 && !stall, + reason: !merged || noStart ? walkAway.reason : blocked ? walkAway.reason @@ -918,8 +933,13 @@ export function scoreObjective(collected, opts = {}) { ? `first asked-for action: ${asked[0].kind} on ${asked[0].where} by ${asked[0].by} at ${asked[0].at}, answering a ${asked[0].asked}` : unprompted.length ? `merged; ${unprompted.length} unprompted human action(s), none asked for` - : `merged with no human action after the label${ownerNote}`, + : walkAwayReason, }; + if (merged && noStart) { + walkAway.value = null; + walkAway.bucket = "unknown"; + walkAway.askedOnly.value = null; + } // Labelled before the rename (`renamed`): a walk-away with every input source read, and an asked-only yes, are not // known; anything else stays as read, noted (a walk-away with an input source unread still breaks the streak). if (renamed) { @@ -957,7 +977,7 @@ export function scoreObjective(collected, opts = {}) { let operator; if (typeof given === "number" && Number.isFinite(given)) operator = { minutes: given, basis: "--minutes (stopwatch)" }; - else if (renamed) operator = { minutes: "unknown", basis: `${RENAMED_WHY}; give --minutes <issue>=<n> from a stopwatch` }; + else if (renamed || noStart) operator = { minutes: "unknown", basis: `${renamed ? RENAMED_WHY : sinceBasis}; give --minutes <issue>=<n> from a stopwatch` }; else if (walkAway.value) operator = { minutes: 0, basis: ownerStep ? "clean merge; the owner step's minutes are apart (ownerStep)" : "clean merge" }; else if (merged && !blocked && !actions.length) operator = { minutes: 0, basis: "no human action (stalled)" }; else operator = { minutes: "unknown", basis: actions.some((a) => a.kind === "workflow hand-over") ? "a workflow hand-over is a person's step: give --minutes <issue>=<n> from a stopwatch" : "give --minutes <issue>=<n> from a stopwatch" }; @@ -1014,7 +1034,7 @@ export function scoreObjective(collected, opts = {}) { runnerMinutes: runner.minutes, runnerBasis: runner.basis, wallMinutes: wall, - wallBasis: !merged ? "not merged" : renamed ? "unknown: labelled before the rename to Pendulum" : `${sinceBasis} to merged`, + wallBasis: !merged ? "not merged" : renamed ? "unknown: labelled before the rename to Pendulum" : noStart ? sinceBasis : `${sinceBasis} to merged`, waitingMinutes: renamed ? null : waiting.minutes, waitingBasis: renamed ? RENAMED_WHY : waiting.basis, workingMinutes: wall === null || waiting.minutes === null ? null : Math.max(0, Math.round((wall - waiting.minutes) * 10) / 10), @@ -1085,7 +1105,7 @@ export const ownerCell = (r) => (r.ownerStep ? `${fmtMin(r.ownerStep.minutes)} ( /** The summary under the table: walk-away both ways, the interventions split and the owner steps, over every row. */ export function summaryLine(rows) { - // A row labelled before the rename (bucket `unknown`) is in no walk-away count. + // A row with an unknown clock is in no walk-away count. const unknown = rows.filter((r) => r.walkAway.bucket === "unknown"); const n = rows.length - unknown.length; const merged = rows.filter((r) => r.exit === "merged" && r.walkAway.bucket !== "unknown").length; @@ -1098,6 +1118,8 @@ export function summaryLine(rows) { const owners = rows.filter((r) => r.ownerStep); const inputs = rows.filter((r) => !r.ownerStep && (r.walkAway.interventions?.requests || []).some((q) => q.kind === "workflow hand-over")); const handovers = `${owners.length ? ` Owner steps (a workflow hand-over, scored as normal work, its minutes apart): ${owners.map((r) => `#${r.issue} ${ownerCell(r)}`).join(", ")}.` : ""}${inputs.length ? ` Workflow hand-overs scored as input: ${inputs.map((r) => `#${r.issue}`).join(", ")}.` : ""}`; - const notKnown = unknown.length ? ` Not known (labelled before the rename to Pendulum), in no count: ${unknown.map((r) => `#${r.issue}`).join(", ")}.` : ""; + const unknownNote = (affected, why) => affected.length ? ` Not known (${why}), in no count: ${affected.map((r) => `#${r.issue}`).join(", ")}.` : ""; + const notKnown = unknownNote(unknown.filter((r) => r.walkAway.clockRenamed), "labelled before the rename to Pendulum") + + unknownNote(unknown.filter((r) => !r.walkAway.clockRenamed), "Draft activation was not recorded"); return `Walk-away: ${strict} of ${n} Objective(s) (${merged} merged) with no human input; ${askedOnly} of ${n} counting only input Pendulum asked for. Interventions: ${sum("asked")} asked for (Question, Blocked notice, review request), ${sum("unprompted")} unprompted.${stalls}${handovers}${notKnown}`; } diff --git a/bench/lib/streak.mjs b/bench/lib/streak.mjs index e680243d..df17eaa5 100644 --- a/bench/lib/streak.mjs +++ b/bench/lib/streak.mjs @@ -11,8 +11,8 @@ // One still running, in review or waiting on a Question has not finished: it is listed as in flight, neither. // An External one (walkAway.bucket: its only stops were external Blocks, lib/objective.mjs walkAwayBucket) is listed // in the sequence as skipped: it neither extends nor breaks, and does not count as finished. A P1 escape found in its -// merge makes it a break. A walk-away merge labelled before the rename to Pendulum (bucket `unknown`: whether it was one -// is not known) is skipped the same way, unless a P1 escape makes it a break; a miss or an External result seen after +// merge makes it a break. A merge with an unknown activation clock (bucket `unknown`) is skipped the same way, +// unless a P1 escape makes it a break; a miss or an External result seen after // its later label is scored as any other. // A workflow hand-over scored as an owner step (lib/objective.mjs HANDOVER_SCORING, the default) leaves the merge a // walk-away: it extends the streak, and its entry says it carries an owner step (`ownerStep`). Scored as input, it breaks. @@ -36,7 +36,7 @@ export function endedAt(row) { /** One finished row's verdict for the streak: `{ok, why}`; an External row's is `{ok: null, external: true, why}`, skipped. */ export function verdict(row) { const escapes = (row.quality?.escapes || []).filter(isP1); - // A walk-away merge labelled before the rename (bucket `unknown`): skipped, unless a P1 escape or an input source not + // A merge with an unknown activation clock: skipped, unless a P1 escape or an input source not // read breaks it. const unread = row.walkAway?.unseen === undefined ? ["input sources not recorded"] : row.walkAway.unseen; if (row.walkAway?.bucket === "unknown" && unread.length) return { ok: false, why: `input not readable (${unread.join(", ")}): walk-away unproven` }; diff --git a/bench/score.mjs b/bench/score.mjs index 0da72088..c492880b 100644 --- a/bench/score.mjs +++ b/bench/score.mjs @@ -39,7 +39,7 @@ * comments alone are read (default: the App that * applied pendulum:running to the issue) * --label NAME the Objective label (default pendulum:objective) - * --clock-after DATE start each clock at the first label event at or + * --clock-after DATE start each clock at the first activation event at or * after DATE (an issue an earlier Pendulum ran under * the same label keeps its old events; this floors them) * --check CMD validation command(s) for the grade-auto line @@ -221,14 +221,14 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) if (!sinceAt) usage(`--since ${sinceTag}: no such tag in ${pendulumRepo}`); } for (const repo of repos) { - const numbers = issues.length ? issues : await listObjectives(api, repo, { since: sinceAt, label }); + const numbers = issues.length ? issues : await listObjectives(api, repo, { since: sinceAt, label, app: values.app ?? null }); if (!numbers.length) { process.stderr.write(`no ${label} issue in ${repo} closed${values.since ? ` since ${values.since}` : ""}, Blocked, Question, In review, Running or parked\n`); if (!pooled) process.exit(65); } byRepo[repo] = []; for (const issue of numbers) { - const collected = snapshot?.collected?.[issue] ?? (await collectObjective(api, repo, issue, { download, usage: usageFor(issue, numbers.length) ?? (usageDir ? [] : null), jobs: !values["no-jobs"], graphql, app: values.app ?? null, ...(values.workflow ? { workflow: values.workflow } : {}) })); + const collected = snapshot?.collected?.[issue] ?? (await collectObjective(api, repo, issue, { download, usage: usageFor(issue, numbers.length) ?? (usageDir ? [] : null), jobs: !values["no-jobs"], graphql, app: values.app ?? null, label, ...(values.workflow ? { workflow: values.workflow } : {}) })); // --usage decides on a replay too: an issue without its own directory has none, whatever the snapshot stored. if (usageDir && snapshot) collected.usage = usageFor(issue, numbers.length) ?? []; collected.harness = collected.usage.find((r) => r.harness)?.harness ?? collected.harness ?? null; diff --git a/bench/test/score.test.mjs b/bench/test/score.test.mjs index 6bc36ac1..3d039931 100644 --- a/bench/test/score.test.mjs +++ b/bench/test/score.test.mjs @@ -7,12 +7,13 @@ import { cpSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, stat import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; -import { collectObjective, snapshotApi, usageDirFor, usageFromDir } from "../lib/collect.mjs"; +import { collectObjective, humanWorkflowRuns, snapshotApi, usageDirFor, usageFromDir } from "../lib/collect.mjs"; import { costOf, loadPrices, parseUsageText, priceTokens } from "../lib/cost.mjs"; import { RENAMED_WHY, humanActions, localPendulumActions, markdownTable, scoreObjective, summaryLine } from "../lib/objective.mjs"; import { blocked, cleanMerge, humanPush, localMerge, OPERATOR, REPO, snapshotOf, withHandover } from "./fixtures/github.mjs"; import { CODEX_NO_TOKENS } from "../../plugin/scripts/lib/usage.mjs"; import { PREVIOUS_NAME } from "../../plugin/scripts/lib/local.mjs"; +import { refusedMarker } from "../../plugin/scripts/lib/stop.mjs"; import { newForms } from "../../plugin/test/fixtures/progress-new-form.mjs"; const BENCH = join(import.meta.dirname, ".."); @@ -38,6 +39,101 @@ test("clean merge: walk-away yes, operator 0, Claude dollars from total_cost_usd assert.equal(row.mergedBy, "acme-pendulum[bot]"); }); +test("Draft removal starts the walk-away clock and workflow lookback; preparation and activation are not interventions", async () => { + const c = cleanMerge(42, usage("claude")); + const [filed, ...working] = c.issueTimeline; + const draft = { ...filed, label: { name: "pendulum:draft" } }; + const startAt = "2031-03-02T01:02:00Z"; + const start = { ...draft, created_at: startAt, event: "unlabeled" }; + const preparation = { user: OPERATOR, created_at: "2031-03-02T01:01:00Z", body: "Prep the acceptance wording." }; + c.issueTimeline = [filed, draft, start, ...working]; + c.issueComments.unshift(preparation); + let query; + await humanWorkflowRuns(async (path) => { + query = decodeURIComponent(path); + return []; + }, REPO, c.issue, c.issueTimeline, c.pulls); + assert.match(query, /created=2031-03-02T01:02:00Z\.\./); + const row = scoreObjective(c, { prices }); + assert.deepEqual([row.walkAway.since, row.walkAway.sinceBasis, row.walkAway.humanActions, row.walkAway.value, row.wallMinutes], [startAt, 'first removal of "pendulum:draft"', 0, true, 148]); + + const held = { ...c, issue: { ...c.issue, state: "open", closed_at: null, labels: [filed.label, draft.label] }, issueTimeline: [draft, filed], pulls: [] }; + const waiting = scoreObjective(held, { prices }); + assert.deepEqual([waiting.walkAway.since, waiting.wallMinutes, waiting.parked], [null, null, false]); + + const resumeAt = "2031-03-02T02:00:00Z"; + c.issueTimeline.push({ ...draft, created_at: "2031-03-02T01:45:00Z" }, { ...start, created_at: resumeAt }); + const resumed = scoreObjective(c, { prices }); + assert.deepEqual([resumed.walkAway.since, resumed.walkAway.humanActions, resumed.walkAway.value], [startAt, 2, false]); +}); + +test("issue-timeline order counts human actions after the exact activation in the same second", () => { + const c = cleanMerge(42, usage("claude")); + const [filed, ...working] = c.issueTimeline; + c.issue.created_at = filed.created_at; + const draft = { ...filed, label: { name: "pendulum:draft" } }; + const at = "2031-03-02T01:00:20Z"; + const held = { ...draft, created_at: at }; + const start = { ...held, event: "unlabeled" }; + const comment = (body) => ({ actor: OPERATOR, created_at: at, event: "commented", body }); + const ownerLabel = { ...filed, actor: c.issue.user, label: { name: "priority" }, created_at: "2031-03-02T01:00:40Z" }; + c.issueTimeline = [filed, draft, comment("Preparatory note"), start, comment("Change after start"), { ...held }, { ...start }, ownerLabel, ...working]; + const actions = humanActions(c, at); + assert.deepEqual(actions.map(({ kind, detail }) => [kind, detail]), [ + ["comment", "Change after start"], + ["labeled pendulum:draft", ""], + ["unlabeled pendulum:draft", ""], + ["labeled priority", ""], + ]); + assert.equal(scoreObjective(c, { prices }).walkAway.humanActions, 4); +}); + +test("legacy direct starts keep bundled filing metadata out of walk-away and count a later Draft hold", () => { + const c = cleanMerge(42, usage("claude")); + const [filed, ...working] = c.issueTimeline; + c.issue.created_at = filed.created_at; + const ownerLabel = (name, created_at = filed.created_at) => ({ ...filed, label: { name }, actor: c.issue.user, created_at }); + c.issueTimeline = [filed, ownerLabel("priority"), ownerLabel("pendulum:local"), ...working]; + assert.equal(scoreObjective(c, { prices }).walkAway.value, true); + + c.issueTimeline.splice(3, 0, ownerLabel("pendulum:draft", "2031-03-02T01:00:40Z")); + const row = scoreObjective(c, { prices }); + assert.deepEqual([row.walkAway.value, row.walkAway.humanActions, row.walkAway.firstHumanAction.kind], [false, 1, "labeled pendulum:draft"]); +}); + +test("only a Pendulum-owned refusal excludes the exact Draft removal from clock and workflow lookback", async () => { + const c = cleanMerge(42, usage("claude")); + const [filed, ...working] = c.issueTimeline; + const draft = { ...filed, label: { name: "pendulum:draft" } }; + const at = "2031-03-02T01:02:00Z"; + const rejected = { ...draft, id: 901, created_at: at, event: "unlabeled" }; + const chosen = { ...rejected, id: 902 }; + const bot = working.find((e) => e.label?.name === "pendulum:running").actor; + const refusal = (id, user) => ({ user, created_at: at, body: refusedMarker(c.issue.number, { id, at }) }); + c.issueTimeline = [filed, draft, rejected, { ...draft, created_at: at }, chosen, ...working]; + c.issueComments.unshift(refusal(901, bot), refusal(902, OPERATOR)); + const row = scoreObjective(c, { prices }); + assert.deepEqual([row.walkAway.since, row.walkAway.humanActions, row.walkAway.value], [at, 0, true]); + c.issueTimeline.splice(4, 1, { ...chosen, created_at: "2031-03-02T01:03:00Z" }); + let query; + await humanWorkflowRuns(async (path) => { + query = decodeURIComponent(path); + return []; + }, REPO, c.issue, c.issueTimeline, c.pulls, { comments: c.issueComments }); + assert.match(query, /created=2031-03-02T01:03:00Z\.\./); +}); + +test("missing Draft removal leaves the merged wall clock and walk-away unknown", () => { + const c = cleanMerge(42, usage("claude")); + const [filed, ...working] = c.issueTimeline; + c.issueTimeline = [filed, { ...filed, label: { name: "pendulum:draft" } }, ...working]; + const row = scoreObjective(c, { prices }); + assert.deepEqual([row.walkAway.since, row.walkAway.value, row.walkAway.askedOnly.value, row.walkAway.bucket, row.wallMinutes], [null, null, null, "unknown", null]); + assert.ok(row.missing.includes("Draft activation event")); + assert.equal(row.operator.minutes, "unknown"); + assert.match(summaryLine([row]), /Not known \(Draft activation was not recorded\), in no count: #42\./); +}); + test("human push: a maintainer's commit on the branch after the label breaks walk-away and names itself", () => { const row = scoreObjective(humanPush(43, usage("claude")), { prices, now: NOW }); assert.equal(row.exit, "merged"); diff --git a/bench/test/streak.test.mjs b/bench/test/streak.test.mjs index 35fcb004..017726ed 100644 --- a/bench/test/streak.test.mjs +++ b/bench/test/streak.test.mjs @@ -8,7 +8,7 @@ import { mkdtempSync, writeFileSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; -import { humanWorkflowRuns } from "../lib/collect.mjs"; +import { humanWorkflowRuns, listObjectives } from "../lib/collect.mjs"; import { loadPrices } from "../lib/cost.mjs"; import { humanActions, p1Escapes, scoreObjective } from "../lib/objective.mjs"; import { pooledStreak, pooledTable, streaks, streakTable, verdict } from "../lib/streak.mjs"; @@ -254,6 +254,30 @@ test("a parked Objective is a row: stopped when Blocked, in flight when its Ques assert.equal(score(blocked(72)).parked, false); }); +test("draft Objectives are collected only after activation when closed or after a stage when open", async () => { + const filed = "2031-03-01T00:00:00Z"; + const activated = "2031-03-02T00:00:00Z"; + const identity = "pendulum:objective"; + const draft = "pendulum:draft"; + const display = (number, state) => ({ number, state, closed_at: state === "closed" ? "2031-03-05T00:00:00Z" : null, labels: [identity, draft] }); + const label = (event, name, created_at) => ({ event, created_at, label: { name } }); + const filing = [label("labeled", identity, filed), label("labeled", draft, filed)]; + const afterStart = [...filing, label("unlabeled", draft, activated), label("labeled", "pendulum:running", activated), label("labeled", draft, "2031-03-04T00:00:00Z")]; + const rows = [display(80, "closed"), display(81, "open"), display(82, "closed"), display(83, "open"), display(84, "closed"), display(85, "closed")]; + const app = "pendulum-app[bot]"; + const refused = [...filing, { ...label("unlabeled", draft, activated), id: 123 }, + { event: "commented", body: "<!-- pendulum:84:relabel-refused:id-123 -->", user: { login: app } }, + label("labeled", draft, "2031-03-04T00:00:00Z")]; + const api = async (path) => { + if (path.includes("/issues?")) return rows; + const n = Number(/\/issues\/(\d+)\/(?:events|timeline)\?/.exec(path)?.[1]); + assert.ok(n >= 80 && n <= 85, path); + if (n === 85) return [...filing, label("labeled", "pendulum:running", activated)]; + return n === 84 ? refused : n < 82 ? filing : afterStart; + }; + assert.deepEqual(await listObjectives(api, REPO, { since: filed, app }), [82, 83, 85]); +}); + test("pooledStreak: two repositories' rows in the order they ended, any harness; any miss resets it", () => { const A = "acme/widgets"; const B = "acme/gadgets"; diff --git a/plugin/scripts/dispatch.mjs b/plugin/scripts/dispatch.mjs index b5544f94..572bb5cb 100644 --- a/plugin/scripts/dispatch.mjs +++ b/plugin/scripts/dispatch.mjs @@ -34,7 +34,8 @@ import { choiceOf } from "./lib/choice.mjs"; import { readHolds } from "./lib/route-holds.mjs"; import { accountWaitResume } from "./lib/account-wait.mjs"; import { startsOf } from "./lib/objective-trust.mjs"; -import { DRAFT_LABEL, RESTART_LABEL, STOP_GRACE_MS, applyStop, goNoted, goTrust, labelTrust, refusedMarker, requeuedIn, restartObjective, stopCause } from "./lib/stop.mjs"; +import { latestDraftEvent, RESUME_OBJECTIVE } from "./lib/activation.mjs"; +import { DRAFT_LABEL, DRAFT_ACTIVATION_REFUSED, RESTART_LABEL, STOP_GRACE_MS, applyStop, draftActivationHold, goNoted, goTrust, labelTrust, refusedMarker, requeuedIn, restartObjective, stopCause } from "./lib/stop.mjs"; import { RATE_LIMIT_SPENT, githubOrigin, quotaKey, spentUntil } from "./lib/network.mjs"; import { openAnswerCheck, screenAnswer } from "./lib/answer-check.mjs"; import { JOB_GRACE_MS, RELAUNCH_MAX, commentsOf, endedNotLost, jobEndedInStint, lastRunningAt, newStint, needsWorkStep, notLostBlock, outageBlockOf, personStart, relaunchDecision, setupAgain, relaunchRecordOf, relaunchRun, runningStint, stintKey, stintReads, stintRun, stintWorkJob, stintWorkStep, timelineOf, writeRelaunchRecord } from "./lib/relaunch.mjs"; @@ -67,7 +68,7 @@ const UNCLAIMED_MS = 5 * 60_000; const UNCLAIMED_SAID = new Map(); /** What a person does about a pendulum:local Objective no loop came back to for the claim pause (claim_pause_hours). */ -const SERVE_FIX = "start `pendulum serve` on the machine that runs it, then re-apply the label"; +const SERVE_FIX = "start `pendulum serve` on the machine that runs it, then resume through Draft"; /** * Today's spend (UTC day) against daily_usd: the spend lines every stage writes in its progress comment (backend.mjs @@ -247,7 +248,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not const from = stage === "review" ? "pendulum:in-review" : "pendulum:running"; issue.labels = [...(issue.labels || []).filter((l) => (typeof l === "string" ? l : l.name) !== from), { name: "pendulum:blocked" }]; log(` #${n}: its ${stage} launch (dispatcher run ${run}) unread for over a day (${read}: ${code}); Blocked`); - if (!dryRun) await blockLocalWait(n, null, `its ${stage} launch, named by dispatcher run ${run}, has been unknown for over a day: ${read} could not be read (${code}), so Pendulum cannot tell whether it started; re-apply the label once GitHub answers that read`, "pendulum"); + if (!dryRun) await blockLocalWait(n, null, `its ${stage} launch, named by dispatcher run ${run}, has been unknown for over a day: ${read} could not be read (${code}), so Pendulum cannot tell whether it started; resume through Draft once GitHub answers that read`, "pendulum"); }; // A launch grace for the Objective whose launch job just failed (its tick names it): the grace's end is a wake of // its own, not a wait for the cron, since that launch will not come. @@ -256,6 +257,11 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not if (!deadlines.some((d) => d.kind === "retry")) due(null, "retry", now.getTime() + RETRY_WAKE_MS); log(`${what} unread this tick; a retry is due`); }; + const draftRemovalUnread = (n, events) => { + if (latestDraftEvent(events)?.event !== "labeled") return false; + retry(`#${n}'s Draft removal`); + return true; + }; // The sandbox record of Objective n, as `{ record }` (null: none written), or null when its comments could not be // read: a failed read is no absent record, so the caller decides nothing on that Objective this tick (#430). const recordRead = async (n) => { @@ -272,11 +278,11 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not // Pendulum's note that a go was not taken (stop.mjs refusedMarker), once per go: one already on the timeline read here // costs no call. `stays`: the state the Objective keeps. const refuseGo = async (n, events, r, stays) => { - if (dryRun || goNoted(events, n, r.at)) return; + if (dryRun || goNoted(events, n, r)) return; const who = r.actor?.login || "someone"; const what = r.draft ? `\`${DRAFT_LABEL}\` taken off` : `\`${inputs.objectiveLabel}\` ${stays === "Queued" ? "applied" : "re-applied"}`; log(` #${n}: ${what} by ${who}, who cannot push and is no maintainer the workflow names: not taken`); - await upsertComment(repo, n, refusedMarker(n, r.at), `Pendulum: ${what} by ${who} was not taken, so the Objective stays ${stays}${stays === "Queued" ? " and does not run" : ""}: only someone who can push to this repository, or a maintainer the workflow names, can run it by applying \`${inputs.objectiveLabel}\`.`, opts).catch((e) => log(` #${n}: refusal note: ${String(e?.message || e).slice(0, 120)}`)); + await upsertComment(repo, n, refusedMarker(n, r), `Pendulum: ${what} by ${who} was not taken, so the Objective stays ${stays}${stays === "Queued" ? " and does not run" : ""}. Someone who can push to this repository, or a maintainer the workflow names, can ${RESUME_OBJECTIVE}.`, opts).catch((e) => log(` #${n}: refusal note: ${String(e?.message || e).slice(0, 120)}`)); }; // The Action's live jobs (work and review, by Objective), read at most once a tick for the restart and recovery passes; // a read that fails is `{failed}`. @@ -428,18 +434,22 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not } watch.mark("restart"); - // Recovery: a Blocked, Question or In-review issue (a PR closed unmerged by a human) - // whose pendulum:objective label was re-applied after it stopped is Queued again (the - // plan's "re-apply the label"). An explicit --issue from workflow_dispatch is the same - // human intent. Only a person who can push, or a pinned maintainer, gives that go (requeuedIn, mayGo): anyone else's - // re-apply changes nothing, and one comment on the issue says so. On the Action's route a Question's review job still - // running (its PR marked ready beside the label: review.mjs readyOwner stands it down) is waited for first, so the - // work stage never starts beside it. + // Recovery: a trusted activation after a Block, Question or In-review label puts the Objective back in Queued. + // Draft removal and legacy Objective label application use the same permission check (requeuedIn, mayGo), and an + // unauthorized activation gets one comment. An explicit --issue from workflow_dispatch counts as human intent. + // On Actions, a live Question review ends first (review.mjs readyOwner), so work never starts beside it. const reset = []; - // Objectives this pass decides nothing on this tick (who re-applied the label unread, a review job still running). + // Objectives this pass is waiting on this tick (unread activation or live review job). const recoveryWaits = new Set(); // Each timeline read here, kept for the relaunch pass below (its outage notice and record are on it too). const timelines = {}; + const draftHeld = async (n, events) => { + const hold = await draftActivationHold(events, n, inputs.objectiveLabel, mayGo); + if (!hold) return false; + log(` #${n}: ${hold}`); + if (hold !== DRAFT_ACTIVATION_REFUSED) retry(`#${n}'s Draft activation`); + return true; + }; for (const issue of wanted) { const n = issue.number; const state = stateOf(issue, statuses[n] ?? null); @@ -449,14 +459,19 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not if (!again) { timelines[n] = await timelineOf(repo, n, cached).catch(() => null); if (!timelines[n]) continue; + if (draftRemovalUnread(n, timelines[n])) { + recoveryWaits.add(n); + continue; + } const go = await requeuedIn(timelines[n], inputs.objectiveLabel, goTrust(timelines[n], n, mayGo)); if (go.unread) { recoveryWaits.add(n); - log(` #${n}: who re-applied ${inputs.objectiveLabel} could not be checked; next tick`); - retry(`#${n}'s re-apply permission`); + log(` #${n}: who requested activation could not be checked; next tick`); + retry(`#${n}'s activation permission`); continue; } for (const r of go.refused) await refuseGo(n, timelines[n], r, state); + if (go.refused.some((r) => r.draft)) recoveryWaits.add(n); again = go.requeued; goAt = go.at ?? null; } @@ -468,14 +483,14 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not const unreadPast = jobs.failed && (!goAt || githubNow() - Date.parse(goAt) >= STOP_GRACE_MS); if (jobs.failed && !unreadPast) { recoveryWaits.add(n); - log(` #${n}: ${inputs.objectiveLabel} re-applied, but the live jobs could not be read to see whether a review job of it runs; next tick`); + log(` #${n}: activation requested, but live jobs could not be read to see whether a review job of it runs; next tick`); retry("live jobs"); continue; } - if (unreadPast) log(` #${n}: the live jobs are still unread ${Math.round(STOP_GRACE_MS / 60_000)} min after ${inputs.objectiveLabel} was re-applied; requeued`); + if (unreadPast) log(` #${n}: the live jobs are still unread ${Math.round(STOP_GRACE_MS / 60_000)} min after activation was requested; requeued`); else if (jobs.review.has(n)) { recoveryWaits.add(n); - log(` #${n}: ${inputs.objectiveLabel} re-applied while a review job of it is running; requeued once it ends`); + log(` #${n}: activation requested while a review job of it is running; requeued once it ends`); retry(`#${n}'s review job`); continue; } @@ -636,7 +651,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not : (e.event === "labeled" || e.event === "unlabeled") && isSelf({ user: e.actor }) && recent(e.created_at), ); }; - const unreadReason = (hold, what) => `${what} for over ${pauseText} and its local claim cannot be read or checked (${hold.reason}); re-apply the label once GitHub answers that read`; + const unreadReason = (hold, what) => `${what} for over ${pauseText} and its local claim cannot be read or checked (${hold.reason}); resume through Draft once GitHub answers that read`; // In review with its review owed (an open PR, not a draft, labelled pendulum:review, or unlabelled with a third-party // wait record no review has taken up since: third-party-review.mjs): only a local loop runs that review, so it waits // as a Running one does, counted from the later of its entering In review and the PR's last pendulum:review label (a @@ -762,6 +777,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not } const block = outageBlockOf(commentsOf(events), n, lastRunningAt(events)); if (!block) continue; + if (await draftHeld(n, events)) continue; const d = await decideLost(n, events, { lost: "outage", key: block.key }); if (!d.block) { if (capHold(n)) continue; @@ -776,7 +792,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not relaunchesUsed.push(n); if (dryRun) continue; const pr = await findPr(repo, `pendulum/${n}`, opts).catch(() => null); - await applyExit(repo, { issue: n, pr, exit: "blocked", reason: why, fix: "Re-apply `pendulum:objective` once the runner's or the sandbox's network is back; the relaunch count starts over.", cause: "outage", notify: inputs.notify, stage: "relaunch" }, opts).catch((e) => { + await applyExit(repo, { issue: n, pr, exit: "blocked", reason: why, fix: "Resume through Draft once the runner's or the sandbox's network is back; the relaunch count starts over.", cause: "outage", notify: inputs.notify, stage: "relaunch" }, opts).catch((e) => { log(` #${n}: the Block could not be written (${String(e?.message || e).slice(0, 120)}); next tick tries again`); retry(`#${n}'s Block`); }); @@ -828,6 +844,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not leaseDue(issue.number, record); continue; } + if (await draftHeld(issue.number, await timeline())) continue; if (record?.waiting === "checks") { if (await checksFinished(issue.number, record)) { relaunch.push(issue.number); @@ -866,6 +883,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not // is away (asleep, off, serve stopped) for its serve to resume, Blocked once away for the claim pause. A read that // failed (the timeline, the claim or its author's check) is no answer: nothing rests on it, the next tick reads again. const read = (await timeline()) ? { at: lastRunningAt(events) } : null; + if (read && await draftHeld(issue.number, events)) continue; const hold = read && (await localWait(issue, read.at)); if (!read || (hold?.state === "unread" && !(backend().trigger.tends(issue) && (await unreadLapsed(issue.number, hold, read.at))))) { log(` #${issue.number}: ${read ? `local claim unread (${hold.reason})` : "Running time unread"}; left alone this tick`); @@ -1102,6 +1120,8 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not // A restart waiting for its stage to stop: nothing merges, updates or sends it back meanwhile. if (restarting[issue.number]) continue; if (stateOf(issue, statuses[issue.number] ?? null) !== "In review") continue; + timelines[issue.number] ??= await timelineOf(repo, issue.number, cached).catch(() => null); + if (await draftHeld(issue.number, timelines[issue.number])) continue; let prRead = true; const open = kept ? kept.open : await findPr(repo, `pendulum/${issue.number}`, opts).catch(() => ((prRead = false), null)); // Read once this tick: the sibling ordering below takes it rather than read it again (overlap.mjs prFinder). @@ -1122,7 +1142,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not log(` #${issue.number}: a split part merged; the next part is queued`); } else if (next === "cap") { statuses[issue.number] = "Blocked"; - await applyExit(repo, { issue: issue.number, pr: null, exit: "blocked", cause: "work", reason: `split into ${inputs.maxParts ?? MAX_PARTS} PRs and work still remains (max_parts); finish it by hand, narrow the issue or raise max_parts, then re-apply the label`, notify: inputs.notify, stage: "dispatch" }, opts); + await applyExit(repo, { issue: issue.number, pr: null, exit: "blocked", cause: "work", reason: `split into ${inputs.maxParts ?? MAX_PARTS} PRs and work still remains (max_parts); finish it by hand, narrow the issue or raise max_parts, then resume through Draft`, notify: inputs.notify, stage: "dispatch" }, opts); } continue; } @@ -1344,7 +1364,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not queueTimeout = await queueTimeoutMin(repo, opts); hungMs = queueHungMs(queueTimeout); } - const how = await mergeReadyOne(repo, { issue: issue.number, prNumber: open.number, queue, checkNames: inputs.ciChecks, report, hungMs, queueTimeout, actionsToken: backend().name === "local" ? null : inputs.githubToken || null, cache, stall: inputs.stall, objectiveLabel: inputs.objectiveLabel, issueData: issue, thirdParty: inputs.thirdPartyReviewers, editCheck: () => openEditCheck({ inputs }), commentCheck: () => openCommentCheck({ inputs }) }, opts).catch((e) => { + const how = await mergeReadyOne(repo, { issue: issue.number, prNumber: open.number, queue, checkNames: inputs.ciChecks, report, hungMs, queueTimeout, actionsToken: backend().name === "local" ? null : inputs.githubToken || null, cache, stall: inputs.stall, objectiveLabel: inputs.objectiveLabel, issueData: issue, issueEvents: timelines[issue.number], thirdParty: inputs.thirdPartyReviewers, editCheck: () => openEditCheck({ inputs }), commentCheck: () => openCommentCheck({ inputs }) }, opts).catch((e) => { log(` #${issue.number}: merge: ${String(e.message).slice(0, 160)}`); return null; }); @@ -1460,7 +1480,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not } // Who started each pick (its latest start: the label applied or the draft label taken off, objective-trust.mjs - // startsOf) must be a person who can push or a pinned maintainer (stop.mjs labelTrust), as for a re-apply above: one + // startsOf) must be a person who can push or a pinned maintainer (stop.mjs labelTrust), as for recovery above: one // anyone else started is held Queued, never run, with one note. Unread waits a tick. Checked on the picks alone, again // until every pick is one a person started; a requeue or restart this tick, or one named by hand, was a person's go. const startChecked = new Set([...reset, ...restarted, ...(inputs.issue ? [inputs.issue] : [])]); @@ -1471,7 +1491,13 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not retry(`#${n}'s timeline`); return "who started it is unread (its timeline); next tick"; } + if (draftRemovalUnread(n, events)) return "Draft removal is not yet visible on its timeline; next tick"; const start = startsOf(events, inputs.objectiveLabel)[0]; + const draft = latestDraftEvent(events); + if (draft && (!start || Date.parse(start.created_at) < Date.parse(draft.created_at))) { + retry(`#${n}'s Draft activation`); + return "its Draft removal has no matching Objective activation; next tick"; + } if (!start) return null; // A restart since (Pendulum's record of a person's restart, logic.mjs restartedAt) is the newer start, as personStart reads. const restart = restartedAt(commentsOf(events)); @@ -1482,7 +1508,7 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not retry(`#${n}'s start permission`); return "who started it could not be checked; next tick"; } - await refuseGo(n, events, { at: start.created_at, actor: start.actor ?? null, draft: start.event === "unlabeled" }, "Queued"); + await refuseGo(n, events, { at: start.created_at, id: start.id, actor: start.actor ?? null, draft: start.event === "unlabeled" }, "Queued"); return `started by ${start.actor?.login || "someone"}, who cannot push and is no maintainer the workflow names: not run`; }; const pick = () => diff --git a/plugin/scripts/launch.mjs b/plugin/scripts/launch.mjs index 6b038012..a021b773 100644 --- a/plugin/scripts/launch.mjs +++ b/plugin/scripts/launch.mjs @@ -30,7 +30,7 @@ import { workflowTokenChecks } from "./doctor.mjs"; import { mintInstallationToken } from "./lib/app-token.mjs"; import { harnessBudgetUsd, openSandbox, sessionCeilingUsd, stageVendorCost, storedUsd } from "./lib/adapters/sandbox.mjs"; import { PLUGIN_ROOT, pluginDigest } from "./lib/checkout.mjs"; -import { checksOn, findPr, findProject, getIssue, getPr, getRepo, graphql, listComments, moveCard, objectiveLabeledAt, primeWriters, projectStatuses, repoOf, requiredChecks, rest, runningSince, setStateLabel, upsertComment, verifyAuthors } from "./lib/github.mjs"; +import { checksOn, findPr, findProject, getIssue, getPr, getRepo, graphql, listComments, moveCard, objectiveLabeledAt, primeWriters, projectStatuses, repoOf, requiredChecks, rest, setStateLabel, upsertComment, verifyAuthors } from "./lib/github.mjs"; import { CLI, CODEX_LOGIN_REFUSED } from "./lib/harness.mjs"; import { DEFAULTS, SECRET_INPUTS, input, log, mask, parseArgs, resolveInputs, setOutput, workflowHarness } from "./lib/inputs.mjs"; import { clockText, whenText } from "./lib/clock.mjs"; @@ -49,7 +49,9 @@ import { READ_PERMISSIONS } from "./lib/token-keeper.mjs"; import { backend } from "./lib/backend.mjs"; import { unknownOf } from "./lib/usage.mjs"; import { sealCollected, sealKey, sealKeyProblem, usageSeal } from "./lib/seal.mjs"; -import { DRAFT_LABEL, RESTART_LABEL, stopCause } from "./lib/stop.mjs"; +import { DRAFT_LABEL, RESTART_LABEL, draftActivationHold, goTrust, labelTrust, requeuedIn, stopCause } from "./lib/stop.mjs"; +import { latestDraftEvent } from "./lib/activation.mjs"; +import { lastRunningAt, timelineOf } from "./lib/relaunch.mjs"; import { launcherDispatch } from "./lib/cross-os.mjs"; import { pendulumBuild } from "./lib/release.mjs"; @@ -100,7 +102,7 @@ export function missingCredential(inputs, account = null) { // An account's own secrets carry its suffix (lib/accounts.mjs routeSecretSuffix): the names its fix gives. const suffix = account ? routeSecretSuffix(account, inputs.harness) : ""; const names = (HARNESS_SECRET_NAMES[inputs.harness] ?? "for that harness").replace(/\b(ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN|PENDULUM_CODEX_GATEWAY_KEY|CODEX_API_KEY|COPILOT_GITHUB_TOKEN)\b/g, `$1${suffix}`); - return { reason: `no ${inputs.harness} credential${account ? ` of account \`${account}\`` : ""} reached the launch job, so a stage on ${inputs.harness} cannot run`, fix: `Add the repository secret ${names} (gh secret set NAME), which the workflow passes to the launch job, then re-apply \`pendulum:objective\`.` }; + return { reason: `no ${inputs.harness} credential${account ? ` of account \`${account}\`` : ""} reached the launch job, so a stage on ${inputs.harness} cannot run`, fix: `Add the repository secret ${names} (gh secret set NAME), which the workflow passes to the launch job, then resume through Draft.` }; } /** @@ -109,7 +111,7 @@ export function missingCredential(inputs, account = null) { */ export function refusedCredential(inputs) { if (inputs.harness !== "codex" || ![inputs.codexGatewayKey, inputs.codexApiKey].some(chatgptLogin)) return null; - return { reason: CODEX_LOGIN_REFUSED, fix: "Replace that secret's value with an OpenAI API key (or a Vercel AI Gateway key), then re-apply `pendulum:objective`." }; + return { reason: CODEX_LOGIN_REFUSED, fix: "Replace that secret's value with an OpenAI API key (or a Vercel AI Gateway key), then resume through Draft." }; } /** The GitHub context a stage's scripts read, as an Actions job has it. */ @@ -262,7 +264,7 @@ export async function readContext({ repo, n, ev, inputs, opts, readEventTime, ru // Read as GitHub has them, with no author's permission read: only Pendulum's own comments (isSelf, pendulumOwn) are // taken from them; the writer list is still loading beside them. rest(`repos/${repo.full}/issues/${n}/comments?per_page=100`, { ...opts, paginate: true }).then((c) => c || []), - due ? runningSince(repo, n, opts).catch(() => null) : null, + timelineOf(repo, n, opts).catch(() => null), due ? findPr(repo, `pendulum/${n}`, opts).then((pr) => reviewRequest(repo, pr, opts, { labelledOnly: true })).catch(() => null) : ev.kind === "review" && Number.isSafeInteger(ev.pr) @@ -282,11 +284,23 @@ export async function readContext({ repo, n, ev, inputs, opts, readEventTime, ru // Whether it may run is lib/stop.mjs stopCause's answer, as on every route: a draft (pendulum:draft) or a restart // pending (pendulum:restart) starts nothing either; the dispatcher restarts the latter first. const cause = issueData.pull_request ? "pull request" : stopCause(issueData, inputs.objectiveLabel); - const closed = !!cause; - if (closed && ev.kind !== "stage") return { skip: cause === "restart" ? `#${n} waits for its restart (${RESTART_LABEL})` : cause === "draft" ? `#${n} is a draft (${DRAFT_LABEL}): never run` : `#${n} is not an open ${inputs.objectiveLabel} issue` }; + if (cause && ev.kind !== "stage") return { skip: cause === "restart" ? `#${n} waits for its restart (${RESTART_LABEL})` : cause === "draft" ? `#${n} is a draft (${DRAFT_LABEL}): never run` : `#${n} is not an open ${inputs.objectiveLabel} issue` }; if (ev.kind !== "stage" && (await backend().trigger.stepsAside(repo, n, opts, issueData))) return { skip: `#${n} is held by a local loop` }; - const [{ project, card }, comments, since, review, headSha, at] = await reads; + const [{ project, card }, comments, events, review, headSha, at] = await reads; const state = stateOf(issueData, card); + // A stage's own cleanup can still collect usage and stop its sandbox when the Objective is held. + let hold = null; + if (!cause && (ev.kind !== "stage" || ev.want === "ended")) { + const draft = latestDraftEvent(events); + if (draft) await primeWriters(repo, opts, { maintainers: inputs.maintainers }); + const trusted = labelTrust(repo, opts); + hold = await draftActivationHold(events, n, inputs.objectiveLabel, trusted); + if (hold && ev.kind !== "stage") return { skip: `#${n}: ${hold}` }; + if (draft && ev.kind === "review" && ev.ready && state === "Question") { + const go = await requeuedIn(events, inputs.objectiveLabel, goTrust(events, n, trusted)); + if (go.requeued) return { skip: `#${n}: Draft activation since the Question requeues the work stage` }; + } + } const record = sandboxRecord(comments, n); // The sweep naming a stage that waits on CI (its check event lost): the branch's head now, and whether its checks are done. let head = headSha; @@ -296,7 +310,7 @@ export async function readContext({ repo, n, ev, inputs, opts, readEventTime, ru const names = inputs.ciChecks.length ? inputs.ciChecks : await requiredChecks(repo, opts).catch(() => []); checksDone = head === record.head && names.length > 0 && !!(await checksOn(repo, head, names, opts).catch(() => null))?.done; } - return { labels, project, state, closed, issueClosed: issueData.state !== "open", record, runningSince: since, review, headSha: head, checksDone, eventAt: at, comments }; + return { labels, project, state, closed: !!(cause || hold), issueClosed: issueData.state !== "open", record, runningSince: due ? lastRunningAt(events) : null, review, headSha: head, checksDone, eventAt: at, comments }; } /** @@ -1043,6 +1057,7 @@ function startCue(run, ctx, decision) { watch.mark("lock"); const now = await reread(run, ctx); watch.mark("reread"); + if (now.closed) return out({ exit: "skipped", reason: `#${n}: the Objective is held or closed` }); const again = now.skip ? { skip: now.skip } : decide(now, ev.kind === "stage" ? { kind: "swept", issue: n, at: null } : ev); if (again.stage !== stage) return out({ exit: "skipped", reason: `#${n}: under the lock the decision changed (${again.skip || again.stage || again.block || "requeue"})` }); // A cue whose start the record already shows (another launcher held the lock first and has released it) starts nothing again. @@ -1268,7 +1283,7 @@ async function quotaWait(run, ctx, { stage, error, quota }) { const freed = `Pendulum destroyed ${sandboxes} sandbox(es) and ${images} image(s) no live Objective needs${storage ? `; ${storageLine(storage)}` : ""}.`; if (quota.giveUp) { await dropQuotaNote(run); - return block(run, `launcher: the ${plain(inputs.sandbox)} sandbox's plan quota stayed used up (${code}) for ${quota.tries} tries over ${Math.round(quota.waitedMs / 60_000)} min after pruning; free the vendor's snapshot storage or raise its plan, then re-apply ${inputs.objectiveLabel}`, failedStartCause("quota")); + return block(run, `launcher: the ${plain(inputs.sandbox)} sandbox's plan quota stayed used up (${code}) for ${quota.tries} tries over ${Math.round(quota.waitedMs / 60_000)} min after pruning; free the vendor's snapshot storage or raise its plan, then resume through Draft`, failedStartCause("quota")); } const until = new Date(Date.parse(quota.since) + QUOTA_WAIT_MS).toISOString(); const note = `Pendulum: the ${stage} stage did not start: the ${plain(inputs.sandbox)} sandbox's plan quota is used up (${code}). ${freed} Snapshot storage is the part Pendulum frees. Try ${quota.tries} failed; the next is after ${clock(quota.retryAt)}. If the quota still refuses at ${clock(until)}, the Objective is handed back Blocked. Freeing the vendor's snapshot storage or raising its plan lets it start sooner.`; diff --git a/plugin/scripts/lib/accounts.mjs b/plugin/scripts/lib/accounts.mjs index 241c12dc..f640ca68 100644 --- a/plugin/scripts/lib/accounts.mjs +++ b/plugin/scripts/lib/accounts.mjs @@ -680,5 +680,5 @@ const statQuiet = (p) => { /** The Blocked reason for a declaration that cannot be used: the accounts' names alone, never a path or a value. */ export const accountReason = (problems) => { const names = [...new Set(problems.map((p) => p.account))]; - return `local mode: ${names.map((n) => `\`${n}\``).join(", ")} in this machine's account declaration cannot be used (account); the local loop's log says why; fix ~/.config/pendulum/accounts.json, then re-apply \`pendulum:objective\``; + return `local mode: ${names.map((n) => `\`${n}\``).join(", ")} in this machine's account declaration cannot be used (account); the local loop's log says why; fix ~/.config/pendulum/accounts.json, then resume through Draft`; }; diff --git a/plugin/scripts/lib/activation.mjs b/plugin/scripts/lib/activation.mjs new file mode 100644 index 00000000..1c67989e --- /dev/null +++ b/plugin/scripts/lib/activation.mjs @@ -0,0 +1,47 @@ +export const DRAFT_LABEL = "pendulum:draft"; + +/** The owner's workflow for continuing an existing Objective without changing its identity label. */ +export const RESUME_OBJECTIVE = `add \`${DRAFT_LABEL}\` if it is missing, then remove it to resume`; + +function labelToggles(events, labels) { + const seen = new Set(); + return (events || []).filter((e) => { + if ((e?.event !== "labeled" && e?.event !== "unlabeled") || !labels.includes(e.label?.name) || !Number.isFinite(Date.parse(e.created_at))) return false; + if (e.id === null || e.id === undefined) return true; + if (seen.has(e.id)) return false; + seen.add(e.id); + return true; + }).sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)); +} + +export const latestDraftEvent = (events) => labelToggles(events, [DRAFT_LABEL]).at(-1) ?? null; + +/** + * An Objective can run when its identity label is present and Draft is absent. New drafts are created with both + * labels, which GitHub can report in either order in the same second. A Draft application in that same second + * suppresses that identity event as a start. An old Objective label applied outside Draft still counts. + * `assumeObjective` applies when the caller already knows the issue is an Objective but the timeline contains no + * identity events. A recorded removal of the identity still stops it. Equal-time events keep their timeline order. + */ +export function activationEvents(events, label, { assumeObjective = false } = {}) { + const toggles = labelToggles(events, [label, DRAFT_LABEL]); + let objective = assumeObjective && !toggles.some((e) => e.label.name === label); + // Null allows the first observed removal when the earlier application is missing from the timeline. + let draft = null; + const starts = []; + for (const e of toggles) { + if (e.label.name === label) { + const applied = e.event === "labeled"; + if (applied && !objective && !draft) starts.push(e); + objective = applied; + } else if (e.event === "labeled") { + if (draft) continue; + draft = true; + while (starts.at(-1)?.label.name === label && Date.parse(starts.at(-1).created_at) === Date.parse(e.created_at)) starts.pop(); + } else { + if (draft !== false && objective) starts.push(e); + draft = false; + } + } + return starts; +} diff --git a/plugin/scripts/lib/answer-check.mjs b/plugin/scripts/lib/answer-check.mjs index 8d3741e4..24478237 100644 --- a/plugin/scripts/lib/answer-check.mjs +++ b/plugin/scripts/lib/answer-check.mjs @@ -14,6 +14,7 @@ // process, never in a harness: the notice and the comments are data between random-tag markers, never instructions. import { randomBytes } from "node:crypto"; import { homedir } from "node:os"; +import { RESUME_OBJECTIVE, activationEvents } from "./activation.mjs"; import { openDecider } from "./decider.mjs"; import { findProject, listComments, moveCard, primeSelf, setStateLabel, upsertComment } from "./github.mjs"; import { log, redactSecrets } from "./inputs.mjs"; @@ -202,8 +203,8 @@ export async function judgeAnswer({ check, repo, issue, comments, decisions, sin const conf = (c) => (typeof c === "number" ? `, confidence ${c.toFixed(2)}` : ""); /** The unanswered notice's text (judgeAnswer `open`): one per comment version judged, a Question notice of the same form. */ -export function unansweredNotice(open, { label = "pendulum:objective" } = {}) { - const how = open.form === "pr" ? "Answer it in a comment on the issue or the PR, then mark the PR ready." : `Answer it in a comment on the issue, or re-apply \`${label}\` to go on without an answer.`; +export function unansweredNotice(open) { + const how = open.form === "pr" ? "Answer it in a comment on the issue or the PR, then mark the PR ready." : `Answer it in a comment on the issue, or ${RESUME_OBJECTIVE} without an answer.`; return `Question still open: the comment by ${open.author} (${open.at}) does not give a decision on the Question above, as the decision model (${open.model}${conf(open.confidence)}) reads it. ${how}`; } @@ -211,7 +212,7 @@ export function unansweredNotice(open, { label = "pendulum:objective" } = {}) { * Post the unanswered notice on the issue, with Pendulum's own token (its login is what judgedOf trusts), `extra` at its * end (the decision calls' spend it carries, decision-spend.mjs). Throws on failure. */ -export const postUnanswered = (repo, open, { label, opts, extra = "" }) => upsertComment(repo, open.issue, unansweredMarker(open.issue, open), `${unansweredNotice(open, { label })}${extra}`, opts); +export const postUnanswered = (repo, open, { opts, extra = "" }) => upsertComment(repo, open.issue, unansweredMarker(open.issue, open), `${unansweredNotice(open)}${extra}`, opts); /** * The unanswered notice said again (judgeAnswer `judged` with its `notice`): the same comment, edited with the time @@ -259,17 +260,19 @@ export async function screenAnswer({ check, repo, issue, since, comments, decisi /** * When the Question this stint resumes was asked: the issue's last pendulum:question label, unless a Block, a delivery - * (a send-back's In review included), a restart or the objective label applied after it started the stint instead (a - * person's go needs no answer: a re-apply counts only from someone `trusted` takes as a person, stop.mjs requeuedIn's - * rule). `events` is the issue's timeline. Null when the stint resumes no Question. + * (a send-back's In review included), a restart, or a trusted activation started the stint after it. A person can + * explicitly resume work without an answer by removing Draft. Older Objective label applications count too. + * `events` is the issue's timeline. Null when the stint resumes no Question. */ export async function questionResumedAt(events, { objectiveLabel, trusted }) { const ends = new Set(["pendulum:blocked", "pendulum:in-review", RESTART_LABEL]); + const starts = new Set(activationEvents(events, objectiveLabel, { assumeObjective: true })); + const changes = (events || []).filter((e) => starts.has(e) || (e?.event === "labeled" && (e.label?.name === "pendulum:question" || ends.has(e.label?.name)))); let asked = null; - for (const e of [...(events || [])].filter((x) => x?.event === "labeled" && x.label?.name).sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at))) { + for (const e of changes.sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at))) { if (e.label.name === "pendulum:question") asked = e.created_at; else if (ends.has(e.label.name)) asked = null; - else if (asked && e.label.name === objectiveLabel && (await trusted(e.actor ?? null, e)) === true) asked = null; + else if (asked && (await trusted(e.actor ?? null, e)) === true) asked = null; } return asked; } diff --git a/plugin/scripts/lib/choice.mjs b/plugin/scripts/lib/choice.mjs index d1c8505f..94f7bbd5 100644 --- a/plugin/scripts/lib/choice.mjs +++ b/plugin/scripts/lib/choice.mjs @@ -67,12 +67,12 @@ export function choiceOf(names = []) { for (const kind of Object.keys(CHOICE_PREFIXES)) { const list = by[kind]; if (!list) continue; - if (list.length > 1) return { ok: false, labels, reason: `the issue has ${list.length} ${WHAT[kind]} labels (${list.map(tick).join(", ")}), so Pendulum cannot tell which one this Objective runs on`, fix: "Keep one of them, then re-apply `pendulum:objective`." }; + if (list.length > 1) return { ok: false, labels, reason: `the issue has ${list.length} ${WHAT[kind]} labels (${list.map(tick).join(", ")}), so Pendulum cannot tell which one this Objective runs on`, fix: "Keep one of them, then resume through Draft." }; const value = list[0].slice(CHOICE_PREFIXES[kind].length).trim(); - if (!value) return { ok: false, labels, reason: `${tick(list[0])} names no ${WHAT[kind]}`, fix: `Name one after the prefix (${tick(`${CHOICE_PREFIXES[kind]}<${kind === "harness" ? "name" : "id"}>`)}) or remove the label, then re-apply \`pendulum:objective\`.` }; + if (!value) return { ok: false, labels, reason: `${tick(list[0])} names no ${WHAT[kind]}`, fix: `Name one after the prefix (${tick(`${CHOICE_PREFIXES[kind]}<${kind === "harness" ? "name" : "id"}>`)}) or remove the label, then resume through Draft.` }; if (kind === "harness") { const h = value.toLowerCase(); - if (!HARNESSES.includes(h)) return { ok: false, labels, reason: `${tick(list[0])} names no harness Pendulum runs (${HARNESSES.join(", ")})`, fix: `Use \`pendulum:harness:claude\`, \`pendulum:harness:codex\` or \`pendulum:harness:copilot\`, then re-apply \`pendulum:objective\`.` }; + if (!HARNESSES.includes(h)) return { ok: false, labels, reason: `${tick(list[0])} names no harness Pendulum runs (${HARNESSES.join(", ")})`, fix: `Use \`pendulum:harness:claude\`, \`pendulum:harness:codex\` or \`pendulum:harness:copilot\`, then resume through Draft.` }; choice.harness = h; } else choice[kind] = value; } @@ -91,8 +91,8 @@ export function hostsOf(names = []) { for (const l of labels) { const host = l.slice(HOST_PREFIX.length).trim().toLowerCase(); const refusal = host.startsWith("*.") && isSandboxHost(host.slice(2)) ? wildcardRefusal(host.slice(2)) : null; - if (refusal) return { ok: false, labels, reason: `${tick(l)} opens every site under \`${host.slice(2)}\`, and the Public Suffix List names \`${refusal.rule}\` there a public suffix anyone can register a name under`, fix: `Name each host it needs, as \`pendulum:host:app.${host.slice(2)}\`, or remove the label, then re-apply \`pendulum:objective\`.` }; - if (!isSandboxHost(host)) return { ok: false, labels, reason: `${tick(l)} names no host Pendulum's sandboxes can allow`, fix: `Name one host after the prefix, as \`pendulum:host:example.com\` or \`pendulum:host:*.example.com\` (no scheme, port, path, IP address or localhost), or remove the label, then re-apply \`pendulum:objective\`.` }; + if (refusal) return { ok: false, labels, reason: `${tick(l)} opens every site under \`${host.slice(2)}\`, and the Public Suffix List names \`${refusal.rule}\` there a public suffix anyone can register a name under`, fix: `Name each host it needs, as \`pendulum:host:app.${host.slice(2)}\`, or remove the label, then resume through Draft.` }; + if (!isSandboxHost(host)) return { ok: false, labels, reason: `${tick(l)} names no host Pendulum's sandboxes can allow`, fix: `Name one host after the prefix, as \`pendulum:host:example.com\` or \`pendulum:host:*.example.com\` (no scheme, port, path, IP address or localhost), or remove the label, then resume through Draft.` }; hosts.add(host); } return { ok: true, hosts: [...hosts].sort(), labels }; @@ -158,7 +158,7 @@ export function chosenInputs({ args = {}, env = process.env, choice = {}, gatewa if (!m) continue; const p = modelProblem(r.harness, m, { gateway: viaGateway }); const label = choice[kind] ? `${CHOICE_PREFIXES[kind]}${m}` : `${CHOICE_PREFIXES.harness}${choice.harness}`; - if (p) return { ok: false, reason: `${tick(label)} asks ${r.harness} for a model it cannot run here${choice[kind] ? "" : ` (its ${WHAT[kind]}, ${tick(m)})`}: ${p.reason}`, fix: `${p.fix} Then re-apply \`pendulum:objective\`.` }; + if (p) return { ok: false, reason: `${tick(label)} asks ${r.harness} for a model it cannot run here${choice[kind] ? "" : ` (its ${WHAT[kind]}, ${tick(m)})`}: ${p.reason}`, fix: `${p.fix} Then resume through Draft.` }; } return { ok: true, inputs: Object.fromEntries(CHOSEN_FIELDS.map((k) => [k, r[k]])) }; } @@ -177,7 +177,7 @@ export const harnessVersionFor = (harness, defaultHarness, version) => (harness export function routeProblem(prepared, harness) { const p = String(prepared ?? "").trim().toLowerCase(); if (!p || p === harness) return null; - return { reason: `this stage was prepared for ${p} (its CLI, credential and sandbox) but the Objective now runs on ${harness}: its harness label changed while the stage started`, fix: "Re-apply `pendulum:objective`: the next stage is prepared for the harness the labels name." }; + return { reason: `this stage was prepared for ${p} (its CLI, credential and sandbox) but the Objective now runs on ${harness}: its harness label changed while the stage started`, fix: "Resume through Draft: the next stage is prepared for the harness the labels name." }; } /** @@ -206,5 +206,5 @@ export function hostsProblem(prepared, hosts = []) { if (prepared === undefined || prepared === null) return null; const was = [...new Set(String(prepared).split(",").map((h) => h.trim()).filter(Boolean))].sort(); if (was.join(",") === [...hosts].sort().join(",")) return null; - return { reason: `this stage's sandboxes were set up for the hosts ${was.length ? was.map(tick).join(", ") : "of no host label"} but the Objective's host labels now name ${hosts.length ? hosts.map(tick).join(", ") : "none"}: a \`pendulum:host:\` label changed while the stage started`, fix: "Re-apply `pendulum:objective`: the next stage's sandboxes are set up for the hosts the labels name." }; + return { reason: `this stage's sandboxes were set up for the hosts ${was.length ? was.map(tick).join(", ") : "of no host label"} but the Objective's host labels now name ${hosts.length ? hosts.map(tick).join(", ") : "none"}: a \`pendulum:host:\` label changed while the stage started`, fix: "Resume through Draft: the next stage's sandboxes are set up for the hosts the labels name." }; } diff --git a/plugin/scripts/lib/continue.mjs b/plugin/scripts/lib/continue.mjs index a5772724..caf2bcaf 100644 --- a/plugin/scripts/lib/continue.mjs +++ b/plugin/scripts/lib/continue.mjs @@ -12,7 +12,7 @@ import { basename, join, resolve } from "node:path"; import { decisionsShown } from "./logic.mjs"; /** Why a fresh work stage Blocks (cause setup) when its clone's untracked leftovers could not be removed: no local path. */ -export const CLEAN_REFUSED = "local mode: the untracked files an earlier stage left in the Objective's clone could not be removed, so the work stage does not run on them; the local loop's log has the error. Fix it on that machine, then re-apply the Objective's label."; +export const CLEAN_REFUSED = "local mode: the untracked files an earlier stage left in the Objective's clone could not be removed, so the work stage does not run on them; the local loop's log has the error. Fix it on that machine, then resume through Draft."; /** What a continued stage needs unchanged since its pause, by the key its record and the decision use. */ export const CONTINUE_GUARDS = { branch: "the branch on GitHub", restart: "the newest restart record", running: "the Objective's Running stint", text: "the Objective's text" }; diff --git a/plugin/scripts/lib/cross-os.mjs b/plugin/scripts/lib/cross-os.mjs index 6edfcdbb..81149798 100644 --- a/plugin/scripts/lib/cross-os.mjs +++ b/plugin/scripts/lib/cross-os.mjs @@ -48,13 +48,13 @@ export const crossOsRoute = (env = process.env) => stageRoute(env) ?? "actions"; export function dispatchRefusal(e, { workflow, branch, route = "actions" }) { const status = e?.status ?? null; const head = `cross-OS CI: GitHub refused to run ${workflow} on ${branch}${status ? ` (${status})` : ""}`; - if (e?.rateLimited) return { reason: `${head}: rate limited; re-apply the label once the limit resets`, cause: "provider-quota" }; + if (e?.rateLimited) return { reason: `${head}: rate limited; resume through Draft once the limit resets`, cause: "provider-quota" }; if (status === 403) { const fix = route === "sandbox" ? "the launcher dispatches it for a cloud sandbox stage with its job token: give the workflow's launch-event job `actions: write`" : route === "local" ? "give the repository token Actions read and write" : "give the workflow's work job `actions: write`"; - return { reason: `${head}: the token cannot dispatch a workflow (Actions write); ${fix}, then re-apply the label`, cause: "setup" }; + return { reason: `${head}: the token cannot dispatch a workflow (Actions write); ${fix}, then resume through Draft`, cause: "setup" }; } - if (status === 404) return { reason: `${head}: no workflow .github/workflows/${workflow} on the default branch; fix cross_os_workflow, then re-apply the label`, cause: "setup" }; - if (status === 422) return { reason: `${head}: ${String(e?.message || "").replace(/^.*?failed \(422\): /, "").slice(0, 200)}; give the workflow a \`workflow_dispatch:\` trigger, then re-apply the label`, cause: "setup" }; + if (status === 404) return { reason: `${head}: no workflow .github/workflows/${workflow} on the default branch; fix cross_os_workflow, then resume through Draft`, cause: "setup" }; + if (status === 422) return { reason: `${head}: ${String(e?.message || "").replace(/^.*?failed \(422\): /, "").slice(0, 200)}; give the workflow a \`workflow_dispatch:\` trigger, then resume through Draft`, cause: "setup" }; return { reason: `${head}: ${String(e?.message || e).slice(0, 200)}`, cause: "outage" }; } @@ -168,10 +168,10 @@ export function crossOsChecks({ setting, repo, issue, prNumber, branch, token, a try { doc = parseYaml(String(await rest(`repos/${repo.full}/contents/.github/workflows/${encodeURIComponent(workflow)}?ref=${sha}`, { token: actionsToken, raw: "Accept: application/vnd.github.raw+json" }))); } catch (e) { - return e.status === 404 ? refused(`no workflow .github/workflows/${workflow} on ${sha.slice(0, 7)}; fix cross_os_workflow, then re-apply the label`) : refused(`.github/workflows/${workflow} could not be read on ${sha.slice(0, 7)}: ${String(e.message || e).slice(0, 160)}`, e.status === 403 ? "setup" : "outage"); + return e.status === 404 ? refused(`no workflow .github/workflows/${workflow} on ${sha.slice(0, 7)}; fix cross_os_workflow, then resume through Draft`) : refused(`.github/workflows/${workflow} could not be read on ${sha.slice(0, 7)}: ${String(e.message || e).slice(0, 160)}`, e.status === 403 ? "setup" : "outage"); } const problem = workflowProblem(doc, workflow); - if (problem) return refused(`${problem}; fix the workflow, then re-apply the label`); + if (problem) return refused(`${problem}; fix the workflow, then resume through Draft`); const h = { id: null, run: null, suites: new Set(), since: 0 }; // A cloud sandbox stage: its launcher dispatches the run (or reuses one on the head) and names it. if (route === "sandbox") { @@ -179,8 +179,8 @@ export function crossOsChecks({ setting, repo, issue, prNumber, branch, token, a // The relay's own bound, within what is left of the stage's wall clock. const boundMs = Math.min(RELAY_WAIT_MS, Number.isFinite(left) ? left : Infinity); const a = relay ? await relay({ workflow, ref: branch, sha, boundMs }) : null; - if (!a) return refused(`the stage has no channel to its launcher, which dispatches the run for a cloud sandbox stage; re-apply the label`, "pendulum"); - if (a.timedOut) return refused(`the launcher gave no run for the stage's request to run ${workflow} on ${sha.slice(0, 7)} within ${Math.round(boundMs / 60_000)} min; check the workflow's launch-event job runs, then re-apply the label`, "outage"); + if (!a) return refused(`the stage has no channel to its launcher, which dispatches the run for a cloud sandbox stage; resume through Draft`, "pendulum"); + if (a.timedOut) return refused(`the launcher gave no run for the stage's request to run ${workflow} on ${sha.slice(0, 7)} within ${Math.round(boundMs / 60_000)} min; check the workflow's launch-event job runs, then resume through Draft`, "outage"); if (a.refused) return { refused: a.refused }; heads.set(sha, h); if (a.run) { @@ -213,7 +213,7 @@ export function crossOsChecks({ setting, repo, issue, prNumber, branch, token, a const run = await rest(`repos/${repo.full}/actions/runs/${id}`, actions).catch(() => null); if (run?.head_sha && run.head_sha !== sha) { heads.delete(sha); - return refused(`the run GitHub made (${id}) is on ${String(run.head_sha).slice(0, 7)}, not on ${sha.slice(0, 7)}: ${branch} moved; re-apply the label`, "pendulum"); + return refused(`the run GitHub made (${id}) is on ${String(run.head_sha).slice(0, 7)}, not on ${sha.slice(0, 7)}: ${branch} moved; resume through Draft`, "pendulum"); } if (run?.id === id) track(h, run); } @@ -231,8 +231,8 @@ export function crossOsChecks({ setting, repo, issue, prNumber, branch, token, a const failed = runs.filter((r) => r.status === "completed" && !["success", ...NOT_RUN].includes(r.conclusion) && !setting.checks.includes(r.name)); const what = skipped.map((l) => `${l.n} ${l.r.conclusion}`).join("; "); return failed.length - ? { reason: `cross-OS CI: ${what} on ${sha.slice(0, 7)}, so ${skipped.length > 1 ? "they" : "it"} did not run: the run's job ${failed.map((r) => `${r.name} ended ${r.conclusion}`).join(", ")} first; read that job on GitHub, fix the branch, then re-apply the label`, cause: "work" } - : { reason: `cross-OS CI: ${what} on ${sha.slice(0, 7)}, so ${skipped.length > 1 ? "they" : "it"} did not run; run the leg on workflow_dispatch in ${workflow}, then re-apply the label`, cause: "setup" }; + ? { reason: `cross-OS CI: ${what} on ${sha.slice(0, 7)}, so ${skipped.length > 1 ? "they" : "it"} did not run: the run's job ${failed.map((r) => `${r.name} ended ${r.conclusion}`).join(", ")} first; read that job on GitHub, fix the branch, then resume through Draft`, cause: "work" } + : { reason: `cross-OS CI: ${what} on ${sha.slice(0, 7)}, so ${skipped.length > 1 ? "they" : "it"} did not run; run the leg on workflow_dispatch in ${workflow}, then resume through Draft`, cause: "setup" }; }, resultLine: (sha, runs) => legsLine({ workflow, names: setting.checks, sha, runs }), }; @@ -343,13 +343,13 @@ export async function launcherDispatch({ inputs, repo, issue, ask = {}, token, a const passing = (e) => !e?.status || e.status >= 500 || !!e.rateLimited; const pause = () => new Promise((r) => setTimeout(r, pauseMs)); const { setting } = crossOs(inputs); - if (!setting) return no("the launcher's settings have cross-OS CI off (cross_os_workflow, cross_os_checks), so it dispatches nothing; set both in the workflow's env block, then re-apply the label", "setup"); + if (!setting) return no("the launcher's settings have cross-OS CI off (cross_os_workflow, cross_os_checks), so it dispatches nothing; set both in the workflow's env block, then resume through Draft", "setup"); const { workflow } = setting; // A stage that read another setting than the launcher's (cross_os_workflow changed while it ran) asks for another file. - if (ask.workflow !== workflow) return no(`the stage asked the launcher for another workflow than ${workflow}, the one cross_os_workflow names in the launcher's settings and the only one it dispatches; when that setting changed while the stage ran, re-apply the label`, "setup"); - if (ask.ref !== branch) return no(`the stage asked the launcher for another ref than its branch ${branch}, the only one it dispatches on; re-apply the label`); - if (!sha) return no(`the stage asked the launcher with no head; re-apply the label`); - if (!actionsToken) return no(`the launch job has no token of its own (github_token) to dispatch ${workflow} with; give the workflow's launch-event job \`actions: write\`, then re-apply the label`, "setup"); + if (ask.workflow !== workflow) return no(`the stage asked the launcher for another workflow than ${workflow}, the one cross_os_workflow names in the launcher's settings and the only one it dispatches; when that setting changed while the stage ran, resume through Draft`, "setup"); + if (ask.ref !== branch) return no(`the stage asked the launcher for another ref than its branch ${branch}, the only one it dispatches on; resume through Draft`); + if (!sha) return no(`the stage asked the launcher with no head; resume through Draft`); + if (!actionsToken) return no(`the launch job has no token of its own (github_token) to dispatch ${workflow} with; give the workflow's launch-event job \`actions: write\`, then resume through Draft`, "setup"); const app = { token, noRateWait: true }; const actions = { token: actionsToken, noRateWait: true }; let head; @@ -357,19 +357,19 @@ export async function launcherDispatch({ inputs, repo, issue, ask = {}, token, a head = (await rest(`repos/${repo.full}/git/ref/heads/${branch}`, app))?.object?.sha ?? null; } catch (e) { if (passing(e)) return again; - if (e.status !== 404) return no(`${branch} could not be read (${e.status}); re-apply the label`, "setup"); + if (e.status !== 404) return no(`${branch} could not be read (${e.status}); resume through Draft`, "setup"); head = null; } - if (head !== sha) return no(`${branch} is ${head ? `at ${head.slice(0, 7)}` : "gone"}, not at ${sha.slice(0, 7)}, the head the stage asked for: the branch moved; re-apply the label`); + if (head !== sha) return no(`${branch} is ${head ? `at ${head.slice(0, 7)}` : "gone"}, not at ${sha.slice(0, 7)}, the head the stage asked for: the branch moved; resume through Draft`); let doc; try { doc = parseYaml(String(await rest(`repos/${repo.full}/contents/.github/workflows/${encodeURIComponent(workflow)}?ref=${sha}`, { ...app, raw: "Accept: application/vnd.github.raw+json" }))); } catch (e) { if (passing(e)) return again; - return e.status === 404 ? no(`no workflow .github/workflows/${workflow} on ${sha.slice(0, 7)}; fix cross_os_workflow, then re-apply the label`, "setup") : no(`.github/workflows/${workflow} could not be read on ${sha.slice(0, 7)} (${e.status})`, "setup"); + return e.status === 404 ? no(`no workflow .github/workflows/${workflow} on ${sha.slice(0, 7)}; fix cross_os_workflow, then resume through Draft`, "setup") : no(`.github/workflows/${workflow} could not be read on ${sha.slice(0, 7)} (${e.status})`, "setup"); } const problem = workflowProblem(doc, workflow); - if (problem) return no(`${problem}; fix the workflow, then re-apply the label`, "setup"); + if (problem) return no(`${problem}; fix the workflow, then resume through Draft`, "setup"); const listRuns = async () => ((await rest(`repos/${repo.full}/actions/runs?head_sha=${sha}&event=workflow_dispatch&per_page=100`, actions)) || {}).workflow_runs || []; const newest = (runs) => runs.sort((a, b) => String(b.created_at || "").localeCompare(String(a.created_at || "")) || b.id - a.id)[0] || null; // A run dispatched on this head already (an earlier ask whose answer was lost or named no suite, a second launcher): @@ -378,7 +378,7 @@ export async function launcherDispatch({ inputs, repo, issue, ask = {}, token, a try { runs = await listRuns(); } catch (e) { - return passing(e) ? again : no(`the launch job's token could not list ${workflow}'s runs (${e.status}); give the workflow's launch-event job \`actions: write\`, then re-apply the label`, "setup"); + return passing(e) ? again : no(`the launch job's token could not list ${workflow}'s runs (${e.status}); give the workflow's launch-event job \`actions: write\`, then resume through Draft`, "setup"); } const before = newest(runs.filter((w) => dispatchedRun(w, workflow, sha))); if (before) return { sha, run: before.id, suite: id(before.check_suite_id), reused: true }; @@ -397,7 +397,7 @@ export async function launcherDispatch({ inputs, repo, issue, ask = {}, token, a if (i) await pause(); run = (await rest(`repos/${repo.full}/actions/runs/${runId}`, actions).catch(() => null)) ?? run; // GitHub made it on another head (the branch moved after the read above): refused, and left to finish. - if (run?.head_sha && run.head_sha !== sha) return no(`the run GitHub made (${runId}) is on ${String(run.head_sha).slice(0, 7)}, not on ${sha.slice(0, 7)}: ${branch} moved; re-apply the label`); + if (run?.head_sha && run.head_sha !== sha) return no(`the run GitHub made (${runId}) is on ${String(run.head_sha).slice(0, 7)}, not on ${sha.slice(0, 7)}: ${branch} moved; resume through Draft`); } return { sha, run: runId, suite: id(run?.check_suite_id) }; } diff --git a/plugin/scripts/lib/finish-card.mjs b/plugin/scripts/lib/finish-card.mjs index b330fc78..c10fae0d 100644 --- a/plugin/scripts/lib/finish-card.mjs +++ b/plugin/scripts/lib/finish-card.mjs @@ -15,7 +15,7 @@ // comment by someone else who can push counts as a run of unknown cost, never its dollars; anyone else's counts nothing. import { pendulumBuild } from "./release.mjs"; -import { DRAFT_LABEL } from "./stop.mjs"; +import { activationEvents, DRAFT_LABEL, latestDraftEvent, RESUME_OBJECTIVE } from "./activation.mjs"; import { DEFAULTS } from "./inputs.mjs"; import { clockText, objectiveZone, timeZone, zoneDay, zoneOffsetMs } from "./clock.mjs"; import { stageHarnessOf } from "./cost-join.mjs"; @@ -24,6 +24,7 @@ import { checkRuns, getPr, listComments, listReviewComments, ownRunArtifact, pri import { RUNNING_LABEL, STATE_LABELS, blockCauseOf, bodyFindings, decisionSpendEntries, isPlaceholder, isSelf, ledgerOfComment, marker, githubWriter, rebaseCostOf, restartedAt, selfLogin, spendParts } from "./logic.mjs"; import { pendulumNotice } from "./answer-check.mjs"; import { sanitize } from "./handoff.mjs"; +import { goNoted } from "./stop.mjs"; import { BASIS, BASIS_NOTE, COLORS, basisText, billingBasis, billingWords, causeSentences, cellCost, centsOf, costChart, costText, durationText, ganttChart, kindsOf, many, modelId, modelName, plainText, tableCell } from "./card-kit.mjs"; // The shared look's helpers this module has always exported (card-kit.mjs holds them now). @@ -41,21 +42,32 @@ const SECOND = 1000; /** - * The Objective's clock, as the scorecard starts it (bench/lib/objective.mjs reads it from here): its first - * `pendulum:objective` label at or after `clockAfter`, or the first time Pendulum picked it up (its Running label) if - * that came first, so a recovery's re-applied label is never mistaken for its start. A draft's clock is the last of its - * label's applications and its draft label's removals before Pendulum first picked it up. Null with neither label event. + * The first activation since `clockAfter`, shared with the scorecard. If the matching start did not survive in the + * timeline, use the first Running label before any later recovery only if this window has no unaccounted-for Draft. + * Pendulum's own refusal records identify activation events that did not start work. */ -export function labelTime(issue, timeline, label = OBJECTIVE, clockAfter = null) { +export function clockStart(timeline = [], label = OBJECTIVE, clockAfter = null, { issue, comments = [], mine = isSelf } = {}) { const floor = clockAfter ? ms(clockAfter) : Number.NEGATIVE_INFINITY; - const events = (timeline || []).filter((e) => e.event === "labeled" && (e.label?.name === label || e.label?.name === RUNNING_LABEL) && ms(e.created_at) >= floor).sort((a, b) => ms(a.created_at) - ms(b.created_at)); - const first = events[0]?.created_at ?? null; - if (!first || !(timeline || []).some((e) => e.event === "labeled" && e.label?.name === DRAFT_LABEL)) return first; - const running = events.find((e) => e.label?.name === RUNNING_LABEL)?.created_at ?? null; - const starts = (timeline || []).filter((e) => ((e.event === "labeled" && e.label?.name === label) || (e.event === "unlabeled" && e.label?.name === DRAFT_LABEL)) && ms(e.created_at) >= ms(first) && (!running || ms(e.created_at) <= ms(running))); - return starts.map((e) => e.created_at).sort((a, b) => ms(a) - ms(b)).at(-1) ?? first; + const history = timeline || []; + const markers = [...(comments || []), ...history.filter((e) => e.event === "commented")]; + const events = activationEvents(history, label); + const refused = (e) => !!issue && goNoted(markers, issue, { at: e.created_at, id: e.id }, mine); + const start = events.find((e) => ms(e.created_at) >= floor && !refused(e)); + const running = history.filter((e) => e.event === "labeled" && e.label?.name === RUNNING_LABEL && ms(e.created_at) >= floor).sort((a, b) => ms(a.created_at) - ms(b.created_at))[0]; + if (!running) return start ?? null; + const runningAt = ms(running.created_at); + const runningIndex = history.indexOf(running); + const byRunning = (e, index) => ms(e.created_at) < runningAt || (ms(e.created_at) === runningAt && index <= runningIndex); + if (start && byRunning(start, history.indexOf(start))) return start; + if (events.some((e) => ms(e.created_at) >= floor && byRunning(e, history.indexOf(e)) && refused(e))) return null; + const draft = latestDraftEvent(history.filter(byRunning)); + if (draft && (ms(draft.created_at) >= floor || !events.includes(draft) || refused(draft))) return null; + return running; } +export const labelTime = (issue, timeline, label = OBJECTIVE, clockAfter = null, options) => + clockStart(timeline, label, clockAfter, { issue: issue?.number, ...options })?.created_at ?? null; + /** * Whether the issue's clock started before the rename to Pendulum (#567): a label event named exactly * `<previous name>:objective` or `<previous name>:running` (local.mjs PREVIOUS_NAME), the name GitHub keeps on the events @@ -69,6 +81,7 @@ export const CLOCK_WHY = Object.freeze(["renamed"]); /** Why a card's wall clock is not known (clockRenamed), as the card says it. */ export const RENAMED_CLOCK_WHY = "its wall clock is not known: it was labelled before the rename to Pendulum"; +const UNRECORDED_ACTIVATION_WHY = "its wall clock is not known because its activation was not recorded"; /** * Whether a comment, review or PR is Pendulum's own, whose markers the card trusts: by the login this process writes as @@ -284,7 +297,7 @@ export function objectiveStages({ issue: n, comments = [], records = [], mine = /** * Where an Objective's run starts over (#517): the latest of its restart record (`pendulum:restart`, logic.mjs * restartedAt) and its reopening (the timeline's `reopened` event), or null. The finish card's clock starts at the - * first label at or after it, and max_objective_usd counts from it. + * first activation or proved start at or after it, and max_objective_usd counts from it. */ export function objectiveWindow(comments = [], timeline = []) { const times = [restartedAt(comments), ...(timeline || []).filter((e) => e?.event === "reopened").map((e) => e.created_at)].filter((t) => Number.isFinite(ms(t))); @@ -528,8 +541,10 @@ export function finishData({ repo, issue, timeline = [], comments = [], pulls = // Objective's branch (open, a draft, or closed unmerged). const open = other ? pulls.filter((p) => p?.pr?.number && !p.pr.merged_at).slice(-1) : []; const shown = [...merged, ...open]; - // The clock: the first label at or after the run's last start over (a restart or a reopen), max_objective_usd's window too. - const started = labelTime(issue, timeline, label, objectiveWindow(comments.filter((c) => mine(c)), timeline)) ?? shown[0]?.pr.created_at ?? endAt; + // The clock starts at the first activation after the most recent restart or reopen. + const window = objectiveWindow(comments.filter((c) => mine(c)), timeline); + const start = clockStart(timeline, label, window, { issue: n, comments, mine }); + const started = start?.created_at ?? window ?? shown[0]?.pr.created_at ?? endAt; const inRun = (at) => ms(at) >= ms(started) && ms(at) <= ms(endAt); const own = comments.filter((c) => mine(c)).sort((a, b) => ms(a.created_at) - ms(b.created_at)); // Which merged part a stage worked on: the parts merged before it started (a split Objective's PRs merge in order). @@ -582,8 +597,7 @@ export function finishData({ repo, issue, timeline = [], comments = [], pulls = findings += (reviewComments || []).filter((c) => ids.has(c.pull_request_review_id) && !c.in_reply_to_id && !isPlaceholder(c.body)).length; } - // Who filed the issue, and who applied the label that started the clock (its latest application by then). - const labelled = (timeline || []).filter((e) => e.event === "labeled" && e.label?.name === label && ms(e.created_at) <= ms(started)).sort((a, b) => ms(a.created_at) - ms(b.created_at)).at(-1); + const startKind = start?.label.name === DRAFT_LABEL ? "draft" : start?.label.name === label ? "objective" : start ? "running" : null; const sum = (k) => shown.reduce((s, p) => s + (Number.isInteger(p.pr[k]) ? p.pr[k] : 0), 0); const holds = apart([...blockedWaits({ repo, timeline, blockers, started, stages }), ...holdsOf(n, own.filter((c) => inRun(noticeAt(c))), stages)]); const closer = (timeline || []).filter((e) => e.event === "closed").sort((a, b) => ms(a.created_at) - ms(b.created_at)).at(-1)?.actor?.login; @@ -591,7 +605,8 @@ export function finishData({ repo, issue, timeline = [], comments = [], pulls = repo, issue: n, author: login(issue.user?.login), - labeller: login(labelled?.actor?.login), + labeller: login(startKind === "draft" || startKind === "objective" ? start.actor?.login : null), + startKind, prs: shown.map((p) => ({ number: p.pr.number, url: p.pr.html_url ?? `https://github.com/${repo}/pull/${p.pr.number}`, opened: p.pr.created_at, merged: p.pr.merged_at ?? null, ours: mine(p.pr), draft: p.pr.draft === true, open: p.pr.state === "open" && !p.pr.merged_at })), started, merged: mergedAt, @@ -608,10 +623,11 @@ export function finishData({ repo, issue, timeline = [], comments = [], pulls = // each Blocked or Question notice and each paused stage until the next stage started, no time in two of them (apart). holds, planned: own.some((c) => (c.body || "").startsWith(marker(n, "plan")) && inRun(c.created_at)), - // The scorer's start of the clock: the first label with no restart window (labelTime), null with no label event. - labelled: labelTime(issue, timeline, label), + // The scorecard's first activation without the restart window. + labelled: labelTime(issue, timeline, label, null, { comments, mine }), // Labelled before the rename to Pendulum: no wall clock (clockRenamed). clockRenamed: clockRenamed(timeline), + clockActivationMissing: !start && latestDraftEvent(timeline) !== null, commits: sum("commits"), additions: sum("additions"), deletions: sum("deletions"), @@ -666,7 +682,7 @@ export function finishTotals(d) { // No stage found at all: the run's cost was not read, so it is unknown, never $0. const unknown = d.stages.reduce((s, x) => s + (x.unknown || 0), 0) + (d.sandbox?.unknown ?? 0) + (d.stages.length ? 0 : 1); const why = [...new Set([...d.stages.flatMap((x) => (x.unknown ? x.why ?? [] : [])), ...sandboxWhy(d), ...(d.stages.length ? [] : ["no-record"])])].sort(); - const wall = d.clockRenamed ? null : ms(d.ended ?? d.merged) - ms(d.started); + const wall = d.clockRenamed || d.clockActivationMissing ? null : ms(d.ended ?? d.merged) - ms(d.started); const waited = waitedMs(d); return { wall, waited, worked: wall === null ? null : Math.max(0, wall - waited), usd: Math.round(usd * 1e6) / 1e6, unknown, why, byBilling: addBilling(...d.stages.map((s) => s.byBilling)) }; } @@ -722,7 +738,10 @@ export function subline(d) { const basis = t.usd > 0 ? basisText(t.usd, t.byBilling) || BASIS.unknown : ""; if (basis) parts.push(basis); if (t.unknown) parts.push(`plus ${many(t.unknown, "AI run")} of unknown cost`); - if (t.wall === null) parts.push(`${RENAMED_CLOCK_WHY[0].toUpperCase()}${RENAMED_CLOCK_WHY.slice(1)}`); + if (t.wall === null) { + const why = d.clockRenamed ? RENAMED_CLOCK_WHY : UNRECORDED_ACTIVATION_WHY; + parts.push(`${why[0].toUpperCase()}${why.slice(1)}`); + } return parts.join(" · "); } @@ -747,7 +766,7 @@ function holdLine(d) { by.set(words, (by.get(words) ?? 0) + (ms(h.end) - ms(h.start))); } const waits = listed([...by].map(([words, took]) => `${durationText(took)} ${words}`)); - const span = t.wall === null ? "" : `; ${durationText(t.wall)} from the label to ${{ merged: "the merge", closed: "the close", blocked: "the Block", question: "the Question" }[d.end]}`; + const span = t.wall === null ? "" : `; ${durationText(t.wall)} from ${d.startKind === "draft" ? "Draft removal" : "the label"} to ${{ merged: "the merge", closed: "the close", blocked: "the Block", question: "the Question" }[d.end]}`; return `Waited ${waits}${span}.`; } @@ -766,7 +785,7 @@ function actionLines(d) { const reason = String(d.reason ?? "").replace(/^question:\s*/i, ""); if (d.end === "blocked") { // Its way on (session.mjs nextStep): one that no resume or restart gets past is said so; any other is fixed, then resumed. - const todo = d.next === "none" ? "a resume or a restart does not get past this; the Blocked notice on this issue says why." : "fix the cause below, then re-apply the `pendulum:objective` label. The Blocked notice on this issue has the full steps."; + const todo = d.next === "none" ? "a resume or a restart does not get past this; the Blocked notice on this issue says why." : `fix the cause below, then ${RESUME_OBJECTIVE}. The Blocked notice on this issue has the full steps.`; return [`> **What to do:** ${todo}`, ">", `> **Why:** ${oneLine(reason.split(/(?<=[.!?])\s/)[0])}`]; } if (d.end === "question") { @@ -779,7 +798,8 @@ function actionLines(d) { /** Who did what, and what Pendulum did, in plain sentences: only what the records say. */ export function summary(d) { - const person = d.author && d.labeller ? (d.author === d.labeller ? "You wrote the issue and added the label." : `**${d.author}** wrote the issue and **${d.labeller}** added the label.`) : d.author ? `**${d.author}** wrote the issue.` : ""; + const act = d.startKind === "draft" ? "removed the Draft label to start it" : "added the label"; + const person = d.author && d.labeller ? (d.author === d.labeller ? `You wrote the issue and ${act}.` : `**${d.author}** wrote the issue and **${d.labeller}** ${act}.`) : d.author ? `**${d.author}** wrote the issue.` : ""; const did = []; if (d.planned) did.push("planned the work"); const change = `${many(d.commits, "commit")}, +${d.additions} −${d.deletions} across ${many(d.files, "file")}`; @@ -1049,7 +1069,11 @@ function runLog(d) { const day = spansDays(d); const zone = zoneOf(d); const at = (t) => clockText(ms(t), { zone, seconds: true, date: day, abbr: false }); - const out = [[d.started, "labelled `pendulum:objective`: the clock starts"]]; + const start = d.startKind === "draft" ? "removed `pendulum:draft`: the clock starts" + : d.startKind === "running" ? "marked Running: the first record of the start" + : d.startKind === null ? "the first recorded point of the run" + : "labelled `pendulum:objective`: the clock starts"; + const out = [[d.started, start]]; for (const s of d.stages) { if (!s.start) continue; const name = stageName(s, d.planned).toLowerCase(); @@ -1151,8 +1175,8 @@ export const reportStageKind = (kind) => (kind === "review" || kind === "rebase" * records, which are no pass and are counted apart as the report counts them, report.mjs foldPasses, #617; null as * `passes` is), `modelMinutes` (the minutes of every harness pass, null unless * `passes` is known and each harness pass has its times), `tokens` (every stage's, summed), and `labelled` and - * `labelledWallMs` (the scorer's start of the clock, the first `pendulum:objective` label with no restart window, and the - * wall clock from it to the merge; null with no label event, or one labelled before the rename to Pendulum: clockRenamed), + * `labelledWallMs` (the first activation with no restart window, and the wall clock from it to the merge; null with + * no clock event, or one labelled before the rename to Pendulum: clockRenamed), * and `clockWhy`, why the wall clock is not known when that is the rename (`renamed`; null otherwise), so a reader takes * it from the card (#587) rather than from the shape of its other fields. */ @@ -1525,7 +1549,8 @@ export async function postFinishCard(repo, issue, opts, { records = async () => // Question card stands over an older end of this kind. const stands = (had) => !!had && (had.end === "merged" || (had.end === "closed" && ending?.kind === "closed" && (!had.at || ms(had.at) >= ms(ending.at))) || (ending && had.end !== "closed" && !!had.at && ms(had.at) > ms(ending.at))); if (stands(cardsOf(comments)[0] && finishEndOf(cardsOf(comments)[0].body, n))) return "had"; - const started = labelTime(issue, timeline, label, objectiveWindow(comments.filter((c) => mine(c)), timeline)); + const window = objectiveWindow(comments.filter((c) => mine(c)), timeline); + const started = labelTime(issue, timeline, label, window, { comments, mine }) ?? window; // The PRs to read whole: the Objective's merged PRs since its clock (a split Objective's parts), oldest first; at another // end, then, the newest unmerged one on its branch. const sinceClock = (p) => !started || ms(p.merged_at) >= ms(started); diff --git a/plugin/scripts/lib/logic.mjs b/plugin/scripts/lib/logic.mjs index fdca9653..3a2588ae 100644 --- a/plugin/scripts/lib/logic.mjs +++ b/plugin/scripts/lib/logic.mjs @@ -149,7 +149,7 @@ export function protectedCovers(rule, path) { */ export function protectedReason(hits) { const why = `touched protected path ${hits.join(", ")}`; - return hits.every((h) => h.startsWith(WORKFLOWS_DIR)) ? `${why}; Pendulum never pushes a workflow file: the worker hands the change over in $PENDULUM_OUT/workflow.patch (pendulum-deliver-pr), so re-apply the label to rerun` : why; + return hits.every((h) => h.startsWith(WORKFLOWS_DIR)) ? `${why}; Pendulum never pushes a workflow file: the worker hands the change over in $PENDULUM_OUT/workflow.patch (pendulum-deliver-pr), so resume through Draft to rerun` : why; } /** @@ -687,7 +687,7 @@ export function fenceDecidable(entry, { extra = [], unknown = [], protectedList * what the fence check said of the files it was asked about (`<path>: <why>`, outbox.mjs box.fenceVerdict). */ export const fixScopeReason = (files, unknown = [], judged = []) => - `a fix pass changed ${files.slice(0, 5).join(", ")}${files.length > 5 ? ` and ${files.length - 5} more` : ""} (toolchain, lockfile or CI configuration), which neither the plan nor the failing check names${judged.length ? `; the fence check: ${judged.slice(0, 3).join("; ")}${judged.length > 3 ? `; and ${judged.length - 3} more` : ""}` : ""}; to allow it, name the file in the issue or a maintainer comment and re-apply pendulum:objective${unknown.length ? `. The setup or install command runs ${unknown.slice(0, 3).join(", ")}${unknown.length > 3 ? ` and ${unknown.length - 3} more` : ""}, which Pendulum cannot resolve to repository files, so every file counts as one it may run; name each file literally in the command, or move the command into a script file` : ""}`; + `a fix pass changed ${files.slice(0, 5).join(", ")}${files.length > 5 ? ` and ${files.length - 5} more` : ""} (toolchain, lockfile or CI configuration), which neither the plan nor the failing check names${judged.length ? `; the fence check: ${judged.slice(0, 3).join("; ")}${judged.length > 3 ? `; and ${judged.length - 3} more` : ""}` : ""}; to allow it, name the file in the issue or a maintainer comment and resume through Draft${unknown.length ? `. The setup or install command runs ${unknown.slice(0, 3).join(", ")}${unknown.length > 3 ? ` and ${unknown.length - 3} more` : ""}, which Pendulum cannot resolve to repository files, so every file counts as one it may run; name each file literally in the command, or move the command into a script file` : ""}`; /** * The Blocked reason for a push GitHub refused because it would create or update a workflow file, which a token @@ -697,10 +697,10 @@ export const fixScopeReason = (files, unknown = [], judged = []) => */ export const workflowScopeReason = ({ branch, defaultBranch, paths = [], own = [] }) => { const list = (p) => `${p.slice(0, 3).join(", ")}${p.length > 3 ? ` and ${p.length - 3} more` : ""}`; - if (own.length) return `push rejected (workflow scope): GitHub refused ${branch} because it changes ${list(own)}, and Pendulum's token may not create or update workflow files; the worker hands a workflow change over in $PENDULUM_OUT/workflow.patch instead (pendulum-deliver-pr), so re-apply the label to rerun`; - if (paths.length) return `push rejected (workflow scope): GitHub refused ${branch} because its ${list(paths)} is not the version ${defaultBranch} has, and Pendulum's token may not create or update workflow files; bring the branch up to date with ${defaultBranch} (re-apply the label to rerun)`; + if (own.length) return `push rejected (workflow scope): GitHub refused ${branch} because it changes ${list(own)}, and Pendulum's token may not create or update workflow files; the worker hands a workflow change over in $PENDULUM_OUT/workflow.patch instead (pendulum-deliver-pr), so resume through Draft to rerun`; + if (paths.length) return `push rejected (workflow scope): GitHub refused ${branch} because its ${list(paths)} is not the version ${defaultBranch} has, and Pendulum's token may not create or update workflow files; bring the branch up to date with ${defaultBranch} (resume through Draft to rerun)`; // The branch's workflow files match the default branch as Pendulum last read it: it moved again before the push. - return `push rejected (workflow scope): GitHub refused ${branch} for a workflow file Pendulum's token may not create or update, though its workflow files matched ${defaultBranch} when Pendulum read it; ${defaultBranch} likely changed one again during the push (re-apply the label to rerun)`; + return `push rejected (workflow scope): GitHub refused ${branch} for a workflow file Pendulum's token may not create or update, though its workflow files matched ${defaultBranch} when Pendulum read it; ${defaultBranch} likely changed one again during the push (resume through Draft to rerun)`; }; /** @@ -969,7 +969,7 @@ export const AGENT_MODELS = Object.freeze({ function subAgentRefusalReason(r, fields) { const pin = Object.hasOwn(AGENT_MODELS, r.subAgent) ? AGENT_MODELS[r.subAgent] : null; const who = r.subAgent ? `its \`${r.subAgent}\` sub-agent` : "a sub-agent"; - const fix = pin ? `the ${pin.what} model, which a \`${pin.label}<id>\` label on the issue (else ${pin.variable}) chooses: name a model this login serves, then re-apply \`pendulum:objective\`` : "the agent's own model: name one this login serves in the agent's file, or fix the credential's account"; + const fix = pin ? `the ${pin.what} model, which a \`${pin.label}<id>\` label on the issue (else ${pin.variable}) chooses: name a model this login serves, then resume through Draft` : "the agent's own model: name one this login serves in the agent's file, or fix the credential's account"; return `${r.harness} was refused by its provider for ${who}${fields ? ` (${fields})` : ""}${r.message ? `: ${clip(r.message)}` : ""}; the run was stopped, since the main session would go on without that work. The fix is ${fix}`; } @@ -993,8 +993,8 @@ export function usageLimitReason(r, { waited = false } = {}) { const fields = refusalFields(r); const reset = Number.isFinite(r.resetAt) ? whenText(r.resetAt) : null; const why = `${r.harness} reached its subscription's usage limit${fields ? ` (${fields})` : ""}${reset ? `, which resets at ${reset}` : ", with no reset time reported"}`; - if (waited) return `${why}; the stage waited for the reset until its time ran out. Re-apply the label to run it again.`; - return `${why}; not run again on another model, since every model of the subscription draws on the same limit. Re-apply the label ${reset ? "after the reset" : "once the limit has reset"}.`; + if (waited) return `${why}; the stage waited for the reset until its time ran out. Resume through Draft to run it again.`; + return `${why}; not run again on another model, since every model of the subscription draws on the same limit. Resume through Draft ${reset ? "after the reset" : "once the limit has reset"}.`; } /** A Question from the worker's exit record: its first question, else the generic line. */ @@ -1037,11 +1037,11 @@ export function deniedHostsFix(hosts, domains = [], route = "local") { const tick = (h) => `\`${h}\``; const labels = left.map((h) => `pendulum:host:${h}`).filter((l) => l.length <= 50); const short = labels.length < left.length ? " (the rest are too long for a label)" : ""; - const alone = labels.length ? `a person who can push applies ${labels.map(tick).join(", ")} to this issue${short}, which opens ${labels.length === 1 ? "it" : "them"} to this Objective alone, then re-applies \`pendulum:objective\`. To open ${them} to every Objective, ` : ""; + const alone = labels.length ? `a person who can push applies ${labels.map(tick).join(", ")} to this issue${short}, which opens ${labels.length === 1 ? "it" : "them"} to this Objective alone, then resumes through Draft. To open ${them} to every Objective, ` : ""; // On Actions and in a cloud sandbox, each harness's sandbox: the workflow's `allowed_domains` input (harness.mjs // claudeRunner, codexRunner, copilotRunner). const setting = route === "runner" ? "the Pendulum workflow's `allowed_domains` input (or `PENDULUM_ALLOWED_DOMAINS` in its env block)" : "`PENDULUM_LOCAL_DOMAINS` (a running `serve` reads it when it restarts)"; - return `${route === "runner" ? "The harness's sandbox" : "The local sandbox"} denied ${left.map(tick).join(", ")}. If the Objective needs ${them}, ${alone}add ${them} to ${setting}, then re-apply \`pendulum:objective\`.`; + return `${route === "runner" ? "The harness's sandbox" : "The local sandbox"} denied ${left.map(tick).join(", ")}. If the Objective needs ${them}, ${alone}add ${them} to ${setting}, then resume through Draft.`; } /** diff --git a/plugin/scripts/lib/objective-cap.mjs b/plugin/scripts/lib/objective-cap.mjs index f31b036b..402e806a 100644 --- a/plugin/scripts/lib/objective-cap.mjs +++ b/plugin/scripts/lib/objective-cap.mjs @@ -13,7 +13,7 @@ import { logTime } from "./clock.mjs"; import { marker, spendText } from "./logic.mjs"; /** What fixes a cap Block: the setting raised or unset, then the label. */ -export const CAP_FIX = "Fix by raising `max_objective_usd` (the workflow's `PENDULUM_MAX_OBJECTIVE_USD`, or a repository variable of that name) above the total, or by unsetting it, then re-apply `pendulum:objective`; a `pendulum:restart` starts the count over."; +export const CAP_FIX = "Fix by raising `max_objective_usd` (the workflow's `PENDULUM_MAX_OBJECTIVE_USD`, or a repository variable of that name) above the total, or by unsetting it, then resume through Draft; a `pendulum:restart` starts the count over."; /** "; 2 runs of unknown cost count nothing toward it", or "" for none. */ const unknownWords = (n) => (n > 0 ? `; ${n} run${n === 1 ? "" : "s"} of unknown cost count${n === 1 ? "s" : ""} nothing toward it` : ""); diff --git a/plugin/scripts/lib/objective-trust.mjs b/plugin/scripts/lib/objective-trust.mjs index d847343c..1333192a 100644 --- a/plugin/scripts/lib/objective-trust.mjs +++ b/plugin/scripts/lib/objective-trust.mjs @@ -12,7 +12,8 @@ import { createHash } from "node:crypto"; import { collaboratorPermission, getIssue, graphql, issueTextChangedAt, labelersOf, primeSelf, rest } from "./github.mjs"; import { log } from "./inputs.mjs"; import { keptLine } from "./edit-check.mjs"; -import { DRAFT_LABEL, goTrust, labelTrust } from "./stop.mjs"; +import { activationEvents, RESUME_OBJECTIVE } from "./activation.mjs"; +import { goTrust, labelTrust } from "./stop.mjs"; import { choiceLabels, choiceOf, chosenInputs, foundationLabel, hostsOf, hostsProblem, isChoiceLabel, routeProblem } from "./choice.mjs"; import { planComment, planTextMarker, stampPlan } from "./handoff.mjs"; import { waitOnAccounts } from "./account-wait.mjs"; @@ -102,9 +103,9 @@ export async function objectiveTrusted(repo, issue, opts, { what = "Pendulum act * changes it, so only a new issue fixes an untrusted author; an untrusted last edit is fixed by a writer saving the body. */ export const AUTHOR_FIX = { - author: "Editing this issue cannot fix that, since its author is checked on every run: a person who can push files the Objective as a new issue and labels that one `pendulum:objective`.", - "last editor": "Fix by having a person who can push read the body and save it (they become its last editor), then re-apply `pendulum:objective`.", - "title renamer": "Fix by having a person who can push read the title and change it (saving the same title records no rename; they become its latest renamer), then re-apply `pendulum:objective`.", + author: "Editing this issue cannot fix that because its author is checked on every run. A person who can push files the Objective as a new issue and starts it.", + "last editor": `Fix by having a person who can push read the body and save it (they become its last editor), then ${RESUME_OBJECTIVE}.`, + "title renamer": `Fix by having a person who can push read the title and change it (saving the same title records no rename; they become its latest renamer), then ${RESUME_OBJECTIVE}.`, }; /** @@ -134,20 +135,15 @@ export async function authorGate({ repo, issue, issueData, pr = null, notify, op /** The Blocked reason and fix when the Objective's text changed after its plan was made (planGate). */ export const EDITED_REASON = "the Objective's title, body or harness, model and host labels (`pendulum:harness:`, `pendulum:model:`, `pendulum:subagent-model:`, `pendulum:reviewer-model:`, `pendulum:host:`) changed after its plan was made, and its plan and code follow the earlier ones, so Pendulum does not go on with the two mixed"; -export const EDITED_FIX = "Re-apply `pendulum:objective` to work from the issue as it is now, its text and its harness, model and host labels: the worker makes its plan again from it, on the same branch and PR."; +export const EDITED_FIX = `To work from the issue as it is now, ${RESUME_OBJECTIVE}. The worker makes its plan again from the current text and harness, model and host labels, on the same branch and PR.`; /** Pendulum's own login, read once (logic.mjs selfLogin): unknown, no plan comment could be told apart, so a stage stops. */ export async function knowSelf(opts) { if (!selfLogin() && !(await primeSelf(opts))) throw new Error("Pendulum's own login could not be read, so its plan comment cannot be told from anyone else's"); } -const isStart = (e, label) => ((e?.event === "labeled" && e.label?.name === label) || (e?.event === "unlabeled" && e.label?.name === DRAFT_LABEL)) && Number.isFinite(Date.parse(e.created_at)); - -/** - * The Objective's start events on its timeline, newest first: its label applied, and the draft label taken off (a draft - * is started by taking that label off, its Objective label on or not). - */ -export const startsOf = (events, label) => (events || []).filter((e) => isStart(e, label)).sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); +/** The Objective's activation events, newest first, for a caller that already knows this is an Objective. */ +export const startsOf = (events, label) => activationEvents(events, label, { assumeObjective: true }).reverse(); /** * When a person last started the Objective, from its timeline events: the latest start (startsOf) whose actor `trusted` @@ -332,7 +328,7 @@ export async function editedSincePlan(repo, issue, opts, { gh = { graphql }, rea } /** What a Blocked notice tells a person to do about a harness, model or foundation label Pendulum did not act on. */ -export const CHOICE_FIX = "A person who can push removes the label and applies it again, or removes it to run this Objective without it (on the repository's defaults, with the one-pass review), then re-applies `pendulum:objective`."; +export const CHOICE_FIX = `Have a person who can push remove the choice label and apply it again, or leave it off to use the repository's defaults and one-pass review. Then ${RESUME_OBJECTIVE}.`; /** * The harness, model and host labels among `names` (the issue's, read with its text) as Pendulum may act on them: @@ -435,12 +431,12 @@ export async function routeAccountCheck({ repo, issue, harness, labels = [], env // Two account labels: the Objective waits until one is left, never Blocked for it (the caller's wait, account-wait.mjs). if (r.two) return { wait: r.two }; if (r.problem) return { refusal: { reason: `${r.problem}, so no stage of it starts`, fix: ROUTE_PIN_FIX } }; - if (!prepared) return { refusal: { reason: "this repository declares accounts (PENDULUM_ACCOUNTS), but its workflow was not rendered for them, so this stage holds no account's credential: its jobs pass the secrets of the accounts setup rendered them for, by name", fix: "Re-render the workflow (`/pendulum:pendulum-setup`, or setup --apply workflow) after every change to PENDULUM_ACCOUNTS: it names each declared account's secrets in the jobs and passes each stage only its account's. Merge it, then re-apply `pendulum:objective`." } }; + if (!prepared) return { refusal: { reason: "this repository declares accounts (PENDULUM_ACCOUNTS), but its workflow was not rendered for them, so this stage holds no account's credential: its jobs pass the secrets of the accounts setup rendered them for, by name", fix: `Re-render the workflow (\`/pendulum:pendulum-setup\`, or setup --apply workflow) after every change to PENDULUM_ACCOUNTS: it names each declared account's secrets in the jobs and passes each stage only its account's. Merge it, then ${RESUME_OBJECTIVE}.` } }; // The account step ran and could pick none (its labels then could not be used), so it passed no credential. - if (prepared === NO_ACCOUNT) return { refusal: { reason: `the job's account step picked no account, so this stage holds no account's credential; the labels now pick \`${r.account.name}\`: its account label changed while the stage started`, fix: "Re-apply `pendulum:objective`: the next stage gets the credential of the account its labels pick." } }; + if (prepared === NO_ACCOUNT) return { refusal: { reason: `the job's account step picked no account, so this stage holds no account's credential; the labels now pick \`${r.account.name}\`: its account label changed while the stage started`, fix: `After checking the account label, ${RESUME_OBJECTIVE}. The next stage gets the credential of the account its labels pick.` } }; // Automatic account choice (#268): with no pin, the step picks any declared account of the harness (route-holds.mjs). if (prepared !== r.account.name && !r.label && routeAutoAccounts(env, harness)?.includes(prepared)) return { account: prepared, note: "", pinned: false }; - if (prepared !== r.account.name) return { refusal: { reason: `this stage was prepared with account \`${prepared}\`'s credential, but the Objective's labels now pick \`${r.account.name}\`: its account label changed while the stage started`, fix: "Re-apply `pendulum:objective`: the next stage gets the credential of the account its labels pick." } }; + if (prepared !== r.account.name) return { refusal: { reason: `this stage was prepared with account \`${prepared}\`'s credential, but the Objective's labels now pick \`${r.account.name}\`: its account label changed while the stage started`, fix: `After checking the account label, ${RESUME_OBJECTIVE}. The next stage gets the credential of the account its labels pick.` } }; return { account: r.account.name, note: "", pinned: !!r.label }; } @@ -498,8 +494,8 @@ export async function accountGate({ repo, issue, harness, labels = [], env = pro await apply(repo, { issue, pr, exit: "blocked", reason: c.refusal.reason, fix: c.refusal.fix, cause: "setup", notify, stage }, opts); return { ok: false, reason: c.refusal.reason }; } -const ACCOUNTS_FIX = 'Fix PENDULUM_ACCOUNTS in .github/workflows/pendulum.yml: re-render it with setup\'s --accounts set to a JSON object of each harness\'s account names, such as {"claude": ["claude", "claude-2"]}, and merge it (docs/INSTALL.md, Several accounts), then re-apply `pendulum:objective`.'; -const ROUTE_PIN_FIX = "A person who can push removes the account label, or applies one naming an account PENDULUM_ACCOUNTS declares for the Objective's harness, then re-applies `pendulum:objective`."; +const ACCOUNTS_FIX = `Fix PENDULUM_ACCOUNTS in .github/workflows/pendulum.yml: re-render it with setup's --accounts set to a JSON object of each harness's account names, such as {"claude": ["claude", "claude-2"]}, and merge it (docs/INSTALL.md, Several accounts), then ${RESUME_OBJECTIVE}.`; +const ROUTE_PIN_FIX = `Have a person who can push remove the account label or apply one naming an account PENDULUM_ACCOUNTS declares for the Objective's harness. Then ${RESUME_OBJECTIVE}.`; export async function choiceGate({ repo, issue, labels, args = {}, env = process.env, pr = null, notify, opts, apply, before = null, stage, gh }) { const t = await choiceTrusted(repo, issue, labels, opts, gh); diff --git a/plugin/scripts/lib/one-repo.mjs b/plugin/scripts/lib/one-repo.mjs index 45caa77f..7bc2eaac 100644 --- a/plugin/scripts/lib/one-repo.mjs +++ b/plugin/scripts/lib/one-repo.mjs @@ -81,10 +81,10 @@ const ONE_REPO = "Pendulum works in one repository per Objective"; * The Question for an issue body that names another repository (declaredRepos), or "": asked before any harness runs. * The owner splits the Objective, one per repository, takes the line out and re-applies `label`. */ -export function declaredQuestion(body, { source, label = "pendulum:objective" }) { +export function declaredQuestion(body, { source }) { const repos = declaredRepos(body, source); if (!repos.length) return ""; - return `the issue names ${repos.join(", ")} on a ${DECLARE_KEY} line, and ${ONE_REPO}; split it into one Objective per repository (this one changes only ${source.full}), remove the line and re-apply ${label}`; + return `the issue names ${repos.join(", ")} on a ${DECLARE_KEY} line, and ${ONE_REPO}; split it into one Objective per repository (this one changes only ${source.full}), remove the line and resume through Draft`; } /** @@ -114,8 +114,8 @@ export function answeredRepos(asked, decisions, { named = true } = {}) { * owner splits the Objective, one per repository, and re-applies `label`, or answers in a comment how to do the work in * this repository alone. `repos` are the ones asked about, recorded so the answer is recognised on the rerun. */ -export function planNeeds(plan, { source, label = "pendulum:objective", answered = new Set() }) { +export function planNeeds(plan, { source, answered = new Set() }) { const missing = plannedRepos(plan).repos.filter((r) => key(r) !== key(source.full) && !answered.has(key(r))); if (!missing.length) return {}; - return { repos: missing, reason: `the plan needs a change in ${missing.join(", ")}, and ${ONE_REPO}; split it into one Objective per repository and re-apply ${label}, or answer in a comment how to do the work in ${source.full} alone` }; + return { repos: missing, reason: `the plan needs a change in ${missing.join(", ")}, and ${ONE_REPO}; split it into one Objective per repository and resume through Draft, or answer in a comment how to do the work in ${source.full} alone` }; } diff --git a/plugin/scripts/lib/progress-card.mjs b/plugin/scripts/lib/progress-card.mjs index b98b7f3d..ed2520bb 100644 --- a/plugin/scripts/lib/progress-card.mjs +++ b/plugin/scripts/lib/progress-card.mjs @@ -14,6 +14,7 @@ // byte for byte: its header, its `- <time> <text>` lines with their hidden UTC stamps). The card itself never writes a // line that starts `- ` and a clock, nor "min at the last line". import { clockText, timeZone, zoneDay } from "./clock.mjs"; +import { RESUME_OBJECTIVE } from "./activation.mjs"; import { AGENTS, BASIS_NOTE, codeSpan, basisText, causeSentences, causesShort, cellCost, centsOf, durationText, ganttChart, kindsOf, many, minutesText, modelId, modelName, moneyText, plainText, stateBadge, stateWords, tableCell } from "./card-kit.mjs"; import { passKind } from "./usage.mjs"; import { sanitize } from "./handoff.mjs"; @@ -596,7 +597,7 @@ function actionLines(d, atZ) { return plainText(clip(first, 300)); }; if (d.exit === "blocked") { - const todo = s?.next === "none" ? "a resume or a restart does not get past this; the Blocked notice on this issue says why." : "fix the cause below, then re-apply the `pendulum:objective` label. The Blocked notice on this issue has the full steps."; + const todo = s?.next === "none" ? "a resume or a restart does not get past this; the Blocked notice on this issue says why." : `fix the cause below, then ${RESUME_OBJECTIVE}. The Blocked notice on this issue has the full steps.`; return [`> **What to do:** ${todo}`, ">", `> **Why:** ${why(s?.reason)}`]; } if (d.exit === "question") { diff --git a/plugin/scripts/lib/report.mjs b/plugin/scripts/lib/report.mjs index a70fe161..863a1f77 100644 --- a/plugin/scripts/lib/report.mjs +++ b/plugin/scripts/lib/report.mjs @@ -636,7 +636,7 @@ export async function readReport(repo, scope, { token, fallback = null, maxCalls } if (arms.length) { if (scope.label) arms[0].listed = [...issues.keys()]; - await vetArms(repo, arms, { budget, opts, started, renamed, timelines, objectiveLabel, permissions, forbidden }); + await vetArms(repo, arms, { budget, opts, started, renamed, timelines, objectiveLabel, permissions, forbidden, mine }); // Only the Objectives a vetted label counts for are read on, and one both arms count for is in neither. for (const n of [...issues.keys()]) if (!armCounted(arms, n)) issues.delete(n); } @@ -887,7 +887,7 @@ const latestLabeled = (events, label) => { * `started` with when each issue's Objective started (finish-card.mjs labelTime, the scorer's start of its wall clock). * A BudgetStop leaves the rest unchecked. */ -async function vetArms(repo, arms, { budget, opts, started, renamed = new Set(), timelines = new Set(), objectiveLabel, permissions = new Map(), forbidden: unreadable = new Set() }) { +async function vetArms(repo, arms, { budget, opts, started, renamed = new Set(), timelines = new Set(), objectiveLabel, permissions = new Map(), forbidden: unreadable = new Set(), mine }) { const all = [...new Set(arms.flatMap((a) => a.listed))].sort((a, b) => a - b); if (!all.length) return; budget.plan(all.length, `the timelines of the ${all.length} Objective(s) labelled ${arms.map((a) => a.label).join(" or ")}: who applied the label (a paged read's first page each)`); @@ -904,7 +904,7 @@ async function vetArms(repo, arms, { budget, opts, started, renamed = new Set(), // Labelled before the rename to Pendulum (finish-card.mjs clockRenamed): no start, so no wall clock, as on its card. if (clockRenamed(events)) renamed.add(n); timelines.add(n); - const start = renamed.has(n) ? null : labelTime(null, events, objectiveLabel); + const start = renamed.has(n) ? null : labelTime({ number: n }, events, objectiveLabel, null, { mine }); if (start) started.set(n, start); for (const arm of arms.filter((a) => a.listed.includes(n))) { const last = latestLabeled(events, arm.label); @@ -1910,7 +1910,7 @@ export function buildReport(read, { prices = loadPrices(), by = [], rates = null // Where its dollars went, by the finish card's rules (#570 V1). row.asked = askedRows; row.churn = churnRows; - // Its clock (#570 V6): the scorer's start (its first `pendulum:objective` label) from its newest finish card's summary + // Its clock (#570 V6): the first activation from its newest finish card's summary // (lastCard: a reopened Objective's last, the same card on both paths, whichever its figures were read from), else from // its timeline where the report read it (a labelled set's arms); its last merge, that card's, else its last merged // PR's, whichever is later; and the wall clock between them. Null with why (`clockWhy`) where no record gives one. diff --git a/plugin/scripts/lib/session.mjs b/plugin/scripts/lib/session.mjs index d308f3b9..da7219c2 100644 --- a/plugin/scripts/lib/session.mjs +++ b/plugin/scripts/lib/session.mjs @@ -10,7 +10,7 @@ import { execFileSync } from "node:child_process"; import { backend, spendInProgress, stageRoute } from "./backend.mjs"; import { runValidation } from "./checkout.mjs"; import { EXIT_ASK_MIN_MS, SESSION_TOTALS_FILE, copilotCreditUsd, decisionSpend, finalText, reservedSpend, openPasses, passesRunning, runHarness, seedSessionTotal, setStageBilling, stagePasses, stageSpendNow, stageSpendSoFar, UsageLimitReached } from "./harness.mjs"; -import { STOP_EXIT_MS, STOP_SETTLE_MS, STOP_TIDY_MS, applyStop, claimExit, exitCommitted, requestStageStop, stopCause, stopText, stoppedRecords } from "./stop.mjs"; +import { STOP_EXIT_MS, STOP_SETTLE_MS, STOP_TIDY_MS, applyStop, claimExit, exitCommitted, readDraftActivationHold, recoveryEpoch, requestStageStop, stopCause, stopText, stoppedRecords } from "./stop.mjs"; import { addLabels, awaitChecks, @@ -44,9 +44,9 @@ import { workflowFile, getPrSettled, listComments, - objectiveLabeledAt, listReviewComments, listReviews, + listTimeline, moveCard, branchState, prComment, @@ -62,6 +62,7 @@ import { RETRY, } from "./github.mjs"; import { input, log, redactSecrets, secretForms, setOutput, commandFailed } from "./inputs.mjs"; +import { RESUME_OBJECTIVE } from "./activation.mjs"; import { endCard } from "./finish-card.mjs"; import { lineClock, logTime, timeZone, whenText } from "./clock.mjs"; import { SHORT_DETAIL, progressBody, progressCard } from "./progress-card.mjs"; @@ -1648,7 +1649,7 @@ export async function validationLoop({ checkout, commands, harness, model, effor const unfinished = (x) => !x.green && x.timedOut && !x.failedRuns?.length; // A running check that ended the wait by making no progress: the Block names its step and times, and the way past // the judgement for a PR that slows a step on purpose (noProgressMarker, posted with the Block). - const noProgress = (x, s) => (x.hung?.length && s.kind === "running" ? { ...s, noProgress: true, reason: `no progress: ${hungChecks(x.hung)}; ${s.reason}; when this change makes that step slower, re-apply the Objective's label: ${sha.slice(0, 7)} is then waited for up to the stage's wall clock` } : s); + const noProgress = (x, s) => (x.hung?.length && s.kind === "running" ? { ...s, noProgress: true, reason: `no progress: ${hungChecks(x.hung)}; ${s.reason}; when this change makes that step slower, resume through Draft: ${sha.slice(0, 7)} is then waited for up to the stage's wall clock` } : s); const history = async () => { // Older commits that ran the checks: the PR's last green head, then the default branch's newest. const green = lastGreenHead(await listComments(checks.repo, checks.prNumber, { token: checks.token }).catch(() => []), checks.issue); @@ -2184,7 +2185,7 @@ export function unchangedBlock(u, lead = "") { if (u?.refused) return { reason: `${head}; ${refusedRerunText(u.refused)}`, cause: u.refused.earlier || u.refused.status === 403 || u.refused.status === 404 ? "setup" : "outage" }; const side = u?.infra ? ", again in their set-up or checkout (GitHub's side)" : ""; const what = u?.red ? `its failed jobs were rerun once and failed again${side}` : u?.already ? `its failed jobs were already rerun once on this head${side}` : `its failed jobs were not rerun (${u?.skipped || "no rerun"})`; - return { reason: `${head}; ${what}; read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then re-apply the label`, cause: (u?.red || u?.already) && u.infra ? "outage" : "work" }; + return { reason: `${head}; ${what}; read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then resume through Draft`, cause: (u?.red || u?.already) && u.infra ? "outage" : "work" }; } /** The longest a stage waits, past its first wait, for required checks GitHub has not started (validationLoop). */ @@ -2693,7 +2694,7 @@ export function appliedExit(args, result) { /** * Whether a Blocked notice's way on is a resume or a restart, said plainly, since the two look alike and a restart - * throws away paid work: re-applying `pendulum:objective` resumes from `pendulum/<issue>` and its PR; `pendulum:restart` + * throws away paid work: Draft removal resumes from `pendulum/<issue>` and its PR; `pendulum:restart` * discards them (stop.mjs restartObjective, whose record names the commit that restores the branch). `next`, decided on * structure: `resume` (the stop is outside the work: every cause but `work`), `work` (the work itself stopped: resume * once its cause is fixed, restart only to redo it), `restart` (a restart was asked for and could not finish), `none` @@ -2704,9 +2705,9 @@ export function nextStep({ issue, pr = null, next = "resume", delivered = false const kept = pr ? `${branch} and PR #${pr.number}` : branch; const lost = pr ? `${delivered ? "the delivered " : ""}PR #${pr.number} with its review, the commits on ${branch} and the spend on them` : `the commits on ${branch}, if any, and the spend on them`; if (next === "none") return "Neither a resume nor a restart gets past this: both check the issue's author again."; - if (next === "restart") return `To keep the work instead of restarting, re-apply \`pendulum:objective\`: that resumes from ${kept}.`; - if (next === "work") return `Resume once the cause is fixed: re-apply \`pendulum:objective\` to go on from ${kept}. Restart (\`pendulum:restart\`) only when the work itself must be redone from the issue's text: a restart discards ${lost}.`; - return `Resume, don't restart: the stop is outside the work. Once its cause is fixed or has passed, re-apply \`pendulum:objective\` to go on from ${kept}. \`pendulum:restart\` would discard ${lost}, and gain nothing.`; + if (next === "restart") return `To keep the work instead of restarting, ${RESUME_OBJECTIVE} from ${kept}.`; + if (next === "work") return `Resume once the cause is fixed: ${RESUME_OBJECTIVE} from ${kept}. Restart (\`pendulum:restart\`) only when the work itself must be redone from the issue's text: a restart discards ${lost}.`; + return `Resume, don't restart: the stop is outside the work. Once its cause is fixed or has passed, ${RESUME_OBJECTIVE} from ${kept}. \`pendulum:restart\` would discard ${lost}, and gain nothing.`; } /** The way on (nextStep) a Block's cause (logic.mjs BLOCK_CAUSES) gives: `work` for the work's own, `resume` for any other. */ @@ -2718,17 +2719,17 @@ export const nextOf = (cause) => (cause === "work" ? "work" : "resume"); * restart (nextStep; `next` defaults to the cause's, nextOf). */ export const blockedLine = ({ issue, pr = null, stage, reason, fix = null, delivered = false, cause = "pendulum", next = null }) => - `Blocked (${stage}): ${reason}${pr || /[.!?]$/.test(reason) ? "" : "."}${pr ? (delivered ? ` — PR #${pr.number} was delivered; it is a draft until this is fixed.` : ` — PR #${pr.number} is a draft with what exists.`) : ""} ${fix || `Fix by pushing to \`pendulum/${issue}\` or editing the issue, then re-apply \`pendulum:objective\`.`}\n\n${nextStep({ issue, pr, delivered, next: next || nextOf(cause) })}`; + `Blocked (${stage}): ${reason}${pr || /[.!?]$/.test(reason) ? "" : "."}${pr ? (delivered ? ` — PR #${pr.number} was delivered; it is a draft until this is fixed.` : ` — PR #${pr.number} is a draft with what exists.`) : ""} ${fix || `Fix by pushing to \`pendulum/${issue}\` or editing the issue.`}\n\n${nextStep({ issue, pr, delivered, next: next || nextOf(cause) })}`; /** * The Block doctor's FAIL rows (doctor.mjs: name, detail, fix) make, cause `setup`: the reason names each failing check - * once with what it found, and the fix is the step each row names, then the re-applied label. A push or an edit to the + * once with what it found, and the fix is the step each row names. A push or an edit to the * issue fixes no secret or setting, so the generic fix line never stands for it. */ export function doctorBlock(rows) { const reason = rows.map((c) => (c.detail ? `${c.name}: ${c.detail}` : c.name)).join("; "); const steps = rows.map((c) => String(c.fix || "").trim().replace(/[.\s]+$/, "")).filter(Boolean); - const fix = `Fix: ${steps.length ? steps.join("; ") : "the step `/pendulum:pendulum-doctor` names"}; then re-apply \`pendulum:objective\`.`; + const fix = `Fix: ${steps.length ? steps.join("; ") : "the step `/pendulum:pendulum-doctor` names"}.`; return { reason, fix, cause: "setup", stage: "doctor" }; } @@ -2785,7 +2786,7 @@ export async function applyExit(repo, { issue, pr, exit, reason, detail = "", no log(`draft: ${String(undrafted.message || undrafted).slice(0, 120)}`); const why = `PR #${pr.number} could not be made a draft for its Question (${code}), so the Question is not asked; the question was: ${reason.replace(/^question:\s*/i, "")}`; // No PR to the Block: it would try the same draft again, and say the PR is one. - const fix = `Fix by letting Pendulum's token convert PR #${pr.number} to a draft, or by making it one by hand, then re-apply \`pendulum:objective\`.`; + const fix = `Fix by letting Pendulum's token convert PR #${pr.number} to a draft, or by making it one by hand, then resume through Draft.`; return applyExit(repo, { issue, pr: null, exit: "blocked", reason: why, notify, stage, cause: "pendulum", fix }, { token, notice }); } await setStateLabel(repo, issue, "question", { token }); @@ -3005,7 +3006,7 @@ async function afterReset(lost, deadlineAt) { /** What ends a stage off the local route on an outage: its reason, and its External cause (logic.mjs BLOCK_CAUSES). */ const outageBlock = (lost) => Number.isFinite(lost.resetAt) - ? { reason: `${outageReason(lost)}, past the stage's deadline. Re-apply the label to run it again after the reset.`, cause: "provider-quota" } + ? { reason: `${outageReason(lost)}, past the stage's deadline. Resume through Draft to run it again after the reset.`, cause: "provider-quota" } : { reason: `${outageReason(lost)}; ${serverDown(lost.code) ? "the stage ended on it" : "the stage waited for the network until its time ran out"}. ${RELAUNCH_NOTE}`, cause: "outage" }; /** @@ -3231,7 +3232,7 @@ export async function postHandedOff(repo, prNumber, issue, sha, { token }) { export const noProgressMarker = (issue, sha) => marker(issue, "no-progress", sha); export async function postNoProgress(repo, prNumber, issue, sha, { token }) { - await prComment(repo, prNumber, `${noProgressMarker(issue, sha)}\nPendulum: a required check on ${sha.slice(0, 7)} made no progress; re-applying the label waits for it up to the stage's wall clock.`, { token }); + await prComment(repo, prNumber, `${noProgressMarker(issue, sha)}\nPendulum: a required check on ${sha.slice(0, 7)} made no progress; resuming through Draft waits for it up to the stage's wall clock.`, { token }); } /** @@ -3492,7 +3493,7 @@ export async function queueEntryState(repo, prNumber, opts, now = Date.now(), ga * applyExit's input for a send-back that Blocks (logic.mjs staleDecision): `why` "stuck" (the conflict came back on the * base the last rebase resolved, `record` its rebase record, files named) or "limit" (`limit`, the rebase_limit in * force, rebases in a day). - * Its key names the condition, the PR's head and the objective label's time (`since`, rebaseMarkers), so the dispatcher + * Its key names the condition, the PR's head and the recovery time (`since`, rebaseMarkers), so the dispatcher * and a `run --wait` loop Blocking the same condition write one comment, not two @mentions; a new head or a human * recovery is a new condition, so it notifies again. */ @@ -3502,7 +3503,7 @@ export function rebaseBlock({ issue, pr, why, record = null, since = null, notif } /** - * The rebase send-backs on the Objective's PR (PLAN.md "Merge") since the issue's last objective label (a human + * The rebase send-backs on the Objective's PR (PLAN.md "Merge") since the last activation (a human * recovery starts the count over): the marker comments Pendulum left and the worker's records of the rebases that * conflicted (logic.mjs ontoRecord). `effective` counts the markers whose send-back pushed (one that names the PR's * head now produced no push: its worker never ran or died, so it is sent again), `recent` those of the last @@ -3510,15 +3511,15 @@ export function rebaseBlock({ issue, pr, why, record = null, since = null, notif * for it. `record` is the newest rebase record of a pass that pushed, and `stuck` that record when the PR still needs * a rebase and the default branch is still the base it was made onto: the conflict came back after its resolution, * with nothing merged since (a failed read of the branch leaves `stuck` null: the send-back goes ahead, and the worker - * Blocks a conflict it cannot resolve itself). `since` is that label's time. Only Pendulum's own comments count (isSelf); - * `unread` says the label's time, Pendulum's login or the comments could not be read: the caller holds the PR this tick. + * Blocks a conflict it cannot resolve itself). Only Pendulum's own comments count (isSelf). + * `unread` means the recovery time, Pendulum's login or the comments could not be read. */ export async function rebaseMarkers(repo, { issue, pr, objectiveLabel }, opts, now = Date.now()) { const prefix = marker(issue, "rebase").replace(/ -->$/, ""); const none = { effective: 0, recent: 0, already: false, record: null, stuck: null }; // A read that fails leaves the count unknown: `unread`, so the caller holds the PR this tick rather than count none. let unread = null; - const since = await objectiveLabeledAt(repo, issue, objectiveLabel, opts).catch((e) => ((unread = e), null)); + const since = await recoveryEpoch(repo, issue, objectiveLabel, opts).catch((e) => ((unread = e), null)); if (!pr) return { ...none, since }; // Only Pendulum's own comments: a writer's pasted marker is no send-back or rebase of Pendulum's. if (!unread && !(selfLogin() || (await primeSelf(opts)))) unread = new Error("Pendulum's own login is unknown"); @@ -3811,7 +3812,7 @@ export async function readQueueRed({ repo, issue, prNumber, base, head, names = return { state: "requeued", line: `merge queue run red${where}: ${q.reason}; not known to be the PR's change (${q.kind}), enqueued again as any drop` }; } // The fix passes since the Objective's last re-entry (an unread timeline counts every one). - const entered = await objectiveLabeledAt(repo, issue, [objectiveLabel, "pendulum:restart", "pendulum:blocked"], { token }).catch(() => null); + const entered = await recoveryEpoch(repo, issue, objectiveLabel, { token }, { states: ["pendulum:restart", "pendulum:blocked"] }).catch(() => null); const fixes = records.filter((r) => r.state === "fixed" && !(Date.parse(entered) > Date.parse(r.at))); // The red the last fix pass was handed, and every one fixed since the re-entry, against this one (fix-progress.mjs), // with what passed on the queue's commit, and for a decision call the before-red's failure lines and the fix pass's own @@ -3835,7 +3836,7 @@ export async function readQueueRed({ repo, issue, prNumber, base, head, names = // One the change's only by default (`unsure`, queueRedOf) is said as that too. const again = q.limit ? "again" : q.unsure ? `${q.unsure}, again` : "the PR's own change again"; const failed = q.limit ? `failed: ${q.reason},` : q.unsure ? `failed (${q.reason}); ${q.unsure},` : `failed in this PR's own change (${q.reason})`; - return { state: "blocked", cause: p && !p.progress && p.undecided ? p.cause || "pendulum" : "work", line: `merge queue run red${where}: ${q.reason}; ${again}, after Pendulum's ${over}`, red: q.red, reason: `the merge queue's run on its commit ${q.sha.slice(0, 7)} ${failed} after Pendulum's ${over}; fix it on the branch, then re-apply the label` }; + return { state: "blocked", cause: p && !p.progress && p.undecided ? p.cause || "pendulum" : "work", line: `merge queue run red${where}: ${q.reason}; ${again}, after Pendulum's ${over}`, red: q.red, reason: `the merge queue's run on its commit ${q.sha.slice(0, 7)} ${failed} after Pendulum's ${over}; fix it on the branch, then resume through Draft` }; } // Started: counted on the record, so a pass that keeps committing nothing reaches the bound above. const record = { ...pending, kind: "own", sigs: q.sigs, jobs: q.jobs, lead: q.red.lead, tries: pending.tries + 1, ends: pending.ends ?? [], ...(q.unsure ? { unsure: q.unsure } : {}) }; @@ -3916,12 +3917,12 @@ export function queueDropBlock({ drops, codes, kinds = [], lines = "" }) { const head = `the merge queue dropped the reviewed PR ${drops} times without merging it (${codes.join(", ")})`; const failed = lines ? `; its run on the queue's commit failed: ${lines}` : ""; const kind = kinds.at(-1) ?? null; - if (kind === "infra" || kind === "not-started") return { cause: "outage", reason: `${head}${failed}. Triage read the failure as GitHub's side (${kind}); rerun the queue's jobs or wait for GitHub, then re-apply the label` }; - if (kind === "base") return { cause: "work", reason: `${head}${failed}. The default branch fails the same way: fix it there, then re-apply the label` }; - if (kind === "unjudged" || kind === "unjudged-outage") return { cause: kind === "unjudged-outage" ? "outage" : "pendulum", reason: `${head}${failed}. Whether the default branch fails the same way could not be judged (the decision model gave no answer${kind === "unjudged-outage" ? ": its vendor's outage" : ""}); check the default branch's runs of the failing jobs, then re-apply the label` }; - if (kind === "flaky") return { cause: "work", reason: `${head}${failed}. Triage read the failure as a flake each time: fix or steady that test on the branch or the default branch, then re-apply the label` }; + if (kind === "infra" || kind === "not-started") return { cause: "outage", reason: `${head}${failed}. Triage read the failure as GitHub's side (${kind}); rerun the queue's jobs or wait for GitHub, then resume through Draft` }; + if (kind === "base") return { cause: "work", reason: `${head}${failed}. The default branch fails the same way: fix it there, then resume through Draft` }; + if (kind === "unjudged" || kind === "unjudged-outage") return { cause: kind === "unjudged-outage" ? "outage" : "pendulum", reason: `${head}${failed}. Whether the default branch fails the same way could not be judged (the decision model gave no answer${kind === "unjudged-outage" ? ": its vendor's outage" : ""}); check the default branch's runs of the failing jobs, then resume through Draft` }; + if (kind === "flaky") return { cause: "work", reason: `${head}${failed}. Triage read the failure as a flake each time: fix or steady that test on the branch or the default branch, then resume through Draft` }; if (!lines) return null; - return { cause: "work", reason: `${head}${failed}. Fix that on the branch (a job the PR's checks do not run, such as another OS, fails only there), then re-apply the label` }; + return { cause: "work", reason: `${head}${failed}. Fix that on the branch (a job the PR's checks do not run, such as another OS, fails only there), then resume through Draft` }; } const QUEUE_CONFLICT_LINE = /^<!-- pendulum:queue-conflict (\{[^\n]*\}) -->$/m; @@ -4029,12 +4030,15 @@ const ROUNDS_RECORD = (issue) => `<!-- pendulum:${issue}:answer-rounds-record `; /** * Pendulum's record of the answer rounds on `prNumber`, on the issue (one comment, marker(issue, "answer-rounds"); a * record by Pendulum or someone who can push, since two routes can write it), as far as it counts since the Objective's - * last re-entry (its label applied again, a restart or a Block, from the issue's timeline): `rounds`, the times of each + * last activation, restart or Block, from the issue's timeline. `rounds` lists the times of each * answer round started; `checks`, each review stage's finding check that left findings without a verdict * ({at, ids, error}) or, after one, judged them all ({at, ids: []}), oldest first. Throws when it cannot be read. */ export async function readAnswerRounds(repo, { issue, prNumber, objectiveLabel }, opts) { - const [comments, since] = await Promise.all([listComments(repo, issue, opts), objectiveLabeledAt(repo, issue, [objectiveLabel, "pendulum:blocked", "pendulum:restart"], opts)]); + const [comments, since] = await Promise.all([ + listComments(repo, issue, opts), + recoveryEpoch(repo, issue, objectiveLabel, opts, { states: ["pendulum:blocked", "pendulum:restart"] }), + ]); const after = (t) => Number.isFinite(Date.parse(t)) && (!since || Date.parse(t) > Date.parse(since)); const rounds = []; const checks = []; @@ -4096,7 +4100,6 @@ export async function takeAnswerRound(repo, ctx, opts, { check = null, rec = nul const placeOf = (t) => `${t.path ?? "the PR"}${Number.isInteger(t.line) ? `:${t.line}` : ""}`; const listed = (items) => `${items.slice(0, THREADS_NAMED).join("; ")}${items.length > THREADS_NAMED ? `, and ${items.length - THREADS_NAMED} more` : ""}`; -const RESUME = "re-apply `pendulum:objective` to resume"; /** The Block cause of a finding check the decider answered with no verdict, from its code (adapters/decider.mjs). */ const checkCause = (error) => (error === "auth" ? "setup" : error === "rate_limited" || error === "billing" ? "provider-quota" : "outage"); @@ -4136,7 +4139,7 @@ export async function openFindingsExit(decision, { repo, issue, prNumber, object const who = decider?.name === "harness" ? `the stage's own harness (${decider.model})` : `the AI Gateway's decision model${decider?.model ? ` (${decider.model})` : ""}`; if (pending.length && tries >= FINDING_CHECK_TRIES) { const fix = decider?.name === "harness" ? "Check the harness login this stage runs on and its usage" : "Check the AI Gateway key, its budget and the gateway's status"; - Object.assign(decision, { exit: "blocked", cause: checkCause(codes[0]), reason: `${who} gave no verdict (${check.error}) on the answers to ${pending.length} reviewer finding(s) on PR #${prNumber} in ${tries} review stages in a row: ${where(pending)}. ${fix}, then ${RESUME}` }); + Object.assign(decision, { exit: "blocked", cause: checkCause(codes[0]), reason: `${who} gave no verdict (${check.error}) on the answers to ${pending.length} reviewer finding(s) on PR #${prNumber} in ${tries} review stages in a row: ${where(pending)}. ${fix}, then ${RESUME_OBJECTIVE}` }); return decision; } const relabel = (what) => exitStep(decision, `${what} and the review label could not be re-applied`, () => addLabels(repo, prNumber, [REVIEW_LABEL], opts)); @@ -4159,7 +4162,7 @@ export async function openFindingsExit(decision, { repo, issue, prNumber, object const round = await exitStep(decision, `the answer rounds on PR #${prNumber} could not be recorded`, () => takeAnswerRound(repo, ctx, opts, { check, rec })); if (!round) return decision; if (!round.taken) { - Object.assign(decision, { exit: "blocked", cause: "work", reason: `${judged.length} reviewer finding(s) still open on PR #${prNumber} after ${round.rounds} answer round(s): ${where(judged)}. Fix them on the branch, or answer each on the PR: a reply by someone who can push in its thread, or resolve the thread (for a finding in the review body, a comment by someone who can push starting \`<!-- pendulum:${issue}:resolved:<finding id> -->\`); then ${RESUME}` }); + Object.assign(decision, { exit: "blocked", cause: "work", reason: `${judged.length} reviewer finding(s) still open on PR #${prNumber} after ${round.rounds} answer round(s): ${where(judged)}. Fix them on the branch, or answer each on the PR: a reply by someone who can push in its thread, or resolve the thread (for a finding in the review body, a comment by someone who can push starting \`<!-- pendulum:${issue}:resolved:<finding id> -->\`); then ${RESUME_OBJECTIVE}` }); return decision; } Object.assign(decision, { exit: "delivered", rerun: true, reason: `${judged.length} reviewer finding(s) still open after the answer pass (${where(judged)})${pending.length ? `, and ${pending.length} answer(s) still to be judged` : ""}; the review runs again to answer them (round ${round.round} of ${ANSWER_ROUNDS})` }); @@ -4241,8 +4244,8 @@ async function conversationsGate(repo, ctx, report, opts) { } if (!round.taken) { report.reason = back.every(scanning) - ? `code scanning still has ${back.length} open alert(s) on PR #${prNumber} after ${round.rounds} answer rounds: ${listed(back.map(placeOf))}. Fix them on the branch or resolve them on the PR, then ${RESUME}` - : `${back.length} review thread(s) still open on PR #${prNumber} after ${round.rounds} answer rounds: ${listed(back.map((t) => `${t.author} on ${placeOf(t)}`))}. Fix them on the branch, or answer or resolve each on the PR, then ${RESUME}`; + ? `code scanning still has ${back.length} open alert(s) on PR #${prNumber} after ${round.rounds} answer rounds: ${listed(back.map(placeOf))}. Fix them on the branch or resolve them on the PR, then ${RESUME_OBJECTIVE}` + : `${back.length} review thread(s) still open on PR #${prNumber} after ${round.rounds} answer rounds: ${listed(back.map((t) => `${t.author} on ${placeOf(t)}`))}. Fix them on the branch, or answer or resolve each on the PR, then ${RESUME_OBJECTIVE}`; return "threads"; } await removeLabel(repo, prNumber, REVIEW_LABEL, opts).catch(() => {}); @@ -4252,7 +4255,7 @@ async function conversationsGate(repo, ctx, report, opts) { } if (!open.length || !rule) return null; const what = (t) => `${t.author ?? "a deleted account"} on ${placeOf(t)}${t.answered ? " (answered; Pendulum could not resolve it)" : ""}`; - report.reason = `PR #${prNumber} cannot merge: ${rule} on ${base} requires every review conversation resolved, and ${open.length} ${open.length === 1 ? "is" : "are"} open: ${listed(open.map(what))}. Answer or resolve each on the PR, then ${RESUME}`; + report.reason = `PR #${prNumber} cannot merge: ${rule} on ${base} requires every review conversation resolved, and ${open.length} ${open.length === 1 ? "is" : "are"} open: ${listed(open.map(what))}. Answer or resolve each on the PR, then ${RESUME_OBJECTIVE}`; return "threads"; } @@ -4325,7 +4328,7 @@ async function textEdit(repo, issue, prNumber, opts) { * default branch, read before the merge or after GitHub refused it: never a Block here; the caller sends it back for a * rebase under logic.mjs staleDecision's rules), "dropped" (the merge queue * dropped it QUEUE_TRIES times since the latest of its review, its head's commit and the issue's last re-entry (the - * `objectiveLabel` applied again) or Block: logic.mjs queueSince and queueRetry; the caller Blocks with mergeBlockReason), + * latest activation) or Block: logic.mjs queueSince and queueRetry; the caller Blocks with mergeBlockReason), * "queue-red" (the queue's newest drop is a red run on its commit, QUEUE_RED_CODE, that no review stage has read: its * record goes on the issue and the review label back on, and the review stage decides it, queueRedOf) or * "held" (a person took it out of the queue: it stays out until they enqueue it again, or it is reviewed again, gets a new head or re-enters), @@ -4342,7 +4345,7 @@ async function textEdit(repo, issue, prNumber, opts) { * `watch: true` whenever the PR is left in the queue, so the caller has it watched until it merges or leaves * (dispatch.mjs watchQueue) rather than waiting for an event GitHub may hold for approval, or a cron. */ -export async function mergeReadyOne(repo, { issue, prNumber, queue, checkNames = null, report = {}, hungMs = null, queueTimeout = undefined, actionsToken = null, cache = {}, stall = STALL_DEFAULTS, objectiveLabel = "pendulum:objective", issueData = null, thirdParty = [], editCheck = null, commentCheck = null }, opts) { +export async function mergeReadyOne(repo, { issue, prNumber, queue, checkNames = null, report = {}, hungMs = null, queueTimeout = undefined, actionsToken = null, cache = {}, stall = STALL_DEFAULTS, objectiveLabel = "pendulum:objective", issueData = null, issueEvents = undefined, thirdParty = [], editCheck = null, commentCheck = null }, opts) { const pr = await getPr(repo, prNumber, opts); if (pr.state !== "open" || pr.draft) return "not-open"; // A stopped Objective (its label removed, its issue closed, a restart asked for, a draft: stop.mjs stopCause) never merges, whoever runs this pass: @@ -4351,6 +4354,12 @@ export async function mergeReadyOne(repo, { issue, prNumber, queue, checkNames = const issueNow = issueData ?? (await getIssue(repo, issue, opts).catch((e) => (log(`#${issue}: the issue could not be read before the merge (${errCode(e)}); next try`), null))); if (!issueNow) return "pending"; if (stopCause(issueNow, objectiveLabel)) return "stopped"; + const events = issueEvents === undefined ? await listTimeline(repo, issue, opts).catch(() => null) : issueEvents; + const hold = await readDraftActivationHold(repo, issue, objectiveLabel, opts, events); + if (hold) { + log(`#${issue}: ${hold}; no merge`); + return "pending"; + } // A sibling merged first and this PR conflicts with the default branch: no merge or enqueue can take it (#2647). if (pr.mergeable_state === "dirty") return "conflict"; let sha = await recordedMergeable(repo, prNumber, issue, opts); @@ -4478,7 +4487,7 @@ export async function mergeReadyOne(repo, { issue, prNumber, queue, checkNames = let since = reviewedAt; if (removals.length) { let unread = null; - const marks = await objectiveLabeledAt(repo, issue, [objectiveLabel, "pendulum:blocked"], opts).catch((e) => ((unread = e), null)); + const marks = await recoveryEpoch(repo, issue, objectiveLabel, opts, { states: ["pendulum:blocked"], events }).catch((e) => ((unread = e), null)); const head = await getCommit(repo, pr.head.sha, opts).catch((e) => ((unread = e), null)); if (unread) { log(`#${issue}: the issue's timeline or PR #${prNumber}'s head is unreadable (${errCode(unread)}); next tick`); @@ -4555,9 +4564,9 @@ export async function mergeReadyOne(repo, { issue, prNumber, queue, checkNames = report.reason = said ? said.reason : hungNow - ? `a required check made no progress on the merge queue's commit (${hungChecks(hungNow)}), again after Pendulum re-enqueued the PR ${retry.cleared ? `${retry.cleared + 1} times (one removal was a step that proved slow, not hung)` : "once"} (drops counted: ${retry.codes.join(", ")}). Find what holds that step (a hung command or a runner that never frees), then re-apply the label` + ? `a required check made no progress on the merge queue's commit (${hungChecks(hungNow)}), again after Pendulum re-enqueued the PR ${retry.cleared ? `${retry.cleared + 1} times (one removal was a step that proved slow, not hung)` : "once"} (drops counted: ${retry.codes.join(", ")}). Find what holds that step (a hung command or a runner that never frees), then resume through Draft` : stuck.length - ? `the merge queue dropped the reviewed PR ${retry.drops} times without merging it (${retry.codes.join(", ")}): ${notStartedReason(stuck)}. GitHub never started the job on the queue's merge_group commit: infrastructure, not the change; fix that, then re-apply the label` + ? `the merge queue dropped the reviewed PR ${retry.drops} times without merging it (${retry.codes.join(", ")}): ${notStartedReason(stuck)}. GitHub never started the job on the queue's merge_group commit: infrastructure, not the change; fix that, then resume through Draft` : retry.block; return "dropped"; } diff --git a/plugin/scripts/lib/stop.mjs b/plugin/scripts/lib/stop.mjs index 5fb7101b..fa2bce29 100644 --- a/plugin/scripts/lib/stop.mjs +++ b/plugin/scripts/lib/stop.mjs @@ -1,13 +1,16 @@ -// A person's stop of one Objective (docs/USAGE.md, "An Objective's lifecycle"): its `pendulum:objective` label removed, -// its issue closed, or `pendulum:draft` applied (a draft never runs, its Objective label on or not); and its restart from the issue's current text (`pendulum:restart`), which stops a running stage -// the same way before the dispatcher discards what the earlier run left (restartObjective). No tick, loop or relaunch picks a stopped Objective (they list only labelled, open issues); this +// A person's stop of one Objective (docs/USAGE.md, "An Objective's lifecycle"): `pendulum:draft` applied, its issue +// closed, or its Objective label removed on an older workflow. A restart (`pendulum:restart`) stops a running stage +// before the dispatcher discards what the earlier run left (restartObjective). No tick, loop or relaunch picks a stopped Objective; this // module is the rest of it: the cause read from the issue, the running stage's own stop (its watch on its issue, the // abort every harness pass of the stage listens to, its claim on the exit), and the tidy that leaves the Objective // stopped (its PR a draft without the review label, its state label off, its card back in Queued). -import { collaboratorPermission, dequeuePr, findPr, findProject, getIssue, getPr, listComments, mergeQueueEntry, moveCard, removeLabel, rest, setDraft, setStateLabel, upsertComment } from "./github.mjs"; +import { collaboratorPermission, dequeuePr, findPr, findProject, getIssue, getPr, labeledAtIn, listComments, listTimeline, mergeQueueEntry, moveCard, removeLabel, rest, setDraft, setStateLabel, upsertComment } from "./github.mjs"; +import { DRAFT_LABEL, activationEvents, latestDraftEvent } from "./activation.mjs"; import { log } from "./inputs.mjs"; import { REVIEW_LABEL, isSelf, knownWriter, marker, pinnedMaintainer, restartedAt, trustedAuthor } from "./logic.mjs"; +export { DRAFT_LABEL }; + /** How often a running stage reads its issue for a stop. */ export const STOP_POLL_MS = 60_000; /** How long a stopping stage waits for its harness passes to end (proc.mjs exec kills a stopped one within 15 s). */ @@ -28,12 +31,6 @@ export const STOP_GRACE_MS = 10 * 60_000; /** The label a person applies to restart an Objective from its issue's current text, in any state. */ export const RESTART_LABEL = "pendulum:restart"; -/** - * The label of a draft Objective: an issue Pendulum never runs (no dispatch, claim or spend, on any route) while it is - * on, even beside the Objective label. Starting a draft takes it off and applies the Objective label. - */ -export const DRAFT_LABEL = "pendulum:draft"; - const names = (issue) => (issue?.labels || []).map((l) => (typeof l === "string" ? l : l?.name)); /** @@ -55,45 +52,92 @@ export function labelTrust(repo, opts) { }; } -/** The marker of Pendulum's note that the go at `at` (a label event's time) on issue `n` was not taken (one per go). */ -export const refusedMarker = (n, at) => marker(n, "relabel-refused", String(at || "").replace(/[^0-9TZ]/g, "")); +/** The marker of Pendulum's note that an activation on issue `n` was refused. */ +export const refusedMarker = (n, { id, at }) => + marker(n, "relabel-refused", Number.isSafeInteger(id) && id > 0 ? `id-${id}` : String(at || "").replace(/[^0-9TZ]/g, "")); /** * `trusted` (labelTrust) on the issue's timeline `events`: a go Pendulum's note there already refused (refusedMarker) is * refused again with no read, so a refusal holds for good and costs nothing at later ticks. */ export function goTrust(events, n, trusted) { - return async (actor, e) => (e && goNoted(events, n, e.created_at) ? false : trusted(actor, e)); + return async (actor, e) => (e && goNoted(events, n, { at: e.created_at, id: e.id }) ? false : trusted(actor, e)); } -/** Whether Pendulum's note that the go at `at` was not taken (refusedMarker) is on the issue's timeline `events`. */ -export const goNoted = (events, n, at) => (events || []).some((e) => e?.event === "commented" && isSelf({ user: e.user ?? e.actor }) && (e.body || "").startsWith(refusedMarker(n, at))); +/** A refusal marked only by time predates event IDs. Keep that refusal valid for its recorded second. */ +export function goNoted(events, n, activation, mine = isSelf) { + const current = refusedMarker(n, activation); + const legacy = refusedMarker(n, { at: activation.at }); + return (events || []).some((e) => e && (!e.event || e.event === "commented") && (e.body?.startsWith(current) || e.body?.startsWith(legacy)) && mine({ ...e, user: e.user ?? e.actor })); +} + +export const DRAFT_REMOVAL_UNREAD = "Draft removal is not yet visible on the Objective's timeline"; +export const DRAFT_ACTIVATION_REFUSED = "the Objective's Draft activation was not authorized"; + +/** + * The Draft-specific activation fence for paths that resume a stage, review or merge it without a normal queued pick. + * Old Objectives with no Draft event continue under their existing admission rules. + */ +export async function draftActivationHold(events, n, label, trusted) { + if (!events) return "the Objective's activation timeline could not be read"; + const draft = latestDraftEvent(events); + if (!draft) return null; + if (draft.event === "labeled") return DRAFT_REMOVAL_UNREAD; + const activation = activationEvents(events, label, { assumeObjective: true }).at(-1); + if (!activation || Date.parse(activation.created_at) < Date.parse(draft.created_at)) return "the Objective has no activation after Draft"; + const restart = restartedAt(events.filter((e) => e?.event === "commented").map((e) => ({ ...e, user: e.user ?? e.actor }))); + if (restart && Date.parse(restart) >= Date.parse(activation.created_at)) return null; + const ok = await goTrust(events, n, trusted)(activation.actor ?? null, activation); + if (ok === true) return null; + return ok === "unread" ? "the Objective's Draft activation permission could not be checked" : DRAFT_ACTIVATION_REFUSED; +} + +export async function readDraftActivationHold(repo, n, label, opts, events = undefined) { + if (events === undefined) events = await listTimeline(repo, n, opts).catch(() => null); + return draftActivationHold(events, n, label, labelTrust(repo, opts)); +} + +/** Recovery resets a counter at its latest legacy/state marker or a later, trusted Draft removal. */ +export async function recoveryEpoch(repo, n, label, opts, { states = [], events = undefined } = {}) { + if (events === undefined) events = await listTimeline(repo, n, opts); + const legacy = labeledAtIn(events, [label, ...states]); + const trusted = goTrust(events, n, labelTrust(repo, opts)); + for (const e of activationEvents(events, label, { assumeObjective: true }).reverse()) { + if (legacy && Date.parse(e.created_at) <= Date.parse(legacy)) break; + if (e.label.name !== DRAFT_LABEL) continue; + const ok = await trusted(e.actor ?? null, e); + if (ok === true) return e.created_at; + if (ok === "unread") throw new Error("the Objective's Draft activation permission could not be checked"); + } + return legacy; +} -/** The states a person's go (the Objective label re-applied) puts back to Queued: their labels, by the issue's timeline. */ +/** The states an activation puts back to Queued, as recorded on the issue's timeline. */ export const REQUEUED_FROM = ["pendulum:blocked", "pendulum:question", "pendulum:in-review"]; /** - * Whether a person re-applied the Objective `label` (or started it from a draft: its DRAFT_LABEL taken off) after its last + * Whether a person removed Draft or applied the legacy Objective `label` after its last * Block, Question or In review, on the issue's timeline `events`: the go that puts it back to Queued for its work stage * (the dispatcher's recovery). serve's pendingReviews and the review job's start read the same rule, so a ready mark * beside such a go starts no review. A go counts only when `trusted` (labelTrust) holds for its actor; anyone else's * changes nothing. Only the newest go decides, as for a pick (dispatch.mjs): taking the label off is a stop, so an * earlier go by a writer does not outlive anyone's later remove and re-apply. Returns `{requeued, at, unread, refused}` - * (`at`: the go that counted): `unread` when the check of its actor could not be made for now (nothing is decided on - * it), and `refused`, when neither, the go that did not count (`[{at, actor, draft}]`, `draft` for a draft's start). + * (`at`: the activation that counted): `unread` when Draft removal or the actor could not be verified, and + * `refused`, when neither, the activation that did not count (`[{at, id, actor, draft}]`). */ export async function requeuedIn(events, label, trusted) { - let since = null; - for (const e of events || []) if (e?.event === "labeled" && REQUEUED_FROM.includes(e.label?.name)) since = e.created_at; const out = { requeued: false, unread: false, refused: [] }; - if (!since) return out; - const go = (e) => (e?.event === "labeled" && e.label?.name === label) || (e?.event === "unlabeled" && e.label?.name === DRAFT_LABEL); - const e = (events || []).filter((x) => go(x) && x.created_at > since).at(-1); - if (!e) return out; + if (latestDraftEvent(events)?.event === "labeled") return { ...out, unread: true }; + const state = events?.findLastIndex((e) => e?.event === "labeled" && REQUEUED_FROM.includes(e.label?.name)) ?? -1; + const e = activationEvents(events, label, { assumeObjective: true }).at(-1); + // GitHub timestamps have second precision. For a tied timestamp, use the issue timeline's event order. + if (state < 0 || !e) return out; + const distance = Date.parse(e.created_at) - Date.parse(events[state].created_at); + if (!(distance > 0 || (distance === 0 && events.indexOf(e) > state))) return out; const ok = await trusted(e.actor ?? null, e); if (ok === true) return { ...out, requeued: true, at: e.created_at }; if (ok === "unread") return { ...out, unread: true }; - return { ...out, refused: [{ at: e.created_at, actor: e.actor ?? null, draft: e.event === "unlabeled" }] }; + return { ...out, refused: [{ at: e.created_at, id: e.id, actor: e.actor ?? null, draft: e.event === "unlabeled" }] }; } /** Whether the issue is a draft (DRAFT_LABEL on it). */ @@ -258,7 +302,7 @@ export function watchObjective({ read, label, everyMs = STOP_POLL_MS, onStop }) /** * Leave the issue's Objective stopped: its open PR (`pr`, or the pendulum/<issue> branch's, found here when undefined) out * of the merge queue and a draft without the review label, so nothing merges it and no review starts; and, unless the issue is closed (the - * dispatcher's Done pass moves a closed one), no state label and its card in Queued, so re-applying the label starts it + * dispatcher's Done pass moves a closed one), no state label and its card in Queued, so removing Draft starts it * again. Each step is tried whatever the one before did; returns the failures' messages (none: []). */ export async function applyStop(repo, issue, { pr = undefined, closed = false, project = undefined } = {}, opts) { diff --git a/plugin/scripts/lib/triage.mjs b/plugin/scripts/lib/triage.mjs index ef82ab99..dac4581d 100644 --- a/plugin/scripts/lib/triage.mjs +++ b/plugin/scripts/lib/triage.mjs @@ -1060,7 +1060,7 @@ export async function redCancels(repo, failedRuns, { token, actionsToken = token } /** What a Block says of cancels Pendulum cannot place (redCancels `unplaced`). */ -export const unplacedCancelReason = (unplaced) => `${unplaced.map((c) => c.text).join("; ")}: not a flake and not known to be the PR's change; re-apply the label`; +export const unplacedCancelReason = (unplaced) => `${unplaced.map((c) => c.text).join("; ")}: not a flake and not known to be the PR's change; resume through Draft`; /** Triggers that never start a workflow on a PR's head commit: they run on the queue's, the default branch's or a tag's. */ const NOT_ON_HEAD = ["merge_group", "schedule", "workflow_call", "workflow_run", "release"]; @@ -1246,11 +1246,11 @@ export function checksNotStarted({ sha, names = [], checkRuns = [], workflowRuns const runs = [...new Set(ended.map((x) => x.w))]; // GitHub could not start a run: most often the workflow file on the default branch, the repository's (setup). A // cancellation may be the repository's own concurrency setting: the work's. - return { waits: false, kind: "ended", cause: runs.some((w) => w.conclusion === "startup_failure") ? "setup" : "work", runs, reason: `required check(s) ${list(ended.map((x) => x.n))} never reported on ${short}: ${list(runs.map((w) => `workflow run ${label(w)} ended ${w.conclusion}`))} before ${ended.length > 1 ? "their jobs" : "its job"} ran${runs.some((w) => w.conclusion === "startup_failure") ? " (GitHub could not start the workflow: its file or GitHub's side, as the run's page says)" : ""}; rerun it on GitHub or fix the workflow, then re-apply the label; no failing run to fix` }; + return { waits: false, kind: "ended", cause: runs.some((w) => w.conclusion === "startup_failure") ? "setup" : "work", runs, reason: `required check(s) ${list(ended.map((x) => x.n))} never reported on ${short}: ${list(runs.map((w) => `workflow run ${label(w)} ended ${w.conclusion}`))} before ${ended.length > 1 ? "their jobs" : "its job"} ran${runs.some((w) => w.conclusion === "startup_failure") ? " (GitHub could not start the workflow: its file or GitHub's side, as the run's page says)" : ""}; rerun it on GitHub or fix the workflow, then resume through Draft; no failing run to fix` }; } if (unreported.length) return { waits: false, kind: "unreported", runs: [], reason: `required check(s) ${list(unreported)} never reported on ${short}: no workflow run on it produces ${unreported.length > 1 ? "them" : "it"} (${list(workflowRuns.slice(0, 3).map((w) => `${label(w)} ${w.status === "completed" ? `completed ${w.conclusion}` : w.status}`))}${workflowRuns.length > 3 ? `, ${workflowRuns.length - 3} more` : ""}); check the required check names; no failing run to fix` }; if (filtered.length) return { waits: false, kind: "filtered", runs: [], reason: `required check(s) ${list(filtered.map((x) => x.n))} never run on ${short}: ${list([...new Set(filtered.map((x) => x.key))])} of ${filtered.length > 1 ? "their workflows skips" : "its workflow skips"} this change, so GitHub starts no run for it; run the check on every change, or stop requiring it; no failing run to fix` }; - if (approval.length) return { waits: false, kind: "approval", runs: [], reason: `required check(s) ${list(approval)} on ${short} wait for a deployment approval; approve ${approval.length > 1 ? "them" : "it"}, then re-apply the label; no failing run to fix` }; + if (approval.length) return { waits: false, kind: "approval", runs: [], reason: `required check(s) ${list(approval)} on ${short} wait for a deployment approval; approve ${approval.length > 1 ? "them" : "it"}, then resume through Draft; no failing run to fix` }; if (started.length) { // Who has not started them: GitHub, the service whose app owns the check, or the repository's own concurrency group. const who = [...new Set(started.map((x) => x.by || "GitHub"))]; @@ -1274,7 +1274,7 @@ export function refusedRerunText(refusal) { const why = refusal?.earlier ? "a rerun was refused earlier on this Objective" : refusal?.permission ? `${status}: the token cannot rerun jobs` : refusal?.rateLimited ? `${status}: rate limited` : status; const grant = refusal?.where === "actions" ? "give the workflow's work and review jobs `actions: write`" : "give the token Actions read and write"; const what = refusal?.unchanged ? "GitHub refused the rerun of the failed jobs" : `red-check triage read it as a flake or infrastructure (${jobs}), but GitHub refused the rerun`; - return `${what} (${why}); rerun the failed jobs on GitHub${refusal?.permission || refusal?.earlier ? `, or ${grant},` : ""} then re-apply the label`; + return `${what} (${why}); rerun the failed jobs on GitHub${refusal?.permission || refusal?.earlier ? `, or ${grant},` : ""} then resume through Draft`; } /** diff --git a/plugin/scripts/lib/worker-relay.mjs b/plugin/scripts/lib/worker-relay.mjs index ffeaab7a..7fbe9da0 100644 --- a/plugin/scripts/lib/worker-relay.mjs +++ b/plugin/scripts/lib/worker-relay.mjs @@ -255,7 +255,7 @@ export async function openWorkerRelay({ inputs, shell, usageDir, env = process.e const sandboxed = local || !!agent; const bwrap = sandboxed ? which("bwrap", { PATH: SAFE_PATH }) || (local ? which("bwrap", env) : null) : null; const socat = sandboxed ? which("socat", { PATH: SAFE_PATH }) || (local ? which("socat", env) : null) : null; - if (sandboxed && (!bwrap || !socat)) return out({ shell: rest, relay: null, blocked: `the gateway relay for ${RELAYED_NAME} needs ${[!bwrap && "bwrap", !socat && "socat"].filter(Boolean).join(" and ")} on this machine (it starts a forwarder in each command's sandbox); install it (sudo apt-get install -y bubblewrap socat), then re-apply pendulum:objective` }); + if (sandboxed && (!bwrap || !socat)) return out({ shell: rest, relay: null, blocked: `the gateway relay for ${RELAYED_NAME} needs ${[!bwrap && "bwrap", !socat && "socat"].filter(Boolean).join(" and ")} on this machine (it starts a forwarder in each command's sandbox); install it (sudo apt-get install -y bubblewrap socat), then resume through Draft` }); let dir; let group = null; let chgrp = null; diff --git a/plugin/scripts/lib/worker-secrets.mjs b/plugin/scripts/lib/worker-secrets.mjs index 2e7ec5e8..287c492a 100644 --- a/plugin/scripts/lib/worker-secrets.mjs +++ b/plugin/scripts/lib/worker-secrets.mjs @@ -262,5 +262,5 @@ export function missingSecretsFix(names, spec = "", route = "runner") { const fresh = left.filter((n) => !opted.includes(n)); if (fresh.length) parts.push(`The worker's shell lacked ${named(fresh)}. If the Objective needs ${fresh.length === 1 ? "it" : "them"}, opt ${fresh.length === 1 ? "it" : "them"} in with the \`worker_secrets\` input (\`PENDULUM_WORKER_SECRETS\` in the workflow's env block) as \`NAME=SOURCE\`, with SOURCE's value ${where}.`); if (opted.length) parts.push(`${named(opted)} ${opted.length === 1 ? "is" : "are"} opted in with \`worker_secrets\` but had no value: set ${opted.length === 1 ? "its" : "their"} SOURCE ${where}, as a key of its own (never Pendulum's \`AI_GATEWAY_API_KEY\`).`); - return `${parts.join(" ")} Any code the worker runs can read and spend such a key: use a dedicated key with a budget the provider enforces (docs/PLAN.md, Worker secrets). Then re-apply \`pendulum:objective\`.`; + return `${parts.join(" ")} Any code the worker runs can read and spend such a key: use a dedicated key with a budget the provider enforces (docs/PLAN.md, Worker secrets). Then resume through Draft.`; } diff --git a/plugin/scripts/local.mjs b/plugin/scripts/local.mjs index 620f20dc..3d7850a1 100644 --- a/plugin/scripts/local.mjs +++ b/plugin/scripts/local.mjs @@ -68,7 +68,7 @@ import { SKIP_SMUDGE_ENV, lfsPinEnv } from "./lib/lfs.mjs"; import { EDITED_REASON, authorGate, foundationTrusted, labelsVouched, objectiveInputs, planStateNow, recordText, settled, startedAt, trustedIssue } from "./lib/objective-trust.mjs"; import { openEditCheck } from "./lib/edit-check.mjs"; import { openCommentCheck } from "./lib/comment-check.mjs"; -import { DRAFT_LABEL, goTrust, isDraft, labelTrust, requeuedIn, stopCause } from "./lib/stop.mjs"; +import { DRAFT_LABEL, goTrust, isDraft, labelTrust, readDraftActivationHold, requeuedIn, stopCause } from "./lib/stop.mjs"; import { loopCap, machineBudget, machineLimits, machineRoom, readPressure, slotHolders, slotsDir, takeSlot } from "./lib/machine.mjs"; import { lapseFacts, lapseInput, openLapseCheck } from "./lib/lapse-check.mjs"; import { flushDecisionSpend } from "./lib/decision-spend.mjs"; @@ -162,7 +162,7 @@ export const runExit = (r) => (r?.exit === "delivered" ? 0 : r?.exit === "paused const twoPinsLine = (labels) => `${labels.map(pinLabelText).join(", ")}: more than one account label moves nothing, so the Objective waits, on no account, until one is left`; /** What a Blocked notice tells a person to do about an account label this machine cannot act on (#265). */ -const PIN_FIX = "Apply one `pendulum:account:<name>` naming an account of this Objective's harness that this machine declares (~/.config/pendulum/accounts.json; doctor.mjs --local lists them), as a person who can push, or remove the label to run on the harness's default account; then re-apply `pendulum:objective`."; +const PIN_FIX = "Apply one `pendulum:account:<name>` naming an account of this Objective's harness that this machine declares (~/.config/pendulum/accounts.json; doctor.mjs --local lists them), as a person who can push, or remove the label to run on the harness's default account; then resume through Draft."; /** Whether a stage's result.json shows a pass its provider served (output or credits), with no usage limit ending it. */ /** A usage limit or quota that Blocked it with no reset reported (`limitRefused`) is a refusal too, never a served pass. */ const servedPass = (r) => !r.usageLimit && !r.limitRefused && [r.tokens?.output, r.aiCredits, r.premiumRequests].some((v) => Number(v) > 0); @@ -1023,7 +1023,7 @@ export class Local { // Only a declaration that cannot be used Blocks, with its fixed reason; any other failure is Pendulum's own. if (e?.code !== "account" || typeof e.reason !== "string") throw e; log(`#${issue}: refusing to run: ${e.message}`); - return { ok: false, reason: e.reason, fix: "Fix those accounts in ~/.config/pendulum/accounts.json on this machine (doctor.mjs --local names what is wrong with each), then re-apply `pendulum:objective`." }; + return { ok: false, reason: e.reason, fix: "Fix those accounts in ~/.config/pendulum/accounts.json on this machine (doctor.mjs --local names what is wrong with each), then resume through Draft." }; } if (pin.problem) { // A Block: the kept labeler check goes with it, so whatever is applied next is read afresh. @@ -1037,14 +1037,14 @@ export class Local { // Each account's problems are in this machine's log already (accountReady); GitHub gets the names alone. const h = HARNESS_NAMES[harness] || harness; log(`#${issue}: no ${h} account can run here: ${unready.map((u) => u.name).join(", ")}`); - return { ok: false, reason: `local mode on this machine cannot run ${h} on any of its accounts (${unready.map((u) => `\`${u.name}\``).join(", ")}); the loop's log names what is missing for each`, fix: "Set those accounts' logins up on this machine (doctor.mjs --local checks each), then re-apply `pendulum:objective`." }; + return { ok: false, reason: `local mode on this machine cannot run ${h} on any of its accounts (${unready.map((u) => `\`${u.name}\``).join(", ")}); the loop's log names what is missing for each`, fix: "Set those accounts' logins up on this machine (doctor.mjs --local checks each), then resume through Draft." }; } if (pin.account) account = pin.account; const problems = this.harnessReady(harness, account); if (!problems.length) return { ok: true, harness, hosts: chosen.hosts, account, ...(pin.account ? { pinned: true, pin: pin.label } : {}), ...(auto ? { auto } : {}) }; // What is missing stays in this machine's log: a path or a probe's output never reaches GitHub (block()). log(`#${issue}: ${harness} cannot run here: ${problems.join("; ")}`); - return { ok: false, reason: `local mode on this machine cannot run ${harness}, which this Objective's harness label asks for; the loop's log names what is missing`, fix: "Set that harness up on this machine (doctor.mjs --local with PENDULUM_HARNESS set to it names what is missing) and re-apply `pendulum:objective`, or run the Objective where that harness is set up." }; + return { ok: false, reason: `local mode on this machine cannot run ${harness}, which this Objective's harness label asks for; the loop's log names what is missing`, fix: "Set that harness up on this machine (doctor.mjs --local with PENDULUM_HARNESS set to it names what is missing) and resume through Draft, or run the Objective where that harness is set up." }; } /** @@ -2095,7 +2095,7 @@ export class Local { const times = count === 1 ? "" : count === 2 ? " twice in a row" : ` ${count} times in a row`; log(`#${issue}: ${what}${times ? " again" : ""}${judged}; Blocking it${where}`); try { - await this.block(issue, stage, `${said(postedError(failure))}${times} on this machine${judged}${where}`.replaceAll(homedir(), "~"), { cause: "pendulum", ...(failure ? { fix: "Fix it on this machine (the local loop's log has the failure), then re-apply `pendulum:objective`." } : {}) }); + await this.block(issue, stage, `${said(postedError(failure))}${times} on this machine${judged}${where}`.replaceAll(homedir(), "~"), { cause: "pendulum", ...(failure ? { fix: "Fix it on this machine (the local loop's log has the failure), then resume through Draft." } : {}) }); await dropClaim(this.repo, issue, this.holder, this.opts); } catch (e) { log(`#${issue}: the Block could not be written (${String(e?.message || e).slice(0, 120)}); the claim stays`); @@ -2203,7 +2203,7 @@ export class Local { this.lapsed?.delete(issue); log(`#${issue}: Blocking it: ${reason}`); try { - await this.block(issue, result?.stage || "work", reason, { cause: "provider-quota", fix: `Re-apply \`pendulum:objective\` once a ${h} account is free again.` }); + await this.block(issue, result?.stage || "work", reason, { cause: "provider-quota", fix: `Resume through Draft once a ${h} account is free again.` }); await dropClaim(this.repo, issue, this.holder, this.opts); } catch (e) { log(`#${issue}: the Block could not be written (${String(e?.message || e).slice(0, 120)}); the claim stays`); @@ -2798,14 +2798,17 @@ export class Local { // Only GitHub's own 5xx is GitHub's status page's to judge: a pause on another host waits on, within the bound. const verdict = paused && serverDown(off.code) && !!off.server && off.origin === githubOrigin() && now - off.since < OUTAGE.blockMs ? await this.serverVerdict(issue, off) : null; const own = verdict?.block ?? null; + const draftOpts = { ...this.opts, cache: (this.timelines ??= new Map()) }; if (paused && (own || now - off.since >= OUTAGE.blockMs)) { + const data = await getIssue(this.repo, issue, this.opts).catch(() => null); + if (!data || stopCause(data, this.objectiveLabel()) || await readDraftActivationHold(this.repo, issue, this.objectiveLabel(), draftOpts)) return { exit: "skipped" }; // GitHub answers here; the host the stage could not reach may still not (a provider), and the notice says which. const back = serverDown(off.code) || !off.origin || (await probeHost(off.origin)) === null; const reason = own - ? `${lostText(off.host, off.code, off.endpoint)} from ${whenText(off.server.requestSince ?? off.since)}; ${own}, before and after one more try, so the failure is this request's, not a GitHub incident. Re-apply the label to run it again once that request is fixed.` + ? `${lostText(off.host, off.code, off.endpoint)} from ${whenText(off.server.requestSince ?? off.since)}; ${own}, before and after one more try, so the failure is this request's, not a GitHub incident. Resume through Draft to run it again once that request is fixed.` : serverDown(off.code) - ? `${lostText(off.host, off.code, off.endpoint)} from ${whenText(off.since)}, through ${pausesText(off.server?.pauses ?? 1)} over ${minutesText(now - off.since)}, past Pendulum's ${minutesText(OUTAGE.blockMs)} bound for ${off.host} failing. Re-apply the label to run it again once ${off.host} answers that request.` - : `${lostText(off.host, off.code)} from ${whenText(off.since)} for ${minutesText(now - off.since)}, past Pendulum's ${minutesText(OUTAGE.blockMs)} bound for an outage. ${back ? "The network is back: re-apply the label to run it again." : `${off.host} is still unreachable from this machine: re-apply the label once it answers.`}`; + ? `${lostText(off.host, off.code, off.endpoint)} from ${whenText(off.since)}, through ${pausesText(off.server?.pauses ?? 1)} over ${minutesText(now - off.since)}, past Pendulum's ${minutesText(OUTAGE.blockMs)} bound for ${off.host} failing. Resume through Draft to run it again once ${off.host} answers that request.` + : `${lostText(off.host, off.code)} from ${whenText(off.since)} for ${minutesText(now - off.since)}, past Pendulum's ${minutesText(OUTAGE.blockMs)} bound for an outage. ${back ? "The network is back: resume through Draft to run it again." : `${off.host} is still unreachable from this machine: resume through Draft once it answers.`}`; log(`#${issue}: ${reason}`); try { await this.block(issue, off.stage || "work", reason, { cause: own ? "pendulum" : "outage" }); @@ -2837,6 +2840,7 @@ export class Local { log(`#${issue}: its PR or issue could not be read (${String(e.message).slice(0, 120)}); the claim stays and the next tick tries again`); return { exit: "skipped" }; } + if (stopCause(data, this.objectiveLabel()) || await readDraftActivationHold(this.repo, issue, this.objectiveLabel(), draftOpts)) return { exit: "skipped" }; // A PR still waiting for its review pass goes to review (as pendingReviews); Running work (a first run, or a // send-back rebase) runs again; anything else (reviewed, waiting in the merge queue) needs nothing here. const next = stageFor({ pr, issue: data }); @@ -2985,7 +2989,7 @@ export class Local { // No longer Running (a person moved it): nothing of this loop's to undo or read again. failures.delete(issue); } else if (count >= START_FAILURES_BLOCK) { - await this.block(issue, "work", `could not start on this machine ${count} times in a row (${e.startFailed}${e.code ? `, ${e.code}` : ""}): ${error}. Fix the machine (disk space, the sandbox, the harness login), then re-apply the label.`); + await this.block(issue, "work", `could not start on this machine ${count} times in a row (${e.startFailed}${e.code ? `, ${e.code}` : ""}): ${error}. Fix the machine (disk space, the sandbox, the harness login), then resume through Draft.`); failures.delete(issue); if (!unknown) await dropClaim(this.repo, issue, this.holder, this.opts); this.lapsed?.delete(issue); @@ -3478,8 +3482,8 @@ export class Local { * Open PRs labelled pendulum:review whose Objective is routed here and held by no loop: the label is the review trigger, * as on Actions. Not a draft PR (a Question or a Block: the reviewer waits for a person) nor a Blocked Objective's. * A Question's PR a person marked ready (#339) is one too, as the Action's ready_for_review event makes it: out of - * draft, its issue still a Question, marked ready after the Question was asked (readyAfter), and its Objective label - * not re-applied since by a person who can push (that reruns its work stage instead: the dispatcher's recovery). The review applies the answer; + * draft, its issue still a Question, marked ready after the Question was asked (readyAfter), and without an activation + * by a person who can push since it was asked (the dispatcher requeues those for work). The review applies the answer; * with none since the Question, a body still asking a `QUESTION:` makes it a Question again (review.mjs readyMark). */ async pendingReviews() { @@ -3495,13 +3499,13 @@ export class Local { const data = asked ?? (await getIssue(this.repo, issue, this.opts).catch(() => null)); // A stopped Objective (its label removed, its issue closed: stop.mjs) gets no review. if (!data || isBlocked(data) || stopCause(data, this.objectiveLabel()) || !BACKENDS.local.trigger.routes(data, this.baseEnv())) continue; + const events = await timelineOf(this.repo, issue, cached).catch(() => null); + if (await readDraftActivationHold(this.repo, issue, this.objectiveLabel(), cached, events)) continue; if (asked) { - const events = await timelineOf(this.repo, issue, cached).catch(() => null); - // The Objective label re-applied since the Question by a person who can push (requeuedIn) is the go to run its - // work stage again: this tick's dispatch puts it back to Queued and picks it, so a ready mark beside it starts - // no review. A re-apply whose actor is unread waits with the dispatcher; anyone else's changes nothing. - const go = events ? await requeuedIn(events, this.objectiveLabel(), goTrust(events, issue, labelTrust(this.repo, this.opts))) : null; - if (!go || go.requeued || go.unread) continue; + // An activation since the Question by a person who can push runs its work stage again. Wait while Draft removal + // or the activation actor cannot be verified, as the dispatcher does. + const go = await requeuedIn(events, this.objectiveLabel(), goTrust(events, issue, labelTrust(this.repo, this.opts))); + if (go.requeued || go.unread) continue; const askedAt = labeledAtIn(events, "pendulum:question"); if (!readyAfter(askedAt ? await timelineOf(this.repo, pr.number, cached).catch(() => []) : [], askedAt)) continue; } @@ -4317,7 +4321,7 @@ const sessionIssueFile = (dir) => join(process.env.PENDULUM_IN || resolve(dir, s /** A session's refusal of an issue whose author, last editor or latest title renamer cannot vouch for it: the Blocked notice's words. */ const untrustedRefusal = (t, what) => new Error(`${what}: ${t.reason}. ${t.fix}`); /** A draft (pendulum:draft) is run on no route, a session's included (lib/stop.mjs stopCause): the refusal and its fix. */ -const draftRefusal = (issue, what) => new Error(`${what}: #${issue} is a draft (${DRAFT_LABEL}), which Pendulum never runs; start it first (take ${DRAFT_LABEL} off and apply the Objective label, or ask "Start Pendulum Objective ${issue}")`); +const draftRefusal = (issue, what) => new Error(`${what}: #${issue} is a draft (${DRAFT_LABEL}), which Pendulum never runs; start it first (ensure it has the Objective label, then remove ${DRAFT_LABEL}, or ask "Start Pendulum Objective ${issue}")`); /** * `pendulum issue <issue> [--out FILE]`: the issue as a session reads it (/pendulum:pendulum-run --here, /pendulum:pendulum-review-here), written diff --git a/plugin/scripts/review.mjs b/plugin/scripts/review.mjs index 00425d77..3dd57733 100644 --- a/plugin/scripts/review.mjs +++ b/plugin/scripts/review.mjs @@ -114,7 +114,7 @@ import { redLines, } from "./lib/session.mjs"; import { eventPayload, stageSealKey, usageSeal } from "./lib/seal.mjs"; -import { claimExit, commitExit, confirmRunning, holdIfStopped, goTrust, labelTrust, objectiveReader, parked, requeuedIn, stopCause, stopText, watchObjective } from "./lib/stop.mjs"; +import { claimExit, commitExit, confirmRunning, holdIfStopped, draftActivationHold, goTrust, labelTrust, objectiveReader, parked, requeuedIn, stopCause, stopText, watchObjective } from "./lib/stop.mjs"; import { timelineOf } from "./lib/relaunch.mjs"; import { CODE_SCANNING, answeredReviewers, clearWait, exitUnaddressed, thirdPartyStep, unlistedRule, waitEnd } from "./lib/third-party-review.mjs"; import { asksQuestion, stageSpendLine, stateOf, usdText } from "./lib/logic.mjs"; @@ -457,19 +457,20 @@ export function workOwnsBranch({ action = null, sender = null, issue = null }) { /** * Why a person's ready mark starts no review, or null, read on the issue's timeline too: workOwnsBranch, or a Question - * whose Objective `label` a person who can push re-applied since it was asked (stop.mjs requeuedIn, the dispatcher's own - * rule). That go wins over the mark beside it: the dispatcher puts the Objective back to Queued and starts its work - * stage, so this review ends at once. A re-apply by anyone else changes nothing, and one whose actor could not be - * checked for now, or a timeline that cannot be read, leaves the mark's review to run (the dispatcher waits for a - * Question's live review job before it requeues it). The timeline is read only for a person's mark on a Question. + * a person who can push reactivated since it was asked (stop.mjs requeuedIn, the dispatcher's own rule). That activation + * puts the Objective back to Queued and starts its work stage. The Draft check applies to every review entry point. + * For older question activations without Draft, an unauthorized or unread actor leaves the mark's review to run + * (the dispatcher waits for a live Question review before it requeues work). */ export async function readyOwner({ repo, action = null, sender = null, issue = null, label, opts }) { const owned = workOwnsBranch({ action, sender, issue }); - if (owned || action !== "ready_for_review" || sender?.type === "Bot" || !issue || stateOf(issue, null) !== "Question") return owned; + if (owned || !issue) return owned; const events = await timelineOf(repo, issue.number, opts).catch(() => null); - if (!events) return null; - const go = await requeuedIn(events, label, goTrust(events, issue.number, labelTrust(repo, opts))); - return go.requeued ? `marked ready beside ${label} re-applied since the Question: its work stage runs again on pendulum/${issue.number}` : null; + const trusted = labelTrust(repo, opts); + const hold = await draftActivationHold(events, issue.number, label, trusted); + if (hold || action !== "ready_for_review" || sender?.type === "Bot" || stateOf(issue, null) !== "Question") return hold; + const go = await requeuedIn(events, label, goTrust(events, issue.number, trusted)); + return go.requeued ? `marked ready beside an activation since the Question: its work stage runs again on pendulum/${issue.number}` : null; } /** diff --git a/plugin/scripts/worker.mjs b/plugin/scripts/worker.mjs index 3f9ce96f..c4ec3e61 100644 --- a/plugin/scripts/worker.mjs +++ b/plugin/scripts/worker.mjs @@ -125,7 +125,7 @@ export async function sendBackGuard({ outbox, onto, defaultBranch, judge = null, ? `; this pass left nothing to keep, so the result of an earlier one kept on the branch \`${kept.name}\` of ${clone} was removed` : kept.failed ? `; its result could not be kept on a branch of ${clone} (the local loop's log says why)` - : `; the conflict pass's result is kept as ${kept.sha} on the branch \`${kept.name}\` of ${clone}. To deliver it, first check that it keeps the Objective's change and touches no secret or protected path (Pendulum's push checks did not run on it), then run \`git push --force-with-lease origin ${kept.name}:${kept.branch}\` in that clone and re-apply the Objective's label: the stages after it validate and review that head like any other`; + : `; the conflict pass's result is kept as ${kept.sha} on the branch \`${kept.name}\` of ${clone}. To deliver it, first check that it keeps the Objective's change and touches no secret or protected path (Pendulum's push checks did not run on it), then run \`git push --force-with-lease origin ${kept.name}:${kept.branch}\` in that clone and resume through Draft: the stages after it validate and review that head like any other`; const why = `the worker could not resolve the conflict with \`${defaultBranch}\` at ${onto.base.slice(0, 7)} in ${conflictFiles(onto.files)}: ${left}; nothing of it was pushed${resume}`; outbox.block(why); log(why); diff --git a/plugin/test/account-move.test.mjs b/plugin/test/account-move.test.mjs index 34af1555..96275f24 100644 --- a/plugin/test/account-move.test.mjs +++ b/plugin/test/account-move.test.mjs @@ -572,7 +572,7 @@ test("#332: PENDULUM_LOCAL_ENV never carries a control variable into a stage, so await off.spentPaused(8, { stage: "work", account: "alpha", hold: { key: "alpha", shared: true }, usageLimit: { harness: "claude", reset: null, since: new Date(t).toISOString(), noReset: true } }); assert.equal(off.holds.avoidUntil("alpha", t), null, "no guess"); assert.equal(gh.blocked().length, 1, "Blocked, as with no move"); - assert.match(gh.blocked()[0].body, /Re-apply `pendulum:objective` once a Claude Code account is free again\./); + assert.match(gh.blocked()[0].body, /Resume through Draft once a Claude Code account is free again\./); }); } finally { gh.restore(); diff --git a/plugin/test/draft.test.mjs b/plugin/test/draft.test.mjs index 95843ac3..9dd68de8 100644 --- a/plugin/test/draft.test.mjs +++ b/plugin/test/draft.test.mjs @@ -1,6 +1,5 @@ // Draft Objectives (#204): an issue with `pendulum:draft` is never run, on any route, even with `pendulum:objective` on -// it too: no dispatch, no claim, no spend. Starting one takes the draft label off and applies the Objective label; the -// scorecard's clock starts there. +// it too: no dispatch, no claim, no spend. Removing Draft starts an admitted Objective and keeps its identity. import "./temp.mjs"; import assert from "node:assert/strict"; import { mkdtempSync } from "node:fs"; @@ -65,6 +64,7 @@ function fakeApi({ issues = () => [], pr = () => null, timeline = () => [], issu if (method === "GET" && onePr) return json({ number: Number(onePr[1]), state: "open", draft: false, node_id: `PR_${onePr[1]}`, mergeable_state: "clean", head: { sha: "a".repeat(40), ref: "pendulum/7" }, base: { ref: "main" }, labels: [] }); if (method === "GET" && /\/issues\/\d+\/timeline$/.test(u.pathname)) return json(timeline(Number(/issues\/(\d+)\//.exec(u.pathname)[1]))); if (method === "GET" && u.pathname.endsWith("/collaborators")) return json([{ login: "maintainer" }]); + if (method === "GET" && u.pathname.endsWith("/collaborators/triager/permission")) return json({ permission: "triage" }); if (method === "GET" && /\/actions\/workflows\/[^/]+\/runs$/.test(u.pathname)) return json({ workflow_runs: [] }); if (method === "GET" && u.pathname.endsWith("/actions/artifacts")) return json({ artifacts: [] }); if (method === "GET" && /\/comments$/.test(u.pathname)) return json([]); @@ -117,6 +117,33 @@ test("dispatcher: a draft is never picked or restarted, even beside pendulum:obj assert.deepEqual(one.writes, []); }); +test("dispatcher waits for the Draft removal event and starts with Objective identity retained", async () => { + const { dispatch } = await import("../scripts/dispatch.mjs"); + const actor = { login: "maintainer", type: "User" }; + const at = (minutesAgo) => new Date(Date.now() - minutesAgo * 60_000).toISOString(); + const record = (event, name, created_at) => ({ event, label: { name }, actor, created_at }); + // The issue listing already shows Draft off. Its timeline still shows the issue as held for editing. + const timeline = [record("labeled", OBJ, at(3)), record("labeled", DRAFT_LABEL, at(2))]; + const tick = () => withApi({}, async () => { + setSelf("pendulum-app[bot]"); + const api = fakeApi({ issues: (label) => (label === OBJ ? [issue([OBJ])] : []), timeline: () => timeline }); + try { + return { result: await dispatch(INPUTS, { token: "t" }), writes: api.writes }; + } finally { + api.restore(); + setSelf(null); + } + }); + const unread = await tick(); + assert.deepEqual(unread.result.ready, []); + assert.match(unread.result.skipped[0].reason, /Draft removal is not yet visible/); + + timeline.push(record("unlabeled", DRAFT_LABEL, at(1))); + const ready = await tick(); + assert.deepEqual(ready.result.ready, [7]); + assert.ok(!ready.writes.includes(`DELETE /issues/7/labels/${OBJ}`)); +}); + test("the merge pass never merges a draft's PR, whoever runs it", async () => { const { mergeReadyOne } = await import("../scripts/lib/session.mjs"); await withApi({}, async () => { @@ -130,6 +157,43 @@ test("the merge pass never merges a draft's PR, whoever runs it", async () => { }); }); +test("merge and cloud review wait for a visible and authorized Draft removal", async () => { + const { launchOne } = await import("../scripts/launch.mjs"); + const { mergeReadyOne } = await import("../scripts/lib/session.mjs"); + const actor = { login: "maintainer", type: "User" }; + const timeline = [ + { event: "labeled", label: { name: OBJ }, created_at: "2026-10-10T10:00:00Z", actor }, + { event: "labeled", label: { name: DRAFT_LABEL }, created_at: "2026-10-10T10:10:00Z", actor }, + ]; + const removeDraft = (minute, by) => ({ event: "unlabeled", label: { name: DRAFT_LABEL }, created_at: `2026-10-10T10:${minute}:00Z`, actor: by }); + await withApi({}, async () => { + setSelf("pendulum-app[bot]"); + const api = fakeApi({ timeline: (n) => n === 7 ? timeline : [], issue: (n) => n === 7 ? issue([OBJ, "pendulum:in-review"]) : null }); + const merge = () => mergeReadyOne(REPO, { issue: 7, prNumber: 70, queue: false, objectiveLabel: OBJ }, { token: "t" }); + const launch = () => launchOne({ + inputs: { ...INPUTS, appToken: "t" }, + eventName: "pull_request", + payload: { action: "ready_for_review", sender: actor, pull_request: { number: 70, head: { ref: "pendulum/7", repo: { full_name: REPO.full } } } }, + gate: true, + }); + try { + assert.equal(await merge(), "pending"); + assert.match((await launch()).reason, /Draft removal is not yet visible/); + timeline.push(removeDraft(11, { login: "triager", type: "User" })); + assert.equal(await merge(), "pending"); + assert.match((await launch()).reason, /Draft activation was not authorized/); + assert.deepEqual(api.writes, []); + + timeline.push({ ...timeline[1], created_at: "2026-10-10T10:12:00Z" }, removeDraft(13, actor)); + assert.equal(await merge(), "not-recorded", "an authorized removal passes Draft admission to normal merge validation"); + assert.equal((await launch()).exit, "start", "an authorized removal passes Draft admission to the launcher"); + } finally { + api.restore(); + setSelf(null); + } + }); +}); + test("local mode: `pendulum run` refuses a draft before any claim; a draft is neither resumed nor reviewed", async () => { const { Local, holderId } = await import("../scripts/local.mjs"); const { claimBody } = await import("../scripts/lib/local.mjs"); @@ -178,4 +242,10 @@ test("a Blocked or Question Objective made a draft and started by taking the dra } // A draft removal from before the Block is no restart of the Blocked run. assert.equal(await run([ev("labeled", DRAFT_LABEL, at(1)), ev("labeled", OBJ, at(1)), ev("unlabeled", DRAFT_LABEL, at(2)), ev("labeled", "pendulum:blocked", at(3))]), false); + // A state change and a maintainer's recovery can share a second. The timeline records their order. + const held = [ev("labeled", OBJ, at(1)), ev("labeled", DRAFT_LABEL, at(2))]; + const blocked = ev("labeled", "pendulum:blocked", at(3)); + const activated = ev("unlabeled", DRAFT_LABEL, at(3)); + assert.equal(await run([...held, blocked, activated]), true); + assert.equal(await run([...held, activated, blocked]), false); }); diff --git a/plugin/test/edit-after-plan.test.mjs b/plugin/test/edit-after-plan.test.mjs index 856fe1d7..ce1c551e 100644 --- a/plugin/test/edit-after-plan.test.mjs +++ b/plugin/test/edit-after-plan.test.mjs @@ -85,7 +85,7 @@ for (const { route, self, person } of ROUTES) { assert.equal(BLOCK_CAUSES[review.applied[0].cause].external, false, "an edit is a person's action, never External"); const notice = blockedLine({ issue: 7, pr: { number: 9 }, stage: "review", reason: EDITED_REASON, fix: EDITED_FIX }); assert.match(notice, /title, body or harness, model and host labels \(`pendulum:harness:`, `pendulum:model:`, `pendulum:subagent-model:`, `pendulum:reviewer-model:`, `pendulum:host:`\) changed after its plan was made/); - assert.match(notice, /Re-apply `pendulum:objective` to work from the issue as it is now, its text and its harness, model and host labels: the worker makes its plan again from it/); + assert.match(notice, /To work from the issue as it is now, add `pendulum:draft` if it is missing, then remove it to resume. The worker makes its plan again from the current text and harness, model and host labels/); }); test(`edit after plan (${route}): a comment answering a Question is no edit`, async () => { diff --git a/plugin/test/exit.test.mjs b/plugin/test/exit.test.mjs index 191a7939..27336c74 100644 --- a/plugin/test/exit.test.mjs +++ b/plugin/test/exit.test.mjs @@ -67,7 +67,7 @@ test("deniedHosts: a blocked exit record's host names, checked for DNS shape, be assert.equal(decideExit({ harness: ok, pr: null, commits: 0, record: rec }).reason, "worker blocked: the proof needs the download host"); assert.equal(decideExit({ harness: ok, pr: null, commits: 0, record: { exit: "blocked", reason: "x", questions: [] } }).deniedHosts, undefined, "without hosts no host fix"); assert.equal(decideExit({ harness: ok, pr: pr(), commits: 1, validation: green, protectedHits: [".github/x"], record: rec }).deniedHosts, undefined, "a Block of Pendulum's own carries no host fix"); - assert.equal(deniedHostsFix(["cdn.example.org"]), "The local sandbox denied `cdn.example.org`. If the Objective needs it, a person who can push applies `pendulum:host:cdn.example.org` to this issue, which opens it to this Objective alone, then re-applies `pendulum:objective`. To open it to every Objective, add it to `PENDULUM_LOCAL_DOMAINS` (a running `serve` reads it when it restarts), then re-apply `pendulum:objective`."); + assert.equal(deniedHostsFix(["cdn.example.org"]), "The local sandbox denied `cdn.example.org`. If the Objective needs it, a person who can push applies `pendulum:host:cdn.example.org` to this issue, which opens it to this Objective alone, then resumes through Draft. To open it to every Objective, add it to `PENDULUM_LOCAL_DOMAINS` (a running `serve` reads it when it restarts), then resume through Draft."); assert.match(deniedHostsFix(["a.example.com", "b.example.com"]), /denied `a\.example\.com`, `b\.example\.com`\. If the Objective needs them, .*To open them to every Objective, add them to `PENDULUM_LOCAL_DOMAINS`/); assert.match(deniedHostsFix(["github.com", "a.cdn.example.com", "b.example.com"], ["github.com", "*.cdn.example.com"]), /denied `b\.example\.com`\./, "hosts already allowed are left out"); assert.equal(deniedHostsFix(["github.com"], ["github.com"]), null, "allowed already: the generic fix stands"); diff --git a/plugin/test/finding-check.test.mjs b/plugin/test/finding-check.test.mjs index 2d101622..70f61bf3 100644 --- a/plugin/test/finding-check.test.mjs +++ b/plugin/test/finding-check.test.mjs @@ -236,7 +236,7 @@ test("#368: only a reply by someone who can push answers Pendulum's finding; a s const exitFor = (n) => decideExit({ harness: { ok: true }, pr: { exists: true }, commits: 1, validation: { green: true, passes: 0 }, reviewUnaddressed: n }); test("#368: findings still open after the answer pass get another answer round within the bound, then the Block names them and how to clear them", async () => { - const gh = github(); + const gh = github({ writers: ["kirk"] }); const open = [{ id: 200, path: "src/b.ts", line: 9 }, { id: "r1-1", path: "src/c.ts", line: 4 }]; await withGitHub(gh, async () => { const stage = () => openFindingsExit(exitFor(open.length), { repo: REPO, issue: 7, prNumber: 12, objectiveLabel: "pendulum:objective", open }, { token: "t" }); @@ -247,11 +247,18 @@ test("#368: findings still open after the answer pass get another answer round w assert.deepEqual(gh.state.labels, ["pendulum:review", "pendulum:review"]); assert.equal(gh.state.issueComments.filter((c) => c.body.startsWith(marker(7, "answer-rounds"))).length, 1, "one record on the issue"); const d = await stage(); - assert.deepEqual(d, { exit: "blocked", cause: "work", reason: "2 reviewer finding(s) still open on PR #12 after 2 answer round(s): src/b.ts:9; src/c.ts:4. Fix them on the branch, or answer each on the PR: a reply by someone who can push in its thread, or resolve the thread (for a finding in the review body, a comment by someone who can push starting `<!-- pendulum:7:resolved:<finding id> -->`); then re-apply `pendulum:objective` to resume" }); + assert.deepEqual(d, { exit: "blocked", cause: "work", reason: "2 reviewer finding(s) still open on PR #12 after 2 answer round(s): src/b.ts:9; src/c.ts:4. Fix them on the branch, or answer each on the PR: a reply by someone who can push in its thread, or resolve the thread (for a finding in the review body, a comment by someone who can push starting `<!-- pendulum:7:resolved:<finding id> -->`); then add `pendulum:draft` if it is missing, then remove it to resume" }); assert.equal(gh.state.labels.length, 2, "no third round"); - // A re-entry (the Objective label applied again) starts the count over. - gh.state.timeline = [{ event: "labeled", label: { name: "pendulum:objective" }, created_at: new Date(Date.now() + 1000).toISOString() }]; - assert.equal((await stage()).rerun, true); + const at = Date.now(); + const toggle = (event, name, login, offset) => ({ event, label: { name }, actor: { login, type: "User" }, created_at: new Date(at + offset).toISOString() }); + gh.state.timeline = [ + toggle("labeled", "pendulum:objective", "kirk", -60_000), + toggle("labeled", "pendulum:draft", "kirk", 1000), + toggle("unlabeled", "pendulum:draft", "viewer", 2000), + ]; + assert.equal((await stage()).exit, "blocked", "an unauthorized Draft removal cannot reset exhausted rounds"); + gh.state.timeline.push(toggle("labeled", "pendulum:draft", "kirk", 3000), toggle("unlabeled", "pendulum:draft", "kirk", 4000)); + assert.equal((await stage()).rerun, true, "trusted Draft removal starts the answer round count over"); }); }); @@ -283,7 +290,7 @@ test("#368: an answer the gateway gave no verdict on costs no answer round: the assert.deepEqual(checkState(rec), { unjudged: [300], failed: 1, error: "unavailable", judgeOnly: true }, "the next stage only judges: no worker pass for them"); // The next stage judged it again and the gateway failed again: Blocked, its cause from the code. const d2 = await openFindingsExit(exitFor(1), { ...ctx, open, unjudged: [{ id: 300, error: "rate_limited" }] }, { token: "t" }); - assert.deepEqual(d2, { exit: "blocked", cause: "provider-quota", reason: "the AI Gateway's decision model gave no verdict (rate_limited) on the answers to 1 reviewer finding(s) on PR #12 in 2 review stages in a row: src/merge.ts:8. Check the AI Gateway key, its budget and the gateway's status, then re-apply `pendulum:objective` to resume" }); + assert.deepEqual(d2, { exit: "blocked", cause: "provider-quota", reason: "the AI Gateway's decision model gave no verdict (rate_limited) on the answers to 1 reviewer finding(s) on PR #12 in 2 review stages in a row: src/merge.ts:8. Check the AI Gateway key, its budget and the gateway's status, then add `pendulum:draft` if it is missing, then remove it to resume" }); assert.equal(gh.state.labels.length, 1); }); // A stage that judged them, with others open, ends the run of failures and takes an answer round. @@ -323,7 +330,7 @@ test("#379: the stage harness's usage limit in the finding check ends the stage assert.match(d2.reason, /^the stage's own harness \(claude claude-fable-5-2\) gave no verdict \(unavailable\)/); const d3 = await openFindingsExit(exitFor(1), { ...ctx, open, unjudged: [{ id: 300, error: "vendor" }], decider }, { token: "t" }); assert.equal(d3.exit, "blocked"); - assert.match(d3.reason, /^the stage's own harness \(claude claude-fable-5-2\) gave no verdict \(vendor\) .* in 2 review stages in a row: src\/merge\.ts:8\. Check the harness login this stage runs on and its usage, then re-apply/); + assert.match(d3.reason, /^the stage's own harness \(claude claude-fable-5-2\) gave no verdict \(vendor\) .* in 2 review stages in a row: src\/merge\.ts:8\. Check the harness login this stage runs on and its usage, then add `pendulum:draft`/); assert.doesNotMatch(d3.reason, /AI Gateway/); }); }); diff --git a/plugin/test/finish-card.test.mjs b/plugin/test/finish-card.test.mjs index 158b8756..e28d4f83 100644 --- a/plugin/test/finish-card.test.mjs +++ b/plugin/test/finish-card.test.mjs @@ -6,7 +6,8 @@ import { join } from "node:path"; import { RETRY } from "../scripts/lib/github.mjs"; import { setSelf, setWriters } from "../scripts/lib/logic.mjs"; import { PREVIOUS_NAME } from "../scripts/lib/local.mjs"; -import { centsOf, finishData, finishMarker, objectiveRecords, renderFinishCard } from "../scripts/lib/finish-card.mjs"; +import { centsOf, finishCardBody, finishData, finishMarker, labelTime, objectiveRecords, readSummary as readClockSummary, renderFinishCard } from "../scripts/lib/finish-card.mjs"; +import { refusedMarker } from "../scripts/lib/stop.mjs"; RETRY.sleep = async () => {}; @@ -34,6 +35,24 @@ const withSelf = (fn) => { setSelf(null); } }; + +test("finish card: creating a draft does not start the clock; removing Draft does", () => + withSelf(() => { + const label = real.timeline.find((e) => e.event === "labeled" && e.label?.name === "pendulum:objective"); + const filed = { ...label, created_at: new Date(Date.parse(label.created_at) - 3_600_000).toISOString() }; + const draft = { ...filed, label: { name: "pendulum:draft" } }; + const start = { ...draft, event: "unlabeled", created_at: label.created_at, actor: { login: "maintainer", type: "User" } }; + for (const creation of [[filed, draft], [draft, filed]]) { + assert.equal(labelTime(real.issue, creation), null); + const timeline = [...creation, start, ...real.timeline.filter((e) => e !== label)]; + const d = data({ timeline }); + assert.equal(d.started, label.created_at); + assert.equal(d.labelled, label.created_at); + assert.equal(d.labeller, "maintainer"); + assert.match(renderFinishCard(d), /\*\*maintainer\*\* removed the Draft label to start it\./); + assert.match(renderFinishCard(d), /removed `pendulum:draft`: the clock starts/); + } + })); // A stage's spend line (logic.mjs spendMarker), as a local or cloud sandbox stage writes it into its progress comment. const spendLine = (v) => `<!-- pendulum:spend ${JSON.stringify(v)} -->`; const withSpend = (lines, comments = real.comments) => @@ -43,6 +62,28 @@ const withSpend = (lines, comments = real.comments) => }); const comment = (id, created, body, updated = created) => ({ id, user: bot, created_at: created, updated_at: updated, body }); +test("finish clocks skip a trusted refusal and show unknown without a recorded Draft release", () => + withSelf(() => { + const label = real.timeline.find((e) => e.event === "labeled" && e.label?.name === "pendulum:objective"); + const filed = { ...label, created_at: new Date(Date.parse(label.created_at) - 3_600_000).toISOString() }; + const draft = { ...filed, label: { name: "pendulum:draft" } }; + const rejected = { ...draft, id: 901, event: "unlabeled", created_at: new Date(Date.parse(label.created_at) - 600_000).toISOString(), actor: { login: "triager", type: "User" } }; + const accepted = { ...rejected, id: 902, created_at: label.created_at, actor: { login: "maintainer", type: "User" } }; + const refusal = comment(903, rejected.created_at, refusedMarker(real.issue.number, { id: rejected.id, at: rejected.created_at })); + const after = real.timeline.filter((e) => e !== label); + const timeline = [filed, draft, rejected, { ...draft, created_at: rejected.created_at }, accepted, ...after]; + const good = data({ timeline, comments: [...real.comments, refusal] }); + assert.deepEqual([good.started, good.labelled, good.labeller], [label.created_at, label.created_at, "maintainer"]); + const running = after.find((e) => e.event === "labeled" && e.label?.name === "pendulum:running"); + assert.equal(labelTime(real.issue, timeline, "pendulum:objective", new Date(Date.parse(accepted.created_at) + 1000).toISOString(), { comments: [refusal] }), running.created_at, "a previous Draft activation does not shadow a Running start in a new window"); + + const missing = data({ timeline: [filed, draft, ...after] }); + const md = finishCardBody(missing); + const summary = readClockSummary(md, real.issue.number); + assert.deepEqual([summary.wallMs, summary.labelledWallMs, summary.labelled], [null, null, null]); + assert.match(md, /wall clock is not known because its activation was not recorded/); + })); + test("finish card: the merged run, every figure from the run's own records (scratch #3, the approved mock-up's run)", () => { const d = withSelf(() => data()); // The clock is the label; each stage is its progress comment; its dollars its usage record (progressRun). diff --git a/plugin/test/fixtures/finish-ends.snap.json b/plugin/test/fixtures/finish-ends.snap.json index 8b3f0d5c..336edc7b 100644 --- a/plugin/test/fixtures/finish-ends.snap.json +++ b/plugin/test/fixtures/finish-ends.snap.json @@ -2,9 +2,9 @@ "mergedClean": "### ✅ Merged in 37 min 33 s · $3.67 + unknown\nIssue #402 → PR #409 · merged through your merge queue at 10:31 AM PST · API-equivalent, not billed · plus 7 AI runs of unknown cost\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PR #409 (**4 commits, +355 −25 across 10 files**), got **1 CI check** green, had the change reviewed (1 finding), and it merged through your merge queue.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 10minute\n todayMarker off\n section Build\n 11m 01s :active, 2026-11-17T09:54:33, 2026-11-17T10:05:34\n section Review\n 14m 52s :active, 2026-11-17T10:05:50, 2026-11-17T10:20:42\n section Queue\n 10m 39s :active, 2026-11-17T10:20:35, 2026-11-17T10:31:14\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 9:54 AM | Plan + build · Opus 5.5 | 11 min 1 s | $1.78 + unknown |\n| 10:05 AM | Review · Fable 5.2 | 14 min 52 s | $1.89 + unknown |\n| 10:20 AM | Merge queue · your CI | 10 min 39 s | — |\n| | **Total** | **37 min 33 s** | **$3.67 + unknown** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Work $1.78 + unknown\", \"Review $1.29 + unknown\", \"Answering the review $0.60\"]\n y-axis \"USD\" 0 --> 2\n bar [1.78, 1.29, 0.60]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Work | $1.78 + unknown |\n| Review | $1.29 + unknown |\n| Answering the review | $0.60 |\n\nBars show recorded dollars only; 7 AI runs of unknown cost are not drawn. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Unknown cost:** 7 AI judge calls went through the AI Gateway, which did not report their cost. They are counted as unknown, never as $0.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- 9:53:41 AM labelled `pendulum:objective`: the clock starts\n- 9:54:33 AM plan + build stage started (claude-opus-5-5)\n- 10:04:00 AM PR #409 opened\n- 10:05:34 AM plan + build stage's last line: $1.78 + unknown\n- 10:05:50 AM review stage started (claude-fable-5-2)\n- 10:10:00 AM last review: 1 review in all, 1 finding\n- 10:20:35 AM added to the merge queue\n- 10:20:42 AM review stage's last line: $1.89 + unknown\n- 10:31:14 AM PR #409 merged, 1 CI check green\n\n</details>", "mergedBlocked": "### ✅ Merged · 1 h 42 min working, 41 min 32 s waiting · $12.58 + unknown\nIssue #416 → PR #428 · merged through your merge queue at 7:40 PM PST · API-equivalent, not billed · plus 14 AI runs of unknown cost\nWaited 41 min 32 s for you; 2 h 23 min from the label to the merge.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PR #428 (**7 commits, +812 −96 across 14 files**), got **1 CI check** green, had the change reviewed (6 findings), and it merged through your merge queue.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 30minute\n todayMarker off\n section Build\n 18m 02s :active, 2026-11-17T17:16:43, 2026-11-17T17:34:45\n section Review 1\n 29m 10s :active, 2026-11-17T17:35:36, 2026-11-17T18:04:46\n section Review 2\n 21m 30s :active, 2026-11-17T18:05:33, 2026-11-17T18:27:03\n section Review 3\n 3m 33s Blocked :crit, 2026-11-17T18:27:35, 2026-11-17T18:31:08\n section On hold\n 41m 32s :done, 2026-11-17T18:31:08, 2026-11-17T19:12:40\n section Work\n 5m 20s :active, 2026-11-17T19:12:40, 2026-11-17T19:18:00\n section Rebase\n 4m 05s :active, 2026-11-17T19:19:00, 2026-11-17T19:23:05\n section Review 4\n 6m 02s :active, 2026-11-17T19:23:39, 2026-11-17T19:29:41\n section Queue\n 10m 39s :active, 2026-11-17T19:29:35, 2026-11-17T19:40:14\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 5:16 PM | Plan + build · Opus 5.5 | 18 min 2 s | $4.12 + unknown |\n| 5:35 PM | Review 1 · Fable 5.2 | 29 min 10 s | $4.02 + unknown |\n| 6:05 PM | Review 2 · Fable 5.2 | 21 min 30 s | $2.31 + unknown |\n| 6:27 PM | Review 3 · Fable 5.2 · ⛔ Blocked | 3 min 33 s | $0.52 + unknown |\n| 6:31 PM | On hold · waiting for you | 41 min 32 s | — |\n| 7:12 PM | Work · Opus 5.5 | 5 min 20 s | $0.52 |\n| 7:19 PM | Rebase · Opus 5.5 | 4 min 5 s | $0.61 |\n| 7:23 PM | Review 4 · Fable 5.2 | 6 min 2 s | $0.48 |\n| 7:29 PM | Merge queue · your CI | 10 min 39 s | — |\n| | Working | 1 h 42 min | |\n| | Waiting | 41 min 32 s | |\n| | **Total** | **2 h 23 min** | **$12.58 + unknown** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Work $3.90 + unknown\", \"Review $4.90 + unknown\", \"Answering the review $2.43\", \"Fixing CI $0.22\", \"Overhead: rebases $0.61\", \"Overhead: after a Block $0.52\"]\n y-axis \"USD\" 0 --> 5\n bar [3.90, 4.90, 2.43, 0.22, 0.61, 0.52]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Work | $3.90 + unknown |\n| Review | $4.90 + unknown |\n| Answering the review | $2.43 |\n| Fixing CI | $0.22 |\n\n| Overhead Pendulum caused | Stages | Cost |\n| :-- | --: | --: |\n| Rebases after other PRs merged (conflict) | 1 | $0.61 |\n| Runs repeated after a Block | 1 | $0.52 |\n\nBars show recorded dollars only; 14 AI runs of unknown cost are not drawn. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Unknown cost:** 14 AI judge calls went through the AI Gateway, which did not report their cost. They are counted as unknown, never as $0.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- **Working and waiting:** Waiting is the time on hold in the table, each from a recorded start and end: an issue that blocked this one, from the blocked-by relation (or the label, when later) to that issue's close or the relation's removal; a stage that recorded a pause for a usage limit or an outage, and a Blocked or Question notice, each until the next stage started. A wait with no recorded start and end is not counted. Working is the rest of the time from the label to the end.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n- **How overhead is counted:** Each item comes from a stage's own record, never a guess. A stage is in the part after the PRs merged before it started; its runs are split by the kinds its spend record names. Overhead is a rebase after other PRs merged (its rebase line), a catch-up run after the default branch changed a workflow, the runs a stage records it ran again after a Block, and a review that records it was started only to judge answers already made (all of it but answering the review and fixing CI). Anything else stays in its stage, as that stage.\n\n**Run log** (PST)\n- 5:16:30 PM labelled `pendulum:objective`: the clock starts\n- 5:16:43 PM plan + build stage started (claude-opus-5-5)\n- 5:34:00 PM PR #428 opened\n- 5:34:45 PM plan + build stage's last line: $4.12 + unknown\n- 5:35:36 PM review stage started (claude-fable-5-2)\n- 6:00:00 PM last review: 1 review in all, 6 findings\n- 6:04:46 PM review stage's last line: $4.02 + unknown\n- 6:05:33 PM review stage started (claude-fable-5-2)\n- 6:27:03 PM review stage's last line: $2.31 + unknown\n- 6:27:35 PM review stage started (claude-fable-5-2)\n- 6:31:08 PM review stage's last line: $0.52 + unknown, Blocked\n- 6:31:08 PM Blocked notice: on hold until the next stage\n- 7:12:40 PM work stage started (claude-opus-5-5)\n- 7:18:00 PM work stage's last line: $0.52\n- 7:19:00 PM rebase stage started (claude-opus-5-5)\n- 7:23:05 PM rebase stage's last line: $0.61\n- 7:23:39 PM review stage started (claude-fable-5-2)\n- 7:29:35 PM added to the merge queue\n- 7:29:41 PM review stage's last line: $0.48\n- 7:40:14 PM PR #428 merged, 1 CI check green\n\n</details>", "closedUnmerged": "### ⏹️ Closed without merging after 1 h 12 min · $4.20\nIssue #230 · PR #236 closed, not merged · closed at 3:02 PM PST · API-equivalent, not billed\n\nYou wrote the issue and added the label. Pendulum planned the work and opened PR #236 (**3 commits, +120 −14 across 5 files**); you closed the issue before it merged.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 10minute\n todayMarker off\n section Build\n 50m 00s :active, 2026-11-17T13:50:00, 2026-11-17T14:40:00\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 1:50 PM | Plan + build · Opus 5.5 | 50 min | $4.20 |\n| | **Total** | **1 h 12 min** | **$4.20** |\n\nCI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- 1:50:00 PM labelled `pendulum:objective`: the clock starts\n- 1:50:00 PM plan + build stage started (claude-opus-5-5)\n- 2:39:00 PM PR #236 opened\n- 2:40:00 PM plan + build stage's last line: $4.20\n- 3:02:00 PM the issue closed\n\n</details>", - "blockedEnd": "### ⛔ Blocked after 1 h 5 min · $2.83 + unknown so far\nIssue #152 · PR #157 is a draft · Blocked at 12:52 PM PST · API-equivalent, not billed · plus 5 AI runs of unknown cost\n\n> **What to do:** fix the cause below, then re-apply the `pendulum:objective` label. The Blocked notice on this issue has the full steps.\n>\n> **Why:** 2 review findings are still open after the answers.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PR #157 (**2 commits, +40 −3 across 2 files**), had the change reviewed (2 findings), and is Blocked.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 15minute\n todayMarker off\n section Build\n 33m 00s :active, 2026-11-17T11:47:00, 2026-11-17T12:20:00\n section Review\n 31m 00s Blocked :crit, 2026-11-17T12:21:00, 2026-11-17T12:52:00\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 11:47 AM | Plan + build · Opus 5.5 | 33 min | $1.90 + unknown |\n| 12:21 PM | Review · Fable 5.2 · ⛔ Blocked | 31 min | $0.93 + unknown |\n| | **Total** | **1 h 5 min** | **$2.83 + unknown** |\n\nCI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Unknown cost:** 5 AI judge calls went through the AI Gateway, which did not report their cost. They are counted as unknown, never as $0.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- 11:47:00 AM labelled `pendulum:objective`: the clock starts\n- 11:47:00 AM plan + build stage started (claude-opus-5-5)\n- 12:19:00 PM PR #157 opened\n- 12:20:00 PM plan + build stage's last line: $1.90 + unknown\n- 12:21:00 PM review stage started (claude-fable-5-2)\n- 12:40:00 PM last review: 1 review in all, 2 findings\n- 12:52:00 PM review stage's last line: $0.93 + unknown, Blocked\n- 12:52:00 PM Blocked\n\n</details>", + "blockedEnd": "### ⛔ Blocked after 1 h 5 min · $2.83 + unknown so far\nIssue #152 · PR #157 is a draft · Blocked at 12:52 PM PST · API-equivalent, not billed · plus 5 AI runs of unknown cost\n\n> **What to do:** fix the cause below, then add `pendulum:draft` if it is missing, then remove it to resume. The Blocked notice on this issue has the full steps.\n>\n> **Why:** 2 review findings are still open after the answers.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PR #157 (**2 commits, +40 −3 across 2 files**), had the change reviewed (2 findings), and is Blocked.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 15minute\n todayMarker off\n section Build\n 33m 00s :active, 2026-11-17T11:47:00, 2026-11-17T12:20:00\n section Review\n 31m 00s Blocked :crit, 2026-11-17T12:21:00, 2026-11-17T12:52:00\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 11:47 AM | Plan + build · Opus 5.5 | 33 min | $1.90 + unknown |\n| 12:21 PM | Review · Fable 5.2 · ⛔ Blocked | 31 min | $0.93 + unknown |\n| | **Total** | **1 h 5 min** | **$2.83 + unknown** |\n\nCI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Unknown cost:** 5 AI judge calls went through the AI Gateway, which did not report their cost. They are counted as unknown, never as $0.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- 11:47:00 AM labelled `pendulum:objective`: the clock starts\n- 11:47:00 AM plan + build stage started (claude-opus-5-5)\n- 12:19:00 PM PR #157 opened\n- 12:20:00 PM plan + build stage's last line: $1.90 + unknown\n- 12:21:00 PM review stage started (claude-fable-5-2)\n- 12:40:00 PM last review: 1 review in all, 2 findings\n- 12:52:00 PM review stage's last line: $0.93 + unknown, Blocked\n- 12:52:00 PM Blocked\n\n</details>", "questionEnd": "### ❓ Question after 9 min · $0.84 so far\nIssue #512 · Question asked at 2:19 PM PST · API-equivalent, not billed\n\n> **What to do:** answer the question in a comment on this issue. Pendulum goes on from where it stopped.\n>\n> **Question:** Should the export keep the legacy column order, or follow the new schema?\n\nYou wrote the issue and added the label. Pendulum asked a Question.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %H:%M\n tickInterval 2minute\n todayMarker off\n section Build\n 9m 00s Question :crit, 2026-11-17T14:10:00, 2026-11-17T14:19:00\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| 2:10 PM | Build · Opus 5.5 · ❓ Question | 9 min | $0.84 |\n| | **Total** | **9 min** | **$0.84** |\n\nCI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- 2:10:00 PM labelled `pendulum:objective`: the clock starts\n- 2:10:00 PM build stage started (claude-opus-5-5)\n- 2:19:00 PM build stage's last line: $0.84, Question\n- 2:19:00 PM Question asked\n\n</details>", "multiDay": "### ✅ Merged · 2 h 28 min working, 2 d waiting · $18.40\nIssue #98 → PRs #101, #104 · Nov 15, 9:12 AM – Nov 17, 12:40 PM PST · billed to your API key\nWaited 2 d for you; 2 d 3 h from the label to the merge.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PRs #101, #104 (**5 commits, +290 −15 across 9 files**), got the last part's **1 CI check** green, and it merged through your merge queue.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %b %d %H:%M\n tickInterval 12hour\n todayMarker off\n section Build\n 41m 10s :active, 2026-11-15T09:14:00, 2026-11-15T09:55:10\n section Review 1\n 22m 05s Question :crit, 2026-11-15T09:56:00, 2026-11-15T10:18:05\n section On hold 1\n 21h 40m :done, 2026-11-15T10:18:05, 2026-11-16T07:58:30\n section Part 2\n 35m 20s :active, 2026-11-16T07:58:30, 2026-11-16T08:33:50\n section Review 2\n 18m 44s Blocked :crit, 2026-11-16T08:34:10, 2026-11-16T08:52:54\n section On hold 2\n 1d 3h :done, 2026-11-16T08:52:54, 2026-11-17T12:12:00\n section Review 3\n 16m 41s :active, 2026-11-17T12:12:00, 2026-11-17T12:28:41\n section Queue\n 11m 12s :active, 2026-11-17T12:28:48, 2026-11-17T12:40:00\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| Nov 15, 9:14 AM | Plan + build · Opus 5.5 | 41 min 10 s | $7.20 |\n| Nov 15, 9:56 AM | Review 1 · Fable 5.2 · ❓ Question | 22 min 5 s | $3.10 |\n| Nov 15, 10:18 AM | On hold 1 · waiting for you | 21 h 40 min | — |\n| Nov 16, 7:58 AM | Part 2 · Opus 5.5 | 35 min 20 s | $4.90 |\n| Nov 16, 8:34 AM | Review 2 · Fable 5.2 · ⛔ Blocked | 18 min 44 s | $1.90 |\n| Nov 16, 8:52 AM | On hold 2 · waiting for you | 1 d 3 h | — |\n| Nov 17, 12:12 PM | Review 3 · Fable 5.2 | 16 min 41 s | $1.30 |\n| Nov 17, 12:28 PM | Merge queue · your CI | 11 min 12 s | — |\n| | Working | 2 h 28 min | |\n| | Waiting | 2 d | |\n| | **Total** | **2 d 3 h** | **$18.40** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Part 1: work $7.20\", \"Part 1: review $3.10\", \"Part 2: work $4.90\", \"Part 2: review $3.20\"]\n y-axis \"USD\" 0 --> 10\n bar [7.20, 3.10, 4.90, 3.20]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Part 1: work | $7.20 |\n| Part 1: review | $3.10 |\n| Part 2: work | $4.90 |\n| Part 2: review | $3.20 |\n\nBars show recorded dollars only. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** These dollars are billed to your API key or AI Gateway key.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- **Working and waiting:** Waiting is the time on hold in the table, each from a recorded start and end: an issue that blocked this one, from the blocked-by relation (or the label, when later) to that issue's close or the relation's removal; a stage that recorded a pause for a usage limit or an outage, and a Blocked or Question notice, each until the next stage started. A wait with no recorded start and end is not counted. Working is the rest of the time from the label to the end.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- Nov 15, 9:12:00 AM labelled `pendulum:objective`: the clock starts\n- Nov 15, 9:14:00 AM plan + build stage started (claude-opus-5-5)\n- Nov 15, 9:50:00 AM PR #101 opened\n- Nov 15, 9:55:10 AM plan + build stage's last line: $7.20\n- Nov 15, 9:56:00 AM review stage started (claude-fable-5-2)\n- Nov 15, 10:18:05 AM review stage's last line: $3.10, Question\n- Nov 15, 10:18:05 AM Question notice: on hold until the next stage\n- Nov 16, 7:58:30 AM part 2 stage started (claude-opus-5-5)\n- Nov 16, 8:30:00 AM PR #104 opened\n- Nov 16, 8:33:50 AM part 2 stage's last line: $4.90\n- Nov 16, 8:34:10 AM review stage started (claude-fable-5-2)\n- Nov 16, 8:52:54 AM review stage's last line: $1.90, Blocked\n- Nov 16, 8:52:54 AM Blocked notice: on hold until the next stage\n- Nov 17, 12:12:00 PM review stage started (claude-fable-5-2)\n- Nov 17, 12:28:41 PM review stage's last line: $1.30\n- Nov 17, 12:28:48 PM added to the merge queue\n- Nov 17, 12:40:00 PM PR #104 merged, 1 CI check green\n\n</details>", - "partTwoBlocked": "### ⛔ Blocked · 2 h working, 21 h 40 min waiting · $17.10 so far\nIssue #98 · PR #104 is a draft · Blocked at Nov 16, 8:53 AM PST · billed to your API key\nWaited 21 h 40 min for you; 23 h 41 min from the label to the Block.\n\n> **What to do:** fix the cause below, then re-apply the `pendulum:objective` label. The Blocked notice on this issue has the full steps.\n>\n> **Why:** 2 findings stay open on PR #104.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PRs #101, #104 (**5 commits, +290 −15 across 9 files**), and is Blocked.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %b %d %H:%M\n tickInterval 6hour\n todayMarker off\n section Build\n 41m 10s :active, 2026-11-15T09:14:00, 2026-11-15T09:55:10\n section Review 1\n 22m 05s Question :crit, 2026-11-15T09:56:00, 2026-11-15T10:18:05\n section On hold\n 21h 40m :done, 2026-11-15T10:18:05, 2026-11-16T07:58:30\n section Part 2\n 35m 20s :active, 2026-11-16T07:58:30, 2026-11-16T08:33:50\n section Review 2\n 18m 44s Blocked :crit, 2026-11-16T08:34:10, 2026-11-16T08:52:54\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| Nov 15, 9:14 AM | Plan + build · Opus 5.5 | 41 min 10 s | $7.20 |\n| Nov 15, 9:56 AM | Review 1 · Fable 5.2 · ❓ Question | 22 min 5 s | $3.10 |\n| Nov 15, 10:18 AM | On hold · waiting for you | 21 h 40 min | — |\n| Nov 16, 7:58 AM | Part 2 · Opus 5.5 | 35 min 20 s | $4.90 |\n| Nov 16, 8:34 AM | Review 2 · Fable 5.2 · ⛔ Blocked | 18 min 44 s | $1.90 |\n| | Working | 2 h | |\n| | Waiting | 21 h 40 min | |\n| | **Total** | **23 h 41 min** | **$17.10** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Part 1: work $7.20\", \"Part 1: review $3.10\", \"Part 2: work $4.90\", \"Part 2: review $1.90\"]\n y-axis \"USD\" 0 --> 10\n bar [7.20, 3.10, 4.90, 1.90]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Part 1: work | $7.20 |\n| Part 1: review | $3.10 |\n| Part 2: work | $4.90 |\n| Part 2: review | $1.90 |\n\nBars show recorded dollars only. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** These dollars are billed to your API key or AI Gateway key.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- **Working and waiting:** Waiting is the time on hold in the table, each from a recorded start and end: an issue that blocked this one, from the blocked-by relation (or the label, when later) to that issue's close or the relation's removal; a stage that recorded a pause for a usage limit or an outage, and a Blocked or Question notice, each until the next stage started. A wait with no recorded start and end is not counted. Working is the rest of the time from the label to the end.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- Nov 15, 9:12:00 AM labelled `pendulum:objective`: the clock starts\n- Nov 15, 9:14:00 AM plan + build stage started (claude-opus-5-5)\n- Nov 15, 9:50:00 AM PR #101 opened\n- Nov 15, 9:55:10 AM plan + build stage's last line: $7.20\n- Nov 15, 9:56:00 AM review stage started (claude-fable-5-2)\n- Nov 15, 10:18:05 AM review stage's last line: $3.10, Question\n- Nov 15, 10:18:05 AM Question notice: on hold until the next stage\n- Nov 16, 7:58:30 AM part 2 stage started (claude-opus-5-5)\n- Nov 16, 8:30:00 AM PR #104 opened\n- Nov 16, 8:33:50 AM part 2 stage's last line: $4.90\n- Nov 16, 8:34:10 AM review stage started (claude-fable-5-2)\n- Nov 16, 8:52:54 AM review stage's last line: $1.90, Blocked\n- Nov 16, 8:53:00 AM Blocked\n\n</details>", + "partTwoBlocked": "### ⛔ Blocked · 2 h working, 21 h 40 min waiting · $17.10 so far\nIssue #98 · PR #104 is a draft · Blocked at Nov 16, 8:53 AM PST · billed to your API key\nWaited 21 h 40 min for you; 23 h 41 min from the label to the Block.\n\n> **What to do:** fix the cause below, then add `pendulum:draft` if it is missing, then remove it to resume. The Blocked notice on this issue has the full steps.\n>\n> **Why:** 2 findings stay open on PR #104.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PRs #101, #104 (**5 commits, +290 −15 across 9 files**), and is Blocked.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %b %d %H:%M\n tickInterval 6hour\n todayMarker off\n section Build\n 41m 10s :active, 2026-11-15T09:14:00, 2026-11-15T09:55:10\n section Review 1\n 22m 05s Question :crit, 2026-11-15T09:56:00, 2026-11-15T10:18:05\n section On hold\n 21h 40m :done, 2026-11-15T10:18:05, 2026-11-16T07:58:30\n section Part 2\n 35m 20s :active, 2026-11-16T07:58:30, 2026-11-16T08:33:50\n section Review 2\n 18m 44s Blocked :crit, 2026-11-16T08:34:10, 2026-11-16T08:52:54\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| Nov 15, 9:14 AM | Plan + build · Opus 5.5 | 41 min 10 s | $7.20 |\n| Nov 15, 9:56 AM | Review 1 · Fable 5.2 · ❓ Question | 22 min 5 s | $3.10 |\n| Nov 15, 10:18 AM | On hold · waiting for you | 21 h 40 min | — |\n| Nov 16, 7:58 AM | Part 2 · Opus 5.5 | 35 min 20 s | $4.90 |\n| Nov 16, 8:34 AM | Review 2 · Fable 5.2 · ⛔ Blocked | 18 min 44 s | $1.90 |\n| | Working | 2 h | |\n| | Waiting | 21 h 40 min | |\n| | **Total** | **23 h 41 min** | **$17.10** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Part 1: work $7.20\", \"Part 1: review $3.10\", \"Part 2: work $4.90\", \"Part 2: review $1.90\"]\n y-axis \"USD\" 0 --> 10\n bar [7.20, 3.10, 4.90, 1.90]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Part 1: work | $7.20 |\n| Part 1: review | $3.10 |\n| Part 2: work | $4.90 |\n| Part 2: review | $1.90 |\n\nBars show recorded dollars only. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** These dollars are billed to your API key or AI Gateway key.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- **Working and waiting:** Waiting is the time on hold in the table, each from a recorded start and end: an issue that blocked this one, from the blocked-by relation (or the label, when later) to that issue's close or the relation's removal; a stage that recorded a pause for a usage limit or an outage, and a Blocked or Question notice, each until the next stage started. A wait with no recorded start and end is not counted. Working is the rest of the time from the label to the end.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n\n**Run log** (PST)\n- Nov 15, 9:12:00 AM labelled `pendulum:objective`: the clock starts\n- Nov 15, 9:14:00 AM plan + build stage started (claude-opus-5-5)\n- Nov 15, 9:50:00 AM PR #101 opened\n- Nov 15, 9:55:10 AM plan + build stage's last line: $7.20\n- Nov 15, 9:56:00 AM review stage started (claude-fable-5-2)\n- Nov 15, 10:18:05 AM review stage's last line: $3.10, Question\n- Nov 15, 10:18:05 AM Question notice: on hold until the next stage\n- Nov 16, 7:58:30 AM part 2 stage started (claude-opus-5-5)\n- Nov 16, 8:30:00 AM PR #104 opened\n- Nov 16, 8:33:50 AM part 2 stage's last line: $4.90\n- Nov 16, 8:34:10 AM review stage started (claude-fable-5-2)\n- Nov 16, 8:52:54 AM review stage's last line: $1.90, Blocked\n- Nov 16, 8:53:00 AM Blocked\n\n</details>", "blockedThenPaused": "### ✅ Merged · 2 h 14 min working, 19 h 31 min waiting · $15.33\nIssue #421 → PR #443 · Nov 17, 12:34 PM – Nov 18, 10:20 AM PST · API-equivalent, not billed\nWaited 12 h 36 min blocked by #420 and 6 h 55 min on a usage limit; 21 h 45 min from the label to the merge.\n\nYou wrote the issue and added the label. Pendulum planned the work, opened PR #443 (**5 commits, +1749 −287 across 31 files**), got **1 CI check** green, had the change reviewed (8 findings), and it merged through your merge queue.\n\n**Timeline** (PST)\n\n```mermaid\ngantt\n dateFormat YYYY-MM-DDTHH:mm:ss\n axisFormat %b %d %H:%M\n tickInterval 6hour\n todayMarker off\n section On hold 1\n 12h 36m :done, 2026-11-17T12:34:26, 2026-11-18T01:10:43\n section Build\n 1h 00m :active, 2026-11-18T01:12:03, 2026-11-18T02:12:42\n section Review 1\n 21s Paused :active, 2026-11-18T02:12:59, 2026-11-18T02:13:20\n section On hold 2\n 6h 55m :done, 2026-11-18T02:13:20, 2026-11-18T09:08:37\n section Review 2\n 31m 21s :active, 2026-11-18T09:08:37, 2026-11-18T09:39:58\n section Review 3\n 27m 04s :active, 2026-11-18T09:40:58, 2026-11-18T10:08:02\n section Queue\n 12m 14s :active, 2026-11-18T10:07:56, 2026-11-18T10:20:10\n```\n\n| Time | Stage | Took | Cost |\n| :-- | :-- | --: | --: |\n| Nov 17, 12:34 PM | On hold 1 · blocked by #420 | 12 h 36 min | — |\n| Nov 18, 1:12 AM | Plan + build · Opus 5.5 | 1 h | $7.81 |\n| Nov 18, 2:12 AM | Review 1 · Fable 5.2 · ⏸️ Paused | 21 s | — |\n| Nov 18, 2:13 AM | On hold 2 · waiting for a usage limit | 6 h 55 min | — |\n| Nov 18, 9:08 AM | Review 2 · Fable 5.2 | 31 min 21 s | $5.37 |\n| Nov 18, 9:40 AM | Review 3 · Fable 5.2 | 27 min 4 s | $2.15 |\n| Nov 18, 10:07 AM | Merge queue · your CI | 12 min 14 s | — |\n| | Working | 2 h 14 min | |\n| | Waiting | 19 h 31 min | |\n| | **Total** | **21 h 45 min** | **$15.33** |\n\n**Where the money went**\n\n```mermaid\nxychart-beta horizontal\n title \"Recorded cost (USD)\"\n x-axis [\"Work $7.80\", \"Review $3.43\", \"Answering the review $4.10\"]\n y-axis \"USD\" 0 --> 10\n bar [7.80, 3.43, 4.10]\n```\n\n| What the issue asked for | Cost |\n| :-- | --: |\n| Work | $7.80 |\n| Review | $3.43 |\n| Answering the review | $4.10 |\n| AI judge calls | <$0.01 |\n\nBars show recorded dollars only. The rows' cents are shared out to add up to the total, so a row can be a cent off its stage's own figure. CI minutes are not included.\n\n<details><summary>Run details</summary>\n\n- **Cost basis:** API-equivalent is what this usage would cost at API list prices; you are on a subscription, so it is not billed.\n- **Where figures come from:** times from the issue, the PR and each stage's own record; dollars from each stage's own record. Nothing is estimated.\n- **Working and waiting:** Waiting is the time on hold in the table, each from a recorded start and end: an issue that blocked this one, from the blocked-by relation (or the label, when later) to that issue's close or the relation's removal; a stage that recorded a pause for a usage limit or an outage, and a Blocked or Question notice, each until the next stage started. A wait with no recorded start and end is not counted. Working is the rest of the time from the label to the end.\n- — in Took means no time was recorded for that row; in Cost, that no AI dollars were (a stage that ran no AI, the merge queue, time on hold).\n- **Pendulum** 0.10.3\n\n**Run log** (PST)\n- Nov 17, 12:34:21 PM labelled `pendulum:objective`: the clock starts\n- Nov 17, 12:34:26 PM blocked by #420: on hold\n- Nov 18, 1:10:43 AM no longer blocked by #420\n- Nov 18, 1:12:03 AM plan + build stage started (claude-opus-5-5)\n- Nov 18, 1:57:14 AM PR #443 opened\n- Nov 18, 2:12:42 AM plan + build stage's last line: $7.80\n- Nov 18, 2:12:59 AM review stage started (claude-fable-5-2)\n- Nov 18, 2:13:20 AM review stage's last line: $0.00, Paused\n- Nov 18, 2:13:20 AM paused for a usage limit: on hold until the next stage\n- Nov 18, 9:08:37 AM review stage started (claude-fable-5-2)\n- Nov 18, 9:39:58 AM review stage's last line: $5.37\n- Nov 18, 9:40:58 AM review stage started (claude-fable-5-2)\n- Nov 18, 9:52:16 AM last review: 2 reviews in all, 8 findings\n- Nov 18, 10:07:56 AM added to the merge queue\n- Nov 18, 10:08:02 AM review stage's last line: $2.15\n- Nov 18, 10:20:10 AM PR #443 merged, 1 CI check green\n\n</details>" } diff --git a/plugin/test/merge-conflict.test.mjs b/plugin/test/merge-conflict.test.mjs index ebaa1be3..431d6b11 100644 --- a/plugin/test/merge-conflict.test.mjs +++ b/plugin/test/merge-conflict.test.mjs @@ -516,7 +516,7 @@ test("#331: another unresolved thread a ruleset or branch protection requires re assert.equal(await mergeReadyOne(repo, { issue: 2, prNumber: 12, queue: true, checkNames: ["ci"], report }, { token: "t" }), "threads"); assert.deepEqual(gh.attempts, []); const why = mergeBlockReason("threads", report); - assert.equal(why, "PR #12 cannot merge: a ruleset on main requires every review conversation resolved, and 1 is open: dana on src/store.ts:41. Answer or resolve each on the PR, then re-apply `pendulum:objective` to resume"); + assert.equal(why, "PR #12 cannot merge: a ruleset on main requires every review conversation resolved, and 1 is open: dana on src/store.ts:41. Answer or resolve each on the PR, then add `pendulum:draft` if it is missing, then remove it to resume"); assert.equal(mergeBlockCause("threads", report), "work"); assert.deepEqual(gh.state.labelled, [], "a stranger's thread is never Pendulum's to answer"); @@ -604,7 +604,7 @@ test("#331: code scanning's review rounds at the merge are bounded per re-entry, gh.state.threads = [alert("A3", 260), alert("A4", 12)]; const report = {}; assert.equal(await pass(report), "threads"); - assert.equal(mergeBlockReason("threads", report), "code scanning still has 2 open alert(s) on PR #12 after 2 answer rounds: packages/application/src/wake-triage-cases.ts:260; packages/application/src/wake-triage-cases.ts:12. Fix them on the branch or resolve them on the PR, then re-apply `pendulum:objective` to resume"); + assert.equal(mergeBlockReason("threads", report), "code scanning still has 2 open alert(s) on PR #12 after 2 answer rounds: packages/application/src/wake-triage-cases.ts:260; packages/application/src/wake-triage-cases.ts:12. Fix them on the branch or resolve them on the PR, then add `pendulum:draft` if it is missing, then remove it to resume"); assert.equal(mergeBlockCause("threads", report), "work"); assert.equal(gh.state.labelled.length, 2, "two rounds, two review labels"); assert.equal((gh.comments[2] || []).filter((c) => c.body.startsWith(marker(2, "answer-rounds"))).length, 1, "one record on the issue"); @@ -672,7 +672,7 @@ test("#595: an unlisted App's open thread goes to the answer pass before the mer // Past the rounds it Blocks, naming the App, its file and line. const report = {}; assert.equal(await pass(report), "threads"); - assert.equal(mergeBlockReason("threads", report), "1 review thread(s) still open on PR #12 after 2 answer rounds: chatgpt-codex-connector[bot] on src/store.ts:41. Fix them on the branch, or answer or resolve each on the PR, then re-apply `pendulum:objective` to resume"); + assert.equal(mergeBlockReason("threads", report), "1 review thread(s) still open on PR #12 after 2 answer rounds: chatgpt-codex-connector[bot] on src/store.ts:41. Fix them on the branch, or answer or resolve each on the PR, then add `pendulum:draft` if it is missing, then remove it to resume"); assert.equal(mergeBlockCause("threads", report), "work"); // The finding check resolved it: the merge goes on. thread.isResolved = true; @@ -700,7 +700,7 @@ test("#595: a writer's open thread goes to the answer pass, and one a writer ans gh.state.threads = [structuredClone(personThread), actions]; const report = {}; assert.equal(await mergeReadyOne(repo, { issue: 2, prNumber: 12, queue: true, checkNames: ["ci"], report }, { token: "t" }), "threads"); - assert.equal(mergeBlockReason("threads", report), "PR #12 cannot merge: a ruleset on main requires every review conversation resolved, and 2 are open: dana on src/store.ts:41; github-actions[bot] on src/b.ts:7. Answer or resolve each on the PR, then re-apply `pendulum:objective` to resume"); + assert.equal(mergeBlockReason("threads", report), "PR #12 cannot merge: a ruleset on main requires every review conversation resolved, and 2 are open: dana on src/store.ts:41; github-actions[bot] on src/b.ts:7. Answer or resolve each on the PR, then add `pendulum:draft` if it is missing, then remove it to resume"); assert.deepEqual(gh.state.labelled, ["12:pendulum:review"], "no review runs for them"); // An App's open thread beside a stranger's: the stranger's holds the merge anyway, so it Blocks at once, no round spent. gh.state.threads = [codexThread("PRRT_codex2", 12), structuredClone(personThread)]; diff --git a/plugin/test/objective-hosts.test.mjs b/plugin/test/objective-hosts.test.mjs index 057156e3..18549da7 100644 --- a/plugin/test/objective-hosts.test.mjs +++ b/plugin/test/objective-hosts.test.mjs @@ -116,7 +116,7 @@ test("Actions and the cloud sandbox: every harness's runner sandbox adds the ope // The Block for a host its sandbox still denies leaves out the ones the labels opened, and offers the label first. assert.equal(BACKENDS.actions.sandbox.deniedFix(["huggingface.co"], env, "claude"), null); const fix = BACKENDS.actions.sandbox.deniedFix(["cdn-lfs.hf.co", "models.example.org"], env, "codex"); - assert.match(fix, /denied `models\.example\.org`\. If the Objective needs it, a person who can push applies `pendulum:host:models\.example\.org` to this issue, which opens it to this Objective alone, then re-applies `pendulum:objective`\. To open it to every Objective, add it to the Pendulum workflow's `allowed_domains` input/); + assert.match(fix, /denied `models\.example\.org`\. If the Objective needs it, a person who can push applies `pendulum:host:models\.example\.org` to this issue, which opens it to this Objective alone, then resumes through Draft\. To open it to every Objective, add it to the Pendulum workflow's `allowed_domains` input/); } finally { openStageHosts([]); } diff --git a/plugin/test/objective-trust.test.mjs b/plugin/test/objective-trust.test.mjs index aabd41da..6abd6793 100644 --- a/plugin/test/objective-trust.test.mjs +++ b/plugin/test/objective-trust.test.mjs @@ -7,7 +7,8 @@ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { setMaintainers } from "../scripts/lib/logic.mjs"; -import { AUTHOR_FIX, authorGate, trustedIssue } from "../scripts/lib/objective-trust.mjs"; +import { DRAFT_LABEL } from "../scripts/lib/activation.mjs"; +import { AUTHOR_FIX, authorGate, startsOf, trustedIssue } from "../scripts/lib/objective-trust.mjs"; import { blockedLine } from "../scripts/lib/session.mjs"; import { inFiles } from "../scripts/lib/handoff.mjs"; @@ -27,6 +28,32 @@ const gh = ({ author, editor = null, lastEditedAt = editor ? "2026-11-09T10:00:0 }); const rest = { number: 7, title: "Objective", body: "Build the thing.", labels: [{ name: "pendulum:objective" }] }; +test("objective activation leaves identity alone and uses the latest Draft removal for runtime trust", () => { + const e = (event, name, created_at, login) => ({ event, label: { name }, created_at, actor: { login, type: "User" } }); + const createAt = "2031-03-02T01:00:00Z"; + const startAt = "2031-03-02T01:01:00Z"; + const identity = e("labeled", "pendulum:objective", createAt, "writer"); + const held = e("labeled", DRAFT_LABEL, createAt, "writer"); + const first = e("unlabeled", DRAFT_LABEL, startAt, "maintainer"); + const laterHold = e("labeled", DRAFT_LABEL, startAt, "maintainer"); + const later = e("unlabeled", DRAFT_LABEL, startAt, "triager"); + const duplicateIdentity = e("labeled", "pendulum:objective", createAt, "triager"); + const duplicateRelease = e("unlabeled", DRAFT_LABEL, startAt, "writer"); + for (const creation of [[identity, held], [held, identity]]) { + assert.deepEqual(startsOf(creation, "pendulum:objective"), []); + assert.deepEqual(startsOf([...creation, first, laterHold, later], "pendulum:objective"), [later, first]); + } + assert.deepEqual(startsOf([identity], "pendulum:objective"), [identity], "legacy identity-only activation"); + assert.deepEqual(startsOf([identity, duplicateIdentity, held], "pendulum:objective"), [], "duplicate applications cannot leave the Draft with an early clock"); + assert.deepEqual(startsOf([identity, duplicateIdentity], "pendulum:objective"), [identity], "a duplicate cannot take over the legacy Objective activation"); + assert.deepEqual(startsOf([identity, held, first, duplicateRelease, laterHold, later], "pendulum:objective"), [later, first], "only real Draft removals activate"); + const reportedRelease = { ...first, id: 101 }; + assert.deepEqual(startsOf([identity, held, reportedRelease, laterHold, { ...reportedRelease }, later], "pendulum:objective"), [later, reportedRelease], "a repeated event ID after a real hold cannot consume the next release"); + assert.deepEqual(startsOf([held, first], "pendulum:objective"), [first], "runtime can vouch for a currently-labelled Objective"); + const removed = e("unlabeled", "pendulum:objective", startAt, "writer"); + assert.deepEqual(startsOf([identity, held, removed, first], "pendulum:objective"), [], "Draft removal without the recorded identity does not activate"); +}); + test("objective trust: a stranger's body Blocks, naming the stranger, and no text comes back", async () => { const t = await trustedIssue(repo, 7, rest, {}, gh({ author: user("stranger") })); assert.equal(t.ok, false); @@ -109,7 +136,7 @@ test("objective trust: a triager's rename before the first plan Blocks, naming t assert.equal(t.issueData, undefined, "no title or body for a harness"); assert.match(t.reason, /^the issue's title was last renamed by `reader`, who cannot push to acme\/app and is not a pinned maintainer, so Pendulum acts on none of its text$/); assert.deepEqual(applied, [{ issue: 7, pr: null, exit: "blocked", reason: t.reason, fix: AUTHOR_FIX["title renamer"], cause: "setup", notify: "boss", stage: "author" }], "Blocked as an untrusted body is, resumed once a writer renames it"); - assert.match(blockedLine({ issue: 7, stage: "author", reason: t.reason, fix: AUTHOR_FIX["title renamer"] }), /person who can push read the title and change it \(saving the same title records no rename; .* re-apply `pendulum:objective`/); + assert.match(blockedLine({ issue: 7, stage: "author", reason: t.reason, fix: AUTHOR_FIX["title renamer"] }), /person who can push read the title and change it \(saving the same title records no rename; .* add `pendulum:draft` if it is missing, then remove it to resume/); const stranger = await trustedIssue(repo, 7, rest, {}, gh({ author: user("kirk"), renamed: [user("stranger")] })); assert.match(stranger.reason, /title was last renamed by `stranger`, who cannot push/); }); diff --git a/plugin/test/one-repo.test.mjs b/plugin/test/one-repo.test.mjs index 486ee5f1..dcbeb731 100644 --- a/plugin/test/one-repo.test.mjs +++ b/plugin/test/one-repo.test.mjs @@ -13,7 +13,7 @@ test("one repository: an issue body naming another repository is a Question befo const body = "Add the export format.\n\nPendulum-Repository: acme/world allow .github/workflows/ci.yml\n"; assert.equal( declaredQuestion(body, { source, label: "pendulum:objective" }), - "the issue names acme/world on a Pendulum-Repository line, and Pendulum works in one repository per Objective; split it into one Objective per repository (this one changes only acme/platform), remove the line and re-apply pendulum:objective", + "the issue names acme/world on a Pendulum-Repository line, and Pendulum works in one repository per Objective; split it into one Objective per repository (this one changes only acme/platform), remove the line and resume through Draft", ); assert.deepEqual(declaredRepos(body, source), ["acme/world"]); assert.deepEqual(declaredRepos("- pendulum-repository: `Acme/World`\nPendulum-Repository: acme/infra", source), ["Acme/World", "acme/infra"], "any case, a list item, backticks"); diff --git a/plugin/test/outbox.test.mjs b/plugin/test/outbox.test.mjs index 066cd4bd..6cdfa0eb 100644 --- a/plugin/test/outbox.test.mjs +++ b/plugin/test/outbox.test.mjs @@ -70,7 +70,7 @@ test("outbox: a protected path or a plain blob LFS should hold is refused before r.run(r.work, "commit", "-q", "-m", "widen ci"); const before = r.run(r.origin, "rev-parse", "pendulum/1"); assert.equal(await box.push(), false); - assert.equal(box.error, "touched protected path .github/workflows/ci.yml; Pendulum never pushes a workflow file: the worker hands the change over in $PENDULUM_OUT/workflow.patch (pendulum-deliver-pr), so re-apply the label to rerun"); + assert.equal(box.error, "touched protected path .github/workflows/ci.yml; Pendulum never pushes a workflow file: the worker hands the change over in $PENDULUM_OUT/workflow.patch (pendulum-deliver-pr), so resume through Draft to rerun"); assert.equal(r.run(r.origin, "rev-parse", "pendulum/1"), before); const r2 = repos(); diff --git a/plugin/test/question-answer.test.mjs b/plugin/test/question-answer.test.mjs index 03b541d4..7adfcba4 100644 --- a/plugin/test/question-answer.test.mjs +++ b/plugin/test/question-answer.test.mjs @@ -11,6 +11,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; +import { DRAFT_LABEL } from "../scripts/lib/activation.mjs"; import { LOOKUP_DELAYS_MS } from "../scripts/lib/gateway-relay.mjs"; import { RETRY } from "../scripts/lib/github.mjs"; import { questionMarker, setSelf } from "../scripts/lib/logic.mjs"; @@ -513,7 +514,7 @@ test("#479 a decisions comment's write: one gone by the write (PATCH 404) is pos } }); -test("work stage, the real wiring: with nothing judged before, a no decision commits the exit, puts the Objective back to Question with one notice and ends it held; a relaunch, a re-applied label or a send-back asks nothing", async () => { +test("work stage judges a new answer once and skips judging after explicit activation, relaunch, or send-back", async () => { const { openAnswerCheck } = await import("../scripts/lib/answer-check.mjs"); const { stopHold } = await import("../scripts/lib/local.mjs"); const gh = fakeGitHub([{ number: 7, pr: PR_BODY }]); @@ -544,6 +545,7 @@ test("work stage, the real wiring: with nothing judged before, a no decision com assert.equal(gh.gateway.calls.length, 2, "and asks nothing"); // A person re-applying the label is a go; a send-back's stage follows an In review: neither resumes a Question. + gh.unlabel(7, OBJ, PERSON); gh.label(7, OBJ); gh.comment(7, PERSON, "hmm, not sure"); assert.equal((await workStage(gh, 7, check())).ended, false); @@ -554,6 +556,14 @@ test("work stage, the real wiring: with nothing judged before, a no decision com assert.equal((await workStage(sentBack, 9, check())).ended, false); assert.equal(gh.gateway.calls.length + sentBack.gateway.calls.length, 2, "neither asks"); + const drafted = fakeGitHub([{ number: 11 }]); + await ask(drafted, 11); + drafted.comment(11, PERSON, "hmm, not sure"); + drafted.label(11, DRAFT_LABEL); + drafted.unlabel(11, DRAFT_LABEL, PERSON); + assert.equal((await workStage(drafted, 11, check())).ended, false); + assert.equal(drafted.gateway.calls.length, 0, "trusted Draft removal resumes without judging the comment"); + // No decider (`decision_route` off): today's rule, nothing asked. const off = fakeGitHub([{ number: 10 }]); await ask(off, 10); @@ -697,7 +707,7 @@ test("#448 Actions: a Question's PR marked ready and its label re-applied by a w gh.reviewJob(7, true); gh.unlabel(7, OBJ); gh.label(7, OBJ); - assert.match(await readyCheck(gh, 7), /re-applied since the Question: its work stage runs again on pendulum\/7/, "the review job ends at once"); + assert.match(await readyCheck(gh, 7), /activation since the Question: its work stage runs again on pendulum\/7/, "the review job ends at once"); const during = await tick(gh); assert.ok(!during.ready.includes(7), "no worker while its review job still runs"); assert.ok(gh.labels(7).includes("pendulum:question"), "nothing changed on it yet"); @@ -715,6 +725,39 @@ test("#448 Actions: a Question's PR marked ready and its label re-applied by a w assert.equal(await readyCheck(plain, 8), null); }); +test("Actions stands down a Question's PR-ready review while Draft removal is unread and when a trusted removal requeues work", async () => { + const gh = fakeGitHub([{ number: 7, pr: PR_BODY }]); + await ask(gh, 7, { pr: gh.pr(7) }); + gh.ready(7); + gh.label(7, DRAFT_LABEL); + gh.unlabel(7, DRAFT_LABEL, PERSON); + const removed = gh.timeline(7).pop(); + assert.match(await readyCheck(gh, 7), /Draft removal is not yet visible/); + gh.timeline(7).push(removed); + assert.match(await readyCheck(gh, 7), /activation since the Question/); +}); + +test("a refusal belongs to its GitHub activation event even when a maintainer activates in the same second", async () => { + const gh = fakeGitHub([{ number: 7 }]); + await ask(gh, 7); + gh.age(7, 36_000); + gh.label(7, DRAFT_LABEL); + gh.unlabel(7, DRAFT_LABEL, TRIAGER); + const refused = gh.timeline(7).at(-1); + refused.id = 1001; + assert.deepEqual((await tick(gh)).ready, []); + assert.match(refusals(gh, 7)[0].body, /relabel-refused:id-1001/); + + gh.label(7, DRAFT_LABEL); + gh.unlabel(7, DRAFT_LABEL, PERSON); + const followed = gh.timeline(7).slice(-2); + followed.forEach((e) => { e.created_at = refused.created_at; }); + followed[1].id = 1003; + assert.deepEqual((await tick(gh)).ready, [7]); + assert.ok(gh.labels(7).includes(OBJ)); + assert.equal(refusals(gh, 7).length, 1); +}); + test("#449 dispatcher: a re-applied pendulum:objective requeues a Question only from a person who can push; a triager's or an App's changes nothing and is said once", async () => { for (const local of [false, true]) { const self = local ? PERSON : BOT; @@ -781,10 +824,10 @@ test("#449 the newest start decides, in the pick and in requeuedIn alike: a writ const at = (m) => new Date(Date.parse("2026-11-15T10:00:00Z") + m * MIN).toISOString(); const ev = (event, name, m, actor) => ({ event, label: { name }, actor, created_at: at(m) }); const trusted = async (actor) => actor?.login === PERSON.login; - const events = [ev("labeled", OBJ, 0, PERSON), ev("labeled", "pendulum:question", 1, BOT), ev("labeled", OBJ, 2, PERSON), ev("unlabeled", OBJ, 3, TRIAGER), ev("labeled", OBJ, 4, TRIAGER)]; + const events = [ev("labeled", OBJ, 0, PERSON), ev("labeled", "pendulum:question", 1, BOT), ev("unlabeled", OBJ, 2, PERSON), ev("labeled", OBJ, 2, PERSON), ev("unlabeled", OBJ, 3, TRIAGER), ev("labeled", OBJ, 4, TRIAGER)]; const go = await requeuedIn(events, OBJ, trusted); assert.deepEqual([go.requeued, go.refused.map((r) => r.actor.login)], [false, ["triager"]], "the triager's re-apply is the go that decides"); - assert.equal((await requeuedIn(events.slice(0, 3), OBJ, trusted)).requeued, true, "the writer's alone requeues"); + assert.equal((await requeuedIn(events.slice(0, 4), OBJ, trusted)).requeued, true, "the writer's alone requeues"); // Through the dispatcher: a Question the writer re-applied, then the triager took off and on again. const q = fakeGitHub([{ number: 7, pr: PR_BODY }]); diff --git a/plugin/test/question-ready.test.mjs b/plugin/test/question-ready.test.mjs index 41a52fe7..fe77e269 100644 --- a/plugin/test/question-ready.test.mjs +++ b/plugin/test/question-ready.test.mjs @@ -72,6 +72,18 @@ test("serve reviews a Question's PR a person marked ready, as the Action's ready assert.deepEqual(out, [{ issue: 7, pr: 70 }], "#8 has no ready mark since its Question, #9 is In review (reviewed, waiting to merge), #6's PR is still a draft"); }); +test("serve waits when a ready PR's Objective timeline still shows Draft held", async () => { + const { out } = await pending({ + pulls: [pull(7)], + issues: { 7: issue([OBJ, "pendulum:question"], 7) }, + timelines: { + 7: [labeled("pendulum:question", "2026-11-15T10:00:00Z"), labeled("pendulum:draft", "2026-11-15T10:01:00Z")], + 70: [ready("2026-11-15T10:02:00Z")], + }, + }); + assert.deepEqual(out, []); +}); + test("a Question whose PR GitHub will not draft Blocks once, naming it, rather than leaving a ready PR serve would ask again each tick", async () => { const { applyExit } = await import("../scripts/lib/session.mjs"); const pr = { number: 70, node_id: "PR_70", draft: false, head: { sha: "abc" }, user: { login: "pendulum[bot]" } }; diff --git a/plugin/test/relaunch.test.mjs b/plugin/test/relaunch.test.mjs index 826d3abb..63e7f66e 100644 --- a/plugin/test/relaunch.test.mjs +++ b/plugin/test/relaunch.test.mjs @@ -310,6 +310,25 @@ test("a stopped, draft or restarting Objective is never relaunched; a started on assert.deepEqual(r.restarted, [23], "the restart runs as before; its card goes back to Queued, not Running"); }); +test("relaunch holds Running work until its newest Draft activation can be verified", async () => { + const gh = fakeGitHub([{ number: 7, labels: [OBJ, "pendulum:running"] }]); + const draft = "pendulum:draft"; + gh.person(7, "labeled", draft); + gh.person(7, "unlabeled", draft); + const timeline = gh.issue(7).timeline; + const removal = timeline.pop(); + assert.deepEqual((await tick(gh)).relaunched, []); + assert.equal(recordOf(gh, 7), null); + + timeline.push({ ...removal, actor: SELF }); + assert.deepEqual((await tick(gh)).relaunched, []); + assert.equal(recordOf(gh, 7), null); + + timeline.pop(); + timeline.push(removal); + assert.deepEqual((await tick(gh)).relaunched, [7]); +}); + test("the count survives across ticks and dispatcher restarts, and starts over when a person re-applies the label", async () => { const gh = fakeGitHub([{ number: 7, labels: [OBJ, "pendulum:running"], since: 20 * MIN }]); await tick(gh); @@ -321,6 +340,7 @@ test("the count survives across ticks and dispatcher restarts, and starts over w assert.deepEqual(r.vanished, [7], "two relaunches already on the issue: Blocked"); assert.equal(recordOf(gh, 7).tries.length, 2); // A person re-applies the label: the Objective is Queued again, picked, and its next loss counts from there. + gh.person(7, "unlabeled", OBJ); gh.person(7, "labeled", OBJ); const picked = await tick(gh); assert.deepEqual(picked.reset, [7]); diff --git a/plugin/test/report-compare.test.mjs b/plugin/test/report-compare.test.mjs index 1a1de6d4..21e8a0f1 100644 --- a/plugin/test/report-compare.test.mjs +++ b/plugin/test/report-compare.test.mjs @@ -10,6 +10,7 @@ import { PENDULUM_VERSION } from "../scripts/lib/inputs.mjs"; import { renderReport } from "../scripts/lib/report.mjs"; import { parseArgs, reportCommand } from "../scripts/local.mjs"; import { PREVIOUS_NAME } from "../scripts/lib/local.mjs"; +import { refusedMarker } from "../scripts/lib/stop.mjs"; import { baselineOf } from "../../bench/lib/baseline.mjs"; // `pendulum report --compare` (#545): two experiment arms side by side, from Pendulum's own records alone, each arm's @@ -216,6 +217,24 @@ test("report --compare: an experiment label counts only where the person who las assert.ok(!plainCalls.some((c) => c.includes("/timeline"))); }); +test("report falls back to the accepted Draft removal and leaves a missing release unknown", async () => { + const w = experiment(); + const draft = (event, minute, id) => ({ event, id, label: { name: "pendulum:draft" }, actor: ME, created_at: at(minute) }); + w.timelines[11].push(draft("labeled", 0), draft("unlabeled", 2, 1101), draft("labeled", 3), draft("unlabeled", 4, 1102)); + w.timelines[11].push({ + event: "commented", + user: BOT, + performed_via_github_app: APP, + created_at: at(3), + body: refusedMarker(11, { id: 1101, at: at(2) }), + }); + w.timelines[12].push(draft("labeled", 0), { event: "labeled", label: { name: "pendulum:running" }, actor: BOT, created_at: at(5) }); + const { json } = await report(w, ["--label", FAST, "--json"]); + const clock = (n) => json.objectives.filter((o) => o.issue === n).map((o) => [o.started, o.wallMinutes]); + assert.deepEqual(clock(11), [[at(4), 56]]); + assert.deepEqual(clock(12), [[null, null]]); +}); + test("report --compare: each arm's n, outcomes, and the exact median and p25..p75 per merged Objective, kinds apart, no blended total", async () => { const { code, json: r, err } = await report(experiment(), ["--compare", "fast", "--compare", "slow", "--json"]); assert.equal(code, 0, err); diff --git a/plugin/test/serve-hold.test.mjs b/plugin/test/serve-hold.test.mjs index ffd52ca4..d45de534 100644 --- a/plugin/test/serve-hold.test.mjs +++ b/plugin/test/serve-hold.test.mjs @@ -685,7 +685,7 @@ test("withClaim: a stage that paused on this machine's network keeps its claim w t = since + OUTAGE.blockMs; assert.equal((await loop.resume(7)).exit, "blocked"); const notice = gh.writes.find((w) => w.startsWith("POST /issues/7/comments") && w.includes("pendulum:block")); - assert.match(notice, /this machine could not reach api\.anthropic\.test \(EAI_AGAIN\) from Nov 14, 8:47 AM UTC for 12 h, past Pendulum's 12 h bound for an outage\. The network is back: re-apply the label/); + assert.match(notice, /this machine could not reach api\.anthropic\.test \(EAI_AGAIN\) from Nov 14, 8:47 AM UTC for 12 h, past Pendulum's 12 h bound for an outage\. The network is back: resume through Draft/); assert.match(notice, /<!-- pendulum:block \{"cause":"outage"\} -->/); assert.equal(gh.comments.filter((c) => c.body.includes(":local -->")).length, 0, "the claim is dropped"); // A later pause long after a resume is a new outage: its own since. diff --git a/plugin/test/stuck-checks.test.mjs b/plugin/test/stuck-checks.test.mjs index 5e40b83f..b8c4efef 100644 --- a/plugin/test/stuck-checks.test.mjs +++ b/plugin/test/stuck-checks.test.mjs @@ -232,7 +232,7 @@ test("a producing workflow run that ended startup_failure, or was cancelled befo assert.equal(result.stuck.kind, "ended"); assert.match(result.stuck.reason, new RegExp(`^required check\\(s\\) quality never reported on a{7}: workflow run CI \\(run 77\\) ended ${conclusion} before its job ran`)); assert.doesNotMatch(result.stuck.reason, /check the required check names/); - assert.match(result.stuck.reason, /rerun it on GitHub or fix the workflow, then re-apply the label; no failing run to fix$/); + assert.match(result.stuck.reason, /rerun it on GitHub or fix the workflow, then resume through Draft; no failing run to fix$/); assert.ok(!phases.some((l) => /waiting up to/.test(l)), "no wait for a run that has ended"); // GitHub could not start it: most often the workflow file, the repository's; a cancellation may be its own concurrency setting. const cause = conclusion === "startup_failure" ? "setup" : "work"; @@ -323,7 +323,7 @@ test("a required check whose step runs past its usual duration has hung: the wai assert.equal(result.passes, 0); assert.equal(minutes, 17); assert.equal(result.stuck.kind, "running"); - assert.equal(result.stuck.reason, "no progress: `quality` / `Run scripts/ci/setup.sh` running 17 min, normally ~1 min; required check(s) quality not finished on aaaaaaa after 17 min: CI (run 77) still in progress; no failing run to fix; when this change makes that step slower, re-apply the Objective's label: aaaaaaa is then waited for up to the stage's wall clock"); + assert.equal(result.stuck.reason, "no progress: `quality` / `Run scripts/ci/setup.sh` running 17 min, normally ~1 min; required check(s) quality not finished on aaaaaaa after 17 min: CI (run 77) still in progress; no failing run to fix; when this change makes that step slower, resume through Draft: aaaaaaa is then waited for up to the stage's wall clock"); assert.equal(posted.length, 1); assert.ok(posted[0].startsWith(noProgressMarker(4, SHA)), posted[0]); // The label re-applied: the next stage on that head has no hang judgement, and the slower step goes green at 40. diff --git a/plugin/test/triage.test.mjs b/plugin/test/triage.test.mjs index 7b49ffa3..6e931708 100644 --- a/plugin/test/triage.test.mjs +++ b/plugin/test/triage.test.mjs @@ -599,7 +599,7 @@ test("again: the failed jobs of a head a fix pass left unchanged are rerun once, assert.equal(r.rerun, false); assert.deepEqual(r.refused, { status: 403, permission: true, rateLimited: false, where: "local", unchanged: true }); const { refusedRerunText } = await import("../scripts/lib/triage.mjs"); - assert.equal(refusedRerunText(r.refused), "GitHub refused the rerun of the failed jobs (403: the token cannot rerun jobs); rerun the failed jobs on GitHub, or give the token Actions read and write, then re-apply the label"); + assert.equal(refusedRerunText(r.refused), "GitHub refused the rerun of the failed jobs (403: the token cannot rerun jobs); rerun the failed jobs on GitHub, or give the token Actions read and write, then resume through Draft"); assert.equal((await t.again({ sha: "f".repeat(40), failedRuns: [{ ...red41[0], id: 48 }] })).refused.earlier, true, "refused once on the Objective: not asked again"); }); rmSync(home, { recursive: true, force: true }); @@ -704,7 +704,7 @@ test("validation loop: a fix pass that commits nothing never counts the same red const lead = `the fix pass changed nothing, so the red on 9999999 is unchanged (quality (required check): ${supplyChain})`; // The work's red: one fresh worker pass after the fix pass, which changed nothing either; the Block names both. const both = `the fix pass and the fresh worker pass after it changed nothing, so the red on 9999999 is unchanged (quality (required check): ${supplyChain})`; - const remedy = "read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then re-apply the label"; + const remedy = "read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then resume through Draft"; // The real run: flaky at 0.55, below the bar, so a fix pass runs and commits nothing; the rerun is red again. const again = await run(); @@ -846,7 +846,7 @@ async function freshRun({ before = testFailed, after = before, logBefore = faili } } // What the unchanged red's Block says on 9999999 before any fresh-pass clause. -const unchangedLead = `the fix pass changed nothing, so the red on 9999999 is unchanged (quality (required check): ${supplyChain}); its failed jobs were rerun once and failed again; read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then re-apply the label`; +const unchangedLead = `the fix pass changed nothing, so the red on 9999999 is unchanged (quality (required check): ${supplyChain}); its failed jobs were rerun once and failed again; read the failing job on GitHub, fix the cause on the branch or rerun the failed jobs there, then resume through Draft`; test("validation loop: a red on Pendulum's own catch-up merge gets its fix pass unjudged; the red after that pass is judged (#399)", async () => { const { validationLoop } = await import("../scripts/lib/session.mjs"); From bd88e620e7e32ad3a9e7edc91f35d98f78eb58c0 Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Thu, 19 Nov 2026 00:10:30 -0800 Subject: [PATCH 6/8] Recheck authorized Draft release before worker startup --- plugin/scripts/dispatch.mjs | 15 ++++++++++--- plugin/scripts/lib/stop.mjs | 3 ++- plugin/scripts/worker.mjs | 37 ++++++++++++++++++++------------- plugin/test/draft.test.mjs | 35 ++++++++++++++++++++++++++++++- plugin/test/rate-limit.test.mjs | 32 ++++++++++++++++++++++++++++ 5 files changed, 102 insertions(+), 20 deletions(-) diff --git a/plugin/scripts/dispatch.mjs b/plugin/scripts/dispatch.mjs index 572bb5cb..c9afae91 100644 --- a/plugin/scripts/dispatch.mjs +++ b/plugin/scripts/dispatch.mjs @@ -313,6 +313,14 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not log(`issue #${inputs.issue} is not an open ${inputs.objectiveLabel} issue; nothing to dispatch`); return { ...nothingDispatched(), skipped: [{ number: inputs.issue, reason: `not open with ${inputs.objectiveLabel}` }], reason: "not an objective" }; } + if (inputs.issue && stopCause(wanted[0], inputs.objectiveLabel) !== "restart") { + const events = await timelineOf(repo, inputs.issue, cached).catch(() => null); + const hold = await draftActivationHold(events, inputs.issue, inputs.objectiveLabel, mayGo); + if (hold) { + log(` #${inputs.issue}: ${hold}`); + return { ...nothingDispatched(), skipped: [{ number: inputs.issue, reason: hold }], reason: hold }; + } + } // Today's spend is read beside everything below: it decides only the picks at the end. It never rejects. const spend = todaysSpend(repo, inputs, { token, now }); @@ -1499,9 +1507,10 @@ export async function dispatch(inputs, { token, decisionRole = "dispatcher", not return "its Draft removal has no matching Objective activation; next tick"; } if (!start) return null; - // A restart since (Pendulum's record of a person's restart, logic.mjs restartedAt) is the newer start, as personStart reads. - const restart = restartedAt(commentsOf(events)); - if (restart && Date.parse(restart) >= Date.parse(start.created_at)) return null; + // A Draft release can be superseded by a restart only when the restart is strictly later (stop.mjs). + const restart = Date.parse(restartedAt(commentsOf(events))); + const started = Date.parse(start.created_at); + if (restart > started || (!draft && restart === started)) return null; const ok = await goTrust(events, n, mayGo)(start.actor ?? null, start); if (ok === true) return null; if (ok === "unread") { diff --git a/plugin/scripts/lib/stop.mjs b/plugin/scripts/lib/stop.mjs index fa2bce29..978f84c9 100644 --- a/plugin/scripts/lib/stop.mjs +++ b/plugin/scripts/lib/stop.mjs @@ -86,7 +86,8 @@ export async function draftActivationHold(events, n, label, trusted) { const activation = activationEvents(events, label, { assumeObjective: true }).at(-1); if (!activation || Date.parse(activation.created_at) < Date.parse(draft.created_at)) return "the Objective has no activation after Draft"; const restart = restartedAt(events.filter((e) => e?.event === "commented").map((e) => ({ ...e, user: e.user ?? e.actor }))); - if (restart && Date.parse(restart) >= Date.parse(activation.created_at)) return null; + // Restart records carry the label's second. A tie does not establish that the restart came after this activation. + if (Date.parse(restart) > Date.parse(activation.created_at)) return null; const ok = await goTrust(events, n, trusted)(activation.actor ?? null, activation); if (ok === true) return null; return ok === "unread" ? "the Objective's Draft activation permission could not be checked" : DRAFT_ACTIVATION_REFUSED; diff --git a/plugin/scripts/worker.mjs b/plugin/scripts/worker.mjs index c4ec3e61..ca96a495 100644 --- a/plugin/scripts/worker.mjs +++ b/plugin/scripts/worker.mjs @@ -18,21 +18,21 @@ import { dropOwned, privateTmp, writeOwn } from "./lib/fsafe.mjs"; import { join, resolve } from "node:path"; import { PLUGIN_ROOT, branchIdentity, installCommand, installDeps, installPlugin, installTools, runnerFileEnv, openRegeneration, runSetup } from "./lib/checkout.mjs"; import { LIMIT, USAGE_LIMIT, UsageLimitReached, credentialEnv, gatewaySession, harnessVersion, runHarness, carveDriftReserve, passMaxUsd, scrubbedEnv, stageLimits } from "./lib/harness.mjs"; -import { addLabels, findPr, getIssue, getRepo, listComments, listReviews, prComment, primeWriters, markReady, removeLabel, repoOf, rest, runningSince } from "./lib/github.mjs"; +import { addLabels, findPr, getIssue, getRepo, listComments, listReviews, listTimeline, prComment, primeWriters, markReady, removeLabel, repoOf, rest, runningSince } from "./lib/github.mjs"; import { commandFailed, log, mask, parseArgs, postedError, redactSecrets, resolveInputs, setOutput } from "./lib/inputs.mjs"; import { useObjectiveZone } from "./lib/clock.mjs"; import { unknownRuns, unpricedCodex } from "./lib/usage.mjs"; import { REVIEW_LABEL, conflictFiles, ontoRecord, rebaseCost, copilotCount, costByPhase, stageSpendLine, usdText, decideExit, decisionsRead, marker, planAskedOf, protectedPaths, protectedTouched, sessionCapNote, setupPaths, sumSpend, isSelf, restartedAt } from "./lib/logic.mjs"; import { TASK_CARD_TEMPLATE, servedSilent, applyExit as applyExitNow, appliedExit, endStep, stateCard, buildPrompt, commitAuthor, openAccess, configureGit, crashed, deadline, doctorBlock, earlyOutageEnd, exitStep, outageExit, outageFirst, usageLimitExit, exitRecord, gitIdentity, lastMessage, liveActivity, markRunning, maskFile, objectiveDecisions, observe, postHandedOff, postValidated, progressReporter, rebaseExitLine, recordMergeable, remainingMs, reviewScope, restoreTranscript, saveAgentTranscript, saveTranscript, stageThreads, stopStage, stoppedRebase, unreadNow, validationLoop, workValidation, writeUsage, onCancel, cancelledEnd, stageProgressRun } from "./lib/session.mjs"; import { eventPayload, stageSealKey, usageSeal } from "./lib/seal.mjs"; -import { DRAFT_LABEL, RESTART_LABEL, claimExit, objectiveReader, commitExit, confirmRunning, holdIfStopped, parked, stopCause, watchObjective } from "./lib/stop.mjs"; +import { DRAFT_LABEL, RESTART_LABEL, claimExit, draftActivationHold, goTrust, labelTrust, objectiveReader, commitExit, confirmRunning, holdIfStopped, parked, stopCause, watchObjective } from "./lib/stop.mjs"; import { GENERATED_ATTR, openOutbox } from "./lib/outbox.mjs"; import { allowAgentEnv } from "./lib/agent.mjs"; import { jobChecks } from "./doctor.mjs"; import { routeInputs, stageMoves } from "./lib/accounts.mjs"; import { routeLimits } from "./lib/route-holds.mjs"; import { reviewHold, waitReason } from "./lib/overlap.mjs"; -import { accountGate, authorGate, choiceGate, planGate, startedAt } from "./lib/objective-trust.mjs"; +import { accountGate, authorGate, choiceGate, planGate, startTime } from "./lib/objective-trust.mjs"; import { stageStart } from "./lib/objective-cap.mjs"; import { ranWith } from "./lib/choice.mjs"; import { agentUser, exec } from "./lib/proc.mjs"; @@ -262,8 +262,6 @@ async function main() { checkout = access.checkout; // notice: local mode's App, for the notices that @mention a person (session.mjs applyExit). const token = { token: keeper.getter, notice: access.notice }; - // No agent uid on this runner (no sudo, no systemd): the run Blocks before anything else. - const agentError = access.agentError || null; await primeWriters(repo, token, { maintainers: inputs.maintainers }); const app = keeper.app; progress = progressReporter(repo, issue, token, { stage: "work", harness: inputs.harness, model: inputs.model }); @@ -383,12 +381,6 @@ async function main() { } async function run() { - if (agentError) { - const block = doctorBlock([agentError]); - await applyExit(repo, { issue, pr: null, exit: "blocked", ...block, notify: inputs.notify }, token); - await finish("blocked", block.reason); - return; - } // 1. The issue. let issueData = await getIssue(repo, issue, token); // Its visible times from here on in the zone its body names, if any (lib/clock.mjs); the progress comment's too. @@ -420,6 +412,24 @@ async function main() { return; } + // The dispatcher's admission can be stale by the time a queued job begins. Use the same fresh timeline for admission + // and for the plan clock, before reading the text's author and starting any work. + const events = await listTimeline(repo, issue, token); + const mayGo = labelTrust(repo, token); + const activationHold = await draftActivationHold(events, issue, inputs.objectiveLabel, mayGo); + if (activationHold) { + await finish("skipped", activationHold); + return; + } + + // No agent uid on this runner (no sudo, no systemd): an admitted run Blocks here. + if (access.agentError) { + const block = doctorBlock([access.agentError]); + await applyExit(repo, { issue, pr: null, exit: "blocked", ...block, notify: inputs.notify }, token); + await finish("blocked", block.reason); + return; + } + // From here the stage stops when a person stops its Objective (its label removed, its issue closed): every harness // pass ends, its spend is recorded, its PR is left a draft, and the stage exits (session.mjs stopStage). // The stopped stage's end when the usual one runs out of time (session.mjs stopStage): written at once, its stream @@ -448,10 +458,7 @@ async function main() { watch = watchObjective({ read: readObjective, label: inputs.objectiveLabel, onStop: (cause) => void stopNow(cause) }); beforeExit = (commit = false) => confirmRunning({ read: readObjective, label: inputs.objectiveLabel, onStop: (cause) => void stopNow(cause), commit }); - // When the Objective was last started (its label applied, or its draft label taken off: objective-trust.mjs startedAt), - // read before the text (planGate): an edit and a start landing between the two reads then count as after this stage's - // plan, never as before it. - const labeledAt = await startedAt(repo, issue, inputs.objectiveLabel, token); + const labeledAt = await startTime(events, inputs.objectiveLabel, goTrust(events, issue, mayGo)); // Only text a writer wrote reaches a harness (objective-trust.mjs): the stage acts on the title and body read with their // author, last editor and latest title renamer, and Blocks before any harness when one cannot push and is not a pinned // maintainer. diff --git a/plugin/test/draft.test.mjs b/plugin/test/draft.test.mjs index 9dd68de8..93ce9679 100644 --- a/plugin/test/draft.test.mjs +++ b/plugin/test/draft.test.mjs @@ -6,7 +6,7 @@ import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; -import { DRAFT_LABEL, RESTART_LABEL, isDraft, requeuedIn, stopCause, stopText, watchObjective } from "../scripts/lib/stop.mjs"; +import { DRAFT_LABEL, RESTART_LABEL, isDraft, requeuedIn, restartMarker, restartRecord, stopCause, stopText, watchObjective } from "../scripts/lib/stop.mjs"; import { RETRY } from "../scripts/lib/github.mjs"; import { setSelf } from "../scripts/lib/logic.mjs"; @@ -144,6 +144,39 @@ test("dispatcher waits for the Draft removal event and starts with Objective ide assert.ok(!ready.writes.includes(`DELETE /issues/7/labels/${OBJ}`)); }); +test("an earlier restart in the same second never authorizes a Draft release", async () => { + const { dispatch } = await import("../scripts/dispatch.mjs"); + const at = new Date(Math.floor(Date.now() / 1000) * 1000).toISOString(); + const maintainer = { login: "maintainer", type: "User" }; + const triager = { login: "triager", type: "User" }; + const release = { id: 13, event: "unlabeled", label: { name: DRAFT_LABEL }, created_at: at, actor: triager }; + const timeline = [ + { id: 10, event: "labeled", label: { name: OBJ }, created_at: at, actor: maintainer }, + { id: 11, event: "commented", created_at: at, actor: { login: "pendulum-app[bot]", type: "Bot" }, body: `${restartMarker(7, at)}\n${restartRecord({ issue: 7, at })}` }, + { ...release, id: 12, event: "labeled", actor: maintainer }, + release, + ]; + await withApi({}, async () => { + setSelf("pendulum-app[bot]"); + const api = fakeApi({ issues: (label) => (label === OBJ ? [issue([OBJ])] : []), timeline: () => timeline }); + try { + const queued = await dispatch(INPUTS, { token: "t" }); + assert.deepEqual(queued.ready, []); + assert.match(queued.skipped[0].reason, /started by triager/); + const named = await dispatch({ ...INPUTS, issue: 7 }, { token: "t" }); + assert.deepEqual(named.ready, []); + assert.match(named.skipped[0].reason, /Draft activation was not authorized/); + + timeline.push({ ...timeline[2], id: 14 }, { ...release, id: 15, actor: maintainer }); + const authorized = await dispatch(INPUTS, { token: "t" }); + assert.deepEqual(authorized.ready, [7]); + } finally { + api.restore(); + setSelf(null); + } + }); +}); + test("the merge pass never merges a draft's PR, whoever runs it", async () => { const { mergeReadyOne } = await import("../scripts/lib/session.mjs"); await withApi({}, async () => { diff --git a/plugin/test/rate-limit.test.mjs b/plugin/test/rate-limit.test.mjs index 62201bd3..0ce18996 100644 --- a/plugin/test/rate-limit.test.mjs +++ b/plugin/test/rate-limit.test.mjs @@ -240,6 +240,38 @@ async function worker(gh, { env = {}, virtual = false } = {}) { return { code, out, result: existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null }; } +test("a queued worker checks the latest Draft release before it touches the plan or starts work", async () => { + const maintainer = { login: "maintainer", type: "User" }; + const triager = { login: "triager", type: "User" }; + const now = Date.now(); + const labelEvent = (id, event, name, actor, secondsAgo) => ({ id, event, label: { name }, actor, created_at: new Date(now - secondsAgo * 1000).toISOString() }); + const timeline = [ + labelEvent(10, "labeled", "pendulum:objective", maintainer, 60), + labelEvent(11, "labeled", "pendulum:running", maintainer, 30), + labelEvent(12, "labeled", "pendulum:draft", maintainer, 15), + labelEvent(13, "unlabeled", "pendulum:draft", triager, 10), + ]; + const gh = await fakeGitHub(({ method, url }) => { + const path = new URL(url, "https://github.test").pathname; + if (method !== "GET") return null; + if (path.endsWith("/collaborators/triager/permission")) return [200, { permission: "triage" }]; + if (path.endsWith("/collaborators")) return [200, [maintainer]]; + if (path.endsWith("/timeline")) return [200, timeline]; + if (path.endsWith("/issues/7")) return [200, { number: 7, state: "open", user: maintainer, body: "", labels: [{ name: "pendulum:objective" }, { name: "pendulum:running" }] }]; + return null; + }); + try { + const { code, out, result } = await worker(gh, { env: { PENDULUM_LOCAL: "1", PENDULUM_APP_SLUG: "pendulum-app" } }); + assert.equal(code, 0, out); + assert.equal(result?.exit, "skipped", out); + assert.match(result.reason, /Draft activation was not authorized/); + assert.ok(gh.seen.some(({ url }) => url.endsWith("/collaborators/triager/permission"))); + assert.ok(!gh.seen.some(({ url }) => /\/pulls|\/git\/refs/.test(url)), "branch and PR state are untouched"); + } finally { + gh.close(); + } +}); + test("worker.mjs, run for real on the local route: a reset 20 minutes ahead (past its 15-minute wait) ends it paused with the reset, nothing sent after", async () => { const reset = Math.ceil((Date.now() + 20 * 60_000) / 1000) * 1000; // The quota stays spent: every request is refused. From 4d13d030d5c20a5f1e97f2fff79707bfdf8edfd0 Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Thu, 19 Nov 2026 00:15:38 -0800 Subject: [PATCH 7/8] Keep manual session entry points and shipped skills in sync --- bench/skills.json | 16 +++++------ plugin/scripts/local.mjs | 32 ++++++++++++++++------ plugin/skills/pendulum-file/reference.md | 2 +- plugin/skills/pendulum-run/reference.md | 2 +- plugin/skills/pendulum-status/SKILL.md | 2 +- plugin/skills/pendulum-status/reference.md | 4 +-- plugin/test/draft.test.mjs | 15 +++++++++- plugin/test/lifecycle.test.mjs | 5 ++-- plugin/test/objective-trust.test.mjs | 22 ++++++++++++++- 9 files changed, 75 insertions(+), 25 deletions(-) diff --git a/bench/skills.json b/bench/skills.json index 650293ab..48aebf56 100644 --- a/bench/skills.json +++ b/bench/skills.json @@ -36,9 +36,9 @@ "words": 617, "files": { "reference.md": { - "sha256": "baa3254e2d546ce969fd8ef234141ddebc488abada0dc96094cac49b23dfce05", + "sha256": "5888e13c3416e62ada9a2392e4214c6609447f5433d7961483e0bc7db678d31a", "lines": 67, - "words": 1303 + "words": 1297 } } }, @@ -152,9 +152,9 @@ "words": 668, "files": { "reference.md": { - "sha256": "7b417884528fa46a397433909e8490e111e9f5f7480b924ad507b1117da9cfbd", + "sha256": "9ac608b8543691e5fef32a94d95b9b1438de704ddfb4f6633e91b54c21085f3e", "lines": 23, - "words": 368 + "words": 379 } } }, @@ -200,14 +200,14 @@ } }, "pendulum-status": { - "sha256": "d6284876e370c596cc37e59a5ba76d3ad41daf63826c538272f995b63cc2eeaf", + "sha256": "394333b54d1b472dca28682f9cf8a0acd8154bf97f3a6048d45ac76957f974d9", "lines": 40, - "words": 626, + "words": 630, "files": { "reference.md": { - "sha256": "a5c20e94c2bf22dce21da23411c2e91a42a6dfcd487a81b62c19ded3341833f0", + "sha256": "b0da1fe6f1bb255963fe1373d6a2ba81155003433879f7e60969eb407cf35ea2", "lines": 55, - "words": 968 + "words": 967 } } }, diff --git a/plugin/scripts/local.mjs b/plugin/scripts/local.mjs index 3d7850a1..480a64e2 100644 --- a/plugin/scripts/local.mjs +++ b/plugin/scripts/local.mjs @@ -65,10 +65,10 @@ import { answeredRepos, declaredQuestion, planNeeds as planNeedsOf } from "./lib import { localDatabaseChecks, noticeAppCheck, pluginVersionCheck } from "./doctor.mjs"; import { RELEASES_URL, checkoutProblem, markInUse, pinDecision, releaseCheckout, runningPendulum, runningName, startProblem } from "./lib/release.mjs"; import { SKIP_SMUDGE_ENV, lfsPinEnv } from "./lib/lfs.mjs"; -import { EDITED_REASON, authorGate, foundationTrusted, labelsVouched, objectiveInputs, planStateNow, recordText, settled, startedAt, trustedIssue } from "./lib/objective-trust.mjs"; +import { EDITED_REASON, authorGate, foundationTrusted, labelsVouched, objectiveInputs, planStateNow, recordText, settled, startTime, trustedIssue } from "./lib/objective-trust.mjs"; import { openEditCheck } from "./lib/edit-check.mjs"; import { openCommentCheck } from "./lib/comment-check.mjs"; -import { DRAFT_LABEL, goTrust, isDraft, labelTrust, readDraftActivationHold, requeuedIn, stopCause } from "./lib/stop.mjs"; +import { DRAFT_LABEL, draftActivationHold, goTrust, isDraft, labelTrust, readDraftActivationHold, requeuedIn, stopCause } from "./lib/stop.mjs"; import { loopCap, machineBudget, machineLimits, machineRoom, readPressure, slotHolders, slotsDir, takeSlot } from "./lib/machine.mjs"; import { lapseFacts, lapseInput, openLapseCheck } from "./lib/lapse-check.mjs"; import { flushDecisionSpend } from "./lib/decision-spend.mjs"; @@ -3193,7 +3193,7 @@ export class Local { * whose state could not be read. `gh`: the GitHub reads, `waitMs` the retry wait (a test's own). */ async runIssue(issue, { wait = false, gh: given = {}, waitMs = 2_000 } = {}) { - const gh = { findPr, getIssue, listComments, ...given }; + const gh = { findPr, getIssue, listComments, timelineOf, ...given }; this.reapHere(issue); const live = liveStage(this.ws(issue)); if (live) throw new Error(`${liveStageLine(issue, live)}, then run again`); @@ -3201,6 +3201,9 @@ export class Local { if (data?.state === "closed") throw new Error(`#${issue} is closed; nothing to run`); // Before any claim: a draft is never run (lib/stop.mjs). if (isDraft(data)) throw draftRefusal(issue, "nothing to run"); + const events = await retried(`reading the activation of #${issue}`, () => gh.timelineOf(this.repo, issue, this.opts), { waitMs }); + const hold = await readDraftActivationHold(this.repo, issue, this.objectiveLabel(), this.opts, events); + if (hold) throw new Error(`#${issue}: ${hold}; nothing to run`); await this.adoptForRun(issue, data); const pr = await retried(`reading the open PR of pendulum/${issue}`, () => gh.findPr(this.repo, `pendulum/${issue}`, this.opts), { waitMs }); const next = stageFor({ pr, issue: data }) ?? "work"; @@ -3257,6 +3260,8 @@ export class Local { */ async reviewToEnd(prNumber, { wait = false, resumeWith = "" } = {}) { const issue = await this.reviewIssueOf(prNumber); + const data = await getIssue(this.repo, issue, this.opts); + await checkDraftRelease(this.repo, issue, this.objectiveLabel(), this.opts, data, "nothing to review"); return this.toEnd(issue, await this.withClaim(issue, () => this.review(issue, prNumber, { wait })), { wait, resumeWith, parts: false }); } @@ -4323,6 +4328,15 @@ const untrustedRefusal = (t, what) => new Error(`${what}: ${t.reason}. ${t.fix}` /** A draft (pendulum:draft) is run on no route, a session's included (lib/stop.mjs stopCause): the refusal and its fix. */ const draftRefusal = (issue, what) => new Error(`${what}: #${issue} is a draft (${DRAFT_LABEL}), which Pendulum never runs; start it first (ensure it has the Objective label, then remove ${DRAFT_LABEL}, or ask "Start Pendulum Objective ${issue}")`); +async function checkDraftRelease(repo, issue, label, opts, data, what) { + if (isDraft(data)) throw draftRefusal(issue, what); + const events = await timelineOf(repo, issue, opts); + const mayGo = labelTrust(repo, opts); + const hold = await draftActivationHold(events, issue, label, mayGo); + if (hold) throw new Error(`${what}: ${hold}`); + return { events, mayGo }; +} + /** * `pendulum issue <issue> [--out FILE]`: the issue as a session reads it (/pendulum:pendulum-run --here, /pendulum:pendulum-review-here), written * to --out (default $PENDULUM_IN/issue.md, else <git dir>/pendulum-in/issue.md) as the worker writes it: the title and @@ -4335,7 +4349,7 @@ async function issueForSession(issue, flags) { const clone = sessionClone(flags); const { inputs } = await sessionInputs(clone); const data = await getIssue(clone.repo, issue, clone.opts); - if (isDraft(data)) throw draftRefusal(issue, `#${issue} is not given to this session`); + await checkDraftRelease(clone.repo, issue, inputs.objectiveLabel, clone.opts, data, `#${issue} is not given to this session`); const t = await trustedIssue(clone.repo, issue, data, clone.opts); if (!t.ok) throw untrustedRefusal(t, `#${issue} is not given to this session`); const file = resolve(flags.out || sessionIssueFile(clone.dir)); @@ -4378,10 +4392,10 @@ async function deliver(issue, flags) { // Run from a session (/pendulum:pendulum-run --here), so the App's key is not read here: notices post with this token. if (process.env.PENDULUM_LOCAL_APP_ID) log("notices post with your own token here, so their @mention notifies no one; the App posts them only for serve and run"); const { defaultBranch, inputs } = await sessionInputs(clone); - // When the Objective was last started, read before the text, as the worker does (objective-trust.mjs startedAt, planGate). - const labeledAt = await startedAt(repo, issue, inputs.objectiveLabel, opts); const issueNow = await getIssue(repo, issue, opts); - if (isDraft(issueNow)) throw draftRefusal(issue, "nothing was delivered"); + const { events, mayGo } = await checkDraftRelease(repo, issue, inputs.objectiveLabel, opts, issueNow, "nothing was delivered"); + // Use the activation clock before reading the checked text, as the worker does. + const labeledAt = await startTime(events, inputs.objectiveLabel, goTrust(events, issue, mayGo)); // The worker's check, made again here: the body the session read may have been edited since by someone who cannot push. const trusted = await authorGate({ repo, issue, issueData: issueNow, notify: inputs.notify, opts, apply: applyExit }); if (!trusted.ok) { @@ -4718,7 +4732,9 @@ async function postFindings(prNumber, file, flags) { if (!issue) throw new Error(`PR #${prNumber} is not on a pendulum/<issue> branch`); // The review job's check: a review judged against text no writer vouches for is not posted. const { inputs } = await sessionInputs(clone); - const trusted = await trustedIssue(repo, issue, await getIssue(repo, issue, opts), opts); + const data = await getIssue(repo, issue, opts); + await checkDraftRelease(repo, issue, inputs.objectiveLabel, opts, data, "nothing posted"); + const trusted = await trustedIssue(repo, issue, data, opts); if (!trusted.ok) throw untrustedRefusal(trusted, "nothing posted"); // The review job's second check: a review of code made from earlier text than the Objective's now is not posted. An // edit since the plan is judged by the edit check on the AI Gateway alone (a session has no stage harness here). diff --git a/plugin/skills/pendulum-file/reference.md b/plugin/skills/pendulum-file/reference.md index 7ba971fd..fd96982c 100644 --- a/plugin/skills/pendulum-file/reference.md +++ b/plugin/skills/pendulum-file/reference.md @@ -35,7 +35,7 @@ When the user wants another harness or model than the workflow's for this Object ## Refine a draft -A draft lives on GitHub, not in this chat: Pendulum never runs an issue with `pendulum:draft` on it, so edit it freely. One with `pendulum:objective` and no `pendulum:draft` is started: an edit before its first plan is used by the run; after it, a typo, formatting or wording-only edit keeps the plan, and any other edit Blocks the Objective at its next stage, where re-applying `pendulum:objective` plans again from the new text ([Edit an Objective](https://github.com/clockgrove/pendulum/blob/v0.10.0/docs/USAGE.md#edit-an-objective)). Say so before going on, and offer to make it a draft again first: `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:draft`, which stops a running stage the way a stop does (a missing label: The draft label). +A draft lives on GitHub, not in this chat: Pendulum never runs an issue with `pendulum:draft` on it, so edit it freely. Once an Objective has been released from Draft, an edit before its first plan is used by the run. After that, a typo, formatting or wording-only edit keeps the plan. Any other edit Blocks the Objective at its next stage. Resuming through Draft plans again from the new text ([Edit an Objective](https://github.com/clockgrove/pendulum/blob/v0.10.9/docs/USAGE.md#edit-an-objective)). Say so before going on, and offer to make it a draft again first: `gh issue edit <issue> --repo OWNER/NAME --add-label pendulum:draft`, which stops a running stage (a missing label: The draft label). Refine it as SKILL.md writes an Objective: the title, `## Goal`, `## Acceptance`, `## Context`, and its checks. Change only what you discussed. Then show the whole new title and body, and say what changed. Write nothing to GitHub without a yes; on a no, keep discussing or leave the issue as it is. On a yes: diff --git a/plugin/skills/pendulum-run/reference.md b/plugin/skills/pendulum-run/reference.md index ad47bd82..89f05ad3 100644 --- a/plugin/skills/pendulum-run/reference.md +++ b/plugin/skills/pendulum-run/reference.md @@ -1,6 +1,6 @@ # In-session readiness -Check that the issue is open, carries `pendulum:objective`, and has neither `pendulum:draft` nor an [open dependency](../pendulum-file/reference.md#start-a-draft). Removing Draft releases it to the dispatcher. For a draft or unlabelled issue, report its state and use pendulum-file only if the user wants that dispatcher handoff. +Check that the issue is open, carries `pendulum:objective`, and has neither `pendulum:draft` nor an [open dependency](../pendulum-file/reference.md#start-a-draft). A writer or named maintainer removing Draft releases it to the dispatcher. The session commands verify this activation. For a draft or unlabelled issue, report its state and use pendulum-file only if the user wants that dispatcher handoff. Check issue state with pendulum-status and the configured route's dispatcher records. Follow an active or paused run. If the configured loop or Action can pick up the issue during this session, leave it to that dispatcher. An eligible issue with no recorded claim yet can still be picked up. In-session setup does not reserve the Objective. diff --git a/plugin/skills/pendulum-status/SKILL.md b/plugin/skills/pendulum-status/SKILL.md index 13cfbb40..e9928aba 100644 --- a/plugin/skills/pendulum-status/SKILL.md +++ b/plugin/skills/pendulum-status/SKILL.md @@ -9,7 +9,7 @@ Read GitHub and report; change nothing. A way on is one of Pendulum's labels or ## Read the queue -1. `gh issue list --repo OWNER/NAME --state open --label pendulum:objective --json number,title,labels,createdAt --limit 100`, and the same with `--label pendulum:draft`, merged by number (a draft may carry both). Given an issue number, `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels` alone. +1. `gh issue list --repo OWNER/NAME --state open --label pendulum:objective --json number,title,labels,createdAt --limit 100`, and the same with `--label pendulum:draft` to include legacy drafts without the Objective label. Combine by issue number. Given an issue number, `gh issue view <issue> --repo OWNER/NAME --json number,title,state,labels` alone. 2. Read state from its labels ([reference.md](reference.md), States). A closed issue is done. Draft holds processing. An issue without `pendulum:objective` is unadmitted or stopped under the older flow. `pendulum:restart` records a restart request. 3. Its route: `pendulum:local`, the local loop's; any other, the Action's (the local loop's where no Action is active). 4. For a Running one, the steps table in Pendulum's progress comment on the issue: its last row, marked **Now**, is the step in progress and for how long; with no **Now** row the stage is between steps, and the rows above say what has run. diff --git a/plugin/skills/pendulum-status/reference.md b/plugin/skills/pendulum-status/reference.md index 3f099e16..58877f8b 100644 --- a/plugin/skills/pendulum-status/reference.md +++ b/plugin/skills/pendulum-status/reference.md @@ -9,8 +9,8 @@ Pendulum keeps each Objective's state in one label and, for an organization repo | Label | State | What happens next | Removing Draft queues a new work stage | | --- | --- | --- | --- | | none | Queued | The dispatcher starts it once a slot is free (`max_concurrent`), the day's spend is under `daily_usd` and every issue that blocks it is closed, `P0` first, then `P1`, `P2`, then by issue number. | no | -| `pendulum:running` | Running | A stage works it; its progress comment says what it is doing. Taking the label off stops it. | no | -| `pendulum:in-review` | In review | Its PR goes through the review, the worker's answer to it, the required checks and the merge on its own. Re-applying the label runs a work stage again, as after its PR was closed unmerged. | yes | +| `pendulum:running` | Running | A stage works it and its progress comment says what it is doing. Adding Draft stops it. | no | +| `pendulum:in-review` | In review | Its PR goes through the review, the worker's answer to it, the required checks and the merge on its own. Resuming through Draft runs a work stage again, as after its PR was closed unmerged. | yes | | `pendulum:blocked` | Blocked | Waits for a person: its Blocked notice names the reason, the fix and whether to resume or restart. | yes | | `pendulum:question` | Question | Waits for the decision it asks: answer it (Questions). | yes | diff --git a/plugin/test/draft.test.mjs b/plugin/test/draft.test.mjs index 93ce9679..ee7c43b4 100644 --- a/plugin/test/draft.test.mjs +++ b/plugin/test/draft.test.mjs @@ -232,9 +232,22 @@ test("local mode: `pendulum run` refuses a draft before any claim; a draft is ne const { claimBody } = await import("../scripts/lib/local.mjs"); const ws = mkdtempSync(join(tmpdir(), "draft-ws-")); const claimed = []; - const loop = Object.assign(Object.create(Local.prototype), { repo: REPO, repoFull: "acme/app", opts: { token: "t" }, wf: {}, holder: "this-loop", baseEnv: () => ({ PENDULUM_LOCAL_ALL: "1" }), reapHere: () => {}, ws: () => ws, withClaim: async (n) => (claimed.push(n), { exit: "delivered" }) }); + const loop = Object.assign(Object.create(Local.prototype), { repo: REPO, repoFull: "acme/app", opts: { token: "t" }, wf: {}, holder: "this-loop", baseEnv: () => ({ PENDULUM_LOCAL_ALL: "1" }), reapHere: () => {}, ws: () => ws, reviewIssueOf: async () => 7, withClaim: async (n) => (claimed.push(n), { exit: "delivered" }) }); const gh = { getIssue: async () => issue([OBJ, DRAFT_LABEL]), findPr: async () => null }; await assert.rejects(loop.runIssue(7, { gh, waitMs: 1 }), /#7 is a draft \(pendulum:draft\), which Pendulum never runs; start it first/); + const at = new Date().toISOString(); + const release = { event: "unlabeled", label: { name: DRAFT_LABEL }, created_at: at, actor: { login: "triager", type: "User" } }; + await withApi({}, async () => { + const timelineOf = async () => [{ ...release, event: "labeled" }, release]; + const api = fakeApi({ issue: () => issue([OBJ]), timeline: () => [{ ...release, event: "labeled" }, release] }); + try { + await assert.rejects(loop.runIssue(7, { gh: { ...gh, getIssue: async () => issue([OBJ]), timelineOf }, waitMs: 1 }), /Draft activation was not authorized/); + await assert.rejects(loop.reviewToEnd(70), /Draft activation was not authorized/); + assert.deepEqual(api.writes, [], "an unauthorized release is refused before local adoption"); + } finally { + api.restore(); + } + }); assert.deepEqual(claimed, [], "no claim is taken"); // Held by a loop of this machine that went away: resumed and reviewed unless a draft. const away = holderId(undefined, 2 ** 22 + 7); diff --git a/plugin/test/lifecycle.test.mjs b/plugin/test/lifecycle.test.mjs index 29f7968a..d7b1ffea 100644 --- a/plugin/test/lifecycle.test.mjs +++ b/plugin/test/lifecycle.test.mjs @@ -200,6 +200,7 @@ function loop() { dev: mkdtempSync(join(tmpdir(), "dev-")), repo: { owner: "o", name: "r", full: "o/r" }, opts: { token: "t" }, + wf: {}, withClaim: async (n, fn) => fn(), review: async (n, prNumber, o) => (ran.push(["review", n, prNumber, o.wait]), { exit: "delivered" }), runObjective: async (n, o) => (ran.push(["work", n, o.wait]), { exit: "delivered" }), @@ -214,12 +215,12 @@ test("pendulum run starts nothing when it cannot tell where the Objective stands // A PR read that keeps failing, on an In-review Objective: retried, then refused, never a work pass. let tries = 0; const { l, ran } = loop(); - await assert.rejects(l.runIssue(7, { waitMs: 1, gh: { findPr: () => (tries++, failing()), getIssue: async () => issue("pendulum:in-review") } }), /reading the open PR of pendulum\/7 failed 3 times .*nothing was started/); + await assert.rejects(l.runIssue(7, { waitMs: 1, gh: { findPr: () => (tries++, failing()), getIssue: async () => issue("pendulum:in-review"), timelineOf: async () => [] } }), /reading the open PR of pendulum\/7 failed 3 times .*nothing was started/); assert.equal(tries, 3); await assert.rejects(l.runIssue(7, { waitMs: 1, gh: { findPr: async () => null, getIssue: failing } }), /reading issue #7 failed/); // A read that fails once and then answers is used. let once = 0; - await l.runIssue(7, { waitMs: 1, gh: { findPr: () => (once++ ? Promise.resolve(pr()) : failing()), getIssue: async () => issue("pendulum:in-review") } }); + await l.runIssue(7, { waitMs: 1, gh: { findPr: () => (once++ ? Promise.resolve(pr()) : failing()), getIssue: async () => issue("pendulum:in-review"), timelineOf: async () => [] } }); assert.deepEqual(ran, [["review", 7, 5, false]]); // A closed issue: nothing to run. ran.length = 0; diff --git a/plugin/test/objective-trust.test.mjs b/plugin/test/objective-trust.test.mjs index 6abd6793..d4352a44 100644 --- a/plugin/test/objective-trust.test.mjs +++ b/plugin/test/objective-trust.test.mjs @@ -159,7 +159,7 @@ test("objective trust: an App's rename never vouches for the title, nor a rename // The session's route (local.mjs issue, deliver, post-review) against a GitHub that answers like the real one. const LOCAL = join(import.meta.dirname, "..", "scripts", "local.mjs"); const run = (args, env, cwd) => new Promise((ok) => execFile(process.execPath, [LOCAL, ...args, "--repo", "acme/app"], { cwd, env, encoding: "utf8", timeout: 60_000 }, (e, stdout, stderr) => ok({ code: e ? e.code : 0, stdout, stderr }))); -async function fakeGitHub({ author, editor = null, renamer = null, perms: p = perms, issueComments = [], commentsStatus = 200 }) { +async function fakeGitHub({ author, editor = null, renamer = null, perms: p = perms, issueComments = [], issueTimeline = [], commentsStatus = 200 }) { const calls = []; const send = (res, status, body) => { res.writeHead(status, { "content-type": "application/json" }); @@ -181,6 +181,7 @@ async function fakeGitHub({ author, editor = null, renamer = null, perms: p = pe if (path === "/repos/acme/app") return send(res, 200, { full_name: "acme/app", default_branch: "main" }); if (path === "/user") return send(res, 200, { login: "dev", type: "User" }); if (path === "/repos/acme/app/issues/7") return send(res, 200, { number: 7, title: "REST title", body: "REST body.", state: "open", labels: [{ name: "pendulum:objective" }] }); + if (path === "/repos/acme/app/issues/7/timeline") return send(res, 200, issueTimeline); if (path === "/repos/acme/app/issues/7/comments") return send(res, commentsStatus, commentsStatus === 200 ? issueComments : { message: "Not Found" }); if (path === "/repos/acme/app/pulls/9") return send(res, 200, { number: 9, head: { ref: "pendulum/7", sha: "a".repeat(40) }, base: { ref: "main" } }); const perm = /^\/repos\/acme\/app\/collaborators\/([^/]+)\/permission$/.exec(path); @@ -219,6 +220,25 @@ function clone({ branch = "main", workflow = null } = {}) { const envFor = (url, root) => ({ PATH: process.env.PATH, HOME: root, TMPDIR: process.env.TMPDIR, GITHUB_API_URL: url, PENDULUM_LOCAL_TOKEN: "github_pat_test", GIT_CONFIG_NOSYSTEM: "1" }); const writes = (calls) => calls.filter((c) => c.method !== "GET" && c.path !== "/graphql"); +test("session commands decline work and review delivery when the latest Draft removal was unauthorized", async () => { + const c = clone({ branch: "pendulum/7" }); + const out = join(c.root, "issue.md"); + const event = (id, event, login) => ({ id, event, actor: { login, type: "User" }, label: { name: "pendulum:draft" }, created_at: "2026-11-19T12:00:00Z" }); + const fake = await fakeGitHub({ author: user("kirk"), issueTimeline: [event(1, "labeled", "kirk"), event(2, "unlabeled", "reader")] }); + try { + for (const args of [["issue", "7", "--out", out], ["deliver", "7"], ["post-review", "9", "findings.json"]]) { + const r = await run(args, envFor(fake.url, c.root), c.work); + assert.equal(r.code, 1, r.stderr); + assert.match(r.stderr, /Draft activation was not authorized/); + } + assert.equal(existsSync(out), false, "no body reaches the session"); + assert.deepEqual(writes(fake.calls), [], "no handoff or review was written"); + assert.doesNotMatch(c.refs(), /pendulum\/7/, "nothing was pushed"); + } finally { + await fake.close(); + } +}); + test("session route: `pendulum deliver` Blocks a stranger's Objective with the author notice and pushes nothing", async () => { const c = clone({ branch: "pendulum/7" }); const fake = await fakeGitHub({ author: user("stranger") }); From 9cfbffd77c8c493b35286b8937d4185f0efc983a Mon Sep 17 00:00:00 2001 From: Kirk Marple <kirk@clockgrove.com> Date: Thu, 19 Nov 2026 00:15:38 -0800 Subject: [PATCH 8/8] Bump Pendulum to v0.10.9 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/.codex-plugin/plugin.json | 2 +- plugin/plugin.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 249f7298..810207d0 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pendulum", "displayName": "Clockgrove Pendulum", - "version": "0.10.8", + "version": "0.10.9", "description": "Label a GitHub issue and walk away: a coding agent (Claude Code, Codex or Copilot CLI) plans, builds and opens the pull request, a second agent reviews it, and your CI and merge queue land it.", "author": { "name": "Clockgrove", diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index d5604fc2..3b2d5188 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "pendulum", - "version": "0.10.8", + "version": "0.10.9", "description": "Label a GitHub issue and walk away: a coding agent (Claude Code, Codex or Copilot CLI) plans, builds and opens the pull request, a second agent reviews it, and your CI and merge queue land it.", "author": { "name": "Clockgrove", diff --git a/plugin/plugin.json b/plugin/plugin.json index 6b0de2bc..e0ab24e2 100644 --- a/plugin/plugin.json +++ b/plugin/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "pendulum", - "version": "0.10.8", + "version": "0.10.9", "description": "Label a GitHub issue and walk away: a coding agent (Claude Code, Codex or Copilot CLI) plans, builds and opens the pull request, a second agent reviews it, and your CI and merge queue land it.", "author": { "name": "Clockgrove", "url": "https://github.com/clockgrove" }, "homepage": "https://github.com/clockgrove/pendulum#readme",