From 0ffcb6b4f6d0dca9fe3e32ca10abd091ff9492f1 Mon Sep 17 00:00:00 2001 From: Vladimir Bragin Date: Sat, 28 Nov 2026 21:58:03 -0600 Subject: [PATCH 1/3] feat(fast-forward): deterministic harness and the remaining ideas Add scripts/fast_forward.py (stdlib): inventory, rule-based plan rows (noop, ff, ff-ref, archive-ff, switch, needs-human) and an apply that runs only fast-forward rows after re-checking the planned evidence, checks the git config digest after each action and writes a receipt. Fetch runs with prompts off and a per-repo timeout that stops the whole process tree. SKILL.md gains sync (default) and land modes, scope and multi-session rules, the harness, --no-track branch creation, bounded check polling, the after-fast-forward deploy and retry rules, and the per-repo report. references/details.md holds CI-state, cross-PC, Windows and snapshot notes. Refs scf-9wg8d Co-Authored-By: Claude Opus 5.5 --- .agent/SKILL_INVENTORY.md | 2 +- .agents/skills/fast-forward/SKILL.md | 84 ++- .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 573 ++++++++++++++++++ .claude/skills/fast-forward/SKILL.md | 84 ++- .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 573 ++++++++++++++++++ .cursor/skills/fast-forward/SKILL.md | 84 ++- .../skills/fast-forward/references/details.md | 41 ++ .../fast-forward/scripts/fast_forward.py | 573 ++++++++++++++++++ CHANGELOG.md | 5 +- docs/agent-asset-inventory.md | 2 +- .../fast-forward-lands-through-pinned-pr.json | 10 +- tests/test_fast_forward.py | 271 +++++++++ 14 files changed, 2361 insertions(+), 23 deletions(-) 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/references/details.md create mode 100644 .claude/skills/fast-forward/scripts/fast_forward.py create mode 100644 .cursor/skills/fast-forward/references/details.md create mode 100644 .cursor/skills/fast-forward/scripts/fast_forward.py create mode 100644 tests/test_fast_forward.py diff --git a/.agent/SKILL_INVENTORY.md b/.agent/SKILL_INVENTORY.md index 3cc3e75..1289cab 100644 --- a/.agent/SKILL_INVENTORY.md +++ b/.agent/SKILL_INVENTORY.md @@ -26,7 +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 | L2 | 2026-11-27 | | 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. User-typed only | L2 | 2026-11-29 | +| 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 | diff --git a/.agents/skills/fast-forward/SKILL.md b/.agents/skills/fast-forward/SKILL.md index abb4948..474b0c5 100644 --- a/.agents/skills/fast-forward/SKILL.md +++ b/.agents/skills/fast-forward/SKILL.md @@ -1,11 +1,11 @@ --- name: fast-forward -description: "Bring the default branch of the current repository level with its remote and land the local work that belongs there: fetch, fast-forward the default branch, 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." +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 and 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: "git and gh, authenticated for the repository's own remote." -output_schema: "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." +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 --- @@ -17,6 +17,15 @@ Typing it approves one commit of the intended tracked changes, one push of a new 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`, "catch up", "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The 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 @@ -24,6 +33,16 @@ How this differs from neighbours: 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 @@ -35,7 +54,32 @@ How this differs from neighbours: - **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 +## 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 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 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 @@ -51,6 +95,8 @@ git rev-list --left-right --count HEAD...origin/ # " " 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 @@ -61,7 +107,8 @@ git rev-list --left-right --count HEAD...origin/ # " " - **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. -- Branch `chore/-` (or the project's pattern, such as `af/-`). Stage +- 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. @@ -79,7 +126,8 @@ project tracks work. ## 5. Merge pinned to the pushed commit -- **Same gate as `/merge-pr`.** Wait about five minutes after the push for checks to register. Then +- **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 @@ -110,13 +158,34 @@ git branch -d # -d, not -D: it mus 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 @@ -126,3 +195,6 @@ already have deleted the local branch, so a failing `git branch -d` there is har - 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. \ No newline at end of file diff --git a/.agents/skills/fast-forward/references/details.md b/.agents/skills/fast-forward/references/details.md new file mode 100644 index 0000000..3786602 --- /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 stops the whole tree on timeout. + +## 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..d350c39 --- /dev/null +++ b/.agents/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,573 @@ +#!/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 files that 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) + rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u in incoming] + 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", 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", 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/fast-forward/SKILL.md b/.claude/skills/fast-forward/SKILL.md index abb4948..474b0c5 100644 --- a/.claude/skills/fast-forward/SKILL.md +++ b/.claude/skills/fast-forward/SKILL.md @@ -1,11 +1,11 @@ --- name: fast-forward -description: "Bring the default branch of the current repository level with its remote and land the local work that belongs there: fetch, fast-forward the default branch, 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." +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 and 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: "git and gh, authenticated for the repository's own remote." -output_schema: "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." +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 --- @@ -17,6 +17,15 @@ Typing it approves one commit of the intended tracked changes, one push of a new 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`, "catch up", "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The 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 @@ -24,6 +33,16 @@ How this differs from neighbours: 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 @@ -35,7 +54,32 @@ How this differs from neighbours: - **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 +## 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 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 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 @@ -51,6 +95,8 @@ git rev-list --left-right --count HEAD...origin/ # " " 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 @@ -61,7 +107,8 @@ git rev-list --left-right --count HEAD...origin/ # " " - **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. -- Branch `chore/-` (or the project's pattern, such as `af/-`). Stage +- 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. @@ -79,7 +126,8 @@ project tracks work. ## 5. Merge pinned to the pushed commit -- **Same gate as `/merge-pr`.** Wait about five minutes after the push for checks to register. Then +- **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 @@ -110,13 +158,34 @@ git branch -d # -d, not -D: it mus 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 @@ -126,3 +195,6 @@ already have deleted the local branch, so a failing `git branch -d` there is har - 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. \ No newline at end of file diff --git a/.claude/skills/fast-forward/references/details.md b/.claude/skills/fast-forward/references/details.md new file mode 100644 index 0000000..3786602 --- /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 stops the whole tree on timeout. + +## 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..d350c39 --- /dev/null +++ b/.claude/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,573 @@ +#!/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 files that 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) + rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u in incoming] + 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", 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", 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/fast-forward/SKILL.md b/.cursor/skills/fast-forward/SKILL.md index abb4948..474b0c5 100644 --- a/.cursor/skills/fast-forward/SKILL.md +++ b/.cursor/skills/fast-forward/SKILL.md @@ -1,11 +1,11 @@ --- name: fast-forward -description: "Bring the default branch of the current repository level with its remote and land the local work that belongs there: fetch, fast-forward the default branch, 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." +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 and 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: "git and gh, authenticated for the repository's own remote." -output_schema: "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." +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 --- @@ -17,6 +17,15 @@ Typing it approves one commit of the intended tracked changes, one push of a new 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`, "catch up", "bring my checkouts up to date" | +| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The 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 @@ -24,6 +33,16 @@ How this differs from neighbours: 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 @@ -35,7 +54,32 @@ How this differs from neighbours: - **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 +## 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 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 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 @@ -51,6 +95,8 @@ git rev-list --left-right --count HEAD...origin/ # " " 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 @@ -61,7 +107,8 @@ git rev-list --left-right --count HEAD...origin/ # " " - **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. -- Branch `chore/-` (or the project's pattern, such as `af/-`). Stage +- 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. @@ -79,7 +126,8 @@ project tracks work. ## 5. Merge pinned to the pushed commit -- **Same gate as `/merge-pr`.** Wait about five minutes after the push for checks to register. Then +- **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 @@ -110,13 +158,34 @@ git branch -d # -d, not -D: it mus 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 @@ -126,3 +195,6 @@ already have deleted the local branch, so a failing `git branch -d` there is har - 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. \ No newline at end of file diff --git a/.cursor/skills/fast-forward/references/details.md b/.cursor/skills/fast-forward/references/details.md new file mode 100644 index 0000000..3786602 --- /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 stops the whole tree on timeout. + +## 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..d350c39 --- /dev/null +++ b/.cursor/skills/fast-forward/scripts/fast_forward.py @@ -0,0 +1,573 @@ +#!/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 files that 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) + rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u in incoming] + 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", 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", 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/CHANGELOG.md b/CHANGELOG.md index f66513d..e6f6010 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,10 @@ All notable changes to this framework are documented here. The format follows 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. + 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 ce608e4..a96b717 100644 --- a/docs/agent-asset-inventory.md +++ b/docs/agent-asset-inventory.md @@ -81,7 +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 level with its remote and land the local work that belongs there: fetch, fast-forward the default branch, 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. | +| `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/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json index e24d7b6..b431826 100644 --- a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json +++ b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json @@ -21,7 +21,12 @@ "**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." + "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." ], "must_not_contain": [ "side_effect_level: read_only", @@ -30,6 +35,7 @@ "git reset --hard", "or asks to fetch, pull", "push -u", - "sync-upstream-fork" + "sync-upstream-fork", + "Wait about five minutes" ] } diff --git a/tests/test_fast_forward.py b/tests/test_fast_forward.py new file mode 100644 index 0000000..fb85242 --- /dev/null +++ b/tests/test_fast_forward.py @@ -0,0 +1,271 @@ +"""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" + + +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"] From 180780f0fc00c8c36b427889dcdd1f5f255b33f5 Mon Sep 17 00:00:00 2001 From: Vladimir Bragin Date: Sat, 28 Nov 2026 22:28:35 -0600 Subject: [PATCH 2/3] fix(fast-forward): ignored-file collisions, branch -f without tracking Ignored files the incoming commits add now count as collisions (a fast-forward overwrites them silently); merge and switch run with --no-overwrite-ignore. git branch -f from origin/ set up tracking in .git/config, so the land step uses --no-track. Land compares the config digest before and after. Tests cover both, plus the git timeout. Refs scf-9wg8d Co-Authored-By: Claude Opus 5.5 --- .agents/skills/fast-forward/SKILL.md | 13 +++++----- .../skills/fast-forward/references/details.md | 2 +- .../fast-forward/scripts/fast_forward.py | 11 +++++--- .claude/skills/fast-forward/SKILL.md | 13 +++++----- .../skills/fast-forward/references/details.md | 2 +- .../fast-forward/scripts/fast_forward.py | 11 +++++--- .cursor/skills/fast-forward/SKILL.md | 13 +++++----- .../skills/fast-forward/references/details.md | 2 +- .../fast-forward/scripts/fast_forward.py | 11 +++++--- .../fast-forward-lands-through-pinned-pr.json | 2 +- tests/test_fast_forward.py | 26 +++++++++++++++++++ 11 files changed, 72 insertions(+), 34 deletions(-) diff --git a/.agents/skills/fast-forward/SKILL.md b/.agents/skills/fast-forward/SKILL.md index 474b0c5..dd0bbca 100644 --- a/.agents/skills/fast-forward/SKILL.md +++ b/.agents/skills/fast-forward/SKILL.md @@ -19,8 +19,8 @@ default branch. | Mode | What it does | Runs when | |---|---|---| -| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward`, "catch up", "bring my checkouts up to date" | -| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The request also says commit, push or merge | +| **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. @@ -70,9 +70,9 @@ python -I "$FF" apply --plan /ff-plan.json [--backup-dir # " " 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 origin/` moves only the + 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. @@ -154,7 +154,8 @@ git rev-list --left-right --count HEAD...origin/ # must print "0 0" git branch -d # -d, not -D: it must be merged ``` -`gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +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. diff --git a/.agents/skills/fast-forward/references/details.md b/.agents/skills/fast-forward/references/details.md index 3786602..17a1423 100644 --- a/.agents/skills/fast-forward/references/details.md +++ b/.agents/skills/fast-forward/references/details.md @@ -31,7 +31,7 @@ Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Ba - 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 stops the whole tree on timeout. + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). ## Generated snapshots diff --git a/.agents/skills/fast-forward/scripts/fast_forward.py b/.agents/skills/fast-forward/scripts/fast_forward.py index d350c39..9abfa97 100644 --- a/.agents/skills/fast-forward/scripts/fast_forward.py +++ b/.agents/skills/fast-forward/scripts/fast_forward.py @@ -5,7 +5,7 @@ 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 files that the incoming + 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 @@ -287,7 +287,10 @@ def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, 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) - rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u 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"]: @@ -470,7 +473,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", origin, read_only=False) + 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}") @@ -482,7 +485,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", d, read_only=False) + 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")} diff --git a/.claude/skills/fast-forward/SKILL.md b/.claude/skills/fast-forward/SKILL.md index 474b0c5..dd0bbca 100644 --- a/.claude/skills/fast-forward/SKILL.md +++ b/.claude/skills/fast-forward/SKILL.md @@ -19,8 +19,8 @@ default branch. | Mode | What it does | Runs when | |---|---|---| -| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward`, "catch up", "bring my checkouts up to date" | -| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The request also says commit, push or merge | +| **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. @@ -70,9 +70,9 @@ python -I "$FF" apply --plan /ff-plan.json [--backup-dir # " " 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 origin/` moves only the + 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. @@ -154,7 +154,8 @@ git rev-list --left-right --count HEAD...origin/ # must print "0 0" git branch -d # -d, not -D: it must be merged ``` -`gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +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. diff --git a/.claude/skills/fast-forward/references/details.md b/.claude/skills/fast-forward/references/details.md index 3786602..17a1423 100644 --- a/.claude/skills/fast-forward/references/details.md +++ b/.claude/skills/fast-forward/references/details.md @@ -31,7 +31,7 @@ Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Ba - 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 stops the whole tree on timeout. + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). ## Generated snapshots diff --git a/.claude/skills/fast-forward/scripts/fast_forward.py b/.claude/skills/fast-forward/scripts/fast_forward.py index d350c39..9abfa97 100644 --- a/.claude/skills/fast-forward/scripts/fast_forward.py +++ b/.claude/skills/fast-forward/scripts/fast_forward.py @@ -5,7 +5,7 @@ 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 files that the incoming + 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 @@ -287,7 +287,10 @@ def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, 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) - rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u 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"]: @@ -470,7 +473,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", origin, read_only=False) + 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}") @@ -482,7 +485,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", d, read_only=False) + 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")} diff --git a/.cursor/skills/fast-forward/SKILL.md b/.cursor/skills/fast-forward/SKILL.md index 474b0c5..dd0bbca 100644 --- a/.cursor/skills/fast-forward/SKILL.md +++ b/.cursor/skills/fast-forward/SKILL.md @@ -19,8 +19,8 @@ default branch. | Mode | What it does | Runs when | |---|---|---| -| **sync** (default) | Inventory, plan, fast-forward-only apply (steps 0–2, then 7) | `/fast-forward`, "catch up", "bring my checkouts up to date" | -| **land** | sync, then commit, push, PR, pinned merge, sync again (steps 3–6) | The request also says commit, push or merge | +| **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. @@ -70,9 +70,9 @@ python -I "$FF" apply --plan /ff-plan.json [--backup-dir # " " 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 origin/` moves only the + 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. @@ -154,7 +154,8 @@ git rev-list --left-right --count HEAD...origin/ # must print "0 0" git branch -d # -d, not -D: it must be merged ``` -`gh pr merge --delete-branch` removes the remote branch, often switches the local checkout, and may +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. diff --git a/.cursor/skills/fast-forward/references/details.md b/.cursor/skills/fast-forward/references/details.md index 3786602..17a1423 100644 --- a/.cursor/skills/fast-forward/references/details.md +++ b/.cursor/skills/fast-forward/references/details.md @@ -31,7 +31,7 @@ Load this when a run crosses PCs, hits CI that looks wrong, or runs under Git Ba - 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 stops the whole tree on timeout. + own process group and, on timeout, tries to stop the whole tree (`taskkill /T` or the process group). ## Generated snapshots diff --git a/.cursor/skills/fast-forward/scripts/fast_forward.py b/.cursor/skills/fast-forward/scripts/fast_forward.py index d350c39..9abfa97 100644 --- a/.cursor/skills/fast-forward/scripts/fast_forward.py +++ b/.cursor/skills/fast-forward/scripts/fast_forward.py @@ -5,7 +5,7 @@ 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 files that the incoming + 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 @@ -287,7 +287,10 @@ def inventory_repo(path: str | Path, timeout: float = 60, use_gh: bool = False, 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) - rec["collisions"] = [collision(top, u, rec["origin_sha"]) for u in untracked if u 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"]: @@ -470,7 +473,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", origin, read_only=False) + 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}") @@ -482,7 +485,7 @@ def execute(row: dict, now: dict, top: Path, d: str, origin: str, backup_dir: st 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", d, read_only=False) + 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")} diff --git a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json index b431826..080ec50 100644 --- a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json +++ b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json @@ -17,7 +17,7 @@ "# must print \"0 0\"", "git branch -d ", "git push origin ", - "git branch -f 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`", diff --git a/tests/test_fast_forward.py b/tests/test_fast_forward.py index fb85242..e519d8b 100644 --- a/tests/test_fast_forward.py +++ b/tests/test_fast_forward.py @@ -144,6 +144,32 @@ def test_different_untracked_copy_needs_human(env, tmp_path): 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") From d3d30b5ab4ef835de941849270f49bcd04afe44e Mon Sep 17 00:00:00 2001 From: Vladimir Bragin Date: Sun, 29 Nov 2026 01:19:53 -0600 Subject: [PATCH 3/3] docs(fast-forward): bare /fast-forward approves sync only The intro said typing /fast-forward approves a commit, push, PR and merge, contradicting sync as the default. Land approvals now apply only when the typed request also says commit, push or merge; the capability line says the same, and the eval fixture pins it. Refs scf-9wg8d Co-Authored-By: Claude Opus 5.5 --- .agents/skills/fast-forward/SKILL.md | 11 ++++++----- .claude/skills/fast-forward/SKILL.md | 11 ++++++----- .cursor/skills/fast-forward/SKILL.md | 11 ++++++----- .../fast-forward-lands-through-pinned-pr.json | 6 ++++-- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/.agents/skills/fast-forward/SKILL.md b/.agents/skills/fast-forward/SKILL.md index dd0bbca..52afa4b 100644 --- a/.agents/skills/fast-forward/SKILL.md +++ b/.agents/skills/fast-forward/SKILL.md @@ -1,7 +1,7 @@ --- 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 and land its intended tracked changes through a pinned PR merge, never by force or a direct push to the default branch." +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." @@ -12,9 +12,10 @@ disable-model-invocation: true # Fast-forward -`/fast-forward` means: **make my default branch match the remote, and land the work that belongs on it.** -Typing it 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 +`/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 | @@ -198,4 +199,4 @@ Then, for land: - 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. \ No newline at end of file +- 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/SKILL.md b/.claude/skills/fast-forward/SKILL.md index dd0bbca..52afa4b 100644 --- a/.claude/skills/fast-forward/SKILL.md +++ b/.claude/skills/fast-forward/SKILL.md @@ -1,7 +1,7 @@ --- 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 and land its intended tracked changes through a pinned PR merge, never by force or a direct push to the default branch." +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." @@ -12,9 +12,10 @@ disable-model-invocation: true # Fast-forward -`/fast-forward` means: **make my default branch match the remote, and land the work that belongs on it.** -Typing it 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 +`/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 | @@ -198,4 +199,4 @@ Then, for land: - 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. \ No newline at end of file +- 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/SKILL.md b/.cursor/skills/fast-forward/SKILL.md index dd0bbca..52afa4b 100644 --- a/.cursor/skills/fast-forward/SKILL.md +++ b/.cursor/skills/fast-forward/SKILL.md @@ -1,7 +1,7 @@ --- 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 and land its intended tracked changes through a pinned PR merge, never by force or a direct push to the default branch." +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." @@ -12,9 +12,10 @@ disable-model-invocation: true # Fast-forward -`/fast-forward` means: **make my default branch match the remote, and land the work that belongs on it.** -Typing it 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 +`/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 | @@ -198,4 +199,4 @@ Then, for land: - 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. \ No newline at end of file +- Retry a command a permission layer refused in another form. Finish the rest and hand it over as a `!` command. diff --git a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json index 080ec50..01077a2 100644 --- a/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json +++ b/evals/skill-scenarios/fast-forward-lands-through-pinned-pr.json @@ -26,7 +26,8 @@ "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." + "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", @@ -36,6 +37,7 @@ "or asks to fetch, pull", "push -u", "sync-upstream-fork", - "Wait about five minutes" + "Wait about five minutes", + "land the work that belongs on it.**\nTyping it approves" ] }