diff --git a/skills/benchmark-checklist/SKILL.md b/skills/benchmark-checklist/SKILL.md index 5e6705a..31f93f3 100644 --- a/skills/benchmark-checklist/SKILL.md +++ b/skills/benchmark-checklist/SKILL.md @@ -1,32 +1,39 @@ --- name: benchmark-checklist -description: "Verify benchmark rigor and performance claims using the Seven Performance Verification Questions before reporting numbers or declaring optimizations." +description: "Vet a perf measurement (limiter, tuning, limits, errors, repeatability, relevance, and whether the work happened) before you report or act on it. Use when you run a benchmark or report a speedup or regression you measured." disable-model-invocation: true --- -# Benchmark Checklist +# Benchmark checklist -Verify every performance claim, benchmark run, or optimization result before reporting numbers. Never trust a single run or guess why code got faster. Answer the Seven Performance Verification Questions directly. +Use this when you produce a performance number: a PR's before and after, a regression claim, a hillclimb harness, or a library or config choice. Answer each question with evidence from a run, not a guess about the code. -## The Seven Performance Verification Questions +For a quick ballpark the user asked for, one run is enough. Still check questions 4 and 7, and say that it is one run. Skip the rest unless that run looks wrong. A choice between options is never a ballpark. -### 1. Limiter (Why not double?) -Ask why the improvement stopped where it did. Why not double the speedup? Name the physical bottleneck or limiter preventing 2x speedup (CPU instructions, memory bandwidth, cache line contention, disk I/O, network RTT, or thread synchronization). If you cannot name the physical limiter holding the ceiling, you do not understand the bottleneck. +## Before you run anything -### 2. Tuning (Production optimization flags) -Are production optimization flags enabled? Check compilation mode and environment flags. Confirm release mode is active (`-O2`, `-O3`, `--release`, or production build target). Verify debug assertions, sanitizers, trace logging, and developer devtools are disabled. A benchmark measured against an unoptimized debug build measures compiler accidents rather than software architecture. +- Write down the claim you expect to make, in the words you would ship ("export is 30% faster at p50 on the 60k-row dataset"). The questions test that sentence. +- Read the measurement script. Note what it times, counts, and ignores. +- Check the load average with `uptime` and the core count with `nproc` (or `sysctl -n hw.ncpu` on macOS). If the machine is busy, find out what is running. If you cannot stop it, interleave the sides so both see the same noise, and say so in the report. -### 3. Arithmetic Limits (Amdahl's law and bounds) -Calculate theoretical bounds before celebrating. Apply Amdahl's law to check the maximum theoretical speedup based on the fraction of execution time the optimized section occupied. If an optimized routine took 20% of baseline runtime, the whole system cannot speed up by 30%. Arithmetic checks prevent impossible speedup claims. +## The questions -### 4. Error Checking (Correctness under benchmark) -Check failure counts and verify correctness. Confirm error states, early bailouts, or skipped validation are not miscounted as fast executions. Inspect exit codes, response bodies, and error logs across the benchmark run. Fast execution that fails silently or returns early is a defect, not a performance win. +1. **Why not double?** Name the limiter. Profile in a run you do not report, because profilers and tracers slow the work down. Use CPU per process (`top`, `pidstat`), a runtime profiler (`node --cpu-prof`, `py-spy`, `perf`), I/O wait, and syscall counts (`strace -c` on Linux), then map the hot spot to source. Watch the load generator too: if it saturates first, you measured the load generator. If a change did not move the number, the limiter explains why, so find it before you call the change useless. +2. **Was it tuned?** Run every side the way production runs it: release builds, production flags and env, batching and transaction settings, connection pools, caches as warm or cold as production sees them, and the same versions and data. If one side runs on defaults, you compared configurations, not implementations. A limiter that is a setting (a commit per row, a debug build, a missing index) means that side is untuned. Tune it and measure again before you pick a winner. If you cannot tune it, do not pick a winner from that run. When the user is choosing what to adopt, narrowing the claim to the code as it ships today does not fix this, because they adopt the option, not today's settings. +3. **Did it break limits?** Do the arithmetic. Compare bytes per second with disk and network bandwidth, operations per second times cost per operation with your cores, and the time saved with the time the changed piece took. Removing a piece that takes 10% of the run can make the run at most about 11% faster. A result past a limit measured something other than the work, such as a cache, a no-op, or a bug. +4. **Did it error?** Count failures and non-success responses, and check that outputs are correct, not just present. Rejections are often fast, and timeouts and retries are slow. If the script does not count errors, add the count. +5. **Does it reproduce?** Run each side at least 5 times, alternating (A, B, A, B, and so on) so warmup, lazy initialization, caches, and drift favor neither. Report the median and range. A gap smaller than the run-to-run variation is no measurable difference. When the call is close, use a rank-sum test or the harness's own statistics. +6. **Does it matter?** Next to any micro result, measure the end-to-end path a user waits on, with realistic data sizes and concurrency, and report the micro result as a share of the whole. A helper that takes 1% of a request can make the request at most 1% faster, however fast the helper gets. +7. **Did it even happen?** Confirm the work ran inside the timed region: the request reached the server, the rows were written, the bytes were read, and the code used the result. Lazy code (generators nobody iterates, promises nobody awaits, results the JIT can discard) and timeouts produce numbers for work that never happened. -### 5. Reproduction (Variance and sample size) -Mandate running at least five runs. Record variance and median, not a single lucky run. Single-iteration spikes distort numbers through CPU frequency scaling, cold caches, background kernel interrupts, or JIT warm-up cycles. Discard cold starts if measuring steady state, report the median and standard deviation across five or more runs, and verify the gain clears noise. +## Report -### 6. Relevance (Microbenchmark versus whole-system) -Compare microbenchmark relevance to the whole-system realistic workload. Microbenchmarks isolate functions but miss cache eviction, memory pressure, context switches, and concurrent lock contention. Verify that microbenchmark improvements translate to end-to-end user-visible latency or throughput under realistic production data sizes and traffic shapes. +- Lead with the verdict: faster, slower, no measurable difference, or inconclusive. +- Give the number with its unit, the run count, the range, and the limiter. For example, "p50 41 ms → 33 ms, median of 7 runs per side, range 32 to 35 ms after, bound by JSON parsing on one core." +- Call the verdict inconclusive when you claim a difference but cannot name the limiter, when a side ran untuned, or when you could not check questions 4 and 7. Name the gap. +- Keep a PR body to one primary number. Deliver the full runs, range, and limiter evidence in the Antigravity Brain Artifact `/brain//perf_report.md` (with `ArtifactMetadata` and `RequestFeedback: false`). -### 7. Lazy Execution (Confirm actual work executed) -Confirm the measured work actually executed. Ensure the compiler, optimizer, or runtime did not eliminate dead code. Prevent dead code elimination by consuming or asserting on benchmark outputs. Confirm asynchronous operations actually completed rather than leaving unmeasured deferred computation pending on an unpolled event loop. +## Other perf material + +- Vet the **Perf issue** playbook's baseline before the playbook plans from it, and every number after that. +- Vet the **Hillclimb** playbook's harness before it is frozen. The frozen harness then prints error and work counts, so each keep-or-revert checks questions 4 and 7 for free. diff --git a/skills/create-verification-skill/SKILL.md b/skills/create-verification-skill/SKILL.md index 44ce543..e493f0a 100644 --- a/skills/create-verification-skill/SKILL.md +++ b/skills/create-verification-skill/SKILL.md @@ -16,7 +16,7 @@ Answer these from the codebase and only ask the user what you cannot observe: - **Surface:** what does a user actually touch? A web UI, a CLI/TUI, a desktop app, an API, a mobile app, a library? A repo can have several; pick the primary one and note the rest. - **Run:** how does the app start locally? Prefer the repo's own documented dev command (package scripts, Makefile, README quickstart). Note ports, env vars, seed data, auth. -- **Drive:** how can an agent interact with it programmatically? Existing harnesses first: Playwright/Cypress specs, expect scripts, PTY helpers, curl-able endpoints, a debug port. For web and Electron, use native `browser_subagent` / CDP with repo-specific routes and selectors. For CLI/TUI, use a tmux/PTY harness. For services, use plain HTTP. +- **Drive:** how can an agent interact with it programmatically? Follow the Surface Precedence Hierarchy: existing harnesses first (Playwright/Cypress specs, expect scripts, PTY helpers, curl-able endpoints, a debug port); for CLI/TUI use a tmux/PTY harness; for services use plain HTTP; for web and Electron UIs use native `browser_subagent` / Chrome DevTools MCP with repo-specific routes and selectors. - **Observe:** what evidence can be captured? Screenshots, terminal transcripts, response bodies, logs, exit codes, DB state. - **Isolate:** can two instances run side by side (ports, data dirs, profiles)? If not, say so in the generated skill: refusing to double-drive a shared instance beats corrupting the user's session. @@ -26,7 +26,7 @@ If the checkout doesn't build or start as-is, fix that first (or report it preci Write `.agents/skills/verify-/SKILL.md` with YAML frontmatter (`name: verify-` and a `description` that names the app, the surface, and when to reach for it: without frontmatter the skill never registers) and these sections, each grounded in what the interview actually found (no placeholders left): -- **Launch:** the exact command that starts the app for verification, and how to tell it has reached a usable state (a log line, a UI render, a prompt). Include teardown. For a short-lived CLI or TUI there is no server to keep alive: launch means build the binary (or install deps) once, then start each drive in its own isolated PTY or tmux session. +- **Launch:** the exact command that starts the app for verification, and how to tell it has reached a usable state (a log line, a UI render, a prompt). Launch must reach a usable state from an empty data dir, including any migrations and seed data. Ready means usable, not just that a process answers. A database health check can pass while its init scripts are still running. Include teardown. For a short-lived CLI or TUI there is no server to keep alive: launch means build the binary (or install deps) once, then start each drive in its own isolated PTY or tmux session. - **Doctor:** one read-only check that answers "is this instance worth driving?" - process up, right version/build, port owned by us, auth valid. An agent runs this first whenever anything looks off. - **Drive:** the harness recipe with real selectors/commands from this repo, not examples. Prefer stable handles (ARIA labels, data attributes, prompt strings, route paths) over coordinates and tab order. - **Evidence:** what to capture for a proof and where it goes. State the proof standards: exercise the real user path, not internal setters or test-only endpoints; capture the action and the resulting state, not just the final screen; verify side effects (files written, rows inserted, messages sent) alongside what's visible; mocks only where a production boundary already isolates the external system. When the safe path is a dry-run or test mode, verify what it actually skips by observing (files, network, git refs) rather than trusting its name: some dry-runs still touch the network or open a browser. @@ -35,11 +35,11 @@ Write `.agents/skills/verify-/SKILL.md` with YAML frontmatter (`name: verif ## 3. Seed the feature map -Create `.agents/skills/verify-/features/README.md` plus one file per user-facing feature you can identify (aim for the top 3-5 to start, from routes, commands, menus, or docs). Follow the shape in [`references/feature-map-example/`](references/feature-map-example/), with a README index and one file per feature. Each file answers, from the user's point of view: what the feature is, how to reach it, how to drive it with the harness, and what observable end state proves it works. The four H2s are `Sub-features`, `How to get to it (user POV)`, `Driving it with `, and `Gotchas`. The map is the repo's maintained verification source; a proof that drives one convenient entry point is incomplete when the map lists others. +Create `.agents/skills/verify-/features/README.md` plus one file per user-facing feature you can identify (aim for the top 3-5 to start, from routes, commands, menus, or docs). Follow the shape in [`references/feature-map-example/`](references/feature-map-example/), with a README index and one file per feature. Each file answers, from the user's point of view: what the feature is, how to reach it, how to drive it with the harness, and what observable end state proves it works. The four H2s are `Sub-features`, `How to get to it (user POV)`, `Driving it with `, and `Gotchas`. If the seed data lacks a precondition that a journey needs, the journey reports a failure and the reason goes in that feature's `Gotchas`. Never weaken the journey to make it pass. The map is the repo's maintained verification source; a proof that drives one convenient entry point is incomplete when the map lists others. ## 4. Prove the generated skill before handing it over -Run its own instructions end to end once: launch, doctor, drive ONE mapped feature (one is enough; the map exists so later runs can cover the rest), capture evidence, clean up. After cleanup, confirm the evidence still exists at the named location: a cleanup that eats the proof fails this step. Fix what fails, and run the generated cleanup after every failed iteration too, so broken attempts don't strand processes and ports. A generated skill that was never executed is a draft, not a deliverable. +Run its own instructions end to end once: launch, doctor, drive ONE mapped feature (one is enough; the map exists so later runs can cover the rest), capture evidence, clean up. After cleanup, confirm the evidence still exists at the named location: a cleanup that eats the proof fails this step. Fix what fails, and run the generated cleanup after every failed iteration too, so broken attempts don't strand processes and ports. A generated skill that was never executed is a draft, not a deliverable. If you proved it in a stand-in for the real target (a container in place of a fresh VM, a local stack in place of a remote one), list every setup step the stand-in did that the target will not. Those steps stay unverified until a run on the real target covers them. ## 5. Offer the maintenance loop diff --git a/skills/maintain-verification-skill/SKILL.md b/skills/maintain-verification-skill/SKILL.md index 53ef6b7..10a1253 100644 --- a/skills/maintain-verification-skill/SKILL.md +++ b/skills/maintain-verification-skill/SKILL.md @@ -24,15 +24,15 @@ Only edit the verification skill's own directory (its SKILL.md, features/, and a 0. **Locate the target.** Find the verification skill to maintain: the project-local skill whose body has launch/drive sections and a feature map (usually `.agents/skills/verify-*/`). Several candidates → ask which one; none → stop and point at `/create-verification-skill` instead of inventing a target. -1. **Index and helper hygiene.** Read the feature map README and glob its sibling files in `features/`. Fix missing, extra, duplicate, or dead entries. Check all scripts in `scripts/` against the skill's `## Helpers` and `## Drive` sections: detect unregistered helper scripts, missing executable permissions, or orphaned utilities. Audit helper CLI contracts and exit codes: ensure status-checking or polling helpers do not emit fatal non-zero exit codes for in-flight domain states (e.g. pending validation), and verify default timeouts accommodate realistic grader queues. Lightweight; no generated inventory. +1. **Index and helper hygiene.** Read the feature map README and glob its sibling files in `features/`. Fix missing, extra, duplicate, or dead entries. Check all scripts in `scripts/` against the skill's `## Helpers` and `## Drive` sections: detect unregistered helper scripts, missing executable permissions, or orphaned utilities. Audit helper CLI contracts and exit codes: ensure status-checking or polling helpers do not emit fatal non-zero exit codes for in-flight domain states (such as pending validation), and verify default timeouts accommodate realistic remote execution or CI queues. Lightweight; no generated inventory. 2. **Source wave.** One read-only subagent per feature file, launched concurrently. Each explains "how does this user-facing feature work?" from source, flags likely doc drift with citations, and returns one concise live-verification recipe. Children never drive the app and never edit files. Return shape: feature summary / source entry points / likely drift or none / one recipe. -3. **Reconcile.** Every feature file has a returned summary. Merge overlapping recipes into as few app states as practical. Spot-check cited drift; don't re-prove clean claims. Sweep recent churn for user-facing surfaces missing from the map — require a concrete source path before calling one missing. Reconcile metric baselines and submission gates: verify that score baselines and threshold constants documented in the skill body match the harness scripts, and ensure local dev metrics are never conflated with remote benchmark scales. +3. **Reconcile.** Every feature file has a returned summary. Merge overlapping recipes into as few app states as practical. Spot-check cited drift; don't re-prove clean claims. Sweep recent churn for user-facing surfaces missing from the map — require a concrete source path before calling one missing. Reconcile documented baselines and verification thresholds: verify that baseline numbers and threshold constants in the skill body match the harness scripts, and ensure local dev measurements are not conflated with production or remote target scales. -4. **Live pass.** Required even when source looks clean. The coordinator owns all driving; follow the verification skill's own launch model — one long-lived instance driven serially for servers and UIs, or a fresh isolated session per drive for short-lived CLIs (the skill's Launch section decides, not this one). Exercise every feature at least once, and hold three invariants the whole pass, whatever the failure: (1) never drive an instance you haven't health-checked since it last did something surprising — doctor before first drive, doctor on each fresh session where sessions are the unit, doctor again after any failed drive, and where doctor can't see the failure (a wedged UI state on a healthy process), reset to a known state or relaunch rather than hoping; doctor must decouple mandatory local build/purity checks from optional external infrastructure (cloud run jobs, remote grader queries) so missing cloud configs warn rather than blocking local driving; where the project supports worktrees, verify launch/drive recipes execute cleanly inside an isolated git worktree; (2) evidence captured so far survives every cleanup, checked at its named location, not assumed; (3) nothing a drive started outlives that drive's usefulness — failed-iteration residue is cleaned whether the session is stuck, exited, or shared (for a shared instance, clean the residue, not the instance; terminate in-flight background pollers and cloud jobs). A doctor failure caused by skill drift is drift: fix it under edit scope and retry once — restart whatever the fix invalidated, nothing more — before calling the pass `blocked`. A feature that can't be reached is `verified-unreachable` only with the concrete prerequisite (auth, entitlement, OS, external state) and the route attempted; if the map omits that prerequisite, that's drift. Any harness fix from triage gets re-driven live before it ships. Final teardown happens after the last drive of the run — including those re-proofs — so nothing outlives the run (evidence stays, per the skill). +4. **Live pass.** Required even when source looks clean. The coordinator owns all driving; follow the verification skill's own launch model — one long-lived instance driven serially for servers and UIs, or a fresh isolated session per drive for short-lived CLIs (the skill's Launch section decides, not this one). Exercise every feature at least once, and hold three invariants the whole pass, whatever the failure: (1) never drive an instance you haven't health-checked since it last did something surprising — doctor before first drive, doctor on each fresh session where sessions are the unit, doctor again after any failed drive, and where doctor can't see the failure (a wedged UI state on a healthy process), reset to a known state or relaunch rather than hoping; doctor must decouple mandatory local build/purity checks from optional external infrastructure (cloud run jobs, remote CI or target environment queries) so missing cloud configs warn rather than blocking local driving; where the project supports worktrees, verify launch/drive recipes execute cleanly inside an isolated git worktree; (2) evidence captured so far survives every cleanup, checked at its named location, not assumed; (3) nothing a drive started outlives that drive's usefulness — failed-iteration residue is cleaned whether the session is stuck, exited, or shared (for a shared instance, clean the residue, not the instance; terminate in-flight background pollers and cloud jobs). A doctor failure caused by skill drift is drift: fix it under edit scope and retry once — restart whatever the fix invalidated, nothing more — before calling the pass `blocked`. A feature that can't be reached is `verified-unreachable` only with the concrete prerequisite (auth, entitlement, OS, external state) and the route attempted; if the map omits that prerequisite, that's drift. Any harness fix from triage gets re-driven live before it ships. Final teardown happens after the last drive of the run — including those re-proofs — so nothing outlives the run (evidence stays, per the skill). -5. **Triage.** Wrong or missing user-POV description → doc drift, fix it. Working behavior the harness can't drive → harness gap, fix it; a harness fix follows the same helpers rule as generation (scripts executable, invocation documented in the skill body). Audit postmortems from recent failed submissions: when a candidate passed local verification but failed the remote grader (e.g. timeout on 2-vCPU runners, thread contention, dense fill explosion), classify this as a harness gap and encode the constraint into the local linter or timing probe before continuing. App behavior that's actually broken → product gap; record it for the user, keep it out of this PR. +5. **Triage.** Wrong or missing user-POV description → doc drift, fix it. Working behavior the harness can't drive → harness gap, fix it; a harness fix follows the same helpers rule as generation (scripts executable, invocation documented in the skill body). Audit postmortems from recent environment failures: when a change passed local verification but failed on a constrained remote target (such as timeouts on low-core runners, thread contention, or memory growth at scale), classify this as a harness gap and encode the constraint into the local linter or timing probe before continuing. App behavior that's actually broken → product gap; record it for the user, keep it out of this PR. 6. **Ship or stop.** For changed: one PR of proven corrections, re-read every changed file first. For clean or blocked: no PR, report the outcome and the coverage honestly. diff --git a/skills/poteto-mode/playbooks/perf-issue.md b/skills/poteto-mode/playbooks/perf-issue.md index 16f7f15..dec5206 100644 --- a/skills/poteto-mode/playbooks/perf-issue.md +++ b/skills/poteto-mode/playbooks/perf-issue.md @@ -2,18 +2,19 @@ **You own the measurement story. Plan, review, verify the numbers.** Tie every fix to a measurement, don't read source instead of measuring. -1. Capture a baseline trace via the matching control skill. -2. `how` to ground hypotheses; don't claim a perf ceiling without running it first. Validate measurement viability against the **benchmark-checklist** skill (tuning flags, arithmetic limits, and lazy execution checks). - Most fixes come from eight strategy families. Use them as hypothesis generators, not a checklist. A family earns an attempt only when the trace shows the signal it names, and a focused fix for the dominant cost beats applying all eight. - - **Elimination.** The cheapest work is work that doesn't run. Before optimizing the hot path, ask whether it needs to exist: a computation nobody consumes, a feature gate that's always off for this user, a sync that redundantly mirrors state, a legacy path kept "just in case". The trace shows what's slow, never that it's deletable, so this family needs the `how` pass, not the profiler. Deleting the work beats every other family when it applies. - - **Divide and conquer.** The dominant cost scales with input size. Split the work so each piece touches less (chunk, shard, prune the search space) or so independent pieces run in parallel. - - **Caching.** The same computation or fetch repeats on identical inputs. Store and reuse the result; name what invalidates it before claiming the win. - - **Indirection.** The hot path does expensive work a cheaper intermediate could absorb: an index instead of a scan, a queue that shifts work off the interactive thread, a handle that lets a cheaper implementation swap in. Add the hop only when it removes more from the critical path than it adds; a layer that sits on the hot path without removing work is pure cost. - - **Batching.** Many small operations each pay a fixed overhead (RPC, query, syscall, draw call). Coalesce them to pay the overhead once per batch. - - **Redundancy.** The wait hangs on one slow instance or attempt. Duplicate the work (replicas, hedged requests, speculative execution) and take the fastest result. This trades extra load for lower tail latency, so the trace has to show the wait dominates and the system has headroom; duplication without that tradeoff only adds load. - - **Lazy evaluation.** Cost lands on results that are never used or not needed yet (eager init on the boot path, rendering offscreen items). Defer the work until first use. - - **Scheduling.** The work must happen, but not during the interactive moment. Move it to where nobody is waiting: idle callbacks, a background warmup after boot, precompute before the user arrives, cleanup after the frame commits. Distinct from Lazy (later-when-needed): Scheduling often runs the work *earlier* than the hot moment, or in its shadow. The win is perceived latency, so measure the interactive path, not total work done. -3. Plan the fix from the trace. If it crosses a function boundary, `architect` first. Delegate implementation to a subagent using your configured perf-issue model (default `pro`); review the diff. Capture a post-fix trace. +1. Capture a baseline trace via the matching control skill. Vet the baseline, and each later number, with the **benchmark-checklist** skill. +2. Trace the code to ground hypotheses. Don't claim a perf ceiling without running it first. + Try the performance mantras in order, cheapest first: + 1. Don't do it. Stop work whose result nothing uses rather than cheapening it. + 2. Do it, but don't do it again. + 3. Do it less. + 4. Do it later. + 5. Do it when they're not looking. + 6. Do it concurrently. + 7. Do it cheaper. + + When an earlier mantra meets the target, stop. +3. Plan the fix from the trace. If it crosses a function boundary, `architect` first. Delegate implementation via `invoke_subagent` using your configured `perf-issue` model (default `inherit`; see `agystack-models.md`); review the diff. Capture a post-fix trace. Apply the **sequence-verifiable-units** principle skill, verifying each attempt before trying the next. 4. Parse and compare the artifacts (JSON to sqlite, diff). "Inconclusive" or wrong-surface is not a pass; flag it. Run the **benchmark-checklist** skill and apply the **explain-the-number** principle (**principle-explain-the-number**) before claiming wins or publishing numbers. Name the physical bottleneck and hardware/kernel root cause rather than guessing from code. Publish the full comparative analysis, charts, and trace diffs to `/brain//perf_report.md` (or `walkthrough.md`) artifact. 5. Cite the measurement in the PR. diff --git a/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts b/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts index 2312522..84ccf59 100644 --- a/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +++ b/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts @@ -7,7 +7,9 @@ import type { PrContext, PullRequestFacts, Repository, + RawReviewThread, ReviewThread, + ReviewThreadPage, RollupPage, } from "./types.ts"; import { parsePrNumber } from "./types.ts"; @@ -17,12 +19,17 @@ export interface FakeReaderOptions { readonly fastPath?: ChecksFastPath; readonly rollupPages?: readonly RollupPage[]; readonly threads?: readonly ReviewThread[]; + readonly threadPages?: readonly ReviewThreadPage[]; readonly commitRollups?: readonly CommitRollup[]; readonly openPullRequests?: readonly OpenPullRequest[]; readonly origin?: Repository | null; readonly current?: PrContext; } +function toRawThread(thread: ReviewThread): RawReviewThread { + return { id: thread.id, firstComment: thread.firstComment, resolved: false }; +} + export function passingCheck(name = "ci"): Check { return { kind: "passed", @@ -78,6 +85,7 @@ export function fakeReader( isDraft: false, }; let page = 0; + let threadPage = 0; return { calls, async originRepo() { @@ -106,9 +114,12 @@ export function fakeReader( calls.push(`checkRollupPage:${after ?? "null"}`); return options.rollupPages?.[page++] ?? { checks: [], endCursor: null }; }, - async reviewThreads() { - calls.push("reviewThreads"); - return options.threads ?? []; + async reviewThreadPage(_requested, after) { + calls.push(`reviewThreadPage:${after ?? "null"}`); + return options.threadPages?.[threadPage++] ?? { + threads: (options.threads ?? []).map(toRawThread), + endCursor: null, + }; }, async commitRollups() { calls.push("commitRollups"); diff --git a/skills/poteto-mode/scripts/watch-pr/github.test.ts b/skills/poteto-mode/scripts/watch-pr/github.test.ts index bd30653..860e042 100644 --- a/skills/poteto-mode/scripts/watch-pr/github.test.ts +++ b/skills/poteto-mode/scripts/watch-pr/github.test.ts @@ -1,14 +1,20 @@ import { describe, expect, it } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { ChecksUnavailable, - GhGitHubReader, WatcherQueryError, + buildReviewThreads, mapRollupNode, orderStack, + parseFastCheck, parsePullRequest, - parseReviewThreads, + parseReviewThreadPage, resolveChecks, resolveContext, + resolveReviewThreads, } from "./github.ts"; import { fakeReader, @@ -120,6 +126,37 @@ describe("rollup node mapping", () => { ).toMatchObject({ kind: "code-review-gate" }); }); + it("classifies a Code Review Gate waiting on an owner approval as the gate", () => { + expect( + mapRollupNode({ + __typename: "CheckRun", + name: "Code Review Gate", + status: "COMPLETED", + conclusion: "ACTION_REQUIRED", + description: "1 of 2 policies", + }) + ).toMatchObject({ + kind: "code-review-gate", + reportedState: "ACTION_REQUIRED", + }); + }); + + it("classifies a fast-path Code Review Gate waiting on an owner approval as the gate", () => { + expect( + parseFastCheck({ + name: "Code Review Gate", + state: "ACTION_REQUIRED", + bucket: "fail", + }) + ).toMatchObject({ + kind: "code-review-gate", + reportedState: "ACTION_REQUIRED", + }); + expect( + parseFastCheck({ name: "ci", state: "ACTION_REQUIRED", bucket: "fail" }) + ).toMatchObject({ kind: "failed", reportedState: "ACTION_REQUIRED" }); + }); + it("maps StatusContext states and drops unknown typenames", () => { expect( mapRollupNode({ @@ -199,6 +236,7 @@ it("annotates Bugbot threads with distinct review-pass counts", () => { repository: { pullRequest: { reviewThreads: { + pageInfo: { hasNextPage: false, endCursor: null }, nodes: [ { id: "one", @@ -251,12 +289,107 @@ it("annotates Bugbot threads with distinct review-pass counts", () => { }, }, }; - const threads = parseReviewThreads(response); + const threads = buildReviewThreads(parseReviewThreadPage(response).threads); expect(threads).toHaveLength(2); expect(threads.map((thread) => thread.isBugbot)).toEqual([true, true]); expect(threads.map((thread) => thread.bugbotReviewPasses)).toEqual([3, 3]); }); +describe("review thread pagination", () => { + const thread = (id: string, resolved = false) => ({ + id, + firstComment: { + authorLogin: "someone", + body: "please fix", + path: "a.ts", + line: 1, + createdAt: "now", + }, + resolved, + }); + + it("keeps walking pages until the cursor is exhausted", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("one")], endCursor: "next" }, + { threads: [thread("two")], endCursor: "last" }, + { threads: [thread("three")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, context); + expect(threads.map((item) => item.id)).toEqual(["one", "two", "three"]); + expect(reader.calls).toEqual([ + "reviewThreadPage:null", + "reviewThreadPage:next", + "reviewThreadPage:last", + ]); + }); + + it("sees an unresolved thread that sits past the first page", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("early", true)], endCursor: "next" }, + { threads: [thread("late")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, context); + expect(threads.map((item) => item.id)).toEqual(["late"]); + }); + + it("stops after a single page when the cursor is exhausted", async () => { + const reader = fakeReader({ + threadPages: [{ threads: [thread("only")], endCursor: null }], + }); + expect((await resolveReviewThreads(reader, context)).length).toBe(1); + expect(reader.calls).toEqual(["reviewThreadPage:null"]); + }); + + it("counts Bugbot review passes across every page", async () => { + const bugbot = (id: string, runId: string) => ({ + id, + firstComment: { + authorLogin: "bugbot", + body: `RUN_ID: ${runId}`, + path: "a.ts", + line: 1, + createdAt: "now", + }, + resolved: false, + }); + const reader = fakeReader({ + threadPages: [ + { threads: [bugbot("one", "run-1")], endCursor: "next" }, + { threads: [bugbot("two", "run-2")], endCursor: null }, + ], + }); + const threads = await resolveReviewThreads(reader, context); + expect(threads.map((item) => item.bugbotReviewPasses)).toEqual([2, 2]); + }); + + it("drops resolved threads from later pages too", async () => { + const reader = fakeReader({ + threadPages: [ + { threads: [thread("one")], endCursor: "next" }, + { threads: [thread("two", true)], endCursor: null }, + ], + }); + expect( + (await resolveReviewThreads(reader, context)).map((item) => item.id) + ).toEqual(["one"]); + }); + + it("rejects a page that omits pageInfo instead of assuming one page", async () => { + const response = { + data: { + repository: { + pullRequest: { reviewThreads: { nodes: [] } }, + }, + }, + }; + expect(() => parseReviewThreadPage(response)).toThrow(WatcherQueryError); + }); +}); + describe("context and stack discovery", () => { it("returns a fully explicit context without any reader call", async () => { const reader = fakeReader(); @@ -289,124 +422,77 @@ describe("context and stack discovery", () => { { number: parsePrNumber(41), headRefName: "base-feature", + isCrossRepository: false, baseRefName: "main", }, { number: context.number, headRefName: "feature", + isCrossRepository: false, baseRefName: "base-feature", }, { number: parsePrNumber(43), headRefName: "upstack", + isCrossRepository: false, baseRefName: "feature", }, ]); expect(ordered.map((item) => Number(item.number))).toEqual([41, 42, 43]); }); -}); - -describe("review thread pagination", () => { - it("paginates GraphQL reviewThreads across pages and resolves over 100 threads", async () => { - const page1Nodes = Array.from({ length: 70 }, (_, i) => ({ - id: `thread-${i}`, - isResolved: false, - comments: { - nodes: [ - { - body: `thread body ${i}`, - createdAt: "2026-10-21T00:00:00Z", - path: `file-${i}.ts`, - line: i + 1, - author: { login: `author-${i}` }, - }, - ], - }, - })); - const page2Nodes = Array.from({ length: 50 }, (_, i) => ({ - id: `thread-${70 + i}`, - isResolved: false, - comments: { - nodes: [ - { - body: `thread body ${70 + i}`, - createdAt: "2026-10-21T00:00:00Z", - path: `file-${70 + i}.ts`, - line: i + 1, - author: { login: `author-${70 + i}` }, - }, - ], - }, - })); + it("does not use a fork's same-named head as a stack parent", () => { + const ordered = orderStack(context, [ + { number: parsePrNumber(41), headRefName: "base-feature", baseRefName: "main", isCrossRepository: true }, + { number: context.number, headRefName: "feature", baseRefName: "base-feature", isCrossRepository: false }, + ]); + expect(ordered.map((item) => Number(item.number))).toEqual([42]); + }); - const capturedCalls: string[][] = []; - const reader = new GhGitHubReader(async (argv) => { - capturedCalls.push([...argv]); - const afterArg = argv.find((arg) => arg.startsWith("after=")); - if (!afterArg) { - return { - data: { - repository: { - pullRequest: { - reviewThreads: { - pageInfo: { - hasNextPage: true, - endCursor: "cursor-page-1", - }, - nodes: page1Nodes, - }, - }, - }, - }, - }; - } - expect(afterArg).toBe("after=cursor-page-1"); - return { - data: { - repository: { - pullRequest: { - reviewThreads: { - pageInfo: { - hasNextPage: false, - endCursor: null, - }, - nodes: page2Nodes, - }, - }, - }, - }, - }; - }); + it("does not attach upstream branch children to a fork head", () => { + const ordered = orderStack(context, [ + { number: context.number, headRefName: "feature", baseRefName: "main", isCrossRepository: true }, + { number: parsePrNumber(43), headRefName: "upstack", baseRefName: "feature", isCrossRepository: false }, + ]); + expect(ordered.map((item) => Number(item.number))).toEqual([42]); + }); - const threads = await reader.reviewThreads(context); - expect(threads).toHaveLength(120); - expect(capturedCalls).toHaveLength(2); - expect(threads[0].id).toBe("thread-0"); - expect(threads[119].id).toBe("thread-119"); + it("terminates when an unrelated fork opens main against main", () => { + const program = `import { orderStack } from ${JSON.stringify(import.meta.dir + "/github.ts")}; + console.log(JSON.stringify(orderStack(${JSON.stringify(context)}, [ + { number: 41, headRefName: "main", baseRefName: "main", isCrossRepository: true }, + { number: 42, headRefName: "feature", baseRefName: "main", isCrossRepository: false } + ])));`; + const child = spawnSync(process.execPath, ["-e", program], { encoding: "utf8", timeout: 2000 }); + expect(child.error).toBeUndefined(); + expect(child.status).toBe(0); + expect(JSON.parse(child.stdout).map((item: { number: number }) => item.number)).toEqual([42]); }); - it("handles nodes array directly in parseReviewThreads", () => { - const nodes = [ - { - id: "direct-node-1", - isResolved: false, - comments: { - nodes: [ - { - body: "comment 1", - createdAt: "now", - path: "test.ts", - line: 1, - author: { login: "alice" }, - }, - ], - }, - }, - ]; - const threads = parseReviewThreads(nodes); - expect(threads).toHaveLength(1); - expect(threads[0].id).toBe("direct-node-1"); + it("requests and parses fork identity from gh before stack discovery", () => { + const directory = mkdtempSync(join(tmpdir(), "watch-pr-fork-")); + try { + writeFileSync(join(directory, "gh"), `#!/bin/sh +case "$*" in + *number,headRefName,baseRefName,isCrossRepository*) ;; + *) exit 2 ;; +esac +printf '%s\\n' '[{"number":42,"headRefName":"feature","baseRefName":"main","isCrossRepository":true}]' +`, { mode: 0o755 }); + const program = `import { GhGitHubReader } from ${JSON.stringify(import.meta.dir + "/github.ts")}; + console.log(JSON.stringify(await new GhGitHubReader().openPullRequests({ owner: "owner", repo: "repo" })));`; + const child = spawnSync(process.execPath, ["-e", program], { + encoding: "utf8", timeout: 2000, + env: { ...process.env, PATH: directory + ":" + process.env.PATH }, + }); + expect(child.error).toBeUndefined(); + expect(child.status).toBe(0); + expect(JSON.parse(child.stdout)).toEqual([ + { number: 42, headRefName: "feature", baseRefName: "main", isCrossRepository: true }, + ]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } }); }); diff --git a/skills/poteto-mode/scripts/watch-pr/github.ts b/skills/poteto-mode/scripts/watch-pr/github.ts index eb735cb..b713a0f 100644 --- a/skills/poteto-mode/scripts/watch-pr/github.ts +++ b/skills/poteto-mode/scripts/watch-pr/github.ts @@ -237,22 +237,20 @@ export function parseFastCheck(value: unknown): T.Check { const details = checkDetails(object, "name"); const state = string(object.state, "check.state").toUpperCase(); const bucket = string(object.bucket, "check.bucket"); - if ( - bucket === "fail" || - ["FAILURE", "ERROR", "ACTION_REQUIRED"].includes(state) - ) + if (state === "ACTION_REQUIRED") return gateOr("failed", details, state); + if (bucket === "fail" || ["FAILURE", "ERROR"].includes(state)) return { ...details, kind: "failed", reportedState: state }; - if (bucket === "pending") return pendingOrGate(details, state); + if (bucket === "pending") return gateOr("pending", details, state); if (bucket === "pass") return { ...details, kind: "passed", reportedState: state }; if (bucket === "skipping") return { ...details, kind: "skipped", reportedState: state }; return { ...details, kind: "failed", reportedState: state }; } -// The owner-approval gate is excluded from pending everywhere, so the rule has -// one home. Classifying it as pending on either read path makes the watcher -// wait on a human, which is the behaviour #172004 removed from the Python. -function pendingOrGate( +const OWNER_APPROVAL_GATE_CHECK = "Code Review Gate"; + +function gateOr( + kind: "pending" | "failed", details: { readonly name: string; readonly description: string; @@ -261,14 +259,14 @@ function pendingOrGate( }, reportedState: string ): T.Check { - return details.name === "Code Review Gate" + return details.name === OWNER_APPROVAL_GATE_CHECK ? { ...details, kind: "code-review-gate", - name: "Code Review Gate", + name: OWNER_APPROVAL_GATE_CHECK, reportedState, } - : { ...details, kind: "pending", reportedState }; + : { ...details, kind, reportedState }; } export function mapRollupNode(value: unknown): T.Check | null { const object = record(value, "rollup node"); @@ -288,22 +286,19 @@ export function mapRollupNode(value: unknown): T.Check | null { ? object.conclusion.toUpperCase() : ""; if (status !== "COMPLETED") - return pendingOrGate({ ...details, link }, "PENDING"); + return gateOr("pending", { ...details, link }, "PENDING"); if (conclusion === "SUCCESS") return { ...details, link, kind: "passed", reportedState: "SUCCESS" }; if (conclusion === "NEUTRAL" || conclusion === "SKIPPED") return { ...details, link, kind: "skipped", reportedState: conclusion }; - return { - ...details, - link, - kind: "failed", - reportedState: conclusion === "ACTION_REQUIRED" ? conclusion : "FAILURE", - }; + if (conclusion === "ACTION_REQUIRED") + return gateOr("failed", { ...details, link }, conclusion); + return { ...details, link, kind: "failed", reportedState: "FAILURE" }; } const state = typeof object.state === "string" ? object.state.toUpperCase() : ""; if (state === "PENDING" || state === "EXPECTED") - return pendingOrGate({ ...details, link }, "PENDING"); + return gateOr("pending", { ...details, link }, "PENDING"); return state === "SUCCESS" ? { ...details, link, kind: "passed", reportedState: state } : { ...details, link, kind: "failed", reportedState: state || "FAILURE" }; @@ -357,27 +352,13 @@ function passKey(comment: T.ReviewComment | null): string | null { } return null; } -export function parseReviewThreads(value: unknown): readonly T.ReviewThread[] { - let nodes: readonly unknown[]; - if (Array.isArray(value)) { - nodes = value; - } else if ( - isRecord(value) && - "nodes" in value && - Array.isArray(value.nodes) - ) { - nodes = value.nodes; - } else { - nodes = list( - at(value, ["data", "repository", "pullRequest", "reviewThreads", "nodes"]), - "reviewThreads.nodes" - ); - } - const threads: { - readonly id: string; - readonly firstComment: T.ReviewComment | null; - readonly resolved: boolean; - }[] = []; +export function parseReviewThreadPage(value: unknown): T.ReviewThreadPage { + const reviewThreads = record( + at(value, ["data", "repository", "pullRequest", "reviewThreads"]), + "reviewThreads" + ); + const nodes = list(reviewThreads.nodes, "reviewThreads.nodes"); + const threads: T.RawReviewThread[] = []; for (const node of nodes) { const thread = record(node, "review thread"); if (typeof thread.isResolved !== "boolean") @@ -392,6 +373,18 @@ export function parseReviewThreads(value: unknown): readonly T.ReviewThread[] { resolved: thread.isResolved, }); } + const page = record(reviewThreads.pageInfo, "reviewThreads.pageInfo"); + if (typeof page.hasNextPage !== "boolean") + missing("reviewThreads.pageInfo.hasNextPage", page.hasNextPage); + const cursor = optionalString( + page.endCursor, + "reviewThreads.pageInfo.endCursor" + ); + return { threads, endCursor: page.hasNextPage && cursor ? cursor : null }; +} +export function buildReviewThreads( + threads: readonly T.RawReviewThread[] +): readonly T.ReviewThread[] { const keys = new Set(); let keyless = false; for (const thread of threads) { @@ -462,11 +455,6 @@ function graphqlArgs( } export class GhGitHubReader implements T.GitHubReader { - constructor( - private readonly runJsonFn: ( - argv: readonly [string, ...string[]] - ) => Promise = runJson - ) {} async originRepo(): Promise { const result = await run(["git", "remote", "get-url", "origin"]); return result.code === 0 ? parseRemote(result.stdout) : null; @@ -511,11 +499,14 @@ export class GhGitHubReader implements T.GitHubReader { "--limit", "300", "--json", - "number,headRefName,baseRefName", + "number,headRefName,baseRefName,isCrossRepository", ]); return list(value, "open PRs").map((item, index) => { const object = record(item, `open PRs[${index}]`); + if (typeof object.isCrossRepository !== "boolean") + missing(`open PRs[${index}].isCrossRepository`, object.isCrossRepository); return { + isCrossRepository: object.isCrossRepository, number: parsePrNumber(object.number, `open PRs[${index}].number`), headRefName: string( object.headRefName, @@ -584,32 +575,13 @@ export class GhGitHubReader implements T.GitHubReader { ); return { checks, endCursor: page.hasNextPage && cursor ? cursor : null }; } - async reviewThreads( - context: T.PrContext - ): Promise { - const allNodes: unknown[] = []; - let cursor: string | null = null; - while (true) { - const argv = graphqlArgs(REVIEW_THREADS_QUERY, context); - if (cursor !== null) argv.push("-f", `after=${cursor}`); - const value = await (this.runJsonFn ?? runJson)(argv); - const threads = record( - at(value, ["data", "repository", "pullRequest", "reviewThreads"]), - "reviewThreads" - ); - const nodes = list(threads.nodes, "reviewThreads.nodes"); - allNodes.push(...nodes); - const page = record(threads.pageInfo, "reviewThreads.pageInfo"); - if (typeof page.hasNextPage !== "boolean") - missing("reviewThreads.pageInfo.hasNextPage", page.hasNextPage); - const endCursor = optionalString( - page.endCursor, - "reviewThreads.pageInfo.endCursor" - ); - if (!page.hasNextPage || !endCursor) break; - cursor = endCursor; - } - return parseReviewThreads(allNodes); + async reviewThreadPage( + context: T.PrContext, + after: string | null + ): Promise { + const argv = graphqlArgs(REVIEW_THREADS_QUERY, context); + if (after !== null) argv.push("-f", `after=${after}`); + return parseReviewThreadPage(await runJson(argv)); } async commitRollups( context: T.PrContext @@ -659,6 +631,19 @@ export async function resolveChecks( : "fast path and GraphQL rollup were empty"; throw new ChecksUnavailable(`could not read PR checks: ${suffix}`); } +export async function resolveReviewThreads( + reader: T.GitHubReader, + context: T.PrContext +): Promise { + const threads: T.RawReviewThread[] = []; + let after: string | null = null; + do { + const page = await reader.reviewThreadPage(context, after); + threads.push(...page.threads); + after = page.endCursor; + } while (after !== null); + return buildReviewThreads(threads); +} export async function resolveContext(args: { readonly reader: T.GitHubReader; readonly owner: string | null; @@ -688,7 +673,11 @@ export function orderStack( open: readonly T.OpenPullRequest[] ): T.NonEmpty { const byNumber = new Map(open.map((pr) => [pr.number, pr])); - const byHead = new Map(open.map((pr) => [pr.headRefName, pr])); + // A base ref belongs to this repository. A fork head with the same name + // cannot be its parent, even when that name is the default branch. + const byHead = new Map( + open.filter((pr) => !pr.isCrossRepository).map((pr) => [pr.headRefName, pr]) + ); const children = new Map(); for (const pr of open) children.set(pr.baseRefName, [...(children.get(pr.baseRefName) ?? []), pr]); @@ -710,6 +699,7 @@ export function orderStack( ]); const up: T.OpenPullRequest[] = []; const visit = (parent: T.OpenPullRequest): void => { + if (parent.isCrossRepository) return; for (const child of children.get(parent.headRefName) ?? []) { if (seen.has(child.number)) continue; seen.add(child.number); diff --git a/skills/poteto-mode/scripts/watch-pr/policy.test.ts b/skills/poteto-mode/scripts/watch-pr/policy.test.ts index 0620dde..1b50403 100644 --- a/skills/poteto-mode/scripts/watch-pr/policy.test.ts +++ b/skills/poteto-mode/scripts/watch-pr/policy.test.ts @@ -10,6 +10,7 @@ import { queryBackoffSeconds, readSnapshot, runQueued, + runSimple, selectTierMajorStackDecision, } from "./policy.ts"; import { @@ -106,7 +107,7 @@ describe("snapshot query planning", () => { expect(snapshot.ci.kind).toBe("ci-pending"); expect(reader.calls).toEqual([ "pullRequest", - "reviewThreads", + "reviewThreadPage:null", "checksFastPath", ]); }); @@ -418,3 +419,62 @@ it("uses the specified retry floor and cap", () => { expect(queryBackoffSeconds(1, 2)).toBe(120); expect(queryBackoffSeconds(60, 4)).toBe(300); }); + +describe("polling deadline sleeps", () => { + for (const mode of ["single", "queued-stack", "query-retry"] as const) { + it(`caps ${mode} sleeps at the configured deadline`, async () => { + let now = 0; + const sleeps: number[] = []; + const pending = fakeReader({ fastPath: { kind: "checks", checks: [pendingCheck()] } }); + const reader = mode === "query-retry" + ? { ...pending, async pullRequest(): Promise { + throw new WatcherQueryError({ kind: "command-exit", retryable: true, code: 1, detail: "temporary failure" }); + } } + : pending; + const dependencies = { + reader, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds: number) { sleeps.push(seconds); now += seconds; }, + }, + emit() {}, + }; + const polling = { ...options, interval: 60, timeout: 5 }; + const result = mode === "queued-stack" + ? await runQueued({ dependencies, contexts: [context(1)], options: polling }) + : await runSimple({ dependencies, contexts: [context(1)], mode: "single", statusOnly: false, options: polling }); + expect(result.kind).toBe("TIMEOUT"); + expect(sleeps).toEqual([5]); + expect(now).toBe(5); + }); + } + it("preserves the polling interval when the deadline is disabled", async () => { + let now = 0; + let reads = 0; + const sleeps: number[] = []; + const pending = fakeReader({ fastPath: { kind: "checks", checks: [pendingCheck()] } }); + const passed = fakeReader({ fastPath: { kind: "checks", checks: [passingCheck()] } }); + const result = await runSimple({ + dependencies: { + reader: { + ...pending, + async checksFastPath(pr) { + reads += 1; + return reads === 1 ? pending.checksFastPath(pr) : passed.checksFastPath(pr); + }, + }, + clock: { + now: () => now, + observedAt: () => "2026-07-26T00:00:00.000Z", + async sleep(seconds) { sleeps.push(seconds); now += seconds; }, + }, + emit() {}, + }, + contexts: [context(1)], mode: "single", statusOnly: false, + options: { ...options, interval: 60, timeout: 0 }, + }); + expect(result.kind).toBe("READY"); + expect(sleeps).toEqual([60]); + }); +}); diff --git a/skills/poteto-mode/scripts/watch-pr/policy.ts b/skills/poteto-mode/scripts/watch-pr/policy.ts index 4665be3..8179f2d 100644 --- a/skills/poteto-mode/scripts/watch-pr/policy.ts +++ b/skills/poteto-mode/scripts/watch-pr/policy.ts @@ -1,4 +1,8 @@ -import { WatcherQueryError, resolveChecks } from "./github.ts"; +import { + WatcherQueryError, + resolveChecks, + resolveReviewThreads, +} from "./github.ts"; import type * as T from "./types.ts"; import { nonEmpty } from "./types.ts"; export function assessGitHubMerge(args: { @@ -63,7 +67,7 @@ export async function readSnapshot(args: { return { kind: "merged", context: args.context, facts }; if (facts.state === "CLOSED") return { kind: "closed", context: args.context, facts }; - const threads = await args.reader.reviewThreads(args.context); + const threads = await resolveReviewThreads(args.reader, args.context); const checks = await resolveChecks(args.reader, args.context); const failed = nonEmpty( checks.checks.filter( @@ -366,6 +370,12 @@ async function pollUntilTerminal(args: { }): Promise { let failures = 0; const started = args.dependencies.clock.now(); + const sleep = async (seconds: number): Promise => { + const remaining = args.options.timeout > 0 + ? Math.max(0, args.options.timeout - (args.dependencies.clock.now() - started)) + : seconds; + await args.dependencies.clock.sleep(Math.min(seconds, remaining)); + }; while (true) { let result: StepResult; try { @@ -396,7 +406,7 @@ async function pollUntilTerminal(args: { exitCode: 5, reason: { kind: "status-unavailable", failure: error.failure }, }); - await args.dependencies.clock.sleep(retryInSeconds); + await sleep(retryInSeconds); continue; } if (result.kind === "terminal") return result.verdict; @@ -406,7 +416,7 @@ async function pollUntilTerminal(args: { deadlinePassed(started, args.options, args.dependencies.clock.now()) ) return result.onDeadline(); - await args.dependencies.clock.sleep(result.seconds); + await sleep(result.seconds); } } } diff --git a/skills/poteto-mode/scripts/watch-pr/types.ts b/skills/poteto-mode/scripts/watch-pr/types.ts index b67144e..60b9abc 100644 --- a/skills/poteto-mode/scripts/watch-pr/types.ts +++ b/skills/poteto-mode/scripts/watch-pr/types.ts @@ -52,6 +52,7 @@ export interface PullRequestFacts { } export interface OpenPullRequest { readonly number: PrNumber; + readonly isCrossRepository: boolean; readonly headRefName: string; readonly baseRefName: string; } @@ -379,6 +380,15 @@ export interface RollupPage { readonly checks: readonly Check[]; readonly endCursor: string | null; } +export interface RawReviewThread { + readonly id: string; + readonly firstComment: ReviewComment | null; + readonly resolved: boolean; +} +export interface ReviewThreadPage { + readonly threads: readonly RawReviewThread[]; + readonly endCursor: string | null; +} export interface GitHubReader { originRepo(): Promise; currentPr(pr: PrNumber | null): Promise; @@ -389,7 +399,10 @@ export interface GitHubReader { context: PrContext, after: string | null ): Promise; - reviewThreads(context: PrContext): Promise; + reviewThreadPage( + context: PrContext, + after: string | null + ): Promise; commitRollups(context: PrContext): Promise; } export interface PollingOptions { diff --git a/skills/poteto-mode/scripts/worktree-audit.sh b/skills/poteto-mode/scripts/worktree-audit.sh index 18df791..b0179d6 100755 --- a/skills/poteto-mode/scripts/worktree-audit.sh +++ b/skills/poteto-mode/scripts/worktree-audit.sh @@ -4,121 +4,115 @@ # operated in it. Emits a table sorted by size with a suggested bucket. Never # deletes anything; deletion stays a human-gated step in the playbook. # -# Usage: worktree-audit.sh [-b ] [repo-path] (defaults to current repo) +# Usage: worktree-audit.sh [-b|--base ] [repo-path] +# repo-path defaults to the current repo. +# -b sets the ref the MERGED column checks against (e.g. origin/integration). +# Without it the base is origin/HEAD, then origin/main, then origin/master. +# origin/HEAD is the remote's default branch, not necessarily the branch PRs +# merge into; pass -b when they differ. set -u -usage() { - cat <<'EOF' -Usage: worktree-audit.sh [-b ] [repo-path] - -Classifies every git worktree by size, merge state, uncommitted work, -remote/PR state, and the most recent chat that operated in it. - -Options: - -b Specify the base branch for merge checks (e.g. origin/main, release) - -h, --help Show this help message and exit -EOF - exit 0 -} - -base_branch="" -repo="" - +base="" while [ $# -gt 0 ]; do case "$1" in - -h|--help) - usage - ;; - -b) - shift - if [ $# -eq 0 ]; then - echo "error: -b requires an argument" >&2 - exit 1 - fi - base_branch="$1" - shift - ;; - -b*) - base_branch="${1#-b}" - shift - ;; - --) - shift - break - ;; - -*) - echo "error: unknown option: $1" >&2 - exit 1 - ;; - *) - if [ -z "$repo" ]; then - repo="$1" - else - echo "error: unexpected extra argument: $1" >&2 - exit 1 - fi - shift - ;; + -b|--base) + [ $# -ge 2 ] || { echo "error: $1 needs a ref" >&2; exit 2; } + base="$2" + shift 2 + ;; + -b?*) + base="${1#-b}" + shift + ;; + -h|--help) + sed -n '2,/^set -u/p' "$0" | sed '$d; s/^# \{0,1\}//' + exit 0 + ;; + --) + shift + break + ;; + -*) + echo "error: unknown option: $1" >&2 + exit 2 + ;; + *) + break + ;; esac done -[ -z "$repo" ] && repo="$(git rev-parse --show-toplevel 2>/dev/null)" +if [ $# -gt 1 ]; then + echo "error: unexpected extra argument: $2" >&2 + exit 2 +fi + +repo="${1:-$(git rev-parse --show-toplevel 2>/dev/null)}" [ -z "$repo" ] && { echo "not in a git repo; pass a repo path" >&2; exit 1; } cd "$repo" || exit 1 - -if [ -z "$base_branch" ]; then - if ref=$(git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null); then - base_branch="${ref#refs/remotes/}" - elif git rev-parse --verify --quiet origin/main >/dev/null 2>&1; then - base_branch="origin/main" - elif git rev-parse --verify --quiet origin/master >/dev/null 2>&1; then - base_branch="origin/master" - else - base_branch="main" - fi -fi +git rev-parse --git-dir >/dev/null 2>&1 || { echo "error: not a git repo: $repo" >&2; exit 1; } # Main worktree is the first entry; everything else is a candidate. main_wt=$(git worktree list --porcelain | awk '/^worktree /{print substr($0, 10); exit}') -# Best-effort fetch of base branch; stale is fine for a first pass. -case "$base_branch" in - */*) - fetch_remote="${base_branch%%/*}" - fetch_ref="${base_branch#*/}" - git fetch "$fetch_remote" "$fetch_ref" --quiet 2>/dev/null || echo "warn: could not fetch $base_branch; merged column may be stale" >&2 - ;; - *) - git fetch origin "$base_branch" --quiet 2>/dev/null || true - ;; +if [ -z "$base" ]; then + for cand in "$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null)" origin/main origin/master; do + [ -n "$cand" ] && git rev-parse --verify --quiet "$cand^{commit}" >/dev/null && { base="$cand"; break; } + done + [ -z "$base" ] && { echo "error: no base ref (origin/HEAD, origin/main, origin/master all missing); pass -b " >&2; exit 1; } + echo "warn: no -b given; MERGED checks against $base" >&2 +fi + +# The explicit refspec creates it even in a single-branch clone. +case "$base" in +origin/*) git fetch origin "+refs/heads/${base#origin/}:refs/remotes/$base" --quiet 2>/dev/null \ + || echo "warn: could not fetch $base; merged column may be stale" >&2 ;; esac +git rev-parse --verify --quiet "$base^{commit}" >/dev/null 2>&1 || { echo "error: base ref not found: $base" >&2; exit 1; } + +# GNU coreutils (Linux, Homebrew gnubin) reads `stat -f` as file system status +# and `date -r` as a file, so pick the stat and date flags once. +if stat -c %Y / >/dev/null 2>&1; then + stat_fmt=(-c '%Y %n') +else + stat_fmt=(-f '%m %N') +fi +if date -d '@0' '+%Y-%m-%d' >/dev/null 2>&1; then + fmt_day() { date -d "@$1" '+%Y-%m-%d'; } +else + fmt_day() { date -r "$1" '+%Y-%m-%d'; } +fi -# PR state by branch, fetched once. Empty if gh is unavailable. prs=$(mktemp) trap 'rm -f "$prs"' EXIT INT TERM -gh pr list --author "@me" --state all --limit 1000 \ - --json number,state,headRefName 2>/dev/null > "$prs" || echo "[]" > "$prs" +if command -v origin >/dev/null 2>&1 \ + && raw=$(origin pr list --author "@me" --state all --limit 1000 \ + --json number,status,headRef 2>/dev/null); then + printf '%s' "$raw" | jq '[.[] | {number, state: (.status // "" | ascii_downcase), head: .headRef}]' > "$prs" 2>/dev/null +elif raw=$(gh pr list --author "@me" --state all --limit 1000 \ + --json number,state,headRefName 2>/dev/null); then + printf '%s' "$raw" | jq '[.[] | {number, state: (.state // "" | ascii_downcase), head: .headRefName}]' > "$prs" 2>/dev/null +fi +[ -s "$prs" ] || echo "[]" > "$prs" # Transcripts dir: Antigravity brain directories agy_ide_transcripts="$HOME/.gemini/antigravity-ide/brain" agy_cli_transcripts="$HOME/.gemini/antigravity/brain" now=$(date +%s) -is_darwin=$([ "$(uname -s)" = "Darwin" ] && echo yes || echo no) -printf "# base: %s\n" "$base_branch" +printf "# base: %s\n" "$base" printf "SIZE\tAGE\tMERGED\tDIRTY\tREMOTE\tPR\tLAST_CHAT\tBUCKET\tWORKTREE\n" git worktree list --porcelain | awk '/^worktree /{print substr($0, 10)}' | while IFS= read -r wt; do [ "$wt" = "$main_wt" ] && continue size=$(du -sh "$wt" 2>/dev/null | awk '{print $1}') + [ -z "$size" ] && size="-" head=$(git -C "$wt" rev-parse HEAD 2>/dev/null) head_ts=$(git -C "$wt" log -1 --format='%ct' HEAD 2>/dev/null || echo 0) age=$([ "$head_ts" -gt 0 ] 2>/dev/null && echo "$(( (now - head_ts) / 86400 ))d" || echo "?") - # Squash-merged branches are not ancestors of main, so PR state is the - # real signal; merge-base only catches fast-forward/rebase merges. - git merge-base --is-ancestor "$head" "$base_branch" 2>/dev/null && merged=YES || merged=no + git merge-base --is-ancestor "$head" "$base" 2>/dev/null && is_base_ancestor=YES || is_base_ancestor=no # Distinguish real WIP (tracked edits) from disposable untracked scratch. porcelain=$(git -C "$wt" status --porcelain 2>/dev/null) @@ -136,7 +130,7 @@ git worktree list --porcelain | awk '/^worktree /{print substr($0, 10)}' | while else remote=no-remote; fi pr=$([ -n "$branch" ] && jq -r --arg b "$branch" \ - '.[] | select(.headRefName==$b) | "#\(.number)/\(.state)"' "$prs" 2>/dev/null | head -1) + '.[] | select(.head==$b) | "#\(.number)/\(.state)"' "$prs" 2>/dev/null | head -1) [ -z "$pr" ] && pr="-" # Most recent chat whose transcript operated in this worktree. Match path @@ -147,33 +141,29 @@ git worktree list --porcelain | awk '/^worktree /{print substr($0, 10)}' | while [ -d "$agy_cli_transcripts" ] && search_dirs+=("$agy_cli_transcripts") if [ ${#search_dirs[@]} -gt 0 ]; then - matched_files=$(rg -l -e "${wt}/" -e "${wt}\"" "${search_dirs[@]}" 2>/dev/null || true) + if command -v rg >/dev/null 2>&1; then + matched_files=$(rg -l -F -e "${wt}/" -e "${wt}\"" "${search_dirs[@]}" 2>/dev/null || true) + else + matched_files=$(grep -rlFI -e "${wt}/" -e "${wt}\"" "${search_dirs[@]}" 2>/dev/null || true) + fi if [ -n "$matched_files" ]; then - if [ "$is_darwin" = yes ]; then - f=$(printf '%s\n' "$matched_files" | xargs stat -f '%m %N' 2>/dev/null | sort -rn | head -1) - if [ -n "$f" ]; then - last_ts=$(echo "$f" | awk '{print $1}') - last=$(date -r "$last_ts" '+%Y-%m-%d' 2>/dev/null || echo "-") - fi - else - f=$(printf '%s\n' "$matched_files" | xargs stat -c '%Y %n' 2>/dev/null | sort -rn | head -1) - if [ -n "$f" ]; then - last_ts=$(echo "$f" | awk '{print $1}') - last=$(date -d "@$last_ts" '+%Y-%m-%d' 2>/dev/null || echo "-") - fi + f=$(printf '%s\n' "$matched_files" | tr '\n' '\0' | xargs -0 stat "${stat_fmt[@]}" 2>/dev/null | sort -rn | head -1) + if [ -n "$f" ]; then + last_ts=$(echo "$f" | awk '{print $1}') + last=$(fmt_day "$last_ts" 2>/dev/null || echo "-") fi fi fi recent=$([ "$last_ts" -gt 0 ] 2>/dev/null && [ $(( (now - last_ts) / 86400 )) -le 4 ] && echo yes || echo no) case "$dirty" in wip:*) bucket=hold-wip ;; *) - case "$pr" in *OPEN*) bucket=hold-open-pr ;; *) + case "$pr" in */open|*/draft) bucket=hold-open-pr ;; *) if [ "$recent" = yes ]; then bucket=verify-recent-chat - elif [ "$merged" = YES ] || [ "$pr" != "-" ]; then bucket=safe + elif [ "$is_base_ancestor" = YES ] || [ "$pr" != "-" ]; then bucket=safe else bucket=review; fi ;; esac ;; esac printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" \ - "$size" "$age" "$merged" "$dirty" "$remote" "$pr" "$last" "$bucket" "$wt" + "$size" "$age" "$is_base_ancestor" "$dirty" "$remote" "$pr" "$last" "$bucket" "$wt" done | sort -t$'\t' -k1,1 -rh