import { z } from "zod/v4"; import { digestForModel, type Digest } from "./digest.ts"; import type { AnalystConfig } from "./settings.ts"; export class AnalystError extends Error {} const Action = z.object({ title: z.string().min(3), detail: z.string().min(3), effort: z.enum(["low", "medium", "high"]), requires_change_control: z.boolean() }); const RawCandidate = z.object({ key: z.string().min(2), title: z.string().min(3), diagnosis: z.string().min(15), actions: z.array(Action).min(1), rewrite_sql: z.string().nullable(), expected: z.string().min(5) }); const Proposal = z.object({ candidates: z.array(RawCandidate).min(2).max(4) }); export type Action = z.infer; export type Candidate = z.infer; export const CANDIDATE_SYSTEM_PROMPT = `You are a SQL Server performance engineer. You receive a JSON digest of one execution plan. Judge only what the digest contains — never invent operators, waits, or row counts you were not given. Return 2 to 4 genuinely different remediation options, not one option restated. Real differences: an index change, a rewritten query, a statistics or parallelism fix, a batching or schema change. At least one option must be the lowest-risk one. Each option needs a snake_case key, a diagnosis naming WHY the plan is slow, 1-4 ordered actions, an optional rewritten query, and an expected effect stated as a concrete claim about the plan (logical reads, seek vs scan, tempdb spill, degree of parallelism). A rewrite must return the same rows as the original. If you cannot rewrite safely, set rewrite_sql to null. Output ONE JSON object and nothing else: {"candidates":[{"key":"idx_covering_orders","title":"...","diagnosis":"...","actions":[{"title":"...","detail":"...", "effort":"low|medium|high","requires_change_control":false}],"rewrite_sql":null,"expected":"..."}]}`; export function extractJson(text: string): unknown { const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text); const s = (fenced ? fenced[1] : text).trim(); const start = s.indexOf("{"); const end = s.lastIndexOf("}"); if (start === -1 || end <= start) throw new AnalystError("The analyst model returned prose instead of JSON."); try { return JSON.parse(s.slice(start, end + 1)); } catch { throw new AnalystError("The analyst model returned malformed JSON."); } } export async function proposeCandidates(cfg: AnalystConfig, digest: Digest, note: string, fetchImpl: typeof fetch = fetch): Promise { const res = await fetchImpl(`${cfg.baseUrl}/chat/completions`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${cfg.apiKey}` }, body: JSON.stringify({ model: cfg.model, temperature: 0.6, ...cfg.extra, stream: false, messages: [{ role: "system", content: CANDIDATE_SYSTEM_PROMPT }, { role: "user", content: JSON.stringify({ digest: digestForModel(digest), user_note: note || null }) }] }), }).catch((e) => { throw new AnalystError(`Could not reach ${cfg.baseUrl}: ${(e as Error).message}`); }); if (!res.ok) throw new AnalystError(`Analyst model returned HTTP ${res.status}. ${(await res.text()).slice(0, 300)}`); const content: string = ((await res.json() as any)?.choices?.[0]?.message?.content) ?? ""; const parsed = Proposal.safeParse(extractJson(content)); if (!parsed.success) { const n = (extractJson(content) as any)?.candidates?.length ?? 0; throw new AnalystError(n < 2 ? `The analyst model proposed ${n} option(s); at least 2 are needed before Jev can rank anything.` : `Analyst output did not match the schema at ${parsed.error.issues[0].path.join(".")}: ${parsed.error.issues[0].message}`); } return parsed.data.candidates; }