Something went wrong. Try again.
Structured planning, bounded memory, TDD, and Git guardrails for local coding models in Pi Code
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537import { join } from "node:path";import { describe, expect, it } from "vitest";import type { GitBranchInput, GitCommitInput, GitCreateBranchInput, GitDeleteBranchInput, GitMergeInput, GitRepoInput, GitRunner, GitSwitchBranchInput, GitWorktreeAddInput, GitWorktreeRemoveInput,} from "../git/runner";import { createPlanStoragePaths, createProjectStoragePaths, type ProjectStoragePaths,} from "../storage/paths";import { initializePlanFiles, readPlanRecord, updatePlanRecord,} from "../storage/plan-store";import { ensureProjectRecord, setActivePlan } from "../storage/project-store";import { createInitialPlanState, createPlanRecord, type PlanStateRecord,} from "../storage/schema";import { initializePlanState, readPlanState } from "../storage/state-store";import { readTaskRecord, upsertTaskArtifacts } from "../storage/task-store";import { MockPlannerFs } from "../test/mock-fs";import { executePlannerGitTool } from "./git-tools";
class MockGitRunner implements GitRunner { readonly calls: Array<{ name: string; input: unknown }> = []; branch: string; head: string; status: string; files: string[];
constructor( input: { branch?: string; head?: string; status?: string; files?: string[]; } = {}, ) { this.branch = input.branch ?? "plan/plan-a"; this.head = input.head ?? "abc123"; this.status = input.status ?? ""; this.files = input.files ?? []; }
async init(input: GitRepoInput): Promise<void> { this.calls.push({ name: "init", input }); } async currentBranch(input: GitRepoInput): Promise<string> { this.calls.push({ name: "currentBranch", input }); return this.branch; } async headCommit(input: GitRepoInput): Promise<string> { this.calls.push({ name: "headCommit", input }); return this.head; } async statusPorcelain(input: GitRepoInput): Promise<string> { this.calls.push({ name: "statusPorcelain", input }); return this.status; } async diffStat(input: GitRepoInput): Promise<string> { this.calls.push({ name: "diffStat", input }); return ""; } async diffNameOnly(input: GitRepoInput): Promise<string> { this.calls.push({ name: "diffNameOnly", input }); return ""; } async listProjectFiles(input: GitRepoInput): Promise<string[]> { this.calls.push({ name: "listProjectFiles", input }); return this.files; } async branchExists(input: GitBranchInput): Promise<boolean> { this.calls.push({ name: "branchExists", input }); return true; } async createBranch(input: GitCreateBranchInput): Promise<void> { this.calls.push({ name: "createBranch", input }); this.branch = input.branch; } async deleteBranch(input: GitDeleteBranchInput): Promise<void> { this.calls.push({ name: "deleteBranch", input }); } async switchBranch(input: GitSwitchBranchInput): Promise<void> { this.calls.push({ name: "switchBranch", input }); this.branch = input.branch; } async stageAll(input: GitRepoInput): Promise<void> { this.calls.push({ name: "stageAll", input }); } async commit(input: GitCommitInput): Promise<void> { this.calls.push({ name: "commit", input }); this.head = "new456"; this.status = ""; } async merge(input: GitMergeInput): Promise<void> { this.calls.push({ name: "merge", input }); this.head = "merge789"; this.status = ""; } async worktreeAdd(input: GitWorktreeAddInput): Promise<void> { this.calls.push({ name: "worktreeAdd", input }); this.branch = input.branch; } async worktreeRemove(input: GitWorktreeRemoveInput): Promise<void> { this.calls.push({ name: "worktreeRemove", input }); } async discardWorktreeChanges(input: GitRepoInput): Promise<void> { this.calls.push({ name: "discardWorktreeChanges", input }); this.status = ""; }}
describe("planner git tools", () => { it("commits through planner git and persists synchronized state", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "write_tests", stepStatus: "running", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, }, }); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "old123", status: " M src/a.ts", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_commit", params: { message: "add failing tests" }, });
expect(result.status).toBe("applied"); expect(git.calls.map((call) => call.name)).toContain("stageAll"); expect(git.calls).toContainEqual({ name: "commit", input: { repoRoot: "/repo/app/.pi/pi-code-planner/worktrees/plan-a", message: "add failing tests", }, }); expect(await readPlanState(fs, setup.planPaths)).toMatchObject({ currentBranch: "task/plan-a/task-1", }); });
it("blocks planner git commit when there are no changes to commit", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "write_tests", stepStatus: "running", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, }, }); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "abc123", status: "", }); const before = await readPlanState(fs, setup.planPaths);
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_commit", params: { message: "empty commit should not happen" }, });
expect(result.status).toBe("blocked"); expect(result.text).toContain("no changes to commit"); expect(git.calls.map((call) => call.name)).not.toContain("stageAll"); expect(git.calls.map((call) => call.name)).not.toContain("commit"); expect(await readPlanState(fs, setup.planPaths)).toEqual(before); });
it("blocks planner git commit while debug artifacts exist", async () => { const fs = new MockPlannerFs(); const debugArtifactsDir = "/repo/app/.pi/pi-code-planner/worktrees/plan-a/.pi/pi-code-planner/debug/task-1/attempt-001-deadbeef"; const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "implement_task", stepStatus: "running", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, lastStuckAttemptId: "attempt-001", debugSessionId: "attempt-001-deadbeef", debugArtifactsDir, debugCleanupRequired: true, }, }); await fs.mkdirp(debugArtifactsDir); await fs.writeTextAtomic(`${debugArtifactsDir}/probe.md`, "debug\n"); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "old123", status: " M src/a.ts", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_commit", params: { message: "must wait" }, });
expect(result.status).toBe("blocked"); expect(result.text).toContain("debug artifacts still exist"); expect(git.calls.map((call) => call.name)).not.toContain("stageAll"); expect(git.calls.map((call) => call.name)).not.toContain("commit"); });
it("keeps merge targets state-bound when merging task into plan", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "merge_task_to_plan", stepStatus: "running", activeTaskId: "task-1", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, mergeTargets: { taskToPlan: "plan/plan-a", planToOutput: null, }, }, }); await seedMergeScopeAudit(fs, setup.planPaths, "task-1"); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "abc123", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_merge_task_to_plan", params: { message: "merge task-1" }, });
expect(result.status).toBe("applied"); expect(git.calls).toContainEqual({ name: "switchBranch", input: { repoRoot: "/repo/app/.pi/pi-code-planner/worktrees/plan-a", branch: "plan/plan-a", }, }); expect(git.calls).toContainEqual({ name: "merge", input: { repoRoot: "/repo/app/.pi/pi-code-planner/worktrees/plan-a", sourceBranch: "task/plan-a/task-1", noFastForward: true, message: "merge task-1", }, }); expect(await readPlanState(fs, setup.planPaths)).toMatchObject({ currentBranch: "plan/plan-a", activeTaskId: null, mergeTargets: { taskToPlan: null }, }); });
it("marks a task done after merging it into the plan branch", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "merge_task_to_plan", stepStatus: "running", activeTaskId: "task-1", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, mergeTargets: { taskToPlan: "plan/plan-a", planToOutput: null, }, }, }); const taskPaths = await upsertTaskArtifacts(fs, setup.planPaths, { taskId: "task-1", title: "Task one", objective: "Do task one.", scope: ["src/a.ts"], acceptanceCriteria: ["Task one is done."], }); await updatePlanRecord(fs, setup.planPaths, (plan) => ({ ...plan, tasks: [{ taskId: "task-1", title: "Task one", status: "pending" }], })); await seedMergeScopeAudit(fs, setup.planPaths, "task-1"); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "abc123", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_merge_task_to_plan", params: { message: "merge task-1" }, });
expect(result.status).toBe("applied"); await expect(readPlanRecord(fs, setup.planPaths)).resolves.toMatchObject({ tasks: [{ taskId: "task-1", status: "done" }], }); await expect(readTaskRecord(fs, taskPaths.paths)).resolves.toMatchObject({ status: "done", }); });
it("blocks merging a task before the merge scope audit is recorded", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "merge_task_to_plan", stepStatus: "running", activeTaskId: "task-1", currentBranch: "task/plan-a/task-1", activeBranches: { base: "main", plan: "plan/plan-a", currentTask: "task/plan-a/task-1", }, mergeTargets: { taskToPlan: "plan/plan-a", planToOutput: null }, }, }); const git = new MockGitRunner({ branch: "task/plan-a/task-1", head: "abc123", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_merge_task_to_plan", params: { message: "merge task-1" }, });
expect(result.status).toBe("blocked"); expect(result.text).toContain("merge scope audit"); expect(git.calls.map((call) => call.name)).not.toContain("merge"); });
it("blocks git wrappers outside their policy step", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "execution", step: "prepare_task", stepStatus: "running", }, });
const result = await executePlannerGitTool({ fs, git: new MockGitRunner(), projectPaths: setup.projectPaths, toolName: "planner_git_commit", params: { message: "should not commit" }, });
expect(result.status).toBe("blocked"); expect(result.text).toContain("blocked"); });
it("discards changes through planner git when worktree is dirty", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "finalize", step: "doubt_review", stepStatus: "running", }, }); const git = new MockGitRunner({ status: " M src/a.ts", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_discard_changes", params: {}, });
expect(result.status).toBe("applied"); expect(result.text).toContain( "Planner discarded all uncommitted worktree changes", ); expect(git.calls).toContainEqual({ name: "discardWorktreeChanges", input: { repoRoot: "/repo/app/.pi/pi-code-planner/worktrees/plan-a" }, }); });
it("does nothing when discarding changes on a clean worktree", async () => { const fs = new MockPlannerFs(); const setup = await createGitToolSetup(fs, { state: { stage: "finalize", step: "doubt_review", stepStatus: "running", }, }); const git = new MockGitRunner({ status: "", });
const result = await executePlannerGitTool({ fs, git, projectPaths: setup.projectPaths, toolName: "planner_git_discard_changes", params: {}, });
expect(result.status).toBe("applied"); expect(result.text).toContain("Planner worktree is already clean"); expect(git.calls.some((c) => c.name === "discardWorktreeChanges")).toBe( false, ); });});
async function seedMergeScopeAudit( fs: MockPlannerFs, planPaths: ReturnType<typeof createPlanStoragePaths>, taskId: string,): Promise<void> { const tddPath = join(planPaths.tasksDir, taskId, "tdd.md"); await fs.writeTextAtomic( tddPath, [ "## Task Merge Scope Audit", "- acceptanceCriteriaCovered: All acceptance criteria met.", "- changedFilesMatchScope: Only in-scope files changed.", "- testsRun: vitest run passed.", "- debugRemoved: No debug code left.", "- commitMessageMatchesBehavior: Commit message matches behavior.", "- branchDriftCheck: Branched from plan, no drift.", "", ].join("\n"), );}
async function createGitToolSetup( fs: MockPlannerFs, input: { state?: Partial<PlanStateRecord>; createWorktreeDir?: boolean; } = {},): Promise<{ projectPaths: ProjectStoragePaths; planPaths: ReturnType<typeof createPlanStoragePaths>;}> { const projectPaths = createProjectStoragePaths({ agentDir: "/agent", projectRoot: "/repo/app", }); const planPaths = createPlanStoragePaths(projectPaths, "plan-a"); const worktreePath = "/repo/app/.pi/pi-code-planner/worktrees/plan-a"; await ensureProjectRecord(fs, projectPaths); await initializePlanFiles( fs, planPaths, createPlanRecord({ planId: "plan-a", title: "Plan A" }), ); await initializePlanState(fs, planPaths, { ...createInitialPlanState({ baseBranch: "main", planBranch: "plan/plan-a", worktreePath, }), currentBranch: "plan/plan-a", ...input.state, }); if (input.createWorktreeDir ?? true) { await fs.mkdirp(worktreePath); await fs.writeText(join(worktreePath, "src/a.ts"), ""); } await setActivePlan(fs, projectPaths, "plan-a"); return { projectPaths, planPaths };}