// PEP-23/24/25, spec project-autonomy: levels, dispatcher (no idle without a push), // auto-merge and closing, working copy after the merge — mock-claude runners, mock Gitea. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { core, db, project, runner, superadmin, teardown, waitFor, type TestProject } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { projects, tasks } from "@peppa/db"; import { eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-auto-")), "gitea")); const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" }; const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" }; before(async () => { await gitea.start(); process.env.GITEA_URL = gitea.url; process.env.GITEA_TOKEN = BOT.token; gitea.addUser(BOT); }); after(async () => { await gitea.stop(); await teardown(); }); const projectOf = (p: TestProject) => core.getProject(db, p.key); const taskOf = async (key: string) => (await core.resolveTask(db, key)).task; const openQuestions = async (projectId: number) => core.pendingQuestions(db, projectId); const activeOf = async (projectId: number) => (await core.listSessions(db, { active: true })).filter((s) => s.projectId === projectId); const autonomy = (now = new Date()) => runner.autonomyTick(db, { now }); /** Settings without quiet hours: tests run at any time of day. */ const NO_QUIET = { quietFrom: null, quietTo: null } as const; describe("autonomy settings", () => { test("a project without settings is manual; presets and custom combinations; validation", async () => { const p = await projectOf(await project({ turns: [] })); const s = await core.getAutonomy(db, p.id); assert.equal(core.autonomyLevel(s), "manual"); assert.deepEqual({ pick: s.pick, merge: s.merge, close: s.close, idlePush: s.idlePush }, { pick: "pm", merge: "manual", close: "pm", idlePush: false }); const auto = await core.setAutonomy(db, p.id, { level: "auto" }); assert.equal(core.autonomyLevel(auto), "auto"); assert.deepEqual({ pick: auto.pick, merge: auto.merge, close: auto.close }, { pick: "auto", merge: "auto", close: "after_merge" }); const custom = await core.setAutonomy(db, p.id, { proposal: "pm", close: "after_hours", closeAfterHours: 6 }); assert.equal(core.autonomyLevel(custom), "custom"); assert.equal(custom.pick, "auto", "fields override the current settings"); assert.match(core.describeAutonomy(custom), /каждый одобряет PM[\s\S]*через 6 ч/); await assert.rejects(core.setAutonomy(db, p.id, { wipLimit: 0 }), /wipLimit/); await assert.rejects(core.setAutonomy(db, p.id, { merge: "yolo" as never }), /merge/); await core.setAutonomy(db, p.id, { level: "manual" }); assert.equal(await core.getSetting(db, `project.autonomy:${p.id}`), null, "manual = no row, as before PEP-23"); }); test("quiet hours wrap over midnight", () => { const q = { quietFrom: 22, quietTo: 9 }; assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 23, 30)), true); assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 8, 59)), true); assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 12, 0)), false); assert.equal(core.inAutonomyQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false); }); }); describe("dispatcher", () => { test("manual (default): nothing starts by itself and the PM gets no push", async () => { const tp = await project({ turns: [] }); const p = await projectOf(tp); await runner.tick(db, { intervalMs: 0, stallMs: 60_000 }); assert.equal((await activeOf(p.id)).length, 0); assert.equal((await openQuestions(p.id)).length, 0); assert.equal((await taskOf(tp.taskKey)).status, "backlog"); }); test("auto: backlog → work → review → merged → done → next story, without a human; then 'backlog empty' once", async () => { const tp = await project({ turns: [[{ mcp: "update_task", args: { task: "$TASK", status: "review" } }, { say: "Готово, PR открыт." }]] }); const p = await projectOf(tp); const second = await core.createTask(db, { projectId: p.id, title: "вторая стори" }); await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); // The watchdog tick runs the dispatcher: the lowest number first, WIP 1. await runner.tick(db, { intervalMs: 0, stallMs: 600_000 }); let active = await activeOf(p.id); assert.equal(active.length, 1); assert.equal(active[0]!.taskKey, tp.taskKey); assert.equal((await taskOf(second.key)).status, "backlog", "WIP limit 1: the second story waits"); await waitFor("first story in review", async () => (await taskOf(tp.taskKey)).status === "review"); await waitFor("agent finished its turn", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input"); assert.equal((await openQuestions(p.id)).length, 0, "merge=auto: no 'ready for review' for the PM"); await autonomy(); assert.equal((await taskOf(tp.taskKey)).status, "done", "no PR → nothing to merge → closed after merge"); assert.equal((await core.getSession(db, active[0]!.id)).status, "done", "its agent stopped"); active = await activeOf(p.id); assert.equal(active[0]?.taskKey, second.key, "the next story was taken in the same tick"); await waitFor("second story in review", async () => (await taskOf(second.key)).status === "review"); await waitFor("second agent idle", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input"); await autonomy(); assert.equal((await taskOf(second.key)).status, "done"); const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")); assert.match(empty[0]?.text ?? "", /Что дальше: опишите следующую задачу аналитику в чате проекта/, "PEP-111: what to do next"); assert.equal(empty.length, 1); await autonomy(); assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once"); }); test("auto: nothing starts while a runner of the project is rate-limited or its pool is exhausted", async () => { const tp = await project({ turns: [] }); const p = await projectOf(tp); const other = await core.createTask(db, { projectId: p.id, title: "другая" }); await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); // A rate-limited runner on another story of the project. const s = await core.createSession(db, { projectId: p.id, taskId: other.task.id }); await core.updateSession(db, s.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3_600_000) }); await autonomy(); assert.equal((await taskOf(tp.taskKey)).status, "backlog"); await core.updateSession(db, s.id, { status: "done" }); const sub = await core.createSubscription(db, { provider: "claude", name: `mock-sub-${p.key}`, authKind: "oauth", secret: "mock-token" }); await core.updateSubscription(db, sub.id, { status: "limited", limitedUntil: new Date(Date.now() + 3_600_000) }); const pool = await core.createPool(db, { name: `mock-pool-${p.key}`, subscriptionIds: [sub.id] }); await core.setProjectPool(db, p.id, pool.id); assert.equal(await core.projectPoolExhausted(db, p.id), true); await autonomy(); assert.equal((await taskOf(tp.taskKey)).status, "backlog"); assert.equal((await openQuestions(p.id)).length, 0, "no push during a limit either"); }); test("auto: a failed start puts the story back, tells the superadmin once and backs off", async () => { const sent = await superadmin(); const tp = await project({ turns: [] }); const p = await projectOf(tp); await db.update(projects).set({ workspacePath: "/nonexistent/mock-ws" }).where(eq(projects.id, p.id)); await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); const now = new Date(); await autonomy(now); assert.equal((await taskOf(tp.taskKey)).status, "backlog"); // PEP-150: the owner is not told — the story shows the delay line, the superadmin gets one message. assert.equal((await openQuestions(p.id)).length, 0); assert.equal(await core.taskDelayed(db, (await taskOf(tp.taskKey)).id), true); const told = async () => (await sent()).filter((t) => t.includes("не смог запустить агента") && t.includes(tp.taskKey)); assert.equal((await told()).length, 1); await autonomy(new Date(now.getTime() + 30_000)); assert.equal((await core.getPlatformDelay(db, { projectId: p.id, taskId: (await taskOf(tp.taskKey)).id }, "start"))!.attempts, 1, "no retry storm within the back-off"); await autonomy(new Date(now.getTime() + 61_000)); assert.equal((await core.getPlatformDelay(db, { projectId: p.id, taskId: (await taskOf(tp.taskKey)).id }, "start"))!.attempts, 2, "retried after the pause"); assert.equal((await told()).length, 1, "a retry is not news"); }); test("PEP-185: «В работу» на вопросе «Взять в работу?» запускает агента", async () => { const tp = await project({ turns: [[{ say: "работаю" }]] }); const p = await projectOf(tp); process.env.PEPPA_PICK_QUESTION = "on"; try { await runner.pickQuestionTick(db); } finally { process.env.PEPPA_PICK_QUESTION = "off"; } const q = (await openQuestions(p.id)).find((x) => x.options?.includes(runner.PICK_TAKE)); assert.ok(q, "question raised"); await runner.answerAndDeliver(db, q.id, runner.PICK_TAKE, "telegram"); await waitFor("agent started", async () => (await activeOf(p.id)).length > 0); assert.equal((await taskOf(tp.taskKey)).status, "in_progress"); }); test("assisted: idle push with buttons — no duplicates; Next offers the next story; Not now snoozes; Take starts", async () => { const tp = await project({ turns: [[{ say: "работаю" }]] }); const p = await projectOf(tp); const second = await core.createTask(db, { projectId: p.id, title: "вторая" }); await core.setAutonomy(db, p.id, { level: "assisted", ...NO_QUIET }); await autonomy(); let [q] = await openQuestions(p.id); assert.ok(q, "pushed"); assert.match(q.text, /агенты простаивают/); assert.match(q.text, new RegExp(`Взять в работу ${tp.taskKey}`)); assert.equal(q.options?.length, 3); await autonomy(); assert.equal((await openQuestions(p.id)).length, 1, "one open push at a time"); await runner.answerAndDeliver(db, q.id, runner.IDLE_NEXT, "telegram"); [q] = await openQuestions(p.id); assert.match(q!.text, new RegExp(`Взять в работу ${second.key}`), "Next → the next story right away"); await runner.answerAndDeliver(db, q!.id, q!.options![2]!, "telegram"); assert.equal((await openQuestions(p.id)).length, 0); await autonomy(); assert.equal((await openQuestions(p.id)).length, 0, "Not now → quiet for idlePushHours"); await autonomy(new Date(Date.now() + 5 * 3_600_000)); [q] = await openQuestions(p.id); assert.ok(q, "pushed again after the snooze"); await runner.answerAndDeliver(db, q.id, q.options![0]!, "web"); assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "Take → the story is in work"); const active = await activeOf(p.id); assert.equal(active.length, 1); await autonomy(); assert.equal((await openQuestions(p.id)).filter((x) => x.text.includes("простаивают")).length, 0, "an agent works: no push"); await runner.stopSession(db, active[0]!.id); }); test("assisted: no push in quiet hours, nor more often than idlePushHours; a manual move closes the push", async () => { const tp = await project({ turns: [[{ say: "работаю" }]] }); const p = await projectOf(tp); await core.setAutonomy(db, p.id, { level: "assisted", quietFrom: 22, quietTo: 9, idlePushHours: 4 }); await autonomy(new Date(2026, 10, 14, 23, 0)); assert.equal((await openQuestions(p.id)).length, 0, "quiet hours"); await autonomy(new Date(2026, 10, 14, 10, 0)); const [q] = await openQuestions(p.id); assert.ok(q); // The PM starts the story from the board instead: the push is moot. const { started } = await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "in_progress"); await autonomy(new Date(2026, 10, 14, 10, 1)); assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system"); await runner.stopSession(db, started!); await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "backlog"); await autonomy(new Date(2026, 10, 14, 11, 0)); assert.equal((await openQuestions(p.id)).length, 0, "not more often than every 4 h"); await autonomy(new Date(2026, 10, 14, 14, 1)); assert.equal((await openQuestions(p.id)).length, 1); }); }); interface PrTask { tp: TestProject; proj: Awaited>; pr: { number: number }; push(files?: Record): string; green(sha: string): void; } /** A story in review with an open PR (task/-1) in mock Gitea. */ async function prTask(level: Parameters[2], turns: Parameters[0]["turns"] = []): Promise { const tp = await project({ turns }); const proj = await projectOf(tp); const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS }); writeFileSync(join(tp.dir, ".peppa/project.json"), pj); gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } }); gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write"; let n = 0; const push = (files: Record = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n), ...files }); const sha = push(); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); const green = (s: string) => { for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success"); }; green(sha); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }); await core.setAutonomy(db, proj.id, { ...level, ...NO_QUIET }); return { tp, proj, pr, push, green }; } const pull = (t: PrTask) => gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[t.pr.number - 1]!; describe("PEP-197: stories of agents in work", () => { test("three stories of agents in work: the fourth does not start; a story of a person does", async () => { const tp = await project({ turns: [] }); const p = await projectOf(tp); await core.setAutonomy(db, p.id, { level: "auto", wipLimit: 5, ...NO_QUIET }); const make = async (title: string, status: "backlog" | "in_progress") => { const ref = await core.createTask(db, { projectId: p.id, title, origin: "acceptance", severity: "breakage" }); await core.approveProposal(db, ref.task.id); // PEP-295: the owner said «Делать» if (status === "in_progress") await core.updateTask(db, ref, { status }); return ref; }; await make("поломка 1", "in_progress"); await make("поломка 2", "in_progress"); await make("поломка 3", "in_progress"); const fourth = await make("поломка 4", "backlog"); assert.equal(await core.agentTasksInWork(db, p.id), 3); await autonomy(); assert.equal((await taskOf(fourth.key)).status, "backlog", "the fourth story of an agent waits"); assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "a story of a person is not held by the limit"); await core.setAgentLimits(db, p.id, { inWork: 4 }); await autonomy(); assert.equal((await taskOf(fourth.key)).status, "in_progress", "the superadmin raised the limit"); }); test("«Предложено»: the dispatcher takes nothing from there until «Делать»", async () => { const tp = await project({ turns: [] }); const p = await projectOf(tp); await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "done" }); await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); const idea = await core.createTask(db, { projectId: p.id, title: "идея агента", origin: "acceptance", severity: "important", proposed: true }); assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), []); await autonomy(); assert.equal((await taskOf(idea.key)).status, "backlog"); assert.equal((await activeOf(p.id)).length, 0); await core.approveProposal(db, idea.task.id); assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [idea.task.id]); }); }); describe("auto-merge and closing", () => { test("merge=auto, close=after_merge: a green PR is merged and the story closed", async () => { const t = await prTask({ merge: "auto", close: "after_merge" }); await autonomy(); assert.equal(pull(t).merged, true); assert.equal((await taskOf(t.tp.taskKey)).status, "done"); }); test("merge=auto, close=pm: merged, then 'ready for review' with Accept → done", async () => { const t = await prTask({ merge: "auto", close: "pm" }); await autonomy(); assert.equal(pull(t).merged, true); assert.equal((await taskOf(t.tp.taskKey)).status, "review"); const [q] = await openQuestions(t.proj.id); assert.match(q!.text, /Изменения приняты автоматически/); assert.ok(await runner.isReviewQuestion(db, q!)); await autonomy(); assert.equal((await openQuestions(t.proj.id)).length, 1, "asked once"); await runner.acceptTask(db, q!.id, "telegram"); assert.equal((await taskOf(t.tp.taskKey)).status, "done"); }); test("PEP-197: a story of an agent (after «Делать») is not merged by default; a breakage and «всё» are", async () => { const mark = (t: PrTask, set: { origin: string; severity: string | null }) => Promise.resolve().then(async () => { const ref = await core.resolveTask(db, t.tp.taskKey); await db.update(tasks).set(set).where(eq(tasks.id, ref.task.id)); }); const important = await prTask({ merge: "auto", close: "after_merge" }); await mark(important, { origin: "acceptance", severity: "important" }); await autonomy(); assert.equal(pull(important).merged, false, "default «мои и поломки»: the owner accepts what the factory thought of"); assert.equal((await taskOf(important.tp.taskKey)).status, "review"); const [q] = await openQuestions(important.proj.id); assert.equal(q, undefined, "nothing is asked of the owner before the agent says it is ready"); const breakage = await prTask({ merge: "auto", close: "after_merge" }); await mark(breakage, { origin: "acceptance", severity: "breakage" }); await autonomy(); assert.equal(pull(breakage).merged, true, "a breakage is accepted automatically by default"); const mineOnly = await prTask({ merge: "auto", close: "after_merge", acceptOwn: "mine" }); await mark(mineOnly, { origin: "acceptance", severity: "breakage" }); await autonomy(); assert.equal(pull(mineOnly).merged, false, "«только мои задачи»: not even a breakage"); const all = await prTask({ merge: "auto", close: "after_merge", acceptOwn: "all" }); await mark(all, { origin: "acceptance", severity: "minor" }); await autonomy(); assert.equal(pull(all).merged, true, "«всё»"); }); test("pending checks: nothing merged yet", async () => { const t = await prTask({ merge: "auto", close: "after_merge" }); t.push(); // new head without statuses await autonomy(); assert.equal(pull(t).merged, false); assert.equal((await taskOf(t.tp.taskKey)).status, "review"); }); test("conflicts: the agent is asked to rebase (once per head commit)", async () => { const t = await prTask({ merge: "auto", close: "after_merge" }); pull(t).mergeable = false; await autonomy(); assert.equal(pull(t).merged, false); assert.equal((await taskOf(t.tp.taskKey)).status, "in_progress", "back to work"); const [s] = await activeOf(t.proj.id); assert.ok(s, "an agent was started for the rebase"); const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase")); assert.match(String(ev.prompt), /force-with-lease/); await runner.stopSession(db, s!.id); }); /** PEP-150: the superadmin is asked in the platform project. */ async function platformProject() { const plat = await project({ turns: [] }); process.env.PEPPA_PLATFORM_KEY = plat.key; const p = await core.getProject(db, plat.key); return async () => (await core.pendingQuestions(db, p.id)).filter((q) => q.text.includes("затрагивают проверки")); } test("pipeline change: not merged, the superadmin is asked once; Accept merges it; the owner gets nothing", async () => { const guard = await platformProject(); const t = await prTask({ merge: "auto", close: "after_merge" }); t.green(t.push({ ".gitea/workflows/ci.yml": "on: push\n" })); await autonomy(); await autonomy(); assert.equal(pull(t).merged, false); const qs = await guard(); assert.equal(qs.length, 1, "asked once per head commit"); assert.equal((await openQuestions(t.proj.id)).length, 0, "the owner gets nothing"); assert.equal((await runner.answerAndDeliver(db, qs[0]!.id, runner.GUARD_ACCEPT, "web")).delivered, true); assert.equal(pull(t).merged, true, "the superadmin's Accept merges it"); assert.equal((await taskOf(t.tp.taskKey)).status, "done"); }); test("pipeline change: «Вернуть агенту» sends the story back to work", async () => { const guard = await platformProject(); const t = await prTask({ merge: "auto", close: "after_merge" }, [[{ say: "Убрал." }]]); t.green(t.push({ ".gitea/workflows/ci.yml": "on: push\n" })); await autonomy(); const [q] = await guard(); await runner.answerAndDeliver(db, q!.id, runner.GUARD_RETURN, "web"); assert.equal(pull(t).merged, false); assert.equal((await taskOf(t.tp.taskKey)).status, "in_progress"); await t.tp.waitLog("agent told why", (e) => e.ev === "prompt" && String(e.prompt).includes("меняет конвейер")); assert.equal((await openQuestions(t.proj.id)).filter((x) => x.kind !== "attention").length, 0, "no question for the owner"); for (const s of await core.listSessions(db, { active: true, projectId: t.proj.id })) await runner.stopSession(db, s.id); }); test("close=after_hours: 'ready for review' without comments for N hours → accepted (PR merged)", async () => { const t = await prTask({ close: "after_hours", closeAfterHours: 2 }); const q = await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" }); await autonomy(new Date(Date.now() + 3_600_000)); assert.equal((await taskOf(t.tp.taskKey)).status, "review", "not yet"); await autonomy(new Date(Date.now() + 2 * 3_600_000 + 60_000)); assert.equal((await taskOf(t.tp.taskKey)).status, "done"); assert.equal(pull(t).merged, true); assert.match((await core.getQuestion(db, q.id)).answer ?? "", /автоматически/); }); test("close=after_hours never accepts a pipeline change by itself", async () => { const guard = await platformProject(); const t = await prTask({ close: "after_hours", closeAfterHours: 1 }); t.green(t.push({ ".gitea/peppa-check.sh": "exit 0\n" })); await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" }); await autonomy(new Date(Date.now() + 2 * 3_600_000)); assert.equal((await taskOf(t.tp.taskKey)).status, "review"); assert.equal(pull(t).merged, false); assert.equal((await guard()).length, 1, "the superadmin is asked"); assert.equal((await openQuestions(t.proj.id)).some((q) => q.text.includes("затрагивают проверки")), false, "not the owner"); }); }); describe("proposal approval and the working copy", () => { test("proposal=pm: the agent can't start Apply itself; the prompt says to request approval", async () => { const tp = await project({ turns: [ [ { mcp: "update_task", args: { task: "$TASK", status: "proposing", openspec_change: "x-1" } }, { mcp: "update_task", args: { task: "$TASK", status: "in_progress" } }, { mcp: "request_approval", args: { task: "$TASK", summary: "Proposal: сделать X без новых зависимостей" } }, ], ], }); const p = await projectOf(tp); await core.setAutonomy(db, p.id, { proposal: "pm" }); const sid = await tp.start(); const refused = await tp.waitLog("refused apply", (e) => e.ev === "mcp" && e.tool === "update_task" && e.isError === true); assert.match(String(refused.text), /approves every proposal/); assert.ok(tp.log().some((e) => e.ev === "prompt" && String(e.prompt).includes("PM одобряет каждый proposal"))); const q = await tp.waitQuestion(sid, "approval"); assert.equal((await taskOf(tp.taskKey)).status, "awaiting_approval"); await runner.answerAndDeliver(db, q.id, "ок", "web"); assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "the PM's approval starts Apply"); await runner.stopSession(db, sid); }); test("syncWorkspace: the working copy on the story branch goes to the merged main; the local branch is deleted", async () => { const root = mkdtempSync(join(tmpdir(), "peppa-sync-")); const g = (cwd: string, ...a: string[]) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); const origin = join(root, "origin.git"); execFileSync("git", ["init", "--bare", "-b", "main", origin], { stdio: "ignore" }); const ws = join(root, "ws"); execFileSync("git", ["clone", origin, ws], { stdio: "ignore" }); g(ws, "checkout", "-b", "main"); writeFileSync(join(ws, "a.txt"), "1"); g(ws, "add", "."); g(ws, "commit", "-m", "init"); g(ws, "push", "-u", "origin", "main"); const tp = await project({ turns: [] }); const p = await projectOf(tp); await db.update(projects).set({ workspacePath: ws }).where(eq(projects.id, p.id)); g(ws, "checkout", "-b", `task/${tp.taskKey}`); writeFileSync(join(ws, "b.txt"), "2"); g(ws, "add", "b.txt"); g(ws, "commit", "-m", "story"); g(ws, "push", "origin", `task/${tp.taskKey}`); // The PR is merged on the server: main gets the story's commit. g(ws, "push", "origin", `task/${tp.taskKey}:main`); const ref = await core.resolveTask(db, tp.taskKey); assert.equal(await runner.syncWorkspace(db, ref), "synced"); assert.equal(g(ws, "rev-parse", "--abbrev-ref", "HEAD"), "main"); assert.equal(g(ws, "rev-parse", "HEAD"), g(ws, "rev-parse", "origin/main")); assert.equal(g(ws, "branch", "--list", `task/${tp.taskKey}`), "", "merged local branch deleted"); // Another branch or uncommitted changes: left alone. g(ws, "checkout", "-b", "feature/other"); assert.equal(await runner.syncWorkspace(db, ref), "other_branch"); g(ws, "checkout", "main"); writeFileSync(join(ws, "a.txt"), "dirty"); assert.equal(await runner.syncWorkspace(db, ref), "dirty"); }); });