import { z } from "zod"; import { TASK_PRIORITY_MODEL } from "./task-priorities.js"; export const PRE_TRIAGE_DEFAULT_TASK_STATUSES = [ "backlog", "todo", "in_progress", "review", "done", "archived", ] as const; export const LEGACY_DEFAULT_TASK_STATUSES = [ "triage", ...PRE_TRIAGE_DEFAULT_TASK_STATUSES, ] as const; export const DEFAULT_TASK_STATUSES = [ "triage", "backlog", "in_progress", "review", "done", ] as const; export const DEFAULT_PROJECT_LANGUAGE = "en"; export const DEFAULT_WEB_PORT = 4567; export const DEFAULT_WEB_PORT_CONFLICT_BEHAVIOR = "fail"; export const DEFAULT_WEB_MAX_REQUEST_BODY_BYTES = 32 * 1024 * 1024; export const MAX_WEB_REQUEST_BODY_BYTES = 256 * 1024 * 1024; export const CURRENT_SCHEMA_VERSION = 1; export const webPortSchema = z.coerce.number().int().min(1).max(65535); export const webPortConflictBehaviorSchema = z.enum(["fail", "auto", "prompt"]); export const webMaxRequestBodyBytesSchema = z.coerce .number() .int() .min(1) .max(MAX_WEB_REQUEST_BODY_BYTES); /** Canonicalize metadata without applying locale behavior anywhere in Pony. */ export const projectLanguageSchema = z .string() .trim() .min(1, "Project language cannot be empty") .transform((language, context) => { try { const [canonicalLanguage] = Intl.getCanonicalLocales(language); if (canonicalLanguage) return canonicalLanguage; } catch { // The validation issue below gives callers a stable, domain-specific error. } context.addIssue({ code: "custom", message: `Invalid BCP 47 language tag "${language}"`, }); return z.NEVER; }); export const writeModeSchema = z.enum([ "working_tree", "commit", "commit_and_push", ]); export const inboxStatusSchema = z.enum(["open", "claimed", "closed"]); export const instructionsSchema = z .object({ type: z.literal("instructions") }) .strict(); export const taskTypeSchema = z.literal("task"); export const inboxMessageTypeSchema = z.literal("inbox_message"); export const docTypeSchema = z.enum([ "brief", "decision", "question", "reference", "note", ]); export const docStatusSchema = z.enum(["active", "resolved", "superseded"]); export const docVisibilitySchema = z.literal("shared"); export const inboxIdSchema = z .string() .regex(/^MSG-[0-9A-HJKMNP-TV-Z]{26}$/, "Expected MSG-"); export const taskIdSchema = z .string() .regex(/^TASK-\d{3,}$/, "Expected TASK-001 style ID"); export const docIdSchema = z .string() .regex(/^DOC-\d{3,}$/, "Expected DOC-001 style ID"); export const isoDateSchema = z.string().refine( (value) => { const parsed = Date.parse(value); return !Number.isNaN(parsed) && new Date(parsed).toISOString() === value; }, { message: "Expected an ISO 8601 UTC timestamp" }, ); export const configSchema = z.object({ schema_version: z.literal(CURRENT_SCHEMA_VERSION), project: z.object({ name: z.string().min(1), language: projectLanguageSchema, }), web: z.object({ port: webPortSchema, port_conflict: webPortConflictBehaviorSchema, max_request_body_bytes: webMaxRequestBodyBytesSchema, }), write: z.object({ mode: writeModeSchema, branch: z.string().min(1), commit_author: z.object({ name: z.string().min(1), email: z.string().min(1), }), }), tasks: z.object({ statuses: z.array(z.string().min(1)).min(1), priority_model: z.literal(TASK_PRIORITY_MODEL).nullable(), }), }); export const referencesSchema = z.object({ inbox: z.array(inboxIdSchema).default([]), tasks: z.array(taskIdSchema).default([]), docs: z.array(docIdSchema).default([]), }); export const inboxAttachmentSchema = z.object({ name: z.string().min(1), path: z .string() .regex( /^MSG-[0-9A-HJKMNP-TV-Z]{26}\.attachments\/[^/]+$/, "Expected a message-scoped attachment path", ), media_type: z.string().min(1), size: z.number().int().min(0), sha256: z.string().regex(/^[a-f0-9]{64}$/, "Expected a SHA-256 digest"), }); /** * Inbox records intentionally reject unknown fields so the titleless format is * a visible breaking change instead of silently accepting legacy `title` data. */ export const inboxMessageSchema = z .object({ id: inboxIdSchema, type: inboxMessageTypeSchema, status: inboxStatusSchema, author_name: z.string().min(1), author_email: z.email(), created_at: isoDateSchema, updated_at: isoDateSchema, claimed_by: z.string().min(1).nullable(), claimed_at: isoDateSchema.nullable(), references: z.object({ tasks: z.array(taskIdSchema), docs: z.array(docIdSchema), }), attachments: z.array(inboxAttachmentSchema), }) .strict() .superRefine((message, context) => { message.attachments.forEach((attachment, index) => { if (!attachment.path.startsWith(`${message.id}.attachments/`)) { context.addIssue({ code: "custom", message: "Attachment paths must belong to their inbox message", path: ["attachments", index, "path"], }); } }); }); export const taskSchema = z.object({ id: taskIdSchema, type: taskTypeSchema, title: z.string().min(1), status: z.string().min(1), priority: z.string().min(1).nullable(), assignee: z.string().min(1).nullable(), created_at: isoDateSchema, updated_at: isoDateSchema, references: z.object({ inbox: z.array(inboxIdSchema), docs: z.array(docIdSchema), }), }); export const docSchema = z.object({ id: docIdSchema, type: docTypeSchema, title: z.string().min(1), status: docStatusSchema, visibility: docVisibilitySchema, created_at: isoDateSchema, updated_at: isoDateSchema, superseded_by: docIdSchema.nullable(), }); export type PonyConfig = z.infer; export type WebPortConflictBehavior = z.infer< typeof webPortConflictBehaviorSchema >; export type WriteMode = z.infer; export type InboxStatus = z.infer; export type Instructions = z.infer; export type InboxMessage = z.infer; export type InboxAttachment = z.infer; export type Task = z.infer; export type Doc = z.infer; export type DocType = z.infer; export type DocStatus = z.infer; export function createDefaultConfig( projectName: string, projectLanguage = DEFAULT_PROJECT_LANGUAGE, ): PonyConfig { return { schema_version: CURRENT_SCHEMA_VERSION, project: { name: projectName, language: projectLanguageSchema.parse(projectLanguage), }, web: { port: DEFAULT_WEB_PORT, port_conflict: DEFAULT_WEB_PORT_CONFLICT_BEHAVIOR, max_request_body_bytes: DEFAULT_WEB_MAX_REQUEST_BODY_BYTES, }, write: { mode: "working_tree", branch: "current", commit_author: { name: "Pony Inbox", email: "inbox@example.invalid", }, }, tasks: { statuses: [...DEFAULT_TASK_STATUSES], priority_model: TASK_PRIORITY_MODEL, }, }; } function asConfigObject(value: unknown): Record { return typeof value === "object" && value !== null ? (value as Record) : {}; } function normalizeConfiguredTaskStatuses(configuredStatuses: unknown): unknown { // Add triage only to Pony's exact pre-triage default. Keep its legacy todo // status until the project explicitly migrates so loading never hides tasks. const isPreTriageDefault = Array.isArray(configuredStatuses) && configuredStatuses.length === PRE_TRIAGE_DEFAULT_TASK_STATUSES.length && configuredStatuses.every( (status, index) => status === PRE_TRIAGE_DEFAULT_TASK_STATUSES[index], ); return isPreTriageDefault ? [...LEGACY_DEFAULT_TASK_STATUSES] : configuredStatuses; } function supportedSchemaVersion(rawVersion: unknown): number { // Configs created before schema versioning already use the v1 shape. Treat // only a missing version as legacy; explicit unknown versions must fail. const version = rawVersion ?? CURRENT_SCHEMA_VERSION; if (version !== CURRENT_SCHEMA_VERSION) { throw new Error( `Unsupported Pony config schema version ${String(version)}; this Pony version supports schema version ${CURRENT_SCHEMA_VERSION}.`, ); } return CURRENT_SCHEMA_VERSION; } function writeOverridesFromEnvironment( env: NodeJS.ProcessEnv, ): Partial { return { ...(env.PONY_WRITE_MODE ? { mode: writeModeSchema.parse(env.PONY_WRITE_MODE) } : {}), ...(env.PONY_WRITE_BRANCH ? { branch: env.PONY_WRITE_BRANCH } : {}), }; } export function normalizeConfig( rawConfig: unknown, projectName: string, env: NodeJS.ProcessEnv = process.env, ): PonyConfig { const raw = asConfigObject(rawConfig); const rawProject = asConfigObject(raw.project); const rawWeb = asConfigObject(raw.web); const rawWrite = asConfigObject(raw.write); const rawTasks = asConfigObject(raw.tasks); const normalizedStatuses = normalizeConfiguredTaskStatuses(rawTasks.statuses); const defaults = createDefaultConfig(projectName); const schemaVersion = supportedSchemaVersion(raw.schema_version); const candidate = { ...defaults, ...raw, schema_version: schemaVersion, project: { ...defaults.project, ...rawProject, language: rawProject.language ?? DEFAULT_PROJECT_LANGUAGE, }, web: { ...defaults.web, ...rawWeb, }, write: { ...defaults.write, ...rawWrite, ...writeOverridesFromEnvironment(env), }, tasks: { ...defaults.tasks, ...rawTasks, priority_model: Object.hasOwn(rawTasks, "priority_model") ? rawTasks.priority_model : null, ...(normalizedStatuses === undefined ? {} : { statuses: normalizedStatuses }), }, }; return configSchema.parse(candidate); }