diff --git a/Makefile b/Makefile index d77b58e..30687cf 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/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/vendor/diagram-design-local/scripts GITLEAKS ?= gitleaks .PHONY: setup check lint test validate security diff --git a/personal/README.md b/personal/README.md index 6087c89..5961c7a 100644 --- a/personal/README.md +++ b/personal/README.md @@ -13,8 +13,10 @@ network hosts, `github.com` and `registry.npmjs.org`, for that command. ```text ~/.agents/skills/ - paseo-first-mate/ the author's own skill (version 1.4.0) and two helper scripts + paseo-first-mate/ the author's own skill (version 1.5.0), its references, and two helper scripts SKILL.md + references/*.md longer procedures the skill links to (delegation, status doc, + 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 FIRST_MATE_DIR, owned by the starting agent (flock) @@ -242,7 +244,8 @@ running and who owns it. A missing tool is reported rather than hidden: the detector prints an `ERROR` line naming the missing CLI, and the shell reports a missing `python3`. The detector only reads GitHub and Paseo state; its only writes are the state and watch files, and the directory that holds them, -`FIRST_MATE_DIR` (default `./tmp`, relative to the current directory). +`FIRST_MATE_DIR` (default `tmp`, resolved to an absolute path; running from inside +`tmp/` does not nest it). ## Updating the First Mate skill diff --git a/personal/TROUBLESHOOTING.md b/personal/TROUBLESHOOTING.md index 51aacd9..f79286c 100644 --- a/personal/TROUBLESHOOTING.md +++ b/personal/TROUBLESHOOTING.md @@ -61,14 +61,16 @@ shell's "command not found" as its output. ## The detector prints nothing and the wait loop never returns That is the intended quiet path: once a baseline exists, it prints nothing when -nothing changed, and the wait loop exits 3 at its cap. The very first run prints -`BASELINE saved` (even with an empty watch list, because agents and permission -prompts are always collected), so the wait loop returns once at first start; -start it again after that (check `status` first). If `paseo` is missing the baseline never settles (see the -previous section), so the loop returns every time. Run the script with `--show` +nothing changed, and the wait loop exits 3 at its cap (default 8 hours), printing one +line that says so. The very first run prints +`BASELINE saved`, so the wait loop returns once at first start; start it again +after that (check `status` first). If `gh` is missing, or `paseo` is missing while +`agents on` or `permits on` is set, the baseline never settles (see the previous +section), so the loop returns every time. Run the script with `--show` to see the full current snapshot, and `list` to see what is being watched. State -and watch files live in `FIRST_MATE_DIR` (default `./tmp`), relative to where -you run the script. +and watch files live in `FIRST_MATE_DIR` (default `tmp`), which the scripts resolve to +an absolute path. `first-mate-wait.sh status` also shows `last-run=`, the age of the +last completed detector run, and warns when it is over twice the interval. ## Several wait loops, or "refusing: a loop is running" 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 3da64da..dace63c 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.4.0" +version: "1.5.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.5.0" + changes: "Wait loop made hard to lose: a first-command-every-turn rule, an hourly heartbeat backstop as part of the default procedure, `status` shows the age of the last detector run and warns when it is stale, and a cap expiry prints one line (default cap now 8 hours). Detector assets: two-phase save (`--peek`/`--commit`) so a killed loop reports a change again instead of losing it, flock-serialized local state, optional own-login filter (off by default), merge-state collapse with UNKNOWN retry, auto-prune of merged and closed items, current head and stale-review marker, absolute `FIRST_MATE_DIR`; offline tests in the kit. SKILL.md: Secrets section, reporting rules and a status doc, credential-limit and host-command pattern, permission-prompt handling, coordinator successor procedure, delegation prompt rules, gh-stack stacking, and a cross-PR checklist, the long ones in `references/`." - version: "1.4.0" changes: "Agent watching reworked: scoped by `paseo.parent-agent-id` label instead of agent name, and agent/permission watching is now opt-in and off by default (`agents on` / `permits on`). The harness already sends finish notices and surfaces pending permits, so watching them by default made the loop wake on the coordinator's own create/archive/finish actions." - version: "1.3.0" @@ -96,6 +98,20 @@ The First Mate coordinates delivery. It does not replace code owners, approve its own work, invent live validation results, or merge changes without explicit authorization. +## Loop Rule (Read First) + +The wait loop exits on purpose when it finds a change, and it ends at its cap +with a one-line notice (exit 3). A missed restart once left five reviews unseen +for three hours. So, as the confirmed coordinator (section 1): + +1. **The first command of every turn is `first-mate-wait.sh status`.** If it + says `none`, restart the loop in that same turn, before anything else. A + non-coordinator (a fork, or a resumed session the user has not confirmed) runs + `status` read-only and starts nothing. +2. **Always run the hourly heartbeat backstop** (section 8). It is part of the + default procedure, not an alternative. +3. Report a loop as running only from a `status` result obtained this turn. + ## When to Use - An epic spans several issues or repositories. @@ -158,6 +174,26 @@ Single-change and read-only work are covered by `avoid_when` above. `take-over` and `stop --force` act on another agent's loop and need the user's explicit word each time; a standing grant does not cover them. +## Secrets + +Invariant 9 in practice. Echoing a token or key value can lock the session, so +treat these as hard stops, for yourself and in every delegation prompt: + +- Never print a secret's value: not in a command, a log, a PR comment, a handoff, + or a report. Names of variables are fine; values are not. +- Never run: bare `env`, `printenv`, `export -p`, `set`, `gh auth token`, + `gh auth status` without a filter (or with a show-token flag), or a command + that dumps a credential file or config. +- To run a command without a variable, use `env -u NAME cmd`. Do not strip the + token variable for a `gh` command that needs it: one `gh stack` command failed + with "none of the git remotes point to a known GitHub host" under `env -u` + and worked without it (hypothesis: it needed the variable for auth when no + stored login existed). +- The bundled scripts never read a token. They call `gh` and `paseo`, which use + their own credentials, and the detector prints only state summaries. +- If a value is printed by mistake, say so at once and tell the user. Do not + hide it or retry. + ## Delivery Levels State the level in every delegation prompt. The user sets it; the coordinator @@ -190,6 +226,11 @@ the handoff. unless the user explicitly overrides that. - The grant covers draft to ready only. It never covers merge. +When the credential cannot do what the level allows (for example, a token that +cannot push workflow files), the agent commits locally, makes one plain push +attempt, and stops with the exact host command. See +`references/host-commands.md`. + ## Procedure ### 1. Adopt or Establish the Role @@ -210,8 +251,12 @@ When resuming an existing effort, or when this session is a fork of another: state, resume it, or recreate it without authorization. Reconcile workspaces against `paseo workspace ls`; retained-workspace notes may be stale in a fresh sandbox. -5. As the confirmed coordinator, ensure one wait loop is running (section 8). - Record your agent ID as coordinator in the handoff. +5. As the confirmed coordinator, ensure one wait loop and its heartbeat backstop + are running (section 8). Record your agent ID as coordinator in the handoff. + +When the user hands the effort to a new coordinator, or you are about to, follow +`references/handoff-and-successor.md`: the loop lock, the old heartbeat, and the +agents' notices are all bound to the old coordinator's ID. ### 2. Establish the Mission @@ -322,9 +367,17 @@ expose, so ask the user to set it after creating a workspace. A provider "build" mode may not suppress prompts; check pending permissions and the daemon log. Never approve a request unless the user instructs it. A standing policy the user has recorded in the handoff (for example, routine web search for public -questions) counts as an instruction, within its stated scope. Some tools need a -specific response shape; if a plain "allow" fails with a validation error, retry -in the shape the error names and record the working form in the handoff. +questions) counts as an instruction, within its stated scope. Never approve a +prompt that sends data to an external service on your own. + +Some tools need a specific response shape; if a plain "allow" fails with a +validation error, retry in the shape the error names and record the working form +in the handoff. For a question-style prompt (for example, a search-service +choice) that you must refuse, one shape worked where several "allow" forms were +rejected by the API: `paseo_respond_to_permission` with +`{"behavior":"deny","interrupt":false,"message":""}`. If an +agent has finished and sits idle with a prompt nobody can dismiss, archiving the +agent clears it (check section 10 first). Both were observed on one Paseo version. Base of a new workspace: `git fetch` first and create the workspace from `origin/` (or the exact head of the PR you depend on), never from @@ -338,6 +391,12 @@ it lands, and do not mark the new work ready first. If an SSH fetch fails host-key verification, fetch over authenticated HTTPS without altering remotes. Never bypass the check. +Build the prompt from `references/delegation-prompt.md`: it holds the rules that +each cost a session something when missing (verify the remote head, merge not +rebase, never delete files you did not create, report every commit, re-review +after applying suggestions, one heavy suite at a time, no external search, brief +reports, clean up only your own scratch). + An implementation prompt states: issue, branch, and delivery level; in- and out-of-scope behavior; base; acceptance criteria including the live criterion; required focused tests and agent-launched self-review; the draft/ready/merge guard; the PR standard @@ -388,6 +447,10 @@ 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 cross-repository dependencies: - Keep the dependent PR draft. @@ -445,21 +508,34 @@ are satisfied and current-head CI/review is green, unless the user has granted ### 8. Follow Up With a Change-Detecting Check -The coordinator needs something to wake it. Two mechanisms are acceptable; use the -one the user prefers and record the choice and any later change in the handoff: +The coordinator needs something to wake it. Use both of these together, and +record the choices and any later change in the handoff: -- **Background wait loop (default, cheapest).** A shell loop that runs the check +- **Background wait loop (the cheap wake-up).** A shell loop that runs the check on an interval and exits only when something changed. The harness notifies the coordinator when it finishes, so waiting costs no model calls. There is at most - one loop per `FIRST_MATE_DIR`, and it is owned by the agent that started it. -- **Paseo heartbeat.** A scheduled prompt that runs the check each time. Use - `paseo heartbeat update --cron ...` to change its cadence (for example, - hourly while nothing is moving, every 15 minutes once something changes). - Prefer it when the user plans to fork or resume sessions often: a heartbeat is a - named schedule, so it is one object that no fork can duplicate, at the price of a - model call per run. - -Either way, a quiet wake-up must not turn into filler. Empty calls (`true`, + one loop per `FIRST_MATE_DIR`, and it is owned by the agent that started it. It + ends on every change and at its cap, so it needs restarting (see the Loop Rule). +- **Hourly Paseo heartbeat (the backstop, always on).** A scheduled prompt that + checks the loop is alive. When healthy it costs one shell call. It is what + catches a loop that ended and was not restarted. Create it when you start the + loop (`paseo heartbeat create`, five-field cron, for example `7 * * * *`), and + delete it when coordination ends. Its prompt, with the path filled in: + + ```text + Run `/first-mate-wait.sh status`. If it starts with `mine` and + has no WARNING line, end the turn silently. If it starts with `none`, start the + loop again as a background command (`/first-mate-wait.sh + `), run `/first-mate-check.py --show` once, and + 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. + ``` + + Use `paseo heartbeat update --cron ...` to change its cadence. + +In both cases a quiet wake-up must not turn into filler. Empty calls (`true`, `date > /dev/null`) cost tokens, change nothing, and can run away into hundreds of calls. Run the check once, then end the turn. @@ -478,15 +554,41 @@ Bundled assets: (for example `add branch kits@main`, `add workflow kits:deploy.yml@main`); `--show` prints the snapshot without saving, and `--reset` forgets state. State and watch files live in - `FIRST_MATE_DIR` (default `./tmp`, which must be ignored by git). -- `assets/first-mate-wait.sh INTERVAL_MIN MAX_MIN` runs the check on an interval - and exits as soon as it reports a change (exit 0, report printed) or at the cap - (exit 3, nothing printed). It holds an `flock` on `FIRST_MATE_DIR/.wait.lock` + `FIRST_MATE_DIR` (default `tmp`, which must be ignored by git). It is made + absolute, and a relative value does not nest when you run from inside it (the + stray `tmp/tmp` bug). + - **Two-phase save.** `--peek` prints what changed and stages the save, without + consuming anything. `--commit` applies it only if the saved state is still the + one the peek used. The wait loop runs peek, prints, then commit. A loop killed + in between leaves the state untouched, so the next run reports the same change + again: a duplicate, never a miss. A run with no flag does both in one step. + - **Merge state** is collapsed to `conflict`, `behind`, or `ok`, and a transient + `UNKNOWN` is re-queried up to three times, so GitHub recomputing does not wake + you. + - **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. + - **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. + - **Own-login filter (`selffilter on`, off by default).** It ignores comments and + reviews written by your own login, so your own posts do not wake the loop. If a + human and an agent share one login, it also hides the human's comments and + reviews, which is the worse failure, so leave it off in that setup and accept + the extra wake-up. Your login comes from `FIRST_MATE_SELF_LOGIN` or `gh api user`. + - Needs Python 3.9+; the wait script needs bash 3.2+ and `flock`. +- `assets/first-mate-wait.sh [INTERVAL_MIN [MAX_MIN]]` runs the check on an + interval (default 15 minutes, cap 480) and exits as soon as it reports a change + (exit 0, report printed) or at the cap (exit 3, one line saying so). It holds an + `flock` on `FIRST_MATE_DIR/.wait.lock` and records the owner (`$PASEO_AGENT_ID`), pid, and start time. The lock frees itself when the process dies, so there is no stale pidfile. Starting while a loop is running never starts a second one: exit 4 if you own it, exit 5 if another agent does. Other forms: - - `status` prints `none`, `mine ...`, or `other owner= ...`. + - `status` prints `none`, `mine ...`, or `other owner= ...`, with + `last-run= ago`, the age of the last completed detector run. It adds a + `WARNING` when that age is over twice the interval: a stuck loop or a failing + detector otherwise looks like a quiet one. - `stop` stops your own loop; `stop --force` stops another owner's. - `take-over INTERVAL MAX` stops any running loop and starts yours. Use it only after the user confirms you are the coordinator. @@ -499,15 +601,17 @@ Procedure: workflows that the effort's milestone depends on. A merge you did not make (another session, another person) and a pipeline that stays red after your merge are both invisible to a PR-only watch list. -2. For the wait loop, run `first-mate-wait.sh status` first, then start the - script as a **background** shell command only if it says `none`. For a - heartbeat, have its prompt run `first-mate-check.py` once. +2. Run `first-mate-wait.sh status` first, then start the script as a + **background** shell command only if it says `none`. Create the hourly heartbeat + with the prompt above. Use absolute paths in both. 3. Use a 5-minute interval while work is in flight (an agent running, CI pending, - or a review or live run awaited) and 15 minutes when quiet. Use a cap of about - two hours on the wait loop. After handling a notification, ensure a loop is - running (`status`, then start if `none`); never start one blindly. To change - the interval, `stop` and start again. Exit code 4 on a start means the loop - you wanted is already there, so do nothing more. + or a review or live run awaited) and 15 minutes when quiet. Use a cap of 8 to + 10 hours (`480` to `600`) on the wait loop, since sessions run long. A cap + expiry prints one line and exits 3: start a new loop. After handling a + notification, run `status` and start a loop if it says `none`, in that same + turn; never start one blindly. To change the interval, `stop` and start again. + Exit code 4 on a start means the loop you wanted is already there, so do + nothing more. 4. **Quiet wake-up rule:** if the check reports nothing, make no further tool calls and end the turn. Whether to say "no change" follows the user's current preference; record it in the handoff. Say it only when it is true: the check @@ -517,14 +621,17 @@ Procedure: When a branch report shows a merge, reconcile before anything else: which open recommendations, agents, and PRs does it supersede, conflict with, or unblock? Another session may have fixed the problem differently. -6. Prune merged and closed items from the watch list. +6. Merged and closed items are pruned automatically; add new PRs as you create + or adopt them. Periodically run the checks in `references/cross-pr-checklist.md`. 7. Report a loop as running only from a `status` result obtained this turn, never from the handoff or from memory. -The detector saves its snapshot when it reports. Two agents running it against -one `FIRST_MATE_DIR` split the events between them, and one never sees a change -the other consumed. Only the coordinator runs it in saving mode; everyone else -uses `--show`. +The detector saves its snapshot when a report is committed. Two agents running it +in saving mode against one `FIRST_MATE_DIR` split the events between them, and one +never sees a change the other consumed. Only the coordinator runs it in saving +mode; everyone else uses `--show`. Reading a PR directly (`gh pr view`) before you +state its state is still required: the detector summarizes, it does not replace +reading. The check resolves exact-head state, so stale cached PR check fields cannot mislead it. It cannot see GitHub notifications or review requests on PRs outside @@ -565,19 +672,25 @@ Updated: YYYY-MM-DD HH:MM UTC ## Wait Log ``` -- **Controls:** coordinator agent ID (`$PASEO_AGENT_ID` of the owner), wait - mechanism (loop or heartbeat), interval, and cap, schedule status (or "not visible"), +- **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. 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: delivery - grants, ready-when-green, filing rule, self-review rule, agent reuse, and - standing answers to routine permission prompts (for example, "web search is - allowed for public questions"). Apply a recorded policy; ask about anything it - does not cover. +- **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 + 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 @@ -639,6 +752,25 @@ After upstream merges: Do not declare the milestone complete until production wiring, downstream consumers, current-head CI, review, and live evidence agree. +## Reporting + +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`. +- **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. +- **A quiet wake-up says nothing** (or one honest line if the user asked for it). +- **Do not report from memory.** Re-read the PR before you state its state, and + name the head SHA when you say "done". If you were wrong, say so plainly and fix + it. +- **When asked why something was missed,** give the root cause with timestamps, + not an apology. + ## Working With the User and Reviewers - **Check existing evidence before asking the user to repeat work.** Search the @@ -662,7 +794,11 @@ consumers, current-head CI, review, and live evidence agree. silently. Say which checks did not run, and ask before installing anything. - **Host-run scripts.** When the user must run something on their machine, give one line starting with a `cd` to the right worktree, or a script plus a one-line - invocation. Scripts must: + invocation. Put no `#` comments inside any block the user will paste: an + interactive zsh passes `#` through as an argument, so give expectations in + prose. Copy files the host must read (a PR body, a script) into the worktree and + exclude them from Git, because the host cannot see the sandbox's temporary + directories (`references/host-commands.md`). Scripts must: - use `timeout --foreground`; plain `timeout` backgrounds the child's process group, and job control freezes it (state `T`) when it touches the terminal; - show live output (`tee`) and set non-interactive flags for the tool under test; @@ -683,6 +819,14 @@ consumers, current-head CI, review, and live evidence agree. Raise it early; the exemption or manual trigger is the user's decision. - **State only what you have verified.** If you have not looked since the last report, say so. Correct a mistaken claim as soon as you notice it. +- **Tie evidence to a head.** Another agent's result (for example, a run on a + platform you cannot reach) counts only for the exact SHA it names. Label an older + report "old head, does not carry over". `NOT EXERCISED` is a result; never turn + it into PASS. Hosted CI is the authority, and the sandbox cannot run other + platforms, so say that on the PR. +- **Tiers and host recipes.** Split risky acceptance into a safe tier on the real + account and a destructive tier in an isolated account, VM, or CI runner, and + watch for the recipe pitfalls in `references/host-commands.md`. - **Lead reports with what changed and what needs a decision.** List decisions once under "What I need from you". @@ -725,7 +869,8 @@ Before declaring coordination complete, verify: - The handoff reflects the final state and its log is cleared. - Exactly one coordinator is recorded, and `first-mate-wait.sh status` was run this turn before any statement about the loop. -- The wait loop or heartbeat is stopped and its state file cleared when coordination ends. +- The wait loop and its heartbeat are stopped, and the state file cleared, when + coordination ends. ## Troubleshooting @@ -748,8 +893,29 @@ Before declaring coordination complete, verify: | Reviewer's change request remains after the fix | Reply with the commits and wait for re-review; a push does not clear it. | | Release PR has no checks | Workflow-token PRs may not trigger them. Ask the user: exempt or trigger manually. | | 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. | +| 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. | +| `gh pr view --json reviewRequests` fails on a GraphQL scope error | Use REST: `gh api repos/OWNER/REPO/pulls/N` (`.requested_reviewers`), and request with `gh api -X POST .../requested_reviewers -f 'reviewers[]=LOGIN'` (`references/host-commands.md`). | +| A push is rejected for a missing scope (for example, workflow files) | Stop after one attempt. Give the exact host command and verify the remote head afterwards (`references/host-commands.md`). | +| An agent raised a search-service permission prompt | Deny it with a message (Permissions in section 5); never approve an external-service prompt on your own. If the prompt cannot be cleared, archive the idle agent. | +| An agent errors with a transient network error | Re-prompt it ("restart from the top, the worktree is clean") before replacing it. Keep one agent per branch. | +| Workspace creation fails with a git configuration error | Run `git worktree prune`, delete the stale local branch of the same name if it matches the remote, and retry. | +| A successor coordinator gets no finish notices | Agents carry the old coordinator's `paseo.parent-agent-id`. Poll `paseo_get_agent_status` on each wake-up (`references/handoff-and-successor.md`). | | Coordinator context is compacted | Read the handoff, GitHub metadata, and the active Paseo inventory before acting. | +## 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/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. +- `references/stacking.md`: stacking reviewed PRs with `github/gh-stack`. +- `references/cross-pr-checklist.md`: periodic cross-PR checks. + ## Related Patterns - Repository code-review procedures for final human review and PR quality. 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 ea14347..62cdcd0 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 @@ -4,8 +4,12 @@ Prints NOTHING when nothing meaningful changed since the last run, so a wait loop that finds no change costs no model tokens. Prints one block per change otherwise. Read-only against GitHub and Paseo; the only writes are the -local state and watch files in FIRST_MATE_DIR (default: ./tmp, which should be -ignored by git). +local state and watch files in FIRST_MATE_DIR (default: tmp, which should be +ignored by git). FIRST_MATE_DIR is made absolute: a relative value resolves +against the current directory, except that when that directory does not exist +and this script itself sits in a directory with that path tail (the skill copies +the scripts into tmp/), the script's directory is used. Running from inside tmp/ +therefore never creates tmp/tmp. What to watch lives in first-mate-watch.json, not in this script: {"repos": {"qs": "OWNER/repo", ...}, @@ -17,9 +21,28 @@ A watched branch reports each new commit on it (so work that lands from other sessions is seen). A watched workflow reports the latest run on a branch: its head, status, and conclusion (so a deploy that stays red after a merge is seen). +A PR line shows its current head and a `stale-review=[...]` marker when a +reviewer's latest approval or change request was made on an older head. +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. + +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 + state it was computed against; consumes nothing + --commit apply the staged save (and auto-prune) if that state is still current, + otherwise drop it +A killed loop leaves the saved state untouched, so the next run reports the same +change again: a duplicate, never a miss. A commit applies only a pending save that +was staged under the same FIRST_MATE_TXN (unset matches unset), so one loop's commit +never consumes another run's report. Without a flag the detector reports and saves +in one step. State saved by an older version holds raw merge values, so run --reset +once after upgrading, or expect one CHANGED line per PR. Usage: - first-mate-check.py compare to saved state, print changes, save + first-mate-check.py compare to saved state, print changes, save (one step) + first-mate-check.py --peek print changes and stage the save + first-mate-check.py --commit apply the staged save first-mate-check.py --show print the full current snapshot, save nothing first-mate-check.py --reset forget saved state (next run is a baseline) first-mate-check.py list print the watch list @@ -29,23 +52,67 @@ watch the latest run of a workflow on a branch first-mate-check.py remove pr qs#611 stop watching and forget its state (also: issue, branch, workflow) first-mate-check.py repo qs OWNER/repo register a repo alias - first-mate-check.py prune stop watching merged/closed PRs and closed issues + first-mate-check.py prune stop watching merged/closed PRs and closed issues now + first-mate-check.py autoprune on|off do that automatically when a report is saved (default on) + first-mate-check.py selffilter on|off ignore comments and reviews by your own login (default off) first-mate-check.py agents on|off watch your own delegated agents (off by default) first-mate-check.py permits on|off watch pending permission prompts (off by default) + +selffilter: your login is FIRST_MATE_SELF_LOGIN, or else `gh api user`. A human +and an agent that share one login are both filtered, which also hides the human's +own comments and reviews; leave it off in that setup. Toggling it, or running +--reset, makes the next run a baseline. + +Needs Python 3.9+. The state lock uses fcntl; where that is missing (Windows) the +detector still runs but concurrent runs are not serialized. """ + import concurrent.futures as cf +import hashlib import json import os import re import shutil import subprocess import sys +import time +from contextlib import contextmanager, nullcontext, suppress + +try: + import fcntl +except ImportError: # no flock on this platform + fcntl = None + +DEFAULT_DIR = "tmp" +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) -HERE = os.path.abspath(os.environ.get("FIRST_MATE_DIR", "tmp")) + +def resolve_dir(value, cwd=None, script_dir=None): + """Absolute FIRST_MATE_DIR (see the module docstring for the rule).""" + value = value or DEFAULT_DIR + if os.path.isabs(value): + return os.path.normpath(value) + value = os.path.normpath(value) + candidate = os.path.join(os.path.abspath(cwd or os.getcwd()), value) + script_dir = os.path.abspath(script_dir or SCRIPT_DIR) + if not os.path.isdir(candidate) and script_dir.endswith(os.sep + value) and os.path.dirname(script_dir) != os.sep: + return script_dir + return candidate + + +HERE = resolve_dir(os.environ.get("FIRST_MATE_DIR")) os.makedirs(HERE, exist_ok=True) 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") +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")) +LOGIN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*(?:\[bot\])?$") +GATING = ("APPROVED", "CHANGES_REQUESTED", "DISMISSED") DEFAULT_WATCH = { "repos": {}, @@ -61,11 +128,15 @@ # `permits on` for heartbeat flows that receive no harness finish notices. "watch_agents": False, "watch_permits": False, + # Drop merged/closed PRs and closed issues from the watch list when a report + # that shows them is saved. Ignore your own login's comments and reviews + # (off: a human and an agent often share one login). + "autoprune": True, + "self_filter": False, } BRANCH_REF = re.compile(r"^(?P[A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)?)@(?P.+)$") -WORKFLOW_REF = re.compile( - r"^(?P[A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)?):(?P[^@:]+)@(?P.+)$") +WORKFLOW_REF = re.compile(r"^(?P[A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)?):(?P[^@:]+)@(?P.+)$") BAD_CONCLUSIONS = {"FAILURE", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"} BAD_STATES = {"FAILURE", "ERROR"} REF = re.compile(r"^(?:(?P[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+|[A-Za-z0-9_-]+)#)(?P\d+)$") @@ -78,14 +149,41 @@ def load_watch(): with open(WATCH) as fh: w = json.load(fh) for k, v in DEFAULT_WATCH.items(): - w.setdefault(k, type(v)()) + w.setdefault(k, json.loads(json.dumps(v))) return w +def write_atomic(path, text): + tmp = f"{path}.{os.getpid()}.tmp" + try: + with open(tmp, "w") as fh: + fh.write(text) + fh.flush() + os.fsync(fh.fileno()) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.remove(tmp) + + def save_watch(w): - with open(WATCH, "w") as fh: - json.dump(w, fh, indent=1) - fh.write("\n") + write_atomic(WATCH, json.dumps(w, indent=1) + "\n") + + +@contextmanager +def file_lock(path): + if fcntl is None: + yield + return + with open(path, "a") as fh: + fcntl.flock(fh, fcntl.LOCK_EX) + yield + + +def state_lock(): + """Serializes every read-modify-write of the state, pending, and watch files. + Held only around local file work, never around network calls.""" + return file_lock(LOCKFILE) def resolve(w, ref): @@ -146,14 +244,88 @@ def gh_json(args): return json.loads(run(["gh"] + args)) -def pr_snapshot(repo, num): - d = gh_json([ - "pr", "view", str(num), "--repo", repo, "--json", - "headRefOid,isDraft,state,reviewDecision,mergeStateStatus,reviews,comments,statusCheckRollup", - ]) - inline = sum(int(x) for x in run([ - "gh", "api", f"repos/{repo}/pulls/{num}/comments?per_page=100", "--paginate", - "--jq", "length"]).split()) +_SELF = [] + + +def self_login(): + """The login to ignore when selffilter is on. Never reads a token: it asks gh.""" + if not _SELF: + login = (os.environ.get("FIRST_MATE_SELF_LOGIN") or run(["gh", "api", "user", "-q", ".login"])).strip() + if not LOGIN.match(login): + raise RuntimeError("could not determine your GitHub login; set FIRST_MATE_SELF_LOGIN") + _SELF.append(login) + return _SELF[0] + + +def login_of(item, key="author"): + return (item.get(key) or {}).get("login") or "ghost" + + +def collapse_merge_state(raw): + """DIRTY and BEHIND are real; UNKNOWN is None (not known yet); the rest is ok.""" + if raw == "UNKNOWN": + return None + return {"DIRTY": "conflict", "BEHIND": "behind"}.get(raw, "ok") + + +def previous_merge(prev): + """The merge value of the last saved snapshot, in collapsed form (old saves held the raw value).""" + m = re.search(r" merge=(\S+)", prev or "") + if not m: + return "ok" + return m.group(1) if m.group(1) in ("conflict", "behind", "ok") else collapse_merge_state(m.group(1)) or "ok" + + +def stale_reviews(reviews, head): + """Each reviewer's latest approval or change request made on a known head other than `head`.""" + latest = {} + for r in sorted(reviews, key=lambda x: x.get("submittedAt") or ""): + if r.get("state") in GATING: + latest[login_of(r)] = r + return sorted( + f"{who}:{r['state']}@{(r.get('commit') or {}).get('oid', '')[:8]}" + for who, r in latest.items() + if r["state"] != "DISMISSED" and (r.get("commit") or {}).get("oid") not in (None, "", head) + ) + + +def pr_snapshot(repo, num, prev=None, self_filter=False): + for attempt in range(UNKNOWN_RETRIES): + d = gh_json( + [ + "pr", + "view", + str(num), + "--repo", + repo, + "--json", + "headRefOid,isDraft,state,reviewDecision,mergeStateStatus,reviews,comments,statusCheckRollup", + ] + ) + merge = collapse_merge_state(d.get("mergeStateStatus")) + if merge is not None or d.get("state") != "OPEN": + break + if attempt + 1 < UNKNOWN_RETRIES: + time.sleep(UNKNOWN_SLEEP) + if merge is None: + merge = previous_merge(prev) + ignore = self_login() if self_filter else None + inline = len( + [ + who + for who in run( + [ + "gh", + "api", + f"repos/{repo}/pulls/{num}/comments?per_page=100", + "--paginate", + "--jq", + '.[] | (.user.login // "ghost")', + ] + ).splitlines() + if who != ignore + ] + ) ok = bad = pend = 0 bad_names = [] for c in d.get("statusCheckRollup") or []: @@ -166,15 +338,20 @@ def pr_snapshot(repo, num): pend += 1 else: ok += 1 - reviews = sorted( - f"{r['author']['login']}:{r['state']}@{(r.get('commit') or {}).get('oid', '')[:8]}" - for r in d.get("reviews") or []) + head = d["headRefOid"] + shown = [r for r in d.get("reviews") or [] if login_of(r) != ignore] + reviews = sorted(f"{login_of(r)}:{r['state']}@{(r.get('commit') or {}).get('oid', '')[:8]}" for r in shown) + stale = stale_reviews(shown, head) + n_comments = sum(1 for c in d.get("comments") or [] if login_of(c) != ignore) return ( - f"head={d['headRefOid'][:8]} {'draft' if d['isDraft'] else 'ready'} {d['state']} " - f"decision={d.get('reviewDecision') or '-'} merge={d.get('mergeStateStatus')} " + f"head={head[:8]} {'draft' if d['isDraft'] else 'ready'} {d['state']} " + f"decision={d.get('reviewDecision') or '-'} merge={merge} " f"checks ok={ok} fail={bad} pending={pend}" + (f" failing={sorted(bad_names)}" if bad_names else "") - + f" reviews={reviews} comments={len(d.get('comments') or [])} inline={inline}") + + f" reviews={reviews}" + + (f" stale-review={stale}" if stale else "") + + f" comments={n_comments} inline={inline}" + ) def issue_snapshot(repo, num): @@ -193,9 +370,22 @@ def branch_snapshot(repo, branch): def workflow_snapshot(repo, workflow, branch): - rows = gh_json([ - "run", "list", "--repo", repo, "--workflow", workflow, "--branch", branch, - "--limit", "1", "--json", "databaseId,headSha,status,conclusion"]) + rows = gh_json( + [ + "run", + "list", + "--repo", + repo, + "--workflow", + workflow, + "--branch", + branch, + "--limit", + "1", + "--json", + "databaseId,headSha,status,conclusion", + ] + ) if not rows: return "no runs" r = rows[0] @@ -207,9 +397,7 @@ def agents_snapshot(self_id): if self_id: args += ["--label", f"paseo.parent-agent-id={self_id}"] rows = json.loads(run(args)) - items = sorted( - f"{r['shortId']}:{r['status']}:{r.get('name', '')[:36]}" - for r in rows) + items = sorted(f"{r['shortId']}:{r['status']}:{r.get('name', '')[:36]}" for r in rows) return "; ".join(items) or "none" @@ -218,11 +406,13 @@ def permits_snapshot(): return "; ".join(sorted(f"{r['agentShortId']}:{r['id']}" for r in rows)) or "none" -def collect(w): +def collect(w, prev=None): + prev = prev or {} jobs = {} for ref in w["prs"]: repo, n = resolve(w, ref) - jobs[f"pr {short(w, repo)}#{n}"] = (pr_snapshot, repo, n) + key = f"pr {short(w, repo)}#{n}" + jobs[key] = (pr_snapshot, repo, n, prev.get(key), bool(w.get("self_filter"))) for ref in w["issues"]: repo, n = resolve(w, ref) jobs[f"issue {short(w, repo)}#{n}"] = (issue_snapshot, repo, n) @@ -259,10 +449,45 @@ def load_state(): def save_state(s): - tmp = STATE + ".tmp" - with open(tmp, "w") as fh: - json.dump(s, fh, indent=1, sort_keys=True) - os.replace(tmp, STATE) + write_atomic(STATE, json.dumps(s, indent=1, sort_keys=True)) + + +def digest(obj): + return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest() + + +def remove_quietly(path): + with suppress(FileNotFoundError): + os.remove(path) + + +PR_STATE = re.compile(r"^head=\S+ (?:draft|ready) (OPEN|MERGED|CLOSED) ") + + +def finished(kind, snap): + """True for a merged or closed PR, or a closed issue (from its saved snapshot).""" + if kind == "pr": + m = PR_STATE.match(snap or "") + return bool(m) and m.group(1) in ("MERGED", "CLOSED") + return (snap or "").startswith("CLOSED") + + +def prunable(w, snaps): + """Watched PRs and issues whose snapshot says they are finished: [(kind, item, label)].""" + found = [] + for kind, key in (("pr", "prs"), ("issue", "issues")): + for item in w[key]: + snap = snaps.get(f"{kind} {item}") + if snap is not None and finished(kind, snap): + found.append((kind, item, PR_STATE.match(snap).group(1) if kind == "pr" else "CLOSED")) + return found + + +def apply_prune(w, st, found): + for kind, item, _ in found: + key = "prs" if kind == "pr" else "issues" + w[key] = [x for x in w[key] if x != item] + st.pop(f"{kind} {item}", None) def manage(w, argv): @@ -308,53 +533,33 @@ def manage(w, argv): print(f"alias {argv[1]} -> {argv[2]}") elif cmd == "prune": st = load_state() - dropped = [] - for kind, key in (("pr", "prs"), ("issue", "issues")): - keep = [] - for item in w[key]: - snap = st.get(f"{kind} {item}", "") - done = (" MERGED " in f" {snap} " or " CLOSED " in f" {snap} ") if kind == "pr" \ - else snap.startswith("CLOSED") - if done: - dropped.append(f"{kind} {item}") - st.pop(f"{kind} {item}", None) - else: - keep.append(item) - w[key] = keep + found = prunable(w, st) + apply_prune(w, st, found) save_watch(w) save_state(st) - print("pruned: " + (", ".join(dropped) or "nothing")) - elif cmd in ("agents", "permits") and len(argv) == 2 and argv[1] in ("on", "off"): - key = "watch_agents" if cmd == "agents" else "watch_permits" - w[key] = (argv[1] == "on") + print("pruned: " + (", ".join(f"{k} {i}" for k, i, _ in found) or "nothing")) + elif cmd in ("agents", "permits", "autoprune", "selffilter") and len(argv) == 2 and argv[1] in ("on", "off"): + key = { + "agents": "watch_agents", + "permits": "watch_permits", + "autoprune": "autoprune", + "selffilter": "self_filter", + }[cmd] + changed = w.get(key) != (argv[1] == "on") + w[key] = argv[1] == "on" save_watch(w) - print(f"{cmd} watching {'on' if w[key] else 'off'}") + print(f"{cmd} {'on' if w[key] else 'off'}") + if cmd == "selffilter" and changed: + remove_quietly(STATE) + remove_quietly(PENDING) + print("state cleared: the next run is a baseline") else: raise SystemExit(__doc__) -def main(): - argv = sys.argv[1:] - if argv and not argv[0].startswith("--"): - manage(load_watch(), argv) - return - arg = argv[0] if argv else "" - if arg == "--reset": - if os.path.exists(STATE): - os.remove(STATE) - print("state reset") - return - w = load_watch() - new, errors = collect(w) - if arg == "--show": - for k in sorted(new): - print(f"{k}: {new[k]}") - for k in sorted(errors): - print(f"ERROR {k}: {errors[k]}") - return - old = load_state() +def report_lines(old, new, errors, pruned, baseline): lines = [] - if not old: + if baseline: lines.append(f"BASELINE saved ({len(new)} items)") else: for k in sorted(new): @@ -364,9 +569,98 @@ def main(): 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)") - save_state({**old, **new}) + for kind, item, label in pruned: + lines.append(f"PRUNED {kind} {item} ({label}): no longer watched after this report") + return lines + + +def detect(arg): + """One detector pass. Concurrent passes take turns (the report lock), so a change is + never reported twice in one-step mode. The state lock covers only local file work, + never the network calls, so add/remove/--commit are not blocked behind a slow collect.""" + with file_lock(REPORT_LOCKFILE) if arg != "--show" else nullcontext(): + run_detect(arg) + + +def run_detect(arg): + with state_lock(): + w = load_watch() + old = load_state() + baseline = not os.path.exists(STATE) + new, errors = collect(w, old) + if arg == "--show": + for k in sorted(new): + print(f"{k}: {new[k]}") + for k in sorted(errors): + print(f"ERROR {k}: {errors[k]}") + return + if new or not errors: # a pass where every query failed did not complete + write_atomic(LASTRUN, f"{int(time.time())}\n") + found = prunable(w, new) if w.get("autoprune") else [] + lines = report_lines(old, new, errors, found, baseline) if lines: - print("\n".join(lines)) + print("\n".join(lines), flush=True) + pending = { + "base": digest(old), + "txn": os.environ.get("FIRST_MATE_TXN", ""), + "new": new, + "prune": [[k, i] for k, i, _ in found], + } + with state_lock(): + if arg == "--peek": + if lines: + write_atomic(PENDING, json.dumps(pending, sort_keys=True)) + else: + remove_quietly(PENDING) + else: + apply_save(pending) + + +def apply_save(pending): + """Save the fresh snapshots (and prunes) over the saved state. Caller holds the lock.""" + st = {**load_state(), **pending["new"]} + w = load_watch() + apply_prune(w, st, [(k, i, "") for k, i in pending.get("prune", [])]) + save_state(st) + save_watch(w) + + +def commit_pending(): + with state_lock(): + if not os.path.exists(PENDING): + return + try: + with open(PENDING) as fh: + pend = json.load(fh) + except (OSError, ValueError): + remove_quietly(PENDING) + return + txn = os.environ.get("FIRST_MATE_TXN", "") + if pend.get("txn", "") != txn: + return # staged by another run; only that run may commit it + if pend.get("base") == digest(load_state()): + apply_save(pend) + remove_quietly(PENDING) # a stale pending (state moved) is dropped; the next run recomputes + + +def main(): + argv = sys.argv[1:] + if argv and not argv[0].startswith("--"): + with state_lock(): + manage(load_watch(), argv) + return + arg = argv[0] if argv else "" + if arg == "--commit": + commit_pending() + elif arg == "--reset": + with state_lock(): + remove_quietly(STATE) + remove_quietly(PENDING) + print("state reset") + elif arg in ("", "--peek", "--show"): + detect(arg) + else: + raise SystemExit(__doc__) if __name__ == "__main__": 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 59876a7..2adcfde 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 @@ -4,20 +4,35 @@ # as it reports a change, so waiting costs no model tokens. # # Usage: -# first-mate-wait.sh INTERVAL_MIN MAX_MIN start a loop (refuses if one is running) -# first-mate-wait.sh status none | mine | other, with owner, pid, start +# first-mate-wait.sh [INTERVAL_MIN [MAX_MIN]] start a loop (refuses if one is running) +# defaults: 15 and 480 (8 hours) +# first-mate-wait.sh status none | mine | other, with owner, pid, start, +# and the age of the last completed detector run # first-mate-wait.sh stop [--force] stop your loop (--force: another owner's) # first-mate-wait.sh take-over INTERVAL MAX stop any running loop, then start yours # +# The loop exits on purpose when it finds a change, so restart it after every notification: +# run `status` first in every turn, and start a new loop in that same turn if it says none. +# `status` also warns when the last detector run is older than twice the interval (a stuck +# loop or a failing detector looks quiet otherwise). Pair the loop with an hourly heartbeat +# that runs `status` and restarts the loop (see the skill). +# # Exit codes of a start: -# 0 change found; the report is printed (state already saved) -# 3 nothing changed within MAX_MIN (prints nothing) +# 0 change found; the report is printed, then the detector's save is committed +# 3 nothing changed within MAX_MIN (prints one line saying the loop ended at its cap) # 4 a loop is already running and you own it; nothing started # 5 a loop is running and another owner holds it; nothing started # 2 usage or environment error (for example, flock is missing) # Run a start as a BACKGROUND shell command so the harness notifies on completion. # Use INTERVAL 5 while work is actively in flight, 15 when it is quiet. # +# The report is printed BEFORE the detector's two-phase save is committed (--peek, print, +# --commit), so a loop killed in between reports the same change again instead of losing it. +# FIRST_MATE_DIR may be relative; it is resolved to an absolute path. When that directory does +# 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). +# # 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 # dies, including by SIGKILL; there is no pidfile to go stale. Needs flock: util-linux on @@ -25,12 +40,27 @@ set -uo pipefail HERE=$(CDPATH='' cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) -DIR=${FIRST_MATE_DIR:-tmp} +PYTHON=${FIRST_MATE_PYTHON:-python3} +resolve_dir() { + local v=${1#./} + v=${v%/} + case $1 in + /*) printf '%s\n' "$1"; return ;; + esac + if [ ! -d "$PWD/$v" ] && [ "${HERE%/"$v"}" != "$HERE" ] && [ "$(dirname "$HERE")" != / ]; then + printf '%s\n' "$HERE" + else + printf '%s\n' "$PWD/$v" + fi +} +DIR=$(resolve_dir "${FIRST_MATE_DIR:-tmp}") mkdir -p -- "$DIR" || exit 2 DIR=$(CDPATH='' cd -- "$DIR" && pwd) export FIRST_MATE_DIR=$DIR LOCK=$DIR/.wait.lock INFO=$DIR/.wait.owner +LASTRUN=$DIR/.first-mate-lastrun +SECS_PER_MIN=${FIRST_MATE_MINUTE_SECS:-60} ME=${FIRST_MATE_OWNER:-${PASEO_AGENT_ID:-local}} export FIRST_MATE_OWNER=$ME @@ -63,15 +93,57 @@ await_info() { return 1 } +# Seconds since the detector last completed a run, or empty when it never has. +lastrun_age() { + local t + t=$(head -n 1 "$LASTRUN" 2>/dev/null) + case $t in ''|*[!0-9]*) return 0 ;; esac + t=$(( $(date +%s) - t )) + [ "$t" -lt 0 ] && t=0 + echo "$t" +} + +human_age() { + local s=$1 + if [ "$s" -lt 120 ]; then echo "${s}s" + elif [ "$s" -lt 7200 ]; then echo "$(( s / 60 ))m" + else echo "$(( s / 3600 ))h$(( s % 3600 / 60 ))m" + fi +} + +# 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() { - if ! is_running; then echo "none"; return 0; fi - local owner kind + local owner kind age interval line since + age=$(lastrun_age) + if ! is_running; then + echo "none" + [ -n "$age" ] && echo "last-run=$(human_age "$age") ago (no loop is running: start one)" + return 0 + fi await_info - is_running || { echo "none"; return 0; } + if ! is_running; then + echo "none" + return 0 + fi owner=$(info_get owner) + interval=$(info_get interval) if [ "$owner" = "$ME" ]; then kind=mine; else kind=other; fi - echo "$kind owner=${owner:-unknown} pid=$(info_get pid) started=$(info_get started)" \ - "interval=$(info_get interval)m max=$(info_get max)m" + line="$kind owner=${owner:-unknown} pid=$(info_get pid) started=$(info_get started)" + line="$line interval=${interval}m max=$(info_get max)m" + if [ -z "$age" ]; then + echo "$line last-run=never" + else + echo "$line last-run=$(human_age "$age") ago" + # A loop younger than two intervals has not had time to refresh a stale file yet. + since=$(info_get epoch) + since=$(( $(date +%s) - ${since:-0} )) + if [ -n "$interval" ] && [ "$age" -gt $(( interval * 2 * SECS_PER_MIN )) ] \ + && [ "$since" -gt $(( interval * 2 * SECS_PER_MIN )) ]; then + echo "WARNING: the last detector run was $(human_age "$age") ago, more than twice the ${interval}m interval;" \ + "the loop may be stuck or the detector failing. Check with first-mate-check.py --show." + fi + fi } cmd_stop() { @@ -110,7 +182,7 @@ cleanup() { } cmd_start() { - local interval=${1:-15} max=${2:-60} owner out deadline got _ + local interval=${1:-15} max=${2:-480} owner out deadline got rc txn _ case "$interval$max" in *[!0-9]*|'') usage; exit 2 ;; esac exec 9>"$LOCK" # status and stop probe the lock by briefly taking it, so a failed attempt is not @@ -133,28 +205,39 @@ cmd_start() { exit 5 fi # Write then rename, so status and stop never read a half-written owner file. - printf 'owner=%s\npid=%s\nstarted=%s\ninterval=%s\nmax=%s\n' \ - "$ME" "$$" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$interval" "$max" > "$INFO.new" \ + printf 'owner=%s\npid=%s\nstarted=%s\ninterval=%s\nmax=%s\nepoch=%s\n' \ + "$ME" "$$" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$interval" "$max" "$(date +%s)" > "$INFO.new" \ && mv -f -- "$INFO.new" "$INFO" OUTF=$(mktemp "$DIR/.wait.out.XXXXXX") || exit 2 trap cleanup EXIT trap 'exit 143' TERM INT - deadline=$(( $(date +%s) + max * 60 )) + deadline=$(( $(date +%s) + max * SECS_PER_MIN )) while :; do # Children must not inherit the lock fd, or a killed loop would keep the lock. # The detector runs in the background and is waited on, so a stop (SIGTERM) is # handled at once instead of after the detector's network calls finish. - python3 "$HERE/first-mate-check.py" >"$OUTF" 2>&1 9>&- & + # --peek prints and stages the save without consuming anything; the commit below + # runs only after the report is printed. The txn ties the commit to this peek. + 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=$? 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 [ -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 + echo "WARNING: could not save the detector state; the same change will be reported again." >&2 + fi exit 0 fi - [ "$(date +%s)" -ge "$deadline" ] && exit 3 - sleep $(( interval * 60 )) 9>&- & + if [ "$(date +%s)" -ge "$deadline" ]; then + echo "first-mate-wait: loop ended at its ${max}-minute cap with no change; start a new one (status first)." + exit 3 + fi + sleep $(( interval * SECS_PER_MIN )) 9>&- & SLEEP_PID=$! wait "$SLEEP_PID" done diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/cross-pr-checklist.md b/personal/files/home/.agents/skills/paseo-first-mate/references/cross-pr-checklist.md new file mode 100644 index 0000000..8e0b2d1 --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/cross-pr-checklist.md @@ -0,0 +1,15 @@ +# Cross-PR Checklist + +Run this when the watch list grows, before a batch of merges, and whenever a +merge lands that you did not make. Each item is a cheap check that caught a real +problem across many open PRs. + +| Check | How | Why | +|-------|-----|-----| +| Sequence-number collisions | List the next free number claimed by each open branch for anything numbered: decision records, migrations, numbered test files. A short script over `git ls-tree` of each branch works. | Several branches claimed the same number; the loser renames late and breaks review. | +| Shared generated files | List the PRs that edit the same index, generated doc, or relevance list. | They conflict one by one as each merges. Plan the order early. | +| Conflict counts | Recompute with `git merge-tree --write-tree --name-only ` against the long-lived branch. | Counts in an epic go stale. Edit the epic in place and check its body did not change under you before you overwrite it. | +| Stale PR bodies | Re-read the Verification section of each PR after pushes. Update it as the standing grant allows. | The body outlives the head it described. Never tick a human attestation box. | +| Merge queue bounces | If a PR bounces on a test that looks unrelated or racy, ask for a re-run (your token may not be able to) and investigate only if it repeats. | One bounce is often noise. | +| What a merge unblocked | Search your held and blocked items for the one you just merged (SKILL.md section 11). | Blocked work is forgotten unless something prompts it. | +| Unmerged duplicate work | Compare open PRs for overlapping paths. | Another session may have fixed the same problem differently. | diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/delegation-prompt.md b/personal/files/home/.agents/skills/paseo-first-mate/references/delegation-prompt.md new file mode 100644 index 0000000..26347f3 --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/delegation-prompt.md @@ -0,0 +1,57 @@ +# Delegation Prompt Template + +Start every implementation or fix prompt from this list and cut what does not +apply. Each rule below exists because an agent went wrong without it. Pair it +with the completion clause for the delivery level (SKILL.md, section 5). + +## Template + +```text +Task: +Delivery level: +Branch / workspace: . Base: . Push target: . + +Before the first edit: +- Confirm `git merge-base HEAD origin/` equals the base SHA, and that + HEAD equals the remote head you are told to extend. If not, stop and report. + +Rules: +- Plain fast-forward push only. Bring in the base branch with a MERGE, never a + rebase, unless told to. Force-push only when told to, with lease. +- Do not comment on the PR, edit its body, or change draft/ready state. The + coordinator does that. Do not merge. +- Never print, log, or paste a secret value. Never run bare `env`, `printenv`, + `export -p`, `set`, `gh auth token`, or an unfiltered `gh auth status`. +- Never delete files or directories you did not create, including shared + scratch space and other agents' environments. If disk is low, stop and report. +- Reproduce first: show the new test failing on the current code. Then fix. + Then give a mutation proof: revert the fix, see the test fail, restore it, + see it pass. Say what the test does not cover. +- Run focused tests only. Run at most one heavy suite at a time. CI runs the rest. +- No external web search or search-service prompts. Fetching public project + sites (code hosts, package registries) is fine. +- Launch ONE read-only, blocker-only adversarial reviewer subagent over your + diff before pushing. Loop until it reports no blockers. After you apply its + suggestions, run it again, or say that you did not. +- Clean up only scratch you created. Name anything you leave behind. +- If the push is rejected for a credential limit (for example, a workflow file + and a token without that scope), stop. Do not retry. Report the exact error + and a one-line host command (references/host-commands.md). + +Final report (short, no pasted logs): commits (every one, including any made +after you first reported), head SHA, what the tests prove and do not prove, +what you left behind, one exact blocker if any. The coordinator reads the +commits and PR for detail. +``` + +## Notes for the coordinator + +- Quote the reviewer's findings verbatim. A paraphrase drifts. +- Keep one agent per branch. If an agent errors with a transient network error, + re-prompt it ("restart from the top; the worktree is clean") before replacing it. +- Verify claims yourself: heads, CI state, "no conflicts". Agent reports of + "CI started" were stale more than once. +- An agent can make a commit after its final report. Compare the remote head with + the head it reported before you trust either. +- Reasoning level and model follow SKILL.md section 5. Do not copy model names + from old prompts. 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 new file mode 100644 index 0000000..d008421 --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md @@ -0,0 +1,51 @@ +# Coordinator Handoff and Successor + +Use this when the context window is filling (tell the user at about 70% and prepare +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 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, + what never to touch, permission policies, delivery level, agent cap. +- Controls: the old coordinator's agent ID, the loop command (with the absolute + `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. +- A standing-policy line for permission prompts, for example: "external + search-service prompts are denied; fetching public project sites is allowed." + +## Launch the successor + +Create the new coordinator in the same workspace with a prompt that says: read the +skill, read the handoff, run `first-mate-wait.sh status`, then `take-over` +(the user's request for a handoff is their word for it), create your own +heartbeat, delete the old one, and claim the running agents. `notifyOnFinish=false` +is fine for the successor itself. + +## What breaks if you skip a step + +- The loop lock is keyed on the owner ID, so `take-over` is required. It needs the + user's word; their handoff request counts. +- The old heartbeat fires into the old session. A heartbeat belongs to the agent + that created it, so the successor may not be able to delete it. Say so in the + handoff, and have the user or the old coordinator delete it before it retires. +- Agents the old coordinator created carry a `paseo.parent-agent-id` label with + the old ID, so their finish notices go to the old session. The successor can + try `paseo_update_agent` to change the label (untested whether it takes + effect), or poll `paseo_get_agent_status` on each wake-up. The old coordinator + stops acting after the take-over. +- Workspace creation can fail with a git configuration error when a stale local + branch or worktree of the same name exists. Run `git worktree prune`, delete the + stale local branch (only if it matches the remote), and retry. A transient + failure also happened once; a plain retry worked. + +## Successor's first turn + +1. `first-mate-wait.sh status`; take over if it is not yours. +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. diff --git a/personal/files/home/.agents/skills/paseo-first-mate/references/host-commands.md b/personal/files/home/.agents/skills/paseo-first-mate/references/host-commands.md new file mode 100644 index 0000000..58255fb --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/host-commands.md @@ -0,0 +1,88 @@ +# Host Commands, Credential Limits, and Verification Tiers + +Some work needs something the sandbox cannot do: a push the token may not make, +a run on the user's real machine, a platform you do not have. + +## When the token cannot push + +Seen with a token that lacks the scope to push `.github/workflows/*`. The same +shape applies to any push a credential refuses. + +1. The agent commits locally and makes ONE plain push attempt. +2. If it is rejected, the agent stops. No retries, no workarounds. +3. It reports the exact error and one host command: + + ```text + cd && git push origin HEAD: + ``` + +4. The user runs it on their host. +5. The coordinator then reads the remote head and compares it with the reported + commit. Agents sometimes commit after reporting, so the pushed head can differ. + +The same token may be unable to re-run workflows, read branch protection, or use +some GraphQL fields. Say what you could not check rather than guess. A +reviewer request that fails on a GraphQL scope error works through REST: + +```text +gh api -X POST repos/OWNER/REPO/pulls/N/requested_reviewers -f 'reviewers[]=LOGIN' +``` + +and `gh api repos/OWNER/REPO/pulls/N` returns `.requested_reviewers`. When +requesting a re-review, comment first (no recap of the diff), then request it. + +## Files the host must read + +The host cannot see the sandbox's temporary directories. Copy anything the user +must read or run (a PR body, a script) into the worktree, and keep it out of Git +with the worktree's `.git/info/exclude` (use `git rev-parse --git-path info/exclude` +for the path). Then refer to it by a worktree-relative path: + +```text +cd && gh pr create --repo OWNER/REPO --base main --head BRANCH --title "TITLE" --body-file PR-BODY.md +``` + +## Writing a command the user pastes + +- One line, starting with `cd` to the worktree. The user's shell may be anywhere. +- No `#` comments inside the block. An interactive zsh passes `#` through as an + argument. Put expectations in prose outside the block. +- Say what a pass and a fail look like, and which revision it tests. +- Applies equally to instructions you give another agent for a host run. + +## Copy-paste recipe pitfalls + +Found when another agent ran a recipe on a native platform: + +- `git clone -c key=value` does not persist the setting. Use `--config`. +- `git checkout` does not rewrite files whose content is identical between + commits. To force re-materialization: `git rm --cached -r -q . && git reset --hard -q`. +- Global commit signing can break tests that make scratch commits. Disable it per + process with `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=commit.gpgsign GIT_CONFIG_VALUE_0=false`. +- A tool may exist on the host under a name you assumed absent (for example, + `python3`). A "missing tool" test needs a PATH-narrowing recipe that was proved + in the same session. +- Use `timeout --foreground`, show live output, and set a per-step timeout (SKILL.md, + Working With the User). + +## Evidence + +- Tie every result to the exact head SHA it tested. Accept a PASS only for that SHA. + Label an older report "old head, does not carry over". +- `NOT EXERCISED` is a first-class result. Never convert it to PASS. +- Hosted CI is the authority. Local runs are focused checks only. If the sandbox + cannot run a platform (macOS, Windows), say so on each PR. + +## Tiers for risky acceptance + +When the real account is the only account, split the verification: + +| Tier | Where | What | +|------|-------|------| +| 1 | The user's real account | Read-only, preview, help, dry-run, and cancel paths | +| 2 | An isolated account, VM, or CI runner | Anything destructive | + +Record each result under its tier. Do not call a Tier 1 pass proof of a Tier 2 +behavior. When no safe local test bed exists, a hosted runner can be one: a workflow +with `workflow_dispatch` and a `ref` input, run on a hosted runner of the target +platform, inside a refusal guard that makes it exit unless it runs in CI. 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 new file mode 100644 index 0000000..aa9447b --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/stacking.md @@ -0,0 +1,38 @@ +# Stacking Reviewed PRs With gh-stack + +The mechanics (commands, flags, troubleshooting) belong to the `github/gh-stack` +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`. + +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. + +## Procedure that worked + +1. Work in a scratch clone, not the user's worktrees. Set `rerere.enabled true` + and `remote.pushDefault origin` in it. +2. Make each branch contain the one below it with plain merges. Never rebase a + branch that has reviews. +3. `gh stack init --base ` adopts the existing + branches and finds their PRs. +4. `gh stack view --json` should show `needsRebase=false` for each layer. +5. Have a read-only blocker-only reviewer compare each layer's diff with its PR's own + diff (equal patch IDs). +6. Ask the user before `gh stack submit --auto --remote origin`. It pushes + atomically with force-with-lease and retargets PR bases. +7. For a later change: fix the owning layer, merge it into the layers above, then + `gh stack push --remote origin`. + +## Caveats + +- If CI runs only for PRs into the default branch, layers above the bottom show + only the title check until they are retargeted. Retargeting is the user's call. +- A stack needs real ancestry. Two PRs on the same base that conflict with each + other, or that touch separate histories, are not a linear stack. +- Host verification on another platform is easier as one stack-level block run at + 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). 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 new file mode 100644 index 0000000..107c602 --- /dev/null +++ b/personal/files/home/.agents/skills/paseo-first-mate/references/status-doc.md @@ -0,0 +1,64 @@ +# 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/scripts/test-first-mate-detector.py b/personal/scripts/test-first-mate-detector.py new file mode 100644 index 0000000..6e1a40e --- /dev/null +++ b/personal/scripts/test-first-mate-detector.py @@ -0,0 +1,566 @@ +#!/usr/bin/env python3 +"""Offline tests for the First Mate detector (first-mate-check.py) and wait loop (first-mate-wait.sh). + +`gh` and `paseo` are replaced by fake executables on PATH, so nothing here touches the +network, GitHub, or a Paseo daemon. Set FIRST_MATE_ASSETS to test another copy of the +assets (for example the previous release, to see which tests it fails), and +FIRST_MATE_TEST_BASH to run the wait loop under another bash (for example a 3.2 build). + +Usage: personal/scripts/test-first-mate-detector.py +""" + +from __future__ import annotations + +import json +import os +import shutil +import stat +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +from pathlib import Path + +sys.dont_write_bytecode = True + +KIT = Path(__file__).resolve().parents[1] +ASSETS = Path(os.environ.get("FIRST_MATE_ASSETS") or KIT / "files/home/.agents/skills/paseo-first-mate/assets") +BASH = os.environ.get("FIRST_MATE_TEST_BASH", "bash") +SECRET = "sentinel-secret-value-7f3a" # noqa: S105 -- fake value used to prove it is never printed + +FAKE_GH = """#!{python} +import json, os, re, sys, time +d = os.environ["FAKE_GH_DIR"] +args = sys.argv[1:] +with open(os.path.join(d, "calls.log"), "a") as fh: + fh.write(" ".join(args) + "\\n") +time.sleep(float(os.environ.get("FAKE_GH_DELAY", "0"))) + + +def load(name, default=None): + path = os.path.join(d, name) + if not os.path.exists(path): + if default is None: + sys.stderr.write("fake gh: no fixture " + name + "\\n") + sys.exit(1) + return default + with open(path) as fh: + return json.load(fh) + + +def counter(name): + path = os.path.join(d, name) + n = int(open(path).read()) if os.path.exists(path) else 0 + with open(path, "w") as fh: + fh.write(str(n + 1)) + return n + + +if args[:2] == ["pr", "view"]: + num = args[2] + data = load("pr-%s.json" % num) + seq = load("pr-%s.merge-seq.json" % num, []) + if seq: + data["mergeStateStatus"] = seq[min(counter("pr-%s.merge-idx" % num), len(seq) - 1)] + print(json.dumps(data)) +elif args[:1] == ["api"] and args[1] == "user": + print(load("login.json", "me")) +elif args[:1] == ["api"] and re.match(r"repos/[^/]+/[^/]+/pulls/(\\d+)/comments", args[1]): + num = re.match(r"repos/[^/]+/[^/]+/pulls/(\\d+)/comments", args[1]).group(1) + logins = load("inline-%s.json" % num, []) + jq = args[args.index("--jq") + 1] + if jq == "length": + print(len(logins)) + elif logins: + print("\\n".join(logins)) +elif args[:1] == ["api"] and re.match(r"repos/[^/]+/[^/]+/commits/", args[1]): + print(json.dumps(load("branch-" + args[1].rsplit("/", 1)[1] + ".json"))) +else: + sys.stderr.write("fake gh: unsupported call: " + " ".join(args) + "\\n") + sys.exit(1) +""" + +FAKE_PASEO = """#!/bin/sh +echo "paseo called: $*" >> "$FAKE_GH_DIR/calls.log" +echo "fake paseo: not available" >&2 +exit 1 +""" + + +def pr(head="aaaaaaaa11111111", state="OPEN", merge="CLEAN", reviews=(), comments=(), draft=False, decision=None): + return { + "headRefOid": head, + "isDraft": draft, + "state": state, + "reviewDecision": decision, + "mergeStateStatus": merge, + "reviews": [ + { + "author": None if who is None else {"login": who}, + "state": st, + "commit": {"oid": oid}, + "submittedAt": f"2026-01-01T00:00:{i:02d}Z", + } + for i, (who, st, oid) in enumerate(reviews) + ], + "comments": [{"author": None if who is None else {"login": who}} for who in comments], + "statusCheckRollup": [], + } + + +class Env: + def __init__(self, root: Path, assets: Path = ASSETS): + self.root = root + self.fake = root / "fake" + self.bin = root / "bin" + self.state = root / "state" + self.tools = root / "tools" + for path in (self.fake, self.bin, self.state, self.tools): + path.mkdir() + gh = self.bin / "gh" + gh.write_text(FAKE_GH.format(python=sys.executable)) + paseo = self.bin / "paseo" + paseo.write_text(FAKE_PASEO) + for exe in (gh, paseo): + exe.chmod(exe.stat().st_mode | stat.S_IXUSR) + for name in ("first-mate-check.py", "first-mate-wait.sh"): + shutil.copy2(assets / name, self.tools / name) + self.check = self.tools / "first-mate-check.py" + self.wait = self.tools / "first-mate-wait.sh" + self.extra_env: dict[str, str] = {} + + def env(self, **more): + env = {k: v for k, v in os.environ.items() if not k.startswith(("FIRST_MATE", "PASEO_", "GITHUB_", "GH_"))} + env.update( + PATH=f"{self.bin}{os.pathsep}{os.environ['PATH']}", + HOME=str(self.root), + FAKE_GH_DIR=str(self.fake), + FIRST_MATE_DIR=str(self.state), + FIRST_MATE_UNKNOWN_SLEEP="0", + FIRST_MATE_SELF_LOGIN="", + GITHUB_TOKEN=SECRET, + ) + env.update(self.extra_env) + env.update(more) + return env + + def put(self, name, data): + (self.fake / name).write_text(json.dumps(data)) + + def set_pr(self, num, **fields): + self.put(f"pr-{num}.json", pr(**fields)) + + def det(self, *args, cwd=None, **more): + return subprocess.run( # noqa: S603 -- fixed local script and synthetic fixtures + [sys.executable, str(self.check), *args], + capture_output=True, + text=True, + env=self.env(**more), + cwd=cwd, + timeout=60, + check=False, + ) + + def sh(self, *args, **more): + return subprocess.run( # noqa: S603 -- fixed local script and synthetic fixtures + [BASH, str(self.wait), *args], # noqa: S607 + capture_output=True, + text=True, + env=self.env(**more), + timeout=60, + check=False, + ) + + def setup_pr(self, num=1, **fields): + self.set_pr(num, **fields) + self.det("repo", "r", "o/r") + self.det("add", "pr", f"r#{num}") + + def baseline(self): + out = self.det("--peek") + self.det("--commit") + return out + + def calls(self): + path = self.fake / "calls.log" + return path.read_text() if path.exists() else "" + + def state_json(self): + return json.loads((self.state / ".first-mate-state.json").read_text()) + + def watch_json(self): + return json.loads((self.state / "first-mate-watch.json").read_text()) + + +class DetectorCase(unittest.TestCase): + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.e = Env(Path(self._tmp.name)) + + +class TwoPhaseSaveTests(DetectorCase): + def test_repeat_peek_is_identical(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, head="bbbbbbbb22222222") + first, second = self.e.det("--peek"), self.e.det("--peek") + self.assertIn("CHANGED pr r#1", first.stdout) + self.assertEqual(first.stdout, second.stdout) + + def test_peek_without_commit_consumes_nothing(self): + self.e.setup_pr() + self.e.baseline() + before = (self.e.state / ".first-mate-state.json").read_text() + self.e.set_pr(1, comments=["alice"]) + self.assertIn("comments=1", self.e.det("--peek").stdout) + self.assertEqual((self.e.state / ".first-mate-state.json").read_text(), before) + self.assertIn("comments=1", self.e.det("--peek").stdout) + + def test_commit_consumes_the_reported_change(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + self.assertIn("CHANGED", self.e.det("--peek").stdout) + self.e.det("--commit") + self.assertEqual(self.e.det("--peek").stdout, "") + + def test_state_moved_between_peek_and_commit_drops_the_commit(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + self.e.det("--peek") + self.e.det("remove", "pr", "r#1") + self.e.det("--commit") + self.assertNotIn("pr r#1", self.e.state_json()) + self.assertFalse((self.e.state / ".first-mate-pending.json").exists()) + + def test_commit_only_applies_its_own_peek(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + self.e.det("--peek", FIRST_MATE_TXN="loop-a") + self.e.det("--commit", FIRST_MATE_TXN="loop-b") + self.assertIn("CHANGED", self.e.det("--peek", FIRST_MATE_TXN="loop-c").stdout) + self.e.det("--peek", FIRST_MATE_TXN="loop-a") + self.e.det("--commit", FIRST_MATE_TXN="loop-a") + self.assertEqual(self.e.det("--peek").stdout, "") + + def test_one_step_run_reports_once_under_concurrency(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + procs = [ + subprocess.Popen( # noqa: S603 -- fixed local script and synthetic fixtures + [sys.executable, str(self.e.check)], + stdout=subprocess.PIPE, + text=True, + env=self.e.env(FAKE_GH_DELAY="0.4"), + ) + for _ in range(2) + ] + outputs = [p.communicate(timeout=60)[0] for p in procs] + self.assertEqual(sum("CHANGED" in out for out in outputs), 1, outputs) + + def test_reset_forgets_pending_too(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + self.e.det("--peek") + self.e.det("--reset") + self.assertIn("BASELINE", self.e.det("--peek").stdout) + self.e.det("--commit") + self.assertEqual(self.e.det("--peek").stdout, "") + + +class LoginFilterTests(DetectorCase): + def test_own_comments_wake_the_loop_by_default(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["me"]) + self.assertIn("comments=1", self.e.det("--peek", FIRST_MATE_SELF_LOGIN="me").stdout) + + def test_selffilter_on_ignores_own_comments_and_reviews(self): + self.e.setup_pr() + self.assertIn("selffilter on", self.e.det("selffilter", "on").stdout) + self.e.baseline() + self.e.set_pr(1, comments=["me"], reviews=[("me", "COMMENTED", "aaaaaaaa11111111")]) + self.e.put("inline-1.json", ["me"]) + self.assertEqual(self.e.det("--peek", FIRST_MATE_SELF_LOGIN="me").stdout, "") + self.e.set_pr(1, comments=["me", "alice"]) + self.assertIn("comments=1", self.e.det("--peek", FIRST_MATE_SELF_LOGIN="me").stdout) + + def test_selffilter_asks_gh_for_the_login_when_unset(self): + self.e.setup_pr() + self.e.det("selffilter", "on") + self.e.put("login.json", "mate") + self.e.baseline() + self.assertIn("api user", self.e.calls()) + + def test_a_deleted_account_does_not_crash_the_detector(self): + self.e.setup_pr(reviews=[(None, "COMMENTED", "aaaaaaaa11111111")], comments=[None]) + out = self.e.det("--show") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("ghost:COMMENTED", out.stdout) + + +class MergeStateTests(DetectorCase): + def test_flicker_between_blocked_clean_and_unstable_is_not_a_change(self): + self.e.setup_pr(merge="CLEAN") + self.e.baseline() + for flicker in ("BLOCKED", "UNSTABLE", "HAS_HOOKS", "CLEAN"): + self.e.set_pr(1, merge=flicker) + self.assertEqual(self.e.det("--peek").stdout, "", flicker) + + def test_conflict_and_behind_are_reported(self): + self.e.setup_pr(merge="CLEAN") + self.e.baseline() + self.e.set_pr(1, merge="DIRTY") + self.assertIn("merge=conflict", self.e.det("--peek").stdout) + self.e.det("--commit") + self.e.set_pr(1, merge="BEHIND") + self.assertIn("merge=behind", self.e.det("--peek").stdout) + + def test_unknown_is_requeried_until_it_settles(self): + self.e.setup_pr(merge="CLEAN") + self.e.baseline() + self.e.put("pr-1.merge-seq.json", ["UNKNOWN", "UNKNOWN", "CLEAN"]) + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertEqual(self.e.calls().count("pr view 1"), 4) + + def test_unknown_that_never_settles_keeps_the_previous_value(self): + self.e.setup_pr(merge="DIRTY") + self.e.baseline() + self.e.put("pr-1.merge-seq.json", ["UNKNOWN"]) + self.assertEqual(self.e.det("--peek").stdout, "") + self.assertIn("merge=conflict", self.e.state_json()["pr r#1"]) + + +class PruneTests(DetectorCase): + def merged(self): + self.e.set_pr(1, state="MERGED") + + def test_merged_pr_is_reported_and_pruned_on_commit(self): + self.e.setup_pr() + self.e.baseline() + self.merged() + out = self.e.det("--peek").stdout + self.assertIn("MERGED", out) + self.assertIn("PRUNED pr r#1", out) + self.assertEqual(self.e.watch_json()["prs"], ["r#1"], "peek must not change the watch list") + self.e.det("--commit") + self.assertEqual(self.e.watch_json()["prs"], []) + self.assertNotIn("pr r#1", self.e.state_json()) + + def test_autoprune_off_keeps_the_pr(self): + self.e.setup_pr() + self.e.det("autoprune", "off") + self.e.baseline() + self.merged() + self.assertNotIn("PRUNED", self.e.det("--peek").stdout) + self.e.det("--commit") + self.assertEqual(self.e.watch_json()["prs"], ["r#1"]) + + def test_manual_prune_still_works(self): + self.e.setup_pr() + self.e.det("autoprune", "off") + self.e.baseline() + self.merged() + self.e.det("--peek") + self.e.det("--commit") + self.assertIn("pruned: pr r#1", self.e.det("prune").stdout) + + def test_open_pr_whose_title_says_closed_is_not_pruned(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, state="OPEN", reviews=[("CLOSED", "COMMENTED", "aaaaaaaa11111111")]) + self.e.det("--peek") + self.e.det("--commit") + self.assertEqual(self.e.watch_json()["prs"], ["r#1"]) + + +class ReportContentTests(DetectorCase): + def test_current_head_is_shown(self): + self.e.setup_pr(head="c0ffee00deadbeef") + self.assertIn("head=c0ffee00", self.e.det("--show").stdout) + + def test_review_of_an_older_head_is_marked_stale(self): + self.e.setup_pr( + head="bbbbbbbb22222222", + reviews=[("wz", "CHANGES_REQUESTED", "aaaaaaaa11111111")], + decision="CHANGES_REQUESTED", + ) + self.assertIn("stale-review=['wz:CHANGES_REQUESTED@aaaaaaaa']", self.e.det("--show").stdout) + + def test_review_of_the_current_head_is_not_stale(self): + self.e.setup_pr(head="aaaaaaaa11111111", reviews=[("wz", "APPROVED", "aaaaaaaa11111111")]) + self.assertNotIn("stale-review", self.e.det("--show").stdout) + + def test_a_later_review_on_the_current_head_supersedes_an_old_one(self): + self.e.setup_pr( + head="bbbbbbbb22222222", + reviews=[("wz", "CHANGES_REQUESTED", "aaaaaaaa11111111"), ("wz", "APPROVED", "bbbbbbbb22222222")], + ) + self.assertNotIn("stale-review", self.e.det("--show").stdout) + + def test_a_new_head_that_leaves_a_review_behind_is_reported(self): + self.e.setup_pr(head="aaaaaaaa11111111", reviews=[("wz", "APPROVED", "aaaaaaaa11111111")]) + self.e.baseline() + self.e.set_pr(1, head="bbbbbbbb22222222", reviews=[("wz", "APPROVED", "aaaaaaaa11111111")]) + out = self.e.det("--peek").stdout + self.assertIn("head=bbbbbbbb", out) + self.assertIn("stale-review", out) + + +class PathTests(DetectorCase): + def test_running_from_inside_the_state_dir_does_not_nest_it(self): + work = self.e.root / "work" + tmp = work / "tmp" + tmp.mkdir(parents=True) + for name in ("first-mate-check.py", "first-mate-wait.sh"): + shutil.copy2(self.e.tools / name, tmp / name) + env = {"FIRST_MATE_DIR": "tmp"} + out = subprocess.run( # noqa: S603 -- fixed local script + [sys.executable, str(tmp / "first-mate-check.py"), "repo", "r", "o/r"], + capture_output=True, + text=True, + env=self.e.env(**env), + cwd=tmp, + timeout=60, + check=False, + ) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertTrue((tmp / "first-mate-watch.json").exists()) + self.assertFalse((tmp / "tmp").exists(), "stray tmp/tmp was created") + + def test_relative_dir_from_the_repo_root_uses_that_root(self): + work = self.e.root / "repo" + (work / "tmp").mkdir(parents=True) + shutil.copy2(self.e.check, work / "tmp" / "first-mate-check.py") + out = subprocess.run( # noqa: S603 -- fixed local script + [sys.executable, str(work / "tmp" / "first-mate-check.py"), "repo", "r", "o/r"], + capture_output=True, + text=True, + env=self.e.env(FIRST_MATE_DIR="tmp"), + cwd=work, + timeout=60, + check=False, + ) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertTrue((work / "tmp" / "first-mate-watch.json").exists()) + self.assertFalse((work / "tmp" / "tmp").exists()) + + +class SecretTests(DetectorCase): + def test_no_secret_is_printed_and_no_token_command_runs(self): + self.e.setup_pr(reviews=[("wz", "APPROVED", "aaaaaaaa11111111")]) + self.e.det("selffilter", "on", FIRST_MATE_SELF_LOGIN="me") + outputs = [self.e.det("--peek"), self.e.det("--commit"), self.e.det("--show"), self.e.det("list")] + outputs.append(self.e.sh("status")) + for out in outputs: + self.assertNotIn(SECRET, out.stdout + out.stderr) + calls = self.e.calls() + for forbidden in ("auth", "token", "hosts.yml"): + self.assertNotIn(forbidden, calls) + self.assertNotIn("paseo called", calls) + for name in ("first-mate-check.py", "first-mate-wait.sh"): + text = (ASSETS / name).read_text() + self.assertNotRegex(text, r"gh auth|printenv|export -p|GITHUB_TOKEN|USAI_API_KEY") + + +@unittest.skipUnless(shutil.which("flock"), "flock not installed") +class WaitLoopTests(DetectorCase): + def test_cap_expiry_prints_one_line_and_exits_3(self): + self.e.setup_pr() + self.e.baseline() + out = self.e.sh("1", "0") + self.assertEqual(out.returncode, 3, out.stderr) + lines = out.stdout.strip().splitlines() + self.assertEqual(len(lines), 1, out.stdout) + self.assertIn("cap", lines[0]) + + def test_change_prints_the_report_then_commits_it(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + out = self.e.sh("1", "5") + self.assertEqual(out.returncode, 0, out.stderr) + self.assertIn("CHANGED pr r#1", out.stdout) + self.assertEqual(self.e.det("--peek").stdout, "", "the loop's report must have been committed") + + def test_a_loop_killed_before_commit_loses_nothing(self): + self.e.setup_pr() + self.e.baseline() + self.e.set_pr(1, comments=["alice"]) + self.e.det("--peek", FIRST_MATE_TXN="dead-loop") + self.assertIn("CHANGED", self.e.sh("1", "5").stdout) + + def test_status_reports_the_age_of_the_last_run(self): + self.e.setup_pr() + self.e.baseline() + self.e.sh("1", "0") + out = self.e.sh("status").stdout + self.assertTrue(out.startswith("none"), out) + self.assertRegex(out, r"last-run=\d+s ago") + + def test_status_warns_when_the_last_run_is_older_than_twice_the_interval(self): + self.e.setup_pr() + self.e.baseline() + stale = int(time.time()) - 3 * 3600 + (self.e.state / ".first-mate-lastrun").write_text(f"{stale}\n") + # FIRST_MATE_MINUTE_SECS=1 makes the loop's "minute" one second, so a 1-minute + # interval means the warning threshold is 2 seconds, and a detector stuck on a slow + # gh never refreshes the file. + loop = subprocess.Popen( # noqa: S603 -- fixed local script + [BASH, str(self.e.wait), "1", "30"], # noqa: S607 + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + env=self.e.env(FIRST_MATE_OWNER="alice", FAKE_GH_DELAY="30", FIRST_MATE_MINUTE_SECS="1"), + ) + try: + out = "" + for _ in range(60): + out = self.e.sh("status", FIRST_MATE_OWNER="alice", FIRST_MATE_MINUTE_SECS="1").stdout + if out.startswith("mine"): + break + time.sleep(0.2) + self.assertTrue(out.startswith("mine"), out) + self.assertIn("last-run=3h", out) + self.assertNotIn("WARNING", out, "a loop younger than two intervals must not warn yet") + time.sleep(3.5) + out = self.e.sh("status", FIRST_MATE_OWNER="alice", FIRST_MATE_MINUTE_SECS="1").stdout + self.assertIn("WARNING", out) + finally: + self.e.sh("stop", "--force", FIRST_MATE_OWNER="alice") + loop.wait(timeout=30) + + def test_default_cap_is_long_enough_for_a_long_session(self): + text = self.e.wait.read_text() + self.assertRegex(text, r"max=\$\{2:-(\d+)\}") + cap = int(__import__("re").search(r"max=\$\{2:-(\d+)\}", text).group(1)) + self.assertGreaterEqual(cap, 480) + + def test_relative_state_dir_is_not_nested(self): + work = self.e.root / "work" + tmp = work / "tmp" + tmp.mkdir(parents=True) + for name in ("first-mate-check.py", "first-mate-wait.sh"): + shutil.copy2(self.e.tools / name, tmp / name) + out = subprocess.run( # noqa: S603 -- fixed local script + [BASH, str(tmp / "first-mate-wait.sh"), "status"], # noqa: S607 + capture_output=True, + text=True, + env=self.e.env(FIRST_MATE_DIR="tmp"), + cwd=tmp, + timeout=60, + check=False, + ) + self.assertEqual(out.stdout.split()[0], "none", out.stdout + out.stderr) + self.assertFalse((tmp / "tmp").exists(), "stray tmp/tmp was created") + + +if __name__ == "__main__": + print(textwrap.dedent(f" assets under test: {ASSETS}")) + unittest.main(verbosity=2) diff --git a/personal/scripts/test-wait-lock b/personal/scripts/test-wait-lock index cc1f2cb..efbc84d 100755 --- a/personal/scripts/test-wait-lock +++ b/personal/scripts/test-wait-lock @@ -156,10 +156,11 @@ check "report is printed" "CHANGED stub" "$out" check "lock released on exit" "none" "$(as alice status)" rm -f "$FIRST_MATE_DIR/change" -echo "the cap exits 3 and prints nothing" +echo "the cap exits 3 and says so in one line" out="$(as alice 1 0 2>&1)"; rc=$? check "exit 3 at the cap" "3" "$rc" -check "nothing printed" "" "$out" +check "one line printed" "1" "$(printf '%s\n' "$out" | wc -l | tr -d ' ')" +case "$out" in *"ended at its 0-minute cap"*) check "the line names the cap" "yes" "yes" ;; *) check "the line names the cap" "yes" "$out" ;; esac printf '\n %d passed, %d failed\n' "$pass" "$fail" [ "$fail" -eq 0 ] diff --git a/personal/scripts/verify b/personal/scripts/verify index 3bba724..cfde1d0 100755 --- a/personal/scripts/verify +++ b/personal/scripts/verify @@ -330,6 +330,20 @@ else skip "flock not installed (wait-loop locking test not run)" fi +info "4c. Detector behaviour (fake gh and paseo, offline)" +# Two-phase save, own-login filter, merge-state collapse, auto-prune, status age, cap +# message, and the stray tmp/tmp case. gh and paseo are fake executables on PATH. +if command -v "$PYTHON_BIN" >/dev/null 2>&1 && command -v flock >/dev/null 2>&1; then + if "$PYTHON_BIN" "$KIT_DIR/scripts/test-first-mate-detector.py" >"$WORK/detector.log" 2>&1; then + ok "first-mate-check.py and first-mate-wait.sh behaviour tests pass ($(grep -c ' ok$' "$WORK/detector.log") tests)" + else + bad "first-mate detector behaviour tests failed" + sed 's/^/ | /' "$WORK/detector.log" >&2 + fi +else + skip "$PYTHON_BIN or flock not installed (detector behaviour test not run)" +fi + info "5. Shipped detector has no baked-in watch targets" # `list` prints the watch list without calling GitHub or Paseo. It must come # back with no PRs, issues, or releases, so nothing is hard-coded to a repo. diff --git a/personal/spec.yaml b/personal/spec.yaml index 07ee733..de0e34c 100644 --- a/personal/spec.yaml +++ b/personal/spec.yaml @@ -54,10 +54,34 @@ files: mode: "0644" source: files/home/.agents/skills/paseo-first-mate/SKILL.md description: The paseo-first-mate skill instructions + - path: /home/agent/.agents/skills/paseo-first-mate/references/cross-pr-checklist.md + mode: "0644" + source: files/home/.agents/skills/paseo-first-mate/references/cross-pr-checklist.md + description: Periodic cross-PR checks for the coordinator + - path: /home/agent/.agents/skills/paseo-first-mate/references/delegation-prompt.md + mode: "0644" + source: files/home/.agents/skills/paseo-first-mate/references/delegation-prompt.md + description: Rules and template for delegation prompts + - path: /home/agent/.agents/skills/paseo-first-mate/references/handoff-and-successor.md + mode: "0644" + source: files/home/.agents/skills/paseo-first-mate/references/handoff-and-successor.md + description: Handing the effort to a new coordinator + - path: /home/agent/.agents/skills/paseo-first-mate/references/host-commands.md + mode: "0644" + source: files/home/.agents/skills/paseo-first-mate/references/host-commands.md + description: Credential limits, host commands, evidence, and verification tiers + - path: /home/agent/.agents/skills/paseo-first-mate/references/stacking.md + 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 + mode: "0644" + source: files/home/.agents/skills/paseo-first-mate/references/status-doc.md + description: The maintained status doc 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 - description: Change detector for watched PRs, issues, releases, agents, and permissions + description: Change detector for watched PRs, issues, releases, branches, and workflows (two-phase save) - path: /home/agent/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh mode: "0755" source: files/home/.agents/skills/paseo-first-mate/assets/first-mate-wait.sh