diff --git a/Makefile b/Makefile index 30687cf..819a147 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ PY := $(VENV)/bin/python PATTERNS ?= .patterns LINT_PATHS := scripts/validate-kits.py scripts/run-kit-tests.py scripts/tests claude-code/files claude-code/tests claude-code/scripts/test claude-code/scripts/verify LINT_PATHS += codex/files codex/tests codex/scripts antigravity/files antigravity/tests antigravity/scripts scripts/verify-native-cli.py personal/scripts/vendor-pocock-skills -LINT_PATHS += personal/scripts/vendor-diagram-design personal/scripts/test-diagram-design.py personal/scripts/test-first-mate-detector.py personal/vendor/diagram-design-local/scripts +LINT_PATHS += personal/scripts/vendor-diagram-design personal/scripts/test-diagram-design.py personal/scripts/test-first-mate-detector.py personal/scripts/test-gh-stack-install.py personal/vendor/diagram-design-local/scripts GITLEAKS ?= gitleaks .PHONY: setup check lint test validate security diff --git a/personal/AGENTS.md b/personal/AGENTS.md index 1f641f8..3fe82e7 100644 --- a/personal/AGENTS.md +++ b/personal/AGENTS.md @@ -22,9 +22,12 @@ An acq `hybrid/v1` skill kit. Start with [`README.md`](README.md). - **Check your work:** `scripts/verify` (offline) and, from the repository root, `python scripts/run-kit-tests.py personal`. Both need `python3`; `shellcheck` and `acq` are used when installed. -- The kit has one `commands` entry on purpose: a background startup step that runs - `files/home/paseo-plugins-install.sh` (ADR 0003). Skills are dropped at their final path; +- The kit has two `commands` entries on purpose, both background startup steps: one runs + `files/home/paseo-plugins-install.sh` (ADR 0003) and one runs + `files/home/gh-stack-install.sh` (ADR 0006; moving its pins means changing the tag, + the commit, and both digests together). Skills are dropped at their final path; do not add a step to link or fetch them. It has no `agent:` block, and `caps.network` - lists `github.com` and `registry.npmjs.org`. A new Paseo plugin is one `install_plugin ID git:owner/repo <40-hex>` + lists `github.com`, `api.github.com`, `release-assets.githubusercontent.com` and + `registry.npmjs.org`. A new Paseo plugin is one `install_plugin ID git:owner/repo <40-hex>` (or `npm:pkg `) line in that script; the script refuses unpinned sources and `scripts/verify` section 3d checks it. Read the plugin's source at the pin first. diff --git a/personal/README.md b/personal/README.md index 3b82cfa..18d2887 100644 --- a/personal/README.md +++ b/personal/README.md @@ -5,17 +5,19 @@ that holds the author's personal layer: the skills a coding agent should have in every sandbox, applied last on top of the global kits. It is an opt-in `--kit` mixin. It installs no agent, writes no provider -configuration, and publishes no ports. It runs one background startup command that -installs Paseo plugins (see [Paseo plugins](#paseo-plugins)), and allow-lists one -network hosts, `github.com` and `registry.npmjs.org`, for that command. +configuration, and publishes no ports. It runs two background startup commands: one +installs Paseo plugins (see [Paseo plugins](#paseo-plugins)), the other installs the +`gh stack` extension and its skill (see [gh stack](#gh-stack)). It allow-lists four +network hosts, `github.com`, `api.github.com`, `release-assets.githubusercontent.com` +and `registry.npmjs.org`, for those commands. ## What it ships ```text ~/.agents/skills/ - paseo-first-mate/ the author's own skill (version 1.6.0), its references, and two helper scripts + paseo-first-mate/ the author's own skill (version 1.7.0), its references, and two helper scripts SKILL.md - references/*.md longer procedures the skill links to (delegation, status doc, + references/*.md longer procedures the skill links to (delegation, status map, handoff, host commands, stacking, cross-PR checks) assets/first-mate-check.py change detector (prints nothing when nothing changed) assets/first-mate-wait.sh background wait loop around the detector; one loop per @@ -33,8 +35,19 @@ network hosts, `github.com` and `registry.npmjs.org`, for that command. so no per-agent linking is needed. The skills are written at their final path by the kit's `files[]` records, so they -need no command. The one startup command is the plugin installer below; it is -detached and always exits 0, so nothing it does can fail a sandbox create. +need no command. The two startup commands are the installers below; each is +detached and always exits 0, so nothing they do can fail a sandbox create. + +## gh stack + +At startup a background script, `~/gh-stack-install.sh`, installs the `gh stack` +extension and the `gh-stack` agent skill that the first-mate skill uses to stack and +merge dependent PRs. Both are pinned: the extension to tag `v0.3.0`, with its binary's +sha256 checked against a recorded digest (the binary is removed on a mismatch), and the +skill to the commit that tag points at. It needs `gh` 2.90.0 or later and does not +upgrade it; the first-mate skill's Prerequisites section says how. It is idempotent, +retries, always exits 0, and logs to `~/.local/state/paseo/gh-stack.log`. Reasoning and +limits: [`docs/decisions/0006`](docs/decisions/0006-install-gh-stack-at-startup.md). ## Paseo plugins @@ -289,7 +302,8 @@ drops files and starts one plugin installer that needs the separate paseo kit, s run commands and push code. Everything is plain text you can read in this directory; review the diff before pinning a new SHA, especially after re-vendoring. -- **`github.com` and `registry.npmjs.org` are open to every agent in the sandbox.** +- **`github.com`, `api.github.com`, `release-assets.githubusercontent.com` and + `registry.npmjs.org` are open to every agent in the sandbox.** `caps.network` is sandbox-wide, not scoped to the installer, so any agent or plugin there can also reach them (clones, gists, pushes, package fetches). The paseo kit already allows the npm registry. diff --git a/personal/docs/decisions/0006-install-gh-stack-at-startup.md b/personal/docs/decisions/0006-install-gh-stack-at-startup.md new file mode 100644 index 0000000..682d799 --- /dev/null +++ b/personal/docs/decisions/0006-install-gh-stack-at-startup.md @@ -0,0 +1,69 @@ +--- +title: "Install gh stack and its skill at sandbox startup" +description: "Pin and digest-check the gh stack extension and its agent skill in the personal kit, so the first-mate skill has its stacking tools" +status: draft +tier: 2 +date: "2026-12-04" +last_updated: "2026-12-04" +decision_makers: ["Bret Mogilefsky"] +nist_controls: ["CM-3", "CM-7", "SA-11", "SR-3"] +impact_level: "Moderate" +ato_relevance: "no" +risk_treatment: "mitigate" +--- + +# Install gh stack and its skill at sandbox startup + +## Context and problem statement + +The `paseo-first-mate` skill stacks and merges dependent pull requests with `gh stack` +and the `gh-stack` agent skill. Neither was present in a new sandbox, so the coordinator +stopped to install them in every sandbox, and the skill did not list them as +prerequisites. Both are a binary and a skill from `github/gh-stack`, fetched over the +network. + +## Decision outcome + +1. **A startup step installs both.** `~/gh-stack-install.sh` runs in the background at + sandbox start, beside the Paseo plugin installer. It runs + `gh extension install github/gh-stack --pin v0.3.0` and + `gh skill install github/gh-stack gh-stack --pin --agent universal --scope user`. + Both are skipped when already present. It always exits 0, retries each install three + times, takes a run lock, and logs to `~/.local/state/paseo/gh-stack.log`. +2. **Everything is pinned, and the binary is verified.** The skill is pinned to the full + commit that tag `v0.3.0` points at. `gh` does not verify a downloaded extension + binary, so the script compares its sha256 with a digest recorded in the script, taken + from the release's published asset digests, and runs `gh extension remove` on a + mismatch. Digests are recorded for Linux amd64 and arm64; other platforms install + nothing and log why. `scripts/verify` section 3d2 fails on an unpinned install, a + missing digest, or a missing removal path. +3. **It does not install or upgrade `gh`.** `gh skill` first shipped in 2.90.0. When `gh` + is missing or older, the script logs it and stops. Upgrading `gh` needs root or an + unpinned download, so the first-mate skill's Prerequisites section carries the + procedure (package manager, or a release tarball checked against its checksums file). +4. **Egress.** `gh extension install` and `gh skill install` reach `api.github.com`, + `github.com`, and `release-assets.githubusercontent.com` (observed with `GH_DEBUG=api` + on gh 2.102.1). The last two are added to `caps.network.allow` with `api.github.com`. + `caps.network` is sandbox-wide. +5. **Moving a pin** means changing the tag, the commit, and both digests together, then + reading the new skill. The skill's text steers the agent, so review its diff. + +## Consequences and limitations + +- The kit adds two egress hosts and a second short background process at startup. +- Digests are not verified against anything the kit controls beyond the release's own + published values, which share a trust root with the binary. They catch corruption and + a changed asset, not a compromised release. +- The skill's metadata records the pin, but `gh skill` does not verify content hashes. +- Not tested: a real `acq run` on msb or sbx, macOS (no pinned digest), a proxy that + inspects HTTPS, and the extension at `gh` versions other than 2.102.1. + +## Verification and rollback + +`scripts/test-gh-stack-install.py` runs the shipped script against a fake `gh` (13 tests, +including the digest-mismatch removal, idempotence, the version gate, failed installs, +and the run lock). The real `gh extension install` and `gh skill install` were run once +with an isolated `HOME` to confirm the commands, flags, digest, and hosts. Run +`personal/scripts/verify` and `python3 scripts/run-kit-tests.py personal`. Roll back by +reverting this decision, the script, its test, the spec records, and the `verify` section. +The record is AI-authored and remains draft pending human review. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/SKILL.md b/personal/files/home/.agents/skills/paseo-first-mate/SKILL.md index 103ad66..10fda43 100644 --- a/personal/files/home/.agents/skills/paseo-first-mate/SKILL.md +++ b/personal/files/home/.agents/skills/paseo-first-mate/SKILL.md @@ -1,7 +1,7 @@ --- name: paseo-first-mate id: paseo-first-mate -version: "1.6.0" +version: "1.7.0" title: "Paseo First Mate" description: "Coordinate a multi-issue engineering effort through isolated Paseo workspaces, structured GitHub metadata, dependency-aware delivery, change-detecting follow-up, and a durable handoff." type: skill @@ -71,6 +71,8 @@ portability: chatgpt: false generic_llm: false changelog: + - version: "1.7.0" + changes: "One status map (`tmp/STATUS-MAP.md`, `references/status-map.md`) replaces the separate handoff and status doc: a file-tree Path to main with one self-contained row per PR, `→you [key]` markers with footnoted commands, goal and remaining work only, no log. Merge sweep: a merged or closed PR's agents, workspaces, worktrees, branches, scratch, and then its row are retired in the same turn, under a recorded standing permission. Prerequisites now check and fix `gh`, the pinned `gh stack` extension, and its skill. Security findings are held privately only once the code has landed. Progress-only finish notices are not final reports; approval-dismissing pushes are named before they happen; stacks merge bottom-up with `gh stack merge`; cancelled duplicate runs are checked before being read as failures. Detector: pending-check counts, agent idle/running flips, and single failed queries no longer wake the loop, and a hung detector run is killed after 240 seconds. The kit installs `gh stack` and its skill at startup (ADR 0006)." - version: "1.6.0" changes: "Add a compact state checkpoint (active owner, next blocking decision, CI and dependency state, next action) required before delegating or relaying a significant follow-up, and a repeated-action stop rule: pause, read the checkpoint, and say why the next action differs before repeating a discretionary status check or delegation. Observed coordination sessions grew costly through repeated handoffs, status narration, and repeated actions. No authority or safety rule changes." - version: "1.5.0" @@ -132,6 +134,34 @@ Single-change and read-only work are covered by `avoid_when` above. - Paseo projects registered for every repository in scope. - Authenticated GitHub CLI with the minimum required permissions. +- **Stacking tooling, checked before any stack work.** Run this in order and fix what + fails; do not stop to ask the user each time. Ask once for standing permission to + install and upgrade these tools, and record it in the status map's Standing rules. + 1. `gh --version` is 2.90.0 or later (the first release with `gh skill`), and + `gh skill install --help` lists `--pin`. If not, upgrade `gh`: `brew upgrade gh` + on macOS; on Debian or Ubuntu with GitHub's apt source, + `sudo apt-get update && sudo apt-get install --only-upgrade gh`; otherwise + download the release tarball from `github.com/cli/cli/releases`, check it + against the release's checksums file, and put the binary in `~/.local/bin` + ahead of the old one on `PATH`. Never pipe a downloaded script into a shell. + 2. The `gh stack` extension is installed and verified. If `gh extension list` has no + `github/gh-stack`, run `gh extension install github/gh-stack --pin v0.3.0`. `gh` + does not verify the downloaded binary, so before you run it even once (including + `gh stack --help`), compare its sha256 with the digest the release publishes for + your platform (`gh api repos/github/gh-stack/releases/tags/v0.3.0 + --jq '.assets[] | "\(.name) \(.digest)"'`; the binary is + `~/.local/share/gh/extensions/gh-stack/gh-stack`), run `gh extension remove + gh-stack` on a mismatch, and confirm it is gone. + 3. The gh-stack skill is installed: `~/.agents/skills/gh-stack/SKILL.md` exists. If + not: `gh skill install github/gh-stack gh-stack + --pin 2a49e6751238633db504655d8a8eba3e433e827d --agent universal --scope user` + (the commit of tag v0.3.0). Read what it installed before relying on it. + 4. Re-run 1 to 3. If anything still fails, report `BLOCKED` with the failing command + and its output. Do not stack by hand, and do not skip the check. + + The kit's startup step does 2 and 3 at sandbox start when `gh` is new enough; this + list is what you run when it did not. To move the pins, change this list, the + startup script, and its digests together. - Repository instructions loaded from each target checkout, including its one-command verification. - A durable tracker containing the epic and implementation issues. @@ -166,8 +196,21 @@ Single-change and read-only work are covered by `avoid_when` above. 8. Never archive dirty, unpushed, unrecoverable, or intentionally retained work. 9. Never include token, key, credential, or secret values in prompts, logs, API calls, comments, or handoff documents. -10. Hold security-relevant findings (guest-integrity, downgrade, trust-boundary) - privately and ask the user how to proceed. Do not file them as public issues. +10. Security-relevant findings (guest-integrity, downgrade, trust-boundary): tell the + user immediately, in your next message and not at the next scheduled report, and + keep exploit detail out of any public place. How privately you handle the rest + depends on whether the vulnerable code has landed. + - **Only in an open, unmerged PR**, with no deploy, preview, release branch, or fork + involved: nobody can run it in the wild yet. Tell the user, then fix it in that PR + unless they say otherwise, and describe the change by what it does ("sanitize PATH"), not by how to exploit the old state. + Rounds of private handling here add review cycles and protect no one. + - **Landed** (on the default branch, in a release, or deployed), or reachable + through a preview deploy, a CI job with secrets, a release branch, or a fork: + hold it privately and ask the user how to proceed. This includes a flaw in landed + code that an open PR's fix would reveal. Do not file a public issue. + - **Cannot tell whether it landed:** treat it as landed and ask the user. + - A repository's own security policy that is stricter than this wins. Tell the user + when it is, because the rule above would otherwise have applied. 11. Never merge, and never change PR draft/ready state, beyond what the user has explicitly granted. 12. One coordinator per effort. A resumed or forked session is a non-coordinator @@ -358,6 +401,11 @@ Reuse and self-review: check runs, a tool missing from its sandbox). Reproduce them on a clean base, or read the exact-head check results yourself, and label what you could not confirm. +- **A finish notice can be a progress report.** An agent's "finished" message that says + work is still running, jobs are pending, or nothing is pushed yet is not its final + report. Do not act on it, do not relay it as a result, and do not nudge the agent: + wait for the final report, or for the agent to go idle without one (then see the next + item). - **Read a finish notice against the agent's status and your last prompt.** A finished notice can be the end of an earlier turn, not the reply to your latest follow-up. If the agent shows as running or idle with no new activity after your @@ -449,9 +497,11 @@ into the lower branch (a plain merge, no force-push). The old head stays an ancestor, so the stack above stays valid; only the upper PR needs a sync. Any force-push still needs the user's approval. -For stacking PRs that already have reviews, follow `references/stacking.md`; it -points to the `github/gh-stack` skill for the command details instead of repeating -them. +For stacking PRs that already have reviews, and for merging a stack without losing +its approvals, follow `references/stacking.md`; it points to the `github/gh-stack` skill +for the command details instead of repeating them. Before any push, restack, or retarget +of a PR that has approvals, ask which of them it would dismiss (a ruleset with +`dismiss_stale_reviews_on_push` dismisses on every push), and say so to the user first. For cross-repository dependencies: @@ -532,7 +582,10 @@ record the choices and any later change in the handoff: say one line about what you restarted. If it has a WARNING line (the last detector run is stale), run `--show` to see the error, then `stop` and start the loop again, and say one line. If it starts with `other`, say so once and do - nothing else. Make no tool calls beyond those named. + nothing else. Make no tool calls beyond those named. Stay completely silent unless + something meaningful changed: a human review or comment, a check's final state or a + new failure, a head or PR state change, an agent finishing or erroring, or a + decision needed. Never narrate check counts moving while checks are pending. ``` Use `paseo heartbeat update --cron ...` to change its cadence. @@ -551,7 +604,7 @@ Bundled assets: permission prompts are watched only when you run `agents on` / `permits on` (off by default: the harness already sends finish notices and surfaces permits, so watching them here would wake the loop on the coordinator's own actions). A - transient API error keeps the previous value and is reported. Manage the watch + failed query keeps the previous value, and is reported only after repeated failures (see below). Manage the watch list with `add`, `remove`, `prune`, `repo`, `agents`, `permits`, and `list` (for example `add branch kits@main`, `add workflow kits:deploy.yml@main`); `--show` prints the snapshot without @@ -570,6 +623,18 @@ Bundled assets: - **Each PR line** shows its current head, and `stale-review=[...]` when a reviewer's latest approval or change request was made on an older head, so you need not work out whether it applies. + - **Noise is saved but never wakes you.** Check counts moving while checks are still + pending (a failure, or checks settling or starting again, still reports); a + watched agent going from idle to running because you prompted it (an agent + finishing, closing, erroring, appearing, or disappearing still reports); and a + failed query, which keeps the previous value and + reports an `ERROR` line only after the same item fails `FIRST_MATE_ERROR_RUNS` + runs in a row (default 3), once. `--show` always prints every error. A real change + in a PR's head, reviews, comments, or merge state is never filtered. + - **A hung detector run is killed** after `FIRST_MATE_DETECTOR_SECS` (default 240), + logged to `FIRST_MATE_DIR/.wait.log`, and retried at the next interval. `status` + shows the last kill as `last-kill=`. Before this, one hung network call left a loop + alive but silent. - **Merged and closed items** are pruned from the watch list automatically when the report that shows them is saved, and the report says so (`PRUNED ...`). `autoprune off` turns that off; `prune` does it on demand. @@ -640,73 +705,59 @@ mislead it. It cannot see GitHub notifications or review requests on PRs outside the watch list. Under `ready-push`, a CI failure is always reported. Quiet wake-ups never delay a direct answer: respond to the user when asked. -### 9. Maintain the Durable Handoff - -Store the handoff in the coordinator worktree, not another repository checkout. -Use a repository-local ignored path such as `tmp/FIRST-MATE-HANDOFF.md`. If -`tmp/` is not ignored, add it to the repository-local `.git/info/exclude` rather -than changing project ignore policy solely for the coordinator. - -Template: - -```markdown -# First Mate Handoff - -Updated: YYYY-MM-DD HH:MM UTC - -## Goal -## Operating Rules -## Controls -## Current Coordination State -(first lines: the checkpoint, section 12) -## Completed Work -## Critical Path -## Parallel Work -## Authoritative PR and Branch Heads -## Issue and Metadata State -## Workspaces and Active Agents -## Verification Evidence -## Live Results -## Merge and Release Order -## Immediate Next Actions -## Workspace Safety -## Fast-Track Grants -## Pending Decisions and Held Items -## Wait Log -``` - -- **Controls:** coordinator agent ID (`$PASEO_AGENT_ID` of the owner), the wait - loop command with its absolute path, interval and cap, the heartbeat ID and cron, - schedule status (or "not visible"), - agent cap, coordinator and delegated models, permission setup per workspace. -- **Current Coordination State:** the first section read after each wake-up; it - starts with the checkpoint (section 12). Keep the whole file near 200 lines. -- **Wait Log:** short dated entries only. Clear it periodically: fold - durable facts into the state sections, save a gitignored backup under - `tmp/archive/`, then empty the log. -- **Standing rules:** record every user process rule with its date, verbatim - where you can: delivery grants, ready-when-green, filing rule, self-review - rule, agent reuse, reporting style, things never to touch, and standing answers - to routine permission prompts (for example, "external search services are - denied; fetching public project sites is allowed"). Apply a recorded policy; ask - about anything it does not cover. Rules given mid-session are the most valuable - content for a successor. -- **Status doc and context:** if you keep a status doc (Reporting), record its - path. Tell the user when your context window is about 70% full and prepare the +### 9. Maintain the Status Map + +The status map is the one standing file for the effort: the user's live view and your +durable memory, in one place. It replaces the separate handoff and status doc, so +"the handoff" anywhere in this skill means the status map. Store it in the coordinator +worktree, not another repository checkout, at an ignored path: `tmp/STATUS-MAP.md`. If +`tmp/` is not ignored, add it to the repository-local `.git/info/exclude` rather than +changing project ignore policy solely for the coordinator. + +The template, row grammar, and footnote rules are in `references/status-map.md`. The +shape that matters: + +- **Needs @human** and **Path to main** come first. Path to main is a tree with one row + per PR, grouped by stack, with `main` at the bottom of each group. +- **One row per PR holds everything about that PR:** status emoji, number, title, head, + review state on that head, delegated agent, and any `→you` action. No other section + repeats it, so a change is one edit. +- **`→you [key]`** marks a row whose next action is the user's. The key points to a + footnote under the tree holding the exact command or the note for a person. Keys are + the PR number plus a short suffix, never a counter. "Needs @human" lists only items + not tied to a PR and points at the tagged rows (`grep '→you' tmp/STATUS-MAP.md`). +- Below the tree: Checkpoint (section 12), Standing rules, Controls, Pending decisions + and held items, Parked. Nothing else. + +Rules for keeping it: + +- **Goal and remaining work only.** There is no completed-work section and no log. + What happened lives in git, the PRs, and the issues. Delete a row and its footnotes + in the same pass that finishes its sweep (section 10). Remove anything superseded the + moment it is superseded: old heads, resolved findings, retention notes for workspaces + that no longer exist, debugging narratives. Keep the file near 150 lines. +- **Standing rules:** record every user process rule with its date, verbatim where you + can: delivery grants, ready-when-green, filing rule, self-review rule, agent reuse, + reporting style, things never to touch, standing answers to routine permission + prompts (for example, "external search services are denied; fetching public project + sites is allowed"), and the cleanup permission (section 10). Apply a recorded + policy; ask about anything it does not cover. Rules given mid-session are the most + valuable content for a successor. +- **Controls:** coordinator agent ID (`$PASEO_AGENT_ID` of the owner), the wait loop + command with its absolute path, interval and cap, the heartbeat ID and cron, agent + cap, coordinator and delegated models, permission setup per workspace. +- **Pending decisions and held items:** for each open question, record your + recommendation, the options, and the trigger that would make it urgent, so the user + can ask "what did you think?" and get the same answer after a compaction. Held + security findings follow invariant 10. +- **Context:** tell the user when your context window is about 70% full and prepare the handoff then (`references/handoff-and-successor.md`), not at the last moment. -- **Pending Decisions and Held Items:** add this section to the template. For each - open question, record your recommendation, the options, and the trigger that - would make it urgent, so the user can ask "what did you think?" and get the - same answer after a compaction. Held security findings are listed by title only, - with a pointer to a private note outside the repository; the note's contents - and any attack detail stay out of the handoff and every public place. -- **Prune stale detail** once superseded: old head SHAs, retention notes for - workspaces that no longer exist, and debugging narratives. - -Update it after every meaningful event before sending the user-facing report. +- Update the map after every meaningful event, before the one-line chat report. Re-read + the PR before writing its state, and name the head the row is true for. + Do not include secrets, sensitive internal topology, or credentials. -### 10. Retire Workspaces Safely +### 10. Retire Workspaces Safely, and Sweep on Merge Archive a workspace only when all conditions are true: @@ -716,16 +767,48 @@ Archive a workspace only when all conditions are true: - No agent is running in it, and no dependent work or PR awaiting feedback is retained there. - Archival is authorized: the coordinator confirms it, or the user has granted - standing permission. Record any standing permission in the handoff. + standing permission. Record any standing permission in the status map. - PR checks are green or the workspace is definitively obsolete. Dirty files, untracked files, staged changes, unpushed commits, unavailable owners, or named retention are hard stops. -When a PR merges, retire what it owned in one pass: archive its idle agent and -workspace, drop it from the watch list, and delete the local branch only if it -matches the remote branch exactly. Do not touch agents or workspaces you did not -create. +**Merge sweep.** The status map holds this invariant: *a row exists exactly while its +resources exist.* Run the sweep whenever the detector reports a PR merged or closed +(`PRUNED`), in that same turn, so the user never has to ask for cleanup. One pass per +merged PR; never use `git branch -D` or `git worktree remove --force`, since a refusal +is the signal to stop: + +1. Archive the idle agents and Paseo workspaces that PR owned, including its review and + fix agents. +2. Remove its git worktrees (`git worktree remove`, then `git worktree prune`). +3. Delete its local branch only if the branch tip equals the PR's final head, and only + after step 2, when `git worktree list` no longer shows the branch. After a squash + merge the branch is not merged into anything, so `git branch -d` refuses and `-D` + would force it; use a compare-and-delete that refuses on any other tip: + `sha=$(gh pr view --json headRefOid -q .headRefOid); git update-ref -d + refs/heads/ "$sha"`. Do the same for each *merged* PR that was stacked under + it; never touch the branch of a PR that is still open, because it will be retargeted + (`references/stacking.md`). If the tip differs, leave the branch and mark the row + `⚠ cleanup blocked`. +4. Delete the remote branch only if the repository does not delete it on merge and + `gh pr list --base ` shows no open PR based on it (deleting a base closes + those PRs). +5. Delete your own scratch for it: files you created for that PR and named for it (a + draft body, a log, a backup, `tmp/cmd/.sh`) that no row references. Never delete + the detector's state and watch files, `.wait.*`, the copied scripts, the status map, + or `tmp/archive/`. +6. Delete its row and its footnotes from the status map, and surface what the merge + unblocked. + +If a hard stop applies, do not skip silently: leave the row and add +`⚠ cleanup blocked: ` to it, so the leftover is visible. A **closed but +unmerged** PR gets the same checks, but ask the user before deleting any branch or +worktree that holds commits that exist nowhere else. Do not touch agents, workspaces, or +branches you did not create. + +Ask once for standing permission to sweep, and record it in Standing rules with its +date. After that, the sweep needs no further word from the user. ### 11. Close the Loop @@ -765,7 +848,7 @@ apply as written. Neither delays a direct answer to the user. **Compact state checkpoint.** Before you delegate, or relay a significant follow-up to an agent or the user, write or refresh this block as the first lines of -`Current Coordination State` in the handoff: +the `Checkpoint` section of the status map: ```text Checkpoint (UTC time, evidence: verified | hypothesis | unverified) @@ -800,11 +883,9 @@ does not read the checkpoint. Keep chat short and put the state in a file the user can leave open. -- **Maintain a status doc** (recommended): one Markdown file, updated in place on - every change, with sections such as Needs you, In progress, Waiting on - reviewers, Backlog, Leaving alone, Merged this session, and Standing rules. Move - rows between sections as state changes and delete a row when it stops being - true. Template and rules: `references/status-doc.md`. +- **Keep the status map current.** One Markdown file, updated in place on every change + (section 9). Move rows between groups as state changes and delete a row when its + resources are gone. Template and rules: `references/status-map.md`. - **One line per event** with a full link, plus any decision you need from the user. Add only what the PR and its commits do not already say. Never recap a push, comment, or review that is already posted, and never repost a table. @@ -910,7 +991,8 @@ Before declaring coordination complete, verify: - Current release pins are immutable and verified. - Live results are observed, not simulated. - Required workspaces are retained; safe obsolete workspaces are archived. -- The handoff reflects the final state and its log is cleared. +- The status map reflects the final state, holds no history, and has no row whose + resources are gone (the merge sweep is complete). - Exactly one coordinator is recorded, and `first-mate-wait.sh status` was run this turn before any statement about the loop. - The wait loop and its heartbeat are stopped, and the state file cleared, when @@ -942,6 +1024,7 @@ Before declaring coordination complete, verify: | Wait script reports an API error | One transient error is noise (the previous value is kept); repeated errors are a blocker. | | The loop finished and nobody noticed | Check `last-run=` in `status` and the heartbeat. Restart in the same turn, run the check once with `--show`, and report the gap with timestamps. The Loop Rule and the heartbeat exist to prevent this. | | `status` warns that the last run is stale | The loop is stuck or the detector is failing. Run `first-mate-check.py --show` to see the error, then `stop` and start again. | +| `status` shows `last-kill=` | A detector run hung and was killed; the loop retries by itself. Repeated kills mean a network or `gh` problem: run `first-mate-check.py --show` and read the error. | | A report arrives twice | Expected after a kill between report and commit: the two-phase save prefers a duplicate to a miss. Compare the heads; nothing was lost. | | A stray `tmp/tmp` appears, or `add pr` says "unknown repo alias" | Different `FIRST_MATE_DIR` or working directory from the one that holds the watch file. Use an absolute `FIRST_MATE_DIR`; the scripts now resolve it, but older copies do not. | | After upgrading the scripts, every PR reports a change once | The saved state holds the old merge-state wording. Run `first-mate-check.py --reset` and take the baseline. | @@ -956,7 +1039,7 @@ Before declaring coordination complete, verify: ## References - `references/delegation-prompt.md`: rules and template for every delegation prompt. -- `references/status-doc.md`: the maintained status doc and chat reporting rules. +- `references/status-map.md`: the status map (live view and handoff in one file) and chat reporting rules. - `references/handoff-and-successor.md`: handing the effort to a new coordinator. - `references/host-commands.md`: credential limits, host commands, recipe pitfalls, evidence, and verification tiers. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-check.py b/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-check.py index 62cdcd0..c7bd2f9 100755 --- a/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-check.py +++ b/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-check.py @@ -26,6 +26,15 @@ mergeStateStatus is collapsed to conflict, behind, or ok, and a transient UNKNOWN is re-queried (and then keeps the previous value), so recomputation does not wake you. +Noise that never wakes you (it is still saved, so the next real change compares against it): + - check counts that move while checks are still pending; a PR reports when a check + fails, or when its checks all settle (no pending) or start again after settling + - a delegated agent going from idle to running (it was prompted); an agent finishing + (running to idle), closing, erroring, appearing, or disappearing still reports + - a query that fails: the previous value is kept, and an ERROR line appears once the same + item has failed FIRST_MATE_ERROR_RUNS runs in a row (default 3), then not again until it + succeeds. --show always prints every error. + Saving. A report must not be consumed before it is delivered. Loops that can be killed use the two-phase form: --peek print what changed and stage a pending save bound to the exact saved @@ -105,12 +114,17 @@ def resolve_dir(value, cwd=None, script_dir=None): STATE = os.path.join(HERE, ".first-mate-state.json") PENDING = os.path.join(HERE, ".first-mate-pending.json") LASTRUN = os.path.join(HERE, ".first-mate-lastrun") +ERRORS = os.path.join(HERE, ".first-mate-errors.json") LOCKFILE = os.path.join(HERE, ".state.lock") REPORT_LOCKFILE = os.path.join(HERE, ".report.lock") WATCH = os.path.join(HERE, "first-mate-watch.json") TIMEOUT = 45 UNKNOWN_RETRIES = 3 UNKNOWN_SLEEP = float(os.environ.get("FIRST_MATE_UNKNOWN_SLEEP", "3")) +try: + ERROR_RUNS = max(1, int(os.environ.get("FIRST_MATE_ERROR_RUNS", "3"))) +except ValueError: + ERROR_RUNS = 3 LOGIN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*(?:\[bot\])?$") GATING = ("APPROVED", "CHANGES_REQUESTED", "DISMISSED") @@ -557,6 +571,68 @@ def manage(w, argv): raise SystemExit(__doc__) +CHECK_COUNTS = re.compile(r"checks ok=\d+ fail=(\d+) pending=(\d+)") + + +def agent_items(snap): + """{short id: (status, rest)} from an agents snapshot ("id:status:name; ...").""" + items = {} + for part in (snap or "").split("; "): + pieces = part.split(":", 2) + if len(pieces) == 3: + items[pieces[0]] = (pieces[1], pieces[2]) + return items + + +def agents_wake(old, new): + """True unless every difference is an agent that went idle -> running (it was prompted). + A finish (running -> idle), a close, an error, and an appearing or vanishing agent all wake.""" + before, after = agent_items(old), agent_items(new) + if before.keys() != after.keys(): + return True + for k, (status, rest) in after.items(): + old_status, old_rest = before[k] + if rest != old_rest: + return True + if status != old_status and not (old_status == "idle" and status == "running"): + return True + return False + + +def comparable(key, snap): + """The part of a snapshot that can wake you; the rest is saved but never reported.""" + if key.startswith("pr "): + return CHECK_COUNTS.sub(lambda m: f"checks fail={m.group(1)} settled={m.group(2) == '0'}", snap) + return snap + + +def load_error_file(): + try: + with open(ERRORS) as fh: + data = json.load(fh) + counts = {k: int(v) for k, v in data.get("counts", {}).items()} + return counts, set(data.get("reported", [])) + except (OSError, ValueError, AttributeError, TypeError): + return {}, set() + + +def save_error_file(counts, reported): + write_atomic(ERRORS, json.dumps({"counts": counts, "reported": sorted(reported)}, sort_keys=True)) + + +def count_errors(errors, seen): + """Count consecutive failed runs per item and return the errors that are due: failed + ERROR_RUNS times in a row and not yet reported. An item is marked reported only when its + report is committed (apply_save), so a report that was lost is repeated, never dropped. + `seen` is every item this run queried. Caller holds the state lock.""" + counts, reported = load_error_file() + counts = {k: v for k, v in counts.items() if k in seen and k in errors} + counts = {k: counts.get(k, 0) + 1 for k in errors} + reported = {k for k in reported if k in errors} + save_error_file(counts, reported) + return {k: e for k, e in errors.items() if counts[k] >= ERROR_RUNS and k not in reported} + + def report_lines(old, new, errors, pruned, baseline): lines = [] if baseline: @@ -565,10 +641,10 @@ def report_lines(old, new, errors, pruned, baseline): for k in sorted(new): if k not in old: lines.append(f"NEW {k}: {new[k]}") - elif old[k] != new[k]: + elif (agents_wake(old[k], new[k]) if k == "agents" else comparable(k, old[k]) != comparable(k, new[k])): lines.append(f"CHANGED {k}\n was: {old[k]}\n now: {new[k]}") for k in sorted(errors): - lines.append(f"ERROR {k}: {errors[k]} (kept previous value)") + lines.append(f"ERROR {k}: {errors[k]} (kept previous value; failed {ERROR_RUNS} runs in a row)") for kind, item, label in pruned: lines.append(f"PRUNED {kind} {item} ({label}): no longer watched after this report") return lines @@ -596,8 +672,10 @@ def run_detect(arg): return if new or not errors: # a pass where every query failed did not complete write_atomic(LASTRUN, f"{int(time.time())}\n") + with state_lock(): + due = count_errors(errors, set(new) | set(errors)) found = prunable(w, new) if w.get("autoprune") else [] - lines = report_lines(old, new, errors, found, baseline) + lines = report_lines(old, new, due, found, baseline) if lines: print("\n".join(lines), flush=True) pending = { @@ -605,13 +683,16 @@ def run_detect(arg): "txn": os.environ.get("FIRST_MATE_TXN", ""), "new": new, "prune": [[k, i] for k, i, _ in found], + "errors": sorted(due), } with state_lock(): if arg == "--peek": if lines: write_atomic(PENDING, json.dumps(pending, sort_keys=True)) else: + # Nothing to report, so nothing can be lost: save the quiet changes now. remove_quietly(PENDING) + apply_save(pending) else: apply_save(pending) @@ -623,6 +704,10 @@ def apply_save(pending): apply_prune(w, st, [(k, i, "") for k, i in pending.get("prune", [])]) save_state(st) save_watch(w) + if pending.get("errors"): + counts, reported = load_error_file() + still_failing = {k for k in pending["errors"] if k in counts} + save_error_file(counts, reported | still_failing) def commit_pending(): @@ -656,6 +741,7 @@ def main(): with state_lock(): remove_quietly(STATE) remove_quietly(PENDING) + remove_quietly(ERRORS) print("state reset") elif arg in ("", "--peek", "--show"): detect(arg) diff --git a/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh b/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh index 2adcfde..3a8285c 100755 --- a/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh +++ b/personal/files/home/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh @@ -32,6 +32,9 @@ # not exist and this script sits in a directory with that path tail (the skill copies the # scripts into tmp/), that directory is used, so running from inside tmp/ never makes tmp/tmp. # FIRST_MATE_PYTHON picks the interpreter (default python3). +# A detector run that takes longer than FIRST_MATE_DETECTOR_SECS (default 240) is killed and +# retried at the next interval, so a hung network call cannot leave the loop alive but silent. +# The kill is logged to FIRST_MATE_DIR/.wait.log and shown by `status`. # # Ownership is the PASEO_AGENT_ID of the caller (override with FIRST_MATE_OWNER). The # lock is an flock(2) on FIRST_MATE_DIR/.wait.lock, so it frees itself when the loop @@ -61,6 +64,9 @@ LOCK=$DIR/.wait.lock INFO=$DIR/.wait.owner LASTRUN=$DIR/.first-mate-lastrun SECS_PER_MIN=${FIRST_MATE_MINUTE_SECS:-60} +DETECTOR_SECS=${FIRST_MATE_DETECTOR_SECS:-240} +case $DETECTOR_SECS in ''|*[!0-9]*) DETECTOR_SECS=240 ;; esac +WAITLOG=$DIR/.wait.log ME=${FIRST_MATE_OWNER:-${PASEO_AGENT_ID:-local}} export FIRST_MATE_OWNER=$ME @@ -114,7 +120,7 @@ human_age() { # The first word of the first line is none | mine | other; callers parse that. The last # detector run follows, with a WARNING line when it is older than twice the interval. describe() { - local owner kind age interval line since + local owner kind age interval line since killed age=$(lastrun_age) if ! is_running; then echo "none" @@ -131,6 +137,8 @@ describe() { if [ "$owner" = "$ME" ]; then kind=mine; else kind=other; fi line="$kind owner=${owner:-unknown} pid=$(info_get pid) started=$(info_get started)" line="$line interval=${interval}m max=$(info_get max)m" + killed=$(tail -n 1 "$WAITLOG" 2>/dev/null) + [ -n "$killed" ] && line="$line last-kill=\"$killed\"" if [ -z "$age" ]; then echo "$line last-run=never" else @@ -171,6 +179,28 @@ cmd_stop() { return 2 } +# Wait for the detector (pid $1), killing it after DETECTOR_SECS. Sets RC. A SIGTERM to the +# loop is still handled at once, because each poll is a short sleep in this shell. +wait_detector() { + local pid=$1 waited=0 + while kill -0 "$pid" 2>/dev/null; do + if [ "$waited" -ge "$DETECTOR_SECS" ]; then + kill "$pid" 2>/dev/null + sleep 1 + kill -9 "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + printf '%s detector killed after %ss; retrying at the next interval\n' \ + "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$DETECTOR_SECS" >> "$WAITLOG" + RC=124 + return 0 + fi + sleep 1 + waited=$(( waited + 1 )) + done + wait "$pid" + RC=$? +} + SLEEP_PID= DET_PID= OUTF= @@ -221,11 +251,15 @@ cmd_start() { txn="$$.$(date +%s).$RANDOM" FIRST_MATE_TXN=$txn "$PYTHON" "$HERE/first-mate-check.py" --peek >"$OUTF" 2>&1 9>&- & DET_PID=$! - wait "$DET_PID" - rc=$? + wait_detector "$DET_PID" + rc=$RC DET_PID= out=$(cat -- "$OUTF") - if [ "$rc" -ne 0 ] && [ -z "$out" ]; then out="first-mate-check.py exited with status $rc and printed nothing"; fi + if [ "$rc" -eq 124 ] && [ -z "$out" ]; then + out= + elif [ "$rc" -ne 0 ] && [ -z "$out" ]; then + out="first-mate-check.py exited with status $rc and printed nothing" + fi if [ -n "$out" ]; then printf '%s\n' "$out" if ! FIRST_MATE_TXN=$txn "$PYTHON" "$HERE/first-mate-check.py" --commit 9>&- >/dev/null 2>&1; then diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md b/personal/files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md index d008421..18544f3 100644 --- a/personal/files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md @@ -5,7 +5,8 @@ early), or when the user asks for a new coordinator in the same workspace. ## Write the handoff first -Follow the template in SKILL.md section 9, and put these in it: +The handoff is the status map (`references/status-map.md`, SKILL.md section 9). Bring it +current, delete anything superseded, and make sure it holds these: - The user's standing rules, verbatim and dated. Rules the user gave mid-session were the most valuable content for a successor. Examples: how to report, @@ -14,7 +15,7 @@ Follow the template in SKILL.md section 9, and put these in it: `FIRST_MATE_DIR`), the heartbeat ID, and a sentence saying these are bound to the old ID and must be re-established. - In-flight commitments, held items, and work that is on hold with its - trigger. Archive the old log under `tmp/archive/` and clear it. + trigger. Keep no history: git and the PRs hold it. - A standing-policy line for permission prompts, for example: "external search-service prompts are denied; fetching public project sites is allowed." @@ -49,3 +50,11 @@ is fine for the successor itself. 2. Re-read GitHub state for everything in the handoff; do not trust its claims. 3. Create the heartbeat. Confirm running agents with `paseo_get_agent_status`. 4. Record your agent ID in Controls. + +## Adopting an older handoff + +An effort that began before the status map has `tmp/FIRST-MATE-HANDOFF.md` and often +`tmp/PR-STATUS.md`. Build `tmp/STATUS-MAP.md` from them once: one row per open PR with +its head re-read from GitHub, the standing rules and controls carried over verbatim, and +every completed-work, log, and superseded entry dropped. Save the old files under +`tmp/archive/`, then stop updating them. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/stacking.md b/personal/files/home/.agents/skills/paseo-first-mate/references/stacking.md index aa9447b..206f764 100644 --- a/personal/files/home/.agents/skills/paseo-first-mate/references/stacking.md +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/stacking.md @@ -5,7 +5,8 @@ project. Read its skill and references first: `skills/gh-stack/SKILL.md`, `references/commands.md`, `references/stack-design.md`, and `references/troubleshooting.md`. If the skill does not load from the local registry, fetch the files with `gh api repos/github/gh-stack/contents/skills/gh-stack/`. -Install the extension with `gh extension install github/gh-stack`. +Installing the extension and the skill, and upgrading `gh`, is a prerequisite step: +see Prerequisites in SKILL.md. This page holds only what is specific to First Mate: stacking PRs that already have reviews. These observations came from gh-stack 0.3.0; recheck them on yours. @@ -36,3 +37,41 @@ have reviews. These observations came from gh-stack 0.3.0; recheck them on yours the tip, with per-layer heads as an optional part. - Do not use `env -u` to strip a token for `gh stack` unless you have verified it still authenticates (see Secrets in SKILL.md). + +## Merging a stack without losing approvals + +Check the repository's ruleset first (`gh api repos/OWNER/REPO/rulesets`). Two settings +decide the order: the allowed merge methods, and whether a push dismisses approvals +(`dismiss_stale_reviews_on_push`). + +- **Never merge top-down.** The top PR's base is the PR below it, so merging it lands + in that branch, not in the default branch. +- **Per-PR bottom-up costs approvals.** With squash-only merging, the merged commit + differs from the PR's own commits. The next PR must be rebased onto the new default + branch, a rebase is a push, and a push dismisses its approvals. Every layer pays it. +- **Prefer `gh stack merge --squash`** from a worktree on the stack. A bare + number is read first as a stack number and only then as a PR number, so a PR number can + match an unrelated stack. Before you give the command, run `gh stack view` from the + branch of the top PR you intend to merge and confirm it lists exactly the layers you + expect; if the number is ambiguous, use the stack number it shows. The merge cannot be + undone. It + merges every member up to and including that PR in one all-or-nothing operation, so + nothing in between needs rebasing or pushing. It does not bypass merge requirements: + each PR still needs its approvals and required checks, and a failure merges none of + them. With a merge queue, the stack is queued. Choose how far up to go; PRs above the + chosen one stay open and must be retargeted afterwards. +- **No pushes between approval and merge.** Every push to a stack member dismisses its + approvals. Land fixes for the top layers first, since a push to the top layer + dismisses only its own, or hold the merge until every layer has a current approval. +- After the merge, retarget the remaining PRs to the default branch, rebase their + remaining commits, and run the merge sweep (SKILL.md section 10). +- Merging from the host is the user's action. Give the command as a status-map + footnote (`references/status-map.md`) that starts with `cd &&`. + +## Checks that look failed but are not + +A double push can leave cancelled duplicate runs that still show as failures on the PR. +Before treating a red check as real, list the runs for that exact head +(`gh run list --commit `) and read the conclusions: if a run of the same workflow +on the same head succeeded, the red entry is a stale duplicate. Say that, with the run +ids, in the report. Do not re-run or push to clear it. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/status-doc.md b/personal/files/home/.agents/skills/paseo-first-mate/references/status-doc.md deleted file mode 100644 index 107c602..0000000 --- a/personal/files/home/.agents/skills/paseo-first-mate/references/status-doc.md +++ /dev/null @@ -1,64 +0,0 @@ -# Status Doc - -A Markdown file the user keeps open in a tab. The coordinator updates it in -place on every event, so chat messages can stay short. In one long session this -was the largest single improvement to the user's experience. - -Location: an ignored path in the coordinator worktree, next to the handoff -(for example `tmp/PR-STATUS.md`). It is a view for the user. GitHub stays -authoritative, and the handoff stays the coordinator's own memory. - -## Template - -```markdown -# Status () - -Updated: YYYY-MM-DD HH:MM UTC · Agents running: N (cap M) · Loop: running, interval, cap - -## Needs you -| Item | Action | Why | - -## In progress (agents) -| PR | Work | - -## Waiting on reviewers -| PR | Head | CI | Notes | - -## Backlog (not started) -| Item | Note | - -## Leaving alone (per you) -Links only. - -## Merged / closed this session -Links only. - -## Tracking issues filed -One line each, with a link. - -## Standing rules -Delivery level, grants, and process rules the user gave, each with its date. -``` - -Link every PR and issue with a full Markdown link. - -## Rules for using it - -- Update the doc first, then say one line in chat. -- Rows move between sections as state changes. Remove a row when it stops being - true (a done action, a merged PR, a duplicate). Stale rows made the user ask - twice for cleanup. -- Name the head SHA a row is true for. Re-read the PR before writing a state; - do not write from memory. -- A "Needs you" row is something only the user can do. Your own to-dos go in - Backlog or in the handoff. - -## Chat reports - -- One line per PR event, with a link, plus the decision you need. Add only what the - PR comments and commits do not already say. -- Do not recap a push, a comment, or a review that is already on the PR. -- Do not repost tables. The doc is the table. -- A quiet wake-up says nothing, or one honest line if the user asked for it. -- State a mistake plainly and fix the doc. When asked why something was missed, - give the root cause with timestamps, not an apology. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/status-map.md b/personal/files/home/.agents/skills/paseo-first-mate/references/status-map.md new file mode 100644 index 0000000..8b414c7 --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/status-map.md @@ -0,0 +1,144 @@ +# Status Map + +One standing file that is both the user's live view and the coordinator's durable +memory. It replaces the separate handoff and status doc, which repeated each other +and drifted. Throughout this skill, "the handoff" means this file. + +Location: an ignored path in the coordinator worktree, `tmp/STATUS-MAP.md`. GitHub +stays authoritative; the map is a view of it plus the things GitHub does not hold +(standing rules, controls, held decisions). + +## Principles + +- **One place per fact.** A PR's head, review state, agent, and next action live on + its one row, nowhere else. There is no heads list, no in-flight table, and no + waiting table to keep in step with the rows. +- **Single-row edits.** Every row stands alone, so copying, editing, or deleting one + row changes exactly one thing. +- **Goal and remaining work only.** History belongs to git, the PRs, and the issues. + There is no completed-work section and no log. A row exists exactly while its + resources exist; the merge sweep (SKILL.md section 10) deletes it. +- **Update the map first, then say one line in chat.** Re-read the PR before writing + its state, and name the head SHA the row is true for. + +## Template + +````markdown +# Status map () + +Updated: YYYY-MM-DD HH:MM UTC · main · Coordinator · Agents N (cap M) · Loop m/m + +## Needs @human +Per-PR actions are the `→you` rows below: `grep '→you' tmp/STATUS-MAP.md`. +- Items not tied to one PR: a release approval, an optional live re-run, a decision. + +## Path to main +```text + + + + └▶ main + + + + └▶ main + +LEGEND ✅ approved · 🔄 feedback addressed, re-review requested · 🆕 awaiting first review + 🛠️ fix in progress · 📝 draft · ⏸️ parked · 🧹 merged, sweep pending +[792a] cd && git push origin +[acc] bash tmp/cmd/acc-push.sh +[bk] tell @reviewer: PATH fix is in, re-review please +``` + +## Checkpoint +(SKILL.md section 12: four fields, replaced in place.) + +## Standing rules +Dated, verbatim where you can: delivery grants, filing rule, self-review rule, agent +reuse, reporting style, things never to touch, standing answers to permission +prompts, and the cleanup permission (merge sweep). + +## Controls +Coordinator agent ID, wait loop command (absolute path), interval and cap, heartbeat +ID and cron, agent cap, models, permission setup per workspace. + +## Pending decisions and held items +Each open question: recommendation, options, trigger. Held security findings by +title only, with a pointer to a private note outside the repository. + +## Parked +One line each, with a link and the trigger that unparks it. +```` + +Keep the whole file near 150 lines. Link every PR and issue with a full Markdown +link in prose; the rows below use `#N` so they stay narrow. + +## Row grammar + +One row per PR, issue, or workstream. Fields are separated by two or more spaces so a +row can be edited by hand: + +```text + #N <head8> <review state> agent <id> →you [key] ⚠ cleanup blocked: <reason> +``` + +- Order inside a group: tip of the stack first, bottom last. The bottom row merges + first. Standalone PRs are one group with no stack, in any order. +- `<review state>`: reviewer and verdict on **this head** (`basiliskus ✅`, + `pburkholder ✖ minor`, `none yet`). A review of an older head is written + `stale (was a0ff464e)`. +- `agent <id>`: the delegated agent working on the row, when one is. +- `→you`: the next action is the human's. This is the only marker that puts a row in + "Needs @human"; do not also copy it there. +- `[key]`: a footnote. Put it on any row, with or without `→you`. +- Heads of rows with no PR yet (workstreams) are the branch name. + +Example: + +```text +credential stack (#695) + ⏸️ #775 SDK transport v2 parked, #781 + 🔄 #730 SDK transport dd0ca08b basiliskus ✖ minor agent d119f19 + ✅ #728 provider validator 85ce5995 basiliskus ✅ →you [728m] + ✅ #726 credential revisions a0ff464e basiliskus ✅ + └▶ main + +standalone + 🛠️ #712 guided uninstall 8ca0907c stale (was 4a5bb048) agent 06534ea + 🆕 #792 Tier-3 oracle fix 8d1a3293 none yet + 🛠️ macOS acceptance stages ci/uninstall-acceptance-stages agent 274d59c →you [acc] + └▶ main + +[728m] cd <worktree> && gh stack merge 728 --squash (merges #726 to #728; checked with gh stack view) +[acc] bash tmp/cmd/acc-push.sh (needs your PAT) +``` + +## Footnotes + +A footnote key is the PR or issue number plus a short suffix when a row needs more +than one (`728m`, `acc`, `bk`). Never a running counter, so deleting a row and its +footnotes never renumbers anything. + +- A command starts with `cd <worktree> &&` so it can be pasted from anywhere. No `#` + comments in it. +- A long or quote-heavy command goes in a file under `tmp/cmd/`, and the footnote + holds `bash tmp/cmd/<name>.sh`. Copy files the host must read into the worktree + (see `references/host-commands.md`). +- A note for a person ("tell @reviewer ...") is written the same way. +- Delete a footnote with its row. A footnote with no row is stale. + +## Rules for using it + +- Rows move between groups as stacks change; a row is removed when its sweep is done. +- A `→you` row is something only the user can do. Your own to-dos are not rows. +- If the same fact now appears twice, delete one copy. +- Do not recap in chat what the map shows. Do not repost the map. + +## Chat reports + +- One line per PR event, with a link, plus the decision you need. Add only what the + PR comments and commits do not already say. +- Do not recap a push, a comment, or a review that is already on the PR. +- A quiet wake-up says nothing, or one honest line if the user asked for it. +- State a mistake plainly and fix the map. When asked why something was missed, give + the root cause with timestamps, not an apology. diff --git a/personal/files/home/gh-stack-install.sh b/personal/files/home/gh-stack-install.sh new file mode 100755 index 0000000..8d9a640 --- /dev/null +++ b/personal/files/home/gh-stack-install.sh @@ -0,0 +1,182 @@ +#!/bin/sh +# gh-stack-install.sh: install the `gh stack` extension and its agent skill so the +# paseo-first-mate skill can stack and merge PRs. Started in the background by the +# personal kit's startup command. See docs/decisions/0006. +# +# It never fails the sandbox: every problem is logged to $STATE_DIR/gh-stack.log and it +# exits 0. It does not install or upgrade `gh` itself (that needs root or an unpinned +# download); when `gh` is missing or too old it says so, and the first-mate skill's +# Prerequisites section covers the upgrade. +# +# Everything is pinned. The extension is a release binary that `gh` does not verify, so +# the script compares its sha256 with the digest recorded here (taken from the release's +# published asset digests) and removes it on a mismatch. The skill is pinned to the +# commit that tag v0.3.0 points at. + +set -u + +STACK_TAG="v0.3.0" +STACK_COMMIT="2a49e6751238633db504655d8a8eba3e433e827d" +# sha256 of the `gh-stack` binary in the v0.3.0 release, per architecture. +STACK_SHA256_LINUX_AMD64="957e822cfa7e435cd84a297cd96c419b58e51e3ac58be249762c24bd9e45099b" +STACK_SHA256_LINUX_ARM64="803ec91eeba9b2ac38827e299a79830fe75ca7284f0c28d60e6a2704bb34ed13" +# `gh skill` first shipped in gh 2.90.0. +MIN_GH="2.90.0" + +STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/paseo" +LOG="$STATE_DIR/gh-stack.log" +ATTEMPTS="${GH_STACK_ATTEMPTS:-3}" +mkdir -p "$STATE_DIR" 2>/dev/null || true + +log() { printf '%s gh-stack: %s\n' "$(date -u +%FT%TZ)" "$*" >>"$LOG"; } + +RUN_LOCK_DIR="$STATE_DIR/gh-stack.run.lock" +have_lock="" +# shellcheck disable=SC2329 # runs from the EXIT and signal traps below +cleanup() { + [ -n "$have_lock" ] && rmdir "$RUN_LOCK_DIR" 2>/dev/null + have_lock="" +} +trap cleanup EXIT +trap 'cleanup; exit 1' HUP INT TERM + +if mkdir "$RUN_LOCK_DIR" 2>/dev/null; then + have_lock=yes +else + log "another installer is running ($RUN_LOCK_DIR exists); this run did nothing" + exit 0 +fi + +PATH="$HOME/.local/bin:$PATH" +export PATH + +command -v gh >/dev/null 2>&1 || { log "gh is not installed; nothing installed (see the first-mate skill's prerequisites)"; exit 0; } + +# True when version $1 is at least $2 (both x.y.z). +version_at_least() { + have_ifs="$IFS"; IFS=. + # shellcheck disable=SC2086 + set -- $1 $2 + IFS="$have_ifs" + [ "$#" -eq 6 ] || return 1 + for part in "$1" "$2" "$3" "$4" "$5" "$6"; do + case "$part" in ""|*[!0-9]*) return 1 ;; esac + done + [ "$1" -gt "$4" ] && return 0 + [ "$1" -lt "$4" ] && return 1 + [ "$2" -gt "$5" ] && return 0 + [ "$2" -lt "$5" ] && return 1 + [ "$3" -ge "$6" ] +} + +gh_version="$(gh --version 2>/dev/null | sed -n '1s/^gh version \([0-9][0-9.]*\).*/\1/p')" +if ! version_at_least "${gh_version:-0.0.0}" "$MIN_GH"; then + log "gh '${gh_version:-unknown}' is older than $MIN_GH (needed for gh skill); nothing installed (see the first-mate skill's prerequisites)" + exit 0 +fi + +sha256_of() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" 2>/dev/null | cut -d' ' -f1 + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 "$1" 2>/dev/null | cut -d' ' -f1 + fi +} + +expected_sha256() { + case "$(uname -s 2>/dev/null)/$(uname -m 2>/dev/null)" in + Linux/x86_64) printf '%s\n' "$STACK_SHA256_LINUX_AMD64" ;; + Linux/aarch64|Linux/arm64) printf '%s\n' "$STACK_SHA256_LINUX_ARM64" ;; + esac +} + +extension_tag() { + gh extension list 2>/dev/null | awk -F'\t' '$2 == "github/gh-stack" { print $3; exit }' | + sed 's/[[:space:]]*$//' +} + +extension_listed() { + gh extension list 2>/dev/null | awk -F'\t' '$2 == "github/gh-stack" { found = 1 } END { exit !found }' +} + +# Check the installed binary against the pinned digest; remove it on a mismatch and say so +# only if it is really gone. Returns 0 when the binary is verified, 1 otherwise. +verify_extension() { + want="$1" + bin="${XDG_DATA_HOME:-$HOME/.local/share}/gh/extensions/gh-stack/gh-stack" + got="$(sha256_of "$bin")" + if [ "$got" = "$want" ]; then + return 0 + fi + gh extension remove gh-stack >>"$LOG" 2>&1 + if extension_listed; then + log "gh-stack extension digest '${got:-unreadable}' is not the pinned '$want' and it could NOT be removed: STILL INSTALLED, UNVERIFIED" + else + log "gh-stack extension REMOVED: digest '${got:-unreadable}' is not the pinned '$want'" + fi + return 1 +} + +install_extension() { + want="$(expected_sha256)" + if extension_listed; then + have="$(extension_tag)" + if [ "$have" != "$STACK_TAG" ]; then + log "gh-stack extension already installed at '${have:-unknown}', not the pin '$STACK_TAG'; skipped, NOT changed" + return 0 + fi + if [ -n "$want" ] && ! verify_extension "$want"; then + return 0 + fi + log "gh-stack extension already installed at $have; skipped" + return 0 + fi + if [ -z "$want" ]; then + log "no pinned digest for $(uname -s)/$(uname -m); the extension was NOT installed" + return 0 + fi + n=1 + while [ "$n" -le "$ATTEMPTS" ]; do + gh extension install github/gh-stack --pin "$STACK_TAG" >>"$LOG" 2>&1 + status=$? + if extension_listed; then + if verify_extension "$want"; then + log "gh-stack extension $STACK_TAG installed on attempt $n (digest verified)" + fi + return 0 + fi + log "gh-stack extension attempt $n of $ATTEMPTS failed (exit $status); see lines above" + [ "$n" -lt "$ATTEMPTS" ] && sleep 5 + n=$((n + 1)) + done + log "gh-stack extension FAILED to install after $ATTEMPTS attempts" +} + +install_skill() { + skill_file="$HOME/.agents/skills/gh-stack/SKILL.md" + if [ -f "$skill_file" ]; then + log "gh-stack skill already present; skipped" + return 0 + fi + n=1 + while [ "$n" -le "$ATTEMPTS" ]; do + gh skill install github/gh-stack gh-stack --pin "$STACK_COMMIT" --agent universal --scope user >>"$LOG" 2>&1 + status=$? + if [ -f "$skill_file" ]; then + if grep -qF "$STACK_COMMIT" "$skill_file"; then + log "gh-stack skill installed at $STACK_COMMIT on attempt $n" + else + log "gh-stack skill installed on attempt $n but its metadata does not name $STACK_COMMIT; review $skill_file" + fi + return 0 + fi + log "gh-stack skill attempt $n of $ATTEMPTS failed (exit $status); see lines above" + [ "$n" -lt "$ATTEMPTS" ] && sleep 5 + n=$((n + 1)) + done + log "gh-stack skill FAILED to install after $ATTEMPTS attempts" +} + +install_extension +install_skill +exit 0 diff --git a/personal/scripts/test-first-mate-detector.py b/personal/scripts/test-first-mate-detector.py index 6e1a40e..713cb01 100644 --- a/personal/scripts/test-first-mate-detector.py +++ b/personal/scripts/test-first-mate-detector.py @@ -84,12 +84,18 @@ def counter(name): FAKE_PASEO = """#!/bin/sh echo "paseo called: $*" >> "$FAKE_GH_DIR/calls.log" +if [ "$1" = "ls" ] && [ -f "$FAKE_GH_DIR/agents.json" ]; then + cat "$FAKE_GH_DIR/agents.json" + exit 0 +fi echo "fake paseo: not available" >&2 exit 1 """ -def pr(head="aaaaaaaa11111111", state="OPEN", merge="CLEAN", reviews=(), comments=(), draft=False, decision=None): +def pr( + head="aaaaaaaa11111111", state="OPEN", merge="CLEAN", reviews=(), comments=(), draft=False, decision=None, checks=() +): return { "headRefOid": head, "isDraft": draft, @@ -106,7 +112,7 @@ def pr(head="aaaaaaaa11111111", state="OPEN", merge="CLEAN", reviews=(), comment for i, (who, st, oid) in enumerate(reviews) ], "comments": [{"author": None if who is None else {"login": who}} for who in comments], - "statusCheckRollup": [], + "statusCheckRollup": [dict(c) for c in checks], } @@ -561,6 +567,204 @@ def test_relative_state_dir_is_not_nested(self): self.assertFalse((tmp / "tmp").exists(), "stray tmp/tmp was created") +def check(name, status="COMPLETED", conclusion="SUCCESS"): + return {"name": name, "status": status, "conclusion": conclusion} + + +def agent(short, status, name="work"): + return {"shortId": short, "status": status, "name": name} + + +class NoiseFilterTests(DetectorCase): + def test_check_counts_moving_while_pending_do_not_wake(self): + pending = check("b", status="IN_PROGRESS", conclusion=None) + self.e.setup_pr(checks=[check("a"), pending, check("c", status="QUEUED", conclusion=None)]) + self.e.baseline() + self.e.set_pr(1, checks=[check("a"), check("b"), check("c", status="QUEUED", conclusion=None)]) + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertIn("ok=2 fail=0 pending=1", self.e.state_json()["pr r#1"], "the quiet change is still saved") + + def test_checks_settling_wakes(self): + self.e.setup_pr(checks=[check("a"), check("b", status="IN_PROGRESS", conclusion=None)]) + self.e.baseline() + self.e.set_pr(1, checks=[check("a"), check("b")]) + self.assertIn("CHANGED pr r#1", self.e.det("--peek").stdout) + + def test_a_failing_check_wakes_even_while_others_are_pending(self): + pending = check("c", status="IN_PROGRESS", conclusion=None) + self.e.setup_pr(checks=[check("a"), pending]) + self.e.baseline() + self.e.set_pr(1, checks=[check("a", conclusion="FAILURE"), pending]) + out = self.e.det("--peek").stdout + self.assertIn("CHANGED pr r#1", out) + self.assertIn("failing=['a']", out) + + def test_checks_starting_again_after_settling_wakes(self): + self.e.setup_pr(checks=[check("a")]) + self.e.baseline() + self.e.set_pr(1, checks=[check("a"), check("b", status="QUEUED", conclusion=None)]) + self.assertIn("CHANGED pr r#1", self.e.det("--peek").stdout) + + def test_a_quiet_change_does_not_hide_a_later_real_one(self): + pending = check("b", status="IN_PROGRESS", conclusion=None) + self.e.setup_pr(checks=[check("a"), pending]) + self.e.baseline() + self.e.set_pr(1, checks=[check("a"), check("b", status="QUEUED", conclusion=None)]) + self.assertEqual(self.e.det("--peek").stdout, "") + self.e.set_pr(1, head="bbbbbbbb22222222", checks=[check("a"), pending]) + self.assertIn("head=bbbbbbbb", self.e.det("--peek").stdout) + + def test_an_agent_that_is_prompted_does_not_wake(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "idle"), agent("a2", "idle")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "idle")]) + self.assertEqual(self.e.det("--peek").stdout, "") + + def test_an_agent_finishing_wakes(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "idle")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "idle"), agent("a2", "idle")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + + def test_an_agent_closing_or_erroring_wakes(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "idle")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "closed")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + self.e.det("--commit") + self.e.put("agents.json", [agent("a1", "error"), agent("a2", "closed")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + + def test_an_agent_disappearing_wakes(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "idle")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "running")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + + def test_a_renamed_agent_wakes(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "running", "one")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "running", "two")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + + def test_a_new_agent_wakes(self): + self.e.det("agents", "on") + self.e.put("agents.json", [agent("a1", "running")]) + self.e.baseline() + self.e.put("agents.json", [agent("a1", "running"), agent("a2", "running")]) + self.assertIn("CHANGED agents", self.e.det("--peek").stdout) + + +class ErrorNoiseTests(DetectorCase): + def test_one_failed_run_is_silent_and_keeps_the_value(self): + self.e.setup_pr() + self.e.baseline() + saved = self.e.state_json()["pr r#1"] + (self.e.fake / "pr-1.json").unlink() + out = self.e.det("--peek") + self.assertEqual(out.stdout, "") + self.assertEqual(self.e.state_json()["pr r#1"], saved) + + def test_the_third_consecutive_failure_reports_once(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertEqual(self.e.det("--peek").stdout, "") + third = self.e.det("--peek").stdout + self.assertIn("ERROR pr r#1", third) + self.e.det("--commit") + self.assertEqual(self.e.det("--peek").stdout, "", "reported once, not every run") + + def test_a_success_resets_the_count(self): + self.e.setup_pr() + self.e.baseline() + saved = (self.e.fake / "pr-1.json").read_text() + (self.e.fake / "pr-1.json").unlink() + self.e.det("--peek") + self.e.det("--peek") + (self.e.fake / "pr-1.json").write_text(saved) + self.assertEqual(self.e.det("--peek").stdout, "") + (self.e.fake / "pr-1.json").unlink() + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertIn("ERROR pr r#1", self.e.det("--peek").stdout) + + def test_a_report_that_was_never_committed_is_repeated(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + self.e.det("--peek") + self.e.det("--peek") + first = self.e.det("--peek").stdout + self.assertIn("ERROR pr r#1", first) + again = self.e.det("--peek").stdout + self.assertIn("ERROR pr r#1", again, "a loop killed before commit must not lose the one-time report") + self.e.det("--commit") + self.assertEqual(self.e.det("--peek").stdout, "") + + def test_a_bad_error_runs_value_falls_back_to_three(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + out = [self.e.det("--peek", FIRST_MATE_ERROR_RUNS="oops") for _ in range(3)] + self.assertTrue(all(o.returncode == 0 for o in out), [o.stderr for o in out]) + self.assertIn("ERROR pr r#1", out[2].stdout) + + def test_a_removed_item_leaves_no_error_count_behind(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + self.e.det("--peek") + self.e.det("remove", "pr", "r#1") + self.e.det("--peek") + counts = json.loads((self.e.state / ".first-mate-errors.json").read_text())["counts"] + self.assertEqual(counts, {}) + + def test_a_commit_after_the_item_recovered_does_not_mark_it_reported(self): + self.e.setup_pr() + self.e.baseline() + saved = (self.e.fake / "pr-1.json").read_text() + (self.e.fake / "pr-1.json").unlink() + self.e.det("--peek") + self.e.det("--peek") + self.assertIn("ERROR pr r#1", self.e.det("--peek", FIRST_MATE_TXN="t").stdout) + (self.e.fake / "pr-1.json").write_text(saved) + self.e.det("--peek", FIRST_MATE_TXN="other") + self.e.det("--commit", FIRST_MATE_TXN="t") + (self.e.fake / "pr-1.json").unlink() + self.e.det("--peek") + self.e.det("--peek") + self.assertIn("ERROR pr r#1", self.e.det("--peek").stdout, "a new failure streak must report again") + + def test_show_always_prints_errors(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + self.assertIn("ERROR pr r#1", self.e.det("--show").stdout) + + def test_a_loop_does_not_return_on_a_single_failed_run(self): + self.e.setup_pr() + self.e.baseline() + (self.e.fake / "pr-1.json").unlink() + out = self.e.sh("1", "0") + self.assertEqual(out.returncode, 3, out.stdout + out.stderr) + + +class DetectorTimeoutTests(DetectorCase): + def test_a_hung_detector_is_killed_and_logged(self): + self.e.setup_pr() + self.e.baseline() + out = self.e.sh("1", "0", FAKE_GH_DELAY="30", FIRST_MATE_DETECTOR_SECS="2") + self.assertEqual(out.returncode, 3, out.stdout + out.stderr) + self.assertIn("detector killed after 2s", (self.e.state / ".wait.log").read_text()) + + if __name__ == "__main__": print(textwrap.dedent(f" assets under test: {ASSETS}")) unittest.main(verbosity=2) diff --git a/personal/scripts/test-gh-stack-install.py b/personal/scripts/test-gh-stack-install.py new file mode 100755 index 0000000..7579a4a --- /dev/null +++ b/personal/scripts/test-gh-stack-install.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +"""Offline tests for gh-stack-install.sh (the personal kit's startup step). + +`gh` is a fake executable on PATH, so nothing here touches the network or installs anything. +The pinned digests belong to real release binaries that cannot be reproduced offline, so the +"digest matches" case runs a temporary copy of the script with the digest lines replaced by +the digest of the fake binary. Every other case runs the shipped script unchanged. + +Usage: personal/scripts/test-gh-stack-install.py +""" + +from __future__ import annotations + +import hashlib +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.dont_write_bytecode = True + +KIT = Path(__file__).resolve().parents[1] +SCRIPT = KIT / "files/home/gh-stack-install.sh" +FAKE_BINARY = b"fake gh-stack binary\n" +FAKE_BINARY_SHA = hashlib.sha256(FAKE_BINARY).hexdigest() + +FAKE_GH = """#!/bin/sh +echo "$*" >> "$FAKE_DIR/calls.log" +data="${XDG_DATA_HOME:-$HOME/.local/share}" +case "$1 $2" in + "--version "*|"--version") + echo "gh version ${FAKE_GH_VERSION:-2.102.1} (2026-10-20)"; exit 0 ;; +esac +case "$1" in + --version) echo "gh version ${FAKE_GH_VERSION:-2.102.1} (2026-10-20)"; exit 0 ;; +esac +if [ "$1 $2" = "extension list" ]; then + if [ -f "$data/gh/extensions/gh-stack/gh-stack" ]; then + printf 'gh stack\\tgithub/gh-stack\\t%s\\n' "${FAKE_INSTALLED_TAG:-v0.3.0}" + fi + exit 0 +fi +if [ "$1 $2" = "extension install" ]; then + [ -n "${FAKE_INSTALL_FAILS:-}" ] && { echo "network down" >&2; exit 1; } + mkdir -p "$data/gh/extensions/gh-stack" + printf 'fake gh-stack binary\\n' > "$data/gh/extensions/gh-stack/gh-stack" + exit 0 +fi +if [ "$1 $2" = "extension remove" ]; then + [ -n "${FAKE_REMOVE_FAILS:-}" ] && { echo "cannot remove" >&2; exit 1; } + rm -rf "$data/gh/extensions/gh-stack" + exit 0 +fi +if [ "$1 $2" = "skill install" ]; then + [ -n "${FAKE_INSTALL_FAILS:-}" ] && { echo "network down" >&2; exit 1; } + pin="" + while [ "$#" -gt 0 ]; do + [ "$1" = "--pin" ] && pin="$2" + shift + done + mkdir -p "$HOME/.agents/skills/gh-stack" + printf -- '---\\nmetadata:\\n github-pinned: %s\\n---\\n' "$pin" > "$HOME/.agents/skills/gh-stack/SKILL.md" + exit 0 +fi +echo "fake gh: unsupported: $*" >&2 +exit 1 +""" + + +class InstallCase(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = Path(self._tmp.name) + self.home = self.root / "home" + self.fake = self.root / "fake" + self.bin = self.root / "bin" + for path in (self.home, self.fake, self.bin): + path.mkdir() + gh = self.bin / "gh" + gh.write_text(FAKE_GH) + gh.chmod(gh.stat().st_mode | stat.S_IXUSR) + # Only the tools the script needs, so the real gh can never be reached. + self.tools = self.root / "tools" + self.tools.mkdir() + for name in ( + "sh", + "date", + "mkdir", + "rmdir", + "rm", + "sed", + "cut", + "awk", + "grep", + "uname", + "sleep", + "sha256sum", + "cat", + ): + found = shutil.which(name) + if found: + (self.tools / name).symlink_to(found) + self.script = SCRIPT + + def use_matching_digest(self): + text = SCRIPT.read_text() + text = re.sub(r'^(STACK_SHA256_LINUX_[A-Z0-9_]+)=".*"$', rf'\1="{FAKE_BINARY_SHA}"', text, flags=re.M) + self.script = self.root / "gh-stack-install-test.sh" + self.script.write_text(text) + + def run_script(self, **more): + env = { + "HOME": str(self.home), + "PATH": os.pathsep.join([str(self.bin), str(self.tools)]), + "FAKE_DIR": str(self.fake), + "GH_STACK_ATTEMPTS": "2", + } + env.update(more) + return subprocess.run( # noqa: S603 -- fixed local script and a fake gh + [str(self.tools / "sh"), str(self.script)], + capture_output=True, + text=True, + env=env, + timeout=120, + check=False, + ) + + def log(self): + path = self.home / ".local/state/paseo/gh-stack.log" + return path.read_text() if path.exists() else "" + + def calls(self): + path = self.fake / "calls.log" + return path.read_text() if path.exists() else "" + + def extension_binary(self): + return self.home / ".local/share/gh/extensions/gh-stack/gh-stack" + + def skill_file(self): + return self.home / ".agents/skills/gh-stack/SKILL.md" + + +@unittest.skipUnless( + os.uname().sysname == "Linux" and os.uname().machine in ("x86_64", "aarch64", "arm64"), + "the pinned digests cover Linux x86_64 and arm64", +) +class GhStackInstallTests(InstallCase): + def test_installs_the_extension_and_skill_at_the_pins(self): + self.use_matching_digest() + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertTrue(self.extension_binary().exists()) + self.assertTrue(self.skill_file().exists()) + self.assertIn("extension install github/gh-stack --pin v0.3.0", self.calls()) + self.assertIn( + "skill install github/gh-stack gh-stack --pin 2a49e6751238633db504655d8a8eba3e433e827d" + " --agent universal --scope user", + self.calls(), + ) + self.assertIn("digest verified", self.log()) + + def test_a_digest_mismatch_removes_the_extension(self): + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertFalse(self.extension_binary().exists(), "an unverified binary must not be left installed") + self.assertIn("REMOVED", self.log()) + self.assertIn("extension remove gh-stack", self.calls()) + + def test_a_removal_that_fails_is_not_reported_as_removed(self): + self.run_script(FAKE_REMOVE_FAILS="1") + self.assertTrue(self.extension_binary().exists()) + self.assertIn("STILL INSTALLED, UNVERIFIED", self.log()) + self.assertNotIn("REMOVED:", self.log()) + + def test_an_installed_extension_with_the_wrong_digest_is_removed_on_the_next_run(self): + self.use_matching_digest() + self.run_script() + self.extension_binary().write_bytes(b"tampered\n") + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertFalse(self.extension_binary().exists()) + self.assertIn("REMOVED", self.log()) + + def test_the_shipped_digest_matches_this_machines_architecture(self): + text = SCRIPT.read_text() + wanted = {"x86_64": "AMD64", "aarch64": "ARM64", "arm64": "ARM64"}[os.uname().machine] + pinned = re.search(rf'^STACK_SHA256_LINUX_{wanted}="([0-9a-f]{{64}})"$', text, flags=re.M).group(1) + case = re.search(r"expected_sha256\(\) \{(.*?)\n\}", text, flags=re.S).group(1) + arch_lines = [line for line in case.splitlines() if os.uname().machine in line] + self.assertTrue(arch_lines, "no case line for this architecture") + self.assertIn(f"STACK_SHA256_LINUX_{wanted}", arch_lines[0]) + self.assertEqual(len(pinned), 64) + + def test_a_second_run_changes_nothing(self): + self.use_matching_digest() + self.run_script() + before = self.calls() + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertNotIn("install", self.calls()[len(before) :]) + self.assertIn("already installed at v0.3.0; skipped", self.log()) + self.assertIn("skill already present; skipped", self.log()) + + def test_a_different_installed_version_is_reported_not_changed(self): + self.use_matching_digest() + self.run_script() + before = self.calls() + self.run_script(FAKE_INSTALLED_TAG="v0.2.1") + self.assertNotIn("extension install", self.calls()[len(before) :]) + self.assertIn("NOT changed", self.log()) + + def test_a_failing_install_exits_zero_and_logs_every_attempt(self): + self.use_matching_digest() + out = self.run_script(FAKE_INSTALL_FAILS="1") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("attempt 2 of 2 failed", self.log()) + self.assertIn("extension FAILED to install", self.log()) + self.assertIn("skill FAILED to install", self.log()) + + def test_an_old_gh_installs_nothing(self): + out = self.run_script(FAKE_GH_VERSION="2.89.9") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertNotIn("install", self.calls()) + self.assertIn("older than 2.90.0", self.log()) + + def test_the_minimum_gh_version_is_allowed(self): + self.use_matching_digest() + self.run_script(FAKE_GH_VERSION="2.90.0") + self.assertIn("extension install", self.calls()) + + def test_a_missing_gh_exits_zero_with_a_message(self): + (self.bin / "gh").unlink() + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("gh is not installed", self.log()) + + def test_a_second_concurrent_run_exits_at_the_lock(self): + lock = self.home / ".local/state/paseo/gh-stack.run.lock" + lock.mkdir(parents=True) + out = self.run_script() + self.assertEqual(out.returncode, 0, out.stderr) + self.assertNotIn("install", self.calls()) + self.assertIn("another installer is running", self.log()) + self.assertTrue(lock.exists(), "a run that did not take the lock must not remove it") + + def test_a_normal_run_leaves_no_lock_behind(self): + self.use_matching_digest() + self.run_script() + self.assertFalse((self.home / ".local/state/paseo/gh-stack.run.lock").exists()) + + +class ShippedPinTests(unittest.TestCase): + def test_pins_are_full_and_unfloating(self): + text = SCRIPT.read_text() + self.assertRegex(text, re.compile(r'^STACK_TAG="v\d+\.\d+\.\d+"$', re.M), "the extension tag must be exact") + self.assertRegex( + text, re.compile(r'^STACK_COMMIT="[0-9a-f]{40}"$', re.M), "the skill commit must be a full SHA" + ) + digests = re.findall(r'^STACK_SHA256_LINUX_[A-Z0-9_]+="([0-9a-f]{64})"$', text, flags=re.M) + self.assertEqual(len(digests), 2) + self.assertEqual(len(set(digests)), 2, "each architecture needs its own digest") + + def test_installs_always_name_a_pin(self): + lines = [ + line.strip() + for line in SCRIPT.read_text().splitlines() + if re.search(r"\bgh (extension|skill) install\b", line) and not line.lstrip().startswith("#") + ] + self.assertEqual(len(lines), 2, lines) + for line in lines: + self.assertIn("--pin", line) + + def test_the_script_is_executable_and_posix_sh(self): + self.assertTrue(os.access(SCRIPT, os.X_OK)) + sh = shutil.which("dash") or "sh" + done = subprocess.run([sh, "-n", str(SCRIPT)], capture_output=True, text=True, check=False) # noqa: S603 + self.assertEqual(done.returncode, 0, done.stderr) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/personal/scripts/verify b/personal/scripts/verify index d459667..39af91e 100755 --- a/personal/scripts/verify +++ b/personal/scripts/verify @@ -20,6 +20,7 @@ SKILL_MD="$SKILL_DIR/SKILL.md" CHECK_PY="$SKILL_DIR/assets/first-mate-check.py" WAIT_SH="$SKILL_DIR/assets/first-mate-wait.sh" PLUGINS_SH="$KIT_DIR/files/home/paseo-plugins-install.sh" +STACK_SH="$KIT_DIR/files/home/gh-stack-install.sh" PYTHON_BIN="${PYTHON_BIN:-python3}" WORK="$(mktemp -d "${TMPDIR:-/tmp}/personal-verify.XXXXXX")" || { echo "mktemp failed" >&2; exit 1; } @@ -33,7 +34,7 @@ info() { printf '\n\033[1m%s\033[0m\n' "$1"; } trap 'rm -rf "$WORK" >/dev/null 2>&1 || true' EXIT INT TERM info "0. Preconditions" -for f in "$SPEC" "$SKILL_MD" "$CHECK_PY" "$WAIT_SH" "$PLUGINS_SH"; do +for f in "$SPEC" "$SKILL_MD" "$CHECK_PY" "$WAIT_SH" "$PLUGINS_SH" "$STACK_SH"; do if [ -f "$f" ]; then ok "present: ${f#"$KIT_DIR"/}" else @@ -132,7 +133,7 @@ for rel, digest in sorted(locked.items()): errors.append("missing: " + rel) elif hashlib.sha256(open(path, "rb").read()).hexdigest() != digest: errors.append("differs from lock: " + rel) -own = ("files/home/.agents/skills/paseo-first-mate/", "files/home/paseo-plugins-install.sh", +own = ("files/home/.agents/skills/paseo-first-mate/", "files/home/paseo-plugins-install.sh", "files/home/gh-stack-install.sh", "files/home/.agents/skills/diagram-design/", "files/home/.agents/licenses/diagram-design-LICENSE", "files/home/.agents/skills/show-me/") for item in lock.get("thirdParty", []): @@ -341,6 +342,38 @@ $calls EOF_CALLS [ "$plug_bad" -eq 0 ] && ok "installer is mode 0755, wired to a background startup command, github.com (and registry.npmjs.org for npm sources) allow-listed, guarded at run time, and every plugin is pinned" +info "3d2. gh stack installer is wired and pinned" +# The installer pins the extension tag, checks the binary's sha256 against a recorded +# digest, and pins the skill to a full commit. See docs/decisions/0006. +stack_bad=0 +spec_commands="$(awk '/^commands:/ {c=1; next} /^[A-Za-z]/ {c=0} c' "$SPEC" | grep -vE '^[[:space:]]*#')" +spec_caps="$(awk '/^caps:/ {c=1; next} /^[A-Za-z]/ {c=0} c' "$SPEC" | grep -vE '^[[:space:]]*#')" +rec="$(awk -v p="/home/agent/gh-stack-install.sh" '$0 == " - path: " p {f=1; next} f && /mode:/ {gsub(/"/,"",$2); print $2; exit}' "$SPEC")" +[ "$rec" = "0755" ] || { bad "spec record for gh-stack-install.sh is missing or not mode 0755 (got '${rec:-<none>}')"; stack_bad=1; } +[ -x "$STACK_SH" ] || { bad "gh-stack-install.sh lost its executable bit"; stack_bad=1; } +printf '%s\n' "$spec_commands" | grep -q 'sh /home/agent/gh-stack-install.sh' || { bad "no startup command runs gh-stack-install.sh"; stack_bad=1; } +for host in github.com api.github.com release-assets.githubusercontent.com; do + printf '%s\n' "$spec_caps" | grep -qE "^[[:space:]]+-[[:space:]]+${host//./\\.}[[:space:]]*\$" || { bad "caps.network.allow does not list $host (needed by gh-stack-install.sh)"; stack_bad=1; } +done +grep -qE '^STACK_TAG="v[0-9]+\.[0-9]+\.[0-9]+"$' "$STACK_SH" || { bad "STACK_TAG is not an exact version tag"; stack_bad=1; } +grep -qE '^STACK_COMMIT="[0-9a-f]{40}"$' "$STACK_SH" || { bad "STACK_COMMIT is not a full commit SHA"; stack_bad=1; } +[ "$(grep -cE '^STACK_SHA256_LINUX_[A-Z0-9_]+="[0-9a-f]{64}"$' "$STACK_SH")" -ge 2 ] || { bad "STACK_SHA256_* digests are missing"; stack_bad=1; } +stack_installs="$(grep -nE '\bgh (extension|skill) install\b' "$STACK_SH" | grep -vE '^[0-9]+:[[:space:]]*#' || true)" +if [ "$(printf '%s\n' "$stack_installs" | grep -c .)" -ne 2 ] || [ "$(printf '%s\n' "$stack_installs" | grep -c -- '--pin')" -ne 2 ]; then + bad "gh-stack-install.sh must have exactly two installs, both with --pin" + printf '%s\n' "$stack_installs" | sed 's/^/ | /' >&2 + stack_bad=1 +fi +grep -qF 'gh extension remove gh-stack' "$STACK_SH" || { bad "the digest-mismatch removal is missing"; stack_bad=1; } +if "$PYTHON_BIN" "$KIT_DIR/scripts/test-gh-stack-install.py" >"$WORK/stack.log" 2>&1; then + : +else + bad "gh-stack-install.sh behaviour tests failed" + sed 's/^/ | /' "$WORK/stack.log" >&2 + stack_bad=1 +fi +[ "$stack_bad" -eq 0 ] && ok "gh stack installer is mode 0755, wired to a background startup command, pinned and digest-checked, hosts allow-listed, behaviour tests pass ($(grep -c ' ok$' "$WORK/stack.log") tests)" + info "3e. Diagram Design provenance and offline export guard" if "$PYTHON_BIN" "$KIT_DIR/scripts/test-diagram-design.py" >"$WORK/diagram.log" 2>&1; then ok "Diagram Design hashes, offline templates, guarded SVG export and browser denial tests pass" @@ -372,8 +405,14 @@ else bad "paseo-plugins-install.sh has a syntax error" sed 's/^/ | /' "$WORK/plugins-sh.log" >&2 fi +if sh -n "$STACK_SH" 2>"$WORK/stack-sh.log"; then + ok "gh-stack-install.sh parses as POSIX sh" +else + bad "gh-stack-install.sh has a syntax error" + sed 's/^/ | /' "$WORK/stack-sh.log" >&2 +fi if command -v shellcheck >/dev/null 2>&1; then - if shellcheck --severity=warning "$WAIT_SH" "$PLUGINS_SH" "$0" "$KIT_DIR/scripts/test-wait-lock" >"$WORK/shellcheck.log" 2>&1; then + if shellcheck --severity=warning "$WAIT_SH" "$PLUGINS_SH" "$STACK_SH" "$0" "$KIT_DIR/scripts/test-wait-lock" >"$WORK/shellcheck.log" 2>&1; then ok "shellcheck --severity=warning passes" else bad "shellcheck --severity=warning failed" diff --git a/personal/spec.yaml b/personal/spec.yaml index 21c67fd..a0f6f99 100644 --- a/personal/spec.yaml +++ b/personal/spec.yaml @@ -17,8 +17,10 @@ # playbook kit ships a different skill named code-review into the same # directory. # -# ONE COMMAND, AT STARTUP, IN THE BACKGROUND: the skills are dropped at their -# final path, so they need no command. The one startup command runs +# TWO COMMANDS, AT STARTUP, IN THE BACKGROUND: the skills are dropped at their +# final path, so they need no command. One startup command runs +# gh-stack-install.sh, which installs the pinned `gh stack` extension and its +# agent skill when `gh` is new enough (docs/decisions/0006). The other runs # paseo-plugins-install.sh, which waits for the Paseo daemon that the separate # `paseo` kit starts, turns on the daemon's plugin switch, and installs the # plugins listed in that script at pinned commits. It is detached, always exits @@ -27,8 +29,10 @@ # installs nothing. See docs/decisions/0003. # # EGRESS: github.com for `git clone` of git-sourced plugins, registry.npmjs.org for -# npm-sourced ones. The skills themselves need none; the first-mate scripts call the `gh` and `paseo` -# CLIs when the agent runs them, and those CLIs' needs belong to other kits. +# npm-sourced ones, and api.github.com plus release-assets.githubusercontent.com for +# `gh extension install` and `gh skill install`. The skills themselves need none; the +# first-mate scripts call the `gh` and `paseo` CLIs when the agent runs them, and those +# CLIs' needs belong to other kits. # # NO `agent:` BLOCK and NO published ports: this is an opt-in --kit mixin. # @@ -49,6 +53,8 @@ caps: network: allow: - github.com + - api.github.com + - release-assets.githubusercontent.com - registry.npmjs.org files: @@ -76,10 +82,10 @@ files: mode: "0644" source: files/home/.agents/skills/paseo-first-mate/references/stacking.md description: Stacking reviewed PRs with gh-stack - - path: /home/agent/.agents/skills/paseo-first-mate/references/status-doc.md + - path: /home/agent/.agents/skills/paseo-first-mate/references/status-map.md mode: "0644" - source: files/home/.agents/skills/paseo-first-mate/references/status-doc.md - description: The maintained status doc and reporting rules + source: files/home/.agents/skills/paseo-first-mate/references/status-map.md + description: The status map (handoff and live view in one file) and reporting rules - path: /home/agent/.agents/skills/paseo-first-mate/assets/first-mate-check.py mode: "0755" source: files/home/.agents/skills/paseo-first-mate/assets/first-mate-check.py @@ -104,6 +110,10 @@ files: mode: "0755" source: files/home/paseo-plugins-install.sh description: Wait for the Paseo daemon, enable plugins, and install the pinned plugin list + - path: /home/agent/gh-stack-install.sh + mode: "0755" + source: files/home/gh-stack-install.sh + description: Install the pinned gh stack extension (digest-checked) and its agent skill when gh is new enough # BEGIN vendored:mattpocock-skills (generated by scripts/vendor-pocock-skills; do not edit) - path: /home/agent/.agents/licenses/mattpocock-skills-LICENSE mode: "0644" @@ -605,6 +615,15 @@ commands: - -c - | sh /home/agent/paseo-plugins-install.sh & + - phase: startup + user: "1000" + background: true + description: Install the pinned gh stack extension and skill (background, never fails the sandbox) + command: + - sh + - -c + - | + sh /home/agent/gh-stack-install.sh & agentContext: | ## Personal skills @@ -615,6 +634,10 @@ agentContext: | agents, issues, or dependent pull requests. Copy its `assets/` scripts into the coordinator worktree's git-ignored `tmp/` as the skill describes rather than running them in place. + - `gh stack`: at startup a background script installs the pinned `gh stack` + extension and its `gh-stack` skill when `gh` is 2.90.0 or later. Its log is + `~/.local/state/paseo/gh-stack.log`. If `gh stack --help` fails, the + first-mate skill's Prerequisites section says how to fix it. - Paseo plugins: at startup a background script enables plugins on the Paseo daemon and installs the ones listed in `~/paseo-plugins-install.sh`. Its log is `~/.local/state/paseo/paseo-plugins.log`; `paseo plugin ls` shows the