From c802715e3f94d0ee84c04009fa954b4a64a9ddb4 Mon Sep 17 00:00:00 2001 From: Vladimir Bragin Date: Sat, 28 Nov 2026 19:57:26 -0600 Subject: [PATCH 1/2] docs(skills): stacked-PR merges, guard and fallback tests, MSYS free-text rewrites Lessons from a session that merged stacked PRs and added input guards: - ship-pr, merge-pr: before merging, look for open PRs based on this head. Deleting their base branch closes them instead of retargeting, and a squash merge leaves each child conflicting. Merge without --delete-branch, retarget, then delete. After a squash, merge the base into the child, check the tree against the reviewed head, and gate again. - test-driven-development: refusal tests pass just as well on an argument error. Pair each refusal with the override, and run them once with the guard disabled. With fallbacks, a pass proves only the branch that ran. - windows-agent-tooling: MSYS also rewrites free text that starts with / (ticket text, commit messages). Co-Authored-By: Claude Opus 5.5 --- .agent/SKILL_INVENTORY.md | 10 +++++----- .agents/skills/merge-pr/SKILL.md | 11 +++++++++++ .agents/skills/ship-pr/SKILL.md | 11 +++++++++++ .agents/skills/test-driven-development/SKILL.md | 8 ++++++++ .agents/skills/windows-agent-tooling/SKILL.md | 3 +++ .claude/skills/merge-pr/SKILL.md | 11 +++++++++++ .claude/skills/ship-pr/SKILL.md | 11 +++++++++++ .claude/skills/test-driven-development/SKILL.md | 8 ++++++++ .claude/skills/windows-agent-tooling/SKILL.md | 3 +++ .cursor/skills/merge-pr/SKILL.md | 11 +++++++++++ .cursor/skills/ship-pr/SKILL.md | 11 +++++++++++ .cursor/skills/test-driven-development/SKILL.md | 8 ++++++++ .cursor/skills/windows-agent-tooling/SKILL.md | 3 +++ 13 files changed, 104 insertions(+), 5 deletions(-) diff --git a/.agent/SKILL_INVENTORY.md b/.agent/SKILL_INVENTORY.md index 80edd0e..8995449 100644 --- a/.agent/SKILL_INVENTORY.md +++ b/.agent/SKILL_INVENTORY.md @@ -1,6 +1,6 @@ # Skill inventory — ${PROJECT_NAME} -**Last reviewed:** 2026-11-28. Companion to [SKILL_CHANGE_AST10_REVIEW.md](SKILL_CHANGE_AST10_REVIEW.md) +**Last reviewed:** 2026-11-29. Companion to [SKILL_CHANGE_AST10_REVIEW.md](SKILL_CHANGE_AST10_REVIEW.md) and [SKILL_COMPILATION.md](SKILL_COMPILATION.md). Update this file (new row or **Last reviewed** date) in the same PR as any skill change. @@ -39,7 +39,7 @@ commands or edit code/config as part of its procedure. | skill-authoring | Create and improve first-party skills with progressive disclosure and eval guidance | L2 | 2026-11-09 | | subagent-review | Review-only external CLI orchestration and structured lightweight decisions (`swarm_decide`) via MCP | L1 | 2026-10-25 | | systematic-debugging | Evidence-first root-cause debugging with reproduce/minimise/hypothesis/regression loop | L2 | 2026-07-14 | -| test-driven-development | Red-green-refactor workflow for behavior changes with practical test seams | L2 | 2026-07-14 | +| test-driven-development | Red-green-refactor workflow for behavior changes with practical test seams | L2 | 2026-11-29 | | rust-testing | Cargo/nextest unit tests beside modules | L2 | 2026-08-14 | | threat-modeling-agentic-tools | Threat-model MCP/tool abuse and injection | L1 | 2026-07-01 | | use-jev | Delegate pending decisions, blocked steps and triage items to Jev in one batched call; act on confident low-risk picks, hand back the rest | L2 | 2026-11-09 | @@ -50,8 +50,8 @@ commands or edit code/config as part of its procedure. | remote-build | Build on a paired build PC over SSH: resolve the host by hostname, pre-flight it (no other heavy build, RAM, disk, clean checkout fast-forwarded to the exact commit), start the build detached with a done-file, verify artifacts (commit, size, SHA-256, version), copy them into a same-commit checkout on each target with a hash read-back, and run each target's project install only after the user approves that PC. User-typed only | L2 | 2026-11-27 | | fix-it | Fix the one problem the latest report named: diagnose read-only, back up before overwriting, smallest reversible fix, verify what the user sees, report with an undo path. Triggered by /fix-it or "fix it" after a report | L2 | 2026-11-21 | | step-back | Recover the ticket's goal, criteria and scope, review the diff against them in both directions, re-plan via next-steps | L2 | 2026-11-19 | -| ship-pr | Take one PR from open to merged: fix CI failures at the root cause, wait for green on the exact head commit, merge, verify. User-typed only; `--no-ci` gates locally when CI exists but can't run; remedies for workflows that never ran and repository-setting failures | L2 | 2026-11-28 | -| merge-pr | Merge one PR without fixing anything: CI already green on the exact head commit; Actions could not start (billing, spending limit, minutes), with the workflow steps replayed locally; a mix of the two; or no CI at all, with the declared checks run locally. Merge pinned to the head commit. User-typed only | L2 | 2026-11-21 | +| ship-pr | Take one PR from open to merged: fix CI failures at the root cause, wait for green on the exact head commit, merge, verify. User-typed only; `--no-ci` gates locally when CI exists but can't run; remedies for workflows that never ran and repository-setting failures | L2 | 2026-11-29 | +| merge-pr | Merge one PR without fixing anything: CI already green on the exact head commit; Actions could not start (billing, spending limit, minutes), with the workflow steps replayed locally; a mix of the two; or no CI at all, with the declared checks run locally. Merge pinned to the head commit. User-typed only | L2 | 2026-11-29 | | validate-implementation | Per-AC Verified/Failed/Unknown verdicts with evidence (**compiled harness**) | L2 | 2026-07-19 | | verification-before-completion | Evidence-backed completion claims with fresh command proof (**compiled harness**) | L1 | 2026-11-04 | @@ -71,7 +71,7 @@ commands or edit code/config as part of its procedure. | lint-format-security | ruff, eslint, clippy, trivy, shellcheck (**compiled harness**) | L2 | 2026-08-14 | | mcp-code-intelligence | MCP tiers; fff, Graphify, Serena, Zoekt, embeddings | L2 | 2026-07-21 | | graphify-knowledge-graph | Query/refresh Graphify MCP or CLI for architecture paths and communities | L2 | 2026-07-21 | -| windows-agent-tooling | Native Windows agent workflows; CLI resolution, persistence and host-context diagnostics; launching CLIs as applications in scripts; PowerShell 5.1 module path | L2 | 2026-11-28 | +| windows-agent-tooling | Native Windows agent workflows; CLI resolution, persistence and host-context diagnostics; launching CLIs as applications in scripts; PowerShell 5.1 module path | L2 | 2026-11-29 | | wsl2-agent-tooling | WSL2 build/test/MCP workflows | L2 | 2026-07-03 | ### Consolidated reusable setup library diff --git a/.agents/skills/merge-pr/SKILL.md b/.agents/skills/merge-pr/SKILL.md index 0bdefd6..cf788d7 100644 --- a/.agents/skills/merge-pr/SKILL.md +++ b/.agents/skills/merge-pr/SKILL.md @@ -209,6 +209,17 @@ Immediately before merging, re-read the PR and confirm: Use the merge method the repository's recent PRs used, pinned to the checked commit: +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` diff --git a/.agents/skills/ship-pr/SKILL.md b/.agents/skills/ship-pr/SKILL.md index 25d5661..05a08e3 100644 --- a/.agents/skills/ship-pr/SKILL.md +++ b/.agents/skills/ship-pr/SKILL.md @@ -156,6 +156,17 @@ Merging is the last step. Immediately before it, re-read the PR and confirm all - the PR is mergeable with no conflicts, and no review has changed; - no new commits arrived. +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + Use the merge method the repository's recent PRs used, and pin the commit so nothing newer can slip in: ```bash diff --git a/.agents/skills/test-driven-development/SKILL.md b/.agents/skills/test-driven-development/SKILL.md index 6c57a91..033e617 100644 --- a/.agents/skills/test-driven-development/SKILL.md +++ b/.agents/skills/test-driven-development/SKILL.md @@ -46,6 +46,12 @@ repo has no practical test seam. State the limitation and choose the closest ver writes, so broken code fails before it touches anything. Keep fixtures where a wrong path can't reach real state: temp folders often sit under the real home folder. Afterwards, check that the RED run left nothing outside the fixture. + For a guard, refusal or permission check, a refusal test passes just as well on an argument error. + Pair each refused call with the same call plus the override and assert it gets past the guard, then + run the refusal tests once with the guard disabled: they must fail because the action happened. + When the code has fallbacks (capture methods, retries, provider chains), a pass proves only the + branch that ran. Assert or log which branch ran, force each one you claim works, or say which ones + stayed unverified. 4. **GREEN — implement the minimum.** Write only enough production code to pass. Do not add unrequested options, abstractions, cleanup, or drive-by edits. If the test is hard to write, treat that as design feedback and improve the seam. @@ -112,6 +118,8 @@ Avoid tests that: - [ ] New behavior has a focused test. - [ ] The test failed for the intended reason before implementation. +- [ ] Guard or refusal tests also fail with the guard disabled, and the override path passes the guard. +- [ ] For code with fallbacks, each branch claimed as working was the one that ran in some test. - [ ] Production code is the minimal change needed to pass. - [ ] Targeted and relevant broader tests pass. - [ ] No test was weakened to fit the implementation. diff --git a/.agents/skills/windows-agent-tooling/SKILL.md b/.agents/skills/windows-agent-tooling/SKILL.md index e188ce5..05970af 100644 --- a/.agents/skills/windows-agent-tooling/SKILL.md +++ b/.agents/skills/windows-agent-tooling/SKILL.md @@ -75,6 +75,9 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws - In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. +- MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit + messages (`/ws` became `C:/Program Files/Git/ws` in a stored ticket). Pass such text through a file + (`--body-file`, `-F`), prefix `MSYS_NO_PATHCONV=1`, or don't start the argument with `/`. - From Git Bash, `powershell -NoProfile -Command "... $_ ..."` lets bash expand `$_` and other `$vars` inside the double quotes before PowerShell parses them, which causes parser errors. Use the harness PowerShell tool, single-quote the command (`-Command '...'`), or put it in a `.ps1` file and run it with `-File`. - **PowerShell 5.1 UTF-8 BOM on config edits:** Whenever generating a PowerShell snippet for a user to edit JSON, TOML, or YAML configs (where Windows' default terminal may be Windows PowerShell 5.1 rather than `pwsh` 7), back up the file first and write via `[IO.File]::WriteAllText($p, $text, [Text.UTF8Encoding]::new($false))` instead of `Set-Content -Encoding utf8` (which writes a UTF-8 BOM that breaks strict JSON loaders); verify by re-parsing with `ConvertFrom-Json`. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). diff --git a/.claude/skills/merge-pr/SKILL.md b/.claude/skills/merge-pr/SKILL.md index 0bdefd6..cf788d7 100644 --- a/.claude/skills/merge-pr/SKILL.md +++ b/.claude/skills/merge-pr/SKILL.md @@ -209,6 +209,17 @@ Immediately before merging, re-read the PR and confirm: Use the merge method the repository's recent PRs used, pinned to the checked commit: +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` diff --git a/.claude/skills/ship-pr/SKILL.md b/.claude/skills/ship-pr/SKILL.md index 25d5661..05a08e3 100644 --- a/.claude/skills/ship-pr/SKILL.md +++ b/.claude/skills/ship-pr/SKILL.md @@ -156,6 +156,17 @@ Merging is the last step. Immediately before it, re-read the PR and confirm all - the PR is mergeable with no conflicts, and no review has changed; - no new commits arrived. +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + Use the merge method the repository's recent PRs used, and pin the commit so nothing newer can slip in: ```bash diff --git a/.claude/skills/test-driven-development/SKILL.md b/.claude/skills/test-driven-development/SKILL.md index 6c57a91..033e617 100644 --- a/.claude/skills/test-driven-development/SKILL.md +++ b/.claude/skills/test-driven-development/SKILL.md @@ -46,6 +46,12 @@ repo has no practical test seam. State the limitation and choose the closest ver writes, so broken code fails before it touches anything. Keep fixtures where a wrong path can't reach real state: temp folders often sit under the real home folder. Afterwards, check that the RED run left nothing outside the fixture. + For a guard, refusal or permission check, a refusal test passes just as well on an argument error. + Pair each refused call with the same call plus the override and assert it gets past the guard, then + run the refusal tests once with the guard disabled: they must fail because the action happened. + When the code has fallbacks (capture methods, retries, provider chains), a pass proves only the + branch that ran. Assert or log which branch ran, force each one you claim works, or say which ones + stayed unverified. 4. **GREEN — implement the minimum.** Write only enough production code to pass. Do not add unrequested options, abstractions, cleanup, or drive-by edits. If the test is hard to write, treat that as design feedback and improve the seam. @@ -112,6 +118,8 @@ Avoid tests that: - [ ] New behavior has a focused test. - [ ] The test failed for the intended reason before implementation. +- [ ] Guard or refusal tests also fail with the guard disabled, and the override path passes the guard. +- [ ] For code with fallbacks, each branch claimed as working was the one that ran in some test. - [ ] Production code is the minimal change needed to pass. - [ ] Targeted and relevant broader tests pass. - [ ] No test was weakened to fit the implementation. diff --git a/.claude/skills/windows-agent-tooling/SKILL.md b/.claude/skills/windows-agent-tooling/SKILL.md index e188ce5..05970af 100644 --- a/.claude/skills/windows-agent-tooling/SKILL.md +++ b/.claude/skills/windows-agent-tooling/SKILL.md @@ -75,6 +75,9 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws - In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. +- MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit + messages (`/ws` became `C:/Program Files/Git/ws` in a stored ticket). Pass such text through a file + (`--body-file`, `-F`), prefix `MSYS_NO_PATHCONV=1`, or don't start the argument with `/`. - From Git Bash, `powershell -NoProfile -Command "... $_ ..."` lets bash expand `$_` and other `$vars` inside the double quotes before PowerShell parses them, which causes parser errors. Use the harness PowerShell tool, single-quote the command (`-Command '...'`), or put it in a `.ps1` file and run it with `-File`. - **PowerShell 5.1 UTF-8 BOM on config edits:** Whenever generating a PowerShell snippet for a user to edit JSON, TOML, or YAML configs (where Windows' default terminal may be Windows PowerShell 5.1 rather than `pwsh` 7), back up the file first and write via `[IO.File]::WriteAllText($p, $text, [Text.UTF8Encoding]::new($false))` instead of `Set-Content -Encoding utf8` (which writes a UTF-8 BOM that breaks strict JSON loaders); verify by re-parsing with `ConvertFrom-Json`. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). diff --git a/.cursor/skills/merge-pr/SKILL.md b/.cursor/skills/merge-pr/SKILL.md index 0bdefd6..cf788d7 100644 --- a/.cursor/skills/merge-pr/SKILL.md +++ b/.cursor/skills/merge-pr/SKILL.md @@ -209,6 +209,17 @@ Immediately before merging, re-read the PR and confirm: Use the merge method the repository's recent PRs used, pinned to the checked commit: +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` diff --git a/.cursor/skills/ship-pr/SKILL.md b/.cursor/skills/ship-pr/SKILL.md index 25d5661..05a08e3 100644 --- a/.cursor/skills/ship-pr/SKILL.md +++ b/.cursor/skills/ship-pr/SKILL.md @@ -156,6 +156,17 @@ Merging is the last step. Immediately before it, re-read the PR and confirm all - the PR is mergeable with no conflicts, and no review has changed; - no new commits arrived. +**Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: +`gh pr list --base --state open`. If there are any: + +- Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it + does not retarget it. Retarget each child with `gh pr edit --base `, then delete the + branch. +- After a squash merge, each child conflicts with the base: git no longer sees the parent's commits + as shared. Merge the base into the child, check that the result's tree equals the reviewed head + (`git diff ` is empty when the base holds exactly the parent's tree), and + gate the new head again. Prefer merge commits for a stack when the repository allows them. + Use the merge method the repository's recent PRs used, and pin the commit so nothing newer can slip in: ```bash diff --git a/.cursor/skills/test-driven-development/SKILL.md b/.cursor/skills/test-driven-development/SKILL.md index 6c57a91..033e617 100644 --- a/.cursor/skills/test-driven-development/SKILL.md +++ b/.cursor/skills/test-driven-development/SKILL.md @@ -46,6 +46,12 @@ repo has no practical test seam. State the limitation and choose the closest ver writes, so broken code fails before it touches anything. Keep fixtures where a wrong path can't reach real state: temp folders often sit under the real home folder. Afterwards, check that the RED run left nothing outside the fixture. + For a guard, refusal or permission check, a refusal test passes just as well on an argument error. + Pair each refused call with the same call plus the override and assert it gets past the guard, then + run the refusal tests once with the guard disabled: they must fail because the action happened. + When the code has fallbacks (capture methods, retries, provider chains), a pass proves only the + branch that ran. Assert or log which branch ran, force each one you claim works, or say which ones + stayed unverified. 4. **GREEN — implement the minimum.** Write only enough production code to pass. Do not add unrequested options, abstractions, cleanup, or drive-by edits. If the test is hard to write, treat that as design feedback and improve the seam. @@ -112,6 +118,8 @@ Avoid tests that: - [ ] New behavior has a focused test. - [ ] The test failed for the intended reason before implementation. +- [ ] Guard or refusal tests also fail with the guard disabled, and the override path passes the guard. +- [ ] For code with fallbacks, each branch claimed as working was the one that ran in some test. - [ ] Production code is the minimal change needed to pass. - [ ] Targeted and relevant broader tests pass. - [ ] No test was weakened to fit the implementation. diff --git a/.cursor/skills/windows-agent-tooling/SKILL.md b/.cursor/skills/windows-agent-tooling/SKILL.md index e188ce5..05970af 100644 --- a/.cursor/skills/windows-agent-tooling/SKILL.md +++ b/.cursor/skills/windows-agent-tooling/SKILL.md @@ -75,6 +75,9 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws - In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. +- MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit + messages (`/ws` became `C:/Program Files/Git/ws` in a stored ticket). Pass such text through a file + (`--body-file`, `-F`), prefix `MSYS_NO_PATHCONV=1`, or don't start the argument with `/`. - From Git Bash, `powershell -NoProfile -Command "... $_ ..."` lets bash expand `$_` and other `$vars` inside the double quotes before PowerShell parses them, which causes parser errors. Use the harness PowerShell tool, single-quote the command (`-Command '...'`), or put it in a `.ps1` file and run it with `-File`. - **PowerShell 5.1 UTF-8 BOM on config edits:** Whenever generating a PowerShell snippet for a user to edit JSON, TOML, or YAML configs (where Windows' default terminal may be Windows PowerShell 5.1 rather than `pwsh` 7), back up the file first and write via `[IO.File]::WriteAllText($p, $text, [Text.UTF8Encoding]::new($false))` instead of `Set-Content -Encoding utf8` (which writes a UTF-8 BOM that breaks strict JSON loaders); verify by re-parsing with `ConvertFrom-Json`. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). From e4f4fc07924028e8eeb44cd51c13030ba336d320 Mon Sep 17 00:00:00 2001 From: Vladimir Bragin Date: Sun, 29 Nov 2026 13:40:20 -0600 Subject: [PATCH 2/2] Merge origin/main into docs/lessons-stacked-prs-guard-tests Conflict in .agent/SKILL_INVENTORY.md: kept this branch's 2026-11-29 review dates. merge-pr: main added a one-line stacked-PR retarget note; folded it into this branch's Stacked PRs block, which now sits before "Use the merge method" instead of between that line and its code block. Co-Authored-By: Claude Opus 5.5 --- .agent/SKILL_INVENTORY.md | 7 +- .agent/setup/library.json | 7 + .../skills/agent-setup/references/usage.md | 9 +- .agents/skills/cross-pc-ssh/SKILL.md | 9 +- .agents/skills/fast-forward/SKILL.md | 202 ++++++ .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 576 ++++++++++++++++++ .agents/skills/flow-complete/SKILL.md | 1 + .agents/skills/flow-next/SKILL.md | 1 + .../skills/git-and-diff-workflows/SKILL.md | 4 + .agents/skills/merge-pr/SKILL.md | 11 +- .agents/skills/ship-pr/SKILL.md | 2 +- .agents/skills/skill-authoring/SKILL.md | 4 + .../skills/test-driven-development/SKILL.md | 2 + .agents/skills/windows-agent-tooling/SKILL.md | 2 +- .../skills/agent-setup/references/usage.md | 9 +- .claude/skills/cross-pc-ssh/SKILL.md | 9 +- .claude/skills/fast-forward/SKILL.md | 202 ++++++ .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 576 ++++++++++++++++++ .claude/skills/flow-complete/SKILL.md | 1 + .claude/skills/flow-next/SKILL.md | 1 + .../skills/git-and-diff-workflows/SKILL.md | 4 + .claude/skills/merge-pr/SKILL.md | 11 +- .claude/skills/ship-pr/SKILL.md | 2 +- .claude/skills/skill-authoring/SKILL.md | 4 + .../skills/test-driven-development/SKILL.md | 2 + .claude/skills/windows-agent-tooling/SKILL.md | 2 +- .../skills/agent-setup/references/usage.md | 9 +- .cursor/skills/cross-pc-ssh/SKILL.md | 9 +- .cursor/skills/fast-forward/SKILL.md | 202 ++++++ .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 576 ++++++++++++++++++ .cursor/skills/flow-complete/SKILL.md | 1 + .cursor/skills/flow-next/SKILL.md | 1 + .../skills/git-and-diff-workflows/SKILL.md | 4 + .cursor/skills/merge-pr/SKILL.md | 11 +- .cursor/skills/ship-pr/SKILL.md | 2 +- .cursor/skills/skill-authoring/SKILL.md | 4 + .../skills/test-driven-development/SKILL.md | 2 + .cursor/skills/windows-agent-tooling/SKILL.md | 2 +- CHANGELOG.md | 8 + docs/agent-asset-inventory.md | 1 + docs/fast-forward/README.md | 99 +++ .../fast-forward-lands-through-pinned-pr.json | 43 ++ tests/test_fast_forward.py | 297 +++++++++ 46 files changed, 3021 insertions(+), 33 deletions(-) create mode 100644 .agents/skills/fast-forward/SKILL.md create mode 100644 .agents/skills/fast-forward/references/details.md create mode 100644 .agents/skills/fast-forward/scripts/fast_forward.py create mode 100644 .claude/skills/fast-forward/SKILL.md create mode 100644 .claude/skills/fast-forward/references/details.md create mode 100644 .claude/skills/fast-forward/scripts/fast_forward.py create mode 100644 .cursor/skills/fast-forward/SKILL.md create mode 100644 .cursor/skills/fast-forward/references/details.md create mode 100644 .cursor/skills/fast-forward/scripts/fast_forward.py create mode 100644 docs/fast-forward/README.md create mode 100644 evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json create mode 100644 tests/test_fast_forward.py diff --git a/.agent/SKILL_INVENTORY.md b/.agent/SKILL_INVENTORY.md index 8995449..fcaff9c 100644 --- a/.agent/SKILL_INVENTORY.md +++ b/.agent/SKILL_INVENTORY.md @@ -26,6 +26,7 @@ commands or edit code/config as part of its procedure. | cross-pc-ssh | Work in the same repository on a paired Windows PC over SSH: locate the peer checkout by root commit and normalized origin (any drive or root folder), re-verify it before each command, read-only status/ls/cat (secret-looking files refused)/allowlisted git, and a headless `claude -p` (Read/Grep/Glob only) or `codex exec -s read-only` (`--allow-edits` only with user approval). All remote strings travel as base64; paths stay inside the checkout; no key or sshd setup; remote-PowerShell quoting reference; stale-alias and git-prompt notes | L2 | 2026-11-28 | | repo-inventory | Compare checkouts of the same repos across PCs: snapshot a projects folder (remote key, default branch and origin SHA, HEAD, branches with ahead/behind/gone/unpushed, worktrees, dirty counts, stashes, in-progress ops) with read-only git, exchange it through the share (`private/host-profile/repos-.json`, atomic), over ssh or as a 16 KB digest, then compare hosts (exit 1 on drift) and print a SAFE / NEEDS HUMAN sync plan it never runs. Repos match by normalized remote plus an alias map for renames | L2 | 2026-11-27 | | commit-and-push | Stage, commit, and push with git safety rules; pairs with release-bump (**compiled harness**) | L2 | 2026-11-19 | +| fast-forward | Level the default branch with origin and land the intended tracked changes: fetch, `--ff-only` pull (stop on overlap with dirty files), commit staged-by-path changes on a short-lived branch, push, PR against the repo's own default branch, merge pinned to the full SHA (merge origin and regenerate on conflict, no force), fast-forward to 0/0, `branch -d`. Untracked files untouched. Sync (default) runs `scripts/fast_forward.py` inventory/plan/apply: ff-only rows only, expected-SHA re-checks, identical untracked copies archived with `--backup-dir`, config digest checked, receipt. User-typed only | L2 | 2026-11-29 | | critical-commit-audit | Deep post-commit hunt for high-severity bugs | L2 | 2026-07-01 | | eval | Capture task quality signals to agent memory (**compiled harness**) | L2 | 2026-07-21 | | export-chat | Export the Cursor agent transcript to Markdown or the clipboard, like Claude Code `/export` | L2 | 2026-10-01 | @@ -62,7 +63,7 @@ commands or edit code/config as part of its procedure. | search-tool-selection | Choose fd vs rg vs ast-grep vs fff MCP vs Graphify vs IDE search (**compiled harness**) | L1 | 2026-07-21 | | safe-command-patterns | Bounded output, inspect-before-edit, confirmation gates | L1 | 2026-07-03 | | search-and-navigation | rg, fd, bat, tree, navigation | L1 | 2026-07-03 | -| git-and-diff-workflows | git, gh, bounded diffs | L1 | 2026-11-09 | +| git-and-diff-workflows | git, gh, bounded diffs | L1 | 2026-11-28 | | cli-tools-overview | Router for CLI skills + shared references (install-tiers, agent-environment) | L1 | 2026-07-04 | | task-env-package-tools | Task runners, sync/frontmatter/pytest gates (**compiled harness**) | L1 | 2026-07-21 | | structural-code-search | ast-grep, semgrep, ctags | L1 | 2026-07-03 | @@ -118,10 +119,10 @@ specializations remain authoritative. Review notes and trigger cases are in | external-gemini-review | Gemini-only external review | L1 | 2026-07-01 | | pr-ready-hygiene | Definition-of-done checks and paste-ready PR text | L2 | 2026-07-01 | | agent-flow | Core rules for projects tracked by agent-flow (`.agent-flow/`): ready queue, claims, evidence, handoffs | L1 | 2026-11-06 | -| flow-complete | Finish an agent-flow ticket: DoD, push, PR, handoff, submit for review | L2 | 2026-11-06 | +| flow-complete | Finish an agent-flow ticket: DoD, push, PR, handoff, submit for review | L2 | 2026-11-28 | | flow-land | End-of-session handoff for agent-flow tickets | L1 | 2026-11-06 | | flow-loop | Capped autonomous agent-flow ticket loop under a run contract; explicit invocation only | L2 | 2026-11-06 | -| flow-next | Claim the next ready agent-flow ticket and set up its branch or worktree | L1 | 2026-11-06 | +| flow-next | Claim the next ready agent-flow ticket and set up its branch or worktree | L1 | 2026-11-28 | | flow-plan | Turn a request or spec into agent-flow tickets with dependencies | L1 | 2026-11-27 | | flow-review | Review an agent-flow ticket against its acceptance criteria | L2 | 2026-11-06 | | flow-status | Read-only agent-flow board summary | L1 | 2026-11-06 | diff --git a/.agent/setup/library.json b/.agent/setup/library.json index 13efbd2..93664ea 100644 --- a/.agent/setup/library.json +++ b/.agent/setup/library.json @@ -78,6 +78,13 @@ "global": true, "projects": [] }, + { + "id": "fast-forward", + "source": ".claude/skills/fast-forward", + "pack": "global", + "global": true, + "projects": [] + }, { "id": "commit-conventions", "source": ".claude/skills/commit-conventions", diff --git a/.agents/skills/agent-setup/references/usage.md b/.agents/skills/agent-setup/references/usage.md index e9e13af..b69216b 100644 --- a/.agents/skills/agent-setup/references/usage.md +++ b/.agents/skills/agent-setup/references/usage.md @@ -24,12 +24,19 @@ Use the local receipt and subsequent plan as evidence; file installation alone d `plan` has no per-skill option. To take in one skill (for example after its PR merges), make the full plan, then keep only that skill's operations: -1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. +1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. When several checkouts or worktrees hold a ledger, use the one whose `targets/*.json` contains the skill's relative path (for example `.claude/skills//SKILL.md`). A ledger without the skill plans every copy as a conflict. 2. Write a copy of the plan that keeps only the operations whose `relative` path is under `//` for the four user skill trees (`.claude/skills`, `.agents/skills`, `.gemini/config/skills`, `.gemini/antigravity-cli/skills`). Update `summary` to match. 3. Have the user review that list, then `apply --input ` and `check --input `. This is safe because `apply` checks every operation it is given (library and installer hashes, the target root, the destination folder, the content hashes) without requiring the full list. Conflicts are skipped and recorded in the receipt. The ownership ledger merges, so other skills' entries stay. +**A conflict that isn't a local edit.** `apply` skips a copy with no ledger entry ("unmanaged or overlapping edit"), even when it equals an earlier library version. For each conflicting file in the skill's folder, `SKILL.md` and `references/` alike, compare it with that file's history (`git log -p -- .claude/skills//`), ignoring line endings. Note that the installer rewrites the frontmatter `name` for a renamed install. If every file matches a past version, it's a stale install, not the user's edit. Keep it in the ledger by going through `apply`: + +- Record it in `.agent/setup/library.json` in a reviewed PR, so `apply` adopts it with a backup, a receipt and a ledger entry. `SKILL.md` goes in `reviewed_global_adoptions`. Every other file (`references/`, scripts) goes in `reviewed_resource_adoptions`, one entry per installed path (`relative`, `sha256`, reason) in each tree that holds it. Or: +- with the user's approval, move the stale folder to a backup under `` (for example `/stale-backups/-/`); `apply` creates its own run folder later. The re-plan then reads `create`, and `apply` writes the files and records ownership. + +Writing the plan's content to the file by hand leaves it unmanaged, with no receipt or rollback, so the next library change to that skill conflicts again. Anything that matches no past version is the user's edit: leave it and report it. + ## Explicit MCP replacement Use this procedure when the user asks to replace one harness's MCP registrations with another's. The named harness is the source for that request, not a permanent default for future tasks. Replacement requires explicit user intent; ordinary synchronization stays additive. diff --git a/.agents/skills/cross-pc-ssh/SKILL.md b/.agents/skills/cross-pc-ssh/SKILL.md index b767e32..87ec22b 100644 --- a/.agents/skills/cross-pc-ssh/SKILL.md +++ b/.agents/skills/cross-pc-ssh/SKILL.md @@ -51,9 +51,12 @@ alone, and the guard then accepts exactly the boundary commits recorded when it 1. `ssh -n -o BatchMode=yes hostname` must print the peer's name. If it asks for a password or fails host-key verification, stop: setting up keys and known_hosts is the user's step, not this skill's. - If it times out, the alias's `HostName` may be a stale address (DHCP). Try the peer's hostname with the - pinned key, `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`, and pass - the same options as `--peer`. Fixing `~/.ssh/config` is the user's step. + If it times out, the alias's `HostName` may be a stale address (DHCP). To check by hostname with the + pinned key, first find the name `known_hosts` holds it under (`ssh-keygen -F `, then + `ssh-keygen -F `): ssh saves a key under the `HostName` unless `HostKeyAlias` is set. + Then run `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`. The helper's + `--peer` takes only an alias or `user@host`, with fixed ssh options, so before using the helper the + user updates `HostName` in `~/.ssh/config`. 2. `locate`. If it finds no checkout, the repository isn't cloned there (or lives outside the roots); say so rather than searching the peer's disks. diff --git a/.agents/skills/fast-forward/SKILL.md b/.agents/skills/fast-forward/SKILL.md new file mode 100644 index 0000000..52afa4b --- /dev/null +++ b/.agents/skills/fast-forward/SKILL.md @@ -0,0 +1,202 @@ +--- +name: fast-forward +description: "Bring the default branch of the current repository (or each repository the work touched) level with its remote with a deterministic inventory, plan and fast-forward-only apply (sync), and, when the user also asks to commit, push and merge, land the local work that belongs there (land): commit the intended tracked changes on a short-lived branch, push it, open a PR against the repository's own default branch, merge it pinned to the pushed commit, fast-forward the local default branch to the merge, and delete the branch. Leaves untracked and unrelated files alone. Runs only when the user types /fast-forward." +capability: "Sync a checkout's default branch with origin, fast-forward only; in land mode, also land its intended tracked changes through a pinned PR merge. Never by force or a direct push to the default branch." +side_effect_level: remote_write +approval_required: true +requires_tools: "python 3.9+ (stdlib only) for scripts/fast_forward.py, git, and gh authenticated for the repository's own remote." +output_schema: "The harness plan table and receipt JSON, then the default branch's position before and after (ahead/behind counts and short SHAs), what was committed (paths and the commit), the PR and its merge commit, the final ahead/behind of 0/0, and every file left untouched with the reason." +risk_class: medium +disable-model-invocation: true +--- + +# Fast-forward + +`/fast-forward` means: **make my default branch match the remote** (sync). Typed alone, it approves only +the sync: a fetch and fast-forward-only moves. When the typed request also says commit, push or merge +(land), it also approves one commit of the intended tracked changes, one push of a new branch, one PR and +its merge. It is not standing approval, and it never force-pushes, rewrites history or pushes straight to the +default branch. + +| Mode | What it does | Runs when | +|---|---|---| +| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward` alone, or with "catch up" or "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The typed request also says commit, push or merge | +| cleanup | Not run here: merged branches and worktrees are listed in the report only | Housekeeping, on its own request | + +A compound request ("fetch, pull, commit, push, merge, fast-forward") authorizes both modes for this run. +Permission to fast-forward a checkout is never permission to push to its default branch. + +How this differs from neighbours: +- `commit-and-push` commits and pushes a branch; it doesn't merge or fast-forward the default branch. +- `/merge-pr` and `/ship-pr` merge an existing PR on CI evidence. `/fast-forward` opens its own small PR + and merges it in the same run, so keep it for changes that need no review: tracker snapshots, + generated files, docs the user already approved. +- Syncing an upstream repository **into** a fork is a different job (some projects have their own + skill for it). `/fast-forward` only talks to the repository's own `origin`. +- `repo-inventory` compares checkouts across PCs and prints a plan it never runs. This skill is the + local executor; on a peer it only runs `inventory` and `plan` (see [references/details.md](references/details.md)). + +## 0. Scope and other sessions + +- **Scope:** the current repository, plus each repository this conversation changed, or the list the user + names. Never sweep a whole projects folder unasked. +- **Other sessions:** before any write, ask the live sessions working in these checkouts (`ListAgents`, + then `SendMessage`) and wait for "safe". If another session already took the same request, split the + repositories and send it what you found (EOL-only files, junk names, identical copies) so it doesn't redo it. + +## 1. Confirm the target + +- **The repository and its default branch.** Read `gh repo view --json nameWithOwner,defaultBranchRef` + for `origin`. In a fork, `gh` defaults to the parent repository, so name the repository on every + `gh` call (`--repo /`). If the project's notes name a read-only upstream, never write to it. +- **This checkout is on the default branch,** or can switch to it cleanly. If it's on another branch + with work in progress, stop and ask; that branch isn't yours to move. +- **Another session may share this checkout.** If one is active here (`ListAgents`, a held tracker ticket, + a running build), ask before switching branches. + +## 2. Fetch and fast-forward (sync) + +Use the harness. It calls git with argument lists (no shell, so no MSYS path rewriting), with prompts off +and a per-repo timeout, and it never edits `.git/config`: + +```bash +FF="/scripts/fast_forward.py" +python -I "$FF" plan --repo [--repo ]... --fetch [--gh] --out /ff-plan.json +python -I "$FF" apply --plan /ff-plan.json [--backup-dir ] --receipt /ff-receipt.json +``` + +| Row | Meaning | Who acts | +|---|---|---| +| `noop` | Already level, or nothing this skill may do | – | +| `ff` | `merge --ff-only` to the fetched SHA in the checkout holding the default branch; unrelated edits stay | apply | +| `ff-ref` | No worktree holds the default branch: `update-ref` with the expected old SHA | apply | +| `archive-ff` | Untracked or ignored files identical (git-normalized) to incoming ones: backed up, verified, removed, then `ff` | apply, with `--backup-dir` | +| `switch` | The current branch is merged (in origin's history, or with `--gh` a PR merged at this exact head) and clean | apply | +| `needs-human` | Diverged, local commits, overlapping edits, a different untracked or ignored file, the default branch checked out elsewhere, an operation in progress, a fetch that failed or timed out | you, with the user | + +- Show the plan table before `apply`. `apply` re-reads every repository first and refuses a row whose + HEAD, SHAs, holder, tracked changes or collision hashes moved since planning; re-plan instead of forcing. +- It compares the git configuration digest after each action and stops all writes on drift. Report a + drift; never restore or "fix" the configuration yourself. +- A timed-out fetch usually waits on a credential prompt. Report it as `needs-human: auth`. +- Without the harness (no Python), the manual rules are: + +```bash +git fetch origin +git rev-list --left-right --count HEAD...origin/ # " " +``` + +- **Behind only (`0 N`):** `git pull --ff-only origin `. Dirty tracked files are fine when the + incoming commits don't touch them. Check with `git log HEAD..origin/ -- ` first. + If they do touch them, stop and report the overlap; don't stash, reset or merge over someone's edits. +- **Ahead (`N 0` or `N M`):** local commits exist on the default branch. Don't push them directly. Move + them to the step-3 branch, or stop and ask if they aren't clearly the user's. `git switch -c ` + keeps the commits and the working tree, then `git branch -f --no-track origin/` moves only the + default branch's pointer back. Never use `git reset` for this: it can discard the dirty tracked files + this step allows. +- **Never** `git pull` without `--ff-only`, and never `--rebase` or `--force` on the default branch. +- **The default branch is checked out in another worktree:** fast-forward it there, only after its owner + says it is safe. Don't move a checked-out branch's ref behind its worktree's back. + +## 3. Commit the intended changes on a branch + +- **Decide what belongs.** List `git status --short`. Commit only tracked changes the user's request + covers, or that this run produced: a tracker snapshot, a regenerated file. Show the diff stat. +- **Untracked files stay untracked** unless the user names them. They are often local notes, exports, + device presets or machine config (`mcp_config.json`, `*.local.*`, `.env*`). List them in the report. +- **Secrets gate before the push:** scan the staged diff (`git diff --cached`) for tokens, keys, + machine-local paths and personal identities. A hit blocks the push. For a PUBLIC repository + (`gh repo view --json visibility`), follow `commit-and-push`'s public-repo checks too. +- Create the branch with `git switch --no-track -c `: `branch.autoSetupMerge=always` would otherwise + write tracking into `.git/config`. Name it `chore/-` (or the project's pattern, such as `af/-`). Stage + paths explicitly (`git add `, never `git add -A`), and commit with a Conventional Commit message + and the attribution lines the session asks for. +- Nothing to commit? Skip steps 3–5 and report that the default branch only fast-forwarded. + +## 4. Push and open the PR + +```bash +git push origin +gh pr create --repo / --base --head --title "" --body-file +``` + +Push without `-u`: an upstream setting writes branch tracking into `.git/config`. The body says what +changed and why it needs no review. Reference the ticket (`Refs `) when the +project tracks work. + +## 5. Merge pinned to the pushed commit + +- **Same gate as `/merge-pr`.** Poll the check state after the push (bounded, about ten minutes) rather than + sleeping a fixed time; zero runs on a repository with workflows is unknown, not green. Then + **every** run and check on the pushed SHA (`gh run list --commit `, plus the commit's + check-runs and status) must have completed green. Anything pending, failing or skipped-only, a + `mergeStateStatus` of `BLOCKED`, or a conflict means stop: hand it to `/ship-pr` or the user. If the + repository has CI but no run registered, or no CI at all, hand the merge to `/merge-pr`, which proves + that case and runs the checks locally. Don't merge on a guess. +- Check that the PR's `headRefOid` equals `git rev-parse HEAD`, so the merge lands exactly the commit + you checked. +- Use the method the repository's recent PRs used, pinned to the **full 40-character SHA** (a short SHA + is rejected): + + ```bash + gh pr merge --repo / --merge --delete-branch --match-head-commit $(git rev-parse HEAD) + ``` +- **"The merge commit cannot be cleanly created":** the default branch moved. Fetch, merge + `origin/` into the branch, and resolve the conflicts. Regenerate generated files rather than + hand-merging them. Re-run the checks, push (no force), then merge again on the new head. + +## 6. Fast-forward the local default branch + +```bash +git switch +git pull --ff-only origin +git rev-list --left-right --count HEAD...origin/ # must print "0 0" +git branch -d # -d, not -D: it must be merged +``` + +Compare `python -I "$FF" inventory`'s `config_digest` from before step 3 with one taken now; a change is a drift to +report, not to repair. `gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +already have deleted the local branch, so a failing `git branch -d` there is harmless. Check +`gh pr view --json state,mergeCommit` rather than trusting its exit code. + +## 7. After the fast-forward + +- `0 0` proves the refs match. It doesn't prove a clean tree, a rebuilt binary or a running new version. + Check what the repository deploys (a `dist/` the harness flags, binaries copied out of a build folder, + skills installed at user level, an npm-linked CLI) and report "source at X, installed at Y". Rebuild or + reinstall only within the request; for skills, hand the user the installer's plan. +- Replacing a binary that live sessions hold open fails until they exit: make it a "close sessions" item. +- Branches whose remote is `[gone]` and squash-merged branches (`gh pr list --state merged --head `) + go in the report as a list. Deleting them is cleanup, the user's call. +- **Retries:** after any failure, read the state (PR state, `git log`, the receipt) before trying again; a + remote merge can succeed while local cleanup fails. Re-plan, and never repeat a commit, a PR or a merge. + +## Report + +One row per repository (and per PC), same columns everywhere; rows with nothing to do collapse into one line +("9 repos already at origin"): + +| Repo | PC | Before | After | Action | Left for you | +|---|---|---|---|---|---| + +Then, for land: + +```markdown +**** is level with origin at (was ahead, behind). + +- Committed as on ; PR # merged as ; branch deleted. +- Left untouched: . +- Archived: backup>; config digest unchanged; deploy: . +``` + +## Never + +- Push directly to the default branch, force-push, rebase or reset a branch with others' work. +- Stash, discard or commit files the user didn't ask for, including untracked ones. +- Merge past a pending or failing required check, a `BLOCKED` state or a requested change. +- Open the PR against an upstream or parent repository the project treats as read-only. +- Delete a branch with `-D`, or delete a branch that isn't merged. +- Edit `.git/config`: no upstream tracking, no `git config`, no `remote set-url` for a moved + repository ("This repository moved" is harmless: GitHub redirects). +- Retry a command a permission layer refused in another form. Finish the rest and hand it over as a `!` command. diff --git a/.agents/skills/fast-forward/references/details.md b/.agents/skills/fast-forward/references/details.md new file mode 100644 index 0000000..17a1423 --- /dev/null +++ b/.agents/skills/fast-forward/references/details.md @@ -0,0 +1,41 @@ +# fast-forward: details + +Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Bash on Windows. + +## Checks that look green or red for the wrong reason + +- **Zero check runs is unknown.** A repository can have Actions enabled and active workflows yet no runs at + all. Look at `gh run list --commit ` and the repository's runs, not only the PR's check list. + `gh pr checks` exits non-zero while checks are pending: that means wait. +- **Classify a failure from the job log:** a repository setting (for example dependency review on a + repository without the dependency graph), an infrastructure error, or a real failure. Only a real + failure belongs to the PR. If the default branch's own latest run fails the same way, report it as + already broken on the base; the PR can't fix it. + +## Across PCs + +- On a peer, run only `inventory` and `plan`, over `cross-pc-ssh` or as a `cross-pc-messages` request. + The plan goes back to that PC's agent with exact commands; its owner approves its own `apply`. +- Reach peers by hostname and pin the host key alias (`ssh -o HostKeyAlias= `), so a + stale address doesn't look like "host unreachable". +- The same repository sits under different folders, drive letters or as a shallow clone on each PC. Match + it by normalized origin and root commits, as `cross-pc-ssh` does, never by folder name. +- After a default branch moves, offer to draft the note telling the peers to fast-forward too. Sending it + is the user's call. +- Fetch in parallel; move refs one repository at a time, so the report and undo stay in order. + +## Windows + +- Under Git Bash, `git show origin/:` has its argument rewritten into a Windows path. Set + `MSYS_NO_PATHCONV=1` for such manual commands; the harness avoids it by never using a shell. +- Compare with carriage returns stripped (`git diff --ignore-cr-at-eol --numstat`); otherwise every mirror + regenerated on Windows looks modified. The harness reports line-ending-only edits as a note. +- A hung `git.exe` (credential helper) outlives a client timeout. The harness starts each git call in its + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). + +## Generated snapshots + +A tracker snapshot such as `.agent-flow/tickets.jsonl` that both sides changed is not a merge by +timestamp. Use the tracker's own export or import, within the task's scope; otherwise it is a +`needs-human` item. Build output that appears after a local test run (`*.egg-info/`, `__pycache__/`, +`target/`) is worth one suggested `.gitignore` line, not a listing every run. diff --git a/.agents/skills/fast-forward/scripts/fast_forward.py b/.agents/skills/fast-forward/scripts/fast_forward.py new file mode 100644 index 0000000..9abfa97 --- /dev/null +++ b/.agents/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,576 @@ +#!/usr/bin/env python3 +"""Fast-forward local default branches to origin, deterministically and without editing .git/config. + +Commands: + inventory [--repo DIR]... [--fetch] [--gh] [--timeout 60] [--json] + Read-only facts per repository: the default branch (origin/HEAD, else main, else master) and its origin + SHA, the local default branch and where it is checked out, HEAD, ahead/behind, upstream, an operation in + progress, tracked changes split into real and line-ending-only edits, untracked or ignored files the incoming + commits would overwrite (each compared with the incoming blob, path-aware), a stale-build hint and a + digest of the git configuration files. --fetch runs "git fetch --prune origin" first (in parallel, + no prompts, per-repo timeout); that is the only write. --gh asks gh whether the current branch's + exact head was merged as a PR (squash merges). + plan [--repo DIR]... [--fetch] [--gh] [--out FILE] [--json] + Rule-based actions per repository, each with its reason: + noop level with origin already + ff git merge --ff-only in the checkout that holds the default branch + ff-ref git update-ref on the default branch when no worktree holds it (expected old SHA) + archive-ff untracked files identical to the incoming ones: back them up, verify, remove, then ff + switch the current branch is merged and the tree is clean: switch to the (advanced) default + needs-human anything else (diverged, local commits, overlap, different untracked file, occupied + default branch, operation in progress, fetch timeout or auth), never executed + apply --plan FILE [--backup-dir DIR] [--receipt FILE] + Runs only ff, ff-ref, archive-ff and switch rows. Before each repository it re-reads the evidence + (HEAD, default and origin SHAs, holder, tracked changes, collision hashes) and refuses a stale row. + It checks the config digest after every action and stops all further writes when it drifts. Prints a + receipt (old and new SHAs, archived files, undo commands). Never fetches, stashes, resets, rebases, + force-pushes, deletes branches or runs "git config". + +Exit codes: 0 nothing left for a human, 1 a needs-human, refused or failed row, 2 usage error. +Stdlib only; git is always called with an argument list, never through a shell. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +SCHEMA = "fast-forward-plan" +SCHEMA_VERSION = 1 +EXECUTABLE = ("ff", "ff-ref", "archive-ff", "switch") +GIT_CFG = ["-c", "core.quotepath=off", "-c", "color.ui=never", "-c", "core.fsmonitor=false"] +OPERATIONS = (("MERGE_HEAD", "merge"), ("rebase-merge", "rebase"), ("rebase-apply", "rebase"), + ("CHERRY_PICK_HEAD", "cherry-pick"), ("REVERT_HEAD", "revert"), ("BISECT_LOG", "bisect")) +# Names a broken shell redirect tends to leave behind ("2>&1", "-o", "nul", "=1.2"): reported, never removed. +JUNK = re.compile(r"(^-|^=|^(nul|con|prn|aux)(\..*)?$|&1$|^\d$)", re.IGNORECASE) + + +class UsageError(Exception): + pass + + +class GitError(Exception): + pass + + +def git_env(read_only: bool = True) -> dict: + env = dict(os.environ) + env.update({"GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never", "GIT_ASKPASS": "", + "SSH_ASKPASS": "", "LC_ALL": "C"}) + env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes") + if read_only: + env["GIT_OPTIONAL_LOCKS"] = "0" + return env + + +def _kill_tree(proc: subprocess.Popen) -> None: + """Stop git and the helpers it started (credential managers, ssh), not only the direct child.""" + try: + if os.name == "nt": + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, check=False) + else: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + + +def run(cmd: list[str], cwd: str | Path, timeout: float = 60, read_only: bool = True) -> subprocess.CompletedProcess: + proc = subprocess.Popen(cmd, cwd=str(cwd), env=git_env(read_only), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + start_new_session=os.name != "nt") + try: + out, err = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _kill_tree(proc) + proc.communicate() + raise TimeoutError(f"{' '.join(cmd[:3])} timed out after {timeout:.0f}s") + return subprocess.CompletedProcess(cmd, proc.returncode, out.decode("utf-8", "replace"), + err.decode("utf-8", "replace")) + + +def git(repo: str | Path, *args: str, timeout: float = 60, check: bool = True, read_only: bool = True) -> str: + cp = run(["git", *GIT_CFG, *args], repo, timeout, read_only) + if check and cp.returncode != 0: + raise GitError(f"git {' '.join(args[:3])}: {cp.stderr.strip()[:300]}") + return cp.stdout + + +def git_ok(repo, *args, timeout: float = 60) -> bool: + return run(["git", *GIT_CFG, *args], repo, timeout).returncode == 0 + + +def rev(repo, ref: str) -> str | None: + cp = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", ref + "^{commit}"], repo) + return cp.stdout.strip() or None if cp.returncode == 0 else None + + +def norm(path: str | Path) -> str: + return os.path.normcase(os.path.normpath(str(Path(path).resolve()))) + + +# ---------------------------------------------------------------- configuration digest + +def config_files(repo: str | Path) -> list[Path]: + common = Path(repo, git(repo, "rev-parse", "--git-common-dir").strip()).resolve() + files = [common / "config"] + files += sorted((common / "worktrees").glob("*/config.worktree")) + if (common / "config.worktree").exists(): + files.append(common / "config.worktree") + return files + + +def config_digest(repo: str | Path) -> str: + h = hashlib.sha256() + for f in config_files(repo): + h.update(f.name.encode() + b"\0" + str(f.parent.name).encode() + b"\0") + h.update(f.read_bytes() if f.exists() else b"") + h.update(b"\0") + return h.hexdigest() + + +# ---------------------------------------------------------------- inventory + +def parse_status(raw: str) -> tuple[list[dict], list[str]]: + """git status --porcelain=v1 -z --untracked-files=all -> (tracked changes, untracked paths).""" + tracked, untracked = [], [] + parts = raw.split("\0") + i = 0 + while i < len(parts): + entry = parts[i] + i += 1 + if len(entry) < 4: + continue + xy, path = entry[:2], entry[3:] + if xy == "??": + untracked.append(path) + continue + if xy == "!!": + continue + item = {"path": path, "xy": xy, "staged": xy[0] not in " ?", "unmerged": "U" in xy or xy in ("AA", "DD")} + if xy[0] in "RC": + item["from"] = parts[i] if i < len(parts) else "" + i += 1 + tracked.append(item) + return tracked, untracked + + +def real_edits(repo) -> set[str]: + """Paths whose diff against HEAD is more than line endings (--name-only ignores --ignore-cr-at-eol).""" + out = set() + for line in git(repo, "diff", "--ignore-cr-at-eol", "--numstat", "--no-renames", "HEAD").splitlines(): + added, deleted, path = line.split("\t", 2) + if (added, deleted) != ("0", "0"): + out.add(path) + return out + + +def worktrees(repo) -> list[dict]: + out, cur = [], {} + for line in git(repo, "worktree", "list", "--porcelain").splitlines() + [""]: + if not line: + if cur: + out.append(cur) + cur = {} + elif line.startswith("worktree "): + cur["path"] = line[9:] + elif line.startswith("HEAD "): + cur["head"] = line[5:] + elif line.startswith("branch "): + cur["branch"] = line[7:] + elif line in ("bare", "detached", "locked", "prunable") or line.startswith(("locked ", "prunable ")): + cur[line.split(" ")[0]] = True + return out + + +def default_branch(repo) -> str | None: + cp = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], repo) + if cp.returncode == 0 and cp.stdout.strip().startswith("refs/remotes/origin/"): + return cp.stdout.strip()[len("refs/remotes/origin/"):] + for name in ("main", "master"): + if rev(repo, f"refs/remotes/origin/{name}"): + return name + return None + + +def origin_slug(repo) -> str | None: + cp = run(["git", *GIT_CFG, "remote", "get-url", "origin"], repo) + m = re.search(r"[/:]([^/:]+)/([^/]+?)(\.git)?/?$", cp.stdout.strip()) if cp.returncode == 0 else None + return f"{m.group(1)}/{m.group(2)}" if m else None + + +def gh_command() -> list[str]: + raw = os.environ.get("FAST_FORWARD_GH", "gh") + return json.loads(raw) if raw.startswith("[") else [raw] + + +def merged_pr_at_head(repo, branch: str, head_sha: str, timeout: float) -> dict | None: + slug = origin_slug(repo) + if not slug: + return None + try: + cp = run([*gh_command(), "pr", "list", "--repo", slug, "--state", "merged", "--head", branch, + "--json", "number,headRefOid,url"], repo, timeout) + except (OSError, TimeoutError): + return None + if cp.returncode != 0: + return None + for pr in json.loads(cp.stdout or "[]"): + if pr.get("headRefOid") == head_sha: # a PR merged earlier does not cover later commits + return {"number": pr.get("number"), "url": pr.get("url")} + return None + + +def build_hint(top: Path, origin_time: int | None) -> str | None: + pkg = top / "package.json" + dist = top / "dist" + try: + scripts = json.loads(pkg.read_text(encoding="utf-8")).get("scripts", {}) if pkg.exists() else {} + except (ValueError, OSError): + return None + if "build" in scripts and dist.is_dir() and origin_time and dist.stat().st_mtime < origin_time: + return "dist/ is older than the default branch tip: run the project's build before calling it deployed" + return None + + +def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, + fetched: dict | None = None) -> dict: + rec: dict = {"input": str(path)} + try: + top = Path(git(path, "rev-parse", "--show-toplevel", timeout=timeout).strip()).resolve() + rec["path"] = str(top) + rec["git_dir"] = str(Path(top, git(top, "rev-parse", "--git-dir").strip()).resolve()) + rec["config_digest"] = config_digest(top) + if fetched: + rec["fetch"] = fetched + d = default_branch(top) + rec["default"] = d + sym = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "HEAD"], top) + rec["head_branch"] = sym.stdout.strip()[len("refs/heads/"):] if sym.returncode == 0 else None + rec["head_sha"] = rev(top, "HEAD") + up = run(["git", *GIT_CFG, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], top) + rec["upstream"] = up.stdout.strip() if up.returncode == 0 else None + rec["operation"] = next((name for marker, name in OPERATIONS if Path(rec["git_dir"], marker).exists()), None) + tracked, untracked = parse_status(git(top, "status", "--porcelain=v1", "-z", "--untracked-files=all")) + real = real_edits(top) if rec["head_sha"] else set() + for item in tracked: + item["eol_only"] = (not item["staged"] and not item["unmerged"] and item["xy"] == " M" + and item["path"] not in real) + rec["tracked"] = tracked + rec["untracked"] = untracked + rec["junk_suspects"] = [u for u in untracked if JUNK.search(Path(u).name)] + rec["worktrees"] = worktrees(top) + if not d: + return rec + rec["origin_sha"] = rev(top, f"refs/remotes/origin/{d}") + rec["local_default_sha"] = rev(top, f"refs/heads/{d}") + rec["holder"] = next((w["path"] for w in rec["worktrees"] if w.get("branch") == f"refs/heads/{d}"), None) + if rec["origin_sha"] and rec["local_default_sha"]: + a, b = git(top, "rev-list", "--left-right", "--count", + f"{rec['local_default_sha']}...{rec['origin_sha']}").split() + rec["ahead"], rec["behind"] = int(a), int(b) + if rec["origin_sha"] and rec["head_sha"]: + incoming = set(filter(None, git(top, "diff", "--name-only", "-z", "--no-renames", + rec["head_sha"], rec["origin_sha"]).split("\0"))) + rec["incoming_paths"] = len(incoming) + rec["overlap"] = sorted(t["path"] for t in tracked if t["path"] in incoming or t.get("from") in incoming) + # Untracked and ignored files alike: a fast-forward overwrites ignored files without asking. + indexed = set(filter(None, git(top, "ls-files", "-z").split("\0"))) + rec["collisions"] = [collision(top, p, rec["origin_sha"]) for p in sorted(incoming) + if p not in indexed and (top / p).is_file()] + rec["head_merged"] = bool(rec["head_branch"] and rec["head_branch"] != d + and git_ok(top, "merge-base", "--is-ancestor", rec["head_sha"], rec["origin_sha"])) + if use_gh and rec["head_branch"] and rec["head_branch"] != d and not rec["head_merged"]: + rec["merged_pr"] = merged_pr_at_head(top, rec["head_branch"], rec["head_sha"], timeout) + t = git(top, "log", "-1", "--format=%ct", rec["origin_sha"]).strip() + rec["build_hint"] = build_hint(top, int(t) if t.isdigit() else None) + except (GitError, TimeoutError, OSError) as exc: + rec["error"] = str(exc) + return rec + + +def collision(top: Path, rel: str, origin_sha: str) -> dict: + local = git(top, "hash-object", f"--path={rel}", "--", str(top / rel)).strip() + blob = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", f"{origin_sha}:{rel}"], top).stdout.strip() + raw = hashlib.sha256((top / rel).read_bytes()).hexdigest() + return {"path": rel, "local_blob": local, "incoming_blob": blob or None, "sha256": raw, "same": bool(blob) and local == blob} + + +def fetch_all(paths: list[str], timeout: float) -> dict[str, dict]: + def one(p: str) -> tuple[str, dict]: + try: + before = rev(p, "refs/remotes/origin/HEAD") + cp = run(["git", *GIT_CFG, "fetch", "--prune", "origin"], p, timeout, read_only=False) + if cp.returncode != 0: + return p, {"ok": False, "error": cp.stderr.strip()[:300] or "fetch failed"} + return p, {"ok": True, "origin_head_before": before} + except (TimeoutError, OSError) as exc: + return p, {"ok": False, "error": f"{exc} (auth prompt or network; check credentials by hand)"} + with ThreadPoolExecutor(max_workers=min(8, max(1, len(paths)))) as pool: + return dict(pool.map(one, paths)) + + +# ---------------------------------------------------------------- plan (pure) + +def plan_repo(rec: dict) -> list[dict]: + def human(reason: str) -> list[dict]: + return [{"action": "needs-human", "reason": reason}] + if rec.get("error"): + return human(f"inventory failed: {rec['error']}") + if rec.get("fetch") and not rec["fetch"].get("ok"): + return human(f"fetch failed: {rec['fetch'].get('error')}") + d = rec.get("default") + if not d or not rec.get("origin_sha"): + return human("no origin default branch found (origin/HEAD, main or master)") + if rec.get("operation"): + return human(f"a {rec['operation']} is in progress here") + if any(t["unmerged"] for t in rec["tracked"]): + return human("unmerged paths") + rows: list[dict] = [] + if not rec.get("local_default_sha"): + rows.append({"action": "noop", "reason": f"no local {d} branch; creating one is not this skill's job"}) + return rows + ahead, behind = rec.get("ahead", 0), rec.get("behind", 0) + if ahead and behind: + return human(f"{d} diverged from origin ({ahead} ahead, {behind} behind): needs a reviewed preservation plan") + if ahead: + return human(f"{d} has {ahead} local commit(s) not on origin: land them through a PR (land mode), don't push") + here = rec.get("holder") and norm(rec["holder"]) == norm(rec["path"]) + real = [t["path"] for t in rec["tracked"] if not t["eol_only"]] + differ = [c["path"] for c in rec.get("collisions", []) if not c["same"]] + same = [c["path"] for c in rec.get("collisions", []) if c["same"]] + on_branch = rec.get("head_branch") and rec["head_branch"] != d + switchable = on_branch and not rec.get("holder") and (rec.get("head_merged") or rec.get("merged_pr")) \ + and not rec["tracked"] + if behind: + if rec.get("holder") and not here: + return human(f"{d} is checked out in another worktree ({rec['holder']}): fast-forward it there, " + "after its owner says it is safe") + if here: + if rec["overlap"]: + return human("local changes overlap incoming commits: " + ", ".join(rec["overlap"][:10])) + if differ: + return human("untracked files differ from incoming ones: " + ", ".join(differ[:10])) + if same: + rows.append({"action": "archive-ff", "reason": f"fast-forward {behind}; {len(same)} untracked " + "file(s) are byte-identical (git-normalized) to incoming ones", "paths": same}) + else: + rows.append({"action": "ff", "reason": f"fast-forward {behind} commit(s)" + + (f"; {len(real)} unrelated local edit(s) stay" if real else "")}) + else: + rows.append({"action": "ff-ref", "reason": f"{d} is not checked out anywhere: move it {behind} commit(s)"}) + if switchable: + if differ: + rows.append({"action": "needs-human", "reason": "untracked files differ from incoming ones: " + + ", ".join(differ[:10])}) + else: + how = "its head is in origin" if rec.get("head_merged") else f"PR #{rec['merged_pr']['number']} merged at this head" + rows.append({"action": "switch", "reason": f"{rec['head_branch']} is merged ({how}) and clean", + "paths": same}) + elif on_branch and not rows: + rows.append({"action": "noop", "reason": f"on {rec['head_branch']} (not merged or not clean); " + f"{d} is level with origin"}) + if not rows: + rows.append({"action": "noop", "reason": f"{d} is level with origin"}) + return rows + + +EVIDENCE = ("path", "head_branch", "head_sha", "local_default_sha", "origin_sha", "holder", "config_digest") + + +def evidence(rec: dict) -> dict: + ev = {k: rec.get(k) for k in EVIDENCE} + ev["tracked"] = sorted(f"{t['xy']} {t['path']}" for t in rec.get("tracked", [])) + ev["collisions"] = sorted(f"{c['path']} {c['sha256']}" for c in rec.get("collisions", [])) + return ev + + +def build_plan(recs: list[dict]) -> dict: + repos = [] + for rec in recs: + rows = plan_repo(rec) + repos.append({"repo": rec.get("path") or rec["input"], "default": rec.get("default"), "rows": rows, + "evidence": evidence(rec), "notes": [n for n in (rec.get("build_hint"),) if n] + + ([f"junk-looking untracked names (left alone): {', '.join(rec['junk_suspects'][:5])}"] + if rec.get("junk_suspects") else []) + + ([f"{sum(t['eol_only'] for t in rec['tracked'])} line-ending-only change(s)"] + if any(t.get("eol_only") for t in rec.get("tracked", [])) else [])}) + return {"schema": SCHEMA, "schema_version": SCHEMA_VERSION, "created": int(time.time()), "repos": repos} + + +# ---------------------------------------------------------------- apply + +def inside(child: Path, parent: Path) -> bool: + try: + child.resolve().relative_to(parent.resolve()) + return True + except ValueError: + return False + + +def apply_plan(plan: dict, backup_dir: str | None) -> dict: + if plan.get("schema") != SCHEMA or plan.get("schema_version") != SCHEMA_VERSION: + raise UsageError("not a fast-forward plan (schema mismatch)") + if not backup_dir and any(r["action"] in ("archive-ff", "switch") and r.get("paths") + for e in plan["repos"] for r in e["rows"]): + raise UsageError("archive rows need --backup-dir (a folder outside the repository); nothing ran") + receipt = {"schema": "fast-forward-receipt", "plan_created": plan.get("created"), "repos": []} + halted: str | None = None + for entry in plan["repos"]: + out = {"repo": entry["repo"], "outcomes": [], "archived": [], "undo": []} + receipt["repos"].append(out) + todo = [r for r in entry["rows"] if r["action"] in EXECUTABLE] + if not todo: + out["outcomes"] = [{"action": r["action"], "result": "skipped", "reason": r["reason"]} for r in entry["rows"]] + continue + if halted: + out["outcomes"].append({"result": "refused", "reason": halted}) + continue + now = inventory_repo(entry["repo"]) + if evidence(now) != entry["evidence"]: + changed = [k for k in entry["evidence"] if evidence(now).get(k) != entry["evidence"][k]] + out["outcomes"].append({"result": "refused", "reason": "state changed since planning: " + ", ".join(changed)}) + continue + top, d, origin = Path(now["path"]), now["default"], now["origin_sha"] + out["before"] = {"head": now["head_sha"], d: now["local_default_sha"], "origin": origin} + digest = now["config_digest"] + for row in todo: + try: + result = execute(row, now, top, d, origin, backup_dir, out) + except (GitError, TimeoutError, OSError, UsageError) as exc: + result = {"result": "failed", "reason": str(exc)} + result["action"] = row["action"] + out["outcomes"].append(result) + after = config_digest(top) + if after != digest: + halted = f"git configuration changed during {row['action']} in {top}; all further writes stopped" + out["outcomes"].append({"result": "config-drift", "reason": halted, "before": digest, "after": after}) + break + if result["result"] != "ok": + break + out["after"] = {"head": rev(top, "HEAD"), d: rev(top, f"refs/heads/{d}")} + out["config_digest"] = config_digest(top) + return receipt + + +def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: str | None, out: dict) -> dict: + old = now["local_default_sha"] + if row["action"] in ("ff", "archive-ff", "ff-ref") and not git_ok(top, "merge-base", "--is-ancestor", old, origin): + return {"result": "refused", "reason": f"{d} is not an ancestor of origin/{d}"} + if row["action"] in ("archive-ff", "switch") and row.get("paths"): + archive(top, row["paths"], backup_dir, out) + if row["action"] in ("ff", "archive-ff"): + git(top, "merge", "--ff-only", "--no-stat", "--no-overwrite-ignore", origin, read_only=False) + if rev(top, "HEAD") != origin: + return {"result": "failed", "reason": "HEAD is not at the origin SHA after the merge"} + out["undo"].append(f"git -C \"{top}\" merge --ff-only is undone with: git -C \"{top}\" reset --keep {old}") + elif row["action"] == "ff-ref": + git(top, "update-ref", "-m", "fast-forward: ff-ref", f"refs/heads/{d}", origin, old, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {old} {origin}") + elif row["action"] == "switch": + cur = rev(top, f"refs/heads/{d}") + if cur and cur != origin and git_ok(top, "merge-base", "--is-ancestor", cur, origin): + git(top, "update-ref", "-m", "fast-forward: switch", f"refs/heads/{d}", origin, cur, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {cur} {origin}") + git(top, "switch", "--no-guess", "--no-overwrite-ignore", d, read_only=False) + out["undo"].append(f"git -C \"{top}\" switch {now['head_branch']}") + return {"result": "ok", "head": rev(top, "HEAD")} + + +def archive(top: Path, paths: list[str], backup_dir: str | None, out: dict) -> None: + if not backup_dir: + raise UsageError("archive rows need --backup-dir (a folder outside the repository)") + root = Path(backup_dir) + if inside(root, top): + raise UsageError("--backup-dir must be outside the repository") + dest_root = root / f"{top.name}-{time.strftime('%Y%m%d-%H%M%S')}" + for rel in paths: + src, dst = top / rel, dest_root / rel + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + if hashlib.sha256(src.read_bytes()).digest() != hashlib.sha256(dst.read_bytes()).digest(): + raise OSError(f"backup copy of {rel} does not match; nothing removed") + for rel in paths: + (top / rel).unlink() + out["archived"].append({"path": rel, "backup": str(dest_root / rel)}) + out["undo"].append(f"restore archived copies from {dest_root}") + + +# ---------------------------------------------------------------- CLI + +def collect(args) -> list[dict]: + paths = args.repo or ["."] + fetched = fetch_all(paths, args.timeout) if args.fetch else {} + return [inventory_repo(p, args.timeout, args.gh, fetched.get(p)) for p in paths] + + +def render(plan: dict) -> str: + lines = ["| Repo | Action | Why |", "|---|---|---|"] + for e in plan["repos"]: + for r in e["rows"]: + lines.append(f"| {Path(e['repo']).name} | {r['action']} | {r['reason']} |") + for n in e["notes"]: + lines.append(f"| {Path(e['repo']).name} | note | {n} |") + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="fast_forward.py", description=(__doc__ or "").splitlines()[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + for name in ("inventory", "plan"): + p = sub.add_parser(name) + p.add_argument("--repo", action="append") + p.add_argument("--fetch", action="store_true") + p.add_argument("--gh", action="store_true") + p.add_argument("--timeout", type=float, default=60) + p.add_argument("--json", action="store_true") + if name == "plan": + p.add_argument("--out") + p = sub.add_parser("apply") + p.add_argument("--plan", required=True) + p.add_argument("--backup-dir") + p.add_argument("--receipt") + try: + args = ap.parse_args(argv) + except SystemExit as exc: + return 2 if exc.code else 0 + try: + if args.cmd == "inventory": + print(json.dumps(collect(args), indent=2)) + return 0 + if args.cmd == "plan": + plan = build_plan(collect(args)) + text = json.dumps(plan, indent=2) + if args.out: + Path(args.out).write_text(text, encoding="utf-8") + print(text if args.json else render(plan)) + return 1 if any(r["action"] == "needs-human" for e in plan["repos"] for r in e["rows"]) else 0 + plan = json.loads(Path(args.plan).read_text(encoding="utf-8")) + receipt = apply_plan(plan, args.backup_dir) + text = json.dumps(receipt, indent=2) + if args.receipt: + Path(args.receipt).write_text(text, encoding="utf-8") + print(text) + bad = [o for r in receipt["repos"] for o in r["outcomes"] if o["result"] not in ("ok", "skipped")] + human = [r for e in plan["repos"] for r in e["rows"] if r["action"] == "needs-human"] + return 1 if bad or human else 0 + except UsageError as exc: + print(f"usage: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/flow-complete/SKILL.md b/.agents/skills/flow-complete/SKILL.md index 87c1eab..1d3877a 100644 --- a/.agents/skills/flow-complete/SKILL.md +++ b/.agents/skills/flow-complete/SKILL.md @@ -31,4 +31,5 @@ risk_class: medium ``` 6. **Submit.** Run `agent-flow submit `. It re-runs the DoD and moves the ticket to `review`. - `GATE_FAILED` tells you exactly what is missing. Fix it and submit again. + - Confirm it printed `Submitted for review` before asking for a review. `INVALID_TRANSITION` (the ticket is still `ready` because a dependency blocks it, or the lease lapsed) means re-claim or clear the blocker, then submit again. A reviewer started earlier can't get a review brief or approve, and a second one duplicates the review. 7. Report the PR URL and the ticket state. Do **not** approve your own ticket. A reviewer does that: `flow-review`, the `flow-reviewer` agent, the swarm, or a human. diff --git a/.agents/skills/flow-next/SKILL.md b/.agents/skills/flow-next/SKILL.md index 5254cf3..a9da4e8 100644 --- a/.agents/skills/flow-next/SKILL.md +++ b/.agents/skills/flow-next/SKILL.md @@ -25,6 +25,7 @@ Arguments: `$ARGUMENTS`, either a ticket id or filters like `--label agent-ok -- 4. **Set up the workspace on the returned `branch`.** - Single agent: `git switch -c `, or `git switch ` if it already exists. - Parallel agents: `agent-flow worktree create `, then work inside the printed path. Worktrees are created one at a time. + - Before editing, `git fetch` and `git merge --ff-only origin/` in the worktree, and diff against `origin/`. The worktree starts from the local base branch, which can be many commits behind, and diffs against it look far larger than the change. 5. **Load the context.** Run `agent-flow show ` and read: - the spec, - the scope paths, diff --git a/.agents/skills/git-and-diff-workflows/SKILL.md b/.agents/skills/git-and-diff-workflows/SKILL.md index 4e71c90..69ee897 100644 --- a/.agents/skills/git-and-diff-workflows/SKILL.md +++ b/.agents/skills/git-and-diff-workflows/SKILL.md @@ -62,6 +62,10 @@ gitleaks detect --source . --no-git -v 2>/dev/null | head -50 separate temporary worktree. Don't stash: `git stash` + `git stash pop` drops what you staged, including `git rm` deletions, so the next commit can come out empty. If you must stash, use `git stash pop --index`. Either way, confirm `git diff --cached --stat` shows your change before you commit. +- **Moving uncommitted changes to another worktree:** `git diff --output=`, then `git apply --3way `. + A shell redirect can re-encode the patch (PowerShell 5.1 writes UTF-16) or mix in `2>&1` warnings. +- **"Untracked working tree files would be overwritten":** back them up outside the repo, `cmp` each copy + (recopy if a live writer changed it), then remove and switch. Never `git clean` or `--force`: it may be the only copy. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). ## Commands Requiring Confirmation diff --git a/.agents/skills/merge-pr/SKILL.md b/.agents/skills/merge-pr/SKILL.md index cf788d7..2416654 100644 --- a/.agents/skills/merge-pr/SKILL.md +++ b/.agents/skills/merge-pr/SKILL.md @@ -207,19 +207,20 @@ Immediately before merging, re-read the PR and confirm: - the runs for `` still show the case from step 2: all green, only the not-started cause, the same mix of passed and not-started runs, or, when CI never triggered or there is none, still none. -Use the merge method the repository's recent PRs used, pinned to the checked commit: - **Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: `gh pr list --base --state open`. If there are any: - Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it does not retarget it. Retarget each child with `gh pr edit --base `, then delete the - branch. + branch. Retarget even when the branch stays: otherwise the child merges into the merged branch and + never reaches the base. - After a squash merge, each child conflicts with the base: git no longer sees the parent's commits as shared. Merge the base into the child, check that the result's tree equals the reviewed head (`git diff ` is empty when the base holds exactly the parent's tree), and gate the new head again. Prefer merge commits for a stack when the repository allows them. +Use the merge method the repository's recent PRs used, pinned to the checked commit: + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` @@ -274,7 +275,9 @@ why the workflow stopped triggering) or, with no CI, that there is none to run. ## Never -Leave these for the user, with a paste-ready command where one helps: +Leave these for the user, with a paste-ready command where one helps. A paste-ready +`gh pr merge --match-head-commit` takes the full 40-character `headRefOid`; a short SHA is rejected +("Could not coerce value ... to GitObjectID"). - Merging when any CI job actually ran and failed, or while runs are still pending. - Merging past a review that isn't approved, or with admin rights to get past branch protection. diff --git a/.agents/skills/ship-pr/SKILL.md b/.agents/skills/ship-pr/SKILL.md index 05a08e3..8f14ae2 100644 --- a/.agents/skills/ship-pr/SKILL.md +++ b/.agents/skills/ship-pr/SKILL.md @@ -130,7 +130,7 @@ Handle every failing job, one cause at a time. | Already broken on base | The base branch's latest run fails the same way | Stop and report | | Flaky test | Force the timing, and show it fail the same way | Fix the race in the test | | Infrastructure | The log shows a runner, network or quota error | One rerun, then stop (with `--no-ci`, step 2b) | -| Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | + | Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | 3. **Find the root cause before editing.** A test that passes locally and fails in CI is usually a race. Force it, for example by delaying a mock, and confirm the same error before changing anything. diff --git a/.agents/skills/skill-authoring/SKILL.md b/.agents/skills/skill-authoring/SKILL.md index ebded80..d154f58 100644 --- a/.agents/skills/skill-authoring/SKILL.md +++ b/.agents/skills/skill-authoring/SKILL.md @@ -166,3 +166,7 @@ When improving an existing skill, compare against the previous version and look - [ ] `python scripts/ci/check_agent_frontmatter.py` passes - [ ] `.agent/SKILL_INVENTORY.md` updated for new or materially changed skills - [ ] AST10 review considerations documented in the PR summary for material changes +- [ ] PR can't merge because `docs/agent-asset-inventory.md` conflicts with another skill PR: merge + `origin/main` into the branch, take either side of that file, run + `python scripts/generate_agent_asset_inventory.py` and its `--check`, then push without force. It's + generated, so don't hand-merge it. diff --git a/.agents/skills/test-driven-development/SKILL.md b/.agents/skills/test-driven-development/SKILL.md index 033e617..7da5cab 100644 --- a/.agents/skills/test-driven-development/SKILL.md +++ b/.agents/skills/test-driven-development/SKILL.md @@ -92,6 +92,8 @@ Avoid tests that: - Keep each red/green step small enough to explain in the final response. - If a failing test exposes an unrelated pre-existing issue, narrow the command or document the blocker before changing scope. +- **Proving a test catches a regression:** the mutated code must compile and fail on that test's assertion + (a compile error proves nothing); restore it and confirm `git status` is clean before claiming the result. ## Red flags diff --git a/.agents/skills/windows-agent-tooling/SKILL.md b/.agents/skills/windows-agent-tooling/SKILL.md index 05970af..6659154 100644 --- a/.agents/skills/windows-agent-tooling/SKILL.md +++ b/.agents/skills/windows-agent-tooling/SKILL.md @@ -72,7 +72,7 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws ## Agent-Safe Patterns - Avoid mixing `D:\` and `/mnt/d/` in one workflow. -- In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). +- In Git Bash, prefix `MSYS_NO_PATHCONV=1` when a non-Windows tool takes a Unix-style path that starts with `/`, since MSYS rewrites it into a Windows path (but see the next bullets: Git's own `-C` then needs `D:/...`). For example, `docker exec`/`docker run` with container paths (`-w /app`, `/data/...`) fails with "Cwd must be an absolute path". - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. - MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit diff --git a/.claude/skills/agent-setup/references/usage.md b/.claude/skills/agent-setup/references/usage.md index e9e13af..b69216b 100644 --- a/.claude/skills/agent-setup/references/usage.md +++ b/.claude/skills/agent-setup/references/usage.md @@ -24,12 +24,19 @@ Use the local receipt and subsequent plan as evidence; file installation alone d `plan` has no per-skill option. To take in one skill (for example after its PR merges), make the full plan, then keep only that skill's operations: -1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. +1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. When several checkouts or worktrees hold a ledger, use the one whose `targets/*.json` contains the skill's relative path (for example `.claude/skills//SKILL.md`). A ledger without the skill plans every copy as a conflict. 2. Write a copy of the plan that keeps only the operations whose `relative` path is under `//` for the four user skill trees (`.claude/skills`, `.agents/skills`, `.gemini/config/skills`, `.gemini/antigravity-cli/skills`). Update `summary` to match. 3. Have the user review that list, then `apply --input ` and `check --input `. This is safe because `apply` checks every operation it is given (library and installer hashes, the target root, the destination folder, the content hashes) without requiring the full list. Conflicts are skipped and recorded in the receipt. The ownership ledger merges, so other skills' entries stay. +**A conflict that isn't a local edit.** `apply` skips a copy with no ledger entry ("unmanaged or overlapping edit"), even when it equals an earlier library version. For each conflicting file in the skill's folder, `SKILL.md` and `references/` alike, compare it with that file's history (`git log -p -- .claude/skills//`), ignoring line endings. Note that the installer rewrites the frontmatter `name` for a renamed install. If every file matches a past version, it's a stale install, not the user's edit. Keep it in the ledger by going through `apply`: + +- Record it in `.agent/setup/library.json` in a reviewed PR, so `apply` adopts it with a backup, a receipt and a ledger entry. `SKILL.md` goes in `reviewed_global_adoptions`. Every other file (`references/`, scripts) goes in `reviewed_resource_adoptions`, one entry per installed path (`relative`, `sha256`, reason) in each tree that holds it. Or: +- with the user's approval, move the stale folder to a backup under `` (for example `/stale-backups/-/`); `apply` creates its own run folder later. The re-plan then reads `create`, and `apply` writes the files and records ownership. + +Writing the plan's content to the file by hand leaves it unmanaged, with no receipt or rollback, so the next library change to that skill conflicts again. Anything that matches no past version is the user's edit: leave it and report it. + ## Explicit MCP replacement Use this procedure when the user asks to replace one harness's MCP registrations with another's. The named harness is the source for that request, not a permanent default for future tasks. Replacement requires explicit user intent; ordinary synchronization stays additive. diff --git a/.claude/skills/cross-pc-ssh/SKILL.md b/.claude/skills/cross-pc-ssh/SKILL.md index b767e32..87ec22b 100644 --- a/.claude/skills/cross-pc-ssh/SKILL.md +++ b/.claude/skills/cross-pc-ssh/SKILL.md @@ -51,9 +51,12 @@ alone, and the guard then accepts exactly the boundary commits recorded when it 1. `ssh -n -o BatchMode=yes hostname` must print the peer's name. If it asks for a password or fails host-key verification, stop: setting up keys and known_hosts is the user's step, not this skill's. - If it times out, the alias's `HostName` may be a stale address (DHCP). Try the peer's hostname with the - pinned key, `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`, and pass - the same options as `--peer`. Fixing `~/.ssh/config` is the user's step. + If it times out, the alias's `HostName` may be a stale address (DHCP). To check by hostname with the + pinned key, first find the name `known_hosts` holds it under (`ssh-keygen -F `, then + `ssh-keygen -F `): ssh saves a key under the `HostName` unless `HostKeyAlias` is set. + Then run `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`. The helper's + `--peer` takes only an alias or `user@host`, with fixed ssh options, so before using the helper the + user updates `HostName` in `~/.ssh/config`. 2. `locate`. If it finds no checkout, the repository isn't cloned there (or lives outside the roots); say so rather than searching the peer's disks. diff --git a/.claude/skills/fast-forward/SKILL.md b/.claude/skills/fast-forward/SKILL.md new file mode 100644 index 0000000..52afa4b --- /dev/null +++ b/.claude/skills/fast-forward/SKILL.md @@ -0,0 +1,202 @@ +--- +name: fast-forward +description: "Bring the default branch of the current repository (or each repository the work touched) level with its remote with a deterministic inventory, plan and fast-forward-only apply (sync), and, when the user also asks to commit, push and merge, land the local work that belongs there (land): commit the intended tracked changes on a short-lived branch, push it, open a PR against the repository's own default branch, merge it pinned to the pushed commit, fast-forward the local default branch to the merge, and delete the branch. Leaves untracked and unrelated files alone. Runs only when the user types /fast-forward." +capability: "Sync a checkout's default branch with origin, fast-forward only; in land mode, also land its intended tracked changes through a pinned PR merge. Never by force or a direct push to the default branch." +side_effect_level: remote_write +approval_required: true +requires_tools: "python 3.9+ (stdlib only) for scripts/fast_forward.py, git, and gh authenticated for the repository's own remote." +output_schema: "The harness plan table and receipt JSON, then the default branch's position before and after (ahead/behind counts and short SHAs), what was committed (paths and the commit), the PR and its merge commit, the final ahead/behind of 0/0, and every file left untouched with the reason." +risk_class: medium +disable-model-invocation: true +--- + +# Fast-forward + +`/fast-forward` means: **make my default branch match the remote** (sync). Typed alone, it approves only +the sync: a fetch and fast-forward-only moves. When the typed request also says commit, push or merge +(land), it also approves one commit of the intended tracked changes, one push of a new branch, one PR and +its merge. It is not standing approval, and it never force-pushes, rewrites history or pushes straight to the +default branch. + +| Mode | What it does | Runs when | +|---|---|---| +| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward` alone, or with "catch up" or "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The typed request also says commit, push or merge | +| cleanup | Not run here: merged branches and worktrees are listed in the report only | Housekeeping, on its own request | + +A compound request ("fetch, pull, commit, push, merge, fast-forward") authorizes both modes for this run. +Permission to fast-forward a checkout is never permission to push to its default branch. + +How this differs from neighbours: +- `commit-and-push` commits and pushes a branch; it doesn't merge or fast-forward the default branch. +- `/merge-pr` and `/ship-pr` merge an existing PR on CI evidence. `/fast-forward` opens its own small PR + and merges it in the same run, so keep it for changes that need no review: tracker snapshots, + generated files, docs the user already approved. +- Syncing an upstream repository **into** a fork is a different job (some projects have their own + skill for it). `/fast-forward` only talks to the repository's own `origin`. +- `repo-inventory` compares checkouts across PCs and prints a plan it never runs. This skill is the + local executor; on a peer it only runs `inventory` and `plan` (see [references/details.md](references/details.md)). + +## 0. Scope and other sessions + +- **Scope:** the current repository, plus each repository this conversation changed, or the list the user + names. Never sweep a whole projects folder unasked. +- **Other sessions:** before any write, ask the live sessions working in these checkouts (`ListAgents`, + then `SendMessage`) and wait for "safe". If another session already took the same request, split the + repositories and send it what you found (EOL-only files, junk names, identical copies) so it doesn't redo it. + +## 1. Confirm the target + +- **The repository and its default branch.** Read `gh repo view --json nameWithOwner,defaultBranchRef` + for `origin`. In a fork, `gh` defaults to the parent repository, so name the repository on every + `gh` call (`--repo /`). If the project's notes name a read-only upstream, never write to it. +- **This checkout is on the default branch,** or can switch to it cleanly. If it's on another branch + with work in progress, stop and ask; that branch isn't yours to move. +- **Another session may share this checkout.** If one is active here (`ListAgents`, a held tracker ticket, + a running build), ask before switching branches. + +## 2. Fetch and fast-forward (sync) + +Use the harness. It calls git with argument lists (no shell, so no MSYS path rewriting), with prompts off +and a per-repo timeout, and it never edits `.git/config`: + +```bash +FF="/scripts/fast_forward.py" +python -I "$FF" plan --repo [--repo ]... --fetch [--gh] --out /ff-plan.json +python -I "$FF" apply --plan /ff-plan.json [--backup-dir ] --receipt /ff-receipt.json +``` + +| Row | Meaning | Who acts | +|---|---|---| +| `noop` | Already level, or nothing this skill may do | – | +| `ff` | `merge --ff-only` to the fetched SHA in the checkout holding the default branch; unrelated edits stay | apply | +| `ff-ref` | No worktree holds the default branch: `update-ref` with the expected old SHA | apply | +| `archive-ff` | Untracked or ignored files identical (git-normalized) to incoming ones: backed up, verified, removed, then `ff` | apply, with `--backup-dir` | +| `switch` | The current branch is merged (in origin's history, or with `--gh` a PR merged at this exact head) and clean | apply | +| `needs-human` | Diverged, local commits, overlapping edits, a different untracked or ignored file, the default branch checked out elsewhere, an operation in progress, a fetch that failed or timed out | you, with the user | + +- Show the plan table before `apply`. `apply` re-reads every repository first and refuses a row whose + HEAD, SHAs, holder, tracked changes or collision hashes moved since planning; re-plan instead of forcing. +- It compares the git configuration digest after each action and stops all writes on drift. Report a + drift; never restore or "fix" the configuration yourself. +- A timed-out fetch usually waits on a credential prompt. Report it as `needs-human: auth`. +- Without the harness (no Python), the manual rules are: + +```bash +git fetch origin +git rev-list --left-right --count HEAD...origin/ # " " +``` + +- **Behind only (`0 N`):** `git pull --ff-only origin `. Dirty tracked files are fine when the + incoming commits don't touch them. Check with `git log HEAD..origin/ -- ` first. + If they do touch them, stop and report the overlap; don't stash, reset or merge over someone's edits. +- **Ahead (`N 0` or `N M`):** local commits exist on the default branch. Don't push them directly. Move + them to the step-3 branch, or stop and ask if they aren't clearly the user's. `git switch -c ` + keeps the commits and the working tree, then `git branch -f --no-track origin/` moves only the + default branch's pointer back. Never use `git reset` for this: it can discard the dirty tracked files + this step allows. +- **Never** `git pull` without `--ff-only`, and never `--rebase` or `--force` on the default branch. +- **The default branch is checked out in another worktree:** fast-forward it there, only after its owner + says it is safe. Don't move a checked-out branch's ref behind its worktree's back. + +## 3. Commit the intended changes on a branch + +- **Decide what belongs.** List `git status --short`. Commit only tracked changes the user's request + covers, or that this run produced: a tracker snapshot, a regenerated file. Show the diff stat. +- **Untracked files stay untracked** unless the user names them. They are often local notes, exports, + device presets or machine config (`mcp_config.json`, `*.local.*`, `.env*`). List them in the report. +- **Secrets gate before the push:** scan the staged diff (`git diff --cached`) for tokens, keys, + machine-local paths and personal identities. A hit blocks the push. For a PUBLIC repository + (`gh repo view --json visibility`), follow `commit-and-push`'s public-repo checks too. +- Create the branch with `git switch --no-track -c `: `branch.autoSetupMerge=always` would otherwise + write tracking into `.git/config`. Name it `chore/-` (or the project's pattern, such as `af/-`). Stage + paths explicitly (`git add `, never `git add -A`), and commit with a Conventional Commit message + and the attribution lines the session asks for. +- Nothing to commit? Skip steps 3–5 and report that the default branch only fast-forwarded. + +## 4. Push and open the PR + +```bash +git push origin +gh pr create --repo / --base --head --title "" --body-file +``` + +Push without `-u`: an upstream setting writes branch tracking into `.git/config`. The body says what +changed and why it needs no review. Reference the ticket (`Refs `) when the +project tracks work. + +## 5. Merge pinned to the pushed commit + +- **Same gate as `/merge-pr`.** Poll the check state after the push (bounded, about ten minutes) rather than + sleeping a fixed time; zero runs on a repository with workflows is unknown, not green. Then + **every** run and check on the pushed SHA (`gh run list --commit `, plus the commit's + check-runs and status) must have completed green. Anything pending, failing or skipped-only, a + `mergeStateStatus` of `BLOCKED`, or a conflict means stop: hand it to `/ship-pr` or the user. If the + repository has CI but no run registered, or no CI at all, hand the merge to `/merge-pr`, which proves + that case and runs the checks locally. Don't merge on a guess. +- Check that the PR's `headRefOid` equals `git rev-parse HEAD`, so the merge lands exactly the commit + you checked. +- Use the method the repository's recent PRs used, pinned to the **full 40-character SHA** (a short SHA + is rejected): + + ```bash + gh pr merge --repo / --merge --delete-branch --match-head-commit $(git rev-parse HEAD) + ``` +- **"The merge commit cannot be cleanly created":** the default branch moved. Fetch, merge + `origin/` into the branch, and resolve the conflicts. Regenerate generated files rather than + hand-merging them. Re-run the checks, push (no force), then merge again on the new head. + +## 6. Fast-forward the local default branch + +```bash +git switch +git pull --ff-only origin +git rev-list --left-right --count HEAD...origin/ # must print "0 0" +git branch -d # -d, not -D: it must be merged +``` + +Compare `python -I "$FF" inventory`'s `config_digest` from before step 3 with one taken now; a change is a drift to +report, not to repair. `gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +already have deleted the local branch, so a failing `git branch -d` there is harmless. Check +`gh pr view --json state,mergeCommit` rather than trusting its exit code. + +## 7. After the fast-forward + +- `0 0` proves the refs match. It doesn't prove a clean tree, a rebuilt binary or a running new version. + Check what the repository deploys (a `dist/` the harness flags, binaries copied out of a build folder, + skills installed at user level, an npm-linked CLI) and report "source at X, installed at Y". Rebuild or + reinstall only within the request; for skills, hand the user the installer's plan. +- Replacing a binary that live sessions hold open fails until they exit: make it a "close sessions" item. +- Branches whose remote is `[gone]` and squash-merged branches (`gh pr list --state merged --head `) + go in the report as a list. Deleting them is cleanup, the user's call. +- **Retries:** after any failure, read the state (PR state, `git log`, the receipt) before trying again; a + remote merge can succeed while local cleanup fails. Re-plan, and never repeat a commit, a PR or a merge. + +## Report + +One row per repository (and per PC), same columns everywhere; rows with nothing to do collapse into one line +("9 repos already at origin"): + +| Repo | PC | Before | After | Action | Left for you | +|---|---|---|---|---|---| + +Then, for land: + +```markdown +**** is level with origin at (was ahead, behind). + +- Committed as on ; PR # merged as ; branch deleted. +- Left untouched: . +- Archived: backup>; config digest unchanged; deploy: . +``` + +## Never + +- Push directly to the default branch, force-push, rebase or reset a branch with others' work. +- Stash, discard or commit files the user didn't ask for, including untracked ones. +- Merge past a pending or failing required check, a `BLOCKED` state or a requested change. +- Open the PR against an upstream or parent repository the project treats as read-only. +- Delete a branch with `-D`, or delete a branch that isn't merged. +- Edit `.git/config`: no upstream tracking, no `git config`, no `remote set-url` for a moved + repository ("This repository moved" is harmless: GitHub redirects). +- Retry a command a permission layer refused in another form. Finish the rest and hand it over as a `!` command. diff --git a/.claude/skills/fast-forward/references/details.md b/.claude/skills/fast-forward/references/details.md new file mode 100644 index 0000000..17a1423 --- /dev/null +++ b/.claude/skills/fast-forward/references/details.md @@ -0,0 +1,41 @@ +# fast-forward: details + +Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Bash on Windows. + +## Checks that look green or red for the wrong reason + +- **Zero check runs is unknown.** A repository can have Actions enabled and active workflows yet no runs at + all. Look at `gh run list --commit ` and the repository's runs, not only the PR's check list. + `gh pr checks` exits non-zero while checks are pending: that means wait. +- **Classify a failure from the job log:** a repository setting (for example dependency review on a + repository without the dependency graph), an infrastructure error, or a real failure. Only a real + failure belongs to the PR. If the default branch's own latest run fails the same way, report it as + already broken on the base; the PR can't fix it. + +## Across PCs + +- On a peer, run only `inventory` and `plan`, over `cross-pc-ssh` or as a `cross-pc-messages` request. + The plan goes back to that PC's agent with exact commands; its owner approves its own `apply`. +- Reach peers by hostname and pin the host key alias (`ssh -o HostKeyAlias= `), so a + stale address doesn't look like "host unreachable". +- The same repository sits under different folders, drive letters or as a shallow clone on each PC. Match + it by normalized origin and root commits, as `cross-pc-ssh` does, never by folder name. +- After a default branch moves, offer to draft the note telling the peers to fast-forward too. Sending it + is the user's call. +- Fetch in parallel; move refs one repository at a time, so the report and undo stay in order. + +## Windows + +- Under Git Bash, `git show origin/:` has its argument rewritten into a Windows path. Set + `MSYS_NO_PATHCONV=1` for such manual commands; the harness avoids it by never using a shell. +- Compare with carriage returns stripped (`git diff --ignore-cr-at-eol --numstat`); otherwise every mirror + regenerated on Windows looks modified. The harness reports line-ending-only edits as a note. +- A hung `git.exe` (credential helper) outlives a client timeout. The harness starts each git call in its + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). + +## Generated snapshots + +A tracker snapshot such as `.agent-flow/tickets.jsonl` that both sides changed is not a merge by +timestamp. Use the tracker's own export or import, within the task's scope; otherwise it is a +`needs-human` item. Build output that appears after a local test run (`*.egg-info/`, `__pycache__/`, +`target/`) is worth one suggested `.gitignore` line, not a listing every run. diff --git a/.claude/skills/fast-forward/scripts/fast_forward.py b/.claude/skills/fast-forward/scripts/fast_forward.py new file mode 100644 index 0000000..9abfa97 --- /dev/null +++ b/.claude/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,576 @@ +#!/usr/bin/env python3 +"""Fast-forward local default branches to origin, deterministically and without editing .git/config. + +Commands: + inventory [--repo DIR]... [--fetch] [--gh] [--timeout 60] [--json] + Read-only facts per repository: the default branch (origin/HEAD, else main, else master) and its origin + SHA, the local default branch and where it is checked out, HEAD, ahead/behind, upstream, an operation in + progress, tracked changes split into real and line-ending-only edits, untracked or ignored files the incoming + commits would overwrite (each compared with the incoming blob, path-aware), a stale-build hint and a + digest of the git configuration files. --fetch runs "git fetch --prune origin" first (in parallel, + no prompts, per-repo timeout); that is the only write. --gh asks gh whether the current branch's + exact head was merged as a PR (squash merges). + plan [--repo DIR]... [--fetch] [--gh] [--out FILE] [--json] + Rule-based actions per repository, each with its reason: + noop level with origin already + ff git merge --ff-only in the checkout that holds the default branch + ff-ref git update-ref on the default branch when no worktree holds it (expected old SHA) + archive-ff untracked files identical to the incoming ones: back them up, verify, remove, then ff + switch the current branch is merged and the tree is clean: switch to the (advanced) default + needs-human anything else (diverged, local commits, overlap, different untracked file, occupied + default branch, operation in progress, fetch timeout or auth), never executed + apply --plan FILE [--backup-dir DIR] [--receipt FILE] + Runs only ff, ff-ref, archive-ff and switch rows. Before each repository it re-reads the evidence + (HEAD, default and origin SHAs, holder, tracked changes, collision hashes) and refuses a stale row. + It checks the config digest after every action and stops all further writes when it drifts. Prints a + receipt (old and new SHAs, archived files, undo commands). Never fetches, stashes, resets, rebases, + force-pushes, deletes branches or runs "git config". + +Exit codes: 0 nothing left for a human, 1 a needs-human, refused or failed row, 2 usage error. +Stdlib only; git is always called with an argument list, never through a shell. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +SCHEMA = "fast-forward-plan" +SCHEMA_VERSION = 1 +EXECUTABLE = ("ff", "ff-ref", "archive-ff", "switch") +GIT_CFG = ["-c", "core.quotepath=off", "-c", "color.ui=never", "-c", "core.fsmonitor=false"] +OPERATIONS = (("MERGE_HEAD", "merge"), ("rebase-merge", "rebase"), ("rebase-apply", "rebase"), + ("CHERRY_PICK_HEAD", "cherry-pick"), ("REVERT_HEAD", "revert"), ("BISECT_LOG", "bisect")) +# Names a broken shell redirect tends to leave behind ("2>&1", "-o", "nul", "=1.2"): reported, never removed. +JUNK = re.compile(r"(^-|^=|^(nul|con|prn|aux)(\..*)?$|&1$|^\d$)", re.IGNORECASE) + + +class UsageError(Exception): + pass + + +class GitError(Exception): + pass + + +def git_env(read_only: bool = True) -> dict: + env = dict(os.environ) + env.update({"GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never", "GIT_ASKPASS": "", + "SSH_ASKPASS": "", "LC_ALL": "C"}) + env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes") + if read_only: + env["GIT_OPTIONAL_LOCKS"] = "0" + return env + + +def _kill_tree(proc: subprocess.Popen) -> None: + """Stop git and the helpers it started (credential managers, ssh), not only the direct child.""" + try: + if os.name == "nt": + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, check=False) + else: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + + +def run(cmd: list[str], cwd: str | Path, timeout: float = 60, read_only: bool = True) -> subprocess.CompletedProcess: + proc = subprocess.Popen(cmd, cwd=str(cwd), env=git_env(read_only), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + start_new_session=os.name != "nt") + try: + out, err = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _kill_tree(proc) + proc.communicate() + raise TimeoutError(f"{' '.join(cmd[:3])} timed out after {timeout:.0f}s") + return subprocess.CompletedProcess(cmd, proc.returncode, out.decode("utf-8", "replace"), + err.decode("utf-8", "replace")) + + +def git(repo: str | Path, *args: str, timeout: float = 60, check: bool = True, read_only: bool = True) -> str: + cp = run(["git", *GIT_CFG, *args], repo, timeout, read_only) + if check and cp.returncode != 0: + raise GitError(f"git {' '.join(args[:3])}: {cp.stderr.strip()[:300]}") + return cp.stdout + + +def git_ok(repo, *args, timeout: float = 60) -> bool: + return run(["git", *GIT_CFG, *args], repo, timeout).returncode == 0 + + +def rev(repo, ref: str) -> str | None: + cp = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", ref + "^{commit}"], repo) + return cp.stdout.strip() or None if cp.returncode == 0 else None + + +def norm(path: str | Path) -> str: + return os.path.normcase(os.path.normpath(str(Path(path).resolve()))) + + +# ---------------------------------------------------------------- configuration digest + +def config_files(repo: str | Path) -> list[Path]: + common = Path(repo, git(repo, "rev-parse", "--git-common-dir").strip()).resolve() + files = [common / "config"] + files += sorted((common / "worktrees").glob("*/config.worktree")) + if (common / "config.worktree").exists(): + files.append(common / "config.worktree") + return files + + +def config_digest(repo: str | Path) -> str: + h = hashlib.sha256() + for f in config_files(repo): + h.update(f.name.encode() + b"\0" + str(f.parent.name).encode() + b"\0") + h.update(f.read_bytes() if f.exists() else b"") + h.update(b"\0") + return h.hexdigest() + + +# ---------------------------------------------------------------- inventory + +def parse_status(raw: str) -> tuple[list[dict], list[str]]: + """git status --porcelain=v1 -z --untracked-files=all -> (tracked changes, untracked paths).""" + tracked, untracked = [], [] + parts = raw.split("\0") + i = 0 + while i < len(parts): + entry = parts[i] + i += 1 + if len(entry) < 4: + continue + xy, path = entry[:2], entry[3:] + if xy == "??": + untracked.append(path) + continue + if xy == "!!": + continue + item = {"path": path, "xy": xy, "staged": xy[0] not in " ?", "unmerged": "U" in xy or xy in ("AA", "DD")} + if xy[0] in "RC": + item["from"] = parts[i] if i < len(parts) else "" + i += 1 + tracked.append(item) + return tracked, untracked + + +def real_edits(repo) -> set[str]: + """Paths whose diff against HEAD is more than line endings (--name-only ignores --ignore-cr-at-eol).""" + out = set() + for line in git(repo, "diff", "--ignore-cr-at-eol", "--numstat", "--no-renames", "HEAD").splitlines(): + added, deleted, path = line.split("\t", 2) + if (added, deleted) != ("0", "0"): + out.add(path) + return out + + +def worktrees(repo) -> list[dict]: + out, cur = [], {} + for line in git(repo, "worktree", "list", "--porcelain").splitlines() + [""]: + if not line: + if cur: + out.append(cur) + cur = {} + elif line.startswith("worktree "): + cur["path"] = line[9:] + elif line.startswith("HEAD "): + cur["head"] = line[5:] + elif line.startswith("branch "): + cur["branch"] = line[7:] + elif line in ("bare", "detached", "locked", "prunable") or line.startswith(("locked ", "prunable ")): + cur[line.split(" ")[0]] = True + return out + + +def default_branch(repo) -> str | None: + cp = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], repo) + if cp.returncode == 0 and cp.stdout.strip().startswith("refs/remotes/origin/"): + return cp.stdout.strip()[len("refs/remotes/origin/"):] + for name in ("main", "master"): + if rev(repo, f"refs/remotes/origin/{name}"): + return name + return None + + +def origin_slug(repo) -> str | None: + cp = run(["git", *GIT_CFG, "remote", "get-url", "origin"], repo) + m = re.search(r"[/:]([^/:]+)/([^/]+?)(\.git)?/?$", cp.stdout.strip()) if cp.returncode == 0 else None + return f"{m.group(1)}/{m.group(2)}" if m else None + + +def gh_command() -> list[str]: + raw = os.environ.get("FAST_FORWARD_GH", "gh") + return json.loads(raw) if raw.startswith("[") else [raw] + + +def merged_pr_at_head(repo, branch: str, head_sha: str, timeout: float) -> dict | None: + slug = origin_slug(repo) + if not slug: + return None + try: + cp = run([*gh_command(), "pr", "list", "--repo", slug, "--state", "merged", "--head", branch, + "--json", "number,headRefOid,url"], repo, timeout) + except (OSError, TimeoutError): + return None + if cp.returncode != 0: + return None + for pr in json.loads(cp.stdout or "[]"): + if pr.get("headRefOid") == head_sha: # a PR merged earlier does not cover later commits + return {"number": pr.get("number"), "url": pr.get("url")} + return None + + +def build_hint(top: Path, origin_time: int | None) -> str | None: + pkg = top / "package.json" + dist = top / "dist" + try: + scripts = json.loads(pkg.read_text(encoding="utf-8")).get("scripts", {}) if pkg.exists() else {} + except (ValueError, OSError): + return None + if "build" in scripts and dist.is_dir() and origin_time and dist.stat().st_mtime < origin_time: + return "dist/ is older than the default branch tip: run the project's build before calling it deployed" + return None + + +def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, + fetched: dict | None = None) -> dict: + rec: dict = {"input": str(path)} + try: + top = Path(git(path, "rev-parse", "--show-toplevel", timeout=timeout).strip()).resolve() + rec["path"] = str(top) + rec["git_dir"] = str(Path(top, git(top, "rev-parse", "--git-dir").strip()).resolve()) + rec["config_digest"] = config_digest(top) + if fetched: + rec["fetch"] = fetched + d = default_branch(top) + rec["default"] = d + sym = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "HEAD"], top) + rec["head_branch"] = sym.stdout.strip()[len("refs/heads/"):] if sym.returncode == 0 else None + rec["head_sha"] = rev(top, "HEAD") + up = run(["git", *GIT_CFG, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], top) + rec["upstream"] = up.stdout.strip() if up.returncode == 0 else None + rec["operation"] = next((name for marker, name in OPERATIONS if Path(rec["git_dir"], marker).exists()), None) + tracked, untracked = parse_status(git(top, "status", "--porcelain=v1", "-z", "--untracked-files=all")) + real = real_edits(top) if rec["head_sha"] else set() + for item in tracked: + item["eol_only"] = (not item["staged"] and not item["unmerged"] and item["xy"] == " M" + and item["path"] not in real) + rec["tracked"] = tracked + rec["untracked"] = untracked + rec["junk_suspects"] = [u for u in untracked if JUNK.search(Path(u).name)] + rec["worktrees"] = worktrees(top) + if not d: + return rec + rec["origin_sha"] = rev(top, f"refs/remotes/origin/{d}") + rec["local_default_sha"] = rev(top, f"refs/heads/{d}") + rec["holder"] = next((w["path"] for w in rec["worktrees"] if w.get("branch") == f"refs/heads/{d}"), None) + if rec["origin_sha"] and rec["local_default_sha"]: + a, b = git(top, "rev-list", "--left-right", "--count", + f"{rec['local_default_sha']}...{rec['origin_sha']}").split() + rec["ahead"], rec["behind"] = int(a), int(b) + if rec["origin_sha"] and rec["head_sha"]: + incoming = set(filter(None, git(top, "diff", "--name-only", "-z", "--no-renames", + rec["head_sha"], rec["origin_sha"]).split("\0"))) + rec["incoming_paths"] = len(incoming) + rec["overlap"] = sorted(t["path"] for t in tracked if t["path"] in incoming or t.get("from") in incoming) + # Untracked and ignored files alike: a fast-forward overwrites ignored files without asking. + indexed = set(filter(None, git(top, "ls-files", "-z").split("\0"))) + rec["collisions"] = [collision(top, p, rec["origin_sha"]) for p in sorted(incoming) + if p not in indexed and (top / p).is_file()] + rec["head_merged"] = bool(rec["head_branch"] and rec["head_branch"] != d + and git_ok(top, "merge-base", "--is-ancestor", rec["head_sha"], rec["origin_sha"])) + if use_gh and rec["head_branch"] and rec["head_branch"] != d and not rec["head_merged"]: + rec["merged_pr"] = merged_pr_at_head(top, rec["head_branch"], rec["head_sha"], timeout) + t = git(top, "log", "-1", "--format=%ct", rec["origin_sha"]).strip() + rec["build_hint"] = build_hint(top, int(t) if t.isdigit() else None) + except (GitError, TimeoutError, OSError) as exc: + rec["error"] = str(exc) + return rec + + +def collision(top: Path, rel: str, origin_sha: str) -> dict: + local = git(top, "hash-object", f"--path={rel}", "--", str(top / rel)).strip() + blob = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", f"{origin_sha}:{rel}"], top).stdout.strip() + raw = hashlib.sha256((top / rel).read_bytes()).hexdigest() + return {"path": rel, "local_blob": local, "incoming_blob": blob or None, "sha256": raw, "same": bool(blob) and local == blob} + + +def fetch_all(paths: list[str], timeout: float) -> dict[str, dict]: + def one(p: str) -> tuple[str, dict]: + try: + before = rev(p, "refs/remotes/origin/HEAD") + cp = run(["git", *GIT_CFG, "fetch", "--prune", "origin"], p, timeout, read_only=False) + if cp.returncode != 0: + return p, {"ok": False, "error": cp.stderr.strip()[:300] or "fetch failed"} + return p, {"ok": True, "origin_head_before": before} + except (TimeoutError, OSError) as exc: + return p, {"ok": False, "error": f"{exc} (auth prompt or network; check credentials by hand)"} + with ThreadPoolExecutor(max_workers=min(8, max(1, len(paths)))) as pool: + return dict(pool.map(one, paths)) + + +# ---------------------------------------------------------------- plan (pure) + +def plan_repo(rec: dict) -> list[dict]: + def human(reason: str) -> list[dict]: + return [{"action": "needs-human", "reason": reason}] + if rec.get("error"): + return human(f"inventory failed: {rec['error']}") + if rec.get("fetch") and not rec["fetch"].get("ok"): + return human(f"fetch failed: {rec['fetch'].get('error')}") + d = rec.get("default") + if not d or not rec.get("origin_sha"): + return human("no origin default branch found (origin/HEAD, main or master)") + if rec.get("operation"): + return human(f"a {rec['operation']} is in progress here") + if any(t["unmerged"] for t in rec["tracked"]): + return human("unmerged paths") + rows: list[dict] = [] + if not rec.get("local_default_sha"): + rows.append({"action": "noop", "reason": f"no local {d} branch; creating one is not this skill's job"}) + return rows + ahead, behind = rec.get("ahead", 0), rec.get("behind", 0) + if ahead and behind: + return human(f"{d} diverged from origin ({ahead} ahead, {behind} behind): needs a reviewed preservation plan") + if ahead: + return human(f"{d} has {ahead} local commit(s) not on origin: land them through a PR (land mode), don't push") + here = rec.get("holder") and norm(rec["holder"]) == norm(rec["path"]) + real = [t["path"] for t in rec["tracked"] if not t["eol_only"]] + differ = [c["path"] for c in rec.get("collisions", []) if not c["same"]] + same = [c["path"] for c in rec.get("collisions", []) if c["same"]] + on_branch = rec.get("head_branch") and rec["head_branch"] != d + switchable = on_branch and not rec.get("holder") and (rec.get("head_merged") or rec.get("merged_pr")) \ + and not rec["tracked"] + if behind: + if rec.get("holder") and not here: + return human(f"{d} is checked out in another worktree ({rec['holder']}): fast-forward it there, " + "after its owner says it is safe") + if here: + if rec["overlap"]: + return human("local changes overlap incoming commits: " + ", ".join(rec["overlap"][:10])) + if differ: + return human("untracked files differ from incoming ones: " + ", ".join(differ[:10])) + if same: + rows.append({"action": "archive-ff", "reason": f"fast-forward {behind}; {len(same)} untracked " + "file(s) are byte-identical (git-normalized) to incoming ones", "paths": same}) + else: + rows.append({"action": "ff", "reason": f"fast-forward {behind} commit(s)" + + (f"; {len(real)} unrelated local edit(s) stay" if real else "")}) + else: + rows.append({"action": "ff-ref", "reason": f"{d} is not checked out anywhere: move it {behind} commit(s)"}) + if switchable: + if differ: + rows.append({"action": "needs-human", "reason": "untracked files differ from incoming ones: " + + ", ".join(differ[:10])}) + else: + how = "its head is in origin" if rec.get("head_merged") else f"PR #{rec['merged_pr']['number']} merged at this head" + rows.append({"action": "switch", "reason": f"{rec['head_branch']} is merged ({how}) and clean", + "paths": same}) + elif on_branch and not rows: + rows.append({"action": "noop", "reason": f"on {rec['head_branch']} (not merged or not clean); " + f"{d} is level with origin"}) + if not rows: + rows.append({"action": "noop", "reason": f"{d} is level with origin"}) + return rows + + +EVIDENCE = ("path", "head_branch", "head_sha", "local_default_sha", "origin_sha", "holder", "config_digest") + + +def evidence(rec: dict) -> dict: + ev = {k: rec.get(k) for k in EVIDENCE} + ev["tracked"] = sorted(f"{t['xy']} {t['path']}" for t in rec.get("tracked", [])) + ev["collisions"] = sorted(f"{c['path']} {c['sha256']}" for c in rec.get("collisions", [])) + return ev + + +def build_plan(recs: list[dict]) -> dict: + repos = [] + for rec in recs: + rows = plan_repo(rec) + repos.append({"repo": rec.get("path") or rec["input"], "default": rec.get("default"), "rows": rows, + "evidence": evidence(rec), "notes": [n for n in (rec.get("build_hint"),) if n] + + ([f"junk-looking untracked names (left alone): {', '.join(rec['junk_suspects'][:5])}"] + if rec.get("junk_suspects") else []) + + ([f"{sum(t['eol_only'] for t in rec['tracked'])} line-ending-only change(s)"] + if any(t.get("eol_only") for t in rec.get("tracked", [])) else [])}) + return {"schema": SCHEMA, "schema_version": SCHEMA_VERSION, "created": int(time.time()), "repos": repos} + + +# ---------------------------------------------------------------- apply + +def inside(child: Path, parent: Path) -> bool: + try: + child.resolve().relative_to(parent.resolve()) + return True + except ValueError: + return False + + +def apply_plan(plan: dict, backup_dir: str | None) -> dict: + if plan.get("schema") != SCHEMA or plan.get("schema_version") != SCHEMA_VERSION: + raise UsageError("not a fast-forward plan (schema mismatch)") + if not backup_dir and any(r["action"] in ("archive-ff", "switch") and r.get("paths") + for e in plan["repos"] for r in e["rows"]): + raise UsageError("archive rows need --backup-dir (a folder outside the repository); nothing ran") + receipt = {"schema": "fast-forward-receipt", "plan_created": plan.get("created"), "repos": []} + halted: str | None = None + for entry in plan["repos"]: + out = {"repo": entry["repo"], "outcomes": [], "archived": [], "undo": []} + receipt["repos"].append(out) + todo = [r for r in entry["rows"] if r["action"] in EXECUTABLE] + if not todo: + out["outcomes"] = [{"action": r["action"], "result": "skipped", "reason": r["reason"]} for r in entry["rows"]] + continue + if halted: + out["outcomes"].append({"result": "refused", "reason": halted}) + continue + now = inventory_repo(entry["repo"]) + if evidence(now) != entry["evidence"]: + changed = [k for k in entry["evidence"] if evidence(now).get(k) != entry["evidence"][k]] + out["outcomes"].append({"result": "refused", "reason": "state changed since planning: " + ", ".join(changed)}) + continue + top, d, origin = Path(now["path"]), now["default"], now["origin_sha"] + out["before"] = {"head": now["head_sha"], d: now["local_default_sha"], "origin": origin} + digest = now["config_digest"] + for row in todo: + try: + result = execute(row, now, top, d, origin, backup_dir, out) + except (GitError, TimeoutError, OSError, UsageError) as exc: + result = {"result": "failed", "reason": str(exc)} + result["action"] = row["action"] + out["outcomes"].append(result) + after = config_digest(top) + if after != digest: + halted = f"git configuration changed during {row['action']} in {top}; all further writes stopped" + out["outcomes"].append({"result": "config-drift", "reason": halted, "before": digest, "after": after}) + break + if result["result"] != "ok": + break + out["after"] = {"head": rev(top, "HEAD"), d: rev(top, f"refs/heads/{d}")} + out["config_digest"] = config_digest(top) + return receipt + + +def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: str | None, out: dict) -> dict: + old = now["local_default_sha"] + if row["action"] in ("ff", "archive-ff", "ff-ref") and not git_ok(top, "merge-base", "--is-ancestor", old, origin): + return {"result": "refused", "reason": f"{d} is not an ancestor of origin/{d}"} + if row["action"] in ("archive-ff", "switch") and row.get("paths"): + archive(top, row["paths"], backup_dir, out) + if row["action"] in ("ff", "archive-ff"): + git(top, "merge", "--ff-only", "--no-stat", "--no-overwrite-ignore", origin, read_only=False) + if rev(top, "HEAD") != origin: + return {"result": "failed", "reason": "HEAD is not at the origin SHA after the merge"} + out["undo"].append(f"git -C \"{top}\" merge --ff-only is undone with: git -C \"{top}\" reset --keep {old}") + elif row["action"] == "ff-ref": + git(top, "update-ref", "-m", "fast-forward: ff-ref", f"refs/heads/{d}", origin, old, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {old} {origin}") + elif row["action"] == "switch": + cur = rev(top, f"refs/heads/{d}") + if cur and cur != origin and git_ok(top, "merge-base", "--is-ancestor", cur, origin): + git(top, "update-ref", "-m", "fast-forward: switch", f"refs/heads/{d}", origin, cur, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {cur} {origin}") + git(top, "switch", "--no-guess", "--no-overwrite-ignore", d, read_only=False) + out["undo"].append(f"git -C \"{top}\" switch {now['head_branch']}") + return {"result": "ok", "head": rev(top, "HEAD")} + + +def archive(top: Path, paths: list[str], backup_dir: str | None, out: dict) -> None: + if not backup_dir: + raise UsageError("archive rows need --backup-dir (a folder outside the repository)") + root = Path(backup_dir) + if inside(root, top): + raise UsageError("--backup-dir must be outside the repository") + dest_root = root / f"{top.name}-{time.strftime('%Y%m%d-%H%M%S')}" + for rel in paths: + src, dst = top / rel, dest_root / rel + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + if hashlib.sha256(src.read_bytes()).digest() != hashlib.sha256(dst.read_bytes()).digest(): + raise OSError(f"backup copy of {rel} does not match; nothing removed") + for rel in paths: + (top / rel).unlink() + out["archived"].append({"path": rel, "backup": str(dest_root / rel)}) + out["undo"].append(f"restore archived copies from {dest_root}") + + +# ---------------------------------------------------------------- CLI + +def collect(args) -> list[dict]: + paths = args.repo or ["."] + fetched = fetch_all(paths, args.timeout) if args.fetch else {} + return [inventory_repo(p, args.timeout, args.gh, fetched.get(p)) for p in paths] + + +def render(plan: dict) -> str: + lines = ["| Repo | Action | Why |", "|---|---|---|"] + for e in plan["repos"]: + for r in e["rows"]: + lines.append(f"| {Path(e['repo']).name} | {r['action']} | {r['reason']} |") + for n in e["notes"]: + lines.append(f"| {Path(e['repo']).name} | note | {n} |") + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="fast_forward.py", description=(__doc__ or "").splitlines()[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + for name in ("inventory", "plan"): + p = sub.add_parser(name) + p.add_argument("--repo", action="append") + p.add_argument("--fetch", action="store_true") + p.add_argument("--gh", action="store_true") + p.add_argument("--timeout", type=float, default=60) + p.add_argument("--json", action="store_true") + if name == "plan": + p.add_argument("--out") + p = sub.add_parser("apply") + p.add_argument("--plan", required=True) + p.add_argument("--backup-dir") + p.add_argument("--receipt") + try: + args = ap.parse_args(argv) + except SystemExit as exc: + return 2 if exc.code else 0 + try: + if args.cmd == "inventory": + print(json.dumps(collect(args), indent=2)) + return 0 + if args.cmd == "plan": + plan = build_plan(collect(args)) + text = json.dumps(plan, indent=2) + if args.out: + Path(args.out).write_text(text, encoding="utf-8") + print(text if args.json else render(plan)) + return 1 if any(r["action"] == "needs-human" for e in plan["repos"] for r in e["rows"]) else 0 + plan = json.loads(Path(args.plan).read_text(encoding="utf-8")) + receipt = apply_plan(plan, args.backup_dir) + text = json.dumps(receipt, indent=2) + if args.receipt: + Path(args.receipt).write_text(text, encoding="utf-8") + print(text) + bad = [o for r in receipt["repos"] for o in r["outcomes"] if o["result"] not in ("ok", "skipped")] + human = [r for e in plan["repos"] for r in e["rows"] if r["action"] == "needs-human"] + return 1 if bad or human else 0 + except UsageError as exc: + print(f"usage: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/skills/flow-complete/SKILL.md b/.claude/skills/flow-complete/SKILL.md index 87c1eab..1d3877a 100644 --- a/.claude/skills/flow-complete/SKILL.md +++ b/.claude/skills/flow-complete/SKILL.md @@ -31,4 +31,5 @@ risk_class: medium ``` 6. **Submit.** Run `agent-flow submit `. It re-runs the DoD and moves the ticket to `review`. - `GATE_FAILED` tells you exactly what is missing. Fix it and submit again. + - Confirm it printed `Submitted for review` before asking for a review. `INVALID_TRANSITION` (the ticket is still `ready` because a dependency blocks it, or the lease lapsed) means re-claim or clear the blocker, then submit again. A reviewer started earlier can't get a review brief or approve, and a second one duplicates the review. 7. Report the PR URL and the ticket state. Do **not** approve your own ticket. A reviewer does that: `flow-review`, the `flow-reviewer` agent, the swarm, or a human. diff --git a/.claude/skills/flow-next/SKILL.md b/.claude/skills/flow-next/SKILL.md index 5254cf3..a9da4e8 100644 --- a/.claude/skills/flow-next/SKILL.md +++ b/.claude/skills/flow-next/SKILL.md @@ -25,6 +25,7 @@ Arguments: `$ARGUMENTS`, either a ticket id or filters like `--label agent-ok -- 4. **Set up the workspace on the returned `branch`.** - Single agent: `git switch -c `, or `git switch ` if it already exists. - Parallel agents: `agent-flow worktree create `, then work inside the printed path. Worktrees are created one at a time. + - Before editing, `git fetch` and `git merge --ff-only origin/` in the worktree, and diff against `origin/`. The worktree starts from the local base branch, which can be many commits behind, and diffs against it look far larger than the change. 5. **Load the context.** Run `agent-flow show ` and read: - the spec, - the scope paths, diff --git a/.claude/skills/git-and-diff-workflows/SKILL.md b/.claude/skills/git-and-diff-workflows/SKILL.md index 4e71c90..69ee897 100644 --- a/.claude/skills/git-and-diff-workflows/SKILL.md +++ b/.claude/skills/git-and-diff-workflows/SKILL.md @@ -62,6 +62,10 @@ gitleaks detect --source . --no-git -v 2>/dev/null | head -50 separate temporary worktree. Don't stash: `git stash` + `git stash pop` drops what you staged, including `git rm` deletions, so the next commit can come out empty. If you must stash, use `git stash pop --index`. Either way, confirm `git diff --cached --stat` shows your change before you commit. +- **Moving uncommitted changes to another worktree:** `git diff --output=`, then `git apply --3way `. + A shell redirect can re-encode the patch (PowerShell 5.1 writes UTF-16) or mix in `2>&1` warnings. +- **"Untracked working tree files would be overwritten":** back them up outside the repo, `cmp` each copy + (recopy if a live writer changed it), then remove and switch. Never `git clean` or `--force`: it may be the only copy. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). ## Commands Requiring Confirmation diff --git a/.claude/skills/merge-pr/SKILL.md b/.claude/skills/merge-pr/SKILL.md index cf788d7..2416654 100644 --- a/.claude/skills/merge-pr/SKILL.md +++ b/.claude/skills/merge-pr/SKILL.md @@ -207,19 +207,20 @@ Immediately before merging, re-read the PR and confirm: - the runs for `` still show the case from step 2: all green, only the not-started cause, the same mix of passed and not-started runs, or, when CI never triggered or there is none, still none. -Use the merge method the repository's recent PRs used, pinned to the checked commit: - **Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: `gh pr list --base --state open`. If there are any: - Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it does not retarget it. Retarget each child with `gh pr edit --base `, then delete the - branch. + branch. Retarget even when the branch stays: otherwise the child merges into the merged branch and + never reaches the base. - After a squash merge, each child conflicts with the base: git no longer sees the parent's commits as shared. Merge the base into the child, check that the result's tree equals the reviewed head (`git diff ` is empty when the base holds exactly the parent's tree), and gate the new head again. Prefer merge commits for a stack when the repository allows them. +Use the merge method the repository's recent PRs used, pinned to the checked commit: + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` @@ -274,7 +275,9 @@ why the workflow stopped triggering) or, with no CI, that there is none to run. ## Never -Leave these for the user, with a paste-ready command where one helps: +Leave these for the user, with a paste-ready command where one helps. A paste-ready +`gh pr merge --match-head-commit` takes the full 40-character `headRefOid`; a short SHA is rejected +("Could not coerce value ... to GitObjectID"). - Merging when any CI job actually ran and failed, or while runs are still pending. - Merging past a review that isn't approved, or with admin rights to get past branch protection. diff --git a/.claude/skills/ship-pr/SKILL.md b/.claude/skills/ship-pr/SKILL.md index 05a08e3..8f14ae2 100644 --- a/.claude/skills/ship-pr/SKILL.md +++ b/.claude/skills/ship-pr/SKILL.md @@ -130,7 +130,7 @@ Handle every failing job, one cause at a time. | Already broken on base | The base branch's latest run fails the same way | Stop and report | | Flaky test | Force the timing, and show it fail the same way | Fix the race in the test | | Infrastructure | The log shows a runner, network or quota error | One rerun, then stop (with `--no-ci`, step 2b) | -| Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | + | Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | 3. **Find the root cause before editing.** A test that passes locally and fails in CI is usually a race. Force it, for example by delaying a mock, and confirm the same error before changing anything. diff --git a/.claude/skills/skill-authoring/SKILL.md b/.claude/skills/skill-authoring/SKILL.md index ebded80..d154f58 100644 --- a/.claude/skills/skill-authoring/SKILL.md +++ b/.claude/skills/skill-authoring/SKILL.md @@ -166,3 +166,7 @@ When improving an existing skill, compare against the previous version and look - [ ] `python scripts/ci/check_agent_frontmatter.py` passes - [ ] `.agent/SKILL_INVENTORY.md` updated for new or materially changed skills - [ ] AST10 review considerations documented in the PR summary for material changes +- [ ] PR can't merge because `docs/agent-asset-inventory.md` conflicts with another skill PR: merge + `origin/main` into the branch, take either side of that file, run + `python scripts/generate_agent_asset_inventory.py` and its `--check`, then push without force. It's + generated, so don't hand-merge it. diff --git a/.claude/skills/test-driven-development/SKILL.md b/.claude/skills/test-driven-development/SKILL.md index 033e617..7da5cab 100644 --- a/.claude/skills/test-driven-development/SKILL.md +++ b/.claude/skills/test-driven-development/SKILL.md @@ -92,6 +92,8 @@ Avoid tests that: - Keep each red/green step small enough to explain in the final response. - If a failing test exposes an unrelated pre-existing issue, narrow the command or document the blocker before changing scope. +- **Proving a test catches a regression:** the mutated code must compile and fail on that test's assertion + (a compile error proves nothing); restore it and confirm `git status` is clean before claiming the result. ## Red flags diff --git a/.claude/skills/windows-agent-tooling/SKILL.md b/.claude/skills/windows-agent-tooling/SKILL.md index 05970af..6659154 100644 --- a/.claude/skills/windows-agent-tooling/SKILL.md +++ b/.claude/skills/windows-agent-tooling/SKILL.md @@ -72,7 +72,7 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws ## Agent-Safe Patterns - Avoid mixing `D:\` and `/mnt/d/` in one workflow. -- In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). +- In Git Bash, prefix `MSYS_NO_PATHCONV=1` when a non-Windows tool takes a Unix-style path that starts with `/`, since MSYS rewrites it into a Windows path (but see the next bullets: Git's own `-C` then needs `D:/...`). For example, `docker exec`/`docker run` with container paths (`-w /app`, `/data/...`) fails with "Cwd must be an absolute path". - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. - MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit diff --git a/.cursor/skills/agent-setup/references/usage.md b/.cursor/skills/agent-setup/references/usage.md index e9e13af..b69216b 100644 --- a/.cursor/skills/agent-setup/references/usage.md +++ b/.cursor/skills/agent-setup/references/usage.md @@ -24,12 +24,19 @@ Use the local receipt and subsequent plan as evidence; file installation alone d `plan` has no per-skill option. To take in one skill (for example after its PR merges), make the full plan, then keep only that skill's operations: -1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. +1. `plan --scope global --state --out /plan-full.json`. Use **the `--state` folder your earlier installs used**: the one holding `targets/*.json`, by default `.agent/local/setup` in the checkout that ran them. A scratch worktree has its own default and no ownership ledger, so its plan shows hundreds of unrelated creates and conflicts. When several checkouts or worktrees hold a ledger, use the one whose `targets/*.json` contains the skill's relative path (for example `.claude/skills//SKILL.md`). A ledger without the skill plans every copy as a conflict. 2. Write a copy of the plan that keeps only the operations whose `relative` path is under `//` for the four user skill trees (`.claude/skills`, `.agents/skills`, `.gemini/config/skills`, `.gemini/antigravity-cli/skills`). Update `summary` to match. 3. Have the user review that list, then `apply --input ` and `check --input `. This is safe because `apply` checks every operation it is given (library and installer hashes, the target root, the destination folder, the content hashes) without requiring the full list. Conflicts are skipped and recorded in the receipt. The ownership ledger merges, so other skills' entries stay. +**A conflict that isn't a local edit.** `apply` skips a copy with no ledger entry ("unmanaged or overlapping edit"), even when it equals an earlier library version. For each conflicting file in the skill's folder, `SKILL.md` and `references/` alike, compare it with that file's history (`git log -p -- .claude/skills//`), ignoring line endings. Note that the installer rewrites the frontmatter `name` for a renamed install. If every file matches a past version, it's a stale install, not the user's edit. Keep it in the ledger by going through `apply`: + +- Record it in `.agent/setup/library.json` in a reviewed PR, so `apply` adopts it with a backup, a receipt and a ledger entry. `SKILL.md` goes in `reviewed_global_adoptions`. Every other file (`references/`, scripts) goes in `reviewed_resource_adoptions`, one entry per installed path (`relative`, `sha256`, reason) in each tree that holds it. Or: +- with the user's approval, move the stale folder to a backup under `` (for example `/stale-backups/-/`); `apply` creates its own run folder later. The re-plan then reads `create`, and `apply` writes the files and records ownership. + +Writing the plan's content to the file by hand leaves it unmanaged, with no receipt or rollback, so the next library change to that skill conflicts again. Anything that matches no past version is the user's edit: leave it and report it. + ## Explicit MCP replacement Use this procedure when the user asks to replace one harness's MCP registrations with another's. The named harness is the source for that request, not a permanent default for future tasks. Replacement requires explicit user intent; ordinary synchronization stays additive. diff --git a/.cursor/skills/cross-pc-ssh/SKILL.md b/.cursor/skills/cross-pc-ssh/SKILL.md index b767e32..87ec22b 100644 --- a/.cursor/skills/cross-pc-ssh/SKILL.md +++ b/.cursor/skills/cross-pc-ssh/SKILL.md @@ -51,9 +51,12 @@ alone, and the guard then accepts exactly the boundary commits recorded when it 1. `ssh -n -o BatchMode=yes hostname` must print the peer's name. If it asks for a password or fails host-key verification, stop: setting up keys and known_hosts is the user's step, not this skill's. - If it times out, the alias's `HostName` may be a stale address (DHCP). Try the peer's hostname with the - pinned key, `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`, and pass - the same options as `--peer`. Fixing `~/.ssh/config` is the user's step. + If it times out, the alias's `HostName` may be a stale address (DHCP). To check by hostname with the + pinned key, first find the name `known_hosts` holds it under (`ssh-keygen -F `, then + `ssh-keygen -F `): ssh saves a key under the `HostName` unless `HostKeyAlias` is set. + Then run `ssh -n -o BatchMode=yes -o HostKeyAlias= @ hostname`. The helper's + `--peer` takes only an alias or `user@host`, with fixed ssh options, so before using the helper the + user updates `HostName` in `~/.ssh/config`. 2. `locate`. If it finds no checkout, the repository isn't cloned there (or lives outside the roots); say so rather than searching the peer's disks. diff --git a/.cursor/skills/fast-forward/SKILL.md b/.cursor/skills/fast-forward/SKILL.md new file mode 100644 index 0000000..52afa4b --- /dev/null +++ b/.cursor/skills/fast-forward/SKILL.md @@ -0,0 +1,202 @@ +--- +name: fast-forward +description: "Bring the default branch of the current repository (or each repository the work touched) level with its remote with a deterministic inventory, plan and fast-forward-only apply (sync), and, when the user also asks to commit, push and merge, land the local work that belongs there (land): commit the intended tracked changes on a short-lived branch, push it, open a PR against the repository's own default branch, merge it pinned to the pushed commit, fast-forward the local default branch to the merge, and delete the branch. Leaves untracked and unrelated files alone. Runs only when the user types /fast-forward." +capability: "Sync a checkout's default branch with origin, fast-forward only; in land mode, also land its intended tracked changes through a pinned PR merge. Never by force or a direct push to the default branch." +side_effect_level: remote_write +approval_required: true +requires_tools: "python 3.9+ (stdlib only) for scripts/fast_forward.py, git, and gh authenticated for the repository's own remote." +output_schema: "The harness plan table and receipt JSON, then the default branch's position before and after (ahead/behind counts and short SHAs), what was committed (paths and the commit), the PR and its merge commit, the final ahead/behind of 0/0, and every file left untouched with the reason." +risk_class: medium +disable-model-invocation: true +--- + +# Fast-forward + +`/fast-forward` means: **make my default branch match the remote** (sync). Typed alone, it approves only +the sync: a fetch and fast-forward-only moves. When the typed request also says commit, push or merge +(land), it also approves one commit of the intended tracked changes, one push of a new branch, one PR and +its merge. It is not standing approval, and it never force-pushes, rewrites history or pushes straight to the +default branch. + +| Mode | What it does | Runs when | +|---|---|---| +| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward` alone, or with "catch up" or "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The typed request also says commit, push or merge | +| cleanup | Not run here: merged branches and worktrees are listed in the report only | Housekeeping, on its own request | + +A compound request ("fetch, pull, commit, push, merge, fast-forward") authorizes both modes for this run. +Permission to fast-forward a checkout is never permission to push to its default branch. + +How this differs from neighbours: +- `commit-and-push` commits and pushes a branch; it doesn't merge or fast-forward the default branch. +- `/merge-pr` and `/ship-pr` merge an existing PR on CI evidence. `/fast-forward` opens its own small PR + and merges it in the same run, so keep it for changes that need no review: tracker snapshots, + generated files, docs the user already approved. +- Syncing an upstream repository **into** a fork is a different job (some projects have their own + skill for it). `/fast-forward` only talks to the repository's own `origin`. +- `repo-inventory` compares checkouts across PCs and prints a plan it never runs. This skill is the + local executor; on a peer it only runs `inventory` and `plan` (see [references/details.md](references/details.md)). + +## 0. Scope and other sessions + +- **Scope:** the current repository, plus each repository this conversation changed, or the list the user + names. Never sweep a whole projects folder unasked. +- **Other sessions:** before any write, ask the live sessions working in these checkouts (`ListAgents`, + then `SendMessage`) and wait for "safe". If another session already took the same request, split the + repositories and send it what you found (EOL-only files, junk names, identical copies) so it doesn't redo it. + +## 1. Confirm the target + +- **The repository and its default branch.** Read `gh repo view --json nameWithOwner,defaultBranchRef` + for `origin`. In a fork, `gh` defaults to the parent repository, so name the repository on every + `gh` call (`--repo /`). If the project's notes name a read-only upstream, never write to it. +- **This checkout is on the default branch,** or can switch to it cleanly. If it's on another branch + with work in progress, stop and ask; that branch isn't yours to move. +- **Another session may share this checkout.** If one is active here (`ListAgents`, a held tracker ticket, + a running build), ask before switching branches. + +## 2. Fetch and fast-forward (sync) + +Use the harness. It calls git with argument lists (no shell, so no MSYS path rewriting), with prompts off +and a per-repo timeout, and it never edits `.git/config`: + +```bash +FF="/scripts/fast_forward.py" +python -I "$FF" plan --repo [--repo ]... --fetch [--gh] --out /ff-plan.json +python -I "$FF" apply --plan /ff-plan.json [--backup-dir ] --receipt /ff-receipt.json +``` + +| Row | Meaning | Who acts | +|---|---|---| +| `noop` | Already level, or nothing this skill may do | – | +| `ff` | `merge --ff-only` to the fetched SHA in the checkout holding the default branch; unrelated edits stay | apply | +| `ff-ref` | No worktree holds the default branch: `update-ref` with the expected old SHA | apply | +| `archive-ff` | Untracked or ignored files identical (git-normalized) to incoming ones: backed up, verified, removed, then `ff` | apply, with `--backup-dir` | +| `switch` | The current branch is merged (in origin's history, or with `--gh` a PR merged at this exact head) and clean | apply | +| `needs-human` | Diverged, local commits, overlapping edits, a different untracked or ignored file, the default branch checked out elsewhere, an operation in progress, a fetch that failed or timed out | you, with the user | + +- Show the plan table before `apply`. `apply` re-reads every repository first and refuses a row whose + HEAD, SHAs, holder, tracked changes or collision hashes moved since planning; re-plan instead of forcing. +- It compares the git configuration digest after each action and stops all writes on drift. Report a + drift; never restore or "fix" the configuration yourself. +- A timed-out fetch usually waits on a credential prompt. Report it as `needs-human: auth`. +- Without the harness (no Python), the manual rules are: + +```bash +git fetch origin +git rev-list --left-right --count HEAD...origin/ # " " +``` + +- **Behind only (`0 N`):** `git pull --ff-only origin `. Dirty tracked files are fine when the + incoming commits don't touch them. Check with `git log HEAD..origin/ -- ` first. + If they do touch them, stop and report the overlap; don't stash, reset or merge over someone's edits. +- **Ahead (`N 0` or `N M`):** local commits exist on the default branch. Don't push them directly. Move + them to the step-3 branch, or stop and ask if they aren't clearly the user's. `git switch -c ` + keeps the commits and the working tree, then `git branch -f --no-track origin/` moves only the + default branch's pointer back. Never use `git reset` for this: it can discard the dirty tracked files + this step allows. +- **Never** `git pull` without `--ff-only`, and never `--rebase` or `--force` on the default branch. +- **The default branch is checked out in another worktree:** fast-forward it there, only after its owner + says it is safe. Don't move a checked-out branch's ref behind its worktree's back. + +## 3. Commit the intended changes on a branch + +- **Decide what belongs.** List `git status --short`. Commit only tracked changes the user's request + covers, or that this run produced: a tracker snapshot, a regenerated file. Show the diff stat. +- **Untracked files stay untracked** unless the user names them. They are often local notes, exports, + device presets or machine config (`mcp_config.json`, `*.local.*`, `.env*`). List them in the report. +- **Secrets gate before the push:** scan the staged diff (`git diff --cached`) for tokens, keys, + machine-local paths and personal identities. A hit blocks the push. For a PUBLIC repository + (`gh repo view --json visibility`), follow `commit-and-push`'s public-repo checks too. +- Create the branch with `git switch --no-track -c `: `branch.autoSetupMerge=always` would otherwise + write tracking into `.git/config`. Name it `chore/-` (or the project's pattern, such as `af/-`). Stage + paths explicitly (`git add `, never `git add -A`), and commit with a Conventional Commit message + and the attribution lines the session asks for. +- Nothing to commit? Skip steps 3–5 and report that the default branch only fast-forwarded. + +## 4. Push and open the PR + +```bash +git push origin +gh pr create --repo / --base --head --title "" --body-file +``` + +Push without `-u`: an upstream setting writes branch tracking into `.git/config`. The body says what +changed and why it needs no review. Reference the ticket (`Refs `) when the +project tracks work. + +## 5. Merge pinned to the pushed commit + +- **Same gate as `/merge-pr`.** Poll the check state after the push (bounded, about ten minutes) rather than + sleeping a fixed time; zero runs on a repository with workflows is unknown, not green. Then + **every** run and check on the pushed SHA (`gh run list --commit `, plus the commit's + check-runs and status) must have completed green. Anything pending, failing or skipped-only, a + `mergeStateStatus` of `BLOCKED`, or a conflict means stop: hand it to `/ship-pr` or the user. If the + repository has CI but no run registered, or no CI at all, hand the merge to `/merge-pr`, which proves + that case and runs the checks locally. Don't merge on a guess. +- Check that the PR's `headRefOid` equals `git rev-parse HEAD`, so the merge lands exactly the commit + you checked. +- Use the method the repository's recent PRs used, pinned to the **full 40-character SHA** (a short SHA + is rejected): + + ```bash + gh pr merge --repo / --merge --delete-branch --match-head-commit $(git rev-parse HEAD) + ``` +- **"The merge commit cannot be cleanly created":** the default branch moved. Fetch, merge + `origin/` into the branch, and resolve the conflicts. Regenerate generated files rather than + hand-merging them. Re-run the checks, push (no force), then merge again on the new head. + +## 6. Fast-forward the local default branch + +```bash +git switch +git pull --ff-only origin +git rev-list --left-right --count HEAD...origin/ # must print "0 0" +git branch -d # -d, not -D: it must be merged +``` + +Compare `python -I "$FF" inventory`'s `config_digest` from before step 3 with one taken now; a change is a drift to +report, not to repair. `gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +already have deleted the local branch, so a failing `git branch -d` there is harmless. Check +`gh pr view --json state,mergeCommit` rather than trusting its exit code. + +## 7. After the fast-forward + +- `0 0` proves the refs match. It doesn't prove a clean tree, a rebuilt binary or a running new version. + Check what the repository deploys (a `dist/` the harness flags, binaries copied out of a build folder, + skills installed at user level, an npm-linked CLI) and report "source at X, installed at Y". Rebuild or + reinstall only within the request; for skills, hand the user the installer's plan. +- Replacing a binary that live sessions hold open fails until they exit: make it a "close sessions" item. +- Branches whose remote is `[gone]` and squash-merged branches (`gh pr list --state merged --head `) + go in the report as a list. Deleting them is cleanup, the user's call. +- **Retries:** after any failure, read the state (PR state, `git log`, the receipt) before trying again; a + remote merge can succeed while local cleanup fails. Re-plan, and never repeat a commit, a PR or a merge. + +## Report + +One row per repository (and per PC), same columns everywhere; rows with nothing to do collapse into one line +("9 repos already at origin"): + +| Repo | PC | Before | After | Action | Left for you | +|---|---|---|---|---|---| + +Then, for land: + +```markdown +**** is level with origin at (was ahead, behind). + +- Committed as on ; PR # merged as ; branch deleted. +- Left untouched: . +- Archived: backup>; config digest unchanged; deploy: . +``` + +## Never + +- Push directly to the default branch, force-push, rebase or reset a branch with others' work. +- Stash, discard or commit files the user didn't ask for, including untracked ones. +- Merge past a pending or failing required check, a `BLOCKED` state or a requested change. +- Open the PR against an upstream or parent repository the project treats as read-only. +- Delete a branch with `-D`, or delete a branch that isn't merged. +- Edit `.git/config`: no upstream tracking, no `git config`, no `remote set-url` for a moved + repository ("This repository moved" is harmless: GitHub redirects). +- Retry a command a permission layer refused in another form. Finish the rest and hand it over as a `!` command. diff --git a/.cursor/skills/fast-forward/references/details.md b/.cursor/skills/fast-forward/references/details.md new file mode 100644 index 0000000..17a1423 --- /dev/null +++ b/.cursor/skills/fast-forward/references/details.md @@ -0,0 +1,41 @@ +# fast-forward: details + +Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Bash on Windows. + +## Checks that look green or red for the wrong reason + +- **Zero check runs is unknown.** A repository can have Actions enabled and active workflows yet no runs at + all. Look at `gh run list --commit ` and the repository's runs, not only the PR's check list. + `gh pr checks` exits non-zero while checks are pending: that means wait. +- **Classify a failure from the job log:** a repository setting (for example dependency review on a + repository without the dependency graph), an infrastructure error, or a real failure. Only a real + failure belongs to the PR. If the default branch's own latest run fails the same way, report it as + already broken on the base; the PR can't fix it. + +## Across PCs + +- On a peer, run only `inventory` and `plan`, over `cross-pc-ssh` or as a `cross-pc-messages` request. + The plan goes back to that PC's agent with exact commands; its owner approves its own `apply`. +- Reach peers by hostname and pin the host key alias (`ssh -o HostKeyAlias= `), so a + stale address doesn't look like "host unreachable". +- The same repository sits under different folders, drive letters or as a shallow clone on each PC. Match + it by normalized origin and root commits, as `cross-pc-ssh` does, never by folder name. +- After a default branch moves, offer to draft the note telling the peers to fast-forward too. Sending it + is the user's call. +- Fetch in parallel; move refs one repository at a time, so the report and undo stay in order. + +## Windows + +- Under Git Bash, `git show origin/:` has its argument rewritten into a Windows path. Set + `MSYS_NO_PATHCONV=1` for such manual commands; the harness avoids it by never using a shell. +- Compare with carriage returns stripped (`git diff --ignore-cr-at-eol --numstat`); otherwise every mirror + regenerated on Windows looks modified. The harness reports line-ending-only edits as a note. +- A hung `git.exe` (credential helper) outlives a client timeout. The harness starts each git call in its + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). + +## Generated snapshots + +A tracker snapshot such as `.agent-flow/tickets.jsonl` that both sides changed is not a merge by +timestamp. Use the tracker's own export or import, within the task's scope; otherwise it is a +`needs-human` item. Build output that appears after a local test run (`*.egg-info/`, `__pycache__/`, +`target/`) is worth one suggested `.gitignore` line, not a listing every run. diff --git a/.cursor/skills/fast-forward/scripts/fast_forward.py b/.cursor/skills/fast-forward/scripts/fast_forward.py new file mode 100644 index 0000000..9abfa97 --- /dev/null +++ b/.cursor/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,576 @@ +#!/usr/bin/env python3 +"""Fast-forward local default branches to origin, deterministically and without editing .git/config. + +Commands: + inventory [--repo DIR]... [--fetch] [--gh] [--timeout 60] [--json] + Read-only facts per repository: the default branch (origin/HEAD, else main, else master) and its origin + SHA, the local default branch and where it is checked out, HEAD, ahead/behind, upstream, an operation in + progress, tracked changes split into real and line-ending-only edits, untracked or ignored files the incoming + commits would overwrite (each compared with the incoming blob, path-aware), a stale-build hint and a + digest of the git configuration files. --fetch runs "git fetch --prune origin" first (in parallel, + no prompts, per-repo timeout); that is the only write. --gh asks gh whether the current branch's + exact head was merged as a PR (squash merges). + plan [--repo DIR]... [--fetch] [--gh] [--out FILE] [--json] + Rule-based actions per repository, each with its reason: + noop level with origin already + ff git merge --ff-only in the checkout that holds the default branch + ff-ref git update-ref on the default branch when no worktree holds it (expected old SHA) + archive-ff untracked files identical to the incoming ones: back them up, verify, remove, then ff + switch the current branch is merged and the tree is clean: switch to the (advanced) default + needs-human anything else (diverged, local commits, overlap, different untracked file, occupied + default branch, operation in progress, fetch timeout or auth), never executed + apply --plan FILE [--backup-dir DIR] [--receipt FILE] + Runs only ff, ff-ref, archive-ff and switch rows. Before each repository it re-reads the evidence + (HEAD, default and origin SHAs, holder, tracked changes, collision hashes) and refuses a stale row. + It checks the config digest after every action and stops all further writes when it drifts. Prints a + receipt (old and new SHAs, archived files, undo commands). Never fetches, stashes, resets, rebases, + force-pushes, deletes branches or runs "git config". + +Exit codes: 0 nothing left for a human, 1 a needs-human, refused or failed row, 2 usage error. +Stdlib only; git is always called with an argument list, never through a shell. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +SCHEMA = "fast-forward-plan" +SCHEMA_VERSION = 1 +EXECUTABLE = ("ff", "ff-ref", "archive-ff", "switch") +GIT_CFG = ["-c", "core.quotepath=off", "-c", "color.ui=never", "-c", "core.fsmonitor=false"] +OPERATIONS = (("MERGE_HEAD", "merge"), ("rebase-merge", "rebase"), ("rebase-apply", "rebase"), + ("CHERRY_PICK_HEAD", "cherry-pick"), ("REVERT_HEAD", "revert"), ("BISECT_LOG", "bisect")) +# Names a broken shell redirect tends to leave behind ("2>&1", "-o", "nul", "=1.2"): reported, never removed. +JUNK = re.compile(r"(^-|^=|^(nul|con|prn|aux)(\..*)?$|&1$|^\d$)", re.IGNORECASE) + + +class UsageError(Exception): + pass + + +class GitError(Exception): + pass + + +def git_env(read_only: bool = True) -> dict: + env = dict(os.environ) + env.update({"GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never", "GIT_ASKPASS": "", + "SSH_ASKPASS": "", "LC_ALL": "C"}) + env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes") + if read_only: + env["GIT_OPTIONAL_LOCKS"] = "0" + return env + + +def _kill_tree(proc: subprocess.Popen) -> None: + """Stop git and the helpers it started (credential managers, ssh), not only the direct child.""" + try: + if os.name == "nt": + subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True, check=False) + else: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + pass + try: + proc.kill() + except OSError: + pass + + +def run(cmd: list[str], cwd: str | Path, timeout: float = 60, read_only: bool = True) -> subprocess.CompletedProcess: + proc = subprocess.Popen(cmd, cwd=str(cwd), env=git_env(read_only), stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0), + start_new_session=os.name != "nt") + try: + out, err = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _kill_tree(proc) + proc.communicate() + raise TimeoutError(f"{' '.join(cmd[:3])} timed out after {timeout:.0f}s") + return subprocess.CompletedProcess(cmd, proc.returncode, out.decode("utf-8", "replace"), + err.decode("utf-8", "replace")) + + +def git(repo: str | Path, *args: str, timeout: float = 60, check: bool = True, read_only: bool = True) -> str: + cp = run(["git", *GIT_CFG, *args], repo, timeout, read_only) + if check and cp.returncode != 0: + raise GitError(f"git {' '.join(args[:3])}: {cp.stderr.strip()[:300]}") + return cp.stdout + + +def git_ok(repo, *args, timeout: float = 60) -> bool: + return run(["git", *GIT_CFG, *args], repo, timeout).returncode == 0 + + +def rev(repo, ref: str) -> str | None: + cp = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", ref + "^{commit}"], repo) + return cp.stdout.strip() or None if cp.returncode == 0 else None + + +def norm(path: str | Path) -> str: + return os.path.normcase(os.path.normpath(str(Path(path).resolve()))) + + +# ---------------------------------------------------------------- configuration digest + +def config_files(repo: str | Path) -> list[Path]: + common = Path(repo, git(repo, "rev-parse", "--git-common-dir").strip()).resolve() + files = [common / "config"] + files += sorted((common / "worktrees").glob("*/config.worktree")) + if (common / "config.worktree").exists(): + files.append(common / "config.worktree") + return files + + +def config_digest(repo: str | Path) -> str: + h = hashlib.sha256() + for f in config_files(repo): + h.update(f.name.encode() + b"\0" + str(f.parent.name).encode() + b"\0") + h.update(f.read_bytes() if f.exists() else b"") + h.update(b"\0") + return h.hexdigest() + + +# ---------------------------------------------------------------- inventory + +def parse_status(raw: str) -> tuple[list[dict], list[str]]: + """git status --porcelain=v1 -z --untracked-files=all -> (tracked changes, untracked paths).""" + tracked, untracked = [], [] + parts = raw.split("\0") + i = 0 + while i < len(parts): + entry = parts[i] + i += 1 + if len(entry) < 4: + continue + xy, path = entry[:2], entry[3:] + if xy == "??": + untracked.append(path) + continue + if xy == "!!": + continue + item = {"path": path, "xy": xy, "staged": xy[0] not in " ?", "unmerged": "U" in xy or xy in ("AA", "DD")} + if xy[0] in "RC": + item["from"] = parts[i] if i < len(parts) else "" + i += 1 + tracked.append(item) + return tracked, untracked + + +def real_edits(repo) -> set[str]: + """Paths whose diff against HEAD is more than line endings (--name-only ignores --ignore-cr-at-eol).""" + out = set() + for line in git(repo, "diff", "--ignore-cr-at-eol", "--numstat", "--no-renames", "HEAD").splitlines(): + added, deleted, path = line.split("\t", 2) + if (added, deleted) != ("0", "0"): + out.add(path) + return out + + +def worktrees(repo) -> list[dict]: + out, cur = [], {} + for line in git(repo, "worktree", "list", "--porcelain").splitlines() + [""]: + if not line: + if cur: + out.append(cur) + cur = {} + elif line.startswith("worktree "): + cur["path"] = line[9:] + elif line.startswith("HEAD "): + cur["head"] = line[5:] + elif line.startswith("branch "): + cur["branch"] = line[7:] + elif line in ("bare", "detached", "locked", "prunable") or line.startswith(("locked ", "prunable ")): + cur[line.split(" ")[0]] = True + return out + + +def default_branch(repo) -> str | None: + cp = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], repo) + if cp.returncode == 0 and cp.stdout.strip().startswith("refs/remotes/origin/"): + return cp.stdout.strip()[len("refs/remotes/origin/"):] + for name in ("main", "master"): + if rev(repo, f"refs/remotes/origin/{name}"): + return name + return None + + +def origin_slug(repo) -> str | None: + cp = run(["git", *GIT_CFG, "remote", "get-url", "origin"], repo) + m = re.search(r"[/:]([^/:]+)/([^/]+?)(\.git)?/?$", cp.stdout.strip()) if cp.returncode == 0 else None + return f"{m.group(1)}/{m.group(2)}" if m else None + + +def gh_command() -> list[str]: + raw = os.environ.get("FAST_FORWARD_GH", "gh") + return json.loads(raw) if raw.startswith("[") else [raw] + + +def merged_pr_at_head(repo, branch: str, head_sha: str, timeout: float) -> dict | None: + slug = origin_slug(repo) + if not slug: + return None + try: + cp = run([*gh_command(), "pr", "list", "--repo", slug, "--state", "merged", "--head", branch, + "--json", "number,headRefOid,url"], repo, timeout) + except (OSError, TimeoutError): + return None + if cp.returncode != 0: + return None + for pr in json.loads(cp.stdout or "[]"): + if pr.get("headRefOid") == head_sha: # a PR merged earlier does not cover later commits + return {"number": pr.get("number"), "url": pr.get("url")} + return None + + +def build_hint(top: Path, origin_time: int | None) -> str | None: + pkg = top / "package.json" + dist = top / "dist" + try: + scripts = json.loads(pkg.read_text(encoding="utf-8")).get("scripts", {}) if pkg.exists() else {} + except (ValueError, OSError): + return None + if "build" in scripts and dist.is_dir() and origin_time and dist.stat().st_mtime < origin_time: + return "dist/ is older than the default branch tip: run the project's build before calling it deployed" + return None + + +def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, + fetched: dict | None = None) -> dict: + rec: dict = {"input": str(path)} + try: + top = Path(git(path, "rev-parse", "--show-toplevel", timeout=timeout).strip()).resolve() + rec["path"] = str(top) + rec["git_dir"] = str(Path(top, git(top, "rev-parse", "--git-dir").strip()).resolve()) + rec["config_digest"] = config_digest(top) + if fetched: + rec["fetch"] = fetched + d = default_branch(top) + rec["default"] = d + sym = run(["git", *GIT_CFG, "symbolic-ref", "--quiet", "HEAD"], top) + rec["head_branch"] = sym.stdout.strip()[len("refs/heads/"):] if sym.returncode == 0 else None + rec["head_sha"] = rev(top, "HEAD") + up = run(["git", *GIT_CFG, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], top) + rec["upstream"] = up.stdout.strip() if up.returncode == 0 else None + rec["operation"] = next((name for marker, name in OPERATIONS if Path(rec["git_dir"], marker).exists()), None) + tracked, untracked = parse_status(git(top, "status", "--porcelain=v1", "-z", "--untracked-files=all")) + real = real_edits(top) if rec["head_sha"] else set() + for item in tracked: + item["eol_only"] = (not item["staged"] and not item["unmerged"] and item["xy"] == " M" + and item["path"] not in real) + rec["tracked"] = tracked + rec["untracked"] = untracked + rec["junk_suspects"] = [u for u in untracked if JUNK.search(Path(u).name)] + rec["worktrees"] = worktrees(top) + if not d: + return rec + rec["origin_sha"] = rev(top, f"refs/remotes/origin/{d}") + rec["local_default_sha"] = rev(top, f"refs/heads/{d}") + rec["holder"] = next((w["path"] for w in rec["worktrees"] if w.get("branch") == f"refs/heads/{d}"), None) + if rec["origin_sha"] and rec["local_default_sha"]: + a, b = git(top, "rev-list", "--left-right", "--count", + f"{rec['local_default_sha']}...{rec['origin_sha']}").split() + rec["ahead"], rec["behind"] = int(a), int(b) + if rec["origin_sha"] and rec["head_sha"]: + incoming = set(filter(None, git(top, "diff", "--name-only", "-z", "--no-renames", + rec["head_sha"], rec["origin_sha"]).split("\0"))) + rec["incoming_paths"] = len(incoming) + rec["overlap"] = sorted(t["path"] for t in tracked if t["path"] in incoming or t.get("from") in incoming) + # Untracked and ignored files alike: a fast-forward overwrites ignored files without asking. + indexed = set(filter(None, git(top, "ls-files", "-z").split("\0"))) + rec["collisions"] = [collision(top, p, rec["origin_sha"]) for p in sorted(incoming) + if p not in indexed and (top / p).is_file()] + rec["head_merged"] = bool(rec["head_branch"] and rec["head_branch"] != d + and git_ok(top, "merge-base", "--is-ancestor", rec["head_sha"], rec["origin_sha"])) + if use_gh and rec["head_branch"] and rec["head_branch"] != d and not rec["head_merged"]: + rec["merged_pr"] = merged_pr_at_head(top, rec["head_branch"], rec["head_sha"], timeout) + t = git(top, "log", "-1", "--format=%ct", rec["origin_sha"]).strip() + rec["build_hint"] = build_hint(top, int(t) if t.isdigit() else None) + except (GitError, TimeoutError, OSError) as exc: + rec["error"] = str(exc) + return rec + + +def collision(top: Path, rel: str, origin_sha: str) -> dict: + local = git(top, "hash-object", f"--path={rel}", "--", str(top / rel)).strip() + blob = run(["git", *GIT_CFG, "rev-parse", "--verify", "--quiet", f"{origin_sha}:{rel}"], top).stdout.strip() + raw = hashlib.sha256((top / rel).read_bytes()).hexdigest() + return {"path": rel, "local_blob": local, "incoming_blob": blob or None, "sha256": raw, "same": bool(blob) and local == blob} + + +def fetch_all(paths: list[str], timeout: float) -> dict[str, dict]: + def one(p: str) -> tuple[str, dict]: + try: + before = rev(p, "refs/remotes/origin/HEAD") + cp = run(["git", *GIT_CFG, "fetch", "--prune", "origin"], p, timeout, read_only=False) + if cp.returncode != 0: + return p, {"ok": False, "error": cp.stderr.strip()[:300] or "fetch failed"} + return p, {"ok": True, "origin_head_before": before} + except (TimeoutError, OSError) as exc: + return p, {"ok": False, "error": f"{exc} (auth prompt or network; check credentials by hand)"} + with ThreadPoolExecutor(max_workers=min(8, max(1, len(paths)))) as pool: + return dict(pool.map(one, paths)) + + +# ---------------------------------------------------------------- plan (pure) + +def plan_repo(rec: dict) -> list[dict]: + def human(reason: str) -> list[dict]: + return [{"action": "needs-human", "reason": reason}] + if rec.get("error"): + return human(f"inventory failed: {rec['error']}") + if rec.get("fetch") and not rec["fetch"].get("ok"): + return human(f"fetch failed: {rec['fetch'].get('error')}") + d = rec.get("default") + if not d or not rec.get("origin_sha"): + return human("no origin default branch found (origin/HEAD, main or master)") + if rec.get("operation"): + return human(f"a {rec['operation']} is in progress here") + if any(t["unmerged"] for t in rec["tracked"]): + return human("unmerged paths") + rows: list[dict] = [] + if not rec.get("local_default_sha"): + rows.append({"action": "noop", "reason": f"no local {d} branch; creating one is not this skill's job"}) + return rows + ahead, behind = rec.get("ahead", 0), rec.get("behind", 0) + if ahead and behind: + return human(f"{d} diverged from origin ({ahead} ahead, {behind} behind): needs a reviewed preservation plan") + if ahead: + return human(f"{d} has {ahead} local commit(s) not on origin: land them through a PR (land mode), don't push") + here = rec.get("holder") and norm(rec["holder"]) == norm(rec["path"]) + real = [t["path"] for t in rec["tracked"] if not t["eol_only"]] + differ = [c["path"] for c in rec.get("collisions", []) if not c["same"]] + same = [c["path"] for c in rec.get("collisions", []) if c["same"]] + on_branch = rec.get("head_branch") and rec["head_branch"] != d + switchable = on_branch and not rec.get("holder") and (rec.get("head_merged") or rec.get("merged_pr")) \ + and not rec["tracked"] + if behind: + if rec.get("holder") and not here: + return human(f"{d} is checked out in another worktree ({rec['holder']}): fast-forward it there, " + "after its owner says it is safe") + if here: + if rec["overlap"]: + return human("local changes overlap incoming commits: " + ", ".join(rec["overlap"][:10])) + if differ: + return human("untracked files differ from incoming ones: " + ", ".join(differ[:10])) + if same: + rows.append({"action": "archive-ff", "reason": f"fast-forward {behind}; {len(same)} untracked " + "file(s) are byte-identical (git-normalized) to incoming ones", "paths": same}) + else: + rows.append({"action": "ff", "reason": f"fast-forward {behind} commit(s)" + + (f"; {len(real)} unrelated local edit(s) stay" if real else "")}) + else: + rows.append({"action": "ff-ref", "reason": f"{d} is not checked out anywhere: move it {behind} commit(s)"}) + if switchable: + if differ: + rows.append({"action": "needs-human", "reason": "untracked files differ from incoming ones: " + + ", ".join(differ[:10])}) + else: + how = "its head is in origin" if rec.get("head_merged") else f"PR #{rec['merged_pr']['number']} merged at this head" + rows.append({"action": "switch", "reason": f"{rec['head_branch']} is merged ({how}) and clean", + "paths": same}) + elif on_branch and not rows: + rows.append({"action": "noop", "reason": f"on {rec['head_branch']} (not merged or not clean); " + f"{d} is level with origin"}) + if not rows: + rows.append({"action": "noop", "reason": f"{d} is level with origin"}) + return rows + + +EVIDENCE = ("path", "head_branch", "head_sha", "local_default_sha", "origin_sha", "holder", "config_digest") + + +def evidence(rec: dict) -> dict: + ev = {k: rec.get(k) for k in EVIDENCE} + ev["tracked"] = sorted(f"{t['xy']} {t['path']}" for t in rec.get("tracked", [])) + ev["collisions"] = sorted(f"{c['path']} {c['sha256']}" for c in rec.get("collisions", [])) + return ev + + +def build_plan(recs: list[dict]) -> dict: + repos = [] + for rec in recs: + rows = plan_repo(rec) + repos.append({"repo": rec.get("path") or rec["input"], "default": rec.get("default"), "rows": rows, + "evidence": evidence(rec), "notes": [n for n in (rec.get("build_hint"),) if n] + + ([f"junk-looking untracked names (left alone): {', '.join(rec['junk_suspects'][:5])}"] + if rec.get("junk_suspects") else []) + + ([f"{sum(t['eol_only'] for t in rec['tracked'])} line-ending-only change(s)"] + if any(t.get("eol_only") for t in rec.get("tracked", [])) else [])}) + return {"schema": SCHEMA, "schema_version": SCHEMA_VERSION, "created": int(time.time()), "repos": repos} + + +# ---------------------------------------------------------------- apply + +def inside(child: Path, parent: Path) -> bool: + try: + child.resolve().relative_to(parent.resolve()) + return True + except ValueError: + return False + + +def apply_plan(plan: dict, backup_dir: str | None) -> dict: + if plan.get("schema") != SCHEMA or plan.get("schema_version") != SCHEMA_VERSION: + raise UsageError("not a fast-forward plan (schema mismatch)") + if not backup_dir and any(r["action"] in ("archive-ff", "switch") and r.get("paths") + for e in plan["repos"] for r in e["rows"]): + raise UsageError("archive rows need --backup-dir (a folder outside the repository); nothing ran") + receipt = {"schema": "fast-forward-receipt", "plan_created": plan.get("created"), "repos": []} + halted: str | None = None + for entry in plan["repos"]: + out = {"repo": entry["repo"], "outcomes": [], "archived": [], "undo": []} + receipt["repos"].append(out) + todo = [r for r in entry["rows"] if r["action"] in EXECUTABLE] + if not todo: + out["outcomes"] = [{"action": r["action"], "result": "skipped", "reason": r["reason"]} for r in entry["rows"]] + continue + if halted: + out["outcomes"].append({"result": "refused", "reason": halted}) + continue + now = inventory_repo(entry["repo"]) + if evidence(now) != entry["evidence"]: + changed = [k for k in entry["evidence"] if evidence(now).get(k) != entry["evidence"][k]] + out["outcomes"].append({"result": "refused", "reason": "state changed since planning: " + ", ".join(changed)}) + continue + top, d, origin = Path(now["path"]), now["default"], now["origin_sha"] + out["before"] = {"head": now["head_sha"], d: now["local_default_sha"], "origin": origin} + digest = now["config_digest"] + for row in todo: + try: + result = execute(row, now, top, d, origin, backup_dir, out) + except (GitError, TimeoutError, OSError, UsageError) as exc: + result = {"result": "failed", "reason": str(exc)} + result["action"] = row["action"] + out["outcomes"].append(result) + after = config_digest(top) + if after != digest: + halted = f"git configuration changed during {row['action']} in {top}; all further writes stopped" + out["outcomes"].append({"result": "config-drift", "reason": halted, "before": digest, "after": after}) + break + if result["result"] != "ok": + break + out["after"] = {"head": rev(top, "HEAD"), d: rev(top, f"refs/heads/{d}")} + out["config_digest"] = config_digest(top) + return receipt + + +def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: str | None, out: dict) -> dict: + old = now["local_default_sha"] + if row["action"] in ("ff", "archive-ff", "ff-ref") and not git_ok(top, "merge-base", "--is-ancestor", old, origin): + return {"result": "refused", "reason": f"{d} is not an ancestor of origin/{d}"} + if row["action"] in ("archive-ff", "switch") and row.get("paths"): + archive(top, row["paths"], backup_dir, out) + if row["action"] in ("ff", "archive-ff"): + git(top, "merge", "--ff-only", "--no-stat", "--no-overwrite-ignore", origin, read_only=False) + if rev(top, "HEAD") != origin: + return {"result": "failed", "reason": "HEAD is not at the origin SHA after the merge"} + out["undo"].append(f"git -C \"{top}\" merge --ff-only is undone with: git -C \"{top}\" reset --keep {old}") + elif row["action"] == "ff-ref": + git(top, "update-ref", "-m", "fast-forward: ff-ref", f"refs/heads/{d}", origin, old, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {old} {origin}") + elif row["action"] == "switch": + cur = rev(top, f"refs/heads/{d}") + if cur and cur != origin and git_ok(top, "merge-base", "--is-ancestor", cur, origin): + git(top, "update-ref", "-m", "fast-forward: switch", f"refs/heads/{d}", origin, cur, read_only=False) + out["undo"].append(f"git -C \"{top}\" update-ref refs/heads/{d} {cur} {origin}") + git(top, "switch", "--no-guess", "--no-overwrite-ignore", d, read_only=False) + out["undo"].append(f"git -C \"{top}\" switch {now['head_branch']}") + return {"result": "ok", "head": rev(top, "HEAD")} + + +def archive(top: Path, paths: list[str], backup_dir: str | None, out: dict) -> None: + if not backup_dir: + raise UsageError("archive rows need --backup-dir (a folder outside the repository)") + root = Path(backup_dir) + if inside(root, top): + raise UsageError("--backup-dir must be outside the repository") + dest_root = root / f"{top.name}-{time.strftime('%Y%m%d-%H%M%S')}" + for rel in paths: + src, dst = top / rel, dest_root / rel + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + if hashlib.sha256(src.read_bytes()).digest() != hashlib.sha256(dst.read_bytes()).digest(): + raise OSError(f"backup copy of {rel} does not match; nothing removed") + for rel in paths: + (top / rel).unlink() + out["archived"].append({"path": rel, "backup": str(dest_root / rel)}) + out["undo"].append(f"restore archived copies from {dest_root}") + + +# ---------------------------------------------------------------- CLI + +def collect(args) -> list[dict]: + paths = args.repo or ["."] + fetched = fetch_all(paths, args.timeout) if args.fetch else {} + return [inventory_repo(p, args.timeout, args.gh, fetched.get(p)) for p in paths] + + +def render(plan: dict) -> str: + lines = ["| Repo | Action | Why |", "|---|---|---|"] + for e in plan["repos"]: + for r in e["rows"]: + lines.append(f"| {Path(e['repo']).name} | {r['action']} | {r['reason']} |") + for n in e["notes"]: + lines.append(f"| {Path(e['repo']).name} | note | {n} |") + return "\n".join(lines) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="fast_forward.py", description=(__doc__ or "").splitlines()[0]) + sub = ap.add_subparsers(dest="cmd", required=True) + for name in ("inventory", "plan"): + p = sub.add_parser(name) + p.add_argument("--repo", action="append") + p.add_argument("--fetch", action="store_true") + p.add_argument("--gh", action="store_true") + p.add_argument("--timeout", type=float, default=60) + p.add_argument("--json", action="store_true") + if name == "plan": + p.add_argument("--out") + p = sub.add_parser("apply") + p.add_argument("--plan", required=True) + p.add_argument("--backup-dir") + p.add_argument("--receipt") + try: + args = ap.parse_args(argv) + except SystemExit as exc: + return 2 if exc.code else 0 + try: + if args.cmd == "inventory": + print(json.dumps(collect(args), indent=2)) + return 0 + if args.cmd == "plan": + plan = build_plan(collect(args)) + text = json.dumps(plan, indent=2) + if args.out: + Path(args.out).write_text(text, encoding="utf-8") + print(text if args.json else render(plan)) + return 1 if any(r["action"] == "needs-human" for e in plan["repos"] for r in e["rows"]) else 0 + plan = json.loads(Path(args.plan).read_text(encoding="utf-8")) + receipt = apply_plan(plan, args.backup_dir) + text = json.dumps(receipt, indent=2) + if args.receipt: + Path(args.receipt).write_text(text, encoding="utf-8") + print(text) + bad = [o for r in receipt["repos"] for o in r["outcomes"] if o["result"] not in ("ok", "skipped")] + human = [r for e in plan["repos"] for r in e["rows"] if r["action"] == "needs-human"] + return 1 if bad or human else 0 + except UsageError as exc: + print(f"usage: {exc}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.cursor/skills/flow-complete/SKILL.md b/.cursor/skills/flow-complete/SKILL.md index 87c1eab..1d3877a 100644 --- a/.cursor/skills/flow-complete/SKILL.md +++ b/.cursor/skills/flow-complete/SKILL.md @@ -31,4 +31,5 @@ risk_class: medium ``` 6. **Submit.** Run `agent-flow submit `. It re-runs the DoD and moves the ticket to `review`. - `GATE_FAILED` tells you exactly what is missing. Fix it and submit again. + - Confirm it printed `Submitted for review` before asking for a review. `INVALID_TRANSITION` (the ticket is still `ready` because a dependency blocks it, or the lease lapsed) means re-claim or clear the blocker, then submit again. A reviewer started earlier can't get a review brief or approve, and a second one duplicates the review. 7. Report the PR URL and the ticket state. Do **not** approve your own ticket. A reviewer does that: `flow-review`, the `flow-reviewer` agent, the swarm, or a human. diff --git a/.cursor/skills/flow-next/SKILL.md b/.cursor/skills/flow-next/SKILL.md index 5254cf3..a9da4e8 100644 --- a/.cursor/skills/flow-next/SKILL.md +++ b/.cursor/skills/flow-next/SKILL.md @@ -25,6 +25,7 @@ Arguments: `$ARGUMENTS`, either a ticket id or filters like `--label agent-ok -- 4. **Set up the workspace on the returned `branch`.** - Single agent: `git switch -c `, or `git switch ` if it already exists. - Parallel agents: `agent-flow worktree create `, then work inside the printed path. Worktrees are created one at a time. + - Before editing, `git fetch` and `git merge --ff-only origin/` in the worktree, and diff against `origin/`. The worktree starts from the local base branch, which can be many commits behind, and diffs against it look far larger than the change. 5. **Load the context.** Run `agent-flow show ` and read: - the spec, - the scope paths, diff --git a/.cursor/skills/git-and-diff-workflows/SKILL.md b/.cursor/skills/git-and-diff-workflows/SKILL.md index 4e71c90..69ee897 100644 --- a/.cursor/skills/git-and-diff-workflows/SKILL.md +++ b/.cursor/skills/git-and-diff-workflows/SKILL.md @@ -62,6 +62,10 @@ gitleaks detect --source . --no-git -v 2>/dev/null | head -50 separate temporary worktree. Don't stash: `git stash` + `git stash pop` drops what you staged, including `git rm` deletions, so the next commit can come out empty. If you must stash, use `git stash pop --index`. Either way, confirm `git diff --cached --stat` shows your change before you commit. +- **Moving uncommitted changes to another worktree:** `git diff --output=`, then `git apply --3way `. + A shell redirect can re-encode the patch (PowerShell 5.1 writes UTF-16) or mix in `2>&1` warnings. +- **"Untracked working tree files would be overwritten":** back them up outside the repo, `cmp` each copy + (recopy if a live writer changed it), then remove and switch. Never `git clean` or `--force`: it may be the only copy. - See [bounded-output-patterns.md](../cli-tools-overview/references/bounded-output-patterns.md). ## Commands Requiring Confirmation diff --git a/.cursor/skills/merge-pr/SKILL.md b/.cursor/skills/merge-pr/SKILL.md index cf788d7..2416654 100644 --- a/.cursor/skills/merge-pr/SKILL.md +++ b/.cursor/skills/merge-pr/SKILL.md @@ -207,19 +207,20 @@ Immediately before merging, re-read the PR and confirm: - the runs for `` still show the case from step 2: all green, only the not-started cause, the same mix of passed and not-started runs, or, when CI never triggered or there is none, still none. -Use the merge method the repository's recent PRs used, pinned to the checked commit: - **Stacked PRs.** Before merging, list open PRs whose base is this PR's head branch: `gh pr list --base --state open`. If there are any: - Merge without `--delete-branch`. Deleting the branch a child PR is based on closes that child; it does not retarget it. Retarget each child with `gh pr edit --base `, then delete the - branch. + branch. Retarget even when the branch stays: otherwise the child merges into the merged branch and + never reaches the base. - After a squash merge, each child conflicts with the base: git no longer sees the parent's commits as shared. Merge the base into the child, check that the result's tree equals the reviewed head (`git diff ` is empty when the base holds exactly the parent's tree), and gate the new head again. Prefer merge commits for a stack when the repository allows them. +Use the merge method the repository's recent PRs used, pinned to the checked commit: + ```bash gh pr merge --merge --delete-branch --match-head-commit ``` @@ -274,7 +275,9 @@ why the workflow stopped triggering) or, with no CI, that there is none to run. ## Never -Leave these for the user, with a paste-ready command where one helps: +Leave these for the user, with a paste-ready command where one helps. A paste-ready +`gh pr merge --match-head-commit` takes the full 40-character `headRefOid`; a short SHA is rejected +("Could not coerce value ... to GitObjectID"). - Merging when any CI job actually ran and failed, or while runs are still pending. - Merging past a review that isn't approved, or with admin rights to get past branch protection. diff --git a/.cursor/skills/ship-pr/SKILL.md b/.cursor/skills/ship-pr/SKILL.md index 05a08e3..8f14ae2 100644 --- a/.cursor/skills/ship-pr/SKILL.md +++ b/.cursor/skills/ship-pr/SKILL.md @@ -130,7 +130,7 @@ Handle every failing job, one cause at a time. | Already broken on base | The base branch's latest run fails the same way | Stop and report | | Flaky test | Force the timing, and show it fail the same way | Fix the race in the test | | Infrastructure | The log shows a runner, network or quota error | One rerun, then stop (with `--no-ci`, step 2b) | -| Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | + | Repository setting | The job fails before any project step, for example "Dependency review is not supported on this repository" | Name the setting. With the user's go-ahead, change it (that one: `gh api -X PUT repos///vulnerability-alerts`, which turns on the dependency graph), then rerun the job once | 3. **Find the root cause before editing.** A test that passes locally and fails in CI is usually a race. Force it, for example by delaying a mock, and confirm the same error before changing anything. diff --git a/.cursor/skills/skill-authoring/SKILL.md b/.cursor/skills/skill-authoring/SKILL.md index ebded80..d154f58 100644 --- a/.cursor/skills/skill-authoring/SKILL.md +++ b/.cursor/skills/skill-authoring/SKILL.md @@ -166,3 +166,7 @@ When improving an existing skill, compare against the previous version and look - [ ] `python scripts/ci/check_agent_frontmatter.py` passes - [ ] `.agent/SKILL_INVENTORY.md` updated for new or materially changed skills - [ ] AST10 review considerations documented in the PR summary for material changes +- [ ] PR can't merge because `docs/agent-asset-inventory.md` conflicts with another skill PR: merge + `origin/main` into the branch, take either side of that file, run + `python scripts/generate_agent_asset_inventory.py` and its `--check`, then push without force. It's + generated, so don't hand-merge it. diff --git a/.cursor/skills/test-driven-development/SKILL.md b/.cursor/skills/test-driven-development/SKILL.md index 033e617..7da5cab 100644 --- a/.cursor/skills/test-driven-development/SKILL.md +++ b/.cursor/skills/test-driven-development/SKILL.md @@ -92,6 +92,8 @@ Avoid tests that: - Keep each red/green step small enough to explain in the final response. - If a failing test exposes an unrelated pre-existing issue, narrow the command or document the blocker before changing scope. +- **Proving a test catches a regression:** the mutated code must compile and fail on that test's assertion + (a compile error proves nothing); restore it and confirm `git status` is clean before claiming the result. ## Red flags diff --git a/.cursor/skills/windows-agent-tooling/SKILL.md b/.cursor/skills/windows-agent-tooling/SKILL.md index 05970af..6659154 100644 --- a/.cursor/skills/windows-agent-tooling/SKILL.md +++ b/.cursor/skills/windows-agent-tooling/SKILL.md @@ -72,7 +72,7 @@ Full diagram: [windows-wsl-split.md](../cli-tools-overview/references/windows-ws ## Agent-Safe Patterns - Avoid mixing `D:\` and `/mnt/d/` in one workflow. -- In Git Bash, prefix `MSYS_NO_PATHCONV=1` to `docker exec`/`docker run` commands that pass container paths (`-w /app`, `/data/...`); otherwise MSYS rewrites them to Windows paths ("Cwd must be an absolute path"). +- In Git Bash, prefix `MSYS_NO_PATHCONV=1` when a non-Windows tool takes a Unix-style path that starts with `/`, since MSYS rewrites it into a Windows path (but see the next bullets: Git's own `-C` then needs `D:/...`). For example, `docker exec`/`docker run` with container paths (`-w /app`, `/data/...`) fails with "Cwd must be an absolute path". - Use the same prefix for `git show :`. MSYS can rewrite the argument into something like `origin\main;.agent\...`, and a pipeline can hide the failure behind a plausible result such as a `0` count. With the prefix set, write paths in that command as `D:/...`: MSYS no longer translates `/d/...`, so `git -C /d/...` fails. - MSYS rewrites any argument that starts with `/`, including free text: ticket titles, acceptance criteria, commit diff --git a/CHANGELOG.md b/CHANGELOG.md index 6851e38..e6f6010 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ All notable changes to this framework are documented here. The format follows ### Added +- `/fast-forward` skill (user-typed only): levels the default branch with `origin` and lands the intended + tracked changes through a small PR. It fetches, fast-forwards with `--ff-only`, commits explicitly staged + paths on a branch, pushes without `-u`, and merges pinned to the full SHA under the same all-green gate as + `/merge-pr`. It ends at 0 ahead, 0 behind and deletes the branch. It never pushes, forces or resets the + default branch, and leaves untracked files alone. Its sync mode (the default) runs a stdlib harness, + `scripts/fast_forward.py inventory | plan | apply`: rule-based rows (ff, ff-ref, archive-ff, switch, + needs-human), apply re-checks the planned evidence, never edits `.git/config` (digest checked) and + writes a receipt with undo commands. - `repo-inventory` skill: snapshots every checkout under a projects folder with read-only git (remote key, default branch and origin SHA, HEAD, branches with ahead/behind/gone/unpushed, worktrees, dirty counts, stashes, merge or rebase in progress), exchanges snapshots through the cross-PC share, over diff --git a/docs/agent-asset-inventory.md b/docs/agent-asset-inventory.md index b59f9fd..a96b717 100644 --- a/docs/agent-asset-inventory.md +++ b/docs/agent-asset-inventory.md @@ -81,6 +81,7 @@ This inventory lists the canonical Claude-authored assets mirrored to Cursor, Co | `electron-development` | `.claude/skills/electron-development/SKILL.md` | Use when changing an Electron main/preload/renderer contract, IPC handler, desktop database flow, or Electron test/build workflow. | | `eval` | `.claude/skills/eval/SKILL.md` | Use at the end of an implemented task, merged PR, or multi-iteration agent workflow to capture quality signals in project memory. Apply when the user mentions eval, feedback loop, task quality, regression learnings, or session scoring. | | `export-chat` | `.claude/skills/export-chat/SKILL.md` | Use when the user types /export or /export-chat, or asks to export, save, dump, copy, or share the current chat, conversation, or agent transcript as a file or to the clipboard. Renders Claude Code, Codex, Cursor, Google Antigravity and Grok transcripts (user/assistant text plus full tool-call inputs) to Markdown that /resume-task can read back. Also use to export an earlier chat by id. | +| `fast-forward` | `.claude/skills/fast-forward/SKILL.md` | Bring the default branch of the current repository (or each repository the work touched) level with its remote with a deterministic inventory, plan and fast-forward-only apply (sync), and, when the user also asks to commit, push and merge, land the local work that belongs there (land): commit the intended tracked changes on a short-lived branch, push it, open a PR against the repository's own default branch, merge it pinned to the pushed commit, fast-forward the local default branch to the merge, and delete the branch. Leaves untracked and unrelated files alone. Runs only when the user types /fast-forward. | | `feature-flag-lifecycle` | `.claude/skills/feature-flag-lifecycle/SKILL.md` | Use when adding, promoting, testing, or removing a feature flag or staged rollout. | | `fix-it` | `.claude/skills/fix-it/SKILL.md` | Fix the one problem your last report named (a gap, a mismatch, something left undone or still showing the old state), then prove it from the user's side. Use when the user types /fix-it, or replies \"fix it\", \"fix that\" or \"yes, fix it\" right after a report that named a problem. Diagnoses first, backs up before overwriting, makes the smallest reversible fix, verifies what the user actually sees, and reports how to undo it. Not for every open item (/go) or a plan (/step-by-step). | | `flow-complete` | `.claude/skills/flow-complete/SKILL.md` | Finish an agent-flow ticket — run the Definition of Done, commit and push the branch, open a PR that references the ticket, write the handoff note and submit for review. Use when implementation is done or the user says "wrap up", "complete", "submit", "open the PR". Only in projects with an `.agent-flow/` folder. | diff --git a/docs/fast-forward/README.md b/docs/fast-forward/README.md new file mode 100644 index 0000000..171b668 --- /dev/null +++ b/docs/fast-forward/README.md @@ -0,0 +1,99 @@ +--- +type: Design Note +title: fast-forward skill ideas +description: Ideas for a skill that brings local checkouts to their default branch tip safely, on one PC or several, after PRs merge. +resource: fast-forward/README.md +tags: [docs, skills, git, ideas] +timestamp: 2026-11-28T00:00:00Z +okf_version: 0.1 +--- + +# fast-forward skill: ideas + +Status: ideas only, nothing built. The goal is a skill that brings local checkouts up to their default branch +tip safely, on one PC or several, after PRs merge. It would answer "fetch, pull, merge, fast-forward to main" +without the trial and error that request takes by hand today. + +## What goes wrong today + +Each of these came up in real sessions: + +- **`git pull` fails with "no tracking information"** when `main` has no upstream. Setting one writes + `.git/config`, which some workspaces forbid. `git fetch origin` then `git merge --ff-only origin/` + does the same job without touching config. +- **A generated file blocks the fast-forward.** A tracker snapshot such as `.agent-flow/tickets.jsonl` + is modified locally, and the incoming commit changes the same file. Whether to keep the local copy or the + incoming one is a per-record decision: compare by record id, then version and `updated_at`. +- **Untracked files block switching to `main`.** Typical case: an older copy of a file that `main` now + tracks. If the content matches, or the file is only an older copy of what `main` has, it's safe. Otherwise + it's someone's work. +- **The current branch was squash-merged.** `git branch --merged` doesn't see that. The PR state (merged), + or a tree or patch-id comparison against `main`, does. +- **Noise looks like work.** Line-ending-only changes (empty under `git diff --ignore-cr-at-eol`), and junk + files with mangled names left by a broken shell redirect, make a clean checkout look dirty. +- **Another worktree already has `main` checked out**, so `git checkout main` fails, and so does `git fetch + origin main:main` (git refuses to fetch into a branch checked out anywhere). Find that worktree with + `git worktree list --porcelain`, run `git fetch origin`, then `git -C merge --ff-only + origin/main`. `git fetch origin main:main` is only for a `main` that no worktree has checked out; it + refuses a move that isn't a fast-forward. +- **Fast-forwarding doesn't deploy.** A CLI linked from the checkout (an npm global junction, a plugin read + from the folder) can keep running an old untracked `dist/` build. The skill should notice the build step + and offer it, not claim the update is live. +- **Renamed repos.** "This repository moved" on push or fetch is harmless, because GitHub redirects. Rewriting + the remote URL edits `.git/config`, so report it and leave it. +- **Permission layers block discards.** Auto-mode classifiers refuse `git checkout -- ` and `git branch + -D` even after a dialog answer. Prefer non-destructive forms (merge `--ff-only`, a rescue branch) and hand + the rest to the user as paste-ready `!` commands. +- **Shared checkouts.** Another agent session may be working in the same folder. Ask the live sessions first. + +## Shape + +Same pattern as the other harness skills: a stdlib Python script with `scan`, `plan` and `apply`. + +- **scan** (read-only, `--fetch`): for each repo under a root, or the current repo only, record: + - default branch and its origin SHA, current branch, ahead and behind; + - upstream set or not; + - the merged-PR state of the current branch (via `gh` when available); + - tracked changes classified into real edits, EOL-only and known generated snapshots; + - untracked files classified into older copies of tracked files, junk names and unknown; + - worktrees holding the default branch; + - in-progress operations; + - a linked-build hint: a `build` script plus an untracked `dist/` older than `HEAD`. +- **plan**: one row per repo with an action and a reason: + - `ff`: `merge --ff-only origin/` in the worktree that has the default branch checked out, or + `fetch origin main:main` when no worktree has it; + - `switch-and-ff`: the current branch is merged and the tree is clean apart from noise; + - `rescue-then-ff`: real edits move to a `rescue/-` branch, never discarded; + - `needs-human`: diverged, conflicted, unpushed commits, or an unknown untracked file; + - `rebuild`: the follow-up when a linked build is stale. +- **apply**: executes only the `ff`, `switch-and-ff` and `rescue-then-ff` rows. It re-checks each repo's + state first and writes a manifest (old and new SHAs, rescue branches) with undo commands. It never + force-pushes, resets `--hard`, deletes branches or edits `.git/config`. + +## Decisions it should batch into one question + +- Snapshot conflicts: keep incoming or keep local, per record, with a "rescue local first" default. +- Branches already merged by squash: delete the local branch (the user runs the `!` command) or keep it. +- Whether to run a stale build. + +## Across PCs + +- Reuse `repo-inventory`: its `plan` already lists SAFE fast-forwards and NEEDS HUMAN rows per host. This + skill can be the one that executes the SAFE rows locally. +- On a peer, run it through `cross-pc-ssh` (read-only `scan` and `plan`), or send a `cross-pc-messages` + request. Each peer's owner approves its own `apply`. + +## Neighbours + +| Skill | Relationship | +|---|---| +| `merge-pr`, `ship-pr` | They merge; `fast-forward` brings checkouts up to date after a merge. Its natural follow-up step. | +| `projects-housekeeping` | Removes stale worktrees and branches; reuse its rescue and manifest code. | +| `repo-inventory` | Read-only snapshot and plan across PCs; `fast-forward` is the local executor. | +| `commit-and-push` | For real edits found in a checkout, when the user wants them shipped instead of rescued. | + +## Open questions + +- Which generated files count as snapshots? A per-repo config list, or detection by path (`.agent-flow/*.jsonl`)? +- Should `switch-and-ff` also remove a merged worktree, or leave that to `projects-housekeeping`? +- Should it run the project's tests after a fast-forward, or only report the new SHA? diff --git a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json new file mode 100644 index 0000000..01077a2 --- /dev/null +++ b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json @@ -0,0 +1,43 @@ +{ + "id": "fast-forward-lands-through-pinned-pr", + "description": "Protect /fast-forward: user-typed only; --ff-only on the default branch; stop when incoming commits touch dirty files; commit only intended tracked paths on a branch; untracked files untouched; PR against the repo named explicitly; merge pinned to the full SHA; conflicts resolved by merging the default branch and regenerating, never force; ends at 0/0 and deletes the branch with -d.", + "target_asset": ".claude/skills/fast-forward/SKILL.md", + "linked_docs": [], + "must_contain": [ + "disable-model-invocation: true", + " Runs only when the user types /fast-forward.\"", + "it never force-pushes, rewrites history or pushes straight to the\ndefault branch.", + "git pull --ff-only origin ", + "don't stash, reset or merge over someone's edits.", + "**Untracked files stay untracked** unless the user names them.", + "never `git add -A`", + "--repo /", + "**full 40-character SHA**", + "Regenerate generated files rather than\n hand-merging them.", + "# must print \"0 0\"", + "git branch -d ", + "git push origin ", + "git branch -f --no-track origin/", + "**every** run and check on the pushed SHA", + "hand the merge to `/merge-pr`", + "`headRefOid` equals `git rev-parse HEAD`", + "A hit blocks the push.", + "python -I \"$FF\" plan --repo", + "git switch --no-track -c ", + "`0 0` proves the refs match.", + "zero runs on a repository with workflows is unknown, not green", + "Permission to fast-forward a checkout is never permission to push to its default branch.", + "Typed alone, it approves only\nthe sync" + ], + "must_not_contain": [ + "side_effect_level: read_only", + "push --force", + "git add -A ", + "git reset --hard", + "or asks to fetch, pull", + "push -u", + "sync-upstream-fork", + "Wait about five minutes", + "land the work that belongs on it.**\nTyping it approves" + ] +} diff --git a/tests/test_fast_forward.py b/tests/test_fast_forward.py new file mode 100644 index 0000000..e519d8b --- /dev/null +++ b/tests/test_fast_forward.py @@ -0,0 +1,297 @@ +"""Tests for the fast-forward skill's harness (inventory, plan, apply) against temp repos with a local origin.""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / ".claude" / "skills" / "fast-forward" / "scripts" / "fast_forward.py" + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + """Isolated git config: no system or user settings leak in (autocrlf, autoSetupMerge, credential helpers).""" + cfg = tmp_path / "gitconfig" + cfg.write_text("[user]\n\tname = Test\n\temail = test@example.invalid\n[init]\n\tdefaultBranch = main\n" + "[core]\n\tautocrlf = false\n", encoding="utf-8") + monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(cfg)) + monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1") + return cfg + + +def g(cwd: Path, *args: str) -> str: + return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() + + +def ff(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(SCRIPT), *args], cwd=cwd or ROOT, capture_output=True, text=True, + check=False) + + +def commit(repo: Path, rel: str, text: str, msg: str | None = None) -> str: + p = repo / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(text.encode()) + g(repo, "add", rel) + g(repo, "commit", "-q", "-m", msg or f"edit {rel}") + return g(repo, "rev-parse", "HEAD") + + +def setup(tmp_path: Path, branch: str = "main") -> tuple[Path, Path]: + """origin.git, a clone 'work' and a clone 'other' that pushes new commits.""" + seed = tmp_path / "seed" + seed.mkdir() + g(seed, "init", "-q", "-b", branch) + commit(seed, "a.txt", "one\n") + g(tmp_path, "clone", "-q", "--bare", str(seed), "origin.git") + g(tmp_path, "clone", "-q", "origin.git", "work") + g(tmp_path, "clone", "-q", "origin.git", "other") + return tmp_path / "work", tmp_path / "other" + + +def push_new(other: Path, rel: str = "b.txt", text: str = "two\n", branch: str = "main") -> str: + sha = commit(other, rel, text) + g(other, "push", "-q", "origin", branch) + return sha + + +def plan(work: Path, tmp_path: Path, *extra: str) -> dict: + out = tmp_path / "plan.json" + cp = ff("plan", "--repo", str(work), "--fetch", "--out", str(out), *extra) + assert cp.returncode in (0, 1), cp.stderr + return json.loads(out.read_text(encoding="utf-8")) + + +def actions(p: dict) -> list[str]: + return [r["action"] for e in p["repos"] for r in e["rows"]] + + +def apply(tmp_path: Path, *extra: str) -> tuple[int, dict]: + cp = ff("apply", "--plan", str(tmp_path / "plan.json"), *extra) + return cp.returncode, json.loads(cp.stdout) if cp.stdout.strip() else {} + + +def digest(work: Path) -> str: + return hashlib.sha256((work / ".git" / "config").read_bytes()).hexdigest() + + +def test_behind_and_clean_fast_forwards_then_second_run_is_noop(env, tmp_path): + work, other = setup(tmp_path) + new = push_new(other) + before = digest(work) + p = plan(work, tmp_path) + assert actions(p) == ["ff"] + code, receipt = apply(tmp_path) + assert code == 0, receipt + assert g(work, "rev-parse", "HEAD") == new + assert digest(work) == before + assert actions(plan(work, tmp_path)) == ["noop"] + + +def test_master_default_without_upstream(env, tmp_path): + work, other = setup(tmp_path, branch="master") + g(work, "branch", "--unset-upstream") + new = push_new(other, branch="master") + p = plan(work, tmp_path) + assert p["repos"][0]["default"] == "master" + assert actions(p) == ["ff"] + assert apply(tmp_path)[0] == 0 + assert g(work, "rev-parse", "HEAD") == new + + +def test_identical_untracked_copy_is_archived_then_fast_forwarded(env, tmp_path): + work, other = setup(tmp_path) + new = push_new(other, "docs/plan.md", "same\n") + (work / "docs").mkdir() + (work / "docs" / "plan.md").write_bytes(b"same\n") + p = plan(work, tmp_path) + assert actions(p) == ["archive-ff"] + code, _ = apply(tmp_path) + assert code == 2 # archive rows need --backup-dir; nothing ran + assert (work / "docs" / "plan.md").exists() and g(work, "rev-parse", "HEAD") != new + backup = tmp_path / "backup" + code, receipt = apply(tmp_path, "--backup-dir", str(backup)) + assert code == 0, receipt + assert g(work, "rev-parse", "HEAD") == new + archived = Path(receipt["repos"][0]["archived"][0]["backup"]) + assert archived.read_bytes() == b"same\n" + + +def test_backup_dir_inside_repo_is_refused(env, tmp_path): + work, other = setup(tmp_path) + push_new(other, "n.txt", "x\n") + (work / "n.txt").write_bytes(b"x\n") + plan(work, tmp_path) + code, receipt = apply(tmp_path, "--backup-dir", str(work / "bk")) + assert code == 1 + assert receipt["repos"][0]["outcomes"][0]["result"] == "failed" + assert (work / "n.txt").exists() + + +def test_different_untracked_copy_needs_human(env, tmp_path): + work, other = setup(tmp_path) + push_new(other, "n.txt", "incoming\n") + (work / "n.txt").write_bytes(b"mine\n") + assert actions(plan(work, tmp_path)) == ["needs-human"] + code, _ = apply(tmp_path) + assert code == 1 + assert (work / "n.txt").read_bytes() == b"mine\n" + + +@pytest.mark.parametrize("content, expected", [(b"mine\n", "needs-human"), (b"same\n", "archive-ff")]) +def test_ignored_file_counts_as_collision(env, tmp_path, content, expected): + work, other = setup(tmp_path) + push_new(other, "local.cfg", "same\n") + (work / ".git" / "info" / "exclude").write_text("local.cfg\n", encoding="utf-8") + (work / "local.cfg").write_bytes(content) + assert actions(plan(work, tmp_path)) == [expected] + apply(tmp_path, "--backup-dir", str(tmp_path / "bk")) + if expected == "needs-human": + assert (work / "local.cfg").read_bytes() == content + + +def test_git_timeout_raises_instead_of_waiting(tmp_path): + import importlib.util + import time + + spec = importlib.util.spec_from_file_location("fast_forward", SCRIPT) + assert spec and spec.loader + fast_forward = importlib.util.module_from_spec(spec) + spec.loader.exec_module(fast_forward) + start = time.monotonic() + with pytest.raises(TimeoutError): + fast_forward.run([sys.executable, "-c", "import time; time.sleep(30)"], tmp_path, timeout=1) + assert time.monotonic() - start < 15 + + +def test_dirty_non_overlapping_edit_is_kept(env, tmp_path): + work, other = setup(tmp_path) + new = push_new(other, "b.txt") + (work / "a.txt").write_bytes(b"local edit\n") + assert actions(plan(work, tmp_path)) == ["ff"] + assert apply(tmp_path)[0] == 0 + assert g(work, "rev-parse", "HEAD") == new + assert (work / "a.txt").read_bytes() == b"local edit\n" + + +def test_dirty_overlapping_edit_needs_human(env, tmp_path): + work, other = setup(tmp_path) + push_new(other, "a.txt", "theirs\n") + (work / "a.txt").write_bytes(b"mine\n") + p = plan(work, tmp_path) + assert actions(p) == ["needs-human"] + assert "overlap" in p["repos"][0]["rows"][0]["reason"] + + +def test_line_ending_only_change_is_noted_not_blocking(env, tmp_path): + work, other = setup(tmp_path) + push_new(other, "b.txt") + (work / "a.txt").write_bytes(b"one\r\n") + p = plan(work, tmp_path) + assert actions(p) == ["ff"] + assert any("line-ending-only" in n for n in p["repos"][0]["notes"]) + + +def test_local_commits_and_divergence_need_human(env, tmp_path): + work, other = setup(tmp_path) + commit(work, "c.txt", "local\n") + assert "local commit" in plan(work, tmp_path)["repos"][0]["rows"][0]["reason"] + push_new(other) + assert "diverged" in plan(work, tmp_path)["repos"][0]["rows"][0]["reason"] + + +def test_default_checked_out_in_another_worktree_needs_human(env, tmp_path): + work, other = setup(tmp_path) + g(work, "worktree", "add", "-q", "--no-track", "-b", "feature", str(tmp_path / "wt")) + push_new(other) + p = plan(tmp_path / "wt", tmp_path) + assert actions(p) == ["needs-human"] + assert "another worktree" in p["repos"][0]["rows"][0]["reason"] + + +def test_merged_branch_switches_to_advanced_default(env, tmp_path): + work, other = setup(tmp_path) + g(work, "switch", "-q", "--no-track", "-c", "topic") + commit(work, "t.txt", "topic\n") + g(work, "push", "-q", "origin", "topic") + g(other, "fetch", "-q", "origin") + g(other, "merge", "-q", "--no-ff", "-m", "merge topic", "origin/topic") + g(other, "push", "-q", "origin", "main") + tip = g(other, "rev-parse", "HEAD") + # main is not checked out anywhere now: its ref moves, then the checkout switches to it + p = plan(work, tmp_path) + assert actions(p) == ["ff-ref", "switch"] + code, receipt = apply(tmp_path) + assert code == 0, receipt + assert g(work, "branch", "--show-current") == "main" + assert g(work, "rev-parse", "HEAD") == tip + + +def test_merged_branch_with_local_edit_does_not_switch(env, tmp_path): + work, other = setup(tmp_path) + g(work, "switch", "-q", "--no-track", "-c", "topic") + commit(work, "t.txt", "topic\n") + g(work, "push", "-q", "origin", "topic") + g(other, "fetch", "-q", "origin") + g(other, "merge", "-q", "--no-ff", "-m", "merge topic", "origin/topic") + g(other, "push", "-q", "origin", "main") + (work / "a.txt").write_bytes(b"work in progress\n") + assert actions(plan(work, tmp_path)) == ["ff-ref"] + assert g(work, "branch", "--show-current") == "topic" + + +def test_squash_merged_branch_needs_exact_head_pr(env, tmp_path, monkeypatch): + work, other = setup(tmp_path) + g(work, "switch", "-q", "--no-track", "-c", "topic") + head = commit(work, "t.txt", "topic\n") + commit(other, "t.txt", "topic\n", "squash of topic") + g(other, "push", "-q", "origin", "main") + assert actions(plan(work, tmp_path)) == ["ff-ref"] # the squash merge is invisible to the graph: no switch + stub = tmp_path / "gh_stub.py" + stub.write_text(f"import json\nprint(json.dumps([{{'number': 7, 'headRefOid': '{head}', 'url': 'u'}}]))\n", + encoding="utf-8") + monkeypatch.setenv("FAST_FORWARD_GH", json.dumps([sys.executable, str(stub)])) + assert actions(plan(work, tmp_path, "--gh")) == ["ff-ref", "switch"] + stub.write_text("import json\nprint(json.dumps([{'number': 7, 'headRefOid': '0' * 40, 'url': 'u'}]))\n", + encoding="utf-8") + assert actions(plan(work, tmp_path, "--gh")) == ["ff-ref"] # merged at an older head: later commits not covered + + +def test_stale_plan_is_refused(env, tmp_path): + work, other = setup(tmp_path) + push_new(other) + plan(work, tmp_path) + (work / "a.txt").write_bytes(b"edited after planning\n") + code, receipt = apply(tmp_path) + assert code == 1 + assert receipt["repos"][0]["outcomes"][0]["result"] == "refused" + assert "tracked" in receipt["repos"][0]["outcomes"][0]["reason"] + + +def test_config_unchanged_with_auto_tracking_settings(env, tmp_path): + env.write_text(env.read_text(encoding="utf-8") + "[branch]\n\tautoSetupMerge = always\n" + "[push]\n\tautoSetupRemote = true\n", encoding="utf-8") + work, other = setup(tmp_path) + g(work, "switch", "-q", "--no-track", "-c", "topic") + g(other, "push", "-q", "origin", "HEAD:refs/heads/topic") + push_new(other) + before = digest(work) + plan(work, tmp_path) + code, receipt = apply(tmp_path) + assert code == 0, receipt + assert digest(work) == before + assert receipt["repos"][0]["config_digest"] == plan(work, tmp_path)["repos"][0]["evidence"]["config_digest"] + + +def test_fetch_failure_is_reported_not_waited_on(env, tmp_path): + work, _ = setup(tmp_path) + g(work, "remote", "set-url", "origin", str(tmp_path / "missing.git")) + p = plan(work, tmp_path) + assert actions(p) == ["needs-human"] + assert "fetch failed" in p["repos"][0]["rows"][0]["reason"]