// PEP-25: after a story is accepted/merged, the project's working copy follows main. import { existsSync } from "node:fs"; import { join } from "node:path"; import { listSessions, type TaskRef } from "@peppa/core"; import type { Db } from "@peppa/db"; import { git } from "./git.ts"; /** * Brings the project's working copy to the merged main: fetch, and — when no agent works * there, the tree is clean and it is on main or on the story's branch — checkout main, * fast-forward, delete the merged local story branch. Anything else is left alone. * `PEPPA_WORKSPACE_SYNC=off` disables it. */ export async function syncWorkspace(db: Db, ref: TaskRef): Promise<"synced" | "busy" | "dirty" | "other_branch" | "no_git" | "off"> { if (process.env.PEPPA_WORKSPACE_SYNC === "off") return "off"; const dir = ref.project.workspacePath; if (!existsSync(join(dir, ".git"))) return "no_git"; // Busy: a runner in this working copy (not in its own worktree, PEP-27) works on a story // or is a free runner; an idle queue runner whose story left work doesn't hold it (PEP-10). const working = ["proposing", "awaiting_approval", "in_progress", "blocked"]; const here = (await listSessions(db, { active: true, projectId: ref.project.id })).filter((s) => !s.workspacePath); if (here.some((s) => s.taskId == null || (s.taskId !== ref.task.id && working.includes(s.taskStatus ?? "")))) return "busy"; const def = ref.project.defaultBranch; const branch = (await git(dir, "rev-parse", "--abbrev-ref", "HEAD")).stdout.trim(); const storyBranch = `task/${ref.key}`.toLowerCase(); if (branch !== def && !branch.toLowerCase().startsWith(storyBranch)) return "other_branch"; if ((await git(dir, "status", "--porcelain")).stdout.trim()) return "dirty"; await git(dir, "fetch", "--prune", "origin"); if (branch !== def) await git(dir, "checkout", def); await git(dir, "merge", "--ff-only", `origin/${def}`); const local = (await git(dir, "branch", "--format=%(refname:short)")).stdout.split("\n").map((b) => b.trim()); for (const b of local.filter((b) => b.toLowerCase().startsWith(storyBranch))) await git(dir, "branch", "-d", b).catch(() => {}); return "synced"; }