import { execFileSync } from "node:child_process"; import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { basename, join, resolve } from "node:path"; import type { ExtensionContext } from "@selesai/code"; /** Kept inside `.git` so a `git add -A` checkpoint never commits it. */ const RUN_STATE_FILE_NAME = "selesai-implement-run.json"; export interface RunState { taskDir: string; branch: string; startCommit: string; worktrees: string[]; } export const SQUASH_CHOICES = ["Squash into one commit", "Leave as staged changes", "Keep commits"] as const; function git(cwd: string, args: string[]): string { return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); } function worktreePaths(cwd: string): string[] { return git(cwd, ["worktree", "list", "--porcelain"]) .split("\n") .filter((line) => line.startsWith("worktree ")) .map((line) => line.slice("worktree ".length)); } export function runStatePath(cwd: string): string | undefined { try { return resolve(cwd, git(cwd, ["rev-parse", "--git-path", RUN_STATE_FILE_NAME])); } catch { return undefined; } } /** Records where the run starts. Returns undefined outside git or on a detached HEAD. */ export function recordRunStart(cwd: string, taskDir: string): { state: RunState; dirty: boolean } | undefined { const statePath = runStatePath(cwd); if (!statePath) return undefined; try { const branch = git(cwd, ["symbolic-ref", "--short", "HEAD"]); const state: RunState = { taskDir, branch, startCommit: git(cwd, ["rev-parse", "HEAD"]), worktrees: worktreePaths(cwd) }; writeFileSync(statePath, `${JSON.stringify(state, null, "\t")}\n`, "utf8"); return { state, dirty: git(cwd, ["status", "--porcelain"]) !== "" }; } catch { rmSync(statePath, { force: true }); return undefined; } } export function readRunState(statePath: string): RunState | undefined { if (!existsSync(statePath)) return undefined; try { return JSON.parse(readFileSync(statePath, "utf8")) as RunState; } catch { return undefined; } } function planTitle(taskDir: string): string { try { const heading = readFileSync(join(taskDir, "plan.md"), "utf8").match(/^#\s+(.+)$/m)?.[1]?.trim(); if (heading) return heading; } catch {} return basename(taskDir); } /** Reports leftover worktrees and offers to squash the run's commits. Never deletes or force-resets. */ export async function finishRun(cwd: string, state: RunState, ctx: Pick): Promise { const notes: string[] = []; const leftovers = worktreePaths(cwd).filter((path) => !state.worktrees.includes(path)); if (leftovers.length > 0) notes.push(`Worktrees left from this run:\n${leftovers.map((path) => `- ${path}`).join("\n")}`); const skip = (reason: string) => ctx.ui.notify([...notes, `Commits not squashed: ${reason}`].join("\n\n"), "warning"); const branch = git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]); if (branch !== state.branch) return skip(`now on ${branch}, the run started on ${state.branch}.`); try { git(cwd, ["merge-base", "--is-ancestor", state.startCommit, "HEAD"]); } catch { return skip(`the start commit ${state.startCommit.slice(0, 9)} is no longer in the branch history.`); } const commits = git(cwd, ["log", "--format=%h %s", `${state.startCommit}..HEAD`]).split("\n").filter(Boolean); if (commits.length === 0) { if (notes.length > 0) ctx.ui.notify(notes.join("\n\n"), "warning"); return; } const unpushed = git(cwd, ["rev-list", "--count", `${state.startCommit}..HEAD`, "--not", "--remotes"]); if (Number(unpushed) !== commits.length) return skip("some of them are already pushed."); if (!ctx.hasUI) return skip("no UI to confirm."); const choice = await ctx.ui.select( [...notes, `/implement made ${commits.length} commit(s):\n${commits.map((line) => `- ${line}`).join("\n")}`].join("\n\n"), [...SQUASH_CHOICES], ); if (choice !== SQUASH_CHOICES[0] && choice !== SQUASH_CHOICES[1]) return; git(cwd, ["reset", "--soft", state.startCommit]); if (choice === SQUASH_CHOICES[0]) { git(cwd, ["commit", "--quiet", "-m", planTitle(state.taskDir)]); ctx.ui.notify(`Squashed ${commits.length} commit(s) into one. The old commits are at ORIG_HEAD.`, "info"); } else { ctx.ui.notify(`Undid ${commits.length} commit(s); their changes are staged. The old commits are at ORIG_HEAD.`, "info"); } }