From daddd1aac47429c965846162e80361a52cbabd3d Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Sun, 22 Nov 2026 17:26:39 +0100 Subject: [PATCH 1/2] feat: process-review measures a repository's PR, review and CI process; coach-process turns its findings into asks for the coordinator process-review mines merged pull requests, reviews and CI runs per day, computes throughput, efficiency and quality, turns fixed rules into suggestions, compares the days before and after every dated process change and renders one HTML report plus a daily digest (tools/process-review/, Node 18, no dependencies; the plugin's one Node tool, DECISIONS 2026-11-18). coach-process delivers at most five asks to the session that coordinates the work, records each in asks.json with the metric it should move, has the next analysis judge it, sends an ask ignored twice to the user, and checks each finding for what ytstack itself could have prevented. Observed on Yesterday-AI/context-mcp, 9 September to 22 November 2026 (about 2,900 merged pull requests): see the pull request. Co-Authored-By: Claude Opus 5.5 --- .ytstack/DECISIONS.md | 22 + .ytstack/spec/SPEC.md | 5 +- .ytstack/spec/dependencies.md | 2 +- .ytstack/spec/process-review.md | 80 +++ .ytstack/spec/skills.md | 2 +- CHANGELOG.md | 39 ++ NOTICE | 28 + QUICKSTART.md | 1 + README.md | 7 +- docs/codex.md | 1 + docs/kimi.md | 2 +- evals/README.md | 1 + evals/process-review/case.yaml | 5 + evals/process-review/fixture.sh | 42 ++ evals/process-review/graders/analyzed.md | 5 + .../process-review/graders/change-measured.md | 5 + evals/process-review/graders/report.md | 4 + .../process-review/graders/rule-triggered.md | 5 + evals/process-review/graders/skill-fired.md | 5 + evals/process-review/prompt.md | 11 + skills/coach-process/SKILL.md | 210 +++++++ skills/process-review/SKILL.md | 266 +++++++++ skills/process-review/references/config.md | 130 +++++ skills/process-review/references/metrics.md | 98 ++++ skills/process-review/references/rules.md | 57 ++ tests/process-review.test.sh | 188 ++++++ tests/skill-preambles.test.sh | 39 +- tools/process-review/README.md | 49 ++ tools/process-review/analyze.mjs | 548 ++++++++++++++++++ tools/process-review/api.mjs | 31 + tools/process-review/daily.mjs | 49 ++ tools/process-review/mine-failures.mjs | 49 ++ tools/process-review/mine-tokens.mjs | 56 ++ tools/process-review/mine.mjs | 115 ++++ tools/process-review/report.mjs | 345 +++++++++++ tools/process-review/rules.mjs | 134 +++++ tools/process-review/tool-versions.mjs | 42 ++ 37 files changed, 2670 insertions(+), 8 deletions(-) create mode 100644 .ytstack/spec/process-review.md create mode 100644 evals/process-review/case.yaml create mode 100644 evals/process-review/fixture.sh create mode 100644 evals/process-review/graders/analyzed.md create mode 100644 evals/process-review/graders/change-measured.md create mode 100644 evals/process-review/graders/report.md create mode 100644 evals/process-review/graders/rule-triggered.md create mode 100644 evals/process-review/graders/skill-fired.md create mode 100644 evals/process-review/prompt.md create mode 100644 skills/coach-process/SKILL.md create mode 100644 skills/process-review/SKILL.md create mode 100644 skills/process-review/references/config.md create mode 100644 skills/process-review/references/metrics.md create mode 100644 skills/process-review/references/rules.md create mode 100644 tests/process-review.test.sh create mode 100644 tools/process-review/README.md create mode 100644 tools/process-review/analyze.mjs create mode 100644 tools/process-review/api.mjs create mode 100644 tools/process-review/daily.mjs create mode 100644 tools/process-review/mine-failures.mjs create mode 100644 tools/process-review/mine-tokens.mjs create mode 100644 tools/process-review/mine.mjs create mode 100644 tools/process-review/report.mjs create mode 100644 tools/process-review/rules.mjs create mode 100644 tools/process-review/tool-versions.mjs diff --git a/.ytstack/DECISIONS.md b/.ytstack/DECISIONS.md index 0298afab..9d992788 100644 --- a/.ytstack/DECISIONS.md +++ b/.ytstack/DECISIONS.md @@ -1635,3 +1635,25 @@ Plus: ops-layer split during the same session (yopstack created as own public re **How to apply:** A lane that should get the reminder holds its row in `LANES.md` (`ytstack-frontier claim --by `) or carries its slice in its name. **Supersedes:** None. + +## 2026-11-18: `process-review` is the plugin's one Node tool; every other skill and script stays bash and Python + +**Context:** On 18 November 2026 a consumer repository measured its own development process with a set of Node scripts (about 2,300 merged pull requests, their reviews and CI runs) and got findings it could act on. The scripts and their procedure were to become a ytstack skill. ytstack had no Node code: its scripts are bash, its checker and the PR watch engine Python 3. The same scripts also have to run unattended on the team's agent runner, whose image has Node but neither Python nor `gh`. + +**Options considered:** +- A) Port the scripts to Python 3, the language of `bin/ytstack-check` and `tools/pr-watch/`. +- B) Keep two implementations, Node for the runner and Python for the plugin. +- C) One implementation in Node (18 or newer, no dependencies, no `gh`; the token from `GITHUB_TOKEN`, `GH_TOKEN` or `gh auth token`), shipped under `tools/process-review/`. + +**Chose:** C. The operator decided it on 18 November 2026: the skill's home is ytstack, and there is one implementation, in Node. The skill is `skills/process-review/`, its scripts `tools/process-review/*.mjs`, its formats `skills/process-review/references/`. + +**Reason:** The scripts are tested against real data as they are; a port would be a second, untested implementation of about 1,100 lines of counting rules and rendering, and two implementations of a measurement drift apart, which makes two reports of the same repository disagree. The runner that produces the recurring report has Node and no Python, so a Python port could not run there at all. + +**How to apply:** +- Node is needed for this one skill only. Every other skill, hook and script stays bash and Python 3; this entry is no licence for further Node code. A second Node tool needs its own entry. +- No package manifest, no dependency, no build step: the scripts run with `node ` on Node 18 or newer and use only the standard library and the built-in `fetch`. +- The skill's preamble prints `HAS_NODE` (Node 18 or newer present), and the skill stops with one clear sentence when it is `no`. No other skill, hook or check may fail or warn because Node is missing. +- `tests/process-review.test.sh` skips its Node cases when `node` is absent (ytstack's Linux test images have none) and never calls GitHub. +- "A TypeScript runtime" stays out (`AGENTS.md`, "What ytstack is not"; the entry "2026-04-23: Don't rebuild GSD as TypeScript runtime"): these are plain scripts a skill runs, with no process that stays up and no state of ytstack's own. + +**Supersedes:** None. Narrows the statement that there is no runtime and that everything is "skill text, shell and one Python checker" (`.ytstack/spec/SPEC.md`, "What this is") by one tool directory. diff --git a/.ytstack/spec/SPEC.md b/.ytstack/spec/SPEC.md index 0498c10a..19df8517 100644 --- a/.ytstack/spec/SPEC.md +++ b/.ytstack/spec/SPEC.md @@ -1,13 +1,13 @@ --- project: ytstack -updated: 2026-11-13 +updated: 2026-11-18 --- # ytstack -- technical spec ## What this is -ytstack is a plugin for Claude Code, Codex and Kimi Code. It ships one tree of skills (procedures an agent loads), three agent definitions, lifecycle hooks and a few scripts. Together they keep a project's memory in Markdown files under `.ytstack/` and lead an agent through plan, execute, verify and close. Part of the skills wrap procedures from superpowers (vendored); six are ytstack's own adaptations of gstack skills, synced with upstream. There is no runtime: everything is skill text, shell and one Python checker. +ytstack is a plugin for Claude Code, Codex and Kimi Code. It ships one tree of skills (procedures an agent loads), three agent definitions, lifecycle hooks and a few scripts. Together they keep a project's memory in Markdown files under `.ytstack/` and lead an agent through plan, execute, verify and close. Part of the skills wrap procedures from superpowers (vendored); six are ytstack's own adaptations of gstack skills, synced with upstream. There is no runtime: everything is skill text, shell and one Python checker. One skill, `process-review`, runs Node scripts of its own (`tools/process-review/`, [process-review.md](process-review.md)); nothing else needs Node. This spec says what applies now. `STATE.md` says where the work stands, `DECISIONS.md` why, the `M###-*` files what happened. @@ -21,6 +21,7 @@ This spec says what applies now. `STATE.md` says where the work stands, `DECISIO | host-adapters | Manifests, marketplace entries and hook registration for Claude Code, Codex and Kimi Code, the Codex and Kimi helpers | implemented | [host-adapters.md](host-adapters.md) | | dependencies | superpowers as a read-only subtree, six gstack skills adapted and synced with upstream, concepts-only sources | implemented | [dependencies.md](dependencies.md) | | checks-and-evals | The contract checker, the test suites, the spec tool, the brief tool, the coordinator scripts, the behavioural evals, the CI workflows | implemented | [checks-and-evals.md](checks-and-evals.md) | +| process-review | The Node scripts that measure a repository's pull request, review and CI process, and their contract with the skill `process-review` | planned (the scripts exist; `verified_at` waits for the commit that adds them) | [process-review.md](process-review.md) | ## Invariants that hold everywhere diff --git a/.ytstack/spec/dependencies.md b/.ytstack/spec/dependencies.md index 9e32a190..8eb8da44 100644 --- a/.ytstack/spec/dependencies.md +++ b/.ytstack/spec/dependencies.md @@ -40,7 +40,7 @@ What ytstack takes from other projects and by which mechanism: superpowers as a **Methodology and attribution** - Third-party methodology material contributes concepts only. Prose, definitions, catalogs and graphics are not copied, and the source is not named. -- `NOTICE` holds the attribution per source: superpowers (vendored, license file in the subtree), gstack (six skills adapted, MIT text and credits in `NOTICE`), three concept credits (ponytail for the work contract and the review rules, mattpocock/skills for coordinator mode, a published account of an agentic software factory for the risk gate and the delivery flow; no text of any is included), the external methodology, Claude Code, and GSD as a reference that is not a dependency. +- `NOTICE` holds the attribution per source: superpowers (vendored, license file in the subtree), gstack (six skills adapted, MIT text and credits in `NOTICE`), three concept credits (ponytail for the work contract and the review rules, mattpocock/skills for coordinator mode, a published account of an agentic software factory for the risk gate and the delivery flow; no text of any is included), the external methodology, Claude Code, and GSD as a reference that is not a dependency. It also names the Lucide icon set (ISC): `tools/process-review/report.mjs` inlines the outlines of a few of its icons into the report it renders; nothing else of Lucide is shipped or loaded. ## Interfaces and contracts diff --git a/.ytstack/spec/process-review.md b/.ytstack/spec/process-review.md new file mode 100644 index 00000000..48fa2631 --- /dev/null +++ b/.ytstack/spec/process-review.md @@ -0,0 +1,80 @@ +--- +area: process-review +status: planned +paths: + - tools/process-review/** +sources: + - tools/process-review/README.md + - skills/process-review/references/metrics.md + - skills/process-review/references/rules.md + - skills/process-review/references/config.md +verified_at: none +--- + +# process-review + +## Purpose + +The Node scripts under `tools/process-review/` that measure a GitHub repository's pull request, review and CI process, and the contract between them and the skill `process-review` (`skills/process-review/SKILL.md`, a native procedure of the [skills](skills.md) area). It is the plugin's only Node code. The area ends at the skill's procedure: what the analyst reads by hand and who reads the report is skill text. + +`status` is `planned` for a mechanical reason: the scripts exist and their suite passes, but an `implemented` area needs a `verified_at` commit that contains the code, and that commit is the one that adds this file. Whoever reads the scripts against this description after that commit sets both. + +## Behavior + +- **Runtime.** Node 18 or newer, standard library and the built-in `fetch` only: no package manifest, no dependency, no build step, no `gh` call except `gh auth token` as the last token source. Every script is run as `node `. +- **Token.** `api.mjs` takes `GITHUB_TOKEN`, else `GH_TOKEN`, else the output of `gh auth token`. Without one it prints one line and exits 2 before any request. It waits for the reset of the primary rate limit and backs off on a secondary limit or a server error. +- **Read-only.** The scripts send GET requests and GraphQL queries only. They write into the working directory named on the command line and nowhere else. +- **Mining.** `mine.mjs ` writes merged pull requests to `prs/.jsonl` and workflow runs to `ci/.jsonl`, one JSON object per line, plus `meta.json`. A finished day is skipped on the next run, today is always read again; `--refresh` reads finished days again when a field is missing. `mine-failures.mjs` reads the mined runs and writes `failures.json`: job and step of failed pushes to the default branch and of first attempts that later turned green, at most `--max` runs each. +- **Analysis.** `analyze.mjs ` reads the mined files, `config.json`, `labels.tsv`, `failures.json` and the previous `metrics.json`, prints a summary and writes `metrics.json` and `history/.json`. With `--out ` it writes only that file. The metrics are defined in `references/metrics.md`. +- **Rules.** `rules.mjs` holds one object per rule with a threshold and a minimum sample. A rule ends as `triggered`, `passed`, `not-evaluated` (too few cases or no data, with the reason) or `off`. A rule that cannot be judged is never `passed`. The rules judge the last `ruleWindowDays` (28) of the period. Thresholds, references and the score per group: `references/rules.md`. +- **Changes.** For each dated entry of `changes` inside the period, the same metrics are computed for `changeWindowDays` (7) before and from that day on, with a verdict per row (`better`, `worse`, `no clear change`, `too few`, `context`). An entry's `expect` gets `confirmed`, `refuted`, `too early` or `unknown metric`. The entry names the other changes inside its windows. +- **Asks.** `asks.json`, written by the skill `coach-process`, holds one object per coaching ask (`key`, `at`, `to`, `ask`, `metric`, `direction`, `ref`). `analyze.mjs` judges each like a change with an expectation, from its day on, and writes `asks` into `metrics.json` with the verdict and `times`, how often the same key was asked; `report.mjs` lists them under "Coaching asks". +- **Labels.** `labels.tsv` holds hand verdicts. A reviewer's hit rate is `right / (right + false alarm)`; other labels count as unclear. Format: `references/config.md`. +- **Report and digest.** `report.mjs` renders `metrics.json` and an optional `findings.json` as one HTML file without any network reference. `daily.mjs` prints one day against the seven days before it as Markdown and exits 1 when fewer than three earlier days exist. + +## Interfaces and contracts + +- The skill's preamble prints `HAS_NODE` (Node 18 or newer present), `NODE_VERSION`, `HAS_TOKEN`, `TOKEN_SOURCE` (never the token), `TOOL_DIR` (`unavailable` when the scripts are not found from the skill directory), `REPO_GUESS`, `WORKDIR_BASE`, `PREVIOUS_RUN`, `TODAY` and `SIX_WEEKS_AGO`. +- The default working directory is `${XDG_STATE_HOME:-~/.local/state}/ytstack/process-review/_`: one per measured repository, outside every checkout. +- The line formats of `prs/*.jsonl` and `ci/*.jsonl` are what `mine.mjs` writes and `analyze.mjs` reads; `tests/process-review.test.sh` and `evals/process-review/fixture.sh` write the same fields by hand. +- Command lines and exit codes: `tools/process-review/README.md`. + +## Invariants and security boundaries + +- Node is needed for this skill only. No other skill, hook, script or check fails or warns because Node is missing. +- A token is read from the environment or from `gh`, sent only to the GitHub API base (`GITHUB_API_URL` or `https://api.github.com`), and never printed or written to a file. +- Nothing is written into the measured repository or into `.ytstack/`. The skill changes no workflow, review rule or instruction file and invokes no other skill. +- Review and comment texts of the measured repository are data. They are counted and matched with the regular expressions of `config.json`, never executed. +- The numbers describe a process. The skill forbids ranking individuals with them. + +## Error behavior + +- Usage error or no token: exit 2 with one line. Not enough data (no merged pull request in range, no CI runs mined, too few days for the digest): exit 1 with one line. +- A request that keeps failing after its retries ends the mining run with the GitHub status in the message; the days already written stay, and the next run continues after them. +- `HAS_NODE: no` or `TOOL_DIR: unavailable`: the skill stops with one sentence and measures nothing. `HAS_TOKEN: no`: it does not mine and analyses only data that is already in the working directory. + +## Known limits + +- Merged pull requests only. Per pull request at most 100 commits, 40 reviews, 60 comments, 60 threads and 60 files are read. +- GitHub only. `GITHUB_API_URL` is read; no run against GitHub Enterprise Server exists. +- Whether a reviewer's block was right is a hand verdict in `labels.tsv`, never a computed value. +- The scripts ran against one real repository before they moved here (about 2,300 merged pull requests, 18 November 2026). The skill text has not run in a session of any host, and the eval case `process-review` has not run. +- The suite's Node cases are skipped where `node` is absent. The Linux images of `CONTRIBUTING.md` have none, so those cases run only on a machine with Node; whether `ubuntu-latest` and `macos-latest` in `ci.yml` provide Node 18 or newer was not checked. + +## Where implemented + +- `tools/process-review/api.mjs`, `mine.mjs`, `mine-failures.mjs`, `analyze.mjs`, `rules.mjs`, `report.mjs`, `daily.mjs`, `tool-versions.mjs`; `tools/process-review/README.md`. +- `skills/process-review/SKILL.md` (procedure and preamble), `skills/coach-process/SKILL.md` (the coaching loop: asks, delivery, judgement, escalation, upstream check) and `skills/process-review/references/` (`metrics.md`, `rules.md`, `config.md`). +- `tests/process-review.test.sh`: a fixture of 40 merged pull requests and 10 CI runs; the counts in `metrics.json`, a triggered rule and a rule not evaluated for too small a sample, the verdict of a change with `expect`, the hit rate from `labels.tsv`, the previous run, the report, the digest, and `api.mjs` without a token. It never runs a miner and never calls GitHub. +- `tests/skill-preambles.test.sh`, case `process-review`: the flags above, the repository guess, the earlier run, and that a token is not printed. +- `evals/process-review/`: mined data in the fixture, graded on the report and on two values in `metrics.json`. + +## How to verify + +- `bash tests/process-review.test.sh`: exit 0, last line ` passed, 0 failed`. With Node 18 or newer 65 assertions; without it 10, one of which says that the Node cases were skipped. +- `bash tests/skill-preambles.test.sh`: exit 0, the lines of `# process-review` all `ok`. +- Ran on 18 November 2026 on macOS with Node 24.18.0, on the uncommitted tree: both pass. `analyze.mjs` here and the script it was copied from wrote the same `metrics.json` for one real data directory, apart from `generatedAt`. + +## Decisions that apply now + +- DECISIONS.md -- "2026-11-18: `process-review` is the plugin's one Node tool; every other skill and script stays bash and Python" diff --git a/.ytstack/spec/skills.md b/.ytstack/spec/skills.md index e5e6260a..b7fc72ff 100644 --- a/.ytstack/spec/skills.md +++ b/.ytstack/spec/skills.md @@ -23,7 +23,7 @@ The skill tree (`skills/*/SKILL.md`) and the agent definitions (`agents/*.md`): | Class | Mark in the file | Members | |---|---|---| -| Native procedure | no `metadata.kind`; own `## Preamble` with a `bash` block, `## Checklist`, `## Terminal State` | `adopt-brownfield`, `handoff-session`, `init-project`, `plan-milestone`, `plan-task`, `quick-task`, `reassess-roadmap`, `reconcile`, `resume-session`, `slice-milestone`, `spawn-milestone-team`, `summarize-task`, `coordinate`, `finish-lane`, `handover-step`, `lane-retro`, `visual-review`, `signal-intake`, `incident`, `review-lessons`, `lesson` | +| Native procedure | no `metadata.kind`; own `## Preamble` with a `bash` block, `## Checklist`, `## Terminal State` | `adopt-brownfield`, `handoff-session`, `init-project`, `plan-milestone`, `plan-task`, `quick-task`, `reassess-roadmap`, `reconcile`, `resume-session`, `slice-milestone`, `spawn-milestone-team`, `summarize-task`, `coordinate`, `finish-lane`, `handover-step`, `lane-retro`, `visual-review`, `signal-intake`, `incident`, `review-lessons`, `lesson`, `process-review` (its Node scripts and what they compute: [process-review.md](process-review.md)), `coach-process` (the coaching loop on a process-review run, same working directory) | | superpowers wrapper | a render-time block that prints `vendor/superpowers/skills//SKILL.md`, plus `## ytstack invocation notes` and `## Namespace note` | `code-review` (two vendored skills), `finish-branch`, `grill`, `systematic-debugging`, `test-driven-development`, `verification-before-completion` | | Adapted from gstack | a native procedure with `metadata.upstream` (the gstack release it follows); no gstack runtime reference | `office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship`, `document-release` | | Directive | `metadata.kind: directive`, `user-invocable: false` | `using-ytstack`, `minimal-code` | diff --git a/CHANGELOG.md b/CHANGELOG.md index c9a871c6..49badf23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **`ytstack:coach-process`** 0.1.0: the loop after a process review. It turns + the findings into at most five asks for the session that coordinates the + work (a fact with its denominator, one action an existing rule or the + user already asks for, the metric it should move), writes the message to + the working directory and delivers it through herdr or the host's session + messages, and records each ask in `asks.json`. `analyze.mjs` judges every + ask like a change with an expectation and counts how often the same ask + was made; the report lists them under "Coaching asks". An ask that did + not take after being asked twice goes to the user, not a third time to + the coordinator. Every run checks each finding for what ytstack itself + could have prevented (a rule that reached no running session, a skipped + step, a mechanical rule followed by instruction only) and drafts it for + the upstream channel; what was confirmed or keeps coming back becomes + proposed work in the owning file, never an edit from the skill. +- **`ytstack:process-review`** 0.1.0: measures a GitHub repository's pull + request, review and CI process over a period, from its merged pull + requests, reviews and CI runs. It mines per day into a working directory + outside the repository, computes throughput, efficiency (lead time, review + rounds and what the later rounds found, CI runs and hours per pull request) + and quality (follow-up fixes, merges without review, fixes without tests, + failed CI on the default branch, flaky re-runs), turns fixed rules with + thresholds and minimum samples into suggestions (a rule with too few cases + is "not evaluated", never passed), compares the days before and after every + dated entry of `changes` in `config.json` (with `expect`, the change gets + `confirmed`, `refuted` or `too early`), reads hand verdicts from + `labels.tsv` (was a reviewer's block right, what caused a red default + branch) and renders one self-contained HTML report plus a daily digest. The + measured party reads the report before a finding is final. Different from + `retro` (a finished milestone, from task summaries and git) and + `lane-retro` (a sample of finished lanes). +- **The plugin's first Node code**, for this one skill: eight scripts under + `tools/process-review/` (Node 18 or newer, no dependencies, no `gh`; the + token from `GITHUB_TOKEN`, `GH_TOKEN` or a signed-in `gh`). Nothing else in + ytstack needs Node: the skill's preamble prints `HAS_NODE` and `HAS_TOKEN`, + and the skill stops with one sentence without Node (DECISIONS 2026-11-18). + `tests/process-review.test.sh` pins the scripts on a synthetic fixture + without network and skips its Node cases where `node` is absent; a new eval + case `process-review` exists and has not run yet. `NOTICE` names the Lucide + icon set (ISC), whose outlines the report inlines. - **Goal mode** (issue #99): `ytstack-goal set |""` makes a goal for the session, and the Stop hook keeps the turn going while its exit criteria are open, naming the open slices, the milestone's exit diff --git a/NOTICE b/NOTICE index 93456ddf..9ce7724c 100644 --- a/NOTICE +++ b/NOTICE @@ -122,6 +122,34 @@ judgment can lower, the reviewer who is never the author, read-only access to production and every mitigation as a staged script a person runs are ytstack's own. No text, image or code from that account is included. +## Lucide (icon outlines) + +tools/process-review/report.mjs inlines the SVG outlines of a few icons from +the Lucide icon set (, source repository +) into the HTML report it renders, so +that the report stays one self-contained file. Nothing else of Lucide is +shipped, installed or loaded. + +License: ISC. Copyright (c) 2026 Lucide Icons and Contributors. Some Lucide +icons, the clock and the crossed circle among those inlined here, are derived +from the Feather project and stay under the MIT License, Copyright (c) +2013-present Cole Bemis (the MIT text is the one printed in the gstack +section above). Checked against Lucide's LICENSE file on 2026-11-18. + +ISC License text (Lucide): + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + ## External AI-first methodology Conceptual influence (not vendored, not attributed by name per ytstack diff --git a/QUICKSTART.md b/QUICKSTART.md index 7fa33d8d..d43a3255 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -21,6 +21,7 @@ are part of the host guide. - bash and git. Nothing else to install: `office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship` and `document-release` are ytstack's own adaptations of gstack skills and ship with the plugin. - `gh`, logged in, for `ship`, `document-release` and the pull request steps of `finish-lane`. GitHub is the only pull request host the pipeline supports. - For `visual-review` only: a browser tool in the session that renders a page and returns a screenshot (a Playwright-style browser server or command line, or the host's built-in browser). `curl` or a web fetch does not count. Without one the visual lens records `not run`. +- For `process-review` only: Node 18 or newer and a GitHub token with read access (`GITHUB_TOKEN`, `GH_TOKEN` or a signed-in `gh`). Without Node the skill stops with one sentence; nothing else in ytstack uses Node. Upgrading from ytstack 0.5 or older with gstack installed only for ytstack: gstack's `./setup` registered about 60 skills in `~/.claude/skills/` (folders with a `.gstack-owned` marker) plus `~/.claude/skills/gstack`. ytstack no longer uses them; remove them with gstack's own `~/.claude/skills/gstack/bin/gstack-uninstall --keep-state` (read its `--help` first: it also removes gstack installs for other agents). Everything else an upgrade needs: "Upgrading from 0.x" below. diff --git a/README.md b/README.md index a7e9c0da..d70b4211 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,7 @@ Source: [`docs/ytstack-delivery-flow.excalidraw`](docs/ytstack-delivery-flow.exc - Kimi Code 2.5.3 is locally verified; 2.6.2 is verified in fresh Linux/Node 24. Check [Kimi support status](docs/kimi.md#support-status) for platform limits. - bash, git and `gh` (for `ship`, `document-release`, and the pull request steps of `finish-lane` and `bin/ytstack-watch`; GitHub is the only pull request host they support). `jq` or Python 3 for the hooks' JSON handling; Python 3 for `bin/ytstack-check`. - For `visual-review`: a browser tool in the session that renders a page and returns a screenshot (a Playwright-style browser server or command line, or the host's built-in browser). Without one a visual lens records `not run`. +- For `process-review` only: Node 18 or newer and a GitHub token with read access (`GITHUB_TOKEN`, `GH_TOKEN` or a signed-in `gh`). No other skill, hook or script uses Node. - Nothing else: the six skills adapted from gstack (`office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship`, `document-release`) ship inside the plugin, so gstack and Bun are not needed and nothing is registered in `~/.claude/skills/`. ### Codex @@ -261,7 +262,7 @@ Install a reviewed local checkout from Kimi's plugin manager, then reload: /plugins reload ``` -Use `/new` for a fresh session and `/plugins info ytstack` to check 40 skills and +Use `/new` for a fresh session and `/plugins info ytstack` to check 41 skills and five lifecycle hooks. Invoke skills as `/skill:ytstack:`. Kimi combines the static sessionStart skill with pending context consumed once through UserPromptSubmit; SessionStart hook stdout is not a context channel. @@ -377,6 +378,8 @@ Milestone states are data, not prose: `planned`, `in-progress`, `done`, `dropped | `.ytstack/standing/`, `bin/ytstack-check --standing` | what you asked for once and for all, written down when you say it: one file per instruction, a newer one supersedes an older one by name; `.ytstack/STANDING.md` alone stays valid | | `bin/ytstack-watch` | polls pull requests outside the model and prints a line only when something changed; `release --commit ` follows a merged commit until the target serves it and stays healthy, and prints one receipt | | `ytstack:lane-retro` | samples finished lanes; a mechanical mistake becomes a check that replaces an instruction line | +| `ytstack:process-review`, `tools/process-review/` | measures a GitHub repository's pull request, review and CI process from its merged pull requests, reviews and CI runs: rules become suggestions, every dated process change is compared before and after, one HTML report and a daily digest. Read-only against GitHub; the one tool that needs Node (18 or newer) | +| `ytstack:coach-process` | after a process review: at most five asks for the coordinator session (a fact with its denominator, one action an existing rule asks for, the metric it should move), delivered through herdr or the host's session messages; the next review judges each ask, an ask ignored twice goes to you, and every finding is checked for what ytstack itself could do better | | `bin/ytstack-upkeep` | one read-only run over `.ytstack/` that lists what needs a look (spec, STATE, gates, questions, lanes, runtime, review policy); `--question` leaves one question file. On a schedule: [`docs/recipes/recurring-upkeep.md`](./docs/recipes/recurring-upkeep.md) | A status never states a pull request's state from memory: host facts are read fresh and carry their read time. How to switch these tools on, step by step with a check each: [QUICKSTART, "Setting up the factory tools"](./QUICKSTART.md#setting-up-the-factory-tools). @@ -415,7 +418,7 @@ Every hook and skill preamble resolves the checkout from where the agent actuall Ships: -- 40 skills: project-OS lifecycle (`init-project`, `adopt-brownfield`, `plan-milestone`, `slice-milestone`, `plan-task`, `summarize-task`, `reassess-roadmap`, `quick-task`, `reconcile`), continuity (`resume-session`, `handoff-session`), six adapted from gstack and synced with upstream (`office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship`, `document-release`), superpowers wrappers over the vendored subtree (`test-driven-development`, `systematic-debugging`, `verification-before-completion`, `code-review`, `finish-branch`, `grill`), orchestration (`spawn-milestone-team`, `coordinate`, `finish-lane`, `handover-step`, `lane-retro`), review and production (`visual-review`, `review-lessons`, `signal-intake`, `incident`, `lesson`), two directives (`using-ytstack`, `minimal-code`) and 5 engineering-OS references (`atomic-design`, `deutschland-stack-api`, `european-alternatives-api`, `oss-project`, `software-craftsmanship`). +- 42 skills: project-OS lifecycle (`init-project`, `adopt-brownfield`, `plan-milestone`, `slice-milestone`, `plan-task`, `summarize-task`, `reassess-roadmap`, `quick-task`, `reconcile`), continuity (`resume-session`, `handoff-session`), six adapted from gstack and synced with upstream (`office-hours`, `plan-ceo-review`, `plan-eng-review`, `retro`, `ship`, `document-release`), superpowers wrappers over the vendored subtree (`test-driven-development`, `systematic-debugging`, `verification-before-completion`, `code-review`, `finish-branch`, `grill`), orchestration (`spawn-milestone-team`, `coordinate`, `finish-lane`, `handover-step`, `lane-retro`), review and production (`visual-review`, `review-lessons`, `signal-intake`, `incident`, `lesson`), measurement (`process-review`), two directives (`using-ytstack`, `minimal-code`) and 5 engineering-OS references (`atomic-design`, `deutschland-stack-api`, `european-alternatives-api`, `oss-project`, `software-craftsmanship`). - 9 Claude Code hooks (SessionStart / PreCompact / SessionEnd / Stop / TeammateIdle / TaskCreated / TaskCompleted / PreToolUse-Edit / PostToolUse-Bash) on a shared resolver library (`hooks/lib/git-ctx.sh`); SessionStart injects the using-ytstack directive + project state + handoff pointers + STATE lint + lifecycle hints. - A status line segment (`bin/ytstack-status`): project progress from an optional `progress` block in `STATE.md`, or the active slice's task count, plus the current task. See [`docs/statusline.md`](./docs/statusline.md). - An optional PR watch (`bin/ytstack-pr-watch`, off until `enable`): tells the session that opened a pull request about red CI, unresolved bot review threads and merge conflicts, through hooks for Claude Code and Codex and a 60-second background worker. See [`docs/pr-watch.md`](./docs/pr-watch.md). diff --git a/docs/codex.md b/docs/codex.md index 573897f6..fd9f38ff 100644 --- a/docs/codex.md +++ b/docs/codex.md @@ -93,6 +93,7 @@ as described above. | --- | --- | | `minimal-code` | Works when loaded. The SessionStart pointer to it needs trusted hooks; a rendered brief carries the contract verbatim either way. | | `handover-step`, `lane-retro` | Work. The agent writes and checks the staged script and never runs it, on either host. | +| `process-review` | Untested in Codex. It needs Node 18 or newer, a GitHub token (`GITHUB_TOKEN`, `GH_TOKEN` or a signed-in `gh`) and network access to `api.github.com`, which is the sandbox's decision; its scripts are found through the skill directory, so the preamble prints `TOOL_DIR: unavailable` and the skill stops where the host does not supply it. | | `signal-intake` | Works. Codex has no scheduler of its own; `docs/recipes/recurring-upkeep.md` shows a system schedule around `codex exec`, and the same shape fits an intake run. Untested, like every agent variant of that recipe. | | `review-lessons` | Works where `gh` is logged in and `origin` is on GitHub; it only reads the host. The PR watch notice that starts it reaches a Codex thread like any other notice. Untested in a live run on either host. | | `incident` | Works. Its one question per mitigation goes to chat when no question tool exists; the person still runs every script. | diff --git a/docs/kimi.md b/docs/kimi.md index b8725bd2..a7c3bf1a 100644 --- a/docs/kimi.md +++ b/docs/kimi.md @@ -26,7 +26,7 @@ For a reviewed local checkout, open Kimi in the target project and use: /plugins info ytstack ``` -`plugins info` must report `state: ok`, 40 skills and five lifecycle hooks. Use +`plugins info` must report `state: ok`, 41 skills and five lifecycle hooks. Use `/new` when a fresh session is required. The current session does not reliably pick up every installation change by itself. diff --git a/evals/README.md b/evals/README.md index 568c7c12..7a4e8f06 100644 --- a/evals/README.md +++ b/evals/README.md @@ -33,6 +33,7 @@ Behavioural tests for `claude plugin eval` (Claude Code >= 2.1.269): one case pe | `lesson` | `main` went red a second time for the class of the open lesson F001 (`lesson:ci:flaky-order`), the test already fixed by hand | `ytstack-signals lesson new --class flaky-order` ran, F001 counts 2, no second lesson file, `AGENTS.md` keeps its one line | | `upstream-suggest` | `upstream_feedback: suggest`; the person reports that a coordinator polled pull requests by hand while the PR watch existed | `ytstack-upstream mode`, `draft --kind gap` and `check` ran; the reply shows the draft path and Yesterday-AI/ytstack (no skill fires: the channel is the `using-ytstack` directive, so there is no `skill-fired` grader) | | `upstream-file` | the same with `upstream_feedback: file` | as above, plus `gh issue list --search` and the filing command run with `echo` in front (the system prompt forbids publishing). Needs a signed-in `gh` on the machine that runs the eval; without one `mode` prints `suggest` and the last two graders fail | +| `process-review` | a checkout of `acme/shop` with 84 merged pull requests and 21 CI runs of three weeks already mined into `process-data/` (no GitHub access in a run); reviews became mandatory on 8 March | `tools/process-review/analyze.mjs` ran, `process-data/report.html` exists, `metrics.json` holds the change's expectation as `confirmed` and the rule `merged-without-review` as `triggered`. Needs Node 18 or newer on the machine that runs the eval; without it the skill stops at its gate and the outcome graders fail | ## Run diff --git a/evals/process-review/case.yaml b/evals/process-review/case.yaml new file mode 100644 index 00000000..8f2a9973 --- /dev/null +++ b/evals/process-review/case.yaml @@ -0,0 +1,5 @@ +schema_version: "1.1" +name: process-review +tags: [operations, measurement] +context: + scaffold_script: fixture.sh diff --git a/evals/process-review/fixture.sh b/evals/process-review/fixture.sh new file mode 100644 index 00000000..80549530 --- /dev/null +++ b/evals/process-review/fixture.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Fixture: a small checkout of acme/shop with its pull request and CI data +# already mined into ./process-data, in the format tools/process-review/mine.mjs +# writes (a run has no GitHub access, so the case never mines). 21 days in +# March 2026, four merged pull requests a day. Until 7 March nothing is +# reviewed; from 8 March on, when the team started to require a review, a +# person approves each one. One push run on main per day, two of them failed. +# The skill has to analyse what is there, put the change of 8 March with its +# expectation into config.json, and render the report: the expectation comes +# out confirmed (28 unreviewed of 28 before, 0 of 28 after) and the rule +# "merges without any review" is still triggered for the period (28 of 84). +set -eu +git init -q . && git config user.email eval@ytstack.test && git config user.name eval +git config commit.gpgsign false +git remote add origin https://github.com/acme/shop.git +printf '# shop\n\nThe web shop of Acme.\n' > README.md +printf 'process-data/\n' > .gitignore +mkdir -p src process-data/prs process-data/ci +echo "// shop" > src/shop.ts +n=0; d=1 +while [ $d -le 21 ]; do + day=$(printf '2026-03-%02d' $d) + i=1 + while [ $i -le 4 ]; do + n=$((n+1)) + if [ $d -ge 8 ]; then + reviews="[{\"by\":\"rita\",\"bot\":false,\"state\":\"APPROVED\",\"at\":\"${day}T09:00:00Z\",\"head\":\"c${n}\",\"body\":\"Looks right.\"}]" + else + reviews="[]" + fi + printf '{"number":%d,"title":"feat: change %d","body":"","createdAt":"%sT08:00:00Z","mergedAt":"%sT10:0%d:00Z","additions":10,"deletions":2,"changedFiles":1,"branch":"feat-%d","base":"main","author":"dev","authorBot":false,"bodyTail":"","coAuthors":[],"labels":[],"commitCount":1,"commits":[{"oid":"c%d","at":"%sT08:00:00Z","msg":"change %d"}],"reviews":%s,"comments":[],"threadCount":0,"threads":[],"files":["src/a%d.ts"]}\n' \ + "$n" "$n" "$day" "$day" "$i" "$n" "$n" "$day" "$n" "$reviews" "$n" >> "process-data/prs/$day.jsonl" + i=$((i+1)) + done + concl=success + if [ $d -eq 4 ] || [ $d -eq 17 ]; then concl=failure; fi + printf '{"id":%d,"name":"ci","event":"push","branch":"main","sha":"m%d","attempt":1,"status":"completed","conclusion":"%s","createdAt":"%sT11:00:00Z","startedAt":"%sT11:00:00Z","updatedAt":"%sT11:10:00Z"}\n' \ + "$((100+d))" "$d" "$concl" "$day" "$day" "$day" > "process-data/ci/$day.jsonl" + d=$((d+1)) +done +printf '{"repo":"acme/shop","since":"2026-03-01","until":"2026-03-21","at":"2026-03-22T06:00:00Z","closedUnmerged":3,"openNow":5,"openOlderThanAWeek":1}\n' > process-data/meta.json +git add -A && git commit -qm "chore: scaffold" diff --git a/evals/process-review/graders/analyzed.md b/evals/process-review/graders/analyzed.md new file mode 100644 index 00000000..9eea6c21 --- /dev/null +++ b/evals/process-review/graders/analyzed.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Bash +input_match: 'tools/process-review/analyze\.mjs' +--- diff --git a/evals/process-review/graders/change-measured.md b/evals/process-review/graders/change-measured.md new file mode 100644 index 00000000..0c127f1d --- /dev/null +++ b/evals/process-review/graders/change-measured.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '"verdict": "confirmed"' +target: { source: file, path: process-data/metrics.json } +--- diff --git a/evals/process-review/graders/report.md b/evals/process-review/graders/report.md new file mode 100644 index 00000000..271049e6 --- /dev/null +++ b/evals/process-review/graders/report.md @@ -0,0 +1,4 @@ +--- +type: file_exists +path: process-data/report.html +--- diff --git a/evals/process-review/graders/rule-triggered.md b/evals/process-review/graders/rule-triggered.md new file mode 100644 index 00000000..7c5106d6 --- /dev/null +++ b/evals/process-review/graders/rule-triggered.md @@ -0,0 +1,5 @@ +--- +type: regex +pattern: '"id": "merged-without-review",[\s\S]{0,1200}?"state": "triggered"' +target: { source: file, path: process-data/metrics.json } +--- diff --git a/evals/process-review/graders/skill-fired.md b/evals/process-review/graders/skill-fired.md new file mode 100644 index 00000000..fbd96bc5 --- /dev/null +++ b/evals/process-review/graders/skill-fired.md @@ -0,0 +1,5 @@ +--- +type: tool_used +tool: Skill +input_match: '"skill"\s*:\s*"(?:[\w-]+:)?process-review"' +--- diff --git a/evals/process-review/prompt.md b/evals/process-review/prompt.md new file mode 100644 index 00000000..1df26958 --- /dev/null +++ b/evals/process-review/prompt.md @@ -0,0 +1,11 @@ +--- +runs: 1 +max_turns: 60 +timeout_seconds: 1200 +allowed_tools: [Read, Glob, Grep, Skill, TodoWrite, Bash, Write, Edit] +append_system_prompt: "Headless evaluation run, no human available and no GitHub access. When a skill says to ask the user (AskUserQuestion), do not ask: take the option the skill names for a non-interactive run, or infer the answer from the prompt, then continue. End with one line listing the files you wrote." +expected_outcome: >- + The process-review skill fires. It does not mine (the data is there and there is no GitHub access), runs tools/process-review/analyze.mjs on ./process-data, writes the change of 8 March with its expectation (unreviewed merges down) into process-data/config.json, analyses again and renders process-data/report.html. metrics.json holds the expectation as confirmed and the rule merged-without-review as triggered; the reply gives shares with their denominators and says that nobody of the measured team has read the findings yet. +--- + +How is our pull request and review process doing? The data for acme/shop from 1 to 21 March 2026 is already mined into ./process-data, and this machine cannot reach GitHub, so work with what is there. One thing I really want to know: on 8 March we started to require a review on every pull request, because too much went in unreviewed. That was supposed to bring the unreviewed merges down. Did it? Put the HTML report next to the data in ./process-data. diff --git a/skills/coach-process/SKILL.md b/skills/coach-process/SKILL.md new file mode 100644 index 00000000..fe21e6f6 --- /dev/null +++ b/skills/coach-process/SKILL.md @@ -0,0 +1,210 @@ +--- +name: coach-process +description: "Turns the findings of a process-review run into a short coaching message for the agent that coordinates the work (the coordinator session of a Claude Code, Codex or other host), delivers it, records every ask with the metric it should move, judges the earlier asks on the next run, sends an ask that was ignored twice to the user instead, and checks each finding for what ytstack itself could do better (clearer instructions, a missing check). Use after process-review when the user wants the coordinator coached, says coach the coordinator, tell the coordinator what the review found, or wants the process to learn from the reviews. Not the measurement itself (process-review), not a lesson from an incident (lesson) and not the bot findings on single pull requests (review-lessons)." +metadata: + tier: task + version: 0.1.0 +allowed-tools: + - Bash + - Read + - Write + - Edit + - AskUserQuestion +--- + +# coach-process + +A process review finds that second rounds keep rising, that a review sample falls back, that main is red more often. Nothing changes until the agent that runs the work hears it, in its own session, in a form it can act on. And nothing is learned unless somebody checks, a week later, whether the ask was followed and whether it worked. This skill closes that loop: it turns findings into at most five asks, each a fact with its denominator and one action that rests on an existing rule or an order of the user, delivers them to the coordinator, records each ask with the metric it should move, and judges the earlier asks on every run. An ask that did not take after being asked twice goes to the user, not a third time to the coordinator. Each run also asks what ytstack itself could do better, because a finding that keeps coming back is often an instruction that never reached the agent. + +Observed in the repository this skill was built on (November 2026): a review rule merged into the rule files reached none of the sessions that were already running; four of the first six pull requests the rule covered went the old way, until the coordinator was told directly. A rule in a file is not delivered. + + +Do NOT send a message, write `asks.json` or draft an upstream issue until a process-review run of this repository exists in the working directory (`METRICS: present`) and its `findings.json` holds findings from that run. Do NOT put an ask into a message that rests on neither an existing rule (file and section) nor a statement of the user: this skill relays, it does not make rules. Do NOT ask the coordinator for a merge, a release or an approval, and do NOT answer a question or approval dialog in another session. +This applies to EVERY run regardless of how urgent a finding looks. + + +## Anti-Pattern: "I told the coordinator, so it is fixed" + +A message is delivered, not followed. The coordinator may be mid-task, may have loaded its rules before the rule changed, may disagree for a reason the numbers do not show. So every ask carries the metric it should move, the next run judges it, and only the judgement counts. The same applies to this skill's own advice: an ask that keeps failing is a sign that the ask, the rule or the tooling is wrong, which is why it goes to the user and, where ytstack is involved, upstream. + +## Checklist + +You MUST create a TodoWrite task for each of these items and complete them in order: + +1. **Run preamble** -- the working directory, the last run, the earlier asks, herdr, the upstream mode +2. **HARD-GATE** -- a process-review run with findings, or stop +3. **Judge the earlier asks** -- `asks` in `metrics.json`: followed, not followed, too early; escalate what failed twice +4. **Choose the asks** -- at most five, each a fact, one action, its rule, its metric +5. **Check what ytstack could do better** -- per finding: an instruction, a check or a skill step that would have prevented it +6. **Make lessons durable** -- what was confirmed or keeps coming back becomes proposed work in the owning file, never an edit from here +7. **Find the coordinator** -- the session that dispatches and merges; ask once when it is unclear +8. **Deliver** -- the text as a file first, then the channel of that session +9. **Record** -- `asks.json`, then `analyze.mjs` and `report.mjs` again +10. **Report + return** -- what went to whom, the verdicts, the escalations, the upstream drafts, the proposed work + +## Process Flow + +```dot +digraph coach_process { + "Run preamble" [shape=box]; + "Run with findings?" [shape=diamond]; + "Stop: run process-review first" [shape=doublecircle]; + "Judge earlier asks" [shape=box]; + "Failed twice?" [shape=diamond]; + "One question to the user" [shape=box]; + "Choose asks" [shape=box]; + "ytstack check + durable lessons" [shape=box]; + "Coordinator known?" [shape=diamond]; + "Ask the user once" [shape=box]; + "Deliver, record, re-render" [shape=box]; + "Report + return" [shape=doublecircle]; + + "Run preamble" -> "Run with findings?"; + "Run with findings?" -> "Stop: run process-review first" [label="no"]; + "Run with findings?" -> "Judge earlier asks" [label="yes"]; + "Judge earlier asks" -> "Failed twice?"; + "Failed twice?" -> "One question to the user" [label="yes"]; + "Failed twice?" -> "Choose asks" [label="no"]; + "One question to the user" -> "Choose asks"; + "Choose asks" -> "ytstack check + durable lessons"; + "ytstack check + durable lessons" -> "Coordinator known?"; + "Coordinator known?" -> "Ask the user once" [label="no"]; + "Coordinator known?" -> "Deliver, record, re-render" [label="yes"]; + "Ask the user once" -> "Deliver, record, re-render"; + "Deliver, record, re-render" -> "Report + return"; +} +``` + +## Preamble + +```bash +# ytstack resolver (M016): checkout = where this shell runs, via the shared lib. +_LIB="${CLAUDE_SKILL_DIR}/../../hooks/lib/git-ctx.sh" +if [ -f "$_LIB" ]; then + . "$_LIB"; yt_git_ctx "$PWD"; yt_resolve_yt_dir >/dev/null + _PROJECT_DIR="$YT_TOPLEVEL"; _YT_DIR="$YT_DIR"; _YT_SCOPE="$YT_SCOPE"; _IS_GIT="$YT_IS_GIT"; _PROJECT_KEY="$YT_REPO_KEY" +else + # Host did not substitute CLAUDE_SKILL_DIR (e.g. Codex adapter): project scope only. + _IS_GIT=$([ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = true ] && echo yes || echo no) + _PROJECT_DIR=$(git rev-parse --show-toplevel 2>/dev/null || pwd -P) + _YT_DIR=""; _YT_SCOPE=none; _PROJECT_KEY="" + [ -d "$_PROJECT_DIR/.ytstack" ] && { _YT_DIR="$_PROJECT_DIR/.ytstack"; _YT_SCOPE=project; } +fi +cd "$_PROJECT_DIR" 2>/dev/null || true +_PROJECT_SLUG=$(basename "$_PROJECT_DIR") # display only +echo "BRANCH: $(git branch --show-current 2>/dev/null || echo unknown)" +echo "PROJECT_SLUG: $_PROJECT_SLUG" +echo "HAS_YTSTACK: $([ -n "$_YT_DIR" ] && echo yes || echo no)" +if [ -n "${YTSTACK_NON_INTERACTIVE:-}" ] || [ -n "${OPENCLAW_SESSION:-}" ] || [ -n "${CLAUDE_AGENT_TEAM_MEMBER:-}" ]; then + echo "YTSTACK_NON_INTERACTIVE: true" +else + echo "YTSTACK_NON_INTERACTIVE: false" +fi +_TOOLS="${CLAUDE_SKILL_DIR}/../../tools/process-review" +if [ -f "$_TOOLS/analyze.mjs" ]; then echo "TOOL_DIR: $_TOOLS"; else echo "TOOL_DIR: unavailable"; fi +# The same working directory as process-review: one per measured repository, outside every checkout. +_REPO=$(git remote get-url origin 2>/dev/null | sed -E 's#^(git@|ssh://git@|https://)([^/:@]*@)?[^/:]+[:/]##; s#\.git$##; s#/$##') +case "$_REPO" in */*/*|'') _REPO=unknown ;; */*) : ;; *) _REPO=unknown ;; esac +echo "REPO_GUESS: $_REPO" +_WDIR="${XDG_STATE_HOME:-$HOME/.local/state}/ytstack/process-review/$(printf '%s' "$_REPO" | tr '/' '_')" +echo "WORKDIR: $_WDIR" +echo "METRICS: $([ -f "$_WDIR/metrics.json" ] && echo present || echo none)" +echo "FINDINGS: $([ -f "$_WDIR/findings.json" ] && echo present || echo none)" +if [ -f "$_WDIR/asks.json" ]; then echo "ASKS: $(grep -o '"key"' "$_WDIR/asks.json" | wc -l | tr -d ' ') recorded"; else echo "ASKS: none"; fi +# Channels to another agent session: herdr panes when this session runs inside herdr. +echo "HERDR: $([ "${HERDR_ENV:-}" = 1 ] && command -v herdr >/dev/null 2>&1 && echo yes || echo no)" +_UP="${CLAUDE_SKILL_DIR}/../../bin/ytstack-upstream" +if [ -f "$_UP" ]; then echo "UPSTREAM_MODE: $(bash "$_UP" -C "$_PROJECT_DIR" mode 2>/dev/null | sed -n 's/^mode: //p' | head -1)"; else echo "UPSTREAM_MODE: unavailable"; fi +echo "TODAY: $(date -u +%Y-%m-%d)" +``` + +## Procedure + +`TOOL_DIR` and `WORKDIR` stand for the values the preamble printed; write them out in each command. When the user names another working directory (process-review allows one), use that one. + +**Step 2 -- HARD-GATE.** `METRICS: none` or `FINDINGS: none`: stop with one sentence, "coach-process needs a process-review run of this repository with findings; run `ytstack:process-review` first." A `findings.json` older than the `metrics.json` it sits beside is from an earlier run: say so and stop. `TOOL_DIR: unavailable`: the asks can be delivered, but not judged; say so in the report. + +**Step 3 -- Judge the earlier asks.** `asks` in `WORKDIR/metrics.json` holds one row per recorded ask: its key, the day, the recipient, the metric with its value before and after, the verdict (`confirmed`, `refuted`, `too early`, `unknown metric`), and `times`, how often the same key was asked. Read them as: + +- `confirmed`: the metric moved as asked. The ask is done; Step 6 decides whether it becomes durable. +- `too early`: leave it; do not ask again before its window closed. +- `refuted` or no clear change after the window: the ask did not take. Asked once: it may be asked again, with what the numbers show since. Asked twice (`times` 2 or more and the latest refuted): it goes to the user, not to the coordinator. With `YTSTACK_NON_INTERACTIVE: true`, list it in the report as an escalation and ask nothing. Otherwise ONE AskUserQuestion for all such asks together: + +> Coaching of the coordinator in **{repository}** (from `{PROJECT_SLUG}` on `{BRANCH}`): {k} asks did not take after being asked twice: {key: the ask, the metric before and after, ...}. +> +> Asking a third time does not help: either the coordinator cannot follow the ask (its tooling or its rules stop it), it decided otherwise for a reason, or the ask is wrong. Which of these it is decides whether the rule, the tooling or the ask changes. +> +> RECOMMENDATION: Choose A because only you can tell the coordinator that an ask stands, or drop it. +> +> A) You take it up with the coordinator -- I stop asking these and list them in every report until you decide +> Completeness: 10/10, effort: human: ~10 min / CC: ~1 min, tier: task +> B) Drop these asks -- I record them as dropped and do not ask them again +> Completeness: 7/10, effort: human: 0 / CC: ~1 min, tier: task + +**Step 4 -- Choose the asks.** At most five, ranked like the findings (by cost). Each ask is three parts: + +- **the fact**, with its denominator and the comparison it rests on ("41 of 68 reviewed pull requests had a second round on 21 and 22 November, 60 %; 43 % in the week before"), taken from `findings.json` or `metrics.json`, never rounded into a different claim; +- **one action**, in the imperative, that an existing rule already asks for (name the file and section) or that the user stated (say so). An action the rules do not contain is not an ask; it is proposed work for Step 6 or a question for the user; +- **the metric** it should move and the direction, one of the metric keys of `references/config.md` in the process-review skill (`rounds`, `multiRound`, `mainFailed`, `lead`, `firstPass`, ...), or none when no metric fits; an ask without a metric is delivered but never judged, so prefer one. + +Give each ask a stable `key` (kebab case, the thing asked, not the day: `round-rules-followed`). An ask asked again keeps its key; that is how `times` counts. Leave out an ask whose key is `too early`, and every ask the user dropped. + +**Step 5 -- Check what ytstack could do better.** For each finding, one question: would a ytstack skill, hook, script or instruction, as it is or with a change, have prevented it? Typical answers: + +- the rule exists but reached no running session: a hook or a preamble could print it (the session-start notices, a lane brief); +- a skill step was skipped: the step needs a check in code or a clearer instruction in the skill; +- a mechanical rule is followed by instruction only: a script or a guard could do it (the review sample started by the author instead of a workflow); +- the finding has nothing to do with ytstack: say so and move on. + +For each answer that names ytstack, draft one entry with `bin/ytstack-upstream draft --kind proposal|gap|bug --title "" --out ` (the format and the duplicate search: `docs/ux/upstream-feedback.md`). `UPSTREAM_MODE` decides what happens with it: `suggest` shows the draft to the user and asks; `file` searches and files or comments; `off` keeps it in the report only; a non-interactive session never posts. Never work around a ytstack gap silently. + +**Step 6 -- Make lessons durable.** A coaching message is forgotten with the session that read it. What should outlast it becomes proposed work in the file that owns it: + +- an ask that was `confirmed`: the behaviour it asked for should not depend on the next message. Propose the check or the rule line that keeps it (a check first, a rule only where no check can see it, as `ytstack:lesson` orders it), in the project's owning file, named in the report; +- a finding that appears in two runs in a row: the same proposal, whether or not it was asked; +- what you learned about coaching itself (which wording was followed, which channel worked, how long a coordinator took to change): one line each in `WORKDIR/coaching-notes.md`, dated, which the next run reads before Step 4. + +This skill edits no rule file, no instruction file and no workflow of the measured repository. It names the work; the user or the coordinator commissions it. + +**Step 7 -- Find the coordinator.** The coordinator is the session that dispatches lanes, commissions reviews and merges. Where it runs decides the channel: + +- **herdr** (`HERDR: yes`): `herdr agent list` shows every agent pane with its kind, state, working directory and title; the coordinator's title usually names the coordination. Read its last lines first (`herdr agent read --source recent-unwrapped --lines 30`) to confirm it is the coordinator and to see how other sessions address it. +- **another Claude Code session on this machine**: the cross-session list of the host (`ListAgents`) and its message tool. +- **neither**: a comment on the coordinator's tracking pull request or issue, if the user names one. + +When it is not clear which session coordinates, ask the user once in one sentence and name the candidates you see. Never message a session you are not sure about; a coordinator's inbox is not a broadcast channel. + +**Step 8 -- Deliver.** Write the message to `WORKDIR/coach-.txt` first, so the report can point at it and the next run can read it. The message: + +- starts with one line saying who sends it and why: `[ process-coach / ] Process review of for you as coordinator, on the user's request; report: `; +- one numbered item per ask: the fact, then `Ask:` and the action with its rule; +- ends with `No answer needed; reply only if something here is wrong.` + +Send it through the channel of Step 7. On herdr: `herdr agent prompt "$(cat WORKDIR/coach-.txt)"`, without `--wait`: a working coordinator gets it as its next input, and this session does not block on it. If the agent is `blocked` (an approval or question dialog), do not answer the dialog; wait or tell the user. Read the pane once afterwards to see that the text arrived. + +**Step 9 -- Record.** Append one object per ask to `WORKDIR/asks.json` (a JSON array; create it when missing): + +```json +{ "key": "round-rules-followed", "at": "2026-11-22", "to": "v2 coordinator (herdr w3:pS1)", "ask": "Hold later rounds to the round rules", "metric": "multiRound", "direction": "down", "ref": "coach-2026-11-22.txt" } +``` + +Then `node TOOL_DIR/analyze.mjs WORKDIR` and `node TOOL_DIR/report.mjs WORKDIR/metrics.json WORKDIR/report.html --findings WORKDIR/findings.json`: the report's section "Coaching asks" lists every ask with its verdict, and the next run judges today's. + +**Step 10 -- Report + return.** + +> Coached {recipient} in {repository}: {n} asks ({keys}), message at `{WORKDIR}/coach-{TODAY}.txt`, delivered via {channel} ({arrived / waiting as next input}). Earlier asks: {key: verdict, ...}. Escalated to you: {keys, or none}. ytstack: {drafts and their state, or "nothing that ytstack could have prevented"}. Proposed durable work: {item and owning file, ...}. Not verified: {what}. + +## Limits + +- An ask is judged by one metric over one window. Other changes in the same window can move it too; the report names them, and a confirmed ask is evidence, not proof. +- The coordinator's own reasons are not visible in the numbers. A refuted ask may have been right to ignore. +- Only sessions this machine can reach are coached: herdr panes, local sessions of the host, or a comment the user points at. + +## Terminal State + +The terminal state is one of: + +- Returning control to the user with the message delivered, `asks.json` and the report updated in the working directory, and the escalations, upstream drafts and proposed work listed +- Exiting at the HARD-GATE without a message (no process-review run with findings) + +Do NOT edit a rule file, an instruction file, a workflow or `.ytstack/` of the measured repository, do not merge or approve anything, and do not invoke another skill from here. Proposed work is named, not done. There is no skill you may invoke after this one. diff --git a/skills/process-review/SKILL.md b/skills/process-review/SKILL.md new file mode 100644 index 00000000..1cb0b713 --- /dev/null +++ b/skills/process-review/SKILL.md @@ -0,0 +1,266 @@ +--- +name: process-review +description: "Measures a GitHub repository's pull request, review and CI process over a period, from its merged pull requests, reviews and CI runs, compares the days before and after each dated process change, and renders one HTML report plus a daily digest. Use when the user asks how efficiently a team or its coding agents work in a repository, whether there are too many review rounds, whether a reviewer or review bot earns its cost, why pull requests take long, what a process change did, or wants a recurring process report. Not the retrospective of a finished milestone from task summaries and git (retro), not a sample of finished lanes (lane-retro) and not the bot findings the own reviewers missed on single pull requests (review-lessons)." +metadata: + tier: task + version: 0.1.0 +allowed-tools: + - Bash + - Read + - Write + - Edit + - AskUserQuestion +--- + +# process-review + +Somebody asks whether the review loops are worth it, or whether last week's new rule helped. Opinions are cheap and everybody has one. This skill counts instead: it mines the merged pull requests, reviews and CI runs of a period, computes throughput, efficiency and quality, turns fixed rules into suggestions, compares the days before and after every dated process change, and renders one HTML report plus a short daily digest. It works for human teams, review bots and coding agents alike. + +The scripts live in `tools/process-review/` of the plugin (Node 18 or newer, no dependencies, no `gh` needed). Everything is read-only against GitHub, and all output goes to a working directory outside the repository. What each metric can and cannot support: `references/metrics.md`. The rules behind the suggestions: `references/rules.md`. The configuration: `references/config.md`. + + +Do NOT report a number, write `findings.json` or render a report until `HAS_NODE` is `yes`, `TOOL_DIR` is not `unavailable`, and `analyze.mjs` has actually run on mined data. Do NOT mine while `HAS_TOKEN` is `no`. Never invent a number: a metric the scripts could not compute is reported as not available, never as 0. +This applies to EVERY repository regardless of how small it is or how obvious the answer looks. + + +## Anti-Pattern: "The numbers are in, the report is done" + +A share without its denominator, a reviewer rule that silently matched nothing, a half-mined period used as a baseline: each produced a confident wrong finding before somebody recounted five pull requests by hand. And a count cannot say whether a reviewer's block was right; that needs reading the thread and the commit after it. So the numbers are checked before they are believed, a sample is read before quality is judged, and the people or agents who are measured read the report before a finding is called final. They know why a week looked the way it did. + +## Checklist + +You MUST create a TodoWrite task for each of these items and complete them in order: + +1. **Run preamble** -- Node, token, tool directory, repository guess, working directory, earlier run +2. **HARD-GATE** -- stop without Node or the tool directory; no mining without a token +3. **Fix the scope** -- repository, period, the question, the working directory +4. **Mine** -- `mine.mjs` writes pull requests and CI runs per day (skipped when the data is already there and the user said so) +5. **First pass** -- `analyze.mjs` without configuration; read the `REVIEWERS` line +6. **Configure** -- `config.json` for what the defaults cannot know, then `analyze.mjs` again +7. **Read the rules and the previous run** -- `results`, `scores` and `previous` in `metrics.json` +8. **Mine the failures** (only if CI runs were mined and `HAS_TOKEN` is `yes`) -- `mine-failures.mjs`, then `analyze.mjs` again +9. **Check the numbers** -- recount one metric on five pull requests, compare the total, name every denominator +10. **Read samples by hand** -- blocking threads, disagreements, follow-up fixes, failed pushes; record each verdict in `labels.tsv` +11. **Make changes measurable** -- every dated process change into `changes`, with `expect` where somebody stated what it should do +12. **Write `findings.json`** -- three to seven findings, each a number with its denominator, its cost and one change +13. **Render the report and the digest** -- `report.mjs`, `daily.mjs`; open the report once +14. **Let the measured party read it** -- one question; corrections go into the findings before they are final +15. **Report + return** -- paths, the findings in two or three sentences, what was not verified + +## Process Flow + +```dot +digraph process_review { + "Run preamble" [shape=box]; + "Node and tools?" [shape=diamond]; + "Stop: one sentence" [shape=doublecircle]; + "Scope" [shape=box]; + "Token or mined data?" [shape=diamond]; + "Mine" [shape=box]; + "Analyze, configure, analyze" [shape=box]; + "Check numbers, read samples, label" [shape=box]; + "Changes with expect" [shape=box]; + "Findings, report, digest" [shape=box]; + "Measured party reads" [shape=diamond]; + "Report + return" [shape=doublecircle]; + + "Run preamble" -> "Node and tools?"; + "Node and tools?" -> "Stop: one sentence" [label="no"]; + "Node and tools?" -> "Scope" [label="yes"]; + "Scope" -> "Token or mined data?"; + "Token or mined data?" -> "Stop: one sentence" [label="neither"]; + "Token or mined data?" -> "Mine" [label="token"]; + "Token or mined data?" -> "Analyze, configure, analyze" [label="mined data only"]; + "Mine" -> "Analyze, configure, analyze"; + "Analyze, configure, analyze" -> "Check numbers, read samples, label"; + "Check numbers, read samples, label" -> "Changes with expect"; + "Changes with expect" -> "Findings, report, digest"; + "Findings, report, digest" -> "Measured party reads"; + "Measured party reads" -> "Findings, report, digest" [label="corrections"]; + "Measured party reads" -> "Report + return" [label="read, or draft"]; +} +``` + +## Preamble + +```bash +# ytstack resolver (M016): checkout = where this shell runs, via the shared lib. +_LIB="${CLAUDE_SKILL_DIR}/../../hooks/lib/git-ctx.sh" +if [ -f "$_LIB" ]; then + . "$_LIB"; yt_git_ctx "$PWD"; yt_resolve_yt_dir >/dev/null + _PROJECT_DIR="$YT_TOPLEVEL"; _YT_DIR="$YT_DIR"; _YT_SCOPE="$YT_SCOPE"; _IS_GIT="$YT_IS_GIT"; _PROJECT_KEY="$YT_REPO_KEY" +else + # Host did not substitute CLAUDE_SKILL_DIR (e.g. Codex adapter): project scope only. + _IS_GIT=$([ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = true ] && echo yes || echo no) + _PROJECT_DIR=$(git rev-parse --show-toplevel 2>/dev/null || pwd -P) + _YT_DIR=""; _YT_SCOPE=none; _PROJECT_KEY="" + [ -d "$_PROJECT_DIR/.ytstack" ] && { _YT_DIR="$_PROJECT_DIR/.ytstack"; _YT_SCOPE=project; } +fi +cd "$_PROJECT_DIR" 2>/dev/null || true +_PROJECT_SLUG=$(basename "$_PROJECT_DIR") # display only +_HAS_YTSTACK=$([ -n "$_YT_DIR" ] && echo yes || echo no) +echo "BRANCH: $(git branch --show-current 2>/dev/null || echo unknown)" +echo "PROJECT_SLUG: $_PROJECT_SLUG" +echo "HAS_YTSTACK: $_HAS_YTSTACK" +echo "YTSTACK_SCOPE: $_YT_SCOPE" +echo "YT_DIR: $_YT_DIR" +if [ -n "${YTSTACK_NON_INTERACTIVE:-}" ] || [ -n "${OPENCLAW_SESSION:-}" ] || [ -n "${CLAUDE_AGENT_TEAM_MEMBER:-}" ]; then + echo "YTSTACK_NON_INTERACTIVE: true" +else + echo "YTSTACK_NON_INTERACTIVE: false" +fi +# Node 18 or newer: the only runtime the scripts need (DECISIONS 2026-11-18). +_NODE_V=$(node -v 2>/dev/null | sed 's/^v//'); _NODE_MAJOR=${_NODE_V%%.*} +case "$_NODE_MAJOR" in ''|*[!0-9]*) _NODE_MAJOR=0 ;; esac +_HAS_NODE=no; [ "$_NODE_MAJOR" -ge 18 ] && _HAS_NODE=yes +echo "HAS_NODE: $_HAS_NODE" +echo "NODE_VERSION: ${_NODE_V:-none}" +# A GitHub token the scripts can resolve: GITHUB_TOKEN, GH_TOKEN, or a signed-in gh. Never printed. +_TOKEN_SOURCE=none +if [ -n "${GITHUB_TOKEN:-}" ]; then _TOKEN_SOURCE=GITHUB_TOKEN +elif [ -n "${GH_TOKEN:-}" ]; then _TOKEN_SOURCE=GH_TOKEN +elif command -v gh >/dev/null 2>&1 && [ -n "$(gh auth token 2>/dev/null)" ]; then _TOKEN_SOURCE=gh +fi +echo "HAS_TOKEN: $([ "$_TOKEN_SOURCE" = none ] && echo no || echo yes)" +echo "TOKEN_SOURCE: $_TOKEN_SOURCE" +_TOOLS="${CLAUDE_SKILL_DIR}/../../tools/process-review" +if [ -f "$_TOOLS/analyze.mjs" ]; then echo "TOOL_DIR: $_TOOLS"; else echo "TOOL_DIR: unavailable"; fi +# The repository to measure, guessed from origin; the user may name another one. +_REPO=$(git remote get-url origin 2>/dev/null | sed -E 's#^(git@|ssh://git@|https://)([^/:@]*@)?[^/:]+[:/]##; s#\.git$##; s#/$##') +case "$_REPO" in */*/*|'') _REPO=unknown ;; */*) : ;; *) _REPO=unknown ;; esac +echo "REPO_GUESS: $_REPO" +# One working directory per measured repository, outside every checkout, so the next run finds the last one. +_WBASE="${XDG_STATE_HOME:-$HOME/.local/state}/ytstack/process-review" +echo "WORKDIR_BASE: $_WBASE" +_WDIR="$_WBASE/$(printf '%s' "$_REPO" | tr '/' '_')" +if [ "$_REPO" != unknown ] && [ -f "$_WDIR/metrics.json" ]; then echo "PREVIOUS_RUN: $_WDIR/metrics.json"; else echo "PREVIOUS_RUN: none"; fi +echo "TODAY: $(date -u +%Y-%m-%d)" +if [ "$_HAS_NODE" = yes ]; then echo "SIX_WEEKS_AGO: $(node -e 'console.log(new Date(Date.now() - 42 * 864e5).toISOString().slice(0, 10))')"; fi +``` + +## Procedure + +In the commands below, `TOOL_DIR` and the working directory stand for the values of this run. Write them out in each command: shell variables do not survive between code blocks. + +**Step 2 -- HARD-GATE.** `HAS_NODE: no`: stop with one sentence, "process-review needs Node 18 or newer on this machine (found: `NODE_VERSION`); nothing was measured." `TOOL_DIR: unavailable`: stop, "the plugin's `tools/process-review/` directory was not found from this skill". `HAS_TOKEN: no`: mining is not possible. Continue only when the user points at a working directory that already holds mined `prs/` files and wants that data analysed; otherwise stop with one sentence: "no GitHub token: set `GITHUB_TOKEN` (read access to pull requests and Actions is enough) or sign in with `gh`". Never ask for a token in the conversation and never print one. + +**Step 3 -- Fix the scope.** Three things, from the user's request first, defaults second: + +- the repository: the one the user named, else `REPO_GUESS`; +- the period: the one the user named, else `SIX_WEEKS_AGO` to `TODAY`. For a before/after question, at least two weeks on each side of the date; +- the question: the one sentence the report has to answer ("are the later review rounds worth it?"). + +The working directory is `WORKDIR_BASE/_` unless the user names another one. Keep one per repository: `PREVIOUS_RUN` is the earlier `metrics.json` there, and the next analysis compares against it by itself. Do not choose a place inside a checkout yourself; when the user names one there, check that the repository ignores it and say so if it does not. + +**Step 4 -- Mine.** Resumable; a finished day is never fetched twice, today always is. + +```bash +node TOOL_DIR/mine.mjs # pull requests and CI runs +node TOOL_DIR/mine.mjs --only prs # pull requests only +``` + +CI runs are the slow part on a busy repository (100 runs per request). Run the two `--only` halves (`prs`, `ci`) as two commands in parallel, or limit CI to the last weeks. After an update of the plugin, add `--refresh` once: it fetches finished days again so that new fields are present. The script waits by itself when GitHub's rate limit (the cap on requests per hour) is reached. Skip this step when the user asked to analyse data that is already mined. + +**Step 5 -- First pass.** `node TOOL_DIR/analyze.mjs ` prints the summary and writes `/metrics.json`. Read the `REVIEWERS` line: it shows which accounts reviewed, and the first line names the reviewer whose reviews were counted as rounds. + +**Step 6 -- Configure.** Open three or four pull requests of the period on GitHub first and look at how reviews actually appear there. A wrong reviewer rule silently yields zero rounds. Then write what the defaults cannot know to `/config.json` (schema and examples: `references/config.md`) and run Step 5 again. Typical needs: + +- a reviewer that posts as a plain comment, or under the author's own account (agent sessions), needs a rule with a `bodyMatch`; +- a bot's "usage limit reached" comments are not reviews: `ignoreBody`; +- reviews that carry a machine-readable count of findings by severity: `findings` makes "blocking" and "clean" rounds exact. Without it the review state decides (changes requested, approved); +- `ciWorkflows` restricts the CI metrics to the workflows that gate a merge; +- `repo` puts the name and the pull request links into the report. + +**Step 7 -- Read the rules and the previous run.** The same run evaluates the rules of `TOOL_DIR/rules.mjs` and prints nothing about them. They land in `metrics.json` as `results` and `scores` and become the report's suggestion cards. Each rule has a threshold and a minimum sample (`references/rules.md`); a rule that cannot be judged has the state `not-evaluated` with its reason and is never shown as passed. The rules judge the last 28 days (`ruleWindowDays`), so a suggestion describes the process as it runs now. Change a threshold to what the team agreed on, never to make a card disappear. With an earlier `metrics.json` in the working directory (or `--prev `), `previous` holds the earlier headline values, and the report marks each suggestion as new or repeated and each earlier one that is now settled. + +**Step 8 -- Mine the failures.** Only if CI runs were mined and `HAS_TOKEN` is `yes`: + +```bash +node TOOL_DIR/mine-failures.mjs --days 7 +node TOOL_DIR/analyze.mjs +``` + +It adds two tables: the failed pushes to the default branch with job, step and the merged pull request behind each, and the jobs that failed and then passed on a re-run (flaky candidates: tests that pass on a second try without a change). One request per run, at most 150 runs each. + +**Step 9 -- Check the numbers.** Each check takes minutes and has caught real errors: + +- Recount one metric by hand on five pull requests from `outliers.mostRounds` in `metrics.json`. +- Compare `total.merged` with the number GitHub shows for `is:pr is:merged merged:..`. +- Give every share its denominator: "107 of 309", not "35 %". +- A comparison needs the same definition and complete data on both sides. A half-mined period is no baseline. + +**Step 10 -- Read samples by hand.** The scripts give proxies. Decide these by reading, and say how many you read: + +- **Were blocking findings right?** `reviewers..sample` in `metrics.json` is a fixed sample of threads per reviewer. Read each thread and the commit that followed: fixed as asked (`right`), rejected with a reason the reviewer accepted (`false alarm`), or `unclear`. +- **Disagreements.** With two reviewers on the same head (`compare`), read the pull requests where only one blocked: who was right? +- **Follow-up fixes.** Read ten entries of `followUps`: could the review have caught the defect, or was it new information? +- **Red default branch.** For each failed push in `failures.defaultBranch`: `merged defect`, `inherited`, `flaky test` or `infrastructure`. + +Record every verdict as one line in `/labels.tsv` (tab-separated, format in `references/config.md`, "labels.tsv"), then run `analyze.mjs` again. The report then shows, per reviewer, how many of the decided blocks were right, and the failures by cause. A label names who gave it; an agent's label and a person's label are not the same evidence. + +**Step 11 -- Make changes measurable.** Every process change that should be judged goes into `changes` in `config.json`: a new reviewer, a rule, a CI change, a new version of the agent tooling. + +```json +{ "changes": [{ "at": "2026-01-15", "label": "second review only on request", "expect": { "metric": "rounds", "direction": "down" }, "decidedBy": "team", "approval": "pending" }] } +``` + +For each entry the analysis compares the days before with the days from it on, metric by metric. With `expect` (the metric keys are listed in `references/config.md`) the change gets its own verdict: `confirmed`, `refuted` or `too early`. Write `expect` when somebody stated what the change should do, in their words, not after seeing the result. Where the dates come from: + +- the people who made the change, and the repository's decision records or changelog; +- `changeCandidates` in `metrics.json`: merged pull requests that touched workflows, review rules or agent instructions, and the first and last day each reviewer was seen; +- tool versions: `node TOOL_DIR/tool-versions.mjs plugin ` lists when each version of a Claude Code plugin arrived on this machine, `node TOOL_DIR/tool-versions.mjs file ''` when a repository changed a pinned version. Group versions of the same day into one entry. + +Read the result with three cautions, which the report prints too. Changes close together cannot be told apart (the card names the others inside its windows). A different mix of work before and after moves the numbers without any process change. The days after a recent change are incomplete. To test a change properly: change one thing, leave it for a full window, and write the date down on the day, not afterwards. + +**Step 12 -- Write `findings.json`.** The suggestion cards come from the rules without you. What only you can add is what you read in Step 10. Write three to seven findings to `/findings.json`: + +```json +[{ "value": "416 of 461", "tone": "bad", "title": "Later review rounds that found nothing blocking", "recommendation": "Let a non-blocking review stand; a later round reads only the fix.", "evidence": "Readable later rounds of the last 28 days. 12 threads read by hand, 9 right. Not verified: rounds on force-pushed branches." }] +``` + +`value` is the one number that carries the finding, `tone` is `good`, `warn` or `bad`, `title` says in one line what the number is, `recommendation` is one sentence, `evidence` holds the denominators, the trend and what was not verified. Rank by cost. Read efficiency and quality together: fewer rounds with more follow-up fixes is no gain (`references/metrics.md`, "Reading the result"). The numbers describe the process, not people. Never rank individuals with them. + +**Step 13 -- Render the report and the digest.** + +```bash +node TOOL_DIR/report.mjs /metrics.json /report.html --findings /findings.json +node TOOL_DIR/daily.mjs /metrics.json --out /digest.md +``` + +Open the report and look at every chart once: an empty chart means a configuration gap, back to Step 6. The digest compares the last complete day with the seven days before it (`--day YYYY-MM-DD` for another day) and is short enough for a chat message. It observes and recommends nothing; changes are decided on the report. For a recurring run, the same three commands (mine, analyze, daily) on a schedule are enough; the digest needs the day and at least three days before it. + +**Step 14 -- Let the measured party read it.** The authors, reviewers or the owners of the agents whose work the report describes read it before a finding is final. `YTSTACK_NON_INTERACTIVE: true`: do not ask; add "Draft: not yet read by the measured party." to the `evidence` of every finding, render again, and say so in the report. Otherwise ONE AskUserQuestion: + +> Process review of **{repository}** for {since} to {until} (run from `{PROJECT_SLUG}` on `{BRANCH}`): the report is at `{workdir}/report.html` with {k} findings, the strongest: {value} {title}. +> +> The report describes how people and agents worked. They know things the counts do not: a week of migration work, a reviewer that was switched off on purpose, a rule that changed on a day nobody wrote down. If they read it first, wrong findings are corrected before anybody acts on them. +> +> RECOMMENDATION: Choose A because a finding the measured party has not seen is a claim about them, not a result. +> +> A) They read it first -- you (or the people you forward it to) read the report and tell me what is wrong or missing; I correct the findings and render again +> Completeness: 10/10, effort: human: ~15 min / CC: ~5 min, tier: task +> B) Deliver as a draft -- every finding is marked "not yet read by the measured party" +> Completeness: 6/10, effort: human: 0 / CC: ~1 min, tier: task + +With A: take each correction into the `evidence` of its finding in the reader's words (or remove the finding), add the missing dates to `changes`, run Steps 11 to 13 again, and note who read it. With B: mark the findings as in the non-interactive case and render again. + +**Step 15 -- Report + return.** + +> Process review of {repository}, {since} to {until}: {n} merged pull requests. Report: `{workdir}/report.html`. Digest: `{workdir}/digest.md`. Findings: {two or three sentences, each with its number and denominator}. Suggestions from the rules: {t} triggered, {e} not evaluated. Changes measured: {label: verdict, ...}. Read by: {who, or "nobody yet (draft)"}. Not verified: {what}. + +## Limits + +- Merged pull requests only: abandoned work, direct pushes and the time before a pull request opened are invisible. +- Per pull request the scripts read at most 100 commits, 40 reviews, 60 comments, 60 threads and 60 files; very large pull requests are undercounted. +- "Fixed again" is cut off at the end of the period: pull requests of the last days had less time to attract a fix. +- CI duration is the wall time of a run's last attempt, not billed minutes; runs are matched to pull requests by branch name. +- GitHub is the only host. The scripts have no test against GitHub Enterprise Server (`GITHUB_API_URL` is read, untested). + +## Terminal State + +The terminal state is one of: + +- Returning control to the user with `report.html`, `digest.md`, `metrics.json` and `findings.json` in the working directory, nothing committed and nothing written into the repository +- Exiting without a number at the HARD-GATE (no Node, no tool directory, or no token and no mined data) + +Do NOT invoke `ytstack:retro`, `ytstack:lane-retro`, `ytstack:lesson` or `ytstack:review-lessons` from here, do not change a workflow, a review rule or an instruction file, and do not add a `changes` entry for a change nobody made: this skill measures, people decide. There is no skill you may invoke after this one. If a finding should become work, name it and stop. To get the findings to the session that coordinates the work, the user runs `ytstack:coach-process` next. diff --git a/skills/process-review/references/config.md b/skills/process-review/references/config.md new file mode 100644 index 00000000..1b24eb0a --- /dev/null +++ b/skills/process-review/references/config.md @@ -0,0 +1,130 @@ +# config.json + +Optional file in the working directory, read by `analyze.mjs`. Every key is optional. + +```json +{ + "repo": "owner/name", + "reviewers": [ + { "name": "Review bot", "login": "some-review-bot", "ignoreBody": "usage limit" }, + { "name": "Agent review", "bodyMatch": "^#+ Independent review" }, + { "name": "Security team", "login": "alice" } + ], + "rounds": { "kind": "Agent review" }, + "findings": { "pattern": "critical (\\d+), high (\\d+), medium (\\d+), low (\\d+)", "blockingGroups": [1, 2] }, + "compare": ["Review bot", "Agent review"], + "ciWorkflows": ["ci"], + "defaultBranch": "main", + "changes": [{ "at": "2026-01-15", "label": "new reviewer" }, { "at": "2026-02-01", "label": "agent tooling 2.0" }], + "fixPattern": "^(fix|hotfix|revert)\\b", + "followUpDays": 7, + "sampleSize": 12 +} +``` + +| Key | Meaning | Default | +| --- | --- | --- | +| `repo` | Shown in the report and used for pull request links. | none | +| `reviewers` | Rules that name who reviewed. Checked in order; the first rule whose `login` (exact) and `bodyMatch` (regular expression, case-insensitive, on the first 300 characters) both fit wins. `ignoreBody` drops the event instead (quota notices). | see below | +| `rounds.kind` | The reviewer whose reviews count as review rounds. | `human` if humans reviewed at least 5 % of the pull requests, else the most frequent reviewer | +| `findings.pattern` | Regular expression with one capture group per severity, matched on a review's text. `blockingGroups` lists the groups (from 1) that block a merge. | none: the review state decides (changes requested blocks, approved is clean) | +| `compare` | Two reviewer names; counts agreement where both reviewed the same head. Needs `findings`. | none | +| `ciWorkflows` | Workflow names that count for CI metrics. | all workflows | +| `defaultBranch` | Branch whose pushes are the "red default branch" metric. | the most frequent base branch | +| `changes` | Dated process changes, `{ "at", "label" }` plus the optional `expect`, `decidedBy` and `approval` (see "Change entries" below). Drawn as lines in the charts and compared before and after (`markers` is read as an older name for the same list). | none | +| `changeWindowDays`, `changeMinSample` | Days on each side of a change; smallest number of cases on each side for a verdict. | 7, 20 | +| `processPaths` | Regular expression on file paths that marks a pull request as a change to the process itself (candidates for `changes`). | workflows and other files under `.github/`, agent instruction files, review rules, linter and test runner configuration | +| `fixPattern` | Regular expression on the title that marks a fix. | conventional `fix`, `hotfix`, `bugfix`, `revert` prefixes | +| `testPattern`, `sourcePattern`, `ignorePaths` | Regular expressions on file paths: what is a test, what is source code, what never counts as a shared file. | common test directories and suffixes; common source extensions; lock files and Markdown | +| `docsPattern`, `sensitivePattern` | Regular expressions on file paths for the risk classes: what is documentation, and what is sensitive (default: migrations, SQL, authentication and security paths, workflows, deployment files). | see `analyze.mjs` | +| `agentPattern` | Regular expression that marks an AI tool in co-author trailers and the end of the description. | common assistant and agent names | +| `rules` | Thresholds or `off` per rule, see `references/rules.md`. | none | +| `roles.pattern` | Regular expression with one capture group that reads the review role out of an inline thread (for example ``"`(code|security|tests)`"`` when threads name their role in backticks). Splits blocking threads by role and by round. | none | +| `plannedFollowUpPattern` | Regular expression on the title and the first 600 characters of a fix that marks it as the planned follow-up of a review finding and not a defect found after merge. | wording such as "follow-up", "review r2", "non-blocking", "nit" | +| `ruleWindowDays` | The rules judge the last so many days of the period. | 28 | +| `ignoreFailedJobs` | Regular expression on `job › step` for jobs that only report that another job failed ("require all checks" gates); dropped from the failure tables. | none | +| `followUpDays` | Window in which a later fix counts as a follow-up. | 7 | +| `sampleSize` | Threads per reviewer in the hand-check sample. | 12 | + +## How reviewers are named without rules + +1. An event by a bot account is named by its login. +2. An event by a person other than the pull request's author is `human`. +3. The author's own comments count as nothing. + +So two cases need a rule: + +- **A reviewer under the author's account.** Coding-agent sessions often post reviews with the token of the account that also opened the pull request. Give the rule only a `bodyMatch` that fits the review's heading. +- **A reviewer that posts plain comments.** A comment counts as a review round only when a rule named it; otherwise only real reviews do, so that ordinary discussion is not counted as rounds. + +An inline thread is attributed through the text of the review it was posted with, so the rule for a review also names its threads. + +A bot's notice that it did not review (usage limit, quota, "couldn't run") is dropped by default; `noticePattern` replaces that expression. + +## Rules for common review bots + +A bot that never approves needs `cleanMatch` (regular expression on the first 300 characters) so that its "nothing found" answer counts as a clean round. Check the wording on a few pull requests of the repository first; bots change their texts. + +```json +{ + "reviewers": [ + { "name": "Codex", "login": "chatgpt-codex-connector", "ignoreBody": "usage limits|codex-pull-request-review-summary", "cleanMatch": "Didn't find any major issues" }, + { "name": "Bugbot", "login": "cursor", "ignoreBody": "usage limit" }, + { "name": "Greptile", "login": "greptile-apps" } + ], + "rounds": { "kind": "Codex" } +} +``` + +A status comment that a bot edits in place (a review summary) is not a review: put it into `ignoreBody`. + +## Rounds + +One round is one reviewed head commit: several reviews of the round reviewer on the same head are one round. A plain comment has no head; it is assigned the last commit dated before it. Force-pushed branches lose their earlier commits, which merges rounds; note it when a repository rebases. + +## Change entries + +```json +{ "at": "2026-01-15", "label": "second review only on request", "expect": { "metric": "rounds", "direction": "down" }, "decidedBy": "team", "approval": "pending" } +``` + +| Field | Meaning | +| --- | --- | +| `at`, `label` | The day the change took effect (UTC) and its name in the charts and cards. An entry outside the analysed period is ignored. | +| `expect.metric`, `expect.direction` | What the change was meant to do: one metric key and `up` or `down` (anything else reads as `down`). The card then carries a verdict of its own: `confirmed` (the metric moved clearly in that direction), `refuted` (it did not move clearly, or moved the other way), `too early` (the window after the change is not complete, or a side has fewer than `changeMinSample` cases), `unknown metric`. | +| `decidedBy` | Who decided the change; shown on the card. | +| `approval` | Free text shown on the card. The value `pending` marks a change that awaits a person's approval; the daily digest lists those. | + +Metric keys for `expect.metric`: `mergedPerDay`, `lead` (median hours), `rounds` (mean per reviewed pull request), `ciHours` (mean per pull request), `size` (median changed lines), `firstPass`, `multiRound` (two or more rounds), `ciFailed` (pull requests with a failed CI run), `noReview`, `fixShare`, `followUp` (fixed again by a linked fix), `fixNoTest`, `mainFailed` (failed CI on the default branch). `mergedPerDay` and `size` are context rows without a verdict, so an expectation on them is never `confirmed`; do not use them. + +A row's verdict is `better`, `worse`, `no clear change` (the difference is within what chance explains: a rank-sum test for values, a two-proportion test for shares, |z| below 1.96), `too few` or `context`. + +## asks.json + +Optional file in the working directory, written by `coach-process`: one object per ask delivered to a coordinator. `analyze.mjs` judges each like a change with an expectation (the metric keys above), from its day on, and counts how often the same `key` was asked. + +```json +[{ "key": "round-rules-followed", "at": "2026-11-22", "to": "v2 coordinator", "ask": "Hold later rounds to the round rules", "metric": "multiRound", "direction": "down", "ref": "coach-2026-11-22.txt" }] +``` + +## labels.tsv + +Optional file in the working directory: what a reader decided by hand. Tab-separated, one line per verdict; lines starting with `#` and a header line starting with `date` are skipped. + +```text +date kind ref subject label by note +2026-01-20 block #1234 Review bot right alice fixed as asked in the next commit +2026-01-20 block #1240 Review bot false alarm alice author explained, reviewer withdrew +2026-01-21 main-failure run 9912 flaky test agent passed on re-run without a change +``` + +| Column | Meaning | +| --- | --- | +| `date` | The day of the verdict. | +| `kind` | `block` (was a reviewer's block right) or `main-failure` (what caused a failed push to the default branch). | +| `ref` | The pull request or run. | +| `subject` | For `block`: the reviewer's name as the report shows it. Empty for `main-failure` (keep the tab). | +| `label` | For `block`: `right` or `false alarm`; anything else counts as unclear. For `main-failure`: the cause in a few words (`merged defect`, `inherited`, `flaky test`, `infrastructure`); the report counts each distinct label. | +| `by`, `note` | Who labelled it (a person or an agent) and one sentence of evidence. | + +The hit rate of a reviewer is `right / (right + false alarm)`; unclear blocks are shown and left out of it. diff --git a/skills/process-review/references/metrics.md b/skills/process-review/references/metrics.md new file mode 100644 index 00000000..73abfbd2 --- /dev/null +++ b/skills/process-review/references/metrics.md @@ -0,0 +1,98 @@ +# Metrics + +All metrics are per merged pull request, grouped by merge day or merge week (UTC, weeks from Monday). `metrics.json` holds them as `total`, per `weeks` and, for counts, per `days`. + +## Throughput + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `merged` | Merged pull requests. | Says nothing about value. Many small pull requests and few large ones can be the same work; read with `sizeMedian`. | + +## Efficiency + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `leadMedianH`, `leadP90H` | Hours from opening to merge. | Work before the pull request opened is invisible. Draft time counts. | +| `firstReviewMedianH` | Hours from opening to the first review event of any named reviewer. | A bot that answers in a minute hides a slow human review. Look at the reviewer that gates the merge. | +| `roundsMean`, `multiRoundShare`, `threePlusShare` | Review rounds of the round reviewer per reviewed pull request; share with two or more, three or more. | Depends entirely on `rounds.kind` and the reviewer rules. | +| `firstRoundBlockingShare` | First rounds that blocked, of those whose outcome is readable. | Without `findings`, only "changes requested" blocks. | +| `laterClean`, `laterNonBlocking`, `laterBlocking`, `laterUnknown` | What each round after the first found: nothing, only non-blocking findings, a blocking finding, not readable. | The core answer to "too many loops": clean and non-blocking later rounds are the avoidable ones. A later blocking round can be a real late find or a regression from the fix; read some. | +| `laterAfterMergeOnly` | Later rounds preceded only by merge commits of the base branch. | A review repeated although the author changed nothing. | +| `reworkCommitsMean` | Commits after the first round, without merge commits. | Squashing authors show one commit. | +| `ciRunsPerPrMedian`, `ciHoursPerPr`, `ciFailedRunShare` | Workflow runs on the pull request's branch; their summed wall time; failed of finished runs. | Matched by branch name, so a reused branch name mixes pull requests. Wall time of a run, not job minutes. | + +| `firstPassShare` | Pull requests whose first finished CI run was green and whose first review round did not block, of those with both known. | The repository-level success rate of the first attempt; its complement is the fix-push-wait load. Not available where the review outcome cannot be read. | +| `ciLoopShare` | Pull requests with at least one failed CI run on their branch. | A failed run from a flaky test counts too. | +| `phases` | Hours from open to the first review, from the first to the last review event, from the last review to merge; median, 75th and 90th percentile each. | Medians of phases do not add up to the median of the total. Vendors cut the phases differently (review may start at open, at the review request or at "ready for review"); compare with a published tier only on the same cut and percentile. | +| `leadHistogram`, `heat` | Pull requests by lead-time bucket; merges by weekday and hour (UTC). | The histogram shows the tail the median hides. The heatmap shows when the pipeline is under load, not when people work. | +| `roundYield` | Per round position (1, 2, 3, 4+): rounds with a blocking finding, only non-blocking findings, nothing, not readable. | The answer to "is a third round worth it". Needs `findings` or review states. | +| `laterYield.byClass`, `laterYield.byRole` | Later rounds that found a blocker, per risk class; blocking threads per review role, in round 1 and in later rounds. | Read these before recommending fewer rounds: a low overall yield can hide a role or a class whose later rounds pay. Role counts are small; give the counts, not only the share. | +| `ci.prBranches`, `ci.defaultBranchPush` | CI statistics for runs on pull request branches and for pushes to the default branch, separately. | Cancelled runs mean different things: a superseded push on a branch, possibly a deliberate queue policy on the default branch. | +| `failures` (from `mine-failures.mjs`) | Failed pushes to the default branch of the last days with the failed job and step and the merged pull request behind the commit; jobs that failed on the first attempt of runs that later turned green. | Job and step, not the test: the failing test is in the log. A failure repeated on consecutive merges is usually inherited from an earlier one. Gate jobs that only mirror other failures need `ignoreFailedJobs`. | +| `classes` | Lead time, review coverage, rounds, CI runs and CI hours per risk class (docs only, tests only, configuration, source code, sensitive). | Classes come from path patterns; set `sensitivePattern` and `docsPattern` to fit. Cost that does not rise with risk is waste at the low end or a gap at the high end. | + +## Authors + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `authors.classes` | Pull requests by author class: bot account, AI-assisted or agent (a co-author trailer, a footer in the description or a branch prefix names an AI tool), no AI mark. | Detection undercounts: some tools leave no mark and trailers can be switched off. "No AI mark" is not "human". The signal that classified each pull request is counted in `authors.signals`. Compare classes inside one repository only. | + +## Quality + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `fixShare` | Pull requests whose title marks a fix. | Depends on title discipline. A rising share can mean more defects or more honest titles. | +| `reverts` | Titles that mark a revert. | Reverts by direct push are invisible. | +| `followUpExplicitShare`, `followUpMedianH` | Pull requests that a later fix names by number (`#123` in title or body) within the window; hours until that fix merged. | The strongest automatic signal of a defect that passed review. Still counts planned follow-ups ("addresses the notes from #123"): read a sample. Right-censored for the newest pull requests. | +| `followUpDefectShare`, `followUpPlannedShare` | The linked follow-ups split by the wording of the fixing pull request: not worded as a review follow-up (possible defect), or only planned follow-ups of review findings. | Where non-blocking findings are deliberately moved to the author's next pull request, the planned part grows when the process works as intended; only the defect part is a quality signal. The split is by wording (`plannedFollowUpPattern`), so read a sample of both. | +| `followUpOverlapShare` | As above, or a later fix touched one of the same files (files touched by more than 5 % of all pull requests, lock files and Markdown ignored). | An upper bound. Busy files make it large without any defect. Use it for the trend only. | +| `noReviewShare` | Merged without any review event or thread by a named reviewer. | Zero if a bot comments on everything; then look per reviewer. | +| `unresolvedThreadPrs` | Merged with at least one unresolved thread. | Zero where a ruleset enforces resolution. | +| `sourceWithoutTestShare`, `fixWithoutTestShare` | Pull requests touching source files without touching any test file; the same among fixes. | Refactorings and configuration need no test. The share among fixes is the telling one. Only the first 60 files are read. | +| CI `failureRate` on the default branch | Failed of finished push runs on the default branch. | Mixes merged defects, flaky tests and infrastructure. Classify the failures by reading the logs of a sample. | +| CI `red` | Periods in which the default branch was red, from the first failed push run to the end of the next green one: count, median, longest, total hours. | A stand-in for time to restore. Runs of several workflows are mixed unless `ciWorkflows` names the gating one. | +| `hotspots` | Files touched by three or more fix pull requests, with all pull requests touching them. | Only the first 60 files of a pull request are read; generated and lock files are ignored through `ignorePaths`. A hotspot is where to look, not a verdict. | +| `meta` | Pull requests closed without a merge in the period, open now, and open for more than a week. | Everything else on the page covers merged pull requests only; these three numbers say how much that leaves out. | +| CI `rerunGreen` | Runs whose later attempt succeeded. | Candidates for flaky tests; a re-run after an infrastructure outage looks the same. | +| CI `hoursNotGreen`, `cancelledShare` | Wall time of runs that did not end green; share of cancelled runs. | Cancelling a superseded run is efficient; a high share of cancelled hours still shows pushes arriving faster than CI finishes. | + +## Reviewers + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `prs`, `prShare` | Pull requests with at least one event of the reviewer. | Presence, not usefulness. | +| `threadsOutdated` of `threadsJudged` | Threads whose lines a later commit changed (GitHub's outdated flag). | The cheapest sign that a finding was acted on. Not causal: rebases and unrelated edits count. Read it as one reviewer against another in the same repository, never against a published number. | +| `threads`, `threadsResolved` | Inline threads the reviewer opened; resolved ones. | Resolved does not mean the finding was right: authors resolve false alarms too. | +| `sample` | A fixed pseudo-random sample of the reviewer's threads. | This is the input for the hand check of precision; the script does not judge it. | +| `compare` | For two reviewers on the same head: both block, only one, neither. | Agreement is not correctness. Read the one-sided cases. | + +## Changes + +| Metric | Definition | Pitfall | +| --- | --- | --- | +| `changes[].rows` | Per dated change: each metric in the window before and the window from the change on, with the number of cases on both sides and a reading: `better`, `worse`, `no clear change`, `too few`, `context`. | A reading of better or worse means the difference is larger than chance explains at the 5 % level (rank-sum test for lead time, rounds and CI hours; two-proportion test for shares). It is not proof of cause. | +| `changes[].confounded` | Other marked changes inside either window. | With several changes in one window the effect belongs to the group, not to one of them. | +| `changes[].incomplete`, `followUpsCensored` | The window after the change runs past the last mined day; later fixes for it may still come. | Re-run when the window is complete before reporting an effect. | +| `changeCandidates` | Merged pull requests that touched process files, and the first and last day each reviewer was seen. | Candidates only: a typo fix in a workflow is not a process change. Changes made outside the repository (a bot's settings, a tool update on a developer machine) do not appear here at all. | + +Two things a before/after window cannot separate from a process change: a different mix of work (a week of documentation next to a week of migrations) and load (twice as many pull requests on the same runners). Check the risk-class table and the merged-per-day row of the same card before attributing an effect. + +## What cannot be measured this way + +- **Recall of a review** (defects it missed) has no direct measure. Follow-up fixes and failures on the default branch are its shadow. +- **Precision of a review** needs reading (the skill's Step 10, "Read samples by hand"). State the sample size with the result. +- **Production quality** (incidents, error rates) lives outside GitHub. If the team has an error tracker or an incident log, add its numbers per week next to the report's quality section and say where they come from. + +## Reading the result + +Efficiency and quality are read together; either alone misleads. + +| Pattern | Likely meaning | Check | +| --- | --- | --- | +| Many later rounds that find nothing | Re-reviews without cause: every push triggers a full round | Rounds after merge-only commits; let a non-blocking review stand. First read "Which later rounds pay": keep the rounds of the role or risk class whose later rounds do find blockers | +| Later rounds with only non-blocking findings | Reviewer reports new details each round, author fixes them one push at a time | Limit later rounds to the changed lines; collect details for the next pull request | +| High first-round blocking share, low follow-up fixes | The review earns its cost | Sample that the findings were right | +| Low blocking share and rising follow-up fixes or red default branch | Review misses defects | Read the follow-ups; what would have caught them | +| Long lead time, few rounds | Waiting, not working: queue for review or CI | Time to first review, CI p90, cancelled runs | +| High share of runner-hours not green | CI spent on runs that were cancelled or failed | Per workflow; concurrency groups, change classes, flaky tests | +| Fixes without a test file | Defects come back | Read five such fixes | diff --git a/skills/process-review/references/rules.md b/skills/process-review/references/rules.md new file mode 100644 index 00000000..554d736f --- /dev/null +++ b/skills/process-review/references/rules.md @@ -0,0 +1,57 @@ +# Rules and suggestions + +`tools/process-review/rules.mjs` holds one object per rule. `analyze.mjs` evaluates them and writes `results` and `scores` to `metrics.json`; `report.mjs` renders a triggered rule as a suggestion card (severity, the problem with its counts, why it matters, the change to make, threshold and sample) and a passed rule as a line under "What works". + +The rules judge the last 28 days of the period (`ruleWindowDays` in `config.json`), not the whole of it: a suggestion should describe the process as it runs now. The CI rules `ci-hours-not-green` and `ci-cancelled` count runs on pull request branches only. + +## States + +| State | Meaning | +| --- | --- | +| `triggered` | The sample is large enough and the threshold is crossed. | +| `passed` | The sample is large enough and the threshold holds. | +| `not-evaluated` | Too few cases or no data (no CI runs mined, no readable finding counts, no second reviewer). Shown with the reason. | +| `off` | Switched off in `config.json`. | + +## The rules + +| Rule | Group | Severity | Triggers when | Threshold | Minimum sample | +| --- | --- | --- | --- | --- | --- | +| `later-rounds-low-yield` | review | high | share of later rounds without a blocking finding is at or above | 0.6 | 20 readable later rounds | +| `rounds-after-merge-only` | review | medium | share of later rounds after merge commits only | 0.1 | 20 later rounds | +| `many-rounds` | review | medium | share of reviewed pull requests with three or more rounds | 0.1 | 30 | +| `merged-without-review` | review | medium | share merged without any review | 0.2 | 30 | +| `unresolved-threads` | review | low | pull requests merged with an open thread, more than | 0 | 30 | +| `reviewers-disagree` | review | medium | share of commits reviewed by both `compare` reviewers where only one blocked | 0.2 | 20 | +| `first-pass-low` | flow | medium | share that passed on the first attempt is below | 0.5 | 30 | +| `slow-first-review` | flow | medium | median hours to the first review above | 4 | 30 | +| `large-prs` | flow | low | median changed lines above | 228 | 30 | +| `ci-hours-not-green` | ci | high | share of CI hours in runs that did not end green | 0.2 | 100 runs | +| `ci-cancelled` | ci | medium | share of cancelled runs | 0.2 | 100 runs | +| `flaky-reruns` | ci | medium | share of runs that turned green on a re-run | 0.01 | 100 runs | +| `red-default-branch` | quality | high | failure rate of push runs on the default branch above | 0.1 | 30 runs | +| `follow-up-fixes` | quality | medium | share of pull requests named by a later fix that is not worded as a review follow-up | 0.08 | 50 | +| `fixes-without-tests` | quality | medium | share of source-code fixes without a test file | 0.2 | 50 fixes | +| `high-fix-share` | quality | low | share of fix pull requests | 0.35 | 50 | + +Three thresholds follow a published reference, named on the card with source and year: `slow-first-review` and `large-prs` (LinearB 2026 benchmarks, 75th percentile of that vendor's customers) and `red-default-branch` (CircleCI 2026, 90 % main-branch success). All others are coaching defaults: a place to start, not a proven standard. Published tiers describe the vendor's customer base and change from year to year; do not present them as a grade. + +## Changing a rule + +```json +{ "rules": { "large-prs": { "threshold": 400 }, "high-fix-share": { "off": true } } } +``` + +Set a threshold to what the team has agreed on. A threshold raised only so that a card disappears hides the finding from the next reader too. + +## Score per group + +`100 × (1 − penalties ÷ (evaluated rules × 12))`, with 12 points for a triggered high rule, 7 for medium and 3 for low (the formula of Microsoft's AI Engineer Coach). Two properties to keep in mind when reading it: a rule costs its penalty once, however often it fired, and a group with few evaluated rules swings widely. There is deliberately no overall score: it would hide what the four group scores explain. + +## Adding a rule + +Add an object to `RULES`: `id`, `group`, `severity`, `name`, `th` (default threshold), `min` (smallest sample), `check(metrics, threshold)` returning `{ n, hit, problem, good }`, plus `why`, `action` and, where the threshold comes from a publication, `ref` with source and year. `problem` and `good` are full sentences with counts and denominators ("413 of 458 ..."), because the card shows them verbatim. If the rule needs a number that `metrics.json` does not hold yet, compute it in `analyze.mjs` first. + +## Since the last report + +`analyze.mjs` reads the previous `metrics.json` of the working directory before it overwrites it (or the file given with `--prev`) and stores the earlier period, headline values and triggered rule ids under `previous`. The report then shows "last report: ..." in the headline tiles, marks each suggestion as new or repeated, and marks a passed rule that was triggered last time as settled. A re-run over the same period keeps the comparison it already had. diff --git a/tests/process-review.test.sh b/tests/process-review.test.sh new file mode 100644 index 00000000..3e622ff7 --- /dev/null +++ b/tests/process-review.test.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# Tests for the process-review tools (tools/process-review/*.mjs, the scripts +# behind skills/process-review). +# +# Contract pinned here, on a synthetic fixture in the format mine.mjs writes +# (40 merged pull requests and 10 CI runs over ten days, as JSON lines): +# - analyze.mjs writes metrics.json with the counts of the fixture, and with +# --out it writes only that file (no history/, the working directory stays +# as it was) +# - a rule whose threshold is crossed on a large enough sample is "triggered"; +# a rule whose sample is too small is "not-evaluated" with the reason, +# never "passed" +# - a dated change with `expect` gets a verdict of its own +# - labels.tsv is read into a hit rate per reviewer and into causes of failed +# pushes +# - a second run finds the first one as `previous` +# - report.mjs writes one HTML file with the suggestions section and the +# analyst's finding; daily.mjs prints the digest of the day asked for +# - api.mjs exits 2 with a clear message when no token can be resolved +# +# No network: mine.mjs and mine-failures.mjs are never run. Node is the +# plugin's one optional runtime (DECISIONS 2026-11-18); without node 18 or +# newer the node cases are skipped and the suite stays green. +# +# Run: /bin/bash tests/process-review.test.sh (exit 0 = all pass) + +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd -P)" +TOOLS="$ROOT/tools/process-review" + +PASS=0; FAIL=0 +ok() { PASS=$((PASS+1)); echo " ok - $1"; } +bad() { FAIL=$((FAIL+1)); echo " FAIL - $1${2:+ ($2)}"; } +eq() { if [ "$2" = "$3" ]; then ok "$1"; else bad "$1" "expected '$2' got '$3'"; fi; } +has() { case "$2" in *"$3"*) ok "$1";; *) bad "$1" "missing '$3'";; esac; } + +echo "# files" +for f in api mine mine-failures analyze rules report daily tool-versions; do + [ -f "$TOOLS/$f.mjs" ] && ok "$f.mjs is shipped" || bad "$f.mjs is shipped" +done +[ -f "$ROOT/skills/process-review/SKILL.md" ] && ok "the skill is shipped" || bad "the skill is shipped" + +NODE_MAJOR=$(node -v 2>/dev/null | sed 's/^v//; s/\..*//') +case "$NODE_MAJOR" in ''|*[!0-9]*) NODE_MAJOR=0 ;; esac +if [ "$NODE_MAJOR" -lt 18 ]; then + ok "node 18 or newer not on PATH: analyze, report, digest and token cases skipped" + echo "$PASS passed, $FAIL failed" + [ "$FAIL" -eq 0 ]; exit $? +fi + +T=$(mktemp -d "${TMPDIR:-/tmp}/ytpr.XXXXXX"); T=$(cd "$T" && pwd -P) +trap 'rm -rf "$T"' EXIT +D="$T/work"; mkdir -p "$D/prs" "$D/ci" + +# ---- fixture: ten days, four merged pull requests a day. Until 5 March nothing +# is reviewed; from 6 March on a person approves each one. One push run on main +# per day, the one of 9 March fails. Numbers 1 to 40, all on base main. +n=0; d=1 +while [ $d -le 10 ]; do + day=$(printf '2026-03-%02d' $d) + i=1 + while [ $i -le 4 ]; do + n=$((n+1)) + if [ $d -ge 6 ]; then + reviews="[{\"by\":\"rita\",\"bot\":false,\"state\":\"APPROVED\",\"at\":\"${day}T09:00:00Z\",\"head\":\"c${n}\",\"body\":\"fine\"}]" + else + reviews="[]" + fi + printf '{"number":%d,"title":"feat: change %d","body":"","createdAt":"%sT08:00:00Z","mergedAt":"%sT10:0%d:00Z","additions":10,"deletions":2,"changedFiles":1,"branch":"feat-%d","base":"main","author":"dev","authorBot":false,"bodyTail":"","coAuthors":[],"labels":[],"commitCount":1,"commits":[{"oid":"c%d","at":"%sT08:00:00Z","msg":"change %d"}],"reviews":%s,"comments":[],"threadCount":0,"threads":[],"files":["src/a%d.ts"]}\n' \ + "$n" "$n" "$day" "$day" "$i" "$n" "$n" "$day" "$n" "$reviews" "$n" >> "$D/prs/$day.jsonl" + i=$((i+1)) + done + concl=success; [ $d -eq 9 ] && concl=failure + printf '{"id":%d,"name":"ci","event":"push","branch":"main","sha":"m%d","attempt":1,"status":"completed","conclusion":"%s","createdAt":"%sT11:00:00Z","startedAt":"%sT11:00:00Z","updatedAt":"%sT11:10:00Z"}\n' \ + "$((100+d))" "$d" "$concl" "$day" "$day" "$day" > "$D/ci/$day.jsonl" + d=$((d+1)) +done +cat > "$D/config.json" <<'EOF' +{ + "repo": "acme/shop", + "changeWindowDays": 3, + "changeMinSample": 5, + "changes": [{ "at": "2026-03-06", "label": "every pull request is reviewed", "expect": { "metric": "noReview", "direction": "down" }, "decidedBy": "team" }] +} +EOF +{ + printf 'date\tkind\tref\tsubject\tlabel\tby\tnote\n' + printf '# three blocks read by hand\n' + printf '2026-03-07\tblock\t#21\thuman\tright\talice\tfixed as asked\n' + printf '2026-03-07\tblock\t#22\thuman\tright\talice\tfixed as asked\n' + printf '2026-03-08\tblock\t#25\thuman\tFalse Alarm\talice\twithdrawn\n' + printf '2026-03-08\tblock\t#26\thuman\tnot sure\talice\t\n' + printf '2026-03-09\tmain-failure\trun 109\t\tflaky test\tagent\tgreen on re-run\n' +} > "$D/labels.tsv" + +# j -> the value, printed +j() { node -e 'const m = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); const v = eval(process.argv[2]); console.log(typeof v === "object" ? JSON.stringify(v) : String(v));' "$1" "$2" 2>&1; } + +echo "# analyze.mjs --out writes only that file" +OUT=$(node "$TOOLS/analyze.mjs" "$D" --out "$T/side.json" 2>&1); EC=$? +eq "analyze --out: exit 0" 0 "$EC" +[ -f "$T/side.json" ] && ok "analyze --out: the named file is written" || bad "analyze --out: the named file is written" +[ ! -e "$D/metrics.json" ] && [ ! -e "$D/history" ] && ok "analyze --out: nothing is written into the working directory" || bad "analyze --out: nothing is written into the working directory" + +echo "# analyze.mjs" +OUT=$(node "$TOOLS/analyze.mjs" "$D" 2>&1); EC=$? +eq "analyze: exit 0" 0 "$EC" +has "analyze: the summary names repository, count and period" "$OUT" "acme/shop: 40 merged pull requests, 2026-03-01 to 2026-03-10" +has "analyze: rounds are counted for the human reviewer" "$OUT" 'rounds counted for reviewer "human"' +M="$D/metrics.json" +[ -f "$M" ] && ok "analyze: metrics.json is written" || bad "analyze: metrics.json is written" +[ -f "$D/history/2026-03-10.json" ] && ok "analyze: the run is kept under history/" || bad "analyze: the run is kept under history/" +eq "metrics: 40 merged" 40 "$(j "$M" 'm.total.merged')" +eq "metrics: 20 reviewed" 20 "$(j "$M" 'm.total.efficiency.reviewed')" +eq "metrics: half merged without review" 0.5 "$(j "$M" 'm.total.quality.noReviewShare')" +eq "metrics: the default branch is main" main "$(j "$M" 'm.defaultBranch')" +eq "metrics: 10 CI runs" 10 "$(j "$M" 'm.ci.all.runs')" +eq "metrics: one failed push to main" 1 "$(j "$M" 'm.ci.defaultBranchPush.failure')" +eq "metrics: the risk class comes from the files" 40 "$(j "$M" 'm.classes["source code"].merged')" + +echo "# rules" +rule() { j "$M" "(m.results.find((r) => r.id === '$1') || {}).$2"; } +eq "rule: merged-without-review is triggered" triggered "$(rule merged-without-review state)" +has "rule: the problem names count and denominator" "$(rule merged-without-review text)" "20 of 40 pull requests were merged without a review" +eq "rule: a sample of 40 is too small for high-fix-share" not-evaluated "$(rule high-fix-share state)" +eq "rule: the reason names both numbers" "only 40 in the sample, the rule needs 50" "$(rule high-fix-share reason)" +eq "rule: no finished later rounds -> not evaluated, not passed" not-evaluated "$(rule later-rounds-low-yield state)" +eq "rule: unresolved-threads passes" passed "$(rule unresolved-threads state)" +eq "score: the review group has one triggered rule" 1 "$(j "$M" 'm.scores.review.triggered')" + +echo "# a dated change with expect" +eq "change: one entry" 1 "$(j "$M" 'm.changes.length')" +eq "change: 12 pull requests before" 12 "$(j "$M" 'm.changes[0].before.n')" +eq "change: 12 pull requests after" 12 "$(j "$M" 'm.changes[0].after.n')" +eq "change: the unreviewed share got better" better "$(j "$M" 'm.changes[0].rows.find((r) => r.key === "noReview").verdict')" +eq "change: the expectation is confirmed" confirmed "$(j "$M" 'm.changes[0].expectation.verdict')" +eq "change: who decided it is kept" team "$(j "$M" 'm.changes[0].decidedBy')" +eq "change: a complete window is not marked incomplete" false "$(j "$M" 'm.changes[0].incomplete')" + +echo "# labels.tsv" +eq "labels: five lines read, header and comment skipped" 5 "$(j "$M" 'm.labels.total')" +eq "labels: four blocks for the reviewer" 4 "$(j "$M" 'm.labels.reviewers.human.labelled')" +eq "labels: hit rate is right of the decided (2 of 3)" 0.667 "$(j "$M" 'm.labels.reviewers.human.hitRate')" +eq "labels: one unclear block" 1 "$(j "$M" 'm.labels.reviewers.human.unclear')" +eq "labels: the failure cause is counted" 1 "$(j "$M" 'm.labels.mainFailures["flaky test"]')" + +echo "# a second run" +eq "previous: none after the first run" undefined "$(j "$M" 'typeof m.previous')" +printf '{"number":41,"title":"fix: late","body":"","createdAt":"2026-03-11T08:00:00Z","mergedAt":"2026-03-11T10:00:00Z","additions":1,"deletions":1,"changedFiles":1,"branch":"fix-41","base":"main","author":"dev","authorBot":false,"bodyTail":"","coAuthors":[],"labels":[],"commitCount":1,"commits":[{"oid":"c41","at":"2026-03-11T08:00:00Z","msg":"late"}],"reviews":[],"comments":[],"threadCount":0,"threads":[],"files":["src/a41.ts"]}\n' > "$D/prs/2026-03-11.jsonl" +node "$TOOLS/analyze.mjs" "$D" >/dev/null 2>&1 +eq "previous: the earlier period is kept" 2026-03-10 "$(j "$M" 'm.previous.period.to')" +eq "previous: its triggered rules are kept" true "$(j "$M" 'm.previous.triggered.includes("merged-without-review")')" +eq "history: the suggestion is open for two runs" 2 "$(rule merged-without-review openRuns)" + +echo "# report.mjs" +printf '[{"value":"20 of 41","tone":"warn","title":"Merged without any review","recommendation":"Require a review for source changes.","evidence":"Fixture."}]\n' > "$D/findings.json" +OUT=$(node "$TOOLS/report.mjs" "$M" "$D/report.html" --findings "$D/findings.json" 2>&1); EC=$? +eq "report: exit 0" 0 "$EC" +[ -s "$D/report.html" ] && ok "report: the file is written" || bad "report: the file is written" "$OUT" +HTML=$(cat "$D/report.html" 2>/dev/null) +has "report: the suggestions section" "$HTML" "Suggestions · " +has "report: the triggered rule is a card" "$HTML" "Merges without any review" +has "report: the analyst's finding" "$HTML" "20 of 41" +has "report: the change and its expectation" "$HTML" "every pull request is reviewed" +has "report: the hand labels" "$HTML" "Blocks checked by hand" +case "$HTML" in *"src=\"http"*|*"href=\"http"*".css"*) bad "report: self-contained (no external script or stylesheet)" ;; *) ok "report: self-contained (no external script or stylesheet)" ;; esac +OUT=$(node "$TOOLS/report.mjs" 2>&1); eq "report: no arguments -> usage, exit 2" 2 "$?" + +echo "# daily.mjs" +OUT=$(node "$TOOLS/daily.mjs" "$M" --day 2026-03-09 --out "$D/digest.md" 2>&1); EC=$? +eq "digest: exit 0" 0 "$EC" +has "digest: prints the day and the repository" "$OUT" "**Process digest 2026-03-09** · acme/shop" +has "digest: merged that day" "$OUT" "- Merged pull requests: **4**" +has "digest: the failed push on main" "$OUT" "1 of 1 runs" +[ -s "$D/digest.md" ] && ok "digest: --out writes the file" || bad "digest: --out writes the file" +OUT=$(node "$TOOLS/daily.mjs" "$M" --day 2026-03-03 2>&1); EC=$? +eq "digest: fewer than three days before -> exit 1" 1 "$EC" +has "digest: says what it needs" "$OUT" "at least three days before it" + +echo "# api.mjs without a token" +NODE_BIN=$(node -e 'console.log(process.execPath)') +mkdir -p "$T/empty" "$T/home" +OUT=$(env -i PATH="$T/empty" HOME="$T/home" "$NODE_BIN" "$TOOLS/api.mjs" 2>&1); EC=$? +eq "api: no token and no gh -> exit 2" 2 "$EC" +has "api: says how to supply one" "$OUT" "no GitHub token: set GITHUB_TOKEN" + +echo "$PASS passed, $FAIL failed" +[ "$FAIL" -eq 0 ] diff --git a/tests/skill-preambles.test.sh b/tests/skill-preambles.test.sh index 3e8a68f7..9db35e0a 100644 --- a/tests/skill-preambles.test.sh +++ b/tests/skill-preambles.test.sh @@ -41,7 +41,7 @@ MAIN="$TMP/main"; mkdir -p "$MAIN/.ytstack" echo seed > f.txt; git add -A; git commit -qm "M999-S01-T01: seed" ) >/dev/null 2>&1 || { echo FATAL fixture; exit 2; } WT="$TMP/wt"; git -C "$MAIN" worktree add -q -b wt-branch "$WT" >/dev/null 2>&1 || { echo FATAL worktree; exit 2; } -SKILLS="adopt-brownfield handoff-session init-project plan-milestone plan-task quick-task reassess-roadmap reconcile resume-session slice-milestone spawn-milestone-team summarize-task office-hours plan-ceo-review plan-eng-review retro ship document-release systematic-debugging test-driven-development verification-before-completion code-review finish-branch grill coordinate finish-lane handover-step lane-retro visual-review signal-intake incident review-lessons lesson" +SKILLS="adopt-brownfield handoff-session init-project plan-milestone plan-task quick-task reassess-roadmap reconcile resume-session slice-milestone spawn-milestone-team summarize-task office-hours plan-ceo-review plan-eng-review retro ship document-release systematic-debugging test-driven-development verification-before-completion code-review finish-branch grill coordinate finish-lane handover-step lane-retro visual-review signal-intake incident review-lessons lesson process-review coach-process" # Brownfield fixture (M010, issue #18): existing docs, no .ytstack -> >= 2 signals BF="$TMP/brown"; mkdir -p "$BF/docs/adr" @@ -516,6 +516,43 @@ REVIEWERS_END" rm -rf "$WT/.ytstack/signals"; own_reviewers_off ;; lane-retro) upstream_checks ;; + process-review) + # the one skill with Node scripts (DECISIONS 2026-11-18): the preamble says whether + # Node and a token are there and where the scripts are; it never prints the token + has "$s: the tool directory is found" "$OUT" "TOOL_DIR: $ROOT/skills/$s/../../tools/process-review" + case "$OUT" in *"HAS_NODE: yes"*|*"HAS_NODE: no"*) ok "$s: HAS_NODE is yes or no" ;; *) bad "$s: HAS_NODE is yes or no" ;; esac + has "$s: no origin in the fixture -> no repository guess" "$OUT" "REPO_GUESS: unknown" + has "$s: no earlier run" "$OUT" "PREVIOUS_RUN: none" + git -C "$WT" remote add origin git@github.com:acme/shop.git + mkdir -p "$TMP/xdg/ytstack/process-review/acme_shop"; echo '{}' > "$TMP/xdg/ytstack/process-review/acme_shop/metrics.json" + ( cd "$WT" || exit 2; env -i PATH="$PATH" HOME="$TMP/home" XDG_STATE_HOME="$TMP/xdg" GITHUB_TOKEN=secret-token-value bash "$P" 2>"$TMP/err" >"$TMP/out" ); OUT=$(cat "$TMP/out") + has "$s: the repository is read from origin" "$OUT" "REPO_GUESS: acme/shop" + has "$s: the earlier run of that repository is found" "$OUT" "PREVIOUS_RUN: $TMP/xdg/ytstack/process-review/acme_shop/metrics.json" + has "$s: GITHUB_TOKEN set -> HAS_TOKEN yes" "$OUT" "HAS_TOKEN: yes" + has "$s: the token's source is named" "$OUT" "TOKEN_SOURCE: GITHUB_TOKEN" + case "$OUT" in *secret-token-value*) bad "$s: the token is never printed" ;; *) ok "$s: the token is never printed" ;; esac + mkdir -p "$TMP/nogh" + ( cd "$WT" || exit 2; env -i PATH="$TMP/nogh:/usr/bin:/bin" HOME="$TMP/home" XDG_STATE_HOME="$TMP/xdg" bash "$P" 2>"$TMP/err" >"$TMP/out" ); OUT=$(cat "$TMP/out") + case "$(command -v -p gh 2>/dev/null)" in + /usr/bin/gh|/bin/gh) ok "$s: gh in a system directory, the no-token case is skipped" ;; + *) has "$s: no token variable and no gh -> HAS_TOKEN no" "$OUT" "HAS_TOKEN: no" ;; + esac + git -C "$WT" remote remove origin; rm -rf "$TMP/xdg/ytstack/process-review" ;; + coach-process) + # the coaching loop after process-review: the same working directory, the asks, the channels + has "$s: the tool directory is found" "$OUT" "TOOL_DIR: $ROOT/skills/$s/../../tools/process-review" + has "$s: no origin in the fixture -> no repository guess" "$OUT" "REPO_GUESS: unknown" + has "$s: no run yet" "$OUT" "METRICS: none" + has "$s: no asks yet" "$OUT" "ASKS: none" + case "$OUT" in *"HERDR: yes"*|*"HERDR: no"*) ok "$s: HERDR is yes or no" ;; *) bad "$s: HERDR is yes or no" ;; esac + git -C "$WT" remote add origin git@github.com:acme/shop.git + _CW="$TMP/xdg/ytstack/process-review/acme_shop"; mkdir -p "$_CW"; echo '{}' > "$_CW/metrics.json"; echo '[]' > "$_CW/findings.json" + printf '[{"key":"a","at":"2026-11-22"},{"key":"b","at":"2026-11-22"}]\n' > "$_CW/asks.json" + ( cd "$WT" || exit 2; env -i PATH="$PATH" HOME="$TMP/home" XDG_STATE_HOME="$TMP/xdg" bash "$P" 2>"$TMP/err" >"$TMP/out" ); OUT=$(cat "$TMP/out") + has "$s: the run of that repository is found" "$OUT" "METRICS: present" + has "$s: its findings are found" "$OUT" "FINDINGS: present" + has "$s: the recorded asks are counted" "$OUT" "ASKS: 2 recorded" + git -C "$WT" remote remove origin; rm -rf "$TMP/xdg/ytstack/process-review" ;; lesson) # the ledger and the questions (M032): every lesson in every state, the open incidents has "$s: the signals script is found" "$OUT" "SIGNALS_TOOL: $ROOT/bin/ytstack-signals" diff --git a/tools/process-review/README.md b/tools/process-review/README.md new file mode 100644 index 00000000..1e51e43c --- /dev/null +++ b/tools/process-review/README.md @@ -0,0 +1,49 @@ +# process-review tools + +The scripts behind `ytstack:process-review` (`skills/process-review/SKILL.md`). They measure a GitHub repository's development process from its merged pull requests, reviews and CI runs. The skill is the procedure; this file says what each script does. + +## Requirements + +- Node 18 or newer. No dependencies, no build step, no `gh` CLI. +- A GitHub token with read access to pull requests, reviews and Actions runs: `GITHUB_TOKEN`, else `GH_TOKEN`, else the token of a signed-in `gh` (`gh auth token`). Without one, every script that calls GitHub exits 2 with one line. `GITHUB_API_URL` replaces `https://api.github.com`. +- Everything is read-only against GitHub. All output goes to the working directory you name; keep it outside the repository. + +These are the only Node scripts of the plugin (`.ytstack/DECISIONS.md`, 2026-11-18). Nothing else in ytstack needs Node. + +## Order of use + +```bash +node mine.mjs [--only prs|ci] [--refresh] +node analyze.mjs [--since d] [--until d] [--out file] [--prev file] +node mine-failures.mjs [--days 7] [--max 150] # optional, then analyze.mjs again +node report.mjs /metrics.json /report.html [--findings /findings.json] +node daily.mjs /metrics.json [--day YYYY-MM-DD] [--out digest.md] +node tool-versions.mjs plugin | file '' # dates for "changes" in config.json +``` + +## The scripts + +| Script | Calls GitHub | What it does | +| --- | --- | --- | +| `api.mjs` | yes | Resolves the token and wraps the REST and GraphQL calls with retries and rate-limit waits. Imported by the two miners, not run by hand. | +| `mine.mjs` | yes | Writes merged pull requests (`prs/.jsonl`) and CI runs (`ci/.jsonl`) per day, plus `meta.json`. Resumable: a finished day is skipped, today is always read again. | +| `mine-failures.mjs` | yes | Reads the mined CI runs and fetches job and step for failed pushes to the default branch and for runs that turned green on a re-run. Writes `failures.json`. | +| `analyze.mjs` | no | Computes the metrics, evaluates the rules, compares before and after each dated change, reads `config.json`, `labels.tsv`, `asks.json`, `failures.json` and the previous `metrics.json`. Prints a summary, writes `metrics.json` and `history/.json` (with `--out` it writes only that file). | +| `rules.mjs` | no | The rules that turn metrics into suggestions, and the score per group. Imported by `analyze.mjs`. | +| `report.mjs` | no | Renders `metrics.json` (and the analyst's `findings.json`) as one self-contained HTML file: no network request, icons inlined. | +| `daily.mjs` | no | Prints the digest of one day against the seven days before it, as Markdown. Needs the day and at least three days before it. | +| `tool-versions.mjs` | no | Lists when each version of a Claude Code plugin arrived on this machine, or when a repository changed a pinned version in a file. | + +Exit codes: 2 for a usage error or a missing token, 1 when the data does not suffice (no merged pull request in range, no CI runs mined, too few days for the digest). + +## Files in the working directory + +`prs/`, `ci/`, `meta.json`, `failures.json` (mined); `config.json`, `labels.tsv`, `findings.json` (written by the analyst), `asks.json` (written by `coach-process`; formats in `skills/process-review/references/config.md`); `metrics.json`, `history/`, `report.html` (computed). + +## Tests + +`bash tests/process-review.test.sh` runs `analyze.mjs`, `report.mjs` and `daily.mjs` on a synthetic fixture and checks that `api.mjs` refuses to run without a token. It never calls GitHub and skips when `node` is absent. + +## Attribution + +`report.mjs` inlines icon outlines from the Lucide icon set (ISC licence), see `NOTICE`. diff --git a/tools/process-review/analyze.mjs b/tools/process-review/analyze.mjs new file mode 100644 index 00000000..61cbd68c --- /dev/null +++ b/tools/process-review/analyze.mjs @@ -0,0 +1,548 @@ +#!/usr/bin/env node +// Computes throughput, efficiency and quality metrics from the files mine.mjs wrote. +// Usage: node analyze.mjs [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out metrics.json] +// Reads /config.json when present (references/config.md). Prints a summary, writes metrics.json. +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { evaluate } from "./rules.mjs"; + +const args = process.argv.slice(2); +const dir = args[0]; +const opt = (k, d) => (args.includes(k) ? args[args.indexOf(k) + 1] : d); +if (!dir) { console.error("usage: analyze.mjs [--since d] [--until d] [--out file]"); process.exit(2); } +const cfg = existsSync(`${dir}/config.json`) ? JSON.parse(readFileSync(`${dir}/config.json`, "utf8")) : {}; +const since = opt("--since", "0000"), until = opt("--until", "9999"); +const load = (sub) => !existsSync(`${dir}/${sub}`) ? [] : readdirSync(`${dir}/${sub}`).filter((f) => f.endsWith(".jsonl")).sort() + .flatMap((f) => readFileSync(`${dir}/${sub}/${f}`, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l))); +const uniq = (rows, key) => [...new Map(rows.map((r) => [r[key], r])).values()]; +const inRange = (iso) => iso.slice(0, 10) >= since && iso.slice(0, 10) <= until; +const prs = uniq(load("prs"), "number").filter((p) => inRange(p.mergedAt)).sort((a, b) => a.mergedAt.localeCompare(b.mergedAt)); +const runs = uniq(load("ci"), "id").filter((r) => inRange(r.createdAt)); +if (!prs.length) { console.error("no merged pull requests in range"); process.exit(1); } + +// ---- helpers +const hours = (a, b) => (new Date(b) - new Date(a)) / 36e5; +const sorted = (a) => [...a].filter(Number.isFinite).sort((x, y) => x - y); +const q = (a, p) => { const s = sorted(a); return s.length ? s[Math.min(s.length - 1, Math.floor(s.length * p))] : null; }; +const med = (a) => q(a, 0.5); +const mean = (a) => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : null); +const share = (n, d) => (d ? n / d : null); +const r1 = (n) => (n === null ? null : Math.round(n * 10) / 10); +const r3 = (n) => (n === null ? null : Math.round(n * 1000) / 1000); +const monday = (iso) => { const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`); return new Date(+d - ((d.getUTCDay() + 6) % 7) * 864e5).toISOString().slice(0, 10); }; +const count = (rows, f) => rows.filter(f).length; + +// ---- who reviewed: configured rules first, then bots by login, then humans other than the author +const rules = (cfg.reviewers ?? []).map((r) => ({ ...r, re: r.bodyMatch && new RegExp(r.bodyMatch, "i"), ig: r.ignoreBody && new RegExp(r.ignoreBody, "i"), cm: r.cleanMatch && new RegExp(r.cleanMatch, "i") })); +// a bot's notice that it did not review is not a review +const noticeRe = new RegExp(cfg.noticePattern ?? "usage limits?|couldn't run|could not run|rate limit|quota (exceeded|reached)|out of credits|review skipped", "i"); +function kindOf(ev, pr) { + // an inline thread is attributed through the body of the review it was posted with + const head = (ev.reviewBody || ev.body || "").slice(0, 300); + for (const r of rules) { + if (r.login && r.login !== ev.by) continue; + if (r.re && !r.re.test(head)) continue; + if (!r.login && !r.re) continue; + return r.ig?.test(head) ? null : { name: r.name, ruled: true, clean: Boolean(r.cm?.test(head)) }; + } + if (ev.bot) return noticeRe.test(head) ? null : { name: ev.by, ruled: false }; + if (ev.by === pr.author) return null; + return { name: "human", ruled: false }; +} +const fcfg = cfg.findings && { re: new RegExp(cfg.findings.pattern, "u"), blocking: cfg.findings.blockingGroups ?? [1] }; +const findings = (body) => { const m = fcfg && body.match(fcfg.re); return m ? m.slice(1).map(Number) : null; }; +const blockingOf = (n) => fcfg.blocking.reduce((s, g) => s + (n[g - 1] ?? 0), 0); +const headAt = (pr, at) => { let h = ""; for (const c of pr.commits) if (c.at <= at) h = c.oid; return h; }; +const STATE = { CHANGES_REQUESTED: 3, APPROVED: 2, COMMENTED: 1 }; + +const fixRe = new RegExp(cfg.fixPattern ?? "^(fix|hotfix|bugfix|revert)\\b|^Revert \"", "i"); +const revertRe = /^revert\b|^Revert "/i; +const testRe = new RegExp(cfg.testPattern ?? "(^|/)(tests?|__tests__|e2e|spec)/|[._-](test|spec)\\.[a-z]+$|_test\\.[a-z]+$", "i"); +const srcRe = new RegExp(cfg.sourcePattern ?? "\\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|rb|php|cs|swift|c|cc|cpp|h|scala|sql)$", "i"); +const ignoreRe = new RegExp(cfg.ignorePaths ?? "(^|/)(pnpm-lock\\.yaml|package-lock\\.json|yarn\\.lock|Cargo\\.lock|go\\.sum|poetry\\.lock|CHANGELOG\\.md)$|\\.md$", "i"); +const plannedRe = new RegExp(cfg.plannedFollowUpPattern ?? "follow-?ups?\\b|review (r\\d|round|finding|comment)|non-?blocking|\\bnits?\\b|\\bmediums?\\b|\\blows?\\b (finding|severity)|addresses? (the )?(review|feedback)", "i"); +const docRe = new RegExp(cfg.docsPattern ?? "\\.(md|mdx|txt|rst|adoc)$|(^|/)(LICENSE|NOTICE)$", "i"); +const riskRe = new RegExp(cfg.sensitivePattern ?? "migrat|\\.sql$|(^|/)(auth|security|secrets?|permissions?|rbac|iam|payments?|billing)(/|[._-])|^\\.github/workflows/|(^|/)(k8s|helm|terraform|deploy)/|\\.tf$|(^|/)Dockerfile", "i"); + +// ---- per pull request +const rows = prs.map((p) => { + const evs = [...p.reviews.map((e) => ({ ...e, type: "review" })), ...p.comments.map((e) => ({ ...e, type: "comment" }))] + .map((e) => ({ ...e, kind: kindOf(e, p) })).filter((e) => e.kind).sort((a, b) => a.at.localeCompare(b.at)); + const threads = p.threads.map((t) => ({ ...t, kind: kindOf(t, p)?.name ?? null })); + const src = p.files.filter((f) => srcRe.test(f) && !testRe.test(f)); + // risk class by the files touched: what is the most that could break + const nonDoc = p.files.filter((f) => !docRe.test(f)); + const cls = !p.files.length ? "unknown" : nonDoc.some((f) => riskRe.test(f)) ? "sensitive" : src.length ? "source code" + : !nonDoc.length ? "docs only" : nonDoc.every((f) => testRe.test(f)) ? "tests only" : "configuration and other"; + return { + p, evs, threads, cls, day: p.mergedAt.slice(0, 10), week: monday(p.mergedAt), lead: hours(p.createdAt, p.mergedAt), + ttfr: evs.length ? Math.max(0, hours(p.createdAt, evs[0].at)) : null, size: p.additions + p.deletions, + kinds: [...new Set([...evs.map((e) => e.kind.name), ...threads.map((t) => t.kind).filter(Boolean)])], + isFix: fixRe.test(p.title), isRevert: revertRe.test(p.title), noReview: !evs.length && !threads.some((t) => t.kind), + unresolved: count(p.threads, (t) => !t.resolved), srcNoTest: src.length > 0 && !p.files.some((f) => testRe.test(f)), touchesSrc: src.length > 0, + }; +}); + +// ---- rounds: one round per reviewed head by the round reviewer +let roundKind = cfg.rounds?.kind; +if (!roundKind) { + const tally = {}; + for (const r of rows) for (const k of new Set(r.evs.filter((e) => e.type === "review" || e.kind.ruled).map((e) => e.kind.name))) tally[k] = (tally[k] ?? 0) + 1; + roundKind = (tally.human ?? 0) >= rows.length * 0.05 ? "human" : Object.entries(tally).sort((a, b) => b[1] - a[1])[0]?.[0] ?? "human"; +} +for (const r of rows) { + const byHead = new Map(); + for (const e of r.evs) { + if (e.kind.name !== roundKind || !(e.type === "review" || e.kind.ruled)) continue; + const head = e.head || headAt(r.p, e.at); + const g = byHead.get(head) ?? { head, at: e.at, n: null, state: "COMMENTED" }; + g.n = findings(e.body) ?? g.n; + if (e.kind.clean) g.cleanHit = true; + if ((STATE[e.state] ?? 0) > STATE[g.state]) g.state = e.state; + byHead.set(head, g); + } + r.roundList = [...byHead.values()].sort((a, b) => a.at.localeCompare(b.at)).map((g) => ({ + ...g, blocking: fcfg ? (g.n ? blockingOf(g.n) > 0 : null) : g.state === "CHANGES_REQUESTED", + clean: fcfg ? (g.n ? g.n.every((x) => x === 0) : null) : g.state === "APPROVED" || Boolean(g.cleanHit), + })); + r.rounds = r.roundList.length; + r.later = r.roundList.slice(1).map((g, i) => { + const between = r.p.commits.filter((c) => c.at > r.roundList[i].at && c.at <= g.at); + return { ...g, mergeOnly: between.length > 0 && between.every((c) => /^Merge /.test(c.msg)) }; + }); + r.reworkCommits = r.rounds ? count(r.p.commits, (c) => c.at > r.roundList[0].at && !/^Merge /.test(c.msg)) : 0; +} + +// ---- quality: follow-up fixes within a window (explicit "#123" link, or shared non-hot files) +const windowH = (cfg.followUpDays ?? 7) * 24; +const pathCount = {}; +for (const r of rows) for (const f of r.p.files) pathCount[f] = (pathCount[f] ?? 0) + 1; +const hotLimit = Math.max(5, rows.length * 0.05); +const cold = (f) => !ignoreRe.test(f) && pathCount[f] <= hotLimit; +for (const r of rows) r.cold = new Set(r.p.files.filter(cold)); +for (const f of rows.filter((r) => r.isFix)) { + const refs = new Set([...`${f.p.title}\n${f.p.body}`.matchAll(/#(\d+)\b/g)].map((m) => +m[1])); + for (const t of rows) { + if (t === f || t.p.mergedAt >= f.p.createdAt) continue; + const h = hours(t.p.mergedAt, f.p.mergedAt); + if (h > windowH) continue; + // a fix worded as the follow-up of a review finding is planned work, not a defect found after merge + if (refs.has(t.p.number)) { t.fixExplicit = true; t.fixHours = Math.min(t.fixHours ?? Infinity, h); (t.fixedBy ??= []).push(f.p.number); if (plannedRe.test(`${f.p.title}\n${f.p.body.slice(0, 600)}`)) t.fixPlanned = true; else t.fixDefect = true; } + else if ([...f.cold].some((x) => t.cold.has(x))) t.fixOverlap = true; + } +} + +// ---- CI +const defaultBranch = cfg.defaultBranch ?? Object.entries(rows.reduce((m, r) => ((m[r.p.base] = (m[r.p.base] ?? 0) + 1), m), {})).sort((a, b) => b[1] - a[1])[0][0]; +const branchOf = new Map(rows.map((r) => [r.p.branch, r])); +const ciRuns = runs.filter((r) => !cfg.ciWorkflows || cfg.ciWorkflows.includes(r.name)).map((r) => { + const min = r.status === "completed" && r.startedAt ? (new Date(r.updatedAt) - new Date(r.startedAt)) / 6e4 : null; + return { ...r, min: min !== null && min >= 0 && min < 360 ? min : null, week: monday(r.createdAt) }; +}); +for (const run of ciRuns) { const r = run.branch !== defaultBranch && branchOf.get(run.branch); if (r) (r.ci ??= []).push(run); } +for (const r of rows) { + const first = r.ci && [...r.ci].filter((c) => c.status === "completed" && c.conclusion !== "cancelled" && c.conclusion !== "skipped").sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0]; + r.firstPass = first && r.rounds && r.roundList[0].blocking !== null ? first.conclusion === "success" && r.roundList[0].blocking === false : null; + r.ciHours = r.ci ? r.ci.reduce((s, c) => s + (c.min ?? 0), 0) / 60 : null; +} +function ciStats(list) { + const done = list.filter((r) => r.status === "completed"); + const ok = count(done, (r) => r.conclusion === "success"), bad = count(done, (r) => r.conclusion === "failure"), cancelled = count(done, (r) => r.conclusion === "cancelled"); + const minutes = (f) => done.filter(f).reduce((s, r) => s + (r.min ?? 0), 0); + return { + runs: list.length, success: ok, failure: bad, cancelled, failureRate: r3(share(bad, ok + bad)), cancelledShare: r3(share(cancelled, done.length)), + rerunShare: r3(share(count(done, (r) => r.attempt > 1), done.length)), rerunGreen: count(done, (r) => r.attempt > 1 && r.conclusion === "success"), + medianMin: r1(med(done.filter((r) => r.conclusion === "success").map((r) => r.min))), p90Min: r1(q(done.filter((r) => r.conclusion === "success").map((r) => r.min), 0.9)), + hours: r1(minutes(() => true) / 60), hoursNotGreen: r1(minutes((r) => r.conclusion !== "success") / 60), + }; +} +const mainRuns = ciRuns.filter((r) => r.branch === defaultBranch && r.event === "push"); +// runs on other branches: where a cancelled run is a superseded push, not a queue the default branch drops on purpose +const prRuns = ciRuns.filter((r) => r.branch !== defaultBranch); + +// ---- aggregate +function summ(g) { + const rv = g.filter((r) => r.rounds); + const later = rv.flatMap((r) => r.later); + const withCi = g.filter((r) => r.ci); + // first attempt: the first finished CI run is green and the first review round does not block + const judged = g.filter((r) => r.firstPass !== null); + const firstPass = count(judged, (r) => r.firstPass); + return { + merged: g.length, + efficiency: { + leadMedianH: r1(med(g.map((r) => r.lead))), leadP90H: r1(q(g.map((r) => r.lead), 0.9)), + firstReviewMedianH: r1(med(g.map((r) => r.ttfr))), sizeMedian: med(g.map((r) => r.size)), commitsMedian: med(g.map((r) => r.p.commitCount)), + reviewed: rv.length, roundsMean: r1(mean(rv.map((r) => r.rounds))), multiRoundShare: r3(share(count(rv, (r) => r.rounds >= 2), rv.length)), + threePlusShare: r3(share(count(rv, (r) => r.rounds >= 3), rv.length)), + firstRoundBlockingShare: r3(share(count(rv, (r) => r.roundList[0].blocking === true), count(rv, (r) => r.roundList[0].blocking !== null))), + laterRounds: later.length, laterClean: count(later, (x) => x.clean === true), laterBlocking: count(later, (x) => x.blocking === true), + laterNonBlocking: count(later, (x) => x.blocking === false && x.clean === false), laterUnknown: count(later, (x) => x.blocking === null), + laterAfterMergeOnly: count(later, (x) => x.mergeOnly), reworkCommitsMean: r1(mean(rv.map((r) => r.reworkCommits))), + ciRunsPerPrMedian: med(withCi.map((r) => r.ci.length)), ciFailedRunShare: r3(share(withCi.reduce((s, r) => s + count(r.ci, (c) => c.conclusion === "failure"), 0), withCi.reduce((s, r) => s + count(r.ci, (c) => c.conclusion === "success" || c.conclusion === "failure"), 0))), + ciHoursPerPr: r1(mean(withCi.map((r) => r.ci.reduce((s, c) => s + (c.min ?? 0), 0) / 60))), + firstPassN: judged.length, firstPassShare: r3(share(firstPass, judged.length)), + ciLoopShare: r3(share(count(withCi, (r) => r.ci.some((c) => c.conclusion === "failure")), withCi.length)), ciJudged: withCi.length, + }, + quality: { + fixShare: r3(share(count(g, (r) => r.isFix), g.length)), reverts: count(g, (r) => r.isRevert), + followUpExplicitShare: r3(share(count(g, (r) => r.fixExplicit), g.length)), followUpOverlapShare: r3(share(count(g, (r) => r.fixExplicit || r.fixOverlap), g.length)), + followUpMedianH: r1(med(g.filter((r) => r.fixExplicit).map((r) => r.fixHours))), + followUpDefectShare: r3(share(count(g, (r) => r.fixDefect), g.length)), followUpPlannedShare: r3(share(count(g, (r) => r.fixPlanned && !r.fixDefect), g.length)), + noReviewShare: r3(share(count(g, (r) => r.noReview), g.length)), unresolvedThreadPrs: count(g, (r) => r.unresolved > 0), + sourceWithoutTestShare: r3(share(count(g, (r) => r.srcNoTest), count(g, (r) => r.touchesSrc))), + fixWithoutTestShare: r3(share(count(g, (r) => r.isFix && r.srcNoTest), count(g, (r) => r.isFix && r.touchesSrc))), + }, + }; +} +const groupBy = (list, key) => list.reduce((m, r) => ((m[r[key]] ??= []).push(r), m), {}); +const weeks = Object.fromEntries(Object.entries(groupBy(rows, "week")).sort().map(([w, g]) => [w, { ...summ(g), mainCi: ciStats(mainRuns.filter((r) => r.week === w)) }])); +const kinds = [...new Set(rows.flatMap((r) => r.kinds))].sort(); +const days = Object.fromEntries(Object.entries(groupBy(rows, "day")).sort().map(([d, g]) => [d, { merged: g.length, kinds: Object.fromEntries(kinds.map((k) => [k, count(g, (r) => r.kinds.includes(k))])) }])); +const reviewers = Object.fromEntries(kinds.map((k) => { + const th = rows.flatMap((r) => r.threads.filter((t) => t.kind === k).map((t) => ({ ...t, pr: r.p.number }))); + // a stable pseudo-random sample of threads, to judge by hand whether the findings were right + const sample = [...th].sort((a, b) => ((a.pr * 2654435761) % 9973) - ((b.pr * 2654435761) % 9973)).slice(0, cfg.sampleSize ?? 12).map((t) => ({ pr: t.pr, path: t.path, body: t.body.slice(0, 240) })); + return [k, { prs: count(rows, (r) => r.kinds.includes(k)), prShare: r3(share(count(rows, (r) => r.kinds.includes(k)), rows.length)), threads: th.length, threadsResolved: count(th, (t) => t.resolved), sample }]; +})); + +// ---- optional: two reviewers on the same head (needs findings counts) +function compareOf(list) { + if (!(cfg.compare && fcfg)) return null; + const [a, b] = cfg.compare; const m = { both: 0, onlyA: 0, onlyB: 0, neither: 0 }; const disagree = []; + for (const r of list) { + const of = (k) => r.evs.filter((e) => e.kind.name === k && findings(e.body)).map((e) => ({ head: e.head || headAt(r.p, e.at), block: blockingOf(findings(e.body)) > 0 })); + for (const x of of(a)) { const y = of(b).find((v) => v.head === x.head); if (!y) continue; + m[x.block ? (y.block ? "both" : "onlyA") : y.block ? "onlyB" : "neither"]++; if (x.block !== y.block) disagree.push({ pr: r.p.number, blocks: x.block ? a : b }); } + } + return { a, b, ...m, disagree }; +} +const compare = compareOf(rows); + +const perWorkflow = Object.fromEntries(Object.entries(groupBy(ciRuns, "name")).map(([n, g]) => [n, ciStats(g)]).sort((a, b) => b[1].hours - a[1].hours)); +const worst = (f, n = 15) => [...rows].sort((a, b) => f(b) - f(a)).slice(0, n).map((r) => ({ pr: r.p.number, title: r.p.title.slice(0, 90), rounds: r.rounds, leadH: r1(r.lead), ciRuns: r.ci?.length ?? 0 })); +const metrics = { + repo: cfg.repo ?? null, generatedAt: new Date().toISOString(), period: { from: rows[0].day, to: rows.at(-1).day }, roundKind, defaultBranch, + findingsParsed: Boolean(fcfg), markers: cfg.changes ?? cfg.markers ?? [], total: summ(rows), weeks, days, reviewers, compare, + ci: runs.length ? { all: ciStats(ciRuns), prBranches: ciStats(prRuns), defaultBranchPush: ciStats(mainRuns), perWorkflow } : null, + outliers: { mostRounds: worst((r) => r.rounds), longestLead: worst((r) => r.lead), mostCiRuns: worst((r) => r.ci?.length ?? 0) }, + followUps: rows.filter((r) => r.fixExplicit).slice(-(cfg.followUpList ?? 40)).map((r) => ({ pr: r.p.number, title: r.p.title.slice(0, 90), fixedAfterH: r1(r.fixHours), fixedBy: r.fixedBy })), +}; +// process cost per risk class +metrics.classes = Object.fromEntries(["docs only", "tests only", "configuration and other", "source code", "sensitive", "unknown"].map((c) => [c, rows.filter((r) => r.cls === c)]).filter(([, g]) => g.length) + .map(([c, g]) => { const s = summ(g); return [c, { merged: s.merged, leadMedianH: s.efficiency.leadMedianH, reviewedShare: r3(1 - s.quality.noReviewShare), roundsMean: s.efficiency.roundsMean, ciRunsMedian: s.efficiency.ciRunsPerPrMedian, ciHoursPerPr: s.efficiency.ciHoursPerPr, firstPassShare: s.efficiency.firstPassShare }]; })); +// ---- who wrote it: bot account, AI mark (co-author trailer, body footer, branch prefix), or no mark +const aiRe = new RegExp(cfg.agentPattern ?? "claude|copilot|codex|cursor|devin|aider|openhands|jules|gemini|generated with|\\[bot\\]", "i"); +for (const r of rows) { + const p = r.p; + r.signal = p.authorBot ? "bot account" : aiRe.test((p.coAuthors ?? []).join(" ")) ? "co-author trailer" : aiRe.test(p.bodyTail ?? "") ? "pull request footer" : /^(claude|codex|copilot|cursor|devin|jules)[/-]/i.test(p.branch ?? "") ? "branch prefix" : null; + r.authorClass = p.authorBot ? "bot account" : r.signal ? "AI-assisted or agent" : p.coAuthors === undefined ? "unknown (mined before author marks)" : "no AI mark"; +} +const bySignal = rows.reduce((mm, r) => (r.signal && (mm[r.signal] = (mm[r.signal] ?? 0) + 1), mm), {}); +metrics.authors = { signals: bySignal, classes: Object.fromEntries(Object.entries(groupBy(rows, "authorClass")).map(([c, g]) => { const s = summ(g); return [c, { merged: s.merged, sizeMedian: s.efficiency.sizeMedian, leadMedianH: s.efficiency.leadMedianH, roundsMean: s.efficiency.roundsMean, firstPassShare: s.efficiency.firstPassShare, followUpExplicitShare: s.quality.followUpExplicitShare, fixShare: s.quality.fixShare }]; })) }; + +// ---- what the agents spent: tokens.json (mine-tokens.mjs). Work transcripts join by branch, else worktree name, +// and split at the pull request's first review round: before = implementation, after = fix. Review transcripts +// join by the pull request they posted to and, by time, to the round they produced. +const tokenFile = `${dir}/tokens.json`; +for (const r of rows) r.roundBucket = !r.rounds ? null : r.rounds === 1 ? "1 round" : r.rounds === 2 ? "2 rounds" : "3 or more rounds"; +if (existsSync(tokenFile)) { + const tk = JSON.parse(readFileSync(tokenFile, "utf8")), prices = cfg.prices ?? {}; + const bUsd = (b) => { const p = prices[b.model]; return p ? (b.in * p.in + b.out * p.out + b.cr * p.cacheRead + b.cw * p.cacheWrite) / 1e6 : 0; }; + const sumB = (bs) => bs.reduce((s, b) => ({ usd: s.usd + bUsd(b), min: s.min + b.ms / 6e4, out: s.out + b.out, tokens: s.tokens + b.in + b.out + b.cr + b.cw }), { usd: 0, min: 0, out: 0, tokens: 0 }); + const mainModel = (bs) => { const m = {}; for (const b of bs) m[b.model] = (m[b.model] ?? 0) + bUsd(b); return Object.entries(m).sort((x, y) => y[1] - x[1])[0]?.[0] ?? "unknown"; }; + const inScope = rows.filter((r) => r.p.mergedAt >= tk.since), byNumber = new Map(inScope.map((r) => [r.p.number, r])); + const work = new Map(); for (const u of tk.units) if (u.kind === "work") (work.get(u.key) ?? work.set(u.key, []).get(u.key)).push(...u.buckets); + const users = new Map(); + for (const r of inScope) { const k = work.has("branch:" + r.p.branch) ? "branch:" + r.p.branch : work.has("worktree:" + (r.p.branch ?? "").split("/").pop()) ? "worktree:" + r.p.branch.split("/").pop() : null; if (k) { r.wk = k; users.set(k, (users.get(k) ?? 0) + 1); } } + const z = () => ({ usd: 0, min: 0, out: 0, tokens: 0 }); + for (const r of inScope) { + if (r.wk && users.get(r.wk) === 1) { // a branch shared by several pull requests cannot be split by time + const cut = r.roundList?.[0] ? Date.parse(r.roundList[0].at) : Infinity, bs = work.get(r.wk); + r.impl = sumB(bs.filter((b) => b.t + tk.bucketMs <= cut)); r.fix = sumB(bs.filter((b) => b.t + tk.bucketMs > cut)); + } + } + const reviewRuns = []; + for (const u of tk.units) if (u.kind === "review") { + const r = byNumber.get(u.pr), s = sumB(u.buckets), end = u.buckets.at(-1).t + tk.bucketMs, model = mainModel(u.buckets); + const run = { pr: u.pr, roles: u.roles, delta: u.delta, model, usd: s.usd, min: s.min, out: s.out, merged: Boolean(r) }; + if (r) { + (r.rev ??= z()); for (const f of ["usd", "min", "out", "tokens"]) r.rev[f] += s[f]; r.revRuns = (r.revRuns ?? 0) + 1; + const i = (r.roundList ?? []).findIndex((g) => Math.abs(Date.parse(g.at) - end) < 20 * 60e3 || (Date.parse(g.at) >= u.buckets[0].t && Date.parse(g.at) <= end + 20 * 60e3)); + if (i >= 0) { const g = r.roundList[i]; Object.assign(run, { round: i + 1, blocking: g.blocking, clean: g.clean, findings: g.n ? g.n.reduce((x, y) => x + y, 0) : null, lastRound: i === r.roundList.length - 1, defectAfterMerge: Boolean(r.fixDefect ?? r.fixExplicit) }); } + } + reviewRuns.push(run); + } + const allUsd = tk.units.reduce((s, u) => s + sumB(u.buckets).usd, 0), kindUsd = (f) => tk.units.filter(f).reduce((s, u) => s + sumB(u.buckets).usd, 0); + const perModel = {}; for (const u of tk.units) for (const b of u.buckets) { const x = (perModel[b.model] ??= { out: 0, usd: 0 }); x.out += b.out; x.usd += bUsd(b); } + const st = (v) => ({ n: v.length, median: r1(med(v)), p90: r1(q(v, 0.9)), mean: r1(mean(v)), sum: Math.round(v.reduce((s, x) => s + x, 0)) }); + const phases = (g) => { const w = g.filter((r) => r.impl), rv = g.filter((r) => r.rev), full = g.filter((r) => r.impl && r.rev); + return { prs: g.length, withWork: w.length, withReview: rv.length, withAll: full.length, + implUsd: st(w.map((r) => r.impl.usd)), fixUsd: st(w.map((r) => r.fix.usd)), reviewUsd: st(rv.map((r) => r.rev.usd)), + implMin: st(w.map((r) => r.impl.min)), fixMin: st(w.map((r) => r.fix.min)), reviewMin: st(rv.map((r) => r.rev.min)), + totalUsd: st(full.map((r) => r.impl.usd + r.fix.usd + r.rev.usd)), + shares: full.length ? (() => { const t = { i: 0, f: 0, v: 0 }; for (const r of full) { t.i += r.impl.usd; t.f += r.fix.usd; t.v += r.rev.usd; } const s = t.i + t.f + t.v; return { impl: r3(t.i / s), fix: r3(t.f / s), review: r3(t.v / s) }; })() : null }; }; + const matchedRuns = reviewRuns.filter((x) => x.round); + const revGroup = (g) => { const judged = g.filter((x) => x.blocking !== null && x.blocking !== undefined), last = g.filter((x) => x.lastRound); + return { runs: g.length, usdMedian: r1(med(g.map((x) => x.usd))), usdP90: r1(q(g.map((x) => x.usd), 0.9)), usdSum: Math.round(g.reduce((s, x) => s + x.usd, 0)), minMedian: r1(med(g.map((x) => x.min))), + judged: judged.length, blockingShare: r3(share(count(judged, (x) => x.blocking), judged.length)), cleanShare: r3(share(count(judged, (x) => x.clean), judged.length)), + findingsMean: r1(mean(g.filter((x) => x.findings !== null && x.findings !== undefined).map((x) => x.findings))), + usdPerBlockingRun: count(judged, (x) => x.blocking) ? r1(judged.reduce((s, x) => s + x.usd, 0) / count(judged, (x) => x.blocking)) : null, + passedLast: last.length, defectAfterPass: r3(share(count(last, (x) => x.defectAfterMerge), last.length)) }; }; + const grp = (key, min = 5) => Object.fromEntries(Object.entries(matchedRuns.reduce((m, x) => ((m[key(x)] ??= []).push(x), m), {})).filter(([, g]) => g.length >= min).sort((x, y) => y[1].length - x[1].length).map(([k, g]) => [k, revGroup(g)])); + for (const r of inScope) if (r.impl || r.rev) { r.usd = (r.impl?.usd ?? 0) + (r.fix?.usd ?? 0) + (r.rev?.usd ?? 0); r.activeMin = (r.impl?.min ?? 0) + (r.fix?.min ?? 0) + (r.rev?.min ?? 0); } + metrics.cost = { since: tk.since, priceNote: prices.note ?? null, transcripts: tk.files, messages: tk.messages, + totalUsd: Math.round(allUsd), coordinationUsd: Math.round(kindUsd((u) => u.key === "coordination")), reviewUsd: Math.round(kindUsd((u) => u.kind === "review")), workUsd: Math.round(kindUsd((u) => u.kind === "work" && u.key !== "coordination")), + perModel: Object.fromEntries(Object.entries(perModel).filter(([, v]) => v.usd >= 1).map(([m, v]) => [m, { out: v.out, usd: Math.round(v.usd) }])), + all: phases(inScope), byClass: Object.fromEntries(Object.entries(groupBy(inScope, "cls")).map(([c, g]) => [c, phases(g)])), + byRounds: Object.fromEntries(Object.entries(groupBy(inScope.filter((r) => r.rounds), "roundBucket")).sort().map(([c, g]) => [c, phases(g)])), + review: { runs: reviewRuns.length, onMergedPrs: reviewRuns.filter((x) => x.merged).length, matchedToRound: matchedRuns.length, all: revGroup(matchedRuns), + byModel: grp((x) => x.model), byRole: grp((x) => (x.roles.length ? x.roles.join(" + ") : "role not named in the brief")), byRound: grp((x) => (x.round === 1 ? "first round" : "later round")), + byModelFirstRound: Object.fromEntries(Object.entries(matchedRuns.filter((x) => x.round === 1).reduce((m, x) => ((m[x.model] ??= []).push(x), m), {})).filter(([, g]) => g.length >= 5).map(([k, g]) => [k, revGroup(g)])) }, + costliest: inScope.filter((r) => r.usd !== undefined).sort((x, y) => y.usd - x.usd).slice(0, 10).map((r) => ({ pr: r.p.number, title: r.p.title.slice(0, 80), usd: Math.round(r.usd), impl: Math.round(r.impl?.usd ?? 0), fix: Math.round(r.fix?.usd ?? 0), review: Math.round(r.rev?.usd ?? 0), rounds: r.rounds ?? null })) }; +} + +// ---- which model wrote it: the co-author trailers that name a tool or model; one name, several ("mixed") or none +const modelRe = new RegExp(cfg.modelPattern ?? cfg.agentPattern ?? "claude|gpt|codex|gemini|copilot|cursor|devin|aider|openhands|jules|llama|mistral", "i"); +for (const r of rows) { + const names = [...new Set((r.p.coAuthors ?? []).filter((n) => modelRe.test(n)).map((n) => n.trim()))]; + r.model = r.p.authorBot ? "bot account" : names.length === 1 ? names[0] : names.length > 1 ? "mixed (" + names.sort().join(" + ") + ")" : r.p.coAuthors === undefined ? "unknown (mined before author marks)" : "no model mark"; +} +{ + const minN = cfg.modelMinPrs ?? 20; + const line = (g) => { const s = summ(g); return { merged: s.merged, sizeMedian: s.efficiency.sizeMedian, leadMedianH: s.efficiency.leadMedianH, reviewed: s.efficiency.reviewed, firstRoundBlockingShare: s.efficiency.firstRoundBlockingShare, roundsMean: s.efficiency.roundsMean, firstPassShare: s.efficiency.firstPassShare, ciHoursPerPr: s.efficiency.ciHoursPerPr, followUpDefectShare: s.quality.followUpDefectShare, fixWithoutTestShare: s.quality.fixWithoutTestShare, withCost: g.filter((r) => r.usd !== undefined).length, usdMedian: r1(med(g.filter((r) => r.usd !== undefined).map((r) => r.usd))), activeMinMedian: r1(med(g.filter((r) => r.usd !== undefined).map((r) => r.activeMin))) }; }; + const byModel = groupBy(rows, "model"); + metrics.models = { minPrs: minN, + overall: Object.fromEntries(Object.entries(byModel).map(([k, g]) => [k, { ...line(g), firstDay: g.map((r) => r.day).sort()[0], lastDay: g.map((r) => r.day).sort().pop() }])), + byClass: Object.fromEntries(Object.entries(groupBy(rows, "cls")).map(([c, cg]) => [c, Object.fromEntries(Object.entries(groupBy(cg, "model")).filter(([, g]) => g.length >= minN).map(([k, g]) => [k, line(g)]))]).filter(([, v]) => Object.keys(v).length > 1)) }; +} + +// ---- where the time goes: open -> first review -> last review -> merge (durations do not add up across medians) +const r2 = (n) => (n === null ? null : Math.round(n * 100) / 100); +const span = (list) => ({ n: list.length, medianH: r2(med(list)), p75H: r2(q(list, 0.75)), p90H: r2(q(list, 0.9)) }); +const timed = rows.filter((r) => r.evs.length); +metrics.phases = { + pickup: span(timed.map((r) => r.ttfr)), + review: span(timed.map((r) => Math.max(0, hours(r.evs[0].at, r.evs.at(-1).at <= r.p.mergedAt ? r.evs.at(-1).at : r.p.mergedAt)))), + mergeWait: span(timed.map((r) => Math.max(0, hours(r.evs.filter((e) => e.at <= r.p.mergedAt).at(-1)?.at ?? r.p.mergedAt, r.p.mergedAt)))), + lead: { ...span(rows.map((r) => r.lead)), p95H: r1(q(rows.map((r) => r.lead), 0.95)) }, +}; +const BUCKETS = [["under 15 min", 0.25], ["15 min to 1 h", 1], ["1 to 4 h", 4], ["4 h to 1 day", 24], ["1 to 3 days", 72], ["3 days to 1 week", 168], ["over 1 week", Infinity]]; +metrics.leadHistogram = BUCKETS.map(([name, max], i) => ({ name, count: count(rows, (r) => r.lead <= max && r.lead > (i ? BUCKETS[i - 1][1] : -1)) })); +// merges by weekday (0 = Monday) and hour, UTC +metrics.heat = Array.from({ length: 7 }, () => Array(24).fill(0)); +for (const r of rows) { const d = new Date(r.p.mergedAt); metrics.heat[(d.getUTCDay() + 6) % 7][d.getUTCHours()]++; } + +// ---- which later rounds pay: by risk class, and by review role where threads name one +const laterBy = (list) => { const l = list.flatMap((r) => r.later), readable = l.filter((x) => x.blocking !== null); return { laterRounds: l.length, readable: readable.length, blocking: count(readable, (x) => x.blocking), blockingShare: r3(share(count(readable, (x) => x.blocking), readable.length)) }; }; +metrics.laterYield = { byClass: Object.fromEntries(Object.entries(groupBy(rows, "cls")).map(([c, g]) => [c, laterBy(g)]).filter(([, v]) => v.laterRounds)), byRole: null }; +if (cfg.roles?.pattern) { + const roleRe = new RegExp(cfg.roles.pattern, "i"), byRole = {}; + for (const r of rows) for (const t of r.threads) { + if (t.kind !== roundKind) continue; + const role = (t.body.match(roleRe)?.[1] ?? "no role named").toLowerCase(); + // a thread is written while its review is drafted, so it belongs to the first round submitted at or after it + const i = r.roundList.findIndex((g) => g.at >= t.at), round = i < 0 ? r.roundList.length : i + 1; + const s = (byRole[role] ??= { first: 0, later: 0, changedAfter: 0, judged: 0 }); + if (round <= 1) s.first++; else s.later++; + if (t.outdated !== undefined) { s.judged++; if (t.outdated) s.changedAfter++; } + } + metrics.laterYield.byRole = byRole; +} + +// ---- what each review round found, by its position +metrics.roundYield = [1, 2, 3, 4].map((i) => { + const g = rows.map((r) => (i < 4 ? r.roundList[i - 1] : null)).filter(Boolean).concat(i === 4 ? rows.flatMap((r) => r.roundList.slice(3)) : []); + return { round: i === 4 ? "4+" : String(i), n: g.length, blocking: count(g, (x) => x.blocking === true), nonBlocking: count(g, (x) => x.blocking === false && x.clean === false), clean: count(g, (x) => x.clean === true), unknown: count(g, (x) => x.blocking === null) }; +}).filter((x) => x.n); +// reviewer ledger: what a reviewer's threads led to +for (const [k, v] of Object.entries(reviewers)) { + const th = rows.flatMap((r) => r.threads.filter((t) => t.kind === k)); + const known = th.filter((t) => t.outdated !== undefined); + Object.assign(v, { prsWithThreads: count(rows, (r) => r.threads.some((t) => t.kind === k)), threadsOutdated: known.length ? count(known, (t) => t.outdated) : null, threadsJudged: known.length }); +} + +// ---- files that fixes keep returning to +const fileStat = {}; +for (const r of rows) for (const f of r.p.files) { if (ignoreRe.test(f)) continue; const s = (fileStat[f] ??= { prs: 0, fixes: 0 }); s.prs++; if (r.isFix) s.fixes++; } +metrics.hotspots = Object.entries(fileStat).filter(([, s]) => s.fixes >= 3).sort((a, b) => b[1].fixes - a[1].fixes).slice(0, 12).map(([path, s]) => ({ path, ...s })); + +// ---- how long the default branch stayed red: from the first failed push run to the next green one +const mainDone = mainRuns.filter((r) => r.conclusion === "success" || r.conclusion === "failure").sort((a, b) => a.createdAt.localeCompare(b.createdAt)); +const reds = []; let redSince = null; +for (const r of mainDone) { if (r.conclusion === "failure") redSince ??= r.createdAt; else if (redSince) { reds.push(hours(redSince, r.updatedAt)); redSince = null; } } +if (metrics.ci) metrics.ci.red = { periods: reds.length, medianH: r1(med(reds)), longestH: r1(reds.length ? Math.max(...reds) : null), totalH: r1(reds.reduce((s, x) => s + x, 0)) }; +// ---- what a change did: the same metrics in a window before and after each dated change +const W = cfg.changeWindowDays ?? 7, MIN = cfg.changeMinSample ?? 20; +const dayPlus = (d, n) => new Date(+new Date(`${d}T00:00:00Z`) + n * 864e5).toISOString().slice(0, 10); +const lastDay = rows.at(-1).day; +// rank-sum test (normal approximation) for values, two-proportion test for shares; |z| >= 1.96 counts as a clear change +function zValues(a, b) { + const all = [...a.map((v) => [v, 0]), ...b.map((v) => [v, 1])].sort((x, y) => x[0] - y[0]); let ra = 0; + for (let i = 0; i < all.length;) { let j = i; while (j < all.length && all[j][0] === all[i][0]) j++; const rank = (i + j + 1) / 2; for (let k = i; k < j; k++) if (all[k][1] === 0) ra += rank; i = j; } + const n1 = a.length, n2 = b.length, u = ra - (n1 * (n1 + 1)) / 2, sd = Math.sqrt((n1 * n2 * (n1 + n2 + 1)) / 12); + return sd ? ((n1 * n2) / 2 - u) / sd : 0; // positive: values after are higher +} +const zShares = (h1, n1, h2, n2) => { const p = (h1 + h2) / (n1 + n2), sd = Math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2)); return sd ? (h2 / n2 - h1 / n1) / sd : 0; }; +const VALUE = [["Lead time, median (h)", (r) => r.lead, med, -1], ["Review rounds per reviewed PR, mean", (r) => r.rounds || null, mean, -1], ["CI hours per PR, mean", (r) => r.ciHours, mean, -1], ["Changed lines, median", (r) => r.size, med, 0]]; +const SHARE = [["Passed on the first attempt", (r) => r.firstPass !== null, (r) => r.firstPass, 1], ["PRs with 2+ review rounds", (r) => r.rounds > 0, (r) => r.rounds >= 2, -1], ["PRs with a failed CI run", (r) => Boolean(r.ci), (r) => r.ci.some((c) => c.conclusion === "failure"), -1], + ["Merged without any review", () => true, (r) => r.noReview, -1], ["Fix PRs", () => true, (r) => r.isFix, -1], ["Fixed again by a linked fix", () => true, (r) => Boolean(r.fixExplicit), -1], ["Fixes without a test file", (r) => r.isFix && r.touchesSrc, (r) => r.srcNoTest, -1]]; +// short keys for the rows, used by "expect" in a change entry +const ROW_KEY = { "Merged per day": "mergedPerDay", "Lead time, median (h)": "lead", "Review rounds per reviewed PR, mean": "rounds", "CI hours per PR, mean": "ciHours", "Changed lines, median": "size", "Passed on the first attempt": "firstPass", "PRs with 2+ review rounds": "multiRound", "PRs with a failed CI run": "ciFailed", "Merged without any review": "noReview", "Fix PRs": "fixShare", "Fixed again by a linked fix": "followUp", "Fixes without a test file": "fixNoTest" }; +const verdict = (z, dir, n1, n2) => (n1 < MIN || n2 < MIN ? "too few" : !dir ? "context" : Math.abs(z) < 1.96 ? "no clear change" : Math.sign(z) === dir ? "better" : "worse"); +const changeList = (cfg.changes ?? cfg.markers ?? []).filter((c) => c.at >= rows[0].day && c.at <= lastDay).sort((a, b) => a.at.localeCompare(b.at)); +function judge(c, peers) { + const from = dayPlus(c.at, -W), to = dayPlus(c.at, W - 1); + const before = rows.filter((r) => r.day >= from && r.day < c.at), after = rows.filter((r) => r.day >= c.at && r.day <= to); + const out = [{ name: "Merged per day", before: r1(before.length / W), after: r1(after.length / Math.max(1, Math.min(W, (new Date(`${lastDay}T00:00:00Z`) - new Date(`${c.at}T00:00:00Z`)) / 864e5 + 1))), n1: before.length, n2: after.length, verdict: "context" }]; + for (const [name, val, stat, dir] of VALUE) { const a = before.map(val).filter((v) => v !== null && v !== undefined), b = after.map(val).filter((v) => v !== null && v !== undefined); + out.push({ name, before: a.length ? r1(stat(a)) : null, after: b.length ? r1(stat(b)) : null, n1: a.length, n2: b.length, verdict: verdict(a.length && b.length ? zValues(a, b) : 0, dir, a.length, b.length) }); } + for (const [name, of, hit, dir] of SHARE) { const a = before.filter(of), b = after.filter(of), h1 = count(a, hit), h2 = count(b, hit); + out.push({ name, share: true, before: r3(share(h1, a.length)), after: r3(share(h2, b.length)), n1: a.length, n2: b.length, verdict: verdict(a.length && b.length ? zShares(h1, a.length, h2, b.length) : 0, dir, a.length, b.length) }); } + const mb = mainDone.filter((r) => r.createdAt.slice(0, 10) >= from && r.createdAt.slice(0, 10) < c.at), ma = mainDone.filter((r) => r.createdAt.slice(0, 10) >= c.at && r.createdAt.slice(0, 10) <= to); + const f1 = count(mb, (r) => r.conclusion === "failure"), f2 = count(ma, (r) => r.conclusion === "failure"); + out.push({ name: `Failed CI on ${defaultBranch}`, share: true, before: r3(share(f1, mb.length)), after: r3(share(f2, ma.length)), n1: mb.length, n2: ma.length, verdict: verdict(mb.length && ma.length ? zShares(f1, mb.length, f2, ma.length) : 0, -1, mb.length, ma.length) }); + for (const r of out) r.key = ROW_KEY[r.name] ?? "mainFailed"; + // the change's own expectation: which metric should move which way + let expectation = null; + if (c.expect?.metric) { + const r = out.find((x) => x.key === c.expect.metric), want = c.expect.direction === "up" ? "up" : "down"; + const moved = !r || !["better", "worse"].includes(r.verdict) ? "none" : r.after > r.before ? "up" : "down"; + const verdictE = !r ? "unknown metric" : to > lastDay || r.verdict === "too few" ? "too early" : moved === want ? "confirmed" : "refuted"; + expectation = { metric: c.expect.metric, name: r?.name ?? c.expect.metric, direction: want, before: r?.before ?? null, after: r?.after ?? null, share: Boolean(r?.share), moved, verdict: verdictE }; + } + return { at: c.at, label: c.label, decidedBy: c.decidedBy ?? null, approval: c.approval ?? null, expectation, windowDays: W, before: { from, to: dayPlus(c.at, -1), n: before.length }, after: { from: c.at, to: to > lastDay ? lastDay : to, n: after.length }, + incomplete: to > lastDay, followUpsCensored: dayPlus(to, cfg.followUpDays ?? 7) > lastDay, + confounded: peers.filter((o) => o !== c && o.at >= from && o.at <= to).map((o) => `${o.label} (${o.at})`), rows: out }; +} +metrics.changes = changeList.map((c) => judge(c, changeList)); +// coaching asks (asks.json, written by the skill coach-process): each ask is judged like a change with an expectation, +// from the day it was delivered; the same key asked again counts how often the same thing had to be asked +const askFile = `${dir}/asks.json`; +const askList = (existsSync(askFile) ? JSON.parse(readFileSync(askFile, "utf8")) : []).filter((a) => a.at >= rows[0].day && a.at <= lastDay).sort((a, b) => a.at.localeCompare(b.at)); +metrics.asks = askList.map((a) => { + const j = judge({ ...a, label: a.ask, expect: a.metric ? { metric: a.metric, direction: a.direction } : a.expect }, changeList); + const same = askList.filter((o) => o.key === a.key); + return { key: a.key, at: a.at, to: a.to ?? null, ask: a.ask, ref: a.ref ?? null, times: same.length, nth: same.indexOf(a) + 1, expectation: j.expectation, incomplete: j.incomplete, confounded: j.confounded }; +}); +// candidates: merged pull requests that changed the process itself, and when each reviewer was first and last seen +const procRe = new RegExp(cfg.processPaths ?? "^\\.github/|(^|/)(AGENTS|CLAUDE|CONTRIBUTING|CODEOWNERS|REVIEW[A-Z]*)(\\.md)?$|^\\.(cursor|claude|codex|greptile)/|(^|/)(lefthook|\\.pre-commit-config|renovate|biome|eslint\\.config|vitest\\.config|playwright\\.config|turbo)\\.", "i"); +metrics.changeCandidates = { + processPrs: rows.filter((r) => r.p.files.some((f) => procRe.test(f))).slice(-(cfg.candidateList ?? 40)).map((r) => ({ at: r.day, pr: r.p.number, title: r.p.title.slice(0, 100), paths: r.p.files.filter((f) => procRe.test(f)).slice(0, 3) })), + reviewers: kinds.map((k) => { const d = rows.filter((r) => r.kinds.includes(k)).map((r) => r.day); return { reviewer: k, firstSeen: d[0], lastSeen: d.at(-1), prs: d.length }; }), +}; +metrics.meta = existsSync(`${dir}/meta.json`) ? JSON.parse(readFileSync(`${dir}/meta.json`, "utf8")) : null; + +// rules -> suggestions, and what changed since the previous report of this working directory +const outFile = opt("--out", `${dir}/metrics.json`); +// the rules judge the recent weeks, so that a suggestion describes the process as it runs now +const ruleDays = cfg.ruleWindowDays ?? 28, ruleFrom = dayPlus(lastDay, -(ruleDays - 1)); +const recentRows = rows.filter((r) => r.day >= ruleFrom), inWin = (r) => r.createdAt.slice(0, 10) >= ruleFrom; +Object.assign(metrics, evaluate({ total: summ(recentRows), defaultBranch, compare: compareOf(recentRows), + ci: runs.length ? { all: ciStats(ciRuns.filter(inWin)), prBranches: ciStats(prRuns.filter(inWin)), defaultBranchPush: ciStats(mainRuns.filter(inWin)) } : null }, cfg.rules)); +metrics.ruleWindow = { from: ruleFrom < rows[0].day ? rows[0].day : ruleFrom, to: lastDay, days: ruleDays, merged: recentRows.length }; +if (existsSync(`${dir}/failures.json`)) { + // jobs that only report that another job failed (a "require all" gate) are noise here: ignoreFailedJobs names them + const F = JSON.parse(readFileSync(`${dir}/failures.json`, "utf8")), ig = cfg.ignoreFailedJobs && new RegExp(cfg.ignoreFailedJobs, "i"), keep = (j) => !ig || !ig.test(`${j.job} › ${j.step ?? ""}`); + metrics.failures = { ...F, defaultBranch: F.defaultBranch.map((r) => ({ ...r, failed: r.failed.filter(keep) })), flaky: F.flaky.filter(keep) }; +} +const headline = (m) => ({ merged: m.total.merged, leadMedianH: m.total.efficiency.leadMedianH, roundsMean: m.total.efficiency.roundsMean, firstPassShare: m.total.efficiency.firstPassShare ?? null, + followUpExplicitShare: m.total.quality.followUpExplicitShare, mainFailureRate: m.ci?.defaultBranchPush.failureRate ?? null, notGreenShare: m.ci?.all.hours ? r3(m.ci.all.hoursNotGreen / m.ci.all.hours) : null }); +const prevFile = opt("--prev", existsSync(outFile) ? outFile : null); +if (prevFile && existsSync(prevFile)) { + const old = JSON.parse(readFileSync(prevFile, "utf8")); + // a re-run over the same period keeps the comparison it already had + const p = old.period?.to === metrics.period.to && old.period?.from === metrics.period.from ? old.previous : old.results && { generatedAt: old.generatedAt, period: old.period, headline: headline(old), triggered: old.results.filter((r) => r.state === "triggered").map((r) => r.id) }; + if (p) metrics.previous = p; +} +metrics.headline = headline(metrics); + +// ---- hand labels: was a reviewer's block right, what caused a failure on the default branch +// labels.tsv: date kind (block | main-failure) ref (pull request or run) subject (reviewer, or empty) label labelled by note +if (existsSync(`${dir}/labels.tsv`)) { + const L = readFileSync(`${dir}/labels.tsv`, "utf8").split("\n").filter((l) => l.trim() && !l.startsWith("#")).map((l) => l.split("\t")).filter((c) => c.length >= 5 && c[0] !== "date") + .map(([date, kind, ref, subject, label, by = "", note = ""]) => ({ date, kind, ref, subject, label: label.trim().toLowerCase(), by, note })); + const tallyBy = (list, f) => list.reduce((mm, x) => ((mm[f(x)] = (mm[f(x)] ?? 0) + 1), mm), {}); + const blocks = L.filter((x) => x.kind === "block"); + metrics.labels = { + total: L.length, by: tallyBy(L, (x) => x.by || "unknown"), + reviewers: Object.fromEntries(Object.entries(groupBy(blocks, "subject")).map(([k, g]) => { const right = count(g, (x) => x.label === "right"), wrong = count(g, (x) => x.label === "false alarm"); return [k || "unnamed", { labelled: g.length, right, falseAlarm: wrong, unclear: g.length - right - wrong, hitRate: r3(share(right, right + wrong)), by: tallyBy(g, (x) => x.by || "unknown") }]; })), + mainFailures: tallyBy(L.filter((x) => x.kind === "main-failure"), (x) => x.label), + }; +} + +// ---- the last eight days one by one, for the daily digest +const dayList = [...new Set(rows.map((r) => r.day))].sort().slice(-9); +metrics.daily = dayList.map((d) => { const g = rows.filter((r) => r.day === d), s = summ(g), mr = ciStats(mainRuns.filter((r) => r.createdAt.slice(0, 10) === d)); + return { day: d, merged: g.length, roundsMean: s.efficiency.roundsMean, multiRoundShare: s.efficiency.multiRoundShare, firstPassShare: s.efficiency.firstPassShare, firstPassN: s.efficiency.firstPassN, ciHoursPerPr: s.efficiency.ciHoursPerPr, leadMedianH: s.efficiency.leadMedianH, mainRuns: mr.success + mr.failure, mainFailed: mr.failure, mainFailureRate: mr.failureRate }; }); + +// ---- history of runs: how long has each suggestion been open +const histDir = `${dir}/history`; +if (!opt("--out")) { + mkdirSync(histDir, { recursive: true }); + writeFileSync(`${histDir}/${metrics.period.to}.json`, JSON.stringify({ generatedAt: metrics.generatedAt, period: metrics.period, headline: metrics.headline, triggered: metrics.results.filter((r) => r.state === "triggered").map((r) => r.id) })); + const hist = readdirSync(histDir).filter((f) => f.endsWith(".json")).sort().map((f) => JSON.parse(readFileSync(`${histDir}/${f}`, "utf8"))); + for (const r of metrics.results) { if (r.state !== "triggered") continue; let since = null, runs = 0; + for (let i = hist.length - 1; i >= 0 && hist[i].triggered.includes(r.id); i--) { since = hist[i].period.to; runs++; } + r.openSince = since; r.openRuns = runs; } + metrics.historyRuns = hist.length; +} +// ---- review sample: pull requests assigned by their number to another reviewer (config "sample") +// Compared by assignment, never by who happened to review: the number is not chosen, the reviewer that answered is. +function sampleOf() { + const s = cfg.sample; if (!s) return null; + const mod = s.modulo ?? 10, loginOf = Object.fromEntries(rules.filter((r) => r.login).map((r) => [r.name, r.login])); + const armOf = (n) => (n % mod !== 0 ? s.control : s.bots ? (Math.floor(n / mod) % 2 === 0 ? s.bots.even : s.bots.odd) : s.reviewer); + const list = rows.filter((r) => r.p.createdAt.slice(0, 10) >= s.since); + for (const r of list) { + r.arm = armOf(r.p.number); + // the first answer of a reviewer: its first review or comment, or (a bot without a finding) its thumbs-up + const firstOf = (k) => [r.evs.find((e) => e.kind.name === k)?.at, (r.p.reactions ?? []).find((x) => x.by === loginOf[k] && x.content === "THUMBS_UP")?.at].filter(Boolean).sort()[0] ?? null; + r.armAt = firstOf(r.arm); r.controlAt = r.arm === s.control ? r.armAt : firstOf(s.control); + // a bot without a finding may leave only its summary in the description: an answer without a time + const mark = s.bodyMark?.[r.arm]; + r.armSeen = Boolean(r.armAt) || Boolean(mark && `${r.p.body}\n${r.p.bodyTail ?? ""}`.includes(mark)); + const at = r.armAt ?? (r.armSeen ? null : r.controlAt); + r.sampleThreads = count(r.threads, (t) => t.kind === (r.armSeen ? r.arm : s.control)); + r.pushesAfter = at ? count(r.p.commits, (c) => c.at > at && !/^Merge /.test(c.msg)) : null; + r.answerH = at ? hours(r.p.createdAt, at) : null; + } + const arm = (name) => { + const g = list.filter((r) => r.arm === name), answered = g.filter((r) => r.armSeen || r.controlAt), known = (f) => answered.map(f).filter((x) => x !== null); + return { + assigned: g.length, byAssigned: count(g, (r) => r.armSeen && !(name !== s.control && r.controlAt)), mixed: count(g, (r) => name !== s.control && r.armSeen && r.controlAt), + fellBack: count(g, (r) => name !== s.control && !r.armSeen && r.controlAt), noReview: count(g, (r) => !r.armSeen && !r.controlAt), + leadMedianH: r1(med(g.map((r) => r.lead))), leadP90H: r1(q(g.map((r) => r.lead), 0.9)), answerMedianH: r1(med(known((r) => r.answerH))), + withThreads: count(answered, (r) => r.sampleThreads > 0), answered: answered.length, withThreadsShare: r3(share(count(answered, (r) => r.sampleThreads > 0), answered.length)), + threadsMean: r1(mean(answered.map((r) => r.sampleThreads))), pushesAfterMean: r1(mean(known((r) => r.pushesAfter))), + ciFailed: count(g, (r) => r.ci?.some((c) => c.conclusion === "failure")), ciJudged: count(g, (r) => r.ci), + defectFix: count(g, (r) => r.fixDefect), linkedFix: count(g, (r) => r.fixExplicit), sizeMedian: med(g.map((r) => r.size)), + }; + }; + const names = [s.control, ...new Set(s.bots ? [s.bots.even, s.bots.odd] : [s.reviewer])]; + const arms = Object.fromEntries(names.map((n) => [n, arm(n)])); + const c = arms[s.control], cg = list.filter((r) => r.arm === s.control); + // each bot against the control group: |z| >= 1.96 is a difference larger than chance explains + const tests = Object.fromEntries(names.slice(1).map((n) => { const a = arms[n], g = list.filter((r) => r.arm === n), enough = a.assigned >= (s.minPrs ?? 30); + return [n, { enough, lead: r1(zValues(cg.map((r) => r.lead), g.map((r) => r.lead))), withThreads: r1(zShares(c.withThreads, c.answered || 1, a.withThreads, a.answered || 1)), + defectFix: r1(zShares(c.defectFix, c.assigned || 1, a.defectFix, a.assigned || 1)), ciFailed: r1(zShares(c.ciFailed, c.ciJudged || 1, a.ciFailed, a.ciJudged || 1)) }]; })); + return { since: s.since, modulo: mod, control: s.control, target: s.target ?? null, total: list.length, arms, tests, + fellBackList: list.filter((r) => r.arm !== s.control && !r.armSeen).map((r) => r.p.number).slice(-40) }; +} +metrics.sample = sampleOf(); +writeFileSync(outFile, JSON.stringify(metrics, null, 1)); + +const pct =(x) => (x === null ? "-" : `${(x * 100).toFixed(1)} %`); +const t = metrics.total, e = t.efficiency, ql = t.quality; +console.log(`${metrics.repo ?? dir}: ${t.merged} merged pull requests, ${metrics.period.from} to ${metrics.period.to}; rounds counted for reviewer "${roundKind}"`); +console.log(`EFFICIENCY lead time median ${e.leadMedianH} h, p90 ${e.leadP90H} h; first review after ${e.firstReviewMedianH} h (median); size median ${e.sizeMedian} lines`); +console.log(` reviewed ${e.reviewed}; rounds mean ${e.roundsMean}; 2+ rounds ${pct(e.multiRoundShare)}; 3+ rounds ${pct(e.threePlusShare)}; first round blocking ${pct(e.firstRoundBlockingShare)}`); +console.log(` later rounds ${e.laterRounds}: clean ${e.laterClean}, non-blocking findings only ${e.laterNonBlocking}, blocking ${e.laterBlocking}, unknown ${e.laterUnknown}; after merge commits only ${e.laterAfterMergeOnly}`); +console.log(` CI per pull request: ${e.ciRunsPerPrMedian} runs (median), ${e.ciHoursPerPr} runner-hours (mean), failed runs ${pct(e.ciFailedRunShare)}`); +console.log(`QUALITY fix share ${pct(ql.fixShare)}; reverts ${ql.reverts}; fixed again within the window: linked ${pct(ql.followUpExplicitShare)} (median after ${ql.followUpMedianH} h), linked or same files ${pct(ql.followUpOverlapShare)}`); +console.log(` merged without any review ${pct(ql.noReviewShare)}; with unresolved threads ${ql.unresolvedThreadPrs}; source changes without a test file ${pct(ql.sourceWithoutTestShare)}, fixes without one ${pct(ql.fixWithoutTestShare)}`); +if (metrics.ci) { const m = metrics.ci.defaultBranchPush, a = metrics.ci.all; + console.log(`CI ${a.runs} runs, ${a.hours} h, of that not green ${a.hoursNotGreen} h; cancelled ${pct(a.cancelledShare)}; re-run ${pct(a.rerunShare)} (${a.rerunGreen} turned green: flake candidates)`); + console.log(` ${defaultBranch} pushes: ${m.runs} runs, failure rate ${pct(m.failureRate)}, median ${m.medianMin} min, p90 ${m.p90Min} min`); } +console.log("REVIEWERS " + Object.entries(reviewers).map(([k, v]) => `${k}: ${pct(v.prShare)} of PRs, ${v.threads} threads`).join("; ")); +if (compare) console.log(`COMPARE ${compare.a} vs ${compare.b} on the same head: both block ${compare.both}, only ${compare.a} ${compare.onlyA}, only ${compare.b} ${compare.onlyB}, neither ${compare.neither}`); +console.log(`written: ${outFile}`); diff --git a/tools/process-review/api.mjs b/tools/process-review/api.mjs new file mode 100644 index 00000000..6b8125ff --- /dev/null +++ b/tools/process-review/api.mjs @@ -0,0 +1,31 @@ +// GitHub API access without dependencies and without the gh CLI. +// Token: GITHUB_TOKEN or GH_TOKEN; when neither is set and gh is installed, `gh auth token`. +// Read access to pull requests, reviews and Actions runs is all it needs. +import { execFileSync } from "node:child_process"; + +let token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || ""; +if (!token) { try { token = execFileSync("gh", ["auth", "token"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { /* no gh */ } } +if (!token) { console.error("no GitHub token: set GITHUB_TOKEN (read access is enough) or sign in with gh"); process.exit(2); } +const BASE = process.env.GITHUB_API_URL || "https://api.github.com"; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +async function call(path, init, tries) { + for (let i = 1; ; i++) { + let res; + try { + res = await fetch(`${BASE}/${path}`, { ...init, headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "dev-process-analysis", ...(init?.headers ?? {}) } }); + } catch (e) { if (i >= tries) throw e; await sleep(15000 * i); continue; } + if (res.ok) return res.json(); + // primary rate limit: wait for the reset; secondary limit or server trouble: back off and retry + const remaining = res.headers.get("x-ratelimit-remaining"), reset = Number(res.headers.get("x-ratelimit-reset")), retry = Number(res.headers.get("retry-after")); + if ((res.status === 403 || res.status === 429) && remaining === "0" && reset) { await sleep(Math.max(1000, reset * 1000 - Date.now() + 2000)); continue; } + if (i >= tries || (res.status < 500 && res.status !== 403 && res.status !== 429)) throw new Error(`GitHub ${res.status} for ${path}: ${(await res.text()).slice(0, 200)}`); + await sleep(retry ? retry * 1000 : 20000 * i); + } +} +export const rest = (path, tries = 3) => call(path, undefined, tries); +export async function graphql(query, variables, tries = 3) { + const body = await call("graphql", { method: "POST", body: JSON.stringify({ query, variables }), headers: { "content-type": "application/json" } }, tries); + if (body.errors?.length && !body.data) throw new Error(`GitHub GraphQL: ${body.errors[0].message}`); + return body; +} diff --git a/tools/process-review/daily.mjs b/tools/process-review/daily.mjs new file mode 100644 index 00000000..00191d1f --- /dev/null +++ b/tools/process-review/daily.mjs @@ -0,0 +1,49 @@ +#!/usr/bin/env node +// The daily digest: one day against the seven days before it. Observes, recommends nothing. +// Usage: node daily.mjs [--day YYYY-MM-DD] [--out digest.md] +// Run mine.mjs, mine-failures.mjs (optional) and analyze.mjs first. Default day: the last complete day +// (yesterday when the newest mined day is today). Prints Markdown short enough for a chat message. +import { readFileSync, writeFileSync } from "node:fs"; + +const [file] = process.argv.slice(2); +const opt = (k) => (process.argv.includes(k) ? process.argv[process.argv.indexOf(k) + 1] : null); +if (!file) { console.error("usage: daily.mjs [--day YYYY-MM-DD] [--out digest.md]"); process.exit(2); } +const m = JSON.parse(readFileSync(file, "utf8")); +const today = new Date().toISOString().slice(0, 10); +const days = m.daily ?? []; +const day = opt("--day") ?? days.filter((d) => d.day < today).at(-1)?.day; +const cur = days.find((d) => d.day === day); +const base = days.filter((d) => d.day < day).slice(-7); +if (!cur || base.length < 3) { console.error(`not enough days around ${day ?? "?"}: the digest needs the day and at least three days before it`); process.exit(1); } + +const pct = (x) => (x === null || x === undefined ? "n/a" : `${(x * 100).toFixed(0)} %`); +const val = (x, unit = "") => (x === null || x === undefined ? "n/a" : `${x}${unit}`); +// a value outside the range of the days before is worth a look; inside it, it is ordinary variation +function line(name, key, fmt, worseWhen) { + const v = cur[key], prior = base.map((d) => d[key]).filter((x) => x !== null && x !== undefined); + if (v === null || v === undefined || prior.length < 3) return `- ${name}: ${fmt(v)}`; + const lo = Math.min(...prior), hi = Math.max(...prior); + const flag = v > hi ? (worseWhen === "high" ? " ⚠ above" : " ↑ above") : v < lo ? (worseWhen === "low" ? " ⚠ below" : " ↓ below") : ""; + return `- ${name}: **${fmt(v)}**${flag ? `${flag} the range of the ${prior.length} days before (${fmt(lo)} to ${fmt(hi)})` : ` (range before: ${fmt(lo)} to ${fmt(hi)})`}`; +} +const out = [`**Process digest ${day}** · ${m.repo ?? ""}`.trim(), "", + line("Merged pull requests", "merged", (x) => val(x), null), + line("Review rounds per reviewed pull request", "roundsMean", (x) => val(x), "high"), + line("Passed on the first attempt", "firstPassShare", pct, "low"), + line("CI hours per pull request", "ciHoursPerPr", (x) => val(x, " h"), "high"), + line(`Failed pushes to ${m.defaultBranch}`, "mainFailureRate", pct, "high") + (cur.mainRuns ? ` · ${cur.mainFailed} of ${cur.mainRuns} runs` : ""), +]; +const fails = (m.failures?.defaultBranch ?? []).filter((r) => r.at.slice(0, 10) === day); +if (fails.length) { + out.push("", `Failed pushes to ${m.failures.branch} that day, to be labelled (merged defect, inherited, flaky test, infrastructure):`); + for (const r of fails.slice(0, 12)) out.push(`- ${r.at.slice(11, 16)} ${r.pr ? `#${r.pr}` : r.sha} ${r.title.slice(0, 70)} · ${r.failed.map((j) => `${j.job} › ${j.step ?? "?"}`).join(" + ") || "no failed job recorded"}`); + if (fails.length > 12) out.push(`- and ${fails.length - 12} more`); +} +const newFlaky = (m.failures?.flaky ?? []).filter((j) => j.lastSeen.slice(0, 10) === day).slice(0, 5); +if (newFlaky.length) { out.push("", "Jobs that failed and passed on a re-run that day:"); for (const j of newFlaky) out.push(`- ${j.job} › ${j.step ?? "?"} (${j.count} times in the period)`); } +const pending = (m.changes ?? []).filter((c) => c.approval === "pending"); +if (pending.length) out.push("", `${pending.length} process change${pending.length > 1 ? "s await" : " awaits"} a person's approval: ${pending.map((c) => `${c.label} (${c.at})`).join("; ")}.`); +out.push("", "_A digest observes. Changes are decided in the weekly review._"); +const text = out.join("\n"); +if (opt("--out")) writeFileSync(opt("--out"), `${text}\n`); +console.log(text); diff --git a/tools/process-review/mine-failures.mjs b/tools/process-review/mine-failures.mjs new file mode 100644 index 00000000..0f415d74 --- /dev/null +++ b/tools/process-review/mine-failures.mjs @@ -0,0 +1,49 @@ +#!/usr/bin/env node +// Looks into the CI runs that need reading: which job and step failed. +// Usage: node mine-failures.mjs [--days 7] [--max 150] +// Reads /ci (from mine.mjs) and /config.json, fetches job details for +// 1. failed push runs on the default branch in the last days, with the commit that was pushed, and +// 2. runs of the whole period that turned green on a re-run (the first attempt's failed jobs: flaky candidates), +// and writes /failures.json. One request per run and attempt, so the number of runs is capped. +import { rest } from "./api.mjs"; +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; + +const [repo, dir] = process.argv.slice(2); +const opt = (k, d) => (process.argv.includes(k) ? Number(process.argv[process.argv.indexOf(k) + 1]) : d); +if (!repo?.includes("/") || !dir) { console.error("usage: mine-failures.mjs [--days 7] [--max 150]"); process.exit(2); } +const days = opt("--days", 7), max = opt("--max", 150); +const cfg = existsSync(`${dir}/config.json`) ? JSON.parse(readFileSync(`${dir}/config.json`, "utf8")) : {}; +const runs = [...new Map(readdirSync(`${dir}/ci`).filter((f) => f.endsWith(".jsonl")).sort().flatMap((f) => readFileSync(`${dir}/ci/${f}`, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l))).map((r) => [r.id, r])).values()] + .filter((r) => !cfg.ciWorkflows || cfg.ciWorkflows.includes(r.name)); +if (!runs.length) { console.error("no CI runs mined"); process.exit(1); } +const tally = {}; for (const r of runs) if (r.event === "push") tally[r.branch] = (tally[r.branch] ?? 0) + 1; +const main = cfg.defaultBranch ?? Object.entries(tally).sort((a, b) => b[1] - a[1])[0][0]; +const last = runs.map((r) => r.createdAt).sort().at(-1); +const from = new Date(+new Date(last) - days * 864e5).toISOString(); + +const gh = async (path) => { try { return await rest(path, 2); } catch { return null; } }; +// the failed jobs of one attempt, each with its first failed step +const failed = async (id, attempt) => ((await gh(`repos/${repo}/actions/runs/${id}/attempts/${attempt}/jobs?per_page=100`))?.jobs ?? []) + .filter((j) => j.conclusion === "failure" || j.conclusion === "timed_out") + .map((j) => ({ job: j.name, step: j.steps?.find((s) => s.conclusion === "failure")?.name ?? null, minutes: j.started_at && j.completed_at ? Math.round((new Date(j.completed_at) - new Date(j.started_at)) / 6e4) : null })); + +const mainFailed = runs.filter((r) => r.branch === main && r.event === "push" && r.conclusion === "failure" && r.createdAt >= from).sort((a, b) => a.createdAt.localeCompare(b.createdAt)).slice(-max); +const defaultBranch = []; for (const r of mainFailed) { + const run = await gh(`repos/${repo}/actions/runs/${r.id}`); + const title = run?.display_title ?? ""; + // the merged pull request behind the pushed commit: from the squash title, else from the commit itself + const pr = Number(title.match(/\(#(\d+)\)\s*$/)?.[1]) || (await gh(`repos/${repo}/commits/${run?.head_sha ?? r.sha}/pulls`))?.[0]?.number || null; + defaultBranch.push({ id: r.id, at: r.createdAt, sha: r.sha, attempt: r.attempt, title: title.slice(0, 140), pr, url: run?.html_url ?? null, failed: await failed(r.id, r.attempt) }); +} +console.log(`default branch: ${defaultBranch.length} failed push runs since ${from.slice(0, 10)}`); + +const rerun = runs.filter((r) => r.attempt > 1 && r.conclusion === "success").sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, max); +const flakyJobs = {}; +let read = 0; +for (const r of rerun) { + const f = await failed(r.id, 1); read++; + for (const j of f) { const k = `${j.job} › ${j.step ?? "(no failed step recorded)"}`; const s = (flakyJobs[k] ??= { job: j.job, step: j.step, count: 0, lastSeen: "", example: r.id }); s.count++; if (r.createdAt > s.lastSeen) { s.lastSeen = r.createdAt; s.example = r.id; } } +} +console.log(`re-runs that turned green: ${read} read of ${runs.filter((r) => r.attempt > 1 && r.conclusion === "success").length}`); +writeFileSync(`${dir}/failures.json`, JSON.stringify({ repo, at: new Date().toISOString(), days, from: from.slice(0, 10), branch: main, defaultBranch, rerunsRead: read, flaky: Object.values(flakyJobs).sort((a, b) => b.count - a.count) }, null, 1)); +console.log(`written: ${dir}/failures.json`); diff --git a/tools/process-review/mine-tokens.mjs b/tools/process-review/mine-tokens.mjs new file mode 100644 index 00000000..3bf2f748 --- /dev/null +++ b/tools/process-review/mine-tokens.mjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// Token usage of local Claude Code sessions, one record per transcript (a session or one subagent). +// usage: mine-tokens.mjs [--since YYYY-MM-DD] +// Reads transcripts only; counts each API message once (by message id); writes /tokens.json. +// A transcript is a "review" when it posts a review to a pull request (that number is its target) and is +// a subagent or was briefed as a review. Any other transcript is "work" and goes to the branch it ran on, else to the +// worktree it names most (at least 60 % of its worktree mentions), else to "coordination". +// Usage is kept in five-minute buckets so the analysis can split work before and after a review. +import { readdirSync, statSync, createReadStream, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createInterface } from "node:readline"; +const [root, filter, out] = process.argv.slice(2); +const si = process.argv.indexOf("--since"), since = si > 0 ? process.argv[si + 1] : "0000"; +const walk = (d) => readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(join(d, e.name)) : e.name.endsWith(".jsonl") ? [join(d, e.name)] : [])); +const files = readdirSync(root).filter((n) => n.includes(filter)).flatMap((n) => walk(join(root, n))).filter((f) => statSync(f).mtime.toISOString() >= since); +const POST = /gh pr review (\d+)|pulls\/(\d+)\/reviews[^"\\]{0,200}?(?:--input|-X POST|--method POST| -f | -F )|(?:--input|-X POST|--method POST)[^"\\]{0,200}?pulls\/(\d+)\/reviews/g; +const BRIEF = /\b(independent|delta|visual)\b[^.\n]{0,80}\breview\b|\breview of (PR|pull request)\b|^review\b/i, ROLES = ["code", "concept", "tests", "security", "visual"]; +const B = 5 * 60e3, seen = new Set(), wtBranch = {}, units = []; +for (const f of files) { + const u = { sub: f.includes("/subagents/"), buckets: new Map(), wt: {}, branches: {}, posts: {}, brief: null, lastTs: 0, n: 0 }; + const rl = createInterface({ input: createReadStream(f) }); + for await (const l of rl) { + if (l.includes(".worktrees/")) { + for (const m of l.matchAll(/\.worktrees\/([A-Za-z0-9._-]+)/g)) u.wt[m[1]] = (u.wt[m[1]] ?? 0) + 1; + for (const m of l.matchAll(/worktree add (?:-q )?-b ([A-Za-z0-9._\/-]+) [^ "\\]*\.worktrees\/([A-Za-z0-9._-]+)/g)) wtBranch[m[2]] = m[1]; + } + const isUse = l.includes('"tool_use"'); + if (isUse && (l.includes("/reviews") || l.includes("gh pr review"))) for (const m of l.matchAll(POST)) { const n = m[1] ?? m[2] ?? m[3]; u.posts[n] = (u.posts[n] ?? 0) + 1; } + if (u.brief === null && l.includes('"type":"user"')) { try { const c = JSON.parse(l).message?.content; u.brief = (typeof c === "string" ? c : (c ?? []).map((x) => x.text ?? "").join(" ")).slice(0, 600); } catch { u.brief = ""; } } + if (!l.includes('"output_tokens"')) continue; + let j; try { j = JSON.parse(l); } catch { continue; } + const us = j.message?.usage, id = j.message?.id; if (!us || !id || !j.timestamp || j.timestamp < since) continue; + if (j.gitBranch && !/^(HEAD|main|master)$/.test(j.gitBranch)) u.branches[j.gitBranch] = (u.branches[j.gitBranch] ?? 0) + 1; + const cwdWt = /\.worktrees\/([^/]+)/.exec(j.cwd ?? "")?.[1]; if (cwdWt) u.wt[cwdWt] = (u.wt[cwdWt] ?? 0) + 5; + if (seen.has(id)) continue; seen.add(id); + const t = Date.parse(j.timestamp), model = j.message.model ?? "unknown", k = Math.floor(t / B) * B + "|" + model; + const b = u.buckets.get(k) ?? { t: Math.floor(t / B) * B, model, in: 0, cw: 0, cr: 0, out: 0, ms: 0 }; + b.in += us.input_tokens ?? 0; b.cw += us.cache_creation_input_tokens ?? 0; b.cr += us.cache_read_input_tokens ?? 0; b.out += us.output_tokens ?? 0; + if (u.lastTs && t - u.lastTs < B && t > u.lastTs) b.ms += t - u.lastTs; + u.lastTs = Math.max(u.lastTs, t); u.buckets.set(k, b); u.n++; + } + if (u.n) units.push(u); +} +const top = (o) => { const e = Object.entries(o).sort((a, b) => b[1] - a[1]); const sum = e.reduce((a, x) => a + x[1], 0); return e.length && e[0][1] / sum >= 0.6 ? e[0][0] : null; }; +const records = units.map((u) => { + const pr = top(u.posts), review = Boolean(pr) && (u.sub || BRIEF.test(u.brief ?? "")); + const b = top(u.branches), w = top(u.wt); + const head = (u.brief ?? "").slice(0, 200).toLowerCase(); + return { kind: review ? "review" : "work", sub: u.sub, + ...(review ? { pr: Number(pr), roles: ROLES.filter((r) => new RegExp("\\b" + r + "\\b").test(head)), delta: /\bdelta\b|re-review|second round|round [2-9]/i.test(head) } + : { key: b ? "branch:" + b : w ? (wtBranch[w] ? "branch:" + wtBranch[w] : "worktree:" + w) : "coordination" }), + buckets: [...u.buckets.values()].sort((x, y) => x.t - y.t) }; +}); +writeFileSync(join(out, "tokens.json"), JSON.stringify({ generatedAt: new Date().toISOString(), since, bucketMs: B, files: files.length, messages: seen.size, units: records })); +console.log(`subagents with a review post ${units.filter((u) => u.sub && Object.keys(u.posts).length).length}, briefed as review ${units.filter((u) => u.sub && BRIEF.test(u.brief ?? "")).length}, both ${units.filter((u) => u.sub && Object.keys(u.posts).length && BRIEF.test(u.brief ?? "")).length}`); +console.log(`files ${files.length}, messages ${seen.size}, transcripts ${records.length}, of them reviews ${records.filter((r) => r.kind === "review").length}`); diff --git a/tools/process-review/mine.mjs b/tools/process-review/mine.mjs new file mode 100644 index 00000000..7c377443 --- /dev/null +++ b/tools/process-review/mine.mjs @@ -0,0 +1,115 @@ +#!/usr/bin/env node +// Mines merged pull requests and CI runs of a GitHub repository into per-day JSONL files. +// Usage: node mine.mjs [--only prs|ci] +// Needs: a GitHub token with read access (GITHUB_TOKEN, GH_TOKEN, or a signed-in gh). Node 18 or newer, no dependencies. +// Resumable: a finished day is skipped, today is always re-read. +import { graphql, rest } from "./api.mjs"; +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; + +const [repo, since, until, out] = process.argv.slice(2); +const only = process.argv.includes("--only") ? process.argv[process.argv.indexOf("--only") + 1] : ""; +if (!repo?.includes("/") || !/^\d{4}-\d\d-\d\d$/.test(since ?? "") || !/^\d{4}-\d\d-\d\d$/.test(until ?? "") || !out) { + console.error("usage: mine.mjs [--only prs|ci]"); + process.exit(2); +} +const today = new Date().toISOString().slice(0, 10); +const days = []; +for (let d = new Date(`${since}T00:00:00Z`); d <= new Date(`${until}T00:00:00Z`); d = new Date(+d + 864e5)) days.push(d.toISOString().slice(0, 10)); + +function save(sub, day, rows) { + mkdirSync(`${out}/${sub}`, { recursive: true }); + const f = `${out}/${sub}/${day}.jsonl`; + writeFileSync(`${f}.tmp`, rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "")); + renameSync(`${f}.tmp`, f); + console.log(`${sub} ${day} ${rows.length}`); +} +// --refresh fetches finished days again (after an update of this script added fields) +const refresh = process.argv.includes("--refresh"); +// (a day already written with the current fields is kept, so an interrupted refresh resumes) +const current = (f) => { const s = readFileSync(f, "utf8"); return !s.trim() || s.includes('"authorBot"'); }; +const done = (sub, day) => { const f = `${out}/${sub}/${day}.jsonl`; return day !== today && existsSync(f) && (!refresh || sub !== "prs" || current(f)); }; + +const QUERY = `query($q:String!,$n:Int!,$c:String){search(query:$q,type:ISSUE,first:$n,after:$c){pageInfo{hasNextPage endCursor} nodes{... on PullRequest{ + number title body createdAt mergedAt additions deletions changedFiles headRefName baseRefName author{login __typename} + labels(first:10){nodes{name}} + reactions(first:30){nodes{content createdAt user{login}}} + commits(first:100){totalCount nodes{commit{oid committedDate messageHeadline message}}} + reviews(first:40){nodes{author{login __typename} state submittedAt body commit{oid}}} + comments(first:60){nodes{author{login __typename} createdAt body}} + reviewThreads(first:60){totalCount nodes{isResolved isOutdated resolvedBy{login} path comments(first:1){nodes{author{login __typename} createdAt body pullRequestReview{body}}}}} + files(first:60){nodes{path}}}}}}`; +// cut text without leaving half an emoji behind (a lone surrogate breaks strict JSON readers such as jq) +const cut = (s, n) => (s ?? "").slice(0, n).replace(/[\uD800-\uDBFF]$/, ""); +const who = (a) => ({ by: a?.login ?? "ghost", bot: a?.__typename === "Bot" }); + +async function minePrs(day) { + const rows = []; + let cursor = ""; + let size = 20; + for (;;) { + let page; + try { + page = (await graphql(QUERY, { q: `repo:${repo} is:pr is:merged merged:${day}`, n: size, c: cursor || null }, 2)).data.search; + } catch (e) { + if (size <= 3) throw e; + size = Math.floor(size / 2); // a heavy page timed out: retry it smaller + continue; + } + for (const p of page.nodes) { + if (!p?.number) continue; + rows.push({ + number: p.number, title: p.title, body: cut(p.body, 2000), createdAt: p.createdAt, mergedAt: p.mergedAt, + additions: p.additions, deletions: p.deletions, changedFiles: p.changedFiles, branch: p.headRefName, base: p.baseRefName, + author: who(p.author).by, authorBot: who(p.author).bot, bodyTail: cut((p.body ?? "").slice(-400), 400), + // names in Co-authored-by trailers: the usual mark of an AI assistant + coAuthors: [...new Set(p.commits.nodes.flatMap(({ commit: c }) => [...(c.message ?? "").matchAll(/^co-authored-by:\s*([^<\n]+)/gim)].map((m) => m[1].trim())))].slice(0, 8), + labels: p.labels.nodes.map((l) => l.name), commitCount: p.commits.totalCount, + // a review bot without a finding answers with a reaction on the pull request, not with a review + reactions: (p.reactions?.nodes ?? []).filter((x) => x.user).map((x) => ({ by: x.user.login.replace(/\[bot\]$/, ""), content: x.content, at: x.createdAt })), + commits: p.commits.nodes.map(({ commit: c }) => ({ oid: c.oid.slice(0, 9), at: c.committedDate, msg: c.messageHeadline })), + reviews: p.reviews.nodes.map((r) => ({ ...who(r.author), state: r.state, at: r.submittedAt, head: (r.commit?.oid ?? "").slice(0, 9), body: cut(r.body, 1500) })), + comments: p.comments.nodes.map((c) => ({ ...who(c.author), at: c.createdAt, body: cut(c.body, 1500) })), + threadCount: p.reviewThreads.totalCount, + threads: p.reviewThreads.nodes.filter((t) => t.comments.nodes[0]).map((t) => ({ ...who(t.comments.nodes[0].author), resolved: t.isResolved, outdated: t.isOutdated, resolvedBy: t.resolvedBy?.login ?? null, path: t.path, at: t.comments.nodes[0].createdAt, body: cut(t.comments.nodes[0].body, 400), reviewBody: cut(t.comments.nodes[0].pullRequestReview?.body, 300) })), + files: p.files.nodes.map((f) => f.path), + }); + } + if (!page.pageInfo.hasNextPage) return rows; + cursor = page.pageInfo.endCursor; + } +} + +async function mineCi(day) { + const rows = []; + const windows = [[new Date(`${day}T00:00:00Z`), new Date(`${day}T23:59:59Z`)]]; + const iso = (d) => d.toISOString().slice(0, 19) + "Z"; + while (windows.length) { + const [a, b] = windows.shift(); + const url = (page) => `repos/${repo}/actions/runs?created=${iso(a)}..${iso(b)}&per_page=100&page=${page}`; + const first = await rest(url(1)); + if (first.total_count > 1000 && b - a > 60000) { + // the API returns at most 1000 runs per query: halve the window + const mid = new Date((+a + +b) / 2); + windows.push([a, new Date(Math.floor(+mid / 1000) * 1000)], [new Date(Math.floor(+mid / 1000) * 1000 + 1000), b]); + continue; + } + for (let page = 1, res = first; ; res = await rest(url(++page))) { + for (const r of res.workflow_runs) { + rows.push({ id: r.id, name: r.name, event: r.event, branch: r.head_branch, sha: (r.head_sha ?? "").slice(0, 9), attempt: r.run_attempt, status: r.status, conclusion: r.conclusion, createdAt: r.created_at, startedAt: r.run_started_at, updatedAt: r.updated_at }); + } + if (page * 100 >= Math.min(first.total_count, 1000) || !res.workflow_runs.length) break; + } + } + return rows; +} + +// what the merged-only view leaves out: pull requests of the period closed without a merge, and those open now +if (only !== "ci") { + const n = async (q) => (await graphql("query($q:String!){search(query:$q,type:ISSUE,first:1){issueCount}}", { q: `repo:${repo} is:pr ${q}` })).data.search.issueCount; + mkdirSync(out, { recursive: true }); + writeFileSync(`${out}/meta.json`, JSON.stringify({ repo, since, until, at: new Date().toISOString(), closedUnmerged: await n(`is:closed is:unmerged closed:${since}..${until}`), openNow: await n("is:open"), openOlderThanAWeek: await n(`is:open created:<${new Date(Date.now() - 7 * 864e5).toISOString().slice(0, 10)}`) })); +} +for (const day of days) { + if (only !== "ci" && !done("prs", day)) save("prs", day, await minePrs(day)); + if (only !== "prs" && !done("ci", day)) save("ci", day, await mineCi(day)); +} diff --git a/tools/process-review/report.mjs b/tools/process-review/report.mjs new file mode 100644 index 00000000..4d658a91 --- /dev/null +++ b/tools/process-review/report.mjs @@ -0,0 +1,345 @@ +#!/usr/bin/env node +// Renders metrics.json (from analyze.mjs) as one self-contained HTML file. +// Usage: node report.mjs [--findings findings.json] +// findings.json: [{ "value": "14 %", "tone": "good|warn|bad", "title": "...", "recommendation": "...", "evidence": "..." }] +// written by the analyst; each becomes a card with the value large and the evidence folded. +import { existsSync, readFileSync, writeFileSync } from "node:fs"; + +const [inFile, outFile] = process.argv.slice(2); +if (!inFile || !outFile) { console.error("usage: report.mjs [--findings findings.json]"); process.exit(2); } +const m = JSON.parse(readFileSync(inFile, "utf8")); +const fi = process.argv.indexOf("--findings"); +const findings = fi > 0 && existsSync(process.argv[fi + 1]) ? JSON.parse(readFileSync(process.argv[fi + 1], "utf8")) : []; + +const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); +const short = (k) => { const [, mo, d] = k.split("-"); return `${Number(d)}.${Number(mo)}.`; }; +const pct = (x) => (x === null || x === undefined ? "–" : `${(x * 100).toFixed(1)} %`); +const U = (x) => (x === null || x === undefined ? "–" : "$" + Number(x).toLocaleString("en-US")); +const num = (x, unit = "") => (x === null || x === undefined ? "–" : `${x}${unit}`); +const COLORS = ["#d97706", "#0891b2", "#7c3aed", "#c2410c", "#15803d", "#be185d", "#4f6bed", "#64748b"]; + +function bars({ keys, values, series, title, sub, width = 1080, height = 300, labelEvery = 1, unit = "", markers = [], dimLast = false, label = short }) { + const padL = 46, padR = 16, padT = 56, padB = 40; + const all = series ? series.flatMap((s) => s.values) : values; + const max = Math.max(1e-9, ...all.map((v) => v ?? 0)); + const step = 10 ** Math.floor(Math.log10(max)); const top = Math.ceil(max / step) * step; + const w = (width - padL - padR) / Math.max(1, keys.length); + const y = (v) => padT + (height - padT - padB) * (1 - (v ?? 0) / top); + let s = `${esc(title)}${esc(sub ?? "")}`; + for (let i = 0; i <= 4; i++) { const g = (top / 4) * i; s += `${+g.toFixed(2)}`; } + keys.forEach((k, i) => { + const x = padL + i * w; + if (series) { const bw = (w * 0.8) / series.length; + series.forEach((sr, j) => { const v = sr.values[i] ?? 0; s += `${k} · ${esc(sr.name)}: ${v}${unit}`; }); + } else { const v = values[i]; + s += `${k}: ${v ?? "–"}${unit}`; + if (keys.length <= 16 && v !== null && v !== undefined) s += `${v}`; } + if (i % labelEvery === 0 || i === keys.length - 1) s += `${esc(label(k))}`; + }); + // more than three changes: numbers on the lines, the legend below the charts (changeLegend) + const many = markers.length > 3; + markers.forEach((mk, n) => { + if (mk.index < 0) return; + const mx = padL + (mk.index + (mk.frac ?? 0)) * w, ty = many ? 58 + (n % 2) * 13 : 60 + n * 14, right = mx > width * 0.6, col = COLORS[(n + 3) % 8]; + s += `` + (many + ? `${n + 1}` + : `${esc(mk.label)}${mk.label ? " · " : ""}${short(mk.at)}`); + }); + if (series) { let lx = width - padR; [...series].reverse().forEach((sr) => { lx -= sr.name.length * 6.4 + 24; s += `${esc(sr.name)}`; }); } + return `${s}`; +} + +// every calendar day and week of the period, including empty ones +const dayKeys = []; for (let d = new Date(`${m.period.from}T00:00:00Z`); d <= new Date(`${m.period.to}T00:00:00Z`); d = new Date(+d + 864e5)) dayKeys.push(d.toISOString().slice(0, 10)); +const lastDays = dayKeys.slice(-42); +const weekKeys = Object.keys(m.weeks).sort(); +const mondayOf = (iso) => { const d = new Date(`${iso}T00:00:00Z`); return new Date(+d - ((d.getUTCDay() + 6) % 7) * 864e5).toISOString().slice(0, 10); }; +const dayMarkers = m.markers.map((mk) => ({ ...mk, index: lastDays.indexOf(mk.at) })); +const weekMarkers = m.markers.map((mk) => ({ ...mk, index: weekKeys.indexOf(mondayOf(mk.at)), frac: ((new Date(`${mk.at}T00:00:00Z`).getUTCDay() + 6) % 7) / 7 })); +const kindNames = Object.entries(m.reviewers).sort((a, b) => b[1].prs - a[1].prs).slice(0, 6).map(([k]) => k); +const wk = (f) => weekKeys.map((k) => f(m.weeks[k])); +const p100 = (x) => (x === null || x === undefined ? null : +(x * 100).toFixed(1)); +const small = (title, sub, values, unit) => `
${bars({ keys: weekKeys, values, title, sub, unit, width: 530, height: 240, labelEvery: Math.ceil(weekKeys.length / 8), markers: weekMarkers.map((x) => ({ ...x, label: "" })) })}
`; + +const t = m.total, e = t.efficiency, ql = t.quality, ci = m.ci; +// inline icons (Lucide outlines, ISC licence), so the file stays self-contained +const ICON = { + merge: '', + clock: '', + repeat: '', + wrench: '', + fail: '', + zap: '', + warn: '', + good: '', + trend: '', + gauge: '', + shield: '', + users: '', + play: '', + search: '', + bulb: '', + test: '', + eye: '', + undo: '', +}; +ICON.bad = ICON.fail; +const icon = (name, size = 18) => ``; +const slug = (x) => x.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").split("-").slice(0, 2).join("-"); +const h2 = (name, text) => `

${icon(name)}${esc(text)}

`; +// weekly trend as a small line; null values are skipped +function spark(values) { + const pts = values.map((v, i) => [i, v]).filter(([, v]) => v !== null && v !== undefined); + if (pts.length < 2) return ""; + const W = 132, H = 34, max = Math.max(...pts.map((p) => p[1])), min = Math.min(0, ...pts.map((p) => p[1])), n = values.length - 1; + const xy = pts.map(([i, v]) => [4 + (i / n) * (W - 8), H - 4 - ((v - min) / (max - min || 1)) * (H - 8)]); + const line = xy.map((p) => p.map((c) => c.toFixed(1)).join(",")).join(" "); + return ``; +} +// one horizontal bar split into labelled parts +function stack(title, parts) { + const total = parts.reduce((s, p) => s + (p.value ?? 0), 0); + if (!total) return ""; + return `
${esc(title)}
${parts.filter((p) => p.value).map((p) => ``).join("")}
${parts.map((p) => `${esc(p.name)} ${p.value} · ${((p.value / total) * 100).toFixed(0)} %`).join("")}
`; +} +const tile = (v, label, ic, trend, extra = "") => `
${ic ? `${icon(ic)}` : ""}${v}${esc(label)}${extra}${trend ? spark(trend) : ""}
`; +const tbl = (head, rows) => `${head.map((h) => ``).join("")}${rows.map((r) => `${r.map((c) => ``).join("")}`).join("")}
${esc(h)}
${c}
`; +const FOLD = new Set(["By role in the brief", "By round", "Review rounds", "Longest lead time", "Where"]); +const TOP = 10; +const table = (head, rows) => (FOLD.has(head[0]) ? `
Table: ${esc(head[0].toLowerCase())} (${rows.length} rows)${tbl(head, rows)}
` + : rows.length <= TOP ? tbl(head, rows) : `${tbl(head, rows.slice(0, TOP))}
Show all ${rows.length} rows: ${esc(head[0].toLowerCase())}${tbl(head, rows)}
`); +// ---- suggestions from the rules, scores per group, the pipeline as a map +const prev = m.previous ?? null; +const was = (key, fmt) => (prev && prev.headline[key] !== null && prev.headline[key] !== undefined ? `last report: ${fmt(prev.headline[key])}` : ""); +const SEV = { high: ["bad", "High"], medium: ["warn", "Medium"], low: ["", "Low"] }; +const results = m.results ?? []; +const hits = results.filter((r) => r.state === "triggered").sort((a, b) => "high medium low".indexOf(a.severity) - "high medium low".indexOf(b.severity)); +const passed = results.filter((r) => r.state === "passed"); +const skipped = results.filter((r) => r.state === "not-evaluated"); +const resolved = prev ? prev.triggered.filter((id) => passed.some((r) => r.id === id)) : []; +const card = (r) => `
${icon(r.severity === "low" ? "bulb" : SEV[r.severity][0], 14)}${SEV[r.severity][1]} · ${esc(r.group)}${r.openRuns > 1 ? `open for ${r.openRuns} runs, since ${esc(r.openSince)}` : prev ? `${prev.triggered.includes(r.id) ? "also in the last report" : "new"}` : ""} +${esc(r.name)}

${esc(r.text)}

→ ${esc(r.action)}

+
Why it matters, and the rule

${esc(r.why)}

Rule ${r.id} · threshold ${r.threshold} · sample ${r.n}${r.ref ? ` · reference: ${esc(r.ref)}` : ""}

`; +const ring = (g, label) => { const s = m.scores?.[g]; if (!s) return `
–${label} · not evaluated
`; + const c = s.score >= 80 ? "#15803d" : s.score >= 50 ? "#d97706" : "#dc2626", len = 2 * Math.PI * 20; + return `
${s.score}${label} · ${s.triggered} of ${s.evaluated} rules triggered
`; }; +function factory() { + const W = 1080, bw = 180, bh = 88, y = 64, gap = (W - 40 - 5 * bw) / 4, x = (i) => 20 + i * (bw + gap); + const st = [ + ["merge", "Pull request", `${t.merged} merged`, `${num(e.sizeMedian)} changed lines (median)`], + ["play", "CI on the branch", `${num(e.ciRunsPerPrMedian)} runs per pull request`, ci ? `${num(ci.all.medianMin, " min")} per green run` : "no CI data"], + ["eye", "Review", `${num(e.roundsMean)} rounds per pull request`, `first review after ${num(e.firstReviewMedianH, " h")}`], + ["clock", "Merge", `${num(e.leadMedianH, " h")} from open to merge`, `${num(e.leadP90H, " h")} at the 90th percentile`], + ["shield", `Branch ${m.defaultBranch}`, ci ? `${pct(ci.defaultBranchPush.failureRate)} of pushes fail CI` : "no CI data", ci ? `${num(ci.defaultBranchPush.medianMin, " min")} per green run` : ""], + ]; + const loops = [[1, e.ciLoopShare, "of the pull requests had a failed CI run", 0.2], [2, e.multiRoundShare, "needed another review round", 0.3], [4, ql.followUpExplicitShare, "were fixed again after merge", 0.1]]; + let s = ` +The pipeline and its loops${e.firstPassShare !== null && e.firstPassShare !== undefined ? `${pct(e.firstPassShare)} of ${e.firstPassN} pull requests passed on the first attempt (first CI run green, first review not blocking)` : "first-attempt pass rate: not available for this period"}`; + st.forEach(([ic, title, a, b], i) => { + s += `${ICON[ic]} +${esc(title)}${esc(a)}${esc(b)}`; + if (i < 4) s += ``; + }); + loops.forEach(([from, v, label, bad], k) => { + if (v === null || v === undefined) return; + const sx = x(from) + bw / 2, tx = x(0) + bw / 2 + (k - 1) * 34, by = y + bh + 38 + k * 40, col = v >= bad ? "#dc2626" : "#64748b"; + s += ` +${pct(v)} ${esc(label)}`; + }); + return `${s}`; +} +const dur = (h) => (h === null || h === undefined ? "–" : h < 1 ? `${Math.round(h * 60)} min` : h < 48 ? `${+h.toFixed(1)} h` : `${+(h / 24).toFixed(1)} d`); +// horizontal bars: median as the bar, 75th and 90th percentile as marks on a square-root scale +function phases() { + const P = m.phases; if (!P) return ""; + const rowsP = [["Open → first review", P.pickup], ["First → last review", P.review], ["Last review → merge", P.mergeWait], ["Open → merge (all)", P.lead]].filter(([, v]) => v?.n); + const W = 1080, left = 190, right = 150, top = 56, rh = 34, max = Math.max(0.1, ...rowsP.map(([, v]) => v.p90H ?? 0)), sx = (v) => left + Math.sqrt((v ?? 0) / max) * (W - left - right); + let s = `Where the time goesbar = median, thin line to the 90th percentile, tick = 75th percentile · hours, square-root scale · medians of phases do not add up to the total`; + rowsP.forEach(([name, v], i) => { const y = top + i * rh; + s += `${name} +${dur(v.medianH)} · p75 ${dur(v.p75H)} · p90 ${dur(v.p90H)}`; }); + return `
${s}
`; +} +function heat() { + const Hm = m.heat; if (!Hm) return ""; + const W = 1080, left = 60, top = 56, cw = (W - left - 20) / 24, ch = 22, max = Math.max(1, ...Hm.flat()), days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + let peak = [0, 0]; Hm.forEach((r, d) => r.forEach((v, h) => { if (v > Hm[peak[0]][peak[1]]) peak = [d, h]; })); + let s = `When pull requests mergemerges by weekday and hour (UTC) · busiest: ${days[peak[0]]} ${peak[1]}:00 with ${Hm[peak[0]][peak[1]]}`; + Hm.forEach((r, d) => { s += `${days[d]}`; + r.forEach((v, h) => { s += `${days[d]} ${h}:00 · ${v} merges`; }); }); + for (let h = 0; h < 24; h += 3) s += `${h}:00`; + return `
${s}
`; +} +function yieldRows() { + const Y = m.roundYield; if (!Y?.length) return ""; + const parts = [["a blocking finding", "blocking", "#dc2626"], ["only non-blocking findings", "nonBlocking", "#d97706"], ["nothing", "clean", "#64748b"], ["not readable", "unknown", "#cbd5e1"]]; + return `
What each review round found
${Y.map((r) => `
Round ${r.round} (${r.n})
${parts.filter(([, k]) => r[k]).map(([name, k, c]) => ``).join("")}
${r.n - r.unknown ? `${((r.blocking / (r.n - r.unknown)) * 100).toFixed(0)} % blocking` : "–"}
`).join("")} +
${parts.map(([name, , c]) => `${name}`).join("")}share blocking = of the rounds with a readable result
`; +} +// what each dated change did: clear changes up front, the full before/after table folded +const dayMinus = (d, n) => new Date(+new Date(`${d}T00:00:00Z`) - n * 864e5).toISOString().slice(0, 10), lastOf = m.period.to; +function changes() { + const C = m.changes ?? []; if (!C.length) return ""; + const fmt = (r, v) => (v === null || v === undefined ? "–" : r.share ? pct(v) : v); + const mark = { better: ["good", "better"], worse: ["bad", "worse"] }; + const cardC = (c) => { const clear = c.rows.filter((r) => mark[r.verdict]); + return `
${short(c.at)}${c.at.slice(0, 4)}${c.before.n} PRs before · ${c.after.n} after${c.incomplete ? 'after-window still running' : ""} +${esc(c.label)} +${c.approval === "pending" ? `

${icon("warn", 14)}awaits a person's approval${c.decidedBy ? `decided by ${esc(c.decidedBy)}` : ""}

` : c.approval ? `

${esc(c.approval)}${c.decidedBy ? ` · decided by ${esc(c.decidedBy)}` : ""}

` : ""} +${c.expectation ? `

${icon(c.expectation.verdict === "confirmed" ? "good" : c.expectation.verdict === "refuted" ? "bad" : "clock", 16)}Expected: ${esc(c.expectation.name)} goes ${c.expectation.direction}. ${fmt(c.expectation, c.expectation.before)} → ${fmt(c.expectation, c.expectation.after)}: ${esc(c.expectation.verdict)}

` : ""} +${clear.length ? `
    ${clear.map((r) => `
  • ${icon(r.verdict === "better" ? "good" : "bad", 16)}${esc(r.name)}: ${fmt(r, r.before)} → ${fmt(r, r.after)} ${mark[r.verdict][1]}
  • `).join("")}
` : `

No metric changed clearly within ${c.windowDays} days before and after.

`} +${c.confounded.length ? `

${icon("warn", 14)} ${c.confounded.length} other changes fall inside the windows; the effect cannot be attributed to this one alone.

The ${c.confounded.length} other changes

${esc(c.confounded.join(", "))}.

` : ""} +
All ${c.rows.length} metrics, before and after${tbl(["Metric", "Before", "After", "n before", "n after", "Reading"], c.rows.map((r) => [esc(r.name), fmt(r, r.before), fmt(r, r.after), r.n1, r.n2, r.verdict + (r.name.startsWith("Fixed again") && c.followUpsCensored ? " (later fixes may still come)" : "")]))}
`; }; + const cand = m.changeCandidates; + return `${h2("repeat", "Changes and their effect")} +

Each card compares the ${C[0].windowDays} days before a change with the ${C[0].windowDays} days from it on (by merge day, UTC). “Better” and “worse” are shown only where the difference is larger than chance would explain at the 5 % level (rank-sum test for values, two-proportion test for shares) and both sides hold at least ${m.changeMinSample ?? 20} cases. A change that falls together with others, or with a different mix of work, shows what happened after it, not what it caused.

+${((open, rest) => `
${open.map(cardC).join("")}
${rest.length ? `
${rest.length} dated changes without a stated expectation
${rest.map(cardC).join("")}
` : ""}`)(C.filter((c) => c.expectation), C.filter((c) => !(c.expectation)))} +${cand ? `
Process changes found in the history (${cand.processPrs.length} pull requests that touched workflows, review rules or agent instructions) -- candidates for changes in config.json${table(["Merged", "Pull request", "Files"], [...cand.processPrs].reverse().map((p) => [p.at, `${prLink(p.pr)} ${esc(p.title)}`, p.paths.map((x) => `${esc(x)}`).join(" ")]))} +${table(["Reviewer", "First seen", "Last seen", "PRs"], cand.reviewers.map((r) => [esc(r.reviewer), r.firstSeen, r.lastSeen, r.prs]))}
` : ""}`; +} +const CLASS_HELP = "Risk class by the files a pull request touches. Process cost should rise from top to bottom."; +const prLink = (n) => (m.repo ? `#${n}` : `#${n}`); + +const html = ` +${esc(m.repo ?? "Repository")} · development process + +

Development process · ${esc(m.repo ?? "")}

+

${t.merged} merged pull requests, ${m.period.from} to ${m.period.to} (days in UTC) · generated ${m.generatedAt.slice(0, 16).replace("T", " ")} UTC · review rounds counted for “${esc(m.roundKind)}”

+${findings.length ? `
At a glance
    ${findings.slice(0, 4).map((x, i) => `
  1. ${esc(x.title)}
  2. `).join("")}
` : ""} +
${tile(t.merged, "merged pull requests", "merge", wk((w) => w.merged), was("merged", (v) => v))}${tile(num(e.leadMedianH, " h"), "lead time, median", "clock", wk((w) => w.efficiency.leadMedianH).slice(-8), was("leadMedianH", (v) => `${v} h`))}${tile(num(e.roundsMean), "review rounds per reviewed PR", "repeat", wk((w) => w.efficiency.roundsMean), was("roundsMean", (v) => v))}${tile(pct(ql.followUpExplicitShare), "fixed again by a linked fix", "wrench", wk((w) => w.quality.followUpExplicitShare), was("followUpExplicitShare", pct))}${tile(ci ? pct(ci.defaultBranchPush.failureRate) : "–", `failed CI on ${m.defaultBranch}`, "fail", wk((w) => w.mainCi.failureRate), was("mainFailureRate", pct))}${tile(ci && ci.all.hours ? pct(ci.all.hoursNotGreen / ci.all.hours) : "–", "CI hours not green", "zap", wk((w) => w.efficiency.ciHoursPerPr), was("notGreenShare", pct))}
+

Lines: the value per merge week (last tile: CI hours per pull request).${prev ? ` Last report: ${prev.period.from} to ${prev.period.to}.` : ""}

+${m.meta ? `

Merged pull requests only (${t.merged}). Not in these numbers: ${m.meta.closedUnmerged} closed without a merge in the period, ${m.meta.openNow} open now, ${m.meta.openOlderThanAWeek} of them for more than a week.

` : ""} +
${factory()}
+${findings.length ? `${h2("search", "Findings")}
${findings.map((f, i) => `
${f.value ? `${["good", "warn", "bad"].includes(f.tone) ? icon(f.tone, 24) : ""}${esc(f.value)}` : ""}${esc(f.title)}${f.recommendation ? `

→ ${esc(f.recommendation)}

` : ""}${f.evidence ? `
Evidence

${esc(f.evidence)}

` : ""}
`).join("")}
` : ""} +${results.length ? `${h2("bulb", `Suggestions · ${hits.length} of ${hits.length + passed.length} rules triggered`)} +
${ring("flow", "Flow")}${ring("review", "Review")}${ring("ci", "CI")}${ring("quality", "Quality")}
+${m.ruleWindow ? `

The rules judge the last ${m.ruleWindow.days} days (${m.ruleWindow.from} to ${m.ruleWindow.to}, ${m.ruleWindow.merged} merged pull requests), so that a suggestion describes the process as it runs now. The charts below cover the whole period.

` : ""} +

Score per group: 100 × (1 − penalties ÷ (evaluated rules × 12)), with 12, 7 and 3 points for a high, medium and low rule. A rule counts once, however often it fired. The thresholds are coaching defaults unless a reference is named; change them in config.json.

+
${hits.slice(0, 3).map(card).join("")}
${hits.length > 3 ? `
${hits.length - 3} more suggestions (${[...new Set(hits.slice(3).map((r) => SEV[r.severity][1].toLowerCase()))].join(", ")})
${hits.slice(3).map(card).join("")}
` : ""} +${passed.length ? `

What works

    ${passed.map((r) => `
  • ${icon("good")}${esc(r.text)}${resolved.includes(r.id) ? " (a suggestion of the last report, now settled)" : ""}
  • `).join("")}
` : ""} +${skipped.length ? `

Not evaluated: ${skipped.map((r) => `${esc(r.name)} (${esc(r.reason)})`).join("; ")}.

` : ""}` : ""} +${changes()} +${h2("trend", "Throughput")} +
${bars({ keys: lastDays, values: lastDays.map((k) => m.days[k]?.merged ?? 0), title: "Merged per day · last 6 weeks", sub: "lighter bar = last day of the period, possibly incomplete", labelEvery: 3, markers: dayMarkers, dimLast: true })}
+
${bars({ keys: weekKeys, values: wk((w) => w.merged), title: "Merged per week (from Monday)", sub: "lighter bar = current week", markers: weekMarkers, dimLast: true })}
+${m.markers.length > 3 ? `

Changes marked in the charts: ${m.markers.map((mk, n) => `${n + 1} ${esc(mk.label)} (${short(mk.at)})`).join(" · ")}

` : ""} +${h2("gauge", "Efficiency")} +${phases()} +${m.leadHistogram ? `
${bars({ keys: m.leadHistogram.map((b) => b.name), values: m.leadHistogram.map((b) => b.count), title: "Lead time, distribution", sub: `pull requests by time from open to merge · 95th percentile ${num(m.phases?.lead.p95H, " h")}`, width: 530, height: 240, label: (k) => k.replace("under ", "<").replace("over ", ">").replace(" to ", "–").replace("days", "d").replace("day", "d").replace("week", "w").replace(" min", "m").replace(/ h/g, "h") })}
${yieldRows()}
` : ""} +${heat()} +
${tile(num(e.leadMedianH, " h"), "lead time open→merge, median", "clock")}${tile(num(e.leadP90H, " h"), "lead time, 90th percentile", "clock")}${tile(num(e.firstReviewMedianH, " h"), "until the first review, median", "eye")}${tile(num(e.roundsMean), "review rounds per reviewed PR", "repeat")}${tile(pct(e.threePlusShare), "PRs with 3 or more rounds", "repeat")}${tile(num(e.ciRunsPerPrMedian), "CI runs per PR, median", "play")}
+${stack(`What the ${e.laterRounds} later review rounds found`, [{ name: "nothing", value: e.laterClean, color: "#64748b" }, { name: "only non-blocking findings", value: e.laterNonBlocking, color: "#d97706" }, { name: "a blocking finding", value: e.laterBlocking, color: "#dc2626" }, { name: "not readable", value: e.laterUnknown, color: "#cbd5e1" }])} +${ci ? stack(`Where the ${ci.all.hours} CI hours went`, [{ name: "green runs", value: +(ci.all.hours - ci.all.hoursNotGreen).toFixed(1), color: "#15803d" }, { name: "cancelled or failed runs", value: ci.all.hoursNotGreen, color: "#dc2626" }]) : ""} +
${small("Lead time, median (h)", "per merge week", wk((w) => w.efficiency.leadMedianH), " h")}${small("Review rounds, mean", "per merge week, reviewed PRs", wk((w) => w.efficiency.roundsMean))}${small("PRs with 2+ rounds (%)", "per merge week", wk((w) => p100(w.efficiency.multiRoundShare)), " %")}${small("CI runner-hours per PR, mean", "per merge week", wk((w) => w.efficiency.ciHoursPerPr), " h")}
+

${e.laterAfterMergeOnly} later rounds followed nothing but merge commits of the base branch. First round blocking: ${pct(e.firstRoundBlockingShare)}.

+${m.classes ? `

Process cost by risk class

${table(["Risk class", "PRs", "Lead time (h, median)", "With a review", "Review rounds", "CI runs (median)", "CI hours per PR", "Passed first attempt"], Object.entries(m.classes).map(([c, v]) => [esc(c), v.merged, num(v.leadMedianH), pct(v.reviewedShare), num(v.roundsMean), num(v.ciRunsMedian), num(v.ciHoursPerPr), pct(v.firstPassShare)]))}

${CLASS_HELP} “Sensitive” means migrations, authentication and security paths, workflows and deployment files; set sensitivePattern in config.json to fit the repository.

` : ""} +${h2("shield", "Quality")} +
${tile(pct(ql.fixShare), "share of fix PRs", "wrench")}${tile(pct(ql.followUpExplicitShare), "PRs fixed again by a linked fix", "wrench")}${tile(num(ql.reverts), "reverts", "undo")}${tile(pct(ql.noReviewShare), "merged without any review", "eye")}${tile(pct(ql.fixWithoutTestShare), "fixes without a test file", "test")}${tile(ci ? pct(ci.defaultBranchPush.failureRate) : "–", `failed CI on ${m.defaultBranch}`, "fail")}
+
${small("Fix PRs (%)", "per merge week", wk((w) => p100(w.quality.fixShare)), " %")}${small("PRs fixed again by a linked fix (%)", "by merge week of the fixed PR; the last week is still open", wk((w) => p100(w.quality.followUpExplicitShare)), " %")}${small(`Failed CI on ${m.defaultBranch} (%)`, "pushes, per week", wk((w) => p100(w.mainCi.failureRate)), " %")}${small("Source changes without a test file (%)", "per merge week", wk((w) => p100(w.quality.sourceWithoutTestShare)), " %")}
+${ql.followUpDefectShare !== undefined ? stack(`The ${Math.round(ql.followUpExplicitShare * t.merged)} pull requests that a later fix names`, [{ name: "named by a fix not worded as a review follow-up (possible defect)", value: Math.round(ql.followUpDefectShare * t.merged), color: "#dc2626" }, { name: "only planned follow-ups of review findings", value: Math.round(ql.followUpPlannedShare * t.merged), color: "#64748b" }]) : ""} +

“Fixed again” counts a pull request that a later fix names by number within the window; with fixes that only touch the same files the share is ${pct(ql.followUpOverlapShare)} (an upper bound, shared files are not proof). Median time until the linked fix: ${num(ql.followUpMedianH, " h")}. ${ql.unresolvedThreadPrs} pull requests were merged with an unresolved thread.

+${m.hotspots?.length ? `

Files that fixes keep returning to

${table(["File", "Fix PRs", "All PRs"], m.hotspots.map((f) => [`${esc(f.path)}`, f.fixes, f.prs]))}` : ""} +${ci?.red?.periods ? `

${esc(m.defaultBranch)} was red ${ci.red.periods} times, from the first failed push run to the next green one: ${num(ci.red.medianH, " h")} at the median, ${num(ci.red.longestH, " h")} at the longest, ${num(ci.red.totalH, " h")} in total.

` : ""} +${h2("users", "Reviewers")} +
${bars({ keys: lastDays, series: kindNames.map((k, i) => ({ name: k, color: COLORS[i], values: lastDays.map((d) => m.days[d]?.kinds[k] ?? 0) })), title: "Who reviewed", sub: "merged PRs per day with at least one review of the kind; a PR can count in several", labelEvery: 3, markers: dayMarkers })}
+${table(["Reviewer", "PRs reviewed", "Share of all PRs", "PRs with a thread", "Threads", "Resolved", "Code changed afterwards"], Object.entries(m.reviewers).sort((a, b) => b[1].prs - a[1].prs).map(([k, v]) => [esc(k), v.prs, pct(v.prShare), v.prsWithThreads ?? "–", v.threads, v.threadsResolved, v.threadsJudged ? `${v.threadsOutdated} of ${v.threadsJudged} (${pct(v.threadsOutdated / v.threadsJudged)})` : "–"]))} +

“Code changed afterwards”: the lines a thread points at were changed by a later commit (GitHub marks the thread outdated). A cheap sign that a finding was acted on, not proof: a rebase or an unrelated edit counts too. “Resolved” says nothing where the branch rules require every thread resolved.

+${m.labels?.reviewers && Object.keys(m.labels.reviewers).length ? `

Blocks checked by hand

${table(["Reviewer", "Labelled", "Right", "False alarm", "Unclear", "Right of the decided", "Labelled by"], Object.entries(m.labels.reviewers).map(([k, v]) => [esc(k), v.labelled, v.right, v.falseAlarm, v.unclear, `${v.right} of ${v.right + v.falseAlarm}`, Object.entries(v.by).map(([b, n]) => `${esc(b)} ${n}`).join(", ")]))}

From labels.tsv. A hit rate holds only for a sample the analysis drew; cases picked by the labelling party show that such blocks exist, not how often.

` : ""} +${m.labels?.mainFailures && Object.keys(m.labels.mainFailures).length ? stack(`Labelled failures on ${m.defaultBranch}, by cause`, Object.entries(m.labels.mainFailures).map(([k, v], i) => ({ name: k, value: v, color: COLORS[i % 8] }))) : ""} +${m.laterYield ? `

Which later rounds pay

${table(["Risk class", "Later rounds", "With a readable result", "Found a blocker", "Share"], Object.entries(m.laterYield.byClass).sort((a, b) => (b[1].blockingShare ?? 0) - (a[1].blockingShare ?? 0)).map(([c, v]) => [esc(c), v.laterRounds, v.readable, v.blocking, pct(v.blockingShare)]))} +${m.laterYield.byRole ? `${table(["Review role", "Threads in round 1", "Threads in later rounds", "Share in later rounds", "Code changed afterwards"], Object.entries(m.laterYield.byRole).sort((a, b) => b[1].later - a[1].later).map(([r, v]) => [esc(r), v.first, v.later, pct(v.later / (v.first + v.later)), v.judged ? `${v.changedAfter} of ${v.judged}` : "–"]))}

A thread is one blocking finding of the round reviewer, counted for the role it names. A role whose findings come mostly in later rounds is the one a rule against later rounds would silence.

` : `

Set roles.pattern in config.json to see the same split by review role.

`}` : ""} +${m.authors && Object.keys(m.authors.classes).length ? `

By author

${table(["Author class", "PRs", "Changed lines (median)", "Lead time (h, median)", "Review rounds", "Passed first attempt", "Fixed again", "Fix PRs"], Object.entries(m.authors.classes).sort((a, b) => b[1].merged - a[1].merged).map(([c, v]) => [esc(c), v.merged, num(v.sizeMedian), num(v.leadMedianH), num(v.roundsMean), pct(v.firstPassShare), pct(v.followUpExplicitShare), pct(v.fixShare)]))} +

Detected by: ${Object.entries(m.authors.signals).map(([k, n]) => `${esc(k)} ${n}`).join(", ") || "no AI mark found"}. A pull request without a mark is not proof of a human author: some tools leave none.

` : ""} +${m.cost ? ((PH, RV) => `

What each step costs

+

From ${esc(m.cost.since)}: ${U(m.cost.totalUsd)} at list prices across ${m.cost.transcripts.toLocaleString("en-US")} local transcripts. Work in lanes ${U(m.cost.workUsd)}, review agents ${U(m.cost.reviewUsd)}, coordination ${U(m.cost.coordinationUsd)} (sessions that belong to no single worktree).

+${table(["Model", "Output tokens", "Cost"], Object.entries(m.cost.perModel).sort((a, b) => b[1].usd - a[1].usd).map(([k, v]) => [esc(k), v.out.toLocaleString("en-US"), U(v.usd)]))} +

Implementation, fix and review per pull request

+${table(["Risk class", ...["PRs", "With work transcript", "Implementation (median)", "min", "Fix after first review (median)", "min", "With review transcript", "Review (median)", "min", "All three (median)"]], [["all", m.cost.all], ...Object.entries(m.cost.byClass)].map(([k, v]) => PH(k, v)))} +${table(["Review rounds", ...["PRs", "With work transcript", "Implementation (median)", "min", "Fix after first review (median)", "min", "With review transcript", "Review (median)", "min", "All three (median)"]], Object.entries(m.cost.byRounds).map(([k, v]) => PH(k, v)))} +

Implementation is the lane's work up to the pull request's first review round, fix is its work after it, review is the review agents that posted to the pull request. Each column has its own number of pull requests, because a lane transcript and a review transcript are found independently; "all three" counts only pull requests with both (${m.cost.all.withAll}). A branch that carried several pull requests is left out of the split.

+

Review agents: price, duration, yield

+

${m.cost.review.runs} review transcripts, ${m.cost.review.matchedToRound} tied to a review round of a merged pull request.

+${table(["By model", ...["Review runs", "Cost (median)", "Cost (p90)", "Active time (min, median)", "With a severity line", "Blocked", "Findings per run", "Cost per blocking run", "Passed as last round", "Of those: defect fix after merge"]], Object.entries(m.cost.review.byModel).map(([k, v]) => RV(k, v)))} +${table(["By model, first round only", ...["Review runs", "Cost (median)", "Cost (p90)", "Active time (min, median)", "With a severity line", "Blocked", "Findings per run", "Cost per blocking run", "Passed as last round", "Of those: defect fix after merge"]], Object.entries(m.cost.review.byModelFirstRound).map(([k, v]) => RV(k, v)))} +${table(["By role in the brief", ...["Review runs", "Cost (median)", "Cost (p90)", "Active time (min, median)", "With a severity line", "Blocked", "Findings per run", "Cost per blocking run", "Passed as last round", "Of those: defect fix after merge"]], Object.entries(m.cost.review.byRole).map(([k, v]) => RV(k, v)))} +${table(["By round", ...["Review runs", "Cost (median)", "Cost (p90)", "Active time (min, median)", "With a severity line", "Blocked", "Findings per run", "Cost per blocking run", "Passed as last round", "Of those: defect fix after merge"]], Object.entries(m.cost.review.byRound).map(([k, v]) => RV(k, v)))} +

"Blocked" is the share of runs whose review carried a blocking finding, among the runs with a readable severity line. "Cost per blocking run" divides the cost of those runs by the number that blocked: what one blocking review costs, including the runs that found nothing. "Defect fix after merge" counts pull requests this run passed as their last round that later got a fix linked to them: a miss of the whole process, not proof the reviewer could have seen it. Whether a block was right is not in these numbers; that is the hand labelling in labels.tsv. Models review different work (the costlier one is likely given the harder pull requests), so read a model's row with its role and round.

+

Costliest pull requests

${table(["PR", "Title", "Total", "Implementation", "Fix", "Review", "Rounds"], m.cost.costliest.map((x) => ["#" + x.pr, esc(x.title), U(x.usd), U(x.impl), U(x.fix), U(x.review), num(x.rounds)]))} +

Cost is what the tokens would cost on the API: ${esc(m.cost.priceNote ?? "prices from config.json")} A subscription bills differently. Only Claude Code transcripts on the machine that ran the analysis are counted: other machines, Codex sessions and the review bots are missing, so totals are a lower bound. A session that sat on a branch for a long time puts all its tokens on that pull request, which is what the costliest rows usually show. Active time adds the gaps under five minutes between API messages. Read the medians.

`)((k, v) => [esc(k), v.prs, v.withWork, U(v.implUsd.median), num(v.implMin.median), U(v.fixUsd.median), num(v.fixMin.median), v.withReview, U(v.reviewUsd.median), num(v.reviewMin.median), U(v.totalUsd.median)], (k, v) => [esc(k), v.runs, U(v.usdMedian), U(v.usdP90), num(v.minMedian), v.judged, pct(v.blockingShare), num(v.findingsMean), U(v.usdPerBlockingRun), v.passedLast, pct(v.defectAfterPass)]) : ""} +${m.models && Object.keys(m.models.overall).length > 1 ? `

By model of the author

${table(["Model", "Seen", ...["PRs", "Changed lines (median)", "Lead time (h, median)", "First round blocked", "Review rounds", "Passed first attempt", "CI hours per PR", "Defect fix after merge", "Fixes without a test", "Cost per PR (USD, median)", "Active agent time (min, median)", "PRs with cost"]], Object.entries(m.models.overall).sort((a, b) => b[1].merged - a[1].merged).map(([k, v]) => [esc(k), esc(v.firstDay.slice(5) + " to " + v.lastDay.slice(5)), ...[v.merged, num(v.sizeMedian), num(v.leadMedianH), pct(v.firstRoundBlockingShare), num(v.roundsMean), pct(v.firstPassShare), num(v.ciHoursPerPr), pct(v.followUpDefectShare), pct(v.fixWithoutTestShare), num(v.usdMedian), num(v.activeMinMedian), v.withCost ?? 0]]))} +${Object.entries(m.models.byClass).map(([c, g]) => `

${esc(c)}

${table(["Model", ...["PRs", "Changed lines (median)", "Lead time (h, median)", "First round blocked", "Review rounds", "Passed first attempt", "CI hours per PR", "Defect fix after merge", "Fixes without a test", "Cost per PR (USD, median)", "Active agent time (min, median)", "PRs with cost"]], Object.entries(g).sort((a, b) => b[1].merged - a[1].merged).map(([k, v]) => [esc(k), ...[v.merged, num(v.sizeMedian), num(v.leadMedianH), pct(v.firstRoundBlockingShare), num(v.roundsMean), pct(v.firstPassShare), num(v.ciHoursPerPr), pct(v.followUpDefectShare), pct(v.fixWithoutTestShare), num(v.usdMedian), num(v.activeMinMedian), v.withCost ?? 0]]))}`).join("")} +

The model is read from the co-author trailers of a pull request's commits; several names give "mixed". Work is not assigned to models at random, and models were in use at different times, so compare only within one risk class and with the dates in "Seen" in mind. Within a class, a model with fewer than ${m.models.minPrs} pull requests is left out. Tools that leave no trailer land in "no model mark".

` : ""} +${m.sample && m.sample.total ? ((S, Z) => `

Review sample: every ${S.modulo}th pull request

+${table(["Group (by number)", "Assigned", "Reviewed by it", "Fell back", "Mixed", "No review", "Changed lines (median)", "Lead time (h, median)", "p90", "First answer after (h)", "With a thread", "Threads per PR", "Pushes after the first answer", "With a failed CI run", "Defect fix after merge"], + Object.entries(S.arms).map(([k, a]) => [esc(k), a.assigned, a.byAssigned, k === S.control ? "–" : a.fellBack, k === S.control ? "–" : a.mixed, a.noReview, num(a.sizeMedian), num(a.leadMedianH) + Z(k, "lead"), num(a.leadP90H), num(a.answerMedianH), + `${a.withThreads} of ${a.answered}${Z(k, "withThreads")}`, num(a.threadsMean), num(a.pushesAfterMean), `${a.ciFailed} of ${a.ciJudged}${Z(k, "ciFailed")}`, `${a.defectFix} of ${a.assigned}${Z(k, "defectFix")}`]))} +

Pull requests opened from ${esc(S.since)}: ${S.total}. A pull request belongs to a group by its number alone, whoever reviewed it in the end, so the groups differ only by chance and by the reviewer; "Fell back" counts those the bot did not answer and the ${esc(S.control)} took over, "Mixed" those both reviewed. ▲ and ▼ mark a difference to ${esc(S.control)} that is larger than chance explains (two-sided, 5 %); no mark means no clear difference, which with few pull requests says little${S.target ? `; the sample is planned to run until each bot has reviewed ${S.target}` : ""}. "With a thread" counts review threads of the group's reviewer: a bot opens a thread for every finding, the ${esc(S.control)} only for blocking ones, so that column compares how often the author had to answer, not how strict the reviewer is. Whether a finding was right is not in this table: read the threads. What the bots cost comes from their invoices, not from this report.${S.fellBackList.length ? ` Not answered by the bot: ${S.fellBackList.map((n) => "#" + n).join(", ")}.` : ""}

`)(m.sample, (k, f) => { const t = m.sample.tests[k]; return !t || !t.enough || Math.abs(t[f]) < 1.96 ? "" : t[f] > 0 ? " ▲" : " ▼"; }) : ""} +${m.asks?.length ? `

Coaching asks

${table(["Asked", "To", "Ask", "Metric", "Before", "After", "Verdict", "Asked so often"], [...m.asks].reverse().map((a) => [short(a.at) + a.at.slice(0, 4), esc(a.to ?? "–"), esc(a.ask), a.expectation ? esc(a.expectation.name) : "–", a.expectation ? (a.expectation.share ? pct(a.expectation.before) : num(a.expectation.before)) : "–", a.expectation ? (a.expectation.share ? pct(a.expectation.after) : num(a.expectation.after)) : "–", a.expectation ? esc(a.expectation.verdict) : "no metric", a.times > 1 ? `${a.nth} of ${a.times}` : "1"]))}

Each ask is judged like a change with an expectation, from the day it was delivered: the metric it names should move in the stated direction within the window. An ask asked more than once is bold: the same thing had to be asked again.

` : ""} +${m.compare ? `

${esc(m.compare.a)} and ${esc(m.compare.b)} on the same head: both block ${m.compare.both}, only ${esc(m.compare.a)} ${m.compare.onlyA}, only ${esc(m.compare.b)} ${m.compare.onlyB}, neither ${m.compare.neither}.

` : ""} +${ci ? `${h2("play", "CI")}${table(["Workflow", "Runs", "Failure rate", "Cancelled", "Re-run", "Median (min)", "p90 (min)", "Runner-hours", "of that not green"], Object.entries(ci.perWorkflow).slice(0, 12).map(([n, s]) => [esc(n), s.runs, pct(s.failureRate), pct(s.cancelledShare), pct(s.rerunShare), num(s.medianMin), num(s.p90Min), num(s.hours), num(s.hoursNotGreen)]))} +

Durations are the last attempt of a run, start to end, and count wall time of the run, not the sum of its jobs. ${ci.all.rerunGreen} re-runs turned green: candidates for flaky tests.

` : ""} +${ci?.prBranches ? `${table(["Where", "Runs", "Failure rate", "Cancelled", "Re-run", "Median (min)", "Runner-hours", "of that not green"], [["Pull request branches", ci.prBranches], [`Pushes to ${m.defaultBranch}`, ci.defaultBranchPush]].map(([n, s]) => [esc(n), s.runs, pct(s.failureRate), pct(s.cancelledShare), pct(s.rerunShare), num(s.medianMin), num(s.hours), num(s.hoursNotGreen)]))}

A cancelled run on a pull request branch is a superseded push. On the default branch it can be by design, where a newer merge replaces a waiting run.

` : ""} +${m.failures ? `

Failed pushes to ${esc(m.failures.branch)}, last ${m.failures.days} days

${m.failures.defaultBranch.length ? table(["Run started (UTC)", "Merge", "Failed job › step"], [...m.failures.defaultBranch].reverse().map((r) => [`${r.url ? `` : ""}${r.at.slice(0, 16).replace("T", " ")}${r.url ? "" : ""}`, `${r.pr ? prLink(r.pr) : `${esc(r.sha)}`} ${esc(r.title.slice(0, 80))}`, r.failed.map((j) => `${esc(j.job)} › ${esc(j.step ?? "–")}`).join("
") || "–"])) : `

None.

`} +

The cause is for a person to classify: a defect in that merge, a defect merged earlier that every later push inherits, a flaky test, or infrastructure. The same job failing on consecutive merges points at an inherited failure.

+${m.failures.flaky.length ? `

Jobs that failed and then passed on a re-run

${table(["Job › step", "Times", "Last seen (UTC)"], m.failures.flaky.slice(0, 15).map((j) => [`${esc(j.job)} › ${esc(j.step ?? "–")}`, j.count, j.lastSeen.slice(0, 16).replace("T", " ")]))}

From the first attempt of ${m.failures.rerunsRead} runs that turned green on a later attempt. This names the job and step; the failing test is in the log of the example runs.

` : ""}` : ""} +${h2("search", "Outliers")} +${table(["Most review rounds", "Rounds", "Lead time (h)", "CI runs"], m.outliers.mostRounds.slice(0, 10).map((o) => [`${prLink(o.pr)} ${esc(o.title)}`, o.rounds, o.leadH, o.ciRuns]))} +${table(["Longest lead time", "Rounds", "Lead time (h)", "CI runs"], m.outliers.longestLead.slice(0, 10).map((o) => [`${prLink(o.pr)} ${esc(o.title)}`, o.rounds, o.leadH, o.ciRuns]))} +${h2("search", "How to read this report")} +
How to read this. The numbers describe the process, not people. They compare this repository with its own past, not with other teams. No number here is a target: a speed figure is only good next to its quality figure. Merged pull requests only; the newest days are incomplete, a fix for them may still come.
+ +`; +const LABEL = [[/^Lines: the value/, "What the lines on the tiles show"], [/^The rules judge/, "Which period the rules judge"], [/^Score per group/, "How the scores are computed"], [/^Each card compares/, "How before and after are compared"], [/^Changes marked/, "Key to the numbered change markers"], + [/Fixed again. counts/, "How “fixed again” is counted"], [/Code changed afterwards.:/, "How to read “code changed afterwards”"], [/^Detected by/, "How author classes are detected"], [/^Implementation is the lane/, "How implementation, fix and review are split"], [/^.Blocked. is the share/, "How to read the review agent columns"], + [/^Cost is what the tokens/, "What the cost figures include and leave out"], [/^The model is read/, "How the author's model is detected"], [/^Pull requests opened from/, "How the review sample is compared"], [/^Each ask is judged/, "How an ask is judged"], [/^Durations are/, "How CI durations are measured"], [/^The cause is for a person/, "Who classifies a failed push"], [/^From the first attempt/, "Where the list of flaky jobs comes from"]]; +const plain = (x) => x.replace(/<[^>]+>/g, "").trim(); +let out = html.replace(/

([\s\S]*?)<\/p>/g, (all, body) => { const t = plain(body), hit = LABEL.find(([re]) => re.test(t)); + if (!hit && t.split(/\s+/).length <= 30) return all; + return `

${hit ? hit[1] : "Method: " + esc(t.split(/\s+/).slice(0, 6).join(" ")) + " …"}

${body}

`; }); +out = out.replace(/

What works<\/h3>(
    [\s\S]*?<\/ul>)/, (all, ul) => `
    What works: ${(ul.match(/
  • /g) ?? []).length} rules passed
  • ${ul}
    `); +out = out.replace(/

    Costliest pull requests<\/h4>([\s\S]*?<\/table>(?:
    [\s\S]*?<\/details>)?)/, (all, t) => `
    Costliest pull requests${t}
    `); +out = out.replace(/(

    By model of the author<\/h3>)([\s\S]*?)(?=

    | h + seg.replace(/

    ([^<]+)<\/h4>(

    [\s\S]*?<\/table>)/g, (a, name, t) => `
    By model, ${name} pull requests only${t}
    `)); +const nav = [...out.matchAll(/

    [\s\S]*?<\/span>([^<]*)<\/h2>/g)].map((x) => `${x[2].split(" · ")[0]}`).join(""); +out = out.replace(/(

    [\s\S]*?<\/p>)/, (all) => `${all}

    `); +writeFileSync(outFile, out); +console.log(`written: ${outFile}`); diff --git a/tools/process-review/rules.mjs b/tools/process-review/rules.mjs new file mode 100644 index 00000000..f2924799 --- /dev/null +++ b/tools/process-review/rules.mjs @@ -0,0 +1,134 @@ +// Rules that turn metrics into suggestions. One object per rule: +// id, group (flow | review | ci | quality), severity (high | medium | low), name, +// th: default threshold, min: smallest sample the rule judges, +// check(m, th) -> { n, hit, problem, good } n = sample size; problem/good are sentences with counts +// why, action, ref (source and year of the threshold, when it has one) +// config.json can set { "rules": { "": { "threshold": 0.3 } } } or { "off": true }. +// Thresholds without a ref are coaching defaults, not proven standards. +const pct = (x) => `${(x * 100).toFixed(0)} %`; +const of = (share, total) => Math.round((share ?? 0) * total); + +export const RULES = [ + { + id: "later-rounds-low-yield", group: "review", severity: "high", name: "Later review rounds rarely find a blocker", th: 0.6, min: 20, + check: ({ total: { efficiency: e } }, th) => { + const n = e.laterClean + e.laterNonBlocking + e.laterBlocking, low = e.laterClean + e.laterNonBlocking; + return { n, hit: low / n >= th, problem: `${low} of ${n} later review rounds with a readable result found nothing that blocks (${e.laterClean} nothing at all, ${e.laterNonBlocking} only non-blocking findings).`, good: `Later review rounds earn their cost: ${e.laterBlocking} of ${n} found a blocker.` }; + }, + why: "Every round costs a reviewer run, a CI run and waiting time. A round that finds nothing blocking delays the merge without protecting it.", + action: "Let a non-blocking review stand: non-blocking findings go into the author's next pull request. A later round reviews only the fixes and the changed lines.", + }, + { + id: "rounds-after-merge-only", group: "review", severity: "medium", name: "Re-reviews after merging the base branch", th: 0.1, min: 20, + check: ({ total: { efficiency: e } }, th) => ({ n: e.laterRounds, hit: e.laterAfterMergeOnly / e.laterRounds >= th, problem: `${e.laterAfterMergeOnly} of ${e.laterRounds} later rounds followed nothing but merge commits of the base branch.`, good: `Only ${e.laterAfterMergeOnly} of ${e.laterRounds} later rounds followed a mere merge of the base branch.` }), + why: "The author changed nothing, yet the whole pull request was reviewed again.", + action: "After a clean merge of the base branch, carry the last review over: compare the added and removed lines and confirm in one line instead of a full round.", + }, + { + id: "many-rounds", group: "review", severity: "medium", name: "Pull requests with three or more review rounds", th: 0.1, min: 30, + check: ({ total: { efficiency: e } }, th) => ({ n: e.reviewed, hit: e.threePlusShare >= th, problem: `${of(e.threePlusShare, e.reviewed)} of ${e.reviewed} reviewed pull requests needed three or more rounds (${pct(e.threePlusShare)}).`, good: `Only ${pct(e.threePlusShare)} of the reviewed pull requests needed three or more rounds.` }), + why: "Three rounds mean the second fix did not settle the review: the task was unclear, the pull request too large, or the reviewer keeps finding new things.", + action: "Stop before the third round: a person or coordinator decides what still has to change. Read the outliers below for the common cause.", + }, + { + id: "first-pass-low", group: "flow", severity: "medium", name: "Few pull requests pass on the first attempt", th: 0.5, min: 30, + check: ({ total: { efficiency: e } }, th) => ({ n: e.firstPassN, hit: e.firstPassShare < th, problem: `${of(e.firstPassShare, e.firstPassN)} of ${e.firstPassN} pull requests passed on the first attempt (first CI run green and first review not blocking): ${pct(e.firstPassShare)}.`, good: `${pct(e.firstPassShare)} of the pull requests passed on the first attempt (first CI run green, first review not blocking).` }), + why: "Everything that does not pass at once is babysitting: fix, push, wait for CI and review again.", + action: "Move the checks that fail most often to before the push (the same lint, type and test commands CI runs), and give authors the reviewer's checklist up front.", + }, + { + id: "slow-first-review", group: "flow", severity: "medium", name: "Pull requests wait for their first review", th: 4, min: 30, + check: ({ total: { efficiency: e } }, th) => ({ n: e.firstReviewMedianH === null ? 0 : e.reviewed, hit: e.firstReviewMedianH > th, problem: `Half of the pull requests wait more than ${e.firstReviewMedianH} hours for their first review.`, good: `The first review arrives after ${e.firstReviewMedianH} hours (median).` }), + why: "Waiting for pickup is the phase authors cannot shorten themselves.", + action: "Agree on a time to first review and name who picks up; let a bot or agent reviewer answer first where one exists.", + ref: "LinearB 2026 benchmarks: pickup under 1 h elite, 1 to 4 h good (75th percentile of vendor customers)", + }, + { + id: "large-prs", group: "flow", severity: "low", name: "Large pull requests", th: 228, min: 30, + check: ({ total: { merged, efficiency: e } }, th) => ({ n: merged, hit: e.sizeMedian > th, problem: `The median pull request changes ${e.sizeMedian} lines.`, good: `The median pull request changes ${e.sizeMedian} lines.` }), + why: "Large changes are reviewed worse and collide more often with other work.", + action: "Split by behaviour, not by file; keep generated files and lock files out of the count (ignorePaths).", + ref: "LinearB 2026 benchmarks: under 100 changed lines elite, over 228 needs focus (75th percentile of vendor customers)", + }, + { + id: "ci-hours-not-green", group: "ci", severity: "high", name: "CI time spent on runs that did not end green", th: 0.2, min: 100, + check: ({ ci }, th) => { const c = ci?.prBranches ?? ci?.all; return { n: c?.runs ?? 0, hit: c.hoursNotGreen / c.hours >= th, problem: `${c.hoursNotGreen} of ${c.hours} CI hours on pull request branches went to runs that were cancelled or failed (${pct(c.hoursNotGreen / c.hours)}).`, good: `Only ${pct(c.hoursNotGreen / c.hours)} of the CI hours on pull request branches went to cancelled or failed runs.` }; }, + why: "Runners are the shared bottleneck when many pull requests are open; time on runs nobody waits for delays every other pull request.", + action: "Collect changes and push once; cancel superseded runs at the start, not the end (concurrency groups); run cheap checks first so a failure stops the expensive jobs.", + }, + { + id: "ci-cancelled", group: "ci", severity: "medium", name: "Many cancelled CI runs", th: 0.2, min: 100, + check: ({ ci }, th) => { const c = ci?.prBranches ?? ci?.all; return { n: c?.runs ?? 0, hit: c.cancelledShare >= th, problem: `${c.cancelled} of ${c.runs} CI runs on pull request branches were cancelled (${pct(c.cancelledShare)}). Runs on the default branch are not counted here.`, good: `Only ${pct(c.cancelledShare)} of the CI runs on pull request branches were cancelled.` }; }, + why: "A cancelled run usually means a newer push arrived before CI finished: pushes come faster than CI answers.", + action: "Verify locally and push when the change is complete; a draft pull request can skip the heavy jobs.", + }, + { + id: "red-default-branch", group: "quality", severity: "high", name: "Failed CI on the default branch", th: 0.1, min: 30, + check: ({ ci, defaultBranch }, th) => { const m = ci?.defaultBranchPush; return { n: m ? m.success + m.failure : 0, hit: m?.failureRate > th, problem: `${m?.failure} of ${m?.success + m?.failure} finished push runs on ${defaultBranch} failed (${pct(m?.failureRate ?? 0)}).`, good: `${pct(1 - (m?.failureRate ?? 0))} of the push runs on ${defaultBranch} were green.` }; }, + why: "A red default branch blocks every open pull request and every release, and shows that the checks before merge did not catch what the checks after merge did.", + action: "Classify one week of failures (merged defect, flaky test, infrastructure). For merged defects: find the check that runs only after merge and move it to the pull request.", + ref: "CircleCI 2026 software delivery report: 90 % main-branch success as benchmark, 70.8 % observed in Q1 2026 (CircleCI customers)", + }, + { + id: "flaky-reruns", group: "ci", severity: "medium", name: "Re-runs that turned green without a change", th: 0.01, min: 100, + check: ({ ci }, th) => ({ n: ci?.all.runs ?? 0, hit: ci.all.rerunGreen / ci.all.runs >= th, problem: `${ci.all.rerunGreen} of ${ci.all.runs} CI runs turned green on a re-run without a change.`, good: `Only ${ci.all.rerunGreen} of ${ci.all.runs} CI runs needed a re-run to turn green.` }), + why: "A test that passes on the second try teaches everyone to re-run instead of read, and hides real failures.", + action: "List the tests that failed in those first attempts; fix or quarantine the repeat offenders and keep a table of known flaky tests.", + }, + { + id: "follow-up-fixes", group: "quality", severity: "medium", name: "Defects fixed shortly after merge", th: 0.08, min: 50, + check: ({ total: { merged, quality: q } }, th) => ({ n: merged, hit: q.followUpDefectShare >= th, problem: `${of(q.followUpDefectShare, merged)} of ${merged} merged pull requests were named by a later fix that is not worded as a review follow-up (${pct(q.followUpDefectShare)}). Another ${of(q.followUpPlannedShare, merged)} were followed only by planned follow-ups of review findings, which do not count here.`, good: `Only ${pct(q.followUpDefectShare)} of the merged pull requests were named by a later defect fix (${pct(q.followUpPlannedShare)} more by planned follow-ups of review findings).` }), + why: "A fix that names an earlier pull request is the nearest thing to a counted escaped defect. Planned follow-ups are told apart by wording only, so read a sample before concluding.", + action: "Read ten entries of the follow-up list: what would have caught each before merge (a test, a review role, a CI check)? Add that check.", + }, + { + id: "fixes-without-tests", group: "quality", severity: "medium", name: "Fixes without a test", th: 0.2, min: 50, + check: ({ total: { merged, quality: q } }, th) => ({ n: of(q.fixShare, merged), hit: q.fixWithoutTestShare >= th, problem: `${pct(q.fixWithoutTestShare)} of the fixes that touch source code touch no test file.`, good: `${pct(1 - (q.fixWithoutTestShare ?? 0))} of the source-code fixes come with a test change.` }), + why: "A defect fixed without a pinning test can come back unnoticed.", + action: "Ask for the failing test first in every behaviour fix; let the review block a fix without one.", + }, + { + id: "high-fix-share", group: "quality", severity: "low", name: "A large share of the work is fixing", th: 0.35, min: 50, + check: ({ total: { merged, quality: q } }, th) => ({ n: merged, hit: q.fixShare >= th, problem: `${of(q.fixShare, merged)} of ${merged} merged pull requests are fixes (${pct(q.fixShare)}).`, good: `${pct(q.fixShare)} of the merged pull requests are fixes.` }), + why: "Shipping fast and fixing fast often means the review or the tests let too much through.", + action: "Look for fix chains: several fixes on the same area in a row point at the part that needs a design decision, not another patch.", + }, + { + id: "merged-without-review", group: "review", severity: "medium", name: "Merges without any review", th: 0.2, min: 30, + check: ({ total: { merged, quality: q } }, th) => ({ n: merged, hit: q.noReviewShare >= th, problem: `${of(q.noReviewShare, merged)} of ${merged} pull requests were merged without a review by any named reviewer (${pct(q.noReviewShare)}).`, good: `${pct(1 - q.noReviewShare)} of the merged pull requests had a review.` }), + why: "An unreviewed merge is fine for low-risk classes and a gap for the others; the number alone does not say which it is.", + action: "Check the risk-class table: unreviewed merges should sit in the docs and tests rows. Require a review for the sensitive class.", + }, + { + id: "unresolved-threads", group: "review", severity: "low", name: "Merged with open review threads", th: 0, min: 30, + check: ({ total: { merged, quality: q } }, th) => ({ n: merged, hit: q.unresolvedThreadPrs > th, problem: `${q.unresolvedThreadPrs} pull requests were merged with an unresolved review thread.`, good: "No pull request was merged with an unresolved review thread." }), + why: "An open thread at merge is a finding nobody answered.", + action: "Require resolved conversations in the branch rules, or answer each thread with the reason it stays open.", + }, + { + id: "reviewers-disagree", group: "review", severity: "medium", name: "Two reviewers disagree on the same commit", th: 0.2, min: 20, + check: ({ compare: c }, th) => { const n = c ? c.both + c.onlyA + c.onlyB + c.neither : 0, d = c ? c.onlyA + c.onlyB : 0; return { n, hit: d / n >= th, problem: `On ${d} of ${n} commits reviewed by both, only one of ${c?.a} and ${c?.b} blocked (${c?.onlyA} only ${c?.a}, ${c?.onlyB} only ${c?.b}).`, good: `${c?.a} and ${c?.b} agree on ${n - d} of ${n} commits both reviewed.` }; }, + why: "Each one-sided block is either a false alarm of one reviewer or a miss of the other. Which one decides whether the reviewer can gate merges.", + action: "Read the one-sided cases and label each: right or false alarm. Report both rates per reviewer before changing who gates.", + }, +]; + +const PENALTY = { high: 12, medium: 7, low: 3 }; +export function evaluate(metrics, overrides = {}) { + const results = RULES.map((r) => { + const o = overrides[r.id] ?? {}; + const base = { id: r.id, group: r.group, severity: r.severity, name: r.name, why: r.why, action: r.action, ref: r.ref ?? null, threshold: o.threshold ?? r.th }; + if (o.off) return { ...base, state: "off" }; + let res; + try { res = r.check(metrics, base.threshold); } catch { res = { n: 0 }; } + if (!res.n || res.n < r.min || Number.isNaN(res.n)) return { ...base, state: "not-evaluated", reason: res.n ? `only ${res.n} in the sample, the rule needs ${r.min}` : "no data for this rule in the period" }; + return { ...base, state: res.hit ? "triggered" : "passed", n: res.n, text: res.hit ? res.problem : res.good }; + }); + // score per group: 100 x (1 - penalties / (evaluated rules x 12)); a triggered rule costs its penalty once + const scores = {}; + for (const g of ["flow", "review", "ci", "quality"]) { + const ev = results.filter((r) => r.group === g && (r.state === "triggered" || r.state === "passed")); + scores[g] = ev.length ? { score: Math.round(100 * (1 - ev.filter((r) => r.state === "triggered").reduce((s, r) => s + PENALTY[r.severity], 0) / (ev.length * 12))), evaluated: ev.length, triggered: ev.filter((r) => r.state === "triggered").length } : null; + } + return { results, scores }; +} diff --git a/tools/process-review/tool-versions.mjs b/tools/process-review/tool-versions.mjs new file mode 100644 index 00000000..3080d0e6 --- /dev/null +++ b/tools/process-review/tool-versions.mjs @@ -0,0 +1,42 @@ +#!/usr/bin/env node +// Prints dated change entries for the versions of a tool, ready for "changes" in config.json. +// Usage: +// node tool-versions.mjs plugin versions of a Claude Code plugin installed on this machine +// node tool-versions.mjs file version bumps of a pinned tool in a repository file +// "plugin" reads the creation time of each version folder under ~/.claude/plugins/cache/*//: +// when that version arrived on THIS machine. Other machines and agents may have updated at other times. +// "file" walks the git history of (for example package.json, .tool-versions, a lock file) and +// reports each commit in which the first capture group of changed: when the repository pinned it. +import { execFileSync } from "node:child_process"; +import { existsSync, readdirSync, statSync } from "node:fs"; +import { homedir } from "node:os"; + +const [mode, a, b, c] = process.argv.slice(2); +const out = []; +if (mode === "plugin" && a) { + const cache = `${homedir()}/.claude/plugins/cache`; + for (const market of existsSync(cache) ? readdirSync(cache) : []) { + const dir = `${cache}/${market}/${a}`; + if (!existsSync(dir)) continue; + for (const v of readdirSync(dir)) { + const st = statSync(`${dir}/${v}`); + if (st.isDirectory()) out.push({ at: st.birthtime.toISOString().slice(0, 10), label: `${a} ${v}`, time: st.birthtime.toISOString() }); + } + } +} else if (mode === "file" && a && b && c) { + const re = new RegExp(c, "m"); + const log = execFileSync("git", ["-C", a, "log", "--reverse", "--format=%H %cI", "--", b], { encoding: "utf8" }).trim().split("\n").filter(Boolean); + let last = null; + for (const line of log) { + const [sha, time] = line.split(" "); + let text = ""; + try { text = execFileSync("git", ["-C", a, "show", `${sha}:${b}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); } catch { continue; } + const v = text.match(re)?.[1] ?? null; + if (v && v !== last) { out.push({ at: time.slice(0, 10), label: `${b}: ${v}`, time, commit: sha.slice(0, 9) }); last = v; } + } +} else { + console.error("usage: tool-versions.mjs plugin | file "); + process.exit(2); +} +out.sort((x, y) => x.time.localeCompare(y.time)); +console.log(JSON.stringify(out, null, 1)); From 85f3e1f0652816a15dc10416da39d1732d8b55e1 Mon Sep 17 00:00:00 2001 From: Alex Wegener Date: Mon, 23 Nov 2026 00:52:21 +0100 Subject: [PATCH 2/2] fix(process-review): PR runs by PR branch, incomplete failure mining, calendar days in the digest - CI runs count as pull-request runs only on a mined PR's branch or a pull_request event, not on every non-default branch. - mine-failures records requests that fail after retries in failures.json, exits 3, and the report marks the section incomplete. - The daily digest uses the last nine calendar days, so a day without merges is zero, not skipped. - coach-process description names no host (Codex packaging test). Co-Authored-By: Claude Opus 5.5 --- skills/coach-process/SKILL.md | 2 +- tools/process-review/analyze.mjs | 10 ++++++---- tools/process-review/mine-failures.mjs | 7 +++++-- tools/process-review/report.mjs | 2 +- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/skills/coach-process/SKILL.md b/skills/coach-process/SKILL.md index fe21e6f6..987df2e7 100644 --- a/skills/coach-process/SKILL.md +++ b/skills/coach-process/SKILL.md @@ -1,6 +1,6 @@ --- name: coach-process -description: "Turns the findings of a process-review run into a short coaching message for the agent that coordinates the work (the coordinator session of a Claude Code, Codex or other host), delivers it, records every ask with the metric it should move, judges the earlier asks on the next run, sends an ask that was ignored twice to the user instead, and checks each finding for what ytstack itself could do better (clearer instructions, a missing check). Use after process-review when the user wants the coordinator coached, says coach the coordinator, tell the coordinator what the review found, or wants the process to learn from the reviews. Not the measurement itself (process-review), not a lesson from an incident (lesson) and not the bot findings on single pull requests (review-lessons)." +description: "Turns the findings of a process-review run into a short coaching message for the agent that coordinates the work (the coordinator session, on whichever host it runs), delivers it, records every ask with the metric it should move, judges the earlier asks on the next run, sends an ask that was ignored twice to the user instead, and checks each finding for what ytstack itself could do better (clearer instructions, a missing check). Use after process-review when the user wants the coordinator coached, says coach the coordinator, tell the coordinator what the review found, or wants the process to learn from the reviews. Not the measurement itself (process-review), not a lesson from an incident (lesson) and not the bot findings on single pull requests (review-lessons)." metadata: tier: task version: 0.1.0 diff --git a/tools/process-review/analyze.mjs b/tools/process-review/analyze.mjs index 61cbd68c..b5ee8eec 100644 --- a/tools/process-review/analyze.mjs +++ b/tools/process-review/analyze.mjs @@ -156,8 +156,9 @@ function ciStats(list) { }; } const mainRuns = ciRuns.filter((r) => r.branch === defaultBranch && r.event === "push"); -// runs on other branches: where a cancelled run is a superseded push, not a queue the default branch drops on purpose -const prRuns = ciRuns.filter((r) => r.branch !== defaultBranch); +// runs of pull requests: where a cancelled run is a superseded push, not a queue the default branch drops on purpose. +// A branch counts when a mined pull request came from it or a pull_request event started the run, never only because it is not the default branch (release or develop branches are no pull requests). +const prRuns = ciRuns.filter((r) => r.branch !== defaultBranch && (branchOf.has(r.branch) || r.event?.startsWith("pull_request"))); // ---- aggregate function summ(g) { @@ -470,8 +471,9 @@ if (existsSync(`${dir}/labels.tsv`)) { }; } -// ---- the last eight days one by one, for the daily digest -const dayList = [...new Set(rows.map((r) => r.day))].sort().slice(-9); +// ---- the last nine calendar days one by one, for the daily digest: a day without a merge is a day with zero merges, not a missing day +const digestEnd = [...rows.map((r) => r.day), ...mainRuns.map((r) => r.createdAt.slice(0, 10))].sort().at(-1); +const dayList = digestEnd ? Array.from({ length: 9 }, (_, i) => new Date(+new Date(`${digestEnd}T00:00:00Z`) - (8 - i) * 864e5).toISOString().slice(0, 10)).filter((d) => d >= metrics.period.from) : []; metrics.daily = dayList.map((d) => { const g = rows.filter((r) => r.day === d), s = summ(g), mr = ciStats(mainRuns.filter((r) => r.createdAt.slice(0, 10) === d)); return { day: d, merged: g.length, roundsMean: s.efficiency.roundsMean, multiRoundShare: s.efficiency.multiRoundShare, firstPassShare: s.efficiency.firstPassShare, firstPassN: s.efficiency.firstPassN, ciHoursPerPr: s.efficiency.ciHoursPerPr, leadMedianH: s.efficiency.leadMedianH, mainRuns: mr.success + mr.failure, mainFailed: mr.failure, mainFailureRate: mr.failureRate }; }); diff --git a/tools/process-review/mine-failures.mjs b/tools/process-review/mine-failures.mjs index 0f415d74..ad7a4528 100644 --- a/tools/process-review/mine-failures.mjs +++ b/tools/process-review/mine-failures.mjs @@ -21,7 +21,9 @@ const main = cfg.defaultBranch ?? Object.entries(tally).sort((a, b) => b[1] - a[ const last = runs.map((r) => r.createdAt).sort().at(-1); const from = new Date(+new Date(last) - days * 864e5).toISOString(); -const gh = async (path) => { try { return await rest(path, 2); } catch { return null; } }; +// A request that still fails after its retries is recorded in failures.json and makes the run exit 3, so incomplete evidence is never shown as complete. +const incomplete = []; +const gh = async (path) => { try { return await rest(path, 2); } catch (e) { incomplete.push({ path, error: String(e?.message ?? e).slice(0, 200) }); return null; } }; // the failed jobs of one attempt, each with its first failed step const failed = async (id, attempt) => ((await gh(`repos/${repo}/actions/runs/${id}/attempts/${attempt}/jobs?per_page=100`))?.jobs ?? []) .filter((j) => j.conclusion === "failure" || j.conclusion === "timed_out") @@ -45,5 +47,6 @@ for (const r of rerun) { for (const j of f) { const k = `${j.job} › ${j.step ?? "(no failed step recorded)"}`; const s = (flakyJobs[k] ??= { job: j.job, step: j.step, count: 0, lastSeen: "", example: r.id }); s.count++; if (r.createdAt > s.lastSeen) { s.lastSeen = r.createdAt; s.example = r.id; } } } console.log(`re-runs that turned green: ${read} read of ${runs.filter((r) => r.attempt > 1 && r.conclusion === "success").length}`); -writeFileSync(`${dir}/failures.json`, JSON.stringify({ repo, at: new Date().toISOString(), days, from: from.slice(0, 10), branch: main, defaultBranch, rerunsRead: read, flaky: Object.values(flakyJobs).sort((a, b) => b.count - a.count) }, null, 1)); +writeFileSync(`${dir}/failures.json`, JSON.stringify({ repo, at: new Date().toISOString(), days, from: from.slice(0, 10), branch: main, defaultBranch, rerunsRead: read, flaky: Object.values(flakyJobs).sort((a, b) => b.count - a.count), incomplete }, null, 1)); console.log(`written: ${dir}/failures.json`); +if (incomplete.length) { console.error(`incomplete: ${incomplete.length} requests failed after retries (first: ${incomplete[0].path}: ${incomplete[0].error}); listed in failures.json`); process.exit(3); } diff --git a/tools/process-review/report.mjs b/tools/process-review/report.mjs index 4d658a91..0b114fdb 100644 --- a/tools/process-review/report.mjs +++ b/tools/process-review/report.mjs @@ -319,7 +319,7 @@ ${m.compare ? `

    ${esc(m.compare.a)} and ${esc(m.compare.b)} on th ${ci ? `${h2("play", "CI")}${table(["Workflow", "Runs", "Failure rate", "Cancelled", "Re-run", "Median (min)", "p90 (min)", "Runner-hours", "of that not green"], Object.entries(ci.perWorkflow).slice(0, 12).map(([n, s]) => [esc(n), s.runs, pct(s.failureRate), pct(s.cancelledShare), pct(s.rerunShare), num(s.medianMin), num(s.p90Min), num(s.hours), num(s.hoursNotGreen)]))}

    Durations are the last attempt of a run, start to end, and count wall time of the run, not the sum of its jobs. ${ci.all.rerunGreen} re-runs turned green: candidates for flaky tests.

    ` : ""} ${ci?.prBranches ? `${table(["Where", "Runs", "Failure rate", "Cancelled", "Re-run", "Median (min)", "Runner-hours", "of that not green"], [["Pull request branches", ci.prBranches], [`Pushes to ${m.defaultBranch}`, ci.defaultBranchPush]].map(([n, s]) => [esc(n), s.runs, pct(s.failureRate), pct(s.cancelledShare), pct(s.rerunShare), num(s.medianMin), num(s.hours), num(s.hoursNotGreen)]))}

    A cancelled run on a pull request branch is a superseded push. On the default branch it can be by design, where a newer merge replaces a waiting run.

    ` : ""} -${m.failures ? `

    Failed pushes to ${esc(m.failures.branch)}, last ${m.failures.days} days

    ${m.failures.defaultBranch.length ? table(["Run started (UTC)", "Merge", "Failed job › step"], [...m.failures.defaultBranch].reverse().map((r) => [`${r.url ? `` : ""}${r.at.slice(0, 16).replace("T", " ")}${r.url ? "" : ""}`, `${r.pr ? prLink(r.pr) : `${esc(r.sha)}`} ${esc(r.title.slice(0, 80))}`, r.failed.map((j) => `${esc(j.job)} › ${esc(j.step ?? "–")}`).join("
    ") || "–"])) : `

    None.

    `} +${m.failures ? `

    Failed pushes to ${esc(m.failures.branch)}, last ${m.failures.days} days

    ${m.failures.incomplete?.length ? `

    Incomplete: ${m.failures.incomplete.length} GitHub requests failed after their retries, so jobs, titles or pull requests below may be missing (listed in failures.json).

    ` : ""}${m.failures.defaultBranch.length ? table(["Run started (UTC)", "Merge", "Failed job › step"], [...m.failures.defaultBranch].reverse().map((r) => [`${r.url ? `` : ""}${r.at.slice(0, 16).replace("T", " ")}${r.url ? "" : ""}`, `${r.pr ? prLink(r.pr) : `${esc(r.sha)}`} ${esc(r.title.slice(0, 80))}`, r.failed.map((j) => `${esc(j.job)} › ${esc(j.step ?? "–")}`).join("
    ") || "–"])) : `

    None.

    `}

    The cause is for a person to classify: a defect in that merge, a defect merged earlier that every later push inherits, a flaky test, or infrastructure. The same job failing on consecutive merges points at an inherited failure.

    ${m.failures.flaky.length ? `

    Jobs that failed and then passed on a re-run

    ${table(["Job › step", "Times", "Last seen (UTC)"], m.failures.flaky.slice(0, 15).map((j) => [`${esc(j.job)} › ${esc(j.step ?? "–")}`, j.count, j.lastSeen.slice(0, 16).replace("T", " ")]))}

    From the first attempt of ${m.failures.rerunsRead} runs that turned green on a later attempt. This names the job and step; the failing test is in the log of the example runs.

    ` : ""}` : ""} ${h2("search", "Outliers")}