import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { ulid } from "ulid"; import { type Doc, type DocStatus, type DocType, type InboxAttachment, type InboxMessage, type Task, docIdSchema, docSchema, inboxIdSchema, inboxMessageSchema, taskIdSchema, taskSchema, } from "./schemas.js"; import { type InboxAttachmentFile, type InboxAttachmentInput, type PreparedInboxAttachment, prepareInboxAttachments, sha256, } from "./inbox-attachments.js"; import { type PonyProject, pathExists, projectRelativePath, requireProject, } from "./project.js"; import { type MarkdownRecord, readMarkdownRecord, writeMarkdownRecord, } from "./markdown.js"; import { applyWritePolicy, assertSupportedWritePolicy, } from "./write-policy.js"; import { createPonyCommitMessage, type PonyCommitMessage, } from "./commit-message.js"; import { createInboxGitDeliveryState, type GitDeliveryState, } from "./git-delivery.js"; import { listMarkdownFiles } from "./markdown-files.js"; import { throwRejectedResults } from "./promise-results.js"; import { fetchUpstreamTaskIds } from "./task-allocation.js"; import { TASK_PRIORITY_MODEL, isCurrentTaskPriority, parseTaskPriorityInput, type TaskPriority, } from "./task-priorities.js"; export type InboxRecord = MarkdownRecord; export type TaskRecord = MarkdownRecord; export type DocRecord = MarkdownRecord; export interface MutationResult { record: TRecord; path: string; commitSha: string | null; created?: boolean; warnings?: string[]; } export interface InboxSubmitResult extends MutationResult { gitDelivery: GitDeliveryState; } export interface InboxSubmitInput { id?: string; body: string; authorName: string; authorEmail: string; attachments?: InboxAttachmentInput[]; } export interface TaskCreateInput { title: string; body?: string; status?: string; priority?: string | null; assignee?: string | null; } export interface RecordUpdateInput { title?: string; body?: string; } export interface InboxLinkInput { taskIds?: string[]; docIds?: string[]; } export interface TaskLinkInput { inboxIds?: string[]; docIds?: string[]; } export interface LinkMutationResult { inbox: InboxRecord[]; tasks: TaskRecord[]; docs: DocRecord[]; changed: boolean; commitSha: string | null; } export interface DocCreateInput { title: string; body?: string; type?: DocType; status?: DocStatus; } export function nowIso(): string { return new Date().toISOString(); } export function createInboxId(): string { return `MSG-${ulid()}`; } function getCollectionDir( project: PonyProject, collection: "inbox" | "tasks" | "docs", ) { return path.join(project.ponyDir, collection); } function inboxPath(project: PonyProject, id: string) { return path.join(getCollectionDir(project, "inbox"), `${id}.md`); } function inboxAttachmentDirectory(project: PonyProject, id: string) { return path.join(getCollectionDir(project, "inbox"), `${id}.attachments`); } function taskPath(project: PonyProject, id: string) { return path.join(getCollectionDir(project, "tasks"), `${id}.md`); } function docPath(project: PonyProject, id: string) { return path.join(getCollectionDir(project, "docs"), `${id}.md`); } interface PendingRecordWrite { absolutePath: string; previousContent: string; nextData: object; body: string; } /** * Link mutations can touch both sides of a relationship. Roll completed file * writes back if a later write fails so validation or filesystem errors do not * leave a one-sided link in the working tree. */ async function writeRecordsAtomically( writes: PendingRecordWrite[], ): Promise { const completed: PendingRecordWrite[] = []; try { for (const write of writes) { await writeMarkdownRecord(write.absolutePath, write.nextData, write.body); completed.push(write); } } catch (error) { await Promise.allSettled( completed.map((write) => writeFile(write.absolutePath, write.previousContent, "utf8"), ), ); throw error; } } async function restoreRecordWrites( writes: PendingRecordWrite[], ): Promise { const results = await Promise.allSettled( writes.map((write) => writeFile(write.absolutePath, write.previousContent, "utf8"), ), ); throwRejectedResults(results, "Failed to restore Pony record files."); } async function applyExistingRecordWrite( project: PonyProject, record: MarkdownRecord, nextData: object, nextBody: string, commitMessage: PonyCommitMessage, ) { const previousContent = await readFile(record.absolutePath, "utf8"); return applyWritePolicy(project, { targets: [{ absolutePath: record.absolutePath, existed: true }], commitMessage, apply: () => writeMarkdownRecord(record.absolutePath, nextData, nextBody), rollback: () => writeFile(record.absolutePath, previousContent, "utf8"), }); } function addUniqueReferences(existing: string[], additions: string[]) { return [...new Set([...existing, ...additions])]; } function arraysEqual(left: string[], right: string[]) { return ( left.length === right.length && left.every((value, index) => value === right[index]) ); } function assertUpdateChanges( kind: "task" | "doc", currentTitle: string, currentBody: string, input: RecordUpdateInput, ) { if (input.title === undefined && input.body === undefined) { throw new Error(`${kind} update requires --title or a body.`); } const nextTitle = input.title ?? currentTitle; const nextBody = input.body?.trimEnd() ?? currentBody; if (nextTitle === currentTitle && nextBody === currentBody) { throw new Error(`${kind} update did not change any fields.`); } return { nextTitle, nextBody }; } function sortByCreatedAtDescending< T extends { data: { created_at: string; id: string } }, >(records: T[]): T[] { return [...records].sort((left, right) => { const dateCompare = right.data.created_at.localeCompare( left.data.created_at, ); return dateCompare === 0 ? left.data.id.localeCompare(right.data.id) : dateCompare; }); } function sortById(records: T[]): T[] { return [...records].sort((left, right) => left.data.id.localeCompare(right.data.id), ); } async function nextSequenceId( project: PonyProject, collection: "tasks" | "docs", prefix: "TASK" | "DOC", additionalIds: string[] = [], ): Promise { const files = await listMarkdownFiles(getCollectionDir(project, collection)); const candidates = [ ...files.map((file) => path.basename(file)), ...additionalIds, ]; const highest = candidates.reduce((max, candidate) => { const match = candidate.match(new RegExp(`^${prefix}-(\\d+)(?:\\.md)?$`)); return match ? Math.max(max, Number(match[1])) : max; }, 0); return `${prefix}-${String(highest + 1).padStart(3, "0")}`; } function assertTaskStatus(project: PonyProject, status: string) { if (!project.config.tasks.statuses.includes(status)) { throw new Error( `Unknown task status "${status}". Expected one of: ${project.config.tasks.statuses.join(", ")}`, ); } } function taskPriorityForMutation( project: PonyProject, priority: string | null | undefined, ): string | null { return project.config.tasks.priority_model === TASK_PRIORITY_MODEL ? parseTaskPriorityInput(priority) : (priority ?? null); } function assertTaskPriorityForProject( project: PonyProject, priority: string | null, ): void { if ( project.config.tasks.priority_model === TASK_PRIORITY_MODEL && !isCurrentTaskPriority(priority) ) { throw new Error( `Unknown persisted task priority "${priority}". Run \`pony doctor\` and migrate legacy priorities before using this project.`, ); } } export async function listInbox(cwd?: string): Promise { const project = await requireProject(cwd); const files = await listMarkdownFiles(getCollectionDir(project, "inbox")); const records = await Promise.all( files.map((file) => readMarkdownRecord(project, file, inboxMessageSchema)), ); return sortByCreatedAtDescending(records); } export async function getInboxMessage( id: string, cwd?: string, ): Promise { const project = await requireProject(cwd); const parsedId = inboxIdSchema.parse(id); return readMarkdownRecord( project, inboxPath(project, parsedId), inboxMessageSchema, ); } export function summarizeInboxMessage( body: string, attachments: InboxAttachment[], maxLength = 100, ): string { const text = body .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1") .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1") .replace(/[`#>*_~|-]+/g, " ") .replace(/\s+/g, " ") .trim(); if (!text) { if (attachments.length === 1) return attachments[0].name; if (attachments.length > 1) return `${attachments.length} attachments`; return "Empty message"; } return text.length > maxLength ? `${text.slice(0, Math.max(1, maxLength - 1)).trimEnd()}…` : text; } export async function getInboxAttachment( id: string, storedName: string, cwd?: string, ): Promise { const project = await requireProject(cwd); const record = await getInboxMessage(id, project.root); const attachment = record.data.attachments.find( (candidate) => path.posix.basename(candidate.path) === storedName, ); if (!attachment) { throw new Error(`Attachment "${storedName}" was not found on ${id}.`); } const inboxDirectory = getCollectionDir(project, "inbox"); const absolutePath = path.resolve(inboxDirectory, attachment.path); const expectedDirectory = `${path.resolve( inboxAttachmentDirectory(project, id), )}${path.sep}`; if (!absolutePath.startsWith(expectedDirectory)) { throw new Error(`Attachment "${storedName}" has an unsafe path.`); } return { absolutePath, metadata: attachment }; } interface PreparedInboxSubmission { id: string; filePath: string; body: string; authorName: string; authorEmail: string; preparedAttachments: PreparedInboxAttachment[]; attachments: InboxAttachment[]; } function prepareInboxSubmission( project: PonyProject, input: InboxSubmitInput, ): PreparedInboxSubmission { const id = inboxIdSchema.parse(input.id ?? createInboxId()); const body = input.body.trimEnd(); const preparedAttachments = prepareInboxAttachments(id, input.attachments); const attachments = preparedAttachments.map(({ metadata }) => metadata); if (!body.trim() && attachments.length === 0) { throw new Error("Inbox messages require text or at least one attachment."); } return { id, filePath: inboxPath(project, id), body, authorName: input.authorName.trim(), authorEmail: input.authorEmail.trim(), preparedAttachments, attachments, }; } function hasSameInboxPayload( existing: InboxRecord, submission: PreparedInboxSubmission, ): boolean { return ( existing.body === submission.body && existing.data.author_name === submission.authorName && existing.data.author_email === submission.authorEmail && JSON.stringify(existing.data.attachments) === JSON.stringify(submission.attachments) ); } async function assertStoredAttachmentsMatch( project: PonyProject, record: InboxRecord, ): Promise { for (const attachment of record.data.attachments) { const attachmentPath = path.join( getCollectionDir(project, "inbox"), attachment.path, ); const storedData = await readFile(attachmentPath); if (sha256(storedData) !== attachment.sha256) { throw new Error( `Inbox message ${record.data.id} already exists with different attachment content.`, ); } } } async function existingInboxSubmission( project: PonyProject, submission: PreparedInboxSubmission, ): Promise { if (!(await pathExists(submission.filePath))) return null; const existing = await readMarkdownRecord( project, submission.filePath, inboxMessageSchema, ); if (!hasSameInboxPayload(existing, submission)) { throw new Error( `Inbox message ${submission.id} already exists with different content.`, ); } await assertStoredAttachmentsMatch(project, existing); return existing; } function createInboxMessage(submission: PreparedInboxSubmission): InboxMessage { const timestamp = nowIso(); return { id: submission.id, type: "inbox_message", status: "open", author_name: submission.authorName, author_email: submission.authorEmail, created_at: timestamp, updated_at: timestamp, claimed_by: null, claimed_at: null, references: { tasks: [], docs: [], }, attachments: submission.attachments, }; } async function writeInboxSubmission( project: PonyProject, submission: PreparedInboxSubmission, message: InboxMessage, ): Promise { if (submission.preparedAttachments.length === 0) { await writeMarkdownRecord(submission.filePath, message, submission.body); return; } const attachmentDirectory = inboxAttachmentDirectory(project, submission.id); if (await pathExists(attachmentDirectory)) { throw new Error( `Attachment directory for ${submission.id} already exists.`, ); } await mkdir(attachmentDirectory); try { for (const attachment of submission.preparedAttachments) { const storedName = path.posix.basename(attachment.metadata.path); await writeFile( path.join(attachmentDirectory, storedName), attachment.data, { flag: "wx", }, ); } await writeMarkdownRecord(submission.filePath, message, submission.body); } catch (error) { await rm(attachmentDirectory, { recursive: true, force: true }); throw error; } } async function removeInboxSubmission( project: PonyProject, submission: PreparedInboxSubmission, ): Promise { const results = await Promise.allSettled([ rm(submission.filePath, { force: true }), rm(inboxAttachmentDirectory(project, submission.id), { recursive: true, force: true, }), ]); throwRejectedResults(results, "Failed to remove inbox submission."); } export async function submitInboxMessage( input: InboxSubmitInput, cwd?: string, ): Promise { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const submission = prepareInboxSubmission(project, input); const existing = await existingInboxSubmission(project, submission); if (existing) { return { record: existing, path: existing.path, commitSha: null, created: false, gitDelivery: createInboxGitDeliveryState( project.config.write.mode, submission.id, ), }; } const message = inboxMessageSchema.parse(createInboxMessage(submission)); const attachmentDirectory = inboxAttachmentDirectory(project, submission.id); const attachmentTargets = submission.preparedAttachments.map( (attachment) => ({ absolutePath: path.join( attachmentDirectory, path.posix.basename(attachment.metadata.path), ), existed: false, }), ); const recordPath = projectRelativePath(project, submission.filePath); const policyResult = await applyWritePolicy(project, { targets: [ { absolutePath: submission.filePath, existed: false }, ...(attachmentTargets.length > 0 ? [ { absolutePath: attachmentDirectory, existed: false, includeInCommit: false, }, ...attachmentTargets, ] : []), ], commitMessage: createPonyCommitMessage({ kind: "inbox_add", id: submission.id, path: recordPath, }), apply: () => writeInboxSubmission(project, submission, message), rollback: () => removeInboxSubmission(project, submission), }); const record = await readMarkdownRecord( project, submission.filePath, inboxMessageSchema, ); return { record, path: recordPath, commitSha: policyResult.commitSha, created: true, gitDelivery: createInboxGitDeliveryState( project.config.write.mode, submission.id, ), }; } export async function claimInboxMessage( id: string, claimedBy: string, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const record = await getInboxMessage(id, project.root); if (record.data.status !== "open") { throw new Error( `Inbox message ${id} is ${record.data.status} and cannot be claimed.`, ); } const timestamp = nowIso(); const updated: InboxMessage = { ...record.data, status: "claimed", claimed_by: claimedBy, claimed_at: timestamp, updated_at: timestamp, }; const policyResult = await applyExistingRecordWrite( project, record, inboxMessageSchema.parse(updated), record.body, createPonyCommitMessage({ kind: "inbox_claim", id: record.data.id, path: record.path, }), ); const updatedRecord = await getInboxMessage(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function closeInboxMessage( id: string, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const record = await getInboxMessage(id, project.root); if (record.data.status === "closed") { return { record, path: record.path, commitSha: null, }; } const updated: InboxMessage = { ...record.data, status: "closed", updated_at: nowIso(), }; const policyResult = await applyExistingRecordWrite( project, record, inboxMessageSchema.parse(updated), record.body, createPonyCommitMessage({ kind: "inbox_close", id: record.data.id, path: record.path, }), ); const updatedRecord = await getInboxMessage(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function listTasks(cwd?: string): Promise { const project = await requireProject(cwd); const files = await listMarkdownFiles(getCollectionDir(project, "tasks")); const records = await Promise.all( files.map((file) => readMarkdownRecord(project, file, taskSchema)), ); for (const record of records) { assertTaskPriorityForProject(project, record.data.priority); } return sortById(records); } export async function getTask(id: string, cwd?: string): Promise { const project = await requireProject(cwd); const parsedId = taskIdSchema.parse(id); const record = await readMarkdownRecord( project, taskPath(project, parsedId), taskSchema, ); assertTaskPriorityForProject(project, record.data.priority); return record; } export async function createTask( input: TaskCreateInput, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const status = input.status ?? project.config.tasks.statuses[0]; assertTaskStatus(project, status); const upstream = await fetchUpstreamTaskIds(project); const id = await nextSequenceId(project, "tasks", "TASK", upstream.ids); const timestamp = nowIso(); const task: Task = { id, type: "task", title: input.title, status, priority: taskPriorityForMutation(project, input.priority), assignee: input.assignee ?? null, created_at: timestamp, updated_at: timestamp, references: { inbox: [], docs: [], }, }; const filePath = taskPath(project, id); const recordPath = projectRelativePath(project, filePath); const policyResult = await applyWritePolicy(project, { targets: [{ absolutePath: filePath, existed: false }], commitMessage: createPonyCommitMessage({ kind: "task_create", id, path: recordPath, }), apply: () => writeMarkdownRecord(filePath, taskSchema.parse(task), input.body ?? ""), rollback: () => rm(filePath, { force: true }), }); const record = await getTask(id, project.root); return { record, path: record.path, commitSha: policyResult.commitSha, created: true, warnings: upstream.warning ? [upstream.warning] : [], }; } export async function moveTask( id: string, status: string, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); assertTaskStatus(project, status); const record = await getTask(id, project.root); const updated: Task = { ...record.data, status, updated_at: nowIso(), }; const policyResult = await applyExistingRecordWrite( project, record, taskSchema.parse(updated), record.body, createPonyCommitMessage({ kind: "task_move", id: record.data.id, path: record.path, status, }), ); const updatedRecord = await getTask(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function prioritizeTask( id: string, priorityInput: string, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); if (project.config.tasks.priority_model !== TASK_PRIORITY_MODEL) { throw new Error( "This project still uses legacy task priorities. Run `pony task migrate-priorities` before prioritizing tasks.", ); } const priority: TaskPriority = parseTaskPriorityInput(priorityInput); const record = await getTask(id, project.root); if (record.data.priority === priority) { return { record, path: record.path, commitSha: null, }; } const updated = taskSchema.parse({ ...record.data, priority, updated_at: nowIso(), }); const policyResult = await applyExistingRecordWrite( project, record, updated, record.body, createPonyCommitMessage({ kind: "task_prioritize", id: record.data.id, path: record.path, priority, }), ); const updatedRecord = await getTask(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function updateTask( id: string, input: RecordUpdateInput, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const record = await getTask(id, project.root); const { nextTitle, nextBody } = assertUpdateChanges( "task", record.data.title, record.body, input, ); const updated = taskSchema.parse({ ...record.data, title: nextTitle, updated_at: nowIso(), }); const policyResult = await applyExistingRecordWrite( project, record, updated, nextBody, createPonyCommitMessage({ kind: "task_update", id: record.data.id, path: record.path, }), ); const updatedRecord = await getTask(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function listDocs(cwd?: string): Promise { const project = await requireProject(cwd); const files = await listMarkdownFiles(getCollectionDir(project, "docs")); const records = await Promise.all( files.map((file) => readMarkdownRecord(project, file, docSchema)), ); return sortById(records); } export async function getDoc(id: string, cwd?: string): Promise { const project = await requireProject(cwd); const parsedId = docIdSchema.parse(id); return readMarkdownRecord(project, docPath(project, parsedId), docSchema); } export async function createDoc( input: DocCreateInput, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const id = await nextSequenceId(project, "docs", "DOC"); const timestamp = nowIso(); const doc: Doc = { id, type: input.type ?? "note", title: input.title, status: input.status ?? "active", visibility: "shared", created_at: timestamp, updated_at: timestamp, superseded_by: null, }; const filePath = docPath(project, id); const recordPath = projectRelativePath(project, filePath); const policyResult = await applyWritePolicy(project, { targets: [{ absolutePath: filePath, existed: false }], commitMessage: createPonyCommitMessage({ kind: "doc_create", id, path: recordPath, }), apply: () => writeMarkdownRecord(filePath, docSchema.parse(doc), input.body ?? ""), rollback: () => rm(filePath, { force: true }), }); const record = await getDoc(id, project.root); return { record, path: record.path, commitSha: policyResult.commitSha, created: true, }; } export async function updateDoc( id: string, input: RecordUpdateInput, cwd?: string, ): Promise> { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const record = await getDoc(id, project.root); const { nextTitle, nextBody } = assertUpdateChanges( "doc", record.data.title, record.body, input, ); const updated = docSchema.parse({ ...record.data, title: nextTitle, updated_at: nowIso(), }); const policyResult = await applyExistingRecordWrite( project, record, updated, nextBody, createPonyCommitMessage({ kind: "doc_update", id: record.data.id, path: record.path, }), ); const updatedRecord = await getDoc(id, project.root); return { record: updatedRecord, path: updatedRecord.path, commitSha: policyResult.commitSha, }; } export async function linkInboxMessage( id: string, input: InboxLinkInput, cwd?: string, ): Promise { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const taskIds = [...new Set(input.taskIds ?? [])].map((taskId) => taskIdSchema.parse(taskId), ); const docIds = [...new Set(input.docIds ?? [])].map((docId) => docIdSchema.parse(docId), ); if (taskIds.length === 0 && docIds.length === 0) { throw new Error("inbox link requires at least one --task or --doc target."); } // Resolve every target before writing either side of a relationship. const [inboxRecord, taskRecords, docRecords] = await Promise.all([ getInboxMessage(id, project.root), Promise.all(taskIds.map((taskId) => getTask(taskId, project.root))), Promise.all(docIds.map((docId) => getDoc(docId, project.root))), ]); const timestamp = nowIso(); const nextInboxTaskRefs = addUniqueReferences( inboxRecord.data.references.tasks, taskIds, ); const nextInboxDocRefs = addUniqueReferences( inboxRecord.data.references.docs, docIds, ); const inboxChanged = !arraysEqual(inboxRecord.data.references.tasks, nextInboxTaskRefs) || !arraysEqual(inboxRecord.data.references.docs, nextInboxDocRefs); const writes: PendingRecordWrite[] = []; if (inboxChanged) { const updatedInbox = inboxMessageSchema.parse({ ...inboxRecord.data, references: { tasks: nextInboxTaskRefs, docs: nextInboxDocRefs }, updated_at: timestamp, }); writes.push({ absolutePath: inboxRecord.absolutePath, previousContent: await readFile(inboxRecord.absolutePath, "utf8"), nextData: updatedInbox, body: inboxRecord.body, }); } for (const taskRecord of taskRecords) { const inboxRefs = addUniqueReferences(taskRecord.data.references.inbox, [ inboxRecord.data.id, ]); if (arraysEqual(taskRecord.data.references.inbox, inboxRefs)) continue; const updatedTask = taskSchema.parse({ ...taskRecord.data, references: { ...taskRecord.data.references, inbox: inboxRefs }, updated_at: timestamp, }); writes.push({ absolutePath: taskRecord.absolutePath, previousContent: await readFile(taskRecord.absolutePath, "utf8"), nextData: updatedTask, body: taskRecord.body, }); } const policyResult = writes.length > 0 ? await applyWritePolicy(project, { targets: writes.map((write) => ({ absolutePath: write.absolutePath, existed: true, })), commitMessage: createPonyCommitMessage({ kind: "inbox_link", id: inboxRecord.data.id, affectedCount: writes.length, }), apply: () => writeRecordsAtomically(writes), rollback: () => restoreRecordWrites(writes), }) : { commitSha: null }; return { inbox: [await getInboxMessage(inboxRecord.data.id, project.root)], tasks: await Promise.all( taskIds.map((taskId) => getTask(taskId, project.root)), ), docs: docRecords, changed: writes.length > 0, commitSha: policyResult.commitSha, }; } export async function linkTask( id: string, input: TaskLinkInput, cwd?: string, ): Promise { const project = await requireProject(cwd); assertSupportedWritePolicy(project); const inboxIds = [...new Set(input.inboxIds ?? [])].map((inboxId) => inboxIdSchema.parse(inboxId), ); const docIds = [...new Set(input.docIds ?? [])].map((docId) => docIdSchema.parse(docId), ); if (inboxIds.length === 0 && docIds.length === 0) { throw new Error("task link requires at least one --inbox or --doc target."); } // Resolve every target before writing either side of a relationship. const [taskRecord, inboxRecords, docRecords] = await Promise.all([ getTask(id, project.root), Promise.all( inboxIds.map((inboxId) => getInboxMessage(inboxId, project.root)), ), Promise.all(docIds.map((docId) => getDoc(docId, project.root))), ]); const timestamp = nowIso(); const nextTaskInboxRefs = addUniqueReferences( taskRecord.data.references.inbox, inboxIds, ); const nextTaskDocRefs = addUniqueReferences( taskRecord.data.references.docs, docIds, ); const taskChanged = !arraysEqual(taskRecord.data.references.inbox, nextTaskInboxRefs) || !arraysEqual(taskRecord.data.references.docs, nextTaskDocRefs); const writes: PendingRecordWrite[] = []; if (taskChanged) { const updatedTask = taskSchema.parse({ ...taskRecord.data, references: { inbox: nextTaskInboxRefs, docs: nextTaskDocRefs }, updated_at: timestamp, }); writes.push({ absolutePath: taskRecord.absolutePath, previousContent: await readFile(taskRecord.absolutePath, "utf8"), nextData: updatedTask, body: taskRecord.body, }); } for (const inboxRecord of inboxRecords) { const taskRefs = addUniqueReferences(inboxRecord.data.references.tasks, [ taskRecord.data.id, ]); if (arraysEqual(inboxRecord.data.references.tasks, taskRefs)) continue; const updatedInbox = inboxMessageSchema.parse({ ...inboxRecord.data, references: { ...inboxRecord.data.references, tasks: taskRefs }, updated_at: timestamp, }); writes.push({ absolutePath: inboxRecord.absolutePath, previousContent: await readFile(inboxRecord.absolutePath, "utf8"), nextData: updatedInbox, body: inboxRecord.body, }); } const policyResult = writes.length > 0 ? await applyWritePolicy(project, { targets: writes.map((write) => ({ absolutePath: write.absolutePath, existed: true, })), commitMessage: createPonyCommitMessage({ kind: "task_link", id: taskRecord.data.id, affectedCount: writes.length, }), apply: () => writeRecordsAtomically(writes), rollback: () => restoreRecordWrites(writes), }) : { commitSha: null }; return { inbox: await Promise.all( inboxIds.map((inboxId) => getInboxMessage(inboxId, project.root)), ), tasks: [await getTask(taskRecord.data.id, project.root)], docs: docRecords, changed: writes.length > 0, commitSha: policyResult.commitSha, }; }