import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { type z } from "zod"; import { createPonyCommitMessage } from "./commit-message.js"; import { parseMarkdownFrontmatter, stringifyMarkdownFrontmatterPreservingContent, } from "./frontmatter.js"; import { runGit } from "./git.js"; import { listMarkdownFiles } from "./markdown-files.js"; import { type MarkdownRecord, readMarkdownRecord } from "./markdown.js"; import { pathExists, projectRelativePath, requireProject, type PonyProject, } from "./project.js"; import { type InboxMessage, type Task, inboxMessageSchema, taskIdSchema, taskSchema, } from "./schemas.js"; import { activeGitOperation, applyRecoveryWritePolicy, type MutationTarget, } from "./write-policy.js"; export interface TaskIdMapping { source: string; target: string; } export interface TextualTaskReference { id: string; path: string; field: "title" | "body"; line: number | null; } export interface TaskIdMutationResult { mappings: TaskIdMapping[]; tasks: MarkdownRecord[]; inbox: MarkdownRecord[]; textualReferences: TextualTaskReference[]; commitSha: string | null; recoveryOperation: "merge" | "rebase" | null; } export interface TaskConflictVariant { stage: 2 | 3; label: "ours" | "theirs"; title: string; createdAt: string; } export interface TaskConflictResult { id: string; path: string; variants: TaskConflictVariant[]; } export interface ResolveTaskConflictResult { conflictId: string; movedStage: 2 | 3; targetId: string; kept: MarkdownRecord; moved: MarkdownRecord; textualReferences: TextualTaskReference[]; recoveryOperation: "merge" | "rebase"; } interface PreparedFileMutation { targets: MutationTarget[]; apply: () => Promise; rollback: () => Promise; } interface MutableMarkdownRecord extends MarkdownRecord { rawData: Record; rawBody: string; } interface TextualRecord { path: string; title?: string; body: string; } async function readMutableMarkdownRecord( project: PonyProject, file: string, schema: TSchema, ): Promise>> { const raw = await readFile(file, "utf8"); const parsed = parseMarkdownFrontmatter(raw); return { data: schema.parse(parsed.data), body: parsed.content.trimEnd(), absolutePath: file, path: projectRelativePath(project, file), rawData: parsed.data, rawBody: parsed.content, }; } function tasksDirectory(project: PonyProject): string { return path.join(project.ponyDir, "tasks"); } function inboxDirectory(project: PonyProject): string { return path.join(project.ponyDir, "inbox"); } function taskFile(project: PonyProject, id: string): string { return path.join(tasksDirectory(project), `${id}.md`); } function taskNumber(id: string): number { return Number(id.slice("TASK-".length)); } function formatTaskId(value: number): string { return `TASK-${String(value).padStart(3, "0")}`; } function replaceTaskIds(values: string[], mapping: Map) { return values.map((value) => mapping.get(value) ?? value); } async function listTaskRecords(project: PonyProject) { const files = await listMarkdownFiles(tasksDirectory(project)); return Promise.all( files.map((file) => readMutableMarkdownRecord(project, file, taskSchema)), ); } async function listInboxRecords(project: PonyProject) { const files = await listMarkdownFiles(inboxDirectory(project)); return Promise.all( files.map((file) => readMutableMarkdownRecord(project, file, inboxMessageSchema), ), ); } async function prepareFileMutation( finalContent: Map, orderedPaths: string[], ): Promise { const previous = new Map(); for (const file of finalContent.keys()) { previous.set( file, (await pathExists(file)) ? await readFile(file, "utf8") : null, ); } async function writeState( contents: Map, paths: string[], ): Promise { for (const file of paths) { const content = contents.get(file) ?? null; if (content === null) { await rm(file, { force: true }); } else { await mkdir(path.dirname(file), { recursive: true }); await writeFile(file, content, "utf8"); } } } return { targets: [...finalContent.keys()].map((absolutePath) => ({ absolutePath, existed: previous.get(absolutePath) !== null, })), apply: async () => { try { await writeState(finalContent, orderedPaths); } catch (error) { await writeState(previous, [...previous.keys()].reverse()); throw error; } }, rollback: () => writeState(previous, [...previous.keys()].reverse()), }; } function plannedCollectionFiles( directory: string, existingFiles: string[], finalContent: Map, ): string[] { const files = new Set(existingFiles); for (const [file, content] of finalContent) { if (path.dirname(file) !== directory) continue; if (content === null) files.delete(file); else files.add(file); } return [...files]; } async function listTextualRecords( project: PonyProject, collection: "inbox" | "tasks" | "docs", finalContent: Map, ): Promise { const directory = path.join(project.ponyDir, collection); const files = plannedCollectionFiles( directory, await listMarkdownFiles(directory), finalContent, ); return Promise.all( files.map(async (file) => { const plannedContent = finalContent.get(file); if (plannedContent === null) { throw new Error( `Deleted file remained in the planned record set: ${file}`, ); } const raw = plannedContent === undefined ? await readFile(file, "utf8") : plannedContent; const parsed = parseMarkdownFrontmatter(raw); return { path: projectRelativePath(project, file), title: typeof parsed.data.title === "string" ? parsed.data.title : undefined, body: parsed.content.trimEnd(), }; }), ); } function referencesInRecord( record: TextualRecord, ids: string[], ): TextualTaskReference[] { return ids.flatMap((id) => { const occurrence = new RegExp(`(^|[^A-Z0-9])${id}(?!\\d)`); const titleMatch: TextualTaskReference[] = record.title && occurrence.test(record.title) ? [{ id, path: record.path, field: "title", line: null }] : []; const bodyMatches = record.body .split("\n") .flatMap((line, index) => occurrence.test(line) ? [{ id, path: record.path, field: "body", line: index + 1 }] : [], ); return [...titleMatch, ...bodyMatches]; }); } async function findTextualReferences( project: PonyProject, ids: string[], finalContent: Map = new Map(), ): Promise { const records = ( await Promise.all( (["inbox", "tasks", "docs"] as const).map((collection) => listTextualRecords(project, collection, finalContent), ), ) ).flat(); const uniqueIds = [...new Set(ids)]; return records.flatMap((record) => referencesInRecord(record, uniqueIds)); } async function mutateTaskIds( project: PonyProject, mappings: TaskIdMapping[], ): Promise { const mapping = new Map( mappings.map(({ source, target }) => [source, target]), ); const tasks = await listTaskRecords(project); const taskById = new Map(tasks.map((record) => [record.data.id, record])); const sourceSet = new Set(mappings.map(({ source }) => source)); for (const { source, target } of mappings) { if (!taskById.has(source)) throw new Error(`Task ${source} does not exist.`); if (taskById.has(target) && !sourceSet.has(target)) { throw new Error(`Target task ID ${target} is already occupied.`); } } const finalContent = new Map(); for (const { source } of mappings) finalContent.set(taskFile(project, source), null); const descending = [...mappings].sort( (left, right) => taskNumber(right.source) - taskNumber(left.source), ); const targetSet = new Set(mappings.map(({ target }) => target)); const taskOperationPaths: string[] = []; for (const { source, target } of descending) { const record = taskById.get(source)!; const targetPath = taskFile(project, target); taskSchema.parse({ ...record.data, id: target }); finalContent.set( targetPath, stringifyMarkdownFrontmatterPreservingContent(record.rawBody, { ...record.rawData, id: target, }), ); taskOperationPaths.push(targetPath); if (!targetSet.has(source)) taskOperationPaths.push(taskFile(project, source)); } const inboxRecords = await listInboxRecords(project); const changedInbox = inboxRecords.filter((record) => record.data.references.tasks.some((id) => mapping.has(id)), ); for (const record of changedInbox) { const updated = inboxMessageSchema.parse({ ...record.data, updated_at: new Date().toISOString(), references: { ...record.data.references, tasks: [ ...new Set(replaceTaskIds(record.data.references.tasks, mapping)), ], }, }); finalContent.set( record.absolutePath, stringifyMarkdownFrontmatterPreservingContent(record.rawBody, updated), ); } const orderedPaths = [ ...taskOperationPaths, ...changedInbox.map((record) => record.absolutePath), ]; const textualReferences = await findTextualReferences( project, mappings.map(({ source }) => source), finalContent, ); const mutation = await prepareFileMutation(finalContent, orderedPaths); const commitMessage = mappings.length === 1 ? createPonyCommitMessage({ kind: "task_renumber", source: mappings[0].source, target: mappings[0].target, affectedTaskCount: 1, affectedPathCount: finalContent.size, }) : createPonyCommitMessage({ kind: "task_shift", source: mappings.at(-1)!.source, target: mappings[0].target, affectedTaskCount: mappings.length, affectedPathCount: finalContent.size, }); const policy = await applyRecoveryWritePolicy(project, { ...mutation, commitMessage, }); const updatedTasks = await Promise.all( mappings.map(({ target }) => readMarkdownRecord(project, taskFile(project, target), taskSchema), ), ); const updatedInbox = await Promise.all( changedInbox.map((record) => readMarkdownRecord(project, record.absolutePath, inboxMessageSchema), ), ); return { mappings, tasks: updatedTasks, inbox: updatedInbox, textualReferences, commitSha: policy.commitSha, recoveryOperation: policy.recoveryOperation ?? null, }; } export async function renumberTask( source: string, target: string, cwd?: string, ): Promise { const project = await requireProject(cwd); const parsedSource = taskIdSchema.parse(source); const parsedTarget = taskIdSchema.parse(target); if (parsedSource === parsedTarget) { throw new Error("Source and target task IDs must differ."); } if (await pathExists(taskFile(project, parsedTarget))) { throw new Error(`Target task ID ${parsedTarget} is already occupied.`); } return mutateTaskIds(project, [ { source: parsedSource, target: parsedTarget }, ]); } export async function shiftTasks( from: string, count: number, cwd?: string, ): Promise { const project = await requireProject(cwd); const parsedFrom = taskIdSchema.parse(from); if (!Number.isSafeInteger(count) || count <= 0) { throw new Error("Task shift count must be a positive integer."); } const threshold = taskNumber(parsedFrom); const mappings = (await listTaskRecords(project)) .map((record) => record.data.id) .filter((id) => taskNumber(id) >= threshold) .sort((left, right) => taskNumber(right) - taskNumber(left)) .map((source) => ({ source, target: formatTaskId(taskNumber(source) + count), })); if (mappings.length === 0) { throw new Error(`No tasks exist at or above ${parsedFrom}.`); } return mutateTaskIds(project, mappings); } async function conflictRepositoryPath( project: PonyProject, id: string, ): Promise<{ repositoryRoot: string; relativePath: string }> { const repositoryRoot = await realpath( ( await runGit(project.root, ["rev-parse", "--show-toplevel"]) ).stdout.trim(), ); const canonicalProjectRoot = await realpath(project.root); const relativePath = path .relative( repositoryRoot, path.join(canonicalProjectRoot, ".pony", "tasks", `${id}.md`), ) .split(path.sep) .join(path.posix.sep); if (!relativePath || relativePath.startsWith(`..${path.posix.sep}`)) { throw new Error("The Pony task path is outside the Git repository."); } return { repositoryRoot, relativePath }; } async function readAddAddVariants( project: PonyProject, id: string, ): Promise< Array<{ stage: 2 | 3; data: Task; rawData: Record; rawBody: string; }> > { const { repositoryRoot, relativePath } = await conflictRepositoryPath( project, id, ); const entries = ( await runGit(repositoryRoot, ["ls-files", "--unmerged", "--", relativePath]) ).stdout .trim() .split("\n") .filter(Boolean); const stages = entries.map((entry) => Number(entry.split(/\s+/)[2])); if (stages.length !== 2 || !stages.includes(2) || !stages.includes(3)) { throw new Error( `${id} is not an add/add task conflict with Git stages 2 and 3.`, ); } return Promise.all( ([2, 3] as const).map(async (stage) => { const raw = ( await runGit(repositoryRoot, ["show", `:${stage}:${relativePath}`]) ).stdout; const parsed = parseMarkdownFrontmatter(raw); const data = taskSchema.parse(parsed.data); if (data.id !== id) { throw new Error( `Git stage ${stage} contains ${data.id}, expected ${id}.`, ); } return { stage, data, rawData: parsed.data, rawBody: parsed.content, }; }), ); } export async function inspectTaskConflict( id: string, cwd?: string, ): Promise { const project = await requireProject(cwd); const parsedId = taskIdSchema.parse(id); const variants = await readAddAddVariants(project, parsedId); return { id: parsedId, path: projectRelativePath(project, taskFile(project, parsedId)), variants: variants.map((variant) => ({ stage: variant.stage, label: variant.stage === 2 ? "ours" : "theirs", title: variant.data.title, createdAt: variant.data.created_at, })), }; } export async function resolveTaskConflict( id: string, moveStage: number, target: string, cwd?: string, ): Promise { const project = await requireProject(cwd); const parsedId = taskIdSchema.parse(id); const parsedTarget = taskIdSchema.parse(target); if (moveStage !== 2 && moveStage !== 3) { throw new Error("--move-stage must be Git stage 2 (ours) or 3 (theirs)."); } if (parsedTarget === parsedId) throw new Error("Conflict target must use a new task ID."); const operation = await activeGitOperation(project); if (!operation) { throw new Error( "Task conflict resolution requires an active Git merge or rebase.", ); } const targetPath = taskFile(project, parsedTarget); const { repositoryRoot, relativePath: targetRelativePath } = await conflictRepositoryPath(project, parsedTarget); const indexedTarget = ( await runGit(repositoryRoot, ["ls-files", "--", targetRelativePath]) ).stdout.trim(); if ((await pathExists(targetPath)) || indexedTarget) { throw new Error(`Target task ID ${parsedTarget} is already occupied.`); } const variants = await readAddAddVariants(project, parsedId); const movedVariant = variants.find((variant) => variant.stage === moveStage)!; const keptVariant = variants.find((variant) => variant.stage !== moveStage)!; const sourcePath = taskFile(project, parsedId); taskSchema.parse({ ...movedVariant.data, id: parsedTarget }); const finalContent = new Map([ [ sourcePath, stringifyMarkdownFrontmatterPreservingContent( keptVariant.rawBody, keptVariant.rawData, ), ], [ targetPath, stringifyMarkdownFrontmatterPreservingContent(movedVariant.rawBody, { ...movedVariant.rawData, id: parsedTarget, }), ], ]); const textualReferences = await findTextualReferences( project, [parsedId], finalContent, ); const mutation = await prepareFileMutation(finalContent, [ sourcePath, targetPath, ]); const policy = await applyRecoveryWritePolicy(project, { ...mutation, commitMessage: createPonyCommitMessage({ kind: "task_renumber", source: parsedId, target: parsedTarget, affectedTaskCount: 1, affectedPathCount: 2, }), }); if (!policy.recoveryOperation) { throw new Error( "Git recovery ended before Pony staged the conflict resolution.", ); } return { conflictId: parsedId, movedStage: moveStage, targetId: parsedTarget, kept: await readMarkdownRecord(project, sourcePath, taskSchema), moved: await readMarkdownRecord(project, targetPath, taskSchema), textualReferences, recoveryOperation: policy.recoveryOperation, }; }