/** * Validation for the app's "Add work" route. Pure so it is unit-testable. * Every kind maps to source "manual" (create() sets it); friction/feedback * become a label so the queue can show what kind of work it is. */ import type { ProjectsState } from '../projects/model.ts' import type { WorkItemPriority } from '../core/work-item.ts' export type CreateInput = { projectId: string title: string body: string priority?: WorkItemPriority labels: string[] repoRef?: string idempotencyKey?: string } const KINDS: Record = { general: null, manual: null, friction: 'friction', feedback: 'feedback' } export function parseCreateInput( raw: Record, state: ProjectsState, ): { ok: true; input: CreateInput } | { ok: false; error: string } { const str = (v: unknown) => (typeof v === 'string' ? v : v == null ? '' : String(v)) const projectId = str(raw.projectId).trim() const project = state.projects[projectId] if (!project) return { ok: false, error: 'Choose a project for this work.' } if (!project.enabled) return { ok: false, error: `${project.displayName} is disabled. Turn it on in Manage projects first.` } const title = str(raw.title).trim() if (!title) return { ok: false, error: 'Add a title so you can recognize this work later.' } if (title.length > 200) return { ok: false, error: 'Keep the title under 200 characters.' } const body = str(raw.body) if (body.length > 8000) return { ok: false, error: 'Keep the details under 8,000 characters.' } let priority: WorkItemPriority | undefined const p = raw.priority if (p !== undefined && p !== null && p !== '') { const n = Number(p) if (!Number.isInteger(n) || n < 0 || n > 3) return { ok: false, error: 'Priority must be P0, P1, P2, or P3.' } priority = n as 0 | 1 | 2 | 3 } const kindKey = str(raw.kind ?? raw.source ?? 'general').trim() || 'general' if (!(kindKey in KINDS)) return { ok: false, error: 'Type must be General task, Friction, or Feedback.' } const kind = KINDS[kindKey] const repoRef = str(raw.repoRef).trim() if (repoRef && !project.repos.some((r) => r.repoRef.toLowerCase() === repoRef.toLowerCase())) { return { ok: false, error: `${repoRef} is not a repository of ${project.displayName}.` } } const idempotencyKey = str(raw.idempotencyKey).trim() if (idempotencyKey && !/^[A-Za-z0-9_-]{8,80}$/.test(idempotencyKey)) return { ok: false, error: 'Invalid idempotency key.' } return { ok: true, input: { projectId, title, body, priority, labels: kind ? [kind] : [], repoRef: repoRef || undefined, ...(idempotencyKey ? { idempotencyKey } : {}) }, } }