import { readFile } from "node:fs/promises"; import path from "node:path"; import { parse, stringify } from "yaml"; import { writeMarkdownRecord } from "./markdown.js"; import { projectRelativePath, requireProject } from "./project.js"; import { type TaskRecord, getTask, listTasks, nowIso } from "./records.js"; import { normalizeConfig, taskSchema } from "./schemas.js"; import { assertSupportedWritePolicy } from "./write-policy.js"; import { createPonyCommitMessage } from "./commit-message.js"; import { applyConfigAndRecordMutation, createPendingFileWrite, type PendingFileWrite, } from "./atomic-writes.js"; export interface RenameTaskStatusResult { sourceStatus: string; targetStatus: string; statuses: string[]; tasks: TaskRecord[]; configPath: string; commitSha: string | null; } function assertStatusToken(status: string, role: "source" | "target"): void { if (!status.trim()) { throw new Error(`${role} task status cannot be empty.`); } } function renamedStatuses( statuses: string[], sourceStatus: string, targetStatus: string, ): string[] { if (statuses.includes(targetStatus)) { let keptTarget = false; return statuses.filter((status) => { if (status === sourceStatus) return false; if (status !== targetStatus) return true; if (keptTarget) return false; keptTarget = true; return true; }); } let renamed = false; return statuses.flatMap((status) => { if (status !== sourceStatus) return [status]; if (renamed) return []; renamed = true; return [targetStatus]; }); } function asRecord(value: unknown): Record { return typeof value === "object" && value !== null ? (value as Record) : {}; } /** * Rename or merge a configured task status only when explicitly requested. * Every affected task and the resulting config are parsed before the first * write, preserving legacy workflows during ordinary project loading. */ export async function renameTaskStatus( sourceStatus: string, targetStatus: string, cwd?: string, ): Promise { assertStatusToken(sourceStatus, "source"); assertStatusToken(targetStatus, "target"); if (sourceStatus === targetStatus) { throw new Error("source and target task statuses must be different."); } const project = await requireProject(cwd); assertSupportedWritePolicy(project); if (!project.config.tasks.statuses.includes(sourceStatus)) { throw new Error( `Unknown source task status "${sourceStatus}". Expected one of: ${project.config.tasks.statuses.join(", ")}`, ); } const [tasks, previousConfigContent] = await Promise.all([ listTasks(project.root), readFile(project.configPath, "utf8"), ]); const nextStatuses = renamedStatuses( project.config.tasks.statuses, sourceStatus, targetStatus, ); const rawConfig = asRecord(parse(previousConfigContent)); const rawTasks = asRecord(rawConfig.tasks); const nextRawConfig = { ...rawConfig, tasks: { ...rawTasks, statuses: nextStatuses }, }; // Validate the persisted shape without deployment-specific env overrides. normalizeConfig( nextRawConfig, path.basename(project.root), {} as NodeJS.ProcessEnv, ); const timestamp = nowIso(); const affectedTasks = tasks.filter( (task) => task.data.status === sourceStatus, ); const taskWrites = await Promise.all( affectedTasks.map(async (task): Promise => { const updated = taskSchema.parse({ ...task.data, status: targetStatus, updated_at: timestamp, }); return createPendingFileWrite(task.absolutePath, () => writeMarkdownRecord(task.absolutePath, updated, task.body), ); }), ); const affectedPathCount = taskWrites.length + 1; const policyResult = await applyConfigAndRecordMutation({ project, recordWrites: taskWrites, previousConfigContent, nextConfigContent: stringify(nextRawConfig, { lineWidth: 0 }), commitMessage: createPonyCommitMessage({ kind: "task_status_rename", sourceStatus, targetStatus, affectedTaskCount: affectedTasks.length, affectedPathCount, }), }); return { sourceStatus, targetStatus, statuses: nextStatuses, tasks: await Promise.all( affectedTasks.map((task) => getTask(task.data.id, project.root)), ), configPath: projectRelativePath(project, project.configPath), commitSha: policyResult.commitSha, }; }