#!/usr/bin/env node import os from "node:os"; import { readFile, realpath } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { Command, CommanderError } from "commander"; import { type DocStatus, type DocType, type DocRecord, type InboxRecord, type LinkMutationResult, type TaskPriorityMigrationPlan, type TaskPriorityMigrationResult, type TaskRecord, type TaskIdMutationResult, claimInboxMessage, closeInboxMessage, createDoc, formatGitDeliveryReminder, createMarkdownContext, createPonyDoctorReport, createTask, formatPonyDoctorReport, getDoc, getInboxMessage, getInstructions, getProjectSnapshot, getTask, getWorkspaceCwd, initProject, listDocs, listInbox, listTasks, linkInboxMessage, linkTask, moveTask, migrateTaskPriorities, inspectTaskConflict, inspectTaskPriorityMigration, prioritizeTask, renumberTask, renameTaskStatus, requireProjectsFromPaths, resolveTaskConflict, shiftTasks, requireProject, summarizeInboxMessage, submitInboxMessage, localizedTaskPriorityLabel, publicTaskPriority, selectNextTask, taskPriorityLabel, updateDoc, updateInstructions, updateTask, } from "../core/index.js"; import { buildStaticWeb } from "./build.js"; import { CHATGPT_PERSONAL_MARKETPLACE_PATH, setupChatGptPlugin, } from "./chatgpt-setup.js"; import { setupClaudePlugin, type ClaudeCommandRunner, type ClaudeSetupResult, } from "./claude-setup.js"; import { setupCodexPlugin, type CodexCommandRunner } from "./codex-setup.js"; import { findPackageRoot, startWebServer } from "./web.js"; interface GlobalOptions { cwd?: string; } export const PONY_COMMAND_MANIFEST_FLAG = "--pony-command-manifest"; export interface PonyCommandManifest { protocolVersion: 1; commands: Array<{ description: string; name: string }>; } interface JsonOption { json?: boolean; } export interface PonyCliInput extends AsyncIterable< string | Uint8Array > { isTTY?: boolean; } export interface PonyCliOutput { isTTY?: boolean; write(value: string): unknown; } export interface PonyCliRuntime { env: NodeJS.ProcessEnv; homeDir?: string; stdin: PonyCliInput; stdout: PonyCliOutput; stderr: PonyCliOutput; runClaudeCommand?: ClaudeCommandRunner; runCodexCommand?: CodexCommandRunner; } const processRuntime: PonyCliRuntime = { env: process.env, stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, }; function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } export function createPonyProgram(runtime: PonyCliRuntime = processRuntime): { program: Command; exitCode: () => number; } { let currentExitCode = 0; const program = new Command(); program .name("pony") .description("Git-backed agent-native project workspace") .option("--cwd ", "workspace directory", getWorkspaceCwd()) .showHelpAfterError() .configureOutput({ writeOut: (value) => runtime.stdout.write(value), writeErr: (value) => runtime.stderr.write(value), }) .exitOverride(); function writeLine(value = ""): void { runtime.stdout.write(`${value}\n`); } function writeWarning(value: string): void { runtime.stderr.write(`Warning: ${value}\n`); } function cwd(): string { return path.resolve( (program.opts().cwd ?? getWorkspaceCwd()).toString(), ); } function printJson(value: unknown): void { writeLine(JSON.stringify(value, null, 2)); } async function packageVersion(): Promise { const packageRoot = await findPackageRoot(); const packageJson = JSON.parse( await readFile(path.join(packageRoot, "package.json"), "utf8"), ) as { version?: unknown }; if (typeof packageJson.version !== "string") { throw new Error("Pony package version is missing or invalid."); } return packageJson.version; } function recordJson(record: { data: object; body: string; path: string }) { return { ...(record.data as Record), body: record.body, path: record.path, }; } function collectOption(value: string, previous: string[]): string[] { return [...previous, value]; } function assignmentOptions( values: string[], option: "--map" | "--restore", ): Record { const assignments: Record = {}; for (const value of values) { const separator = value.indexOf("="); if (separator <= 0 || separator === value.length - 1) { throw new Error( `${option} expects ; received "${value}".`, ); } const source = value.slice(0, separator); const target = value.slice(separator + 1); if (assignments[source] !== undefined) { throw new Error(`Duplicate ${option} source "${source}".`); } assignments[source] = target; } return assignments; } function printTaskPriorityMigrationPlan( plan: TaskPriorityMigrationPlan, options: JsonOption, ): void { if (options.json) { printJson(plan); return; } writeLine( plan.migrationRequired ? "Task priority migration is required." : "Task priorities are current.", ); writeLine(`Statuses: ${plan.statuses.join(", ")}`); printLegacyPriorityInventory(plan.legacyPriorities); printArchivedTaskInventory(plan.archivedTasks); } function printLegacyPriorityInventory( priorities: TaskPriorityMigrationPlan["legacyPriorities"], ): void { if (priorities.length === 0) return; writeLine("Legacy priorities:"); for (const priority of priorities) { writeLine( `- ${priority.value}: ${priority.taskCount} ${taskCountNoun(priority.taskCount)}${mappingSuggestion(priority.suggestedMapping)}`, ); } } function taskCountNoun(taskCount: number): "task" | "tasks" { return taskCount === 1 ? "task" : "tasks"; } function mappingSuggestion(suggestion: string | null): string { return suggestion ? `; suggested ${suggestion}` : ""; } function printArchivedTaskInventory( tasks: TaskPriorityMigrationPlan["archivedTasks"], ): void { if (tasks.length === 0) return; writeLine("Archived tasks requiring an active status:"); for (const task of tasks) { writeLine(`- ${task.id}: ${task.title}`); } } function printTaskPriorityMigrationResult( result: TaskPriorityMigrationResult, options: JsonOption, ): void { if (options.json) { printJson({ priorityModel: result.priorityModel, statuses: result.statuses, tasks: result.tasks.map(recordJson), changedTaskCount: result.tasks.length, configPath: result.configPath, commitSha: result.commitSha, }); return; } writeLine( `Migrated task priorities across ${result.tasks.length} task${result.tasks.length === 1 ? "" : "s"}`, ); } function linkResultJson(result: { inbox: InboxRecord[]; tasks: TaskRecord[]; docs: DocRecord[]; changed: boolean; commitSha: string | null; }) { return { inbox: result.inbox.map(recordJson), tasks: result.tasks.map(recordJson), docs: result.docs.map(recordJson), changed: result.changed, commitSha: result.commitSha, }; } function printInboxTable(records: InboxRecord[]): void { writeLine(["ID", "STATUS", "MESSAGE", "AUTHOR", "FILES"].join("\t")); for (const record of records) { writeLine( [ record.data.id, record.data.status, summarizeInboxMessage(record.body, record.data.attachments, 60), record.data.author_name, record.data.attachments.length, ].join("\t"), ); } } function printTaskTable(records: TaskRecord[]): void { writeLine(["ID", "STATUS", "PRIORITY", "TITLE", "ASSIGNEE"].join("\t")); for (const record of records) { writeLine( [ record.data.id, record.data.status, taskPriorityLabel(record.data.priority), record.data.title, record.data.assignee ?? "", ].join("\t"), ); } } function printDocTable(records: DocRecord[]): void { writeLine(["ID", "TYPE", "STATUS", "TITLE"].join("\t")); for (const record of records) { writeLine( [ record.data.id, record.data.type, record.data.status, record.data.title, ].join("\t"), ); } } function printRecord(record: InboxRecord | TaskRecord | DocRecord): void { printJson(recordJson(record)); } function printTitledRecord( record: TaskRecord | DocRecord, fields: Array, ): void { writeLine(`# ${record.data.title}`); writeLine(); writeLine(`id: ${record.data.id}`); for (const [label, value] of fields) { writeLine(`${label}: ${value}`); } writeLine(`path: ${record.path}`); if (record.body) { writeLine(); writeLine(record.body); } } function printRecordMutationResult( result: { record: InboxRecord | TaskRecord | DocRecord; commitSha: string | null; warnings?: string[]; }, options: JsonOption, message: string, ): void { if (options.json) { printJson({ ...recordJson(result.record), commitSha: result.commitSha, ...(result.warnings ? { warnings: result.warnings } : {}), }); return; } writeLine(message); for (const warning of result.warnings ?? []) writeWarning(warning); } function printLinkMutationResult( result: LinkMutationResult, options: JsonOption, id: string, ): void { if (options.json) { printJson(linkResultJson(result)); return; } writeLine(result.changed ? `Linked ${id}` : `${id} links already exist`); } function taskIdMutationJson(result: TaskIdMutationResult) { return { mappings: result.mappings, tasks: result.tasks.map(recordJson), inbox: result.inbox.map(recordJson), textualReferences: result.textualReferences, commitSha: result.commitSha, recoveryOperation: result.recoveryOperation, }; } function printTextualReferenceFollowUp( references: TaskIdMutationResult["textualReferences"], ): void { if (references.length === 0) return; writeLine("Textual task ID occurrences require manual review:"); for (const reference of references) { const location = reference.line ? `body line ${reference.line} at ${reference.path}` : reference.path; writeLine(`- ${reference.id} in ${reference.field} at ${location}`); } } function defaultAuthorName(): string { return ( runtime.env.PONY_AUTHOR_NAME ?? runtime.env.USER ?? os.userInfo().username ); } function authorEmail(option?: string): string { const email = option ?? runtime.env.PONY_AUTHOR_EMAIL; if (!email) { throw new Error( "Inbox messages require --email or PONY_AUTHOR_EMAIL.", ); } return email; } async function readPipedBody(fallback = ""): Promise { if (runtime.stdin.isTTY) { return fallback; } return (await readStandardInput()) || fallback; } async function readStandardInput(): Promise { const chunks: Buffer[] = []; for await (const chunk of runtime.stdin) { chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); } return Buffer.concat(chunks).toString("utf8").trimEnd(); } async function readOptionalPipedBody( argumentBody?: string, ): Promise { if (argumentBody !== undefined) return argumentBody; if (runtime.stdin.isTTY) return undefined; return (await readStandardInput()) || undefined; } async function readAttachmentInputs(attachmentPaths: string[]) { return Promise.all( attachmentPaths.map(async (attachmentPath) => { try { return { name: path.basename(attachmentPath), data: await readFile(path.resolve(attachmentPath)), }; } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error( `Cannot read attachment "${attachmentPath}": ${message}`, ); } }), ); } program .command("init") .description("create .pony project state") .option("--name ", "project display name") .option("--language ", "project content language", "en") .action(async (options: { name?: string; language: string }) => { const result = await initProject(cwd(), options.name, options.language); writeLine( result.createdConfig ? `Created ${path.relative(cwd(), result.project.configPath)}` : `${path.relative(cwd(), result.project.configPath)} already exists`, ); }); const setup = program .command("setup") .description("configure optional integrations"); setup .command("chatgpt") .description("add Pony to ChatGPT's personal plugin marketplace") .option("--json", "print JSON") .action(async (options: JsonOption) => { const marketplacePath = path.join( runtime.homeDir ?? os.homedir(), CHATGPT_PERSONAL_MARKETPLACE_PATH, ); const result = await setupChatGptPlugin( await packageVersion(), marketplacePath, ); if (options.json) { printJson(result); return; } writeLine( result.changed ? `Added Pony ${result.version} to ChatGPT's ${result.marketplaceName} plugin marketplace.` : `Pony ${result.version} is already available in ChatGPT's ${result.marketplaceName} plugin marketplace.`, ); writeLine( "Restart ChatGPT, then open Plugins > Personal and install Pony.", ); }); setup .command("claude") .description("install Pony for Claude Code at user scope") .option("--json", "print JSON") .action(async (options: JsonOption) => { const result = await setupClaudePlugin( await packageVersion(), runtime.runClaudeCommand, ); if (options.json) { printJson(result); return; } const messages: Record = { current: `Claude Code plugin ${result.pluginId} ${result.installedVersion} is already current at ${result.scope} scope.`, installed: `Installed Claude Code plugin ${result.pluginId} ${result.installedVersion} at ${result.scope} scope.`, newer: `Claude Code plugin ${result.pluginId} ${result.installedVersion} is newer than Pony ${result.version}; left it unchanged.`, upgraded: `Upgraded Claude Code plugin ${result.pluginId} to ${result.installedVersion} at ${result.scope} scope.`, }; writeLine(messages[result.outcome]); writeLine( "Run `/reload-plugins` in Claude Code or start a new session to use the Pony skill.", ); }); setup .command("codex") .description("report Whitespace Codex marketplace availability") .option("--json", "print JSON") .action(async (options: JsonOption) => { const result = await setupCodexPlugin( await packageVersion(), runtime.runCodexCommand, ); if (options.json) { printJson(result); return; } if (!result.marketplaceAdded && !result.pluginChanged) { writeLine( `Codex plugin ${result.pluginId} is already set up for Pony ${result.version}.`, ); return; } writeLine( `Set up Codex plugin ${result.pluginId} for Pony ${result.version}.`, ); writeLine("Start a new Codex task to use the Pony skill."); }); program .command("start [projectPaths...]") .description( "start the prebuilt Pony web app for this workspace or selected projects", ) .option("--port ", "override the configured web port") .option("--host ", "host interface to bind") .option("--no-open", "do not open Pony in a browser") .action( async ( projectPaths: string[], options: { host?: string; open: boolean; port?: string }, ) => { const projects = projectPaths.length > 0 ? await requireProjectsFromPaths(projectPaths, cwd()) : [await requireProject(cwd())]; currentExitCode = await startWebServer( await findPackageRoot(), projects, options, ); }, ); program .command("build") .description("build a static read-only Pony web snapshot") .option("--base ", "deployment base path", "/") .option("--out-dir ", "output directory", ".pony-web") .action(async (options: { base: string; outDir: string }) => { const project = await requireProject(cwd()); const result = await buildStaticWeb( await findPackageRoot(), project, options, runtime.env, ); writeLine(`Built static Pony web snapshot at ${result.outDir}`); }); const inbox = program .command("inbox") .description("work with inbox messages"); inbox .command("list") .option("--json", "print JSON") .action(async (options: JsonOption) => { const records = await listInbox(cwd()); if (options.json) { printJson(records.map(recordJson)); return; } printInboxTable(records); }); inbox .command("show") .argument("") .option("--json", "print JSON") .action(async (id: string, options: JsonOption) => { const record = await getInboxMessage(id, cwd()); if (options.json) { printRecord(record); return; } writeLine("# Inbox message"); writeLine(); writeLine(`id: ${record.data.id}`); writeLine(`status: ${record.data.status}`); writeLine(`author: ${record.data.author_name}`); writeLine(`email: ${record.data.author_email}`); writeLine(`attachments: ${record.data.attachments.length}`); writeLine(`path: ${record.path}`); if (record.body) { writeLine(); writeLine(record.body); } }); inbox .command("add") .argument("[message]") .option("--author ", "author name") .option("--email ", "author email") .option("--id ", "client-generated inbox ID") .option( "--attachment ", "attach a file (repeatable)", collectOption, [], ) .option("--json", "print JSON") .action( async ( message: string | undefined, options: JsonOption & { attachment: string[]; author?: string; email?: string; id?: string; }, ) => { const result = await submitInboxMessage( { id: options.id, body: await readPipedBody(message ?? ""), authorName: options.author ?? defaultAuthorName(), authorEmail: authorEmail(options.email), attachments: await readAttachmentInputs(options.attachment), }, cwd(), ); if (options.json) { printJson({ ...recordJson(result.record), commitSha: result.commitSha, gitDelivery: result.gitDelivery, }); return; } writeLine(`Added ${result.record.data.id} at ${result.path}`); const gitReminder = formatGitDeliveryReminder(result.gitDelivery); if (gitReminder) writeLine(gitReminder); }, ); inbox .command("link") .argument("") .option("--task ", "link a task (repeatable)", collectOption, []) .option("--doc ", "link a doc (repeatable)", collectOption, []) .option("--json", "print JSON") .action( async ( id: string, options: JsonOption & { task: string[]; doc: string[] }, ) => { const result = await linkInboxMessage( id, { taskIds: options.task, docIds: options.doc }, cwd(), ); printLinkMutationResult(result, options, id); }, ); inbox .command("claim") .argument("") .option("--by ", "claiming agent name") .option("--json", "print JSON") .action(async (id: string, options: JsonOption & { by?: string }) => { const result = await claimInboxMessage( id, options.by ?? defaultAuthorName(), cwd(), ); printRecordMutationResult( result, options, `Claimed ${result.record.data.id}`, ); }); inbox .command("close") .argument("") .option("--json", "print JSON") .action(async (id: string, options: JsonOption) => { const result = await closeInboxMessage(id, cwd()); printRecordMutationResult( result, options, `Closed ${result.record.data.id}`, ); }); const task = program.command("task").description("work with tasks"); task .command("list") .option("--json", "print JSON") .action(async (options: JsonOption) => { const records = await listTasks(cwd()); if (options.json) { printJson(records.map(recordJson)); return; } printTaskTable(records); }); task .command("show") .argument("") .option("--json", "print JSON") .action(async (id: string, options: JsonOption) => { const record = await getTask(id, cwd()); if (options.json) { printRecord(record); return; } printTitledRecord(record, [ ["status", record.data.status], ["priority", taskPriorityLabel(record.data.priority)], ]); }); task .command("next") .description("recommend the next eligible task without changing it") .option("--json", "print JSON") .action(async (options: JsonOption) => { const snapshot = await getProjectSnapshot(cwd()); const result = selectNextTask( snapshot.tasks, snapshot.taskStatuses, snapshot.projectLanguage, ); const task = result.task; if (options.json) { printJson({ task: task ? { id: task.data.id, title: task.data.title, status: task.data.status, priority: publicTaskPriority(task.data.priority), } : null, nextStatus: result.nextStatus, selection: result.selection, }); return; } const isSwedish = snapshot.projectLanguage === "sv" || snapshot.projectLanguage.startsWith("sv-"); if (!task) { writeLine(isSwedish ? "Ingen valbar uppgift." : "No eligible task."); return; } const priority = publicTaskPriority(task.data.priority); writeLine(`${task.data.id}: ${task.data.title}`); writeLine(`Status: ${task.data.status}`); writeLine( `${isSwedish ? "Prioritet" : "Priority"}: ${localizedTaskPriorityLabel(priority, snapshot.projectLanguage)}`, ); writeLine( `${isSwedish ? "Nästa status" : "Next status"}: ${result.nextStatus ?? (isSwedish ? "Ingen" : "None")}`, ); writeLine( `${isSwedish ? "Vald eftersom" : "Selected because"}: ${result.selection.explanation}`, ); }); task .command("create") .argument("") .argument("[body]") .option("--status <status>", "task status") .option( "--priority <priority>", "task priority: asap, soon, in_turn/null, later, or not_planned", ) .option("--assignee <assignee>", "task assignee") .option("--json", "print JSON") .action( async ( title: string, body: string | undefined, options: JsonOption & { status?: string; priority?: string; assignee?: string; }, ) => { const result = await createTask( { title, body: await readPipedBody(body ?? ""), status: options.status, priority: options.priority ?? null, assignee: options.assignee ?? null, }, cwd(), ); printRecordMutationResult( result, options, `Created ${result.record.data.id} at ${result.path}`, ); }, ); task .command("move") .argument("<id>") .argument("<status>") .option("--json", "print JSON") .action(async (id: string, status: string, options: JsonOption) => { const result = await moveTask(id, status, cwd()); printRecordMutationResult( result, options, `Moved ${result.record.data.id} to ${result.record.data.status}`, ); }); task .command("prioritize") .description( "set task scheduling priority (in_turn and null both persist priority: null)", ) .argument("<id>") .argument("<priority>", "asap, soon, in_turn/null, later, or not_planned") .option("--json", "print JSON") .action(async (id: string, priority: string, options: JsonOption) => { const result = await prioritizeTask(id, priority, cwd()); printRecordMutationResult( result, options, result.commitSha ? `Prioritized ${result.record.data.id} as ${taskPriorityLabel(result.record.data.priority)}` : `${result.record.data.id} is already ${taskPriorityLabel(result.record.data.priority)}`, ); }); task .command("migrate-priorities") .description( "explicitly migrate legacy priorities and archived task statuses", ) .option("--inspect", "show required mappings without changing files") .option( "--map <legacy=priority>", "map one legacy priority (repeatable)", collectOption, [], ) .option( "--restore <TASK-ID=status>", "restore one archived task to an active status (repeatable)", collectOption, [], ) .option("--json", "print JSON") .action( async ( options: JsonOption & { inspect?: boolean; map: string[]; restore: string[]; }, ) => { if (options.inspect) { if (options.map.length > 0 || options.restore.length > 0) { throw new Error( "--inspect cannot be combined with --map or --restore.", ); } printTaskPriorityMigrationPlan( await inspectTaskPriorityMigration(cwd()), options, ); return; } const result = await migrateTaskPriorities( { priorityMappings: assignmentOptions(options.map, "--map"), archivedTaskStatuses: assignmentOptions( options.restore, "--restore", ), }, cwd(), ); printTaskPriorityMigrationResult(result, options); }, ); task .command("renumber") .description("atomically rename one task ID") .argument("<source>") .argument("<target>") .option("--json", "print JSON") .action(async (source: string, target: string, options: JsonOption) => { const result = await renumberTask(source, target, cwd()); if (options.json) { printJson(taskIdMutationJson(result)); return; } writeLine(`Renumbered ${source} to ${target}`); if (result.recoveryOperation) { writeLine( `Staged recovery files for the active Git ${result.recoveryOperation}; continue it manually.`, ); } printTextualReferenceFollowUp(result.textualReferences); }); task .command("shift") .description("atomically shift task IDs at or above a starting ID") .argument("<from>") .requiredOption("--by <count>", "positive increment") .option("--json", "print JSON") .action(async (from: string, options: JsonOption & { by: string }) => { const result = await shiftTasks(from, Number(options.by), cwd()); if (options.json) { printJson(taskIdMutationJson(result)); return; } writeLine( `Shifted ${result.mappings.length} task ID${result.mappings.length === 1 ? "" : "s"} by ${options.by}`, ); if (result.recoveryOperation) { writeLine( `Staged recovery files for the active Git ${result.recoveryOperation}; continue it manually.`, ); } printTextualReferenceFollowUp(result.textualReferences); }); task .command("conflict") .description("inspect an add/add task conflict from Git index stages") .argument("<id>") .option("--json", "print JSON") .action(async (id: string, options: JsonOption) => { const result = await inspectTaskConflict(id, cwd()); if (options.json) { printJson({ id: result.id, path: result.path, variants: result.variants.map((variant) => ({ stage: variant.stage, label: variant.label, title: variant.title, created_at: variant.createdAt, })), }); return; } writeLine(`${result.id} add/add conflict at ${result.path}`); for (const variant of result.variants) { writeLine( `Stage ${variant.stage} (${variant.label}): ${variant.title} — ${variant.createdAt}`, ); } }); task .command("resolve-conflict") .description("move one add/add variant to a free task ID and stage both") .argument("<id>") .requiredOption("--move-stage <stage>", "Git stage 2 (ours) or 3 (theirs)") .requiredOption("--to <target>", "free target task ID") .option("--json", "print JSON") .action( async ( id: string, options: JsonOption & { moveStage: string; to: string }, ) => { const result = await resolveTaskConflict( id, Number(options.moveStage), options.to, cwd(), ); if (options.json) { printJson({ conflictId: result.conflictId, movedStage: result.movedStage, targetId: result.targetId, kept: recordJson(result.kept), moved: recordJson(result.moved), textualReferences: result.textualReferences, recoveryOperation: result.recoveryOperation, }); return; } writeLine( `Kept the other variant at ${result.conflictId}, moved stage ${result.movedStage} to ${result.targetId}, and staged both files.`, ); writeLine( `Continue the active Git ${result.recoveryOperation} manually. Existing ${result.conflictId} references remain ambiguous.`, ); printTextualReferenceFollowUp(result.textualReferences); }, ); task .command("rename-status") .description("rename or merge a configured task status") .argument("<source>") .argument("<target>") .option("--json", "print JSON") .action(async (source: string, target: string, options: JsonOption) => { const result = await renameTaskStatus(source, target, cwd()); if (options.json) { printJson({ sourceStatus: result.sourceStatus, targetStatus: result.targetStatus, statuses: result.statuses, tasks: result.tasks.map(recordJson), changedTaskCount: result.tasks.length, configPath: result.configPath, commitSha: result.commitSha, }); return; } writeLine( `Renamed task status ${source} to ${target} in ${result.tasks.length} task${result.tasks.length === 1 ? "" : "s"}`, ); }); task .command("update") .argument("<id>") .argument("[body]") .option("--title <title>", "replace the task title") .option("--json", "print JSON") .action( async ( id: string, body: string | undefined, options: JsonOption & { title?: string }, ) => { const result = await updateTask( id, { title: options.title, body: await readOptionalPipedBody(body) }, cwd(), ); printRecordMutationResult( result, options, `Updated ${result.record.data.id} at ${result.path}`, ); }, ); task .command("link") .argument("<id>") .option( "--inbox <id>", "link an inbox message (repeatable)", collectOption, [], ) .option("--doc <id>", "link a doc (repeatable)", collectOption, []) .option("--json", "print JSON") .action( async ( id: string, options: JsonOption & { inbox: string[]; doc: string[] }, ) => { const result = await linkTask( id, { inboxIds: options.inbox, docIds: options.doc }, cwd(), ); printLinkMutationResult(result, options, id); }, ); const instructions = program .command("instructions") .description("work with shared project instructions"); instructions .command("show") .description("show the canonical shared instructions") .option("--json", "print JSON") .action(async (options: JsonOption) => { const result = await getInstructions(cwd()); if (options.json) { printJson({ ...recordJson(result.record), exists: result.exists, }); return; } writeLine("# Project instructions"); writeLine(); writeLine(`path: ${result.record.path}`); writeLine(`exists: ${result.exists ? "yes" : "no"}`); if (result.record.body) { writeLine(); writeLine(result.record.body); } }); instructions .command("update") .description("replace the canonical shared instructions") .argument("[body]") .option("--json", "print JSON") .action(async (body: string | undefined, options: JsonOption) => { const result = await updateInstructions( await readPipedBody(body ?? ""), cwd(), ); if (options.json) { printJson({ ...recordJson(result.record), exists: result.exists, changed: result.changed, created: result.created, commitSha: result.commitSha, }); return; } writeLine( result.changed ? `${result.created ? "Created" : "Updated"} ${result.record.path}` : `${result.record.path} already has this content`, ); }); const docs = program.command("docs").description("work with shared docs"); docs .command("list") .option("--json", "print JSON") .action(async (options: JsonOption) => { const records = await listDocs(cwd()); if (options.json) { printJson(records.map(recordJson)); return; } printDocTable(records); }); docs .command("show") .argument("<id>") .option("--json", "print JSON") .action(async (id: string, options: JsonOption) => { const record = await getDoc(id, cwd()); if (options.json) { printRecord(record); return; } printTitledRecord(record, [ ["type", record.data.type], ["status", record.data.status], ]); }); docs .command("create") .argument("<title>") .argument("[body]") .option("--type <type>", "doc type") .option("--status <status>", "doc status") .option("--json", "print JSON") .action( async ( title: string, body: string | undefined, options: JsonOption & { type?: string; status?: string }, ) => { const result = await createDoc( { title, body: await readPipedBody(body ?? ""), type: options.type as DocType | undefined, status: options.status as DocStatus | undefined, }, cwd(), ); printRecordMutationResult( result, options, `Created ${result.record.data.id} at ${result.path}`, ); }, ); docs .command("update") .argument("<id>") .argument("[body]") .option("--title <title>", "replace the doc title") .option("--json", "print JSON") .action( async ( id: string, body: string | undefined, options: JsonOption & { title?: string }, ) => { const result = await updateDoc( id, { title: options.title, body: await readOptionalPipedBody(body) }, cwd(), ); printRecordMutationResult( result, options, `Updated ${result.record.data.id} at ${result.path}`, ); }, ); program .command("doctor") .description("report Pony files that violate the current schemas") .option("--json", "print a machine-readable report") .action(async (options: JsonOption) => { const report = await createPonyDoctorReport(cwd()); if (options.json) { printJson(report); } else { runtime.stdout.write(formatPonyDoctorReport(report)); } if (!report.valid) currentExitCode = 1; }); program .command("context") .option("--format <format>", "context format", "markdown") .action(async (options: { format: string }) => { if (options.format !== "markdown") { throw new Error( `Context format "${options.format}" is not implemented in Pony v0.`, ); } runtime.stdout.write(await createMarkdownContext(cwd())); }); return { program, exitCode: () => currentExitCode, }; } /** * Runs an isolated CLI invocation so callers can execute Pony repeatedly without * sharing Commander state, process streams, or exit codes between invocations. */ export async function runPonyCli( args: string[], runtime: PonyCliRuntime = processRuntime, ): Promise<number> { const { program, exitCode } = createPonyProgram(runtime); try { await program.parseAsync(args, { from: "user" }); return exitCode(); } catch (error) { if (error instanceof CommanderError) return error.exitCode; runtime.stderr.write(`${errorMessage(error)}\n`); return 1; } } /** * The launcher asks the project runtime for its commands instead of assuming * that a global release knows every command exposed by an older local release. */ export async function createPonyCommandManifest(): Promise<PonyCommandManifest> { const { program } = createPonyProgram(); return { protocolVersion: 1, commands: program.commands .filter( (command) => command.name() !== "init" && command.name() !== "setup", ) .map((command) => ({ description: command.description(), name: command.name(), })), }; } export async function isCliEntrypoint( invokedPath: string | undefined, moduleUrl = import.meta.url, ): Promise<boolean> { if (!invokedPath) return false; try { return ( (await realpath(path.resolve(invokedPath))) === (await realpath(fileURLToPath(moduleUrl))) ); } catch { return pathToFileURL(path.resolve(invokedPath)).href === moduleUrl; } } if (await isCliEntrypoint(process.argv[1])) { process.exitCode = await runPonyCli(process.argv.slice(2)); }