// The output contract (docs/SPEC.md → Output contract): schema, checks and hard rules. import { readFileSync, existsSync, statSync } from 'node:fs'; import path from 'node:path'; export const MAX_TEXT = 80; const evidence = { type: 'object', properties: { type: { type: 'string', enum: ['file', 'pipeline', 'rubric'] }, path: { type: ['string', 'null'] }, line: { type: ['integer', 'null'] }, job_id: { type: ['integer', 'null'] }, rule_id: { type: ['string', 'null'] }, }, required: ['type', 'path', 'line', 'job_id', 'rule_id'], additionalProperties: false, }; const evidenceList = { type: 'array', items: evidence, minItems: 1 }; export const verdictSchema = { type: 'object', properties: { verdict: { type: 'string', enum: ['go', 'no_go', 'waiting'] }, reason: { type: 'string' }, findings: { type: 'array', items: { type: 'object', properties: { kind: { type: 'string', enum: ['bad', 'ok', 'todo'] }, text: { type: 'string' }, evidence: evidenceList, }, required: ['kind', 'text', 'evidence'], additionalProperties: false, }, }, post_deploy: { type: 'array', items: { type: 'object', properties: { text: { type: 'string' }, evidence: evidenceList }, required: ['text', 'evidence'], additionalProperties: false, }, }, }, required: ['verdict', 'reason', 'findings', 'post_deploy'], additionalProperties: false, }; export type Evidence = { type: 'file' | 'pipeline' | 'rubric'; path: string | null; line: number | null; job_id: number | null; rule_id: string | null }; export type Finding = { kind: 'bad' | 'ok' | 'todo'; text: string; evidence: Evidence[] }; export type Verdict = { verdict: 'go' | 'no_go' | 'waiting'; reason: string; findings: Finding[]; post_deploy: Array<{ text: string; evidence: Evidence[] }> }; export type ResolvedEvidence = Evidence & { label: string; url: string }; export type Checked = { verdict: Verdict['verdict']; reason: string; findings: Array<{ kind: Finding['kind']; text: string; evidence: ResolvedEvidence[] }>; postDeploy: Array<{ text: string; evidence: ResolvedEvidence[] }>; dropped: string[]; overrides: string[]; }; export type Context = { repoDir: string; blobBase: string; sha: string; rubricIds: Set; rubricUrl: (id: string) => string; pipeline: { status: string } | null; pipelineIds: number[]; loadJob: (id: number) => Promise<{ pipelineId: number; name: string; webUrl: string } | null>; }; export function rubricIds(markdown: string): Set { return new Set([...markdown.matchAll(/^## (R\d+)\b/gm)].map((m) => m[1])); } // Shape problems are the model's mistake: they are sent back once for a retry. export function shapeErrors(raw: string): { value: Verdict | null; errors: string[] } { let v: any; try { v = JSON.parse(raw); } catch { return { value: null, errors: ['The answer is not valid JSON.'] }; } const errors: string[] = []; if (!['go', 'no_go', 'waiting'].includes(v?.verdict)) errors.push('verdict must be go, no_go or waiting.'); if (typeof v?.reason !== 'string' || !v.reason.trim()) errors.push('reason is missing.'); else if (v.reason.length > MAX_TEXT) errors.push(`reason is ${v.reason.length} characters; the limit is ${MAX_TEXT}.`); if (!Array.isArray(v?.findings)) errors.push('findings must be a list.'); if (!Array.isArray(v?.post_deploy)) errors.push('post_deploy must be a list.'); const items = [...(v?.findings ?? []).map((f: any, i: number) => [`findings[${i}]`, f]), ...(v?.post_deploy ?? []).map((f: any, i: number) => [`post_deploy[${i}]`, f])]; for (const [where, f] of items) { if (typeof f?.text !== 'string' || !f.text.trim()) errors.push(`${where}.text is missing.`); else if (f.text.length > MAX_TEXT) errors.push(`${where}.text is ${f.text.length} characters; the limit is ${MAX_TEXT}.`); if (!Array.isArray(f?.evidence) || f.evidence.length === 0) errors.push(`${where} has no evidence.`); for (const [j, e] of (f?.evidence ?? []).entries()) { if (e?.type === 'file' && (!e.path || !Number.isInteger(e.line))) errors.push(`${where}.evidence[${j}] of type file needs path and line.`); if (e?.type === 'pipeline' && !Number.isInteger(e.job_id)) errors.push(`${where}.evidence[${j}] of type pipeline needs job_id.`); if (e?.type === 'rubric' && !e.rule_id) errors.push(`${where}.evidence[${j}] of type rubric needs rule_id.`); } } if (v?.verdict === 'go' && (v.findings ?? []).some((f: any) => f?.kind === 'bad')) errors.push('verdict is go but a finding is bad.'); if (v?.verdict === 'no_go' && !(v.findings ?? []).some((f: any) => f?.kind === 'bad')) errors.push('verdict is no_go but no finding is bad.'); return { value: errors.length ? null : (v as Verdict), errors }; } async function resolveOne(e: Evidence, ctx: Context): Promise { if (e.type === 'file') { const rel = e.path!.replace(/^\/+/, ''); const abs = path.resolve(ctx.repoDir, rel); if (!abs.startsWith(path.resolve(ctx.repoDir) + path.sep) || !existsSync(abs) || !statSync(abs).isFile()) return `file ${rel} does not exist at ${ctx.sha.slice(0, 8)}`; const lines = readFileSync(abs, 'utf8').split('\n').length; if (e.line! < 1 || e.line! > lines) return `${rel}:${e.line} is outside the file (${lines} lines)`; return { ...e, path: rel, label: `${rel}:${e.line}`, url: `${ctx.blobBase}/${rel}#L${e.line}` }; } if (e.type === 'pipeline') { const job = await ctx.loadJob(e.job_id!); if (!job || !ctx.pipelineIds.includes(job.pipelineId)) return `job ${e.job_id} is not part of this MR's pipelines`; return { ...e, label: `job ${job.name}`, url: job.webUrl }; } if (!ctx.rubricIds.has(e.rule_id!)) return `rubric rule ${e.rule_id} does not exist`; return { ...e, label: `rubric ${e.rule_id}`, url: ctx.rubricUrl(e.rule_id!) }; } // Evidence that does not resolve is never shown. A bad or todo finding without any valid // evidence is a model error (retry); an ok finding without it is dropped. export async function check(v: Verdict, ctx: Context): Promise<{ checked: Checked | null; errors: string[] }> { const errors: string[] = []; const dropped: string[] = []; const findings: Checked['findings'] = []; for (const [i, f] of v.findings.entries()) { const resolved = await Promise.all(f.evidence.map((e) => resolveOne(e, ctx))); const good = resolved.filter((r): r is ResolvedEvidence => typeof r !== 'string'); const bad = resolved.filter((r): r is string => typeof r === 'string'); if (good.length === 0) { if (f.kind === 'ok') dropped.push(`"${f.text}" (${bad.join('; ')})`); else errors.push(`findings[${i}] "${f.text}": ${bad.join('; ')}`); continue; } findings.push({ kind: f.kind, text: f.text, evidence: good }); } const postDeploy: Checked['postDeploy'] = []; for (const [i, p] of v.post_deploy.entries()) { const resolved = await Promise.all(p.evidence.map((e) => resolveOne(e, ctx))); const good = resolved.filter((r): r is ResolvedEvidence => typeof r !== 'string'); if (good.length === 0) errors.push(`post_deploy[${i}] "${p.text}": ${resolved.join('; ')}`); else postDeploy.push({ text: p.text, evidence: good }); } if (errors.length) return { checked: null, errors }; // Hard rules: decided by code, never by the model. const overrides: string[] = []; let verdict = v.verdict; let reason = v.reason; if (verdict === 'go' && ctx.pipeline && ctx.pipeline.status !== 'success') { verdict = 'waiting'; reason = 'Nunggu pipeline hijau.'; overrides.push(`go → waiting: pipeline is ${ctx.pipeline.status}`); } return { checked: { verdict, reason, findings, postDeploy, dropped, overrides }, errors: [] }; }