import { createPlan, loadPlanStore, savePlanStore, updatePlanStatus, withPlanLink, PLAN_STATUSES, type PlanStatus, type PlanPriority, type PlanLink, type Plan, } from '../../core/plan.ts' import { nowIso } from '../../core/work-item.ts' /** * Create or update a plan. Status changes record history. * * @example * import upsertPlan from 'kody:@kody/kody-factory/plans/upsert' * await upsertPlan({ title: 'Ship the board', status: 'decided', priority: 1 }) */ export default async function upsertPlan(input: { id?: string title?: string body?: string status?: PlanStatus priority?: PlanPriority projectId?: string linkedIssue?: Plan['linkedIssue'] links?: PlanLink[] workItemIds?: string[] archived?: boolean actor?: string reason?: string dryRun?: boolean }) { if (!input) throw new Error('plans/upsert: input is required') const store = await loadPlanStore() const at = nowIso() const actor = input.actor ?? 'human' const reason = input.reason ?? 'updated' let plan: Plan let created = false if (input.id && store.plans[input.id]) { plan = { ...store.plans[input.id]! } if (input.title !== undefined) plan.title = input.title if (input.body !== undefined) plan.body = input.body if (input.priority !== undefined) plan.priority = input.priority if (input.projectId !== undefined) plan.projectId = input.projectId if (input.linkedIssue !== undefined) plan.linkedIssue = input.linkedIssue if (input.workItemIds !== undefined) plan.workItemIds = input.workItemIds if (input.archived !== undefined) plan.archived = input.archived if (input.links) { for (const link of input.links) { plan.links = withPlanLink(plan.links, link) } } if (input.status && input.status !== plan.status) { if (!PLAN_STATUSES.includes(input.status)) throw new Error(`plans/upsert: invalid status ${input.status}`) plan = updatePlanStatus(plan, input.status, reason, actor) } plan.updatedAt = at } else { if (!input.title?.trim()) throw new Error('plans/upsert: title is required for a new plan') plan = createPlan({ title: input.title!, body: input.body, status: input.status, priority: input.priority, projectId: input.projectId, linkedIssue: input.linkedIssue, }) if (input.id) plan.id = input.id if (input.workItemIds) plan.workItemIds = input.workItemIds if (input.archived) plan.archived = true if (input.links) { for (const link of input.links) { plan.links = withPlanLink(plan.links, link) } } created = true } if (input.dryRun) { return { plan, created, persisted: false } } store.plans[plan.id] = plan await savePlanStore(store) return { plan, created, persisted: true } }