Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

fix(harness): guard harness-revert --hard against dropping non-session commits

Jerome4a0541719b38
diff --git a/.claude/commands/harness-revert.md b/.claude/commands/harness-revert.md
index 6d985dde..aabef75b 100644
--- a/.claude/commands/harness-revert.md
+++ b/.claude/commands/harness-revert.md
@@ -15,12 +15,14 @@ Revert everything a harness session merged into your branch, then remove its tem
2. **Show what will be undone, then confirm — including the strategy.** Run `git --no-pager diff --stat session-base/<short>..session/<short>` and name the base branch it landed on. Ask the user to confirm with `AskUserQuestion`, offering the two strategies (default unless the user already said which):
- **revert** (default, safe): keeps history, adds a revert commit; safe even if other sessions landed on the same branch afterwards.
- **hard** (clean history): `git reset --hard` to the session's fork point — the session's commits disappear entirely (no merge, no revert commit), but anything else committed after the fork is also dropped. Best when this session is the only thing on the branch (e.g. demos). If the user asked to "completely remove the branch / drop the commits / clean history", pick this.
+ **Before offering hard, preview the collateral.** Run `git --no-pager log --oneline session-base/<short>..HEAD`: these are ALL commits `--hard` would drop, not just the session's. If any are unrelated to the session (e.g. the user's own commits made after the session forked, common for a `#technical-harness` run, which never promotes onto the base branch so its work is not even there), warn explicitly that hard would delete them too, and steer to **revert** (or, for a non-promoted session, note that default mode cleans up branches/worktrees without touching the base branch at all). The script enforces this: `--hard` refuses when such collateral exists unless `--force`.
Do not proceed without an explicit yes.
3. **On confirmation, run the script** from the repo root (append `--hard` for the clean-history strategy):
```
- node "$(git rev-parse --show-toplevel)/.claude/scripts/harness-revert.mjs" <short> [--hard]
+ node "$(git rev-parse --show-toplevel)/.claude/scripts/harness-revert.mjs" <short> [--hard] [--force]
```
+ If `--hard` refuses because it would drop commits not belonging to the session, do NOT reflexively add `--force`; relay the listed commits to the user and re-confirm; `--force` bypasses the guard and permanently drops them.
(Run it once with `--dry-run` appended first if you want to preview the exact git actions.) Relay the script's output. Default mode reverts this session's promotion merge commit(s) (safe even if other sessions landed on the same branch); `--hard` resets the base branch to the fork point (refuses if history diverged). Either way it then removes the session's worktrees, branches, `sessionbase.<short>` config, and `/tmp` dir.
4. **If the script reports a conflict**, tell the user which step stopped and that another session likely touched the same files; they must resolve it manually before re-running. Never force the revert.
diff --git a/.claude/scripts/harness-revert.mjs b/.claude/scripts/harness-revert.mjs
index dd350f36..b78353aa 100755
--- a/.claude/scripts/harness-revert.mjs
+++ b/.claude/scripts/harness-revert.mjs
@@ -28,13 +28,16 @@ import { join } from "node:path";
const argv = process.argv.slice(2);
const DRY_RUN = argv.includes("--dry-run") || argv.includes("-n");
const HARD = argv.includes("--hard");
+const FORCE = argv.includes("--force");
const SHORT = argv.find((a) => !a.startsWith("-"));
const log = (msg) => process.stdout.write(`${msg}\n`);
const err = (msg) => process.stderr.write(`${msg}\n`);
if (!SHORT) {
- err("usage: harness-revert.mjs <SESSION_SHORT_ID> [--hard] [--dry-run]");
+ err(
+ "usage: harness-revert.mjs <SESSION_SHORT_ID> [--hard] [--force] [--dry-run]",
+ );
process.exit(2);
}
@@ -124,6 +127,44 @@ if (HARD) {
);
process.exit(1);
}
+ // Safety: `reset --hard` drops EVERYTHING in forkSha..HEAD, not just the
+ // session. The session's own footprint here is its promotion merge(s) plus the
+ // commits reachable from session/<short>; anything else is UNRELATED work (e.g.
+ // commits you made on the base branch after the session forked) that --hard
+ // would silently destroy. Refuse when such collateral exists, unless --force.
+ const sessionRef = `session/${SHORT}`;
+ const hasSessionBranch =
+ git(["show-ref", "--verify", "--quiet", `refs/heads/${sessionRef}`])
+ .code === 0;
+ const collateral = git(["rev-list", `${forkSha}..HEAD`])
+ .out.split("\n")
+ .filter(Boolean)
+ .filter((sha) => {
+ if (
+ git(["show", "-s", "--format=%s", sha]).out ===
+ `merge(session): ${SHORT}`
+ )
+ return false; // this session's promotion merge
+ if (
+ hasSessionBranch &&
+ git(["merge-base", "--is-ancestor", sha, sessionRef]).code === 0
+ )
+ return false; // brought in by the session
+ return true; // unrelated commit
+ });
+ if (collateral.length && !FORCE) {
+ err(
+ `!! reset --hard to ${anchor} would ALSO drop ${collateral.length} commit(s) NOT part of session ${SHORT}:`,
+ );
+ for (const sha of collateral.slice(0, 20))
+ err(` ${git(["show", "-s", "--format=%h %s", sha]).out}`);
+ if (collateral.length > 20)
+ err(` ... and ${collateral.length - 20} more`);
+ err(
+ ` These would be permanently removed from ${CURRENT_BRANCH}. Use the default (revert) mode (drop --hard) - it never touches unrelated commits - or re-run with --force if you really mean to reset to the fork point.`,
+ );
+ if (!DRY_RUN) process.exit(1);
+ }
stashDirty();
log(
`==> Hard-resetting ${CURRENT_BRANCH} to ${anchor} (${forkSha.slice(0, 12)}) — the session disappears from history`,
diff --git a/.claude/scripts/test/harness-revert.test.mjs b/.claude/scripts/test/harness-revert.test.mjs
new file mode 100644
index 00000000..4aabbfe3
--- /dev/null
+++ b/.claude/scripts/test/harness-revert.test.mjs
@@ -0,0 +1,73 @@
+// Tests for harness-revert.mjs --hard collateral guard: `reset --hard` to the
+// session fork point must NOT silently drop commits that are not part of the
+// session (e.g. the user's own commits made on the base branch after the fork).
+
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, test } from "vitest";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const SCRIPT = join(HERE, "..", "harness-revert.mjs");
+const SHORT = "beef1234";
+
+let TMP = null;
+afterEach(() => {
+ if (TMP) rmSync(TMP, { recursive: true, force: true });
+ TMP = null;
+});
+
+// A repo forked at `base`, a session branch with one change, and one UNRELATED
+// commit on main made AFTER the fork (the collateral --hard would drop).
+const setup = () => {
+ TMP = mkdtempSync(join(tmpdir(), "harness-revert-test-"));
+ const app = join(TMP, "app");
+ const g = (...a) => spawnSync("git", ["-C", app, ...a], { encoding: "utf8" });
+ spawnSync("git", ["init", "-q", "-b", "main", app]);
+ g("config", "user.email", "[email protected]");
+ g("config", "user.name", "t");
+ writeFileSync(join(app, "file.txt"), "base\n");
+ g("add", ".");
+ g("commit", "-qm", "base");
+ const forkSha = g("rev-parse", "HEAD").stdout.trim();
+ g("branch", `session-base/${SHORT}`);
+ g("branch", `session/${SHORT}`);
+ // session work lands on the session branch (never merged to main here)
+ g("checkout", "-q", `session/${SHORT}`);
+ writeFileSync(join(app, "file.txt"), "session change\n");
+ g("add", ".");
+ g("commit", "-qm", "session work");
+ g("checkout", "-q", "main");
+ // the user's unrelated commit on main, AFTER the fork
+ writeFileSync(join(app, "unrelated.txt"), "my own work\n");
+ g("add", ".");
+ g("commit", "-qm", "unrelated commit");
+ g("config", "--local", `sessionbase.${SHORT}.branch`, "main");
+
+ const head = () => g("rev-parse", "HEAD").stdout.trim();
+ const run = (...args) =>
+ spawnSync("node", [SCRIPT, SHORT, ...args], { cwd: app, encoding: "utf8" });
+ return { app, forkSha, head, run };
+};
+
+describe("harness-revert --hard collateral guard", () => {
+ test("refuses --hard when it would drop non-session commits", () => {
+ const { head, run } = setup();
+ const before = head();
+ const r = run("--hard");
+ expect(r.status).toBe(1);
+ expect(r.stderr).toMatch(/NOT part of session/);
+ expect(r.stderr).toContain("unrelated commit");
+ // HEAD untouched — nothing was reset.
+ expect(head()).toBe(before);
+ });
+
+ test("--force lets --hard reset to the fork point", () => {
+ const { forkSha, head, run } = setup();
+ const r = run("--hard", "--force");
+ expect(r.status).toBe(0);
+ expect(head()).toBe(forkSha);
+ });
+});