import { parseDocument } from "yaml"; import { JobGraph } from "./job-graph.ts"; import { AGENT_TIMEOUT_MINUTES, BUILT_IN_IMAGES, DEFAULT_SIZE, DEFAULT_TIMEOUT_MINUTES, INSTANCE_SIZES, MAX_TIMEOUT_MINUTES, type BranchFilter, type BuiltInImage, type CacheSpec, type ConfigProblem, type ImageRef, type InstanceSize, type Job, type ParseResult, type Step, type Triggers, } from "./pipeline.ts"; export const CONFIG_PATH = ".refs/ci.yml"; export const MAX_CONFIG_BYTES = 64 * 1024; export const MAX_JOBS = 64; export const MAX_STEPS = 100; const NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/i; const IMAGE = /^(?:refs\/)?([a-z0-9][a-z0-9-]{0,63})(?:@(\d{4}-\d{2}))?$/; const STEP_NAME_LENGTH = 80; export const SECRET_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/; const ROOT_KEYS = new Set(["on", "jobs"]); const TRIGGER_KEYS = new Set(["push", "pull_request", "manual"]); const FILTER_KEYS = new Set(["branches"]); const JOB_KEYS = new Set(["image", "size", "needs", "steps", "environment", "timeout_minutes", "cache", "artifacts", "secrets", "agent", "prompt"]); const AGENT_JOB_KEYS = new Set(["agent", "prompt", "needs", "timeout_minutes"]); const AGENT_HANDLE = /^[a-z][a-z0-9-]{1,31}$/; const MAX_PROMPT = 4000; const STEP_KEYS = new Set(["name", "run"]); const CACHE_KEYS = new Set(["key", "paths"]); const DEFAULT_TRIGGERS: Triggers = { push: { branches: [] }, pullRequest: { branches: [] }, manual: true }; /** Reads `.refs/ci.yml`. Returns every problem it finds, with the path of the field, instead of stopping at the first. */ export function parsePipeline(text: string): ParseResult { if (new TextEncoder().encode(text).length > MAX_CONFIG_BYTES) return invalid([{ path: "", message: `The file is larger than ${MAX_CONFIG_BYTES / 1024} KB.` }]); const document = parseDocument(text, { uniqueKeys: true }); if (document.errors.length) return invalid(document.errors.map((error) => ({ path: "", message: error.message }))); const reader = new Reader(); const root: unknown = document.toJS({ maxAliasCount: 16 }); if (!isRecord(root)) return invalid([{ path: "", message: "The file must be a mapping with a jobs key." }]); reader.keys(root, "", ROOT_KEYS); const triggers = root.on === undefined ? DEFAULT_TRIGGERS : reader.triggers(root.on, "on"); const jobs = reader.jobs(root.jobs, "jobs"); if (reader.problems.length || !triggers) return invalid(reader.problems); const checked = JobGraph.check(jobs); if ("problems" in checked) return invalid(checked.problems); return { kind: "valid", pipeline: { triggers, jobs } }; } function invalid(problems: readonly ConfigProblem[]): ParseResult { return { kind: "invalid", problems }; } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } function isBuiltIn(name: string): name is BuiltInImage { return BUILT_IN_IMAGES.some((image) => image === name); } function isSize(value: unknown): value is InstanceSize { return INSTANCE_SIZES.some((size) => size === value); } class Reader { readonly problems: ConfigProblem[] = []; fail(path: string, message: string): null { this.problems.push({ path, message }); return null; } keys(value: Record, path: string, allowed: ReadonlySet): void { for (const key of Object.keys(value)) if (!allowed.has(key)) this.fail(path ? `${path}.${key}` : key, `Unknown key "${key}".`); } string(value: unknown, path: string): string | null { if (typeof value === "string" && value.trim()) return value; return this.fail(path, "Must be a non-empty string."); } strings(value: unknown, path: string): string[] | null { if (typeof value === "string") return this.string(value, path) === null ? null : [value]; if (!Array.isArray(value)) return this.fail(path, "Must be a string or a list of strings."); const read = value.map((item, index) => this.string(item, `${path}[${index}]`)); return read.every((item) => item !== null) ? read : null; } triggers(value: unknown, path: string): Triggers | null { if (!isRecord(value)) return this.fail(path, "Must be a mapping of push, pull_request and manual."); this.keys(value, path, TRIGGER_KEYS); const manual = value.manual; if (manual !== undefined && manual !== null && manual !== true && !(isRecord(manual) && !Object.keys(manual).length)) this.fail(`${path}.manual`, "Must be empty or true."); return { push: "push" in value ? this.filter(value.push, `${path}.push`) : null, pullRequest: "pull_request" in value ? this.filter(value.pull_request, `${path}.pull_request`) : null, manual: "manual" in value, }; } filter(value: unknown, path: string): BranchFilter | null { if (value === null || value === undefined) return { branches: [] }; if (!isRecord(value)) return this.fail(path, "Must be empty or a mapping with branches."); this.keys(value, path, FILTER_KEYS); if (value.branches === undefined) return { branches: [] }; const branches = this.strings(value.branches, `${path}.branches`); return branches && { branches }; } jobs(value: unknown, path: string): Map { const jobs = new Map(); if (!isRecord(value) || !Object.keys(value).length) { this.fail(path, "Must be a mapping with at least one job."); return jobs; } const names = Object.keys(value); if (names.length > MAX_JOBS) this.fail(path, `A pipeline can have at most ${MAX_JOBS} jobs.`); for (const name of names.slice(0, MAX_JOBS)) { if (!NAME.test(name)) { this.fail(`${path}.${name}`, "A job name uses letters, digits, - and _, and is at most 64 characters."); continue; } const job = this.job(name, value[name], `${path}.${name}`); if (job) jobs.set(name, job); } return jobs; } job(name: string, value: unknown, path: string): Job | null { if (!isRecord(value)) return this.fail(path, "Must be a mapping with steps."); const before = this.problems.length; if (value.agent !== undefined) return this.agentJob(name, value, path); if (value.prompt !== undefined) this.fail(`${path}.prompt`, "Only an agent job takes a prompt. Add agent, or remove prompt."); this.keys(value, path, JOB_KEYS); const image = value.image === undefined ? { kind: "built-in" as const, name: "base" as const, version: null } : this.image(value.image, `${path}.image`); const size = value.size === undefined ? DEFAULT_SIZE : isSize(value.size) ? value.size : this.fail(`${path}.size`, `Must be one of ${INSTANCE_SIZES.join(", ")}.`); const needs = value.needs === undefined ? [] : this.strings(value.needs, `${path}.needs`); const steps = this.steps(value.steps, `${path}.steps`); const environment = value.environment === undefined ? null : this.environment(value.environment, `${path}.environment`); const timeoutMinutes = value.timeout_minutes === undefined ? DEFAULT_TIMEOUT_MINUTES : this.timeout(value.timeout_minutes, `${path}.timeout_minutes`); const cache = value.cache === undefined ? null : this.cache(value.cache, `${path}.cache`); const artifacts = value.artifacts === undefined ? [] : this.strings(value.artifacts, `${path}.artifacts`); const secrets = value.secrets === undefined ? [] : this.secretNames(value.secrets, `${path}.secrets`); if (this.problems.length > before || !image || !size || !needs || !steps || timeoutMinutes === null || !artifacts || !secrets) return null; return { name, agent: null, image, size, needs, steps, environment, timeoutMinutes, cache, artifacts, secrets }; } /** A job that runs a hosted agent. It has no container, so it takes no image, size, steps, environment or secrets. */ agentJob(name: string, value: Record, path: string): Job | null { const before = this.problems.length; for (const key of Object.keys(value)) if (!AGENT_JOB_KEYS.has(key)) this.fail(`${path}.${key}`, "An agent job takes only agent, prompt, needs and timeout_minutes."); const handle = typeof value.agent === "string" ? value.agent.replace(/^@/, "") : ""; if (!AGENT_HANDLE.test(handle)) this.fail(`${path}.agent`, "Must be the handle of a hosted agent, such as reviewer."); const prompt = value.prompt === undefined ? "" : this.string(value.prompt, `${path}.prompt`); if (prompt && prompt.length > MAX_PROMPT) this.fail(`${path}.prompt`, `A prompt is at most ${MAX_PROMPT} characters.`); const needs = value.needs === undefined ? [] : this.strings(value.needs, `${path}.needs`); const timeoutMinutes = value.timeout_minutes === undefined ? AGENT_TIMEOUT_MINUTES : this.timeout(value.timeout_minutes, `${path}.timeout_minutes`); if (this.problems.length > before || prompt === null || !needs || timeoutMinutes === null) return null; const step = { name: `@${handle}`, run: prompt || `@${handle} follows its own instructions.` }; return { name, agent: { handle, prompt }, image: { kind: "built-in", name: "base", version: null }, size: DEFAULT_SIZE, needs, steps: [step], environment: null, timeoutMinutes, cache: null, artifacts: [], secrets: [] }; } image(value: unknown, path: string): ImageRef | null { const match = typeof value === "string" ? IMAGE.exec(value) : null; if (!match) return this.fail(path, "Must be an image name such as node or rust@2026-12."); const [, name, version] = match; if (isBuiltIn(name)) return { kind: "built-in", name, version: version ?? null }; if (version) return this.fail(path, "Only built-in images have dated versions."); if (typeof value === "string" && value.startsWith("refs/")) return this.fail(path, `There is no built-in image named "${name}".`); return this.fail(path, `There is no image named "${name}". Use one of ${BUILT_IN_IMAGES.join(", ")}.`); } secretNames(value: unknown, path: string): string[] | null { const names = this.strings(value, path); if (!names) return null; const bad = names.find((name) => !SECRET_NAME.test(name)); return bad === undefined ? names : this.fail(path, `"${bad}" is not a secret name. Use capital letters, digits and _, and do not start with a digit.`); } steps(value: unknown, path: string): Step[] | null { if (!Array.isArray(value) || !value.length) return this.fail(path, "Must be a list with at least one step."); if (value.length > MAX_STEPS) return this.fail(path, `A job can have at most ${MAX_STEPS} steps.`); const steps = value.map((item, index) => this.step(item, `${path}[${index}]`)); return steps.every((step) => step !== null) ? steps : null; } step(value: unknown, path: string): Step | null { if (typeof value === "string") return value.trim() ? { name: stepName(value), run: value } : this.fail(path, "A step cannot be empty."); if (!isRecord(value)) return this.fail(path, "Must be a command or a mapping with run."); this.keys(value, path, STEP_KEYS); const run = this.string(value.run, `${path}.run`); const name = value.name === undefined ? null : this.string(value.name, `${path}.name`); if (!run || (value.name !== undefined && !name)) return null; return { name: name ?? stepName(run), run }; } environment(value: unknown, path: string): string | null { if (typeof value === "string" && NAME.test(value)) return value; return this.fail(path, "An environment name uses letters, digits, - and _."); } timeout(value: unknown, path: string): number | null { if (Number.isInteger(value) && typeof value === "number" && value >= 1 && value <= MAX_TIMEOUT_MINUTES) return value; return this.fail(path, `Must be a whole number of minutes from 1 to ${MAX_TIMEOUT_MINUTES}.`); } cache(value: unknown, path: string): CacheSpec | null { if (!isRecord(value)) return this.fail(path, "Must be a mapping with key and paths."); this.keys(value, path, CACHE_KEYS); const key = this.string(value.key, `${path}.key`); const paths = this.strings(value.paths, `${path}.paths`); return key && paths ? { key, paths } : null; } } function stepName(run: string): string { const line = run.trim().split("\n")[0].trim(); return line.length > STEP_NAME_LENGTH ? `${line.slice(0, STEP_NAME_LENGTH - 1)}…` : line; }