/** * Shared helpers for decision ladders: many small `noul` questions asked in * one model call, combined in code. Rules are checked top to bottom; the first * question whose probability clears `threshold` decides. Jev and Clef answer * in one pass without reasoning, so the logic lives here, not in the prompt. */ export type NoulQuestion = { type: 'noul' instructions: string criteria: { true: string; false: string } } export type LadderRule = { /** Question key in the request's `questions` map. */ key: string /** Outcome when this question clears the threshold. */ outcome: T question: NoulQuestion /** Probability this rule needs to decide (default LADDER_THRESHOLD). */ threshold?: number } export type LadderDecision = { value: T confidence: number /** Question key that decided, or `default`. */ decidedBy: string } /** Answers clear a rule at this probability. */ export const LADDER_THRESHOLD = 0.5 export function ladderQuestions(rules: ReadonlyArray>): Record { const out: Record = {} for (const rule of rules) out[rule.key] = rule.question return out } function asRecord(v: unknown): Record | null { return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : null } /** Find `answers` in direct, `{ result }`, or `{ response }` envelopes. */ export function findAnswers(data: unknown): Record | null { let node = asRecord(data) for (let depth = 0; node && depth < 4; depth += 1) { const a = asRecord(node.answers) if (a) return a node = asRecord(node.result) ?? asRecord(node.response) } return null } function noulOf(answer: unknown): number | null { const a = asRecord(answer) const p = a?.noul ?? a?.probability return typeof p === 'number' && Number.isFinite(p) && p >= 0 && p <= 1.0001 ? Math.min(1, p) : null } /** * Walk the ladder. Returns null when any rule's answer is missing or * malformed, so callers keep their existing "model returned nothing" path. * Confidence is P(yes) of the deciding rule, or for the default, the lowest * P(no) across all rules. */ export function decideLadder( answers: Record | null, rules: ReadonlyArray>, fallback: T, threshold = LADDER_THRESHOLD, ): LadderDecision | null { if (!answers) return null const probs: number[] = [] for (const rule of rules) { const p = noulOf(answers[rule.key]) if (p === null) return null probs.push(p) } for (let i = 0; i < rules.length; i += 1) { if (probs[i]! >= (rules[i]!.threshold ?? threshold)) { return { value: rules[i]!.outcome, confidence: round(probs[i]!), decidedBy: rules[i]!.key } } } const confidence = probs.length ? Math.min(...probs.map((p) => 1 - p)) : 1 return { value: fallback, confidence: round(confidence), decidedBy: 'default' } } function round(n: number) { return Math.round(n * 1000) / 1000 }