import { readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { createPonyCommitMessage } from "./commit-message.js"; import { type MarkdownRecord, readMarkdownRecord, writeMarkdownRecord, } from "./markdown.js"; import { INSTRUCTIONS_FILE, pathExists, projectRelativePath, requireProject, } from "./project.js"; import { type Instructions, instructionsSchema } from "./schemas.js"; import { applyWritePolicy, assertSupportedWritePolicy, } from "./write-policy.js"; export type InstructionsRecord = MarkdownRecord; export interface InstructionsReadResult { record: InstructionsRecord; exists: boolean; } export interface InstructionsUpdateResult extends InstructionsReadResult { path: string; changed: boolean; created: boolean; commitSha: string | null; } function instructionsPath(ponyDir: string): string { return path.join(ponyDir, INSTRUCTIONS_FILE); } /** * Legacy Pony projects may omit the canonical instructions file. Represent * that state as an empty virtual record while preserving its absence in the * result so callers can distinguish it from a present, intentionally empty * file. */ export async function getInstructions( cwd?: string, ): Promise { const project = await requireProject(cwd); const absolutePath = instructionsPath(project.ponyDir); const exists = await pathExists(absolutePath); if (!exists) { return { exists: false, record: { data: { type: "instructions" }, body: "", absolutePath, path: projectRelativePath(project, absolutePath), }, }; } return { exists: true, record: await readMarkdownRecord(project, absolutePath, instructionsSchema), }; } export async function updateInstructions( body: string, cwd?: string, ): Promise { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const current = await getInstructions(project.root); const nextBody = body.trimEnd(); if (current.exists && current.record.body === nextBody) { return { ...current, path: current.record.path, changed: false, created: false, commitSha: null, }; } const previousContent = current.exists ? await readFile(current.record.absolutePath, "utf8") : null; const policy = await applyWritePolicy(project, { targets: [ { absolutePath: current.record.absolutePath, existed: current.exists, }, ], commitMessage: createPonyCommitMessage({ kind: current.exists ? "instructions_update" : "instructions_create", path: current.record.path, }), apply: () => writeMarkdownRecord( current.record.absolutePath, { type: "instructions" }, nextBody, ), rollback: () => previousContent === null ? rm(current.record.absolutePath, { force: true }) : writeFile(current.record.absolutePath, previousContent, "utf8"), }); const updated = await getInstructions(project.root); return { ...updated, path: updated.record.path, changed: true, created: !current.exists, commitSha: policy.commitSha, }; }