import { copyFile, mkdir, mkdtemp, realpath, rename, rm, } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { type PonyCommitMessage } from "./commit-message.js"; import { errorMessage, GitCommandError, GIT_NETWORK_COMMAND_TIMEOUT_MS, runGit, } from "./git.js"; import { pathExists, type PonyProject } from "./project.js"; export interface WritePolicyResult { commitSha: string | null; recoveryOperation?: "merge" | "rebase"; } export interface MutationTarget { absolutePath: string; existed: boolean; includeInCommit?: boolean; } export interface WritePolicyMutation { targets: MutationTarget[]; commitMessage: PonyCommitMessage; apply: () => Promise; rollback: () => Promise; } interface CommitPreflight { branchName: string; branchRef: string; headSha: string; pushDestination: PushDestination | null; relativePaths: string[]; repositoryRoot: string; } interface PushDestination { remoteName: string; remoteRef: string; trackingRef: string; } export class PushDeliveryError extends Error { readonly commitSha: string; readonly remoteName: string; readonly remoteRef: string; readonly retryCommand: string; constructor( commitSha: string, destination: PushDestination, retryCommand: string, detail: string, ) { super( `Push failed after Pony created local commit ${commitSha}; the commit and mutation files were retained, and Pony did not report delivery success. Destination: ${destination.remoteName} ${destination.remoteRef}. Retry with: ${retryCommand}. ${detail}`, ); this.name = "PushDeliveryError"; this.commitSha = commitSha; this.remoteName = destination.remoteName; this.remoteRef = destination.remoteRef; this.retryCommand = retryCommand; } } function repositoryRelativePath( repositoryRoot: string, projectRoot: string, canonicalProjectRoot: string, absolutePath: string, ): string { const projectRelativePath = path.relative( projectRoot, path.resolve(absolutePath), ); if ( !projectRelativePath || projectRelativePath === ".." || projectRelativePath.startsWith(`..${path.sep}`) || path.isAbsolute(projectRelativePath) ) { throw new Error( `Pony mutation target must be a file inside the project: ${absolutePath}`, ); } const relativePath = path.relative( repositoryRoot, path.resolve(canonicalProjectRoot, projectRelativePath), ); if ( !relativePath || relativePath === ".." || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath) ) { throw new Error( `Pony mutation target must be a file inside the Git repository: ${absolutePath}`, ); } return relativePath.split(path.sep).join(path.posix.sep); } async function resolveRepositoryState( project: PonyProject, ): Promise> { let repositoryRoot: string; try { repositoryRoot = await realpath( ( await runGit(project.root, ["rev-parse", "--show-toplevel"]) ).stdout.trim(), ); } catch (error) { throw new Error( `Commit mode requires ${project.root} to be inside a Git repository: ${errorMessage(error)}`, { cause: error }, ); } let headSha: string; try { headSha = ( await runGit(repositoryRoot, ["rev-parse", "--verify", "HEAD"]) ).stdout.trim(); } catch (error) { throw new Error( "Commit mode requires a repository with an initial commit before Pony writes files.", { cause: error }, ); } let branchRef: string; try { branchRef = ( await runGit(repositoryRoot, ["symbolic-ref", "--quiet", "HEAD"]) ).stdout.trim(); } catch (error) { throw new Error( "Commit mode requires a checked-out named branch; detached HEAD is not supported.", { cause: error }, ); } const branchName = ( await runGit(repositoryRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]) ).stdout.trim(); const configuredBranch = project.config.write.branch; if (configuredBranch !== "current" && configuredBranch !== branchName) { throw new Error( `Commit mode is configured for branch "${configuredBranch}", but "${branchName}" is checked out. Pony never switches branches automatically.`, ); } return { branchName, branchRef, headSha, repositoryRoot }; } function fishQuote(value: string): string { return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`; } function pushCommand(destination: PushDestination, commitSha: string): string { return `git push --porcelain --no-verify ${fishQuote(destination.remoteName)} ${fishQuote(`${commitSha}:${destination.remoteRef}`)}`; } async function divergenceCounts( repositoryRoot: string, headSha: string, destination: PushDestination, ): Promise<{ ahead: number; behind: number }> { let output: string; try { output = ( await runGit(repositoryRoot, [ "rev-list", "--left-right", "--count", `${headSha}...${destination.trackingRef}`, ]) ).stdout.trim(); } catch (error) { throw new Error( `The configured upstream tracking ref "${destination.trackingRef}" is unavailable. Fetch from ${fishQuote(destination.remoteName)} manually, then retry.`, { cause: error }, ); } const [ahead, behind] = output.split(/\s+/).map(Number); if (!Number.isInteger(ahead) || !Number.isInteger(behind)) { throw new Error( `Git returned invalid ahead/behind counts for upstream "${destination.trackingRef}".`, ); } return { ahead, behind }; } async function resolvePushDestination( repository: Omit, ): Promise { const upstream = ( await runGit(repository.repositoryRoot, [ "for-each-ref", "--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)", repository.branchRef, ]) ).stdout.trimEnd(); const [remoteName, remoteRef, trackingRef] = upstream.split("\0"); if (!remoteName || !remoteRef || !trackingRef) { throw new Error( `commit_and_push requires branch "${repository.branchName}" to have an existing upstream before Pony writes files. Configure it with Git, then retry.`, ); } const destination = { remoteName, remoteRef, trackingRef }; const { ahead, behind } = await divergenceCounts( repository.repositoryRoot, repository.headSha, destination, ); if (ahead > 0 && behind === 0) { throw new Error( `commit_and_push requires local HEAD to match its upstream before a new mutation. Branch "${repository.branchName}" is ahead by ${ahead} commit${ahead === 1 ? "" : "s"}. Finish the pending delivery with: ${pushCommand(destination, repository.headSha)}`, ); } if (ahead === 0 && behind > 0) { throw new Error( `commit_and_push requires local HEAD to match its upstream before a new mutation. Branch "${repository.branchName}" is behind by ${behind} commit${behind === 1 ? "" : "s"}. Fetch from ${fishQuote(remoteName)} and reconcile manually; Pony never pulls, merges, or rebases automatically.`, ); } if (ahead > 0 && behind > 0) { throw new Error( `commit_and_push requires local HEAD to match its upstream before a new mutation. Branch "${repository.branchName}" has diverged (${ahead} local, ${behind} upstream). Fetch from ${fishQuote(remoteName)} and reconcile manually; Pony never force pushes, pulls, merges, or rebases automatically.`, ); } return destination; } async function resolveMutationPaths( project: PonyProject, repositoryRoot: string, mutation: WritePolicyMutation, ): Promise<{ allPaths: string[]; commitPaths: string[] }> { const canonicalProjectRoot = await realpath(project.root); const allPaths = mutation.targets.map((target) => repositoryRelativePath( repositoryRoot, project.root, canonicalProjectRoot, target.absolutePath, ), ); if (new Set(allPaths).size !== allPaths.length) { throw new Error("Pony mutation targets must not contain duplicate paths."); } const commitPaths = mutation.targets.flatMap((target, index) => target.includeInCommit === false ? [] : [allPaths[index]], ); if (commitPaths.length === 0) { throw new Error("Pony mutation must declare at least one file to commit."); } return { allPaths, commitPaths }; } async function assertMutationTargetsAreClean( repositoryRoot: string, mutation: WritePolicyMutation, relativePaths: string[], ): Promise { for (const [index, target] of mutation.targets.entries()) { const exists = await pathExists(target.absolutePath); if (exists !== target.existed) { throw new Error( `Pony mutation target changed before delivery: ${relativePaths[index]}`, ); } if (target.existed) { try { await runGit(repositoryRoot, [ "ls-files", "--error-unmatch", "--", relativePaths[index], ]); } catch (error) { throw new Error( `Existing Pony mutation target is not tracked by Git: ${relativePaths[index]}`, { cause: error }, ); } } } const status = await runGit(repositoryRoot, [ "status", "--porcelain=v1", "--untracked-files=all", "--", ...relativePaths, ]); if (status.stdout.length > 0) { throw new Error( `Commit mode requires clean mutation target paths. Resolve these target-path changes first:\n${status.stdout.trimEnd()}`, ); } } async function preflightCommit( project: PonyProject, mutation: WritePolicyMutation, ): Promise { const repository = await resolveRepositoryState(project); const pushDestination = project.config.write.mode === "commit_and_push" ? await resolvePushDestination(repository) : null; const paths = await resolveMutationPaths( project, repository.repositoryRoot, mutation, ); await assertMutationTargetsAreClean( repository.repositoryRoot, mutation, paths.allPaths, ); return { ...repository, pushDestination, relativePaths: paths.commitPaths, }; } async function restoreBranchAfterFailedDelivery( preflight: CommitPreflight, committedSha: string, primaryError: unknown, ): Promise { try { await runGit(preflight.repositoryRoot, [ "update-ref", preflight.branchRef, preflight.headSha, committedSha, ]); } catch (rollbackError) { throw new AggregateError( [primaryError, rollbackError], `Commit delivery failed and Pony could not restore ${preflight.branchRef}: ${errorMessage(primaryError)} Rollback error: ${errorMessage(rollbackError)}`, ); } throw primaryError; } async function createIsolatedCommit( project: PonyProject, mutation: WritePolicyMutation, preflight: CommitPreflight, ): Promise { const temporaryDirectory = await mkdtemp( path.join(os.tmpdir(), "pony-git-index-"), ); const indexPath = path.join(temporaryDirectory, "index"); const hooksPath = path.join(temporaryDirectory, "hooks"); const isolatedEnvironment = { GIT_INDEX_FILE: indexPath }; let committedSha: string | null = null; try { await mkdir(hooksPath); await runGit(preflight.repositoryRoot, ["read-tree", preflight.headSha], { env: isolatedEnvironment, }); await runGit( preflight.repositoryRoot, ["add", "--", ...preflight.relativePaths], { env: isolatedEnvironment }, ); const stagedDiff = await runGit( preflight.repositoryRoot, ["diff", "--cached", "--quiet", "--exit-code"], { acceptedExitCodes: [0, 1], env: isolatedEnvironment }, ); if (stagedDiff.exitCode === 0) { throw new Error( "Pony mutation did not produce a Git diff; refusing to create an empty commit.", ); } const author = project.config.write.commit_author; await runGit( preflight.repositoryRoot, [ "-c", "commit.gpgSign=false", "-c", `core.hooksPath=${hooksPath}`, "commit", "--quiet", "--no-gpg-sign", "-m", mutation.commitMessage.subject, "-m", mutation.commitMessage.body, ], { env: { ...isolatedEnvironment, GIT_AUTHOR_NAME: author.name, GIT_AUTHOR_EMAIL: author.email, GIT_COMMITTER_NAME: author.name, GIT_COMMITTER_EMAIL: author.email, }, }, ); committedSha = ( await runGit(preflight.repositoryRoot, ["rev-parse", "HEAD"]) ).stdout.trim(); /** * Advancing HEAD makes the old target entries stale. Refresh only the * preflight-clean Pony targets so subsequent commits work, while preserving * every unrelated staged entry in the caller-owned index. */ await runGit(preflight.repositoryRoot, [ "reset", "--quiet", committedSha, "--", ...preflight.relativePaths, ]); return committedSha; } catch (error) { if (committedSha) { return restoreBranchAfterFailedDelivery(preflight, committedSha, error); } throw error; } finally { await rm(temporaryDirectory, { recursive: true, force: true }).catch( () => undefined, ); } } async function pushCommit( preflight: CommitPreflight, commitSha: string, ): Promise { const destination = preflight.pushDestination; if (!destination) { throw new Error("Push delivery requires resolved upstream metadata."); } const retryCommand = pushCommand(destination, commitSha); try { await runGit( preflight.repositoryRoot, [ "push", "--porcelain", "--no-verify", destination.remoteName, `${commitSha}:${destination.remoteRef}`, ], { timeoutMs: GIT_NETWORK_COMMAND_TIMEOUT_MS, }, ); } catch (error) { const gitOutput = error instanceof GitCommandError ? `${error.result.stdout}\n${error.result.stderr}`.trim() : errorMessage(error); const remoteRejected = /\b(rejected|non-fast-forward|fetch first|failed to push)\b/i.test( gitOutput, ); const recovery = remoteRejected ? "The remote rejected the update. Fetch and reconcile manually before retrying; Pony never force pushes, pulls, merges, or rebases automatically." : "The remote response was unsuccessful or unavailable. Retrying the exact command is safe if the remote already accepted the commit."; throw new PushDeliveryError( commitSha, destination, retryCommand, `${recovery} Git reported: ${gitOutput || "no diagnostic output"}`, ); } } async function rollbackFailedMutation( mutation: WritePolicyMutation, primaryError: unknown, ): Promise { try { await mutation.rollback(); } catch (rollbackError) { throw new AggregateError( [primaryError, rollbackError], `Commit delivery failed and Pony could not fully restore the mutation: ${errorMessage(primaryError)} Rollback error: ${errorMessage(rollbackError)}`, ); } throw new Error( `Commit delivery failed; Pony restored the pre-mutation files. ${errorMessage(primaryError)}`, { cause: primaryError }, ); } export function assertSupportedWritePolicy(project: PonyProject): void { switch (project.config.write.mode) { case "working_tree": case "commit": case "commit_and_push": return; } } /** * Apply one declared filesystem mutation and, in commit mode, deliver it as an * isolated local commit. Callers must bypass this function for domain-level * no-change results so idempotent operations never invoke Git. */ export async function applyWritePolicy( project: PonyProject, mutation: WritePolicyMutation, ): Promise { assertSupportedWritePolicy(project); if (project.config.write.mode === "working_tree") { await mutation.apply(); return { commitSha: null }; } const preflight = await preflightCommit(project, mutation); try { await mutation.apply(); } catch (error) { return rollbackFailedMutation(mutation, error); } let commitSha: string; try { commitSha = await createIsolatedCommit(project, mutation, preflight); } catch (error) { return rollbackFailedMutation(mutation, error); } if (project.config.write.mode === "commit_and_push") { await pushCommit(preflight, commitSha); } return { commitSha }; } async function resolveRepositoryRoot(project: PonyProject): Promise { try { return await realpath( ( await runGit(project.root, ["rev-parse", "--show-toplevel"]) ).stdout.trim(), ); } catch (error) { throw new Error( `Git recovery requires ${project.root} to be inside a Git repository: ${errorMessage(error)}`, { cause: error }, ); } } async function gitMetadataPath( repositoryRoot: string, name: string, ): Promise { const value = ( await runGit(repositoryRoot, ["rev-parse", "--git-path", name]) ).stdout.trim(); return path.resolve(repositoryRoot, value); } export async function activeGitOperation( project: PonyProject, ): Promise<"merge" | "rebase" | null> { let repositoryRoot: string; try { repositoryRoot = await resolveRepositoryRoot(project); } catch { return null; } const [mergeHead, rebaseMerge, rebaseApply] = await Promise.all([ gitMetadataPath(repositoryRoot, "MERGE_HEAD"), gitMetadataPath(repositoryRoot, "rebase-merge"), gitMetadataPath(repositoryRoot, "rebase-apply"), ]); if (await pathExists(mergeHead)) return "merge"; if ((await pathExists(rebaseMerge)) || (await pathExists(rebaseApply))) { return "rebase"; } return null; } /** * Recovery must update the worktree and index as one logical mutation while an * outer Git operation owns history. Stage against a copied index first, then * atomically replace the real index only after every declared file is valid. */ async function stageRecoveryMutation( project: PonyProject, mutation: WritePolicyMutation, operation: "merge" | "rebase", ): Promise { const repositoryRoot = await resolveRepositoryRoot(project); const paths = await resolveMutationPaths(project, repositoryRoot, mutation); const indexPath = await gitMetadataPath(repositoryRoot, "index"); const temporaryDirectory = await mkdtemp( path.join(path.dirname(indexPath), ".pony-recovery-index-"), ); const temporaryIndex = path.join(temporaryDirectory, "index"); try { await copyFile(indexPath, temporaryIndex); try { await mutation.apply(); await runGit(repositoryRoot, ["add", "--", ...paths.commitPaths], { env: { GIT_INDEX_FILE: temporaryIndex }, }); await rename(temporaryIndex, indexPath); } catch (error) { return rollbackFailedMutation(mutation, error); } } finally { await rm(temporaryDirectory, { recursive: true, force: true }).catch( () => undefined, ); } return { commitSha: null, recoveryOperation: operation }; } export async function applyRecoveryWritePolicy( project: PonyProject, mutation: WritePolicyMutation, ): Promise { const operation = await activeGitOperation(project); return operation ? stageRecoveryMutation(project, mutation, operation) : applyWritePolicy(project, mutation); }