import type { MetricLink, MetricNode } from '../data/sqlite'; import { queryProductLines, queryRegions, queryRisks, queryTrend } from '../data/sqlite'; import { achieveRate, fmt, fmtSigned, gapOf } from './metric'; import type { ParsedAsk } from './intent'; /** * 结构化回答引擎:消费 intent.ts 的解析结果,查询 SQL 数据层, * 产出对齐设计书 5.3 五段式(结论 + 迷你图 + 分点 + 行动 + 来源)的 AiReply。 * 全部计算离线完成:外推用最小二乘、传播用网络边强度、归因用偏差×权重贡献分解。 */ export interface AiSpark { /** 折线值:历史 12 期(+ 假设/外推段) */ values: number[]; /** values 末尾多少点属于外推(虚线渲染) */ forecastCount?: number; /** 目标参考虚线 */ target?: number; unit: string; } export interface AiPoint { label?: string; text: string; tone?: 'good' | 'warn' | 'bad' } export interface AiAction { label: string; /** 跳转到指标(联动左侧树与中央看板) */ code?: string; /** 以该问句继续追问 */ ask?: string; } export interface AiReply { /** 核心结论:1-2 句,直接回答问句 */ conclusion: string; spark?: AiSpark; /** 分点详细分析 */ points: AiPoint[]; /** 建议行动(可点击) */ actions: AiAction[]; /** 数据来源标注:数据域 + 更新频率 + 权限 */ source: string; /** 回答聚焦的指标,用于行动按钮联动 */ focusCode?: string; } export interface AnswerCtx { flat: MetricNode[]; byCode: Map; links: MetricLink[]; /** 全局时间游标:历史序列截断到该期,结论文字与迷你图同口径(节点值已由 App 层投影) */ period: number; } const label = (n: MetricNode) => n.name_zh; const unitOf = (n: MetricNode) => n.unit; const SRC_METRIC = '指标中台(metric_node / metric_trend / metric_link)· 月度更新 · 内部可见'; const SRC_BIZ = '经营分析(product_line / region_data / risk_matrix)· 季度更新 · 内部可见'; /** 最小二乘线性回归:返回斜率与外推函数 */ function linreg(ys: number[]) { const n = ys.length; if (n < 2) return { slope: 0, at: (_i: number) => ys[0] ?? 0 }; const mx = (n - 1) / 2; const my = ys.reduce((a, b) => a + b, 0) / n; let num = 0, den = 0; for (let i = 0; i < n; i++) { num += (i - mx) * (ys[i] - my); den += (i - mx) ** 2; } const slope = den ? num / den : 0; return { slope, at: (i: number) => my + slope * (i - mx) }; } /** 游标前的历史序列(含游标当期):回答不会把“未来月份”当成已经历的实绩 */ const trendOf = (code: string, period: number): number[] => queryTrend(code).map(p => p.actual).slice(0, Math.max(2, period + 1)); /** 游标口径的红黄绿计数:ctx.flat 已由 App 投影,直接按定级字段统计即得该时点分布 */ const countAlerts = (ctx: AnswerCtx) => { let red = 0, yellow = 0, green = 0; ctx.flat.forEach(n => { if (n.level < 2) return; if (n.alert_level === 'red') red++; else if (n.alert_level === 'yellow') yellow++; else green++; }); return { red, yellow, green, total: ctx.flat.length }; }; /** 偏差 / 变化量单位:% 类指标用百分点 pt(与目标值本身的 % 区分口径),其余按语言取单位 */ const gapUnit = (n: MetricNode) => (n.unit === '%' ? 'pt' : n.unit); /* ── 各意图引擎 ─────────────────────────────────────────────────────────── */ /** 指标查询:当期值 / 目标 / 偏差 / 达成率 + 趋势 + 最大拖累 */ function answerQuery(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const n = ctx.byCode.get(parsed.metricCode!)!; const gap = gapOf(n); const rate = achieveRate(n); const trend = trendOf(n.code, ctx.period); const last3 = trend.slice(-3); const good = gap >= 0; const kids = ctx.flat .filter(k => k.parent_code === n.code) .sort((a, b) => Math.abs(gapOf(b)) - Math.abs(gapOf(a))); const worst = kids.find(k => gapOf(k) < 0); const mom = last3.length >= 2 ? last3[2] - last3[0] : 0; const conclusion = `「${label(n)}」当期 ${fmt(n.value)}${unitOf(n)},目标 ${fmt(n.target)}${unitOf(n)}(偏差 ${fmtSigned(gap)}${gapUnit(n)}),达成率 ${fmt(rate, 0)}%,${good ? '处于达标线以上。' : '尚未达标。'}`; return { conclusion, spark: { values: trend, target: n.target, unit: unitOf(n) }, focusCode: n.code, points: [ { label: '责任部门', text: `${n.owner} · ${n.frequency}更新` }, { label: '近 3 期', text: `${last3.map(v => fmt(v)).join(' → ')}${unitOf(n)}(${mom >= 0 ? ('改善基调') : ('走弱')})`, tone: mom >= 0 ? 'good' : 'warn' }, worst && { label: '最大拖累', text: `下层「${label(worst)}」偏差最大(${fmtSigned(gapOf(worst))}${gapUnit(worst)})`, tone: 'bad', }, { label: '指标说明', text: n.desc_zh}, ].filter(Boolean) as AiPoint[], actions: [ { label: `查看「${label(n)}」归因`, code: n.code, ask: `${n.name_zh}为什么低于目标`}, { label: '趋势预测', ask: `预测${n.name_zh}下月走势`}, ], source: SRC_METRIC, }; } /** 归因分析:子因子偏差×权重贡献分解 + 跨树驱动边排序 */ function answerAttribute(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!; const gap = gapOf(n); const kids = ctx.flat.filter(k => k.parent_code === n.code); const contribs = kids .map(k => ({ node: k, contrib: +(gapOf(k) * k.weight).toFixed(2) })) .sort((a, b) => a.contrib - b.contrib); // 负贡献(拖累)优先 const totalNeg = contribs.filter(c => c.contrib < 0).reduce((a, b) => a + Math.abs(b.contrib), 0) || 1; const outsiders = ctx.links .filter(l => l.to_code === n.code && !kids.some(k => k.code === l.from_code)) .map(l => ({ link: l, node: ctx.byCode.get(l.from_code)! })) .filter(x => x.node) .sort((a, b) => Math.abs(b.link.strength) - Math.abs(a.link.strength)) .slice(0, 2); const top = contribs.slice(0, 3); const topStr = top .map(c => `${label(c.node)}(贡献 ${Math.round(Math.abs(c.contrib) / totalNeg * 100)}%)`) .join('、'); const conclusion = `「${label(n)}」偏差 ${fmtSigned(gap)}${gapUnit(n)} 的主因:${topStr}。属于结构性偏离,建议优先调整产品与供应结构,而非单纯压费用。`; return { conclusion, spark: { values: trendOf(n.code, ctx.period), target: n.target, unit: unitOf(n) }, focusCode: n.code, points: [ ...top.map(c => ({ label: label(c.node), text: `当期 ${fmt(c.node.value)}${unitOf(c.node)} / 目标 ${fmt(c.node.target)}${unitOf(c.node)}(${fmtSigned(gapOf(c.node))}${gapUnit(c.node)})· ${c.node.owner}`, tone: c.contrib < 0 ? 'bad' as const : 'good' as const, })), ...outsiders.map(x => ({ label: '跨树驱动', text: `「${label(x.node)}」→ 本指标(强度 ${x.link.strength},${x.link.relation === 'conflict' ? '负向制约' : '正向驱动'})`, })), ], actions: [ ...(top[0] ? [{ label: `打开主因「${label(top[0].node)}」`, code: top[0].node.code }] : []), ...(top[0] ? [{ label: `模拟改善路径`, ask: `如果${top[0].node.name_zh}提升到目标会怎样`}] : []), ], source: SRC_METRIC, }; } /** 趋势预测:最小二乘外推 3 期 + 达标判断(在手订单特例:收入支撑度) */ function answerForecast(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const n = ctx.byCode.get(parsed.metricCode ?? 'R01')!; const trend = trendOf(n.code, ctx.period); const { slope, at } = linreg(trend); /* 从游标往后外推三期(不是从 12 月末),历史越短回归越不稳定,因而标注样本期数 */ const h = trend.length; const ext = [at(h), at(h + 1), at(h + 2)].map(v => +v.toFixed(2)); const end = ext[2]; const endGap = n.polarity === 'down' ? -(end - n.target) : end - n.target; const willHit = endGap >= 0; let conclusion: string; const tail = `${fmt(trend[h - 1])} → ${fmt(ext[0])} → ${fmt(ext[2])}${unitOf(n)}`; if (n.code === 'R10') { const r1 = ctx.byCode.get('R01')!; const cover = +((n.value / (r1.value * 3) * 100)).toFixed(1); conclusion = `在手订单 ${fmt(n.value)}${unitOf(n)}约可覆盖未来 3 个月收入节奏(月均 ${fmt(r1.value)}${unitOf(r1)})的 ${fmt(cover, 0)}%,缺口需靠新签订单补齐。在手订单趋势:${tail}。`; } else { conclusion = `按游标前 ${h} 期线性趋势外推:「${label(n)}」下期 ${fmt(ext[0])}${unitOf(n)},3 期后 ${fmt(end)}${unitOf(n)}。对比目标 ${fmt(n.target)}${unitOf(n)},${willHit ? '有望达成' : `仍差 ${fmt(Math.abs(endGap))}${gapUnit(n)}`}。`; } const mom = slope; // 每期平均变化 return { conclusion, spark: { values: [...trend, ...ext], forecastCount: 3, target: n.target, unit: unitOf(n) }, focusCode: n.code, points: [ { label: '趋势斜率', text: `每期 ${fmtSigned(mom, 2)}${gapUnit(n)}(${h} 期回归斜率)`, tone: mom >= 0 ? 'good' : 'warn' }, { label: '近期动能', text: trend.slice(-3).map(v => fmt(v)).join(' → ') + unitOf(n) }, { label: '达标判定', text: willHit ? (`3 期外推终点回到目标线以上`) : (`当前节奏下缺口将持续,需要额外举措拉动`), tone: willHit ? 'good' : 'bad' }, ], actions: [ { label: `查看「${label(n)}」归因`, code: n.code, ask: `${n.name_zh}为什么低于目标`}, ], source: SRC_METRIC + (' ※线性回归外推'), }; } /** 假设模拟:假设值 → 相对变化率沿网络边强度传播(单位无关近似) */ function answerWhatIf(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!; const hasAbs = parsed.absValue !== undefined; const hasDelta = parsed.deltaValue !== undefined; if (!hasAbs && !hasDelta) { return { conclusion: `模拟需要给出假设数值。例如:「如果高毛利产品占比提升到 40% 会怎样」,指定指标与目标值即可推演。`, points: [], actions: [{ label: '试一个例子', ask: '如果高毛利产品占比提升到 40% 会怎样'}], source: SRC_METRIC, focusCode: n.code, }; } const newValue = hasAbs ? parsed.absValue! : +(n.value + parsed.deltaValue!).toFixed(2); const delta = +(newValue - n.value).toFixed(2); const relChange = n.value !== 0 ? delta / Math.abs(n.value) : 0; const outs = ctx.links .filter(l => l.from_code === n.code) .map(l => ({ link: l, node: ctx.byCode.get(l.to_code)! })) .filter(x => x.node) .sort((a, b) => Math.abs(b.link.strength) - Math.abs(a.link.strength)) .slice(0, 3); const selfGapNew = n.polarity === 'down' ? -(newValue - n.target) : newValue - n.target; const conclusion = `若「${label(n)}」从 ${fmt(n.value)}${unitOf(n)} 变为 ${fmt(newValue)}${unitOf(n)}(${fmtSigned(delta)}${gapUnit(n)}):${selfGapNew >= 0 ? '该指标将回到目标线以上' : '该指标仍低于目标'}。${outs.length ? `影响最大的下游是「${label(outs[0].node)}」。` : ''}`; return { conclusion, spark: { values: [...trendOf(n.code, ctx.period), newValue], forecastCount: 1, target: n.target, unit: unitOf(n) }, focusCode: n.code, points: [ { label: label(n), text: `对比目标 ${fmt(n.target)}${unitOf(n)}:${selfGapNew >= 0 ? '达标(偏差' : '未达标(缺口'}${fmtSigned(selfGapNew)}${gapUnit(n)})`, tone: selfGapNew >= 0 ? 'good' : 'warn', }, ...outs.map(x => { const impacted = +(x.node.value * (1 + x.link.strength * relChange)).toFixed(2); const chg = +(impacted - x.node.value).toFixed(2); return { label: label(x.node), text: `${fmt(x.node.value)} → ${fmt(impacted)}${unitOf(x.node)}(${fmtSigned(chg)}${gapUnit(x.node)},传播强度 ${x.link.strength})`, tone: chg >= 0 ? ('good' as const) : ('warn' as const), }; }), ], actions: [ { label: `打开「${label(n)}」`, code: n.code }, ...(outs[0] ? [{ label: `查看受影响的「${label(outs[0].node)}」`, code: outs[0].node.code }] : []), ], source: SRC_METRIC + (' ※按网络边强度线性传播近似'), }; } /** 对比分析:产品线 / 区域 */ function answerCompare(parsed: ParsedAsk, _ctx: AnswerCtx): AiReply { if (parsed.compareScope === 'region') { const regions = queryRegions(); const top = regions[0]; const weakMargin = [...regions].sort((a, b) => a.gross_margin - b.gross_margin)[0]; const bestPerCapita = [...regions].sort((a, b) => b.per_capita - a.per_capita)[0]; return { conclusion: `${top.name_zh}收入贡献最大(${fmt(top.revenue)} 亿元,占 ${fmt((top.revenue / regions.reduce((a, r) => a + r.revenue, 0)) * 100, 0)}%);人均产值以${bestPerCapita.name_zh}最高(${fmt(bestPerCapita.per_capita, 0)} 万元);${weakMargin.name_zh}毛利率最低(${fmt(weakMargin.gross_margin)}%),是盈利结构的洼地。`, points: regions.map(r => ({ label: r.name_zh, text: `收入 ${fmt(r.revenue)} 亿元 · 毛利率 ${fmt(r.gross_margin)}% · 人均产值 ${fmt(r.per_capita, 0)} 万元 · ${fmt(r.headcount, 0)} 人`, tone: r.gross_margin === weakMargin.gross_margin ? 'bad' as const : undefined, })), actions: [{ label: '切到指标明细查看区域对比', code: 'R01' }], source: SRC_BIZ, }; } const lines = queryProductLines(); const byRevenue = [...lines].sort((a, b) => b.revenue - a.revenue); const byMargin = [...lines].sort((a, b) => b.gross_margin - a.gross_margin); const byGrowth = [...lines].sort((a, b) => b.yoy_growth - a.yoy_growth); const total = lines.reduce((a, l) => a + l.revenue, 0); return { conclusion: `${byRevenue[0].name_zh}收入规模最大(${fmt(byRevenue[0].revenue)} 亿元,占 ${fmt(byRevenue[0].revenue / total * 100, 0)}%);${byMargin[0].name_zh}毛利率最高(${fmt(byMargin[0].gross_margin)}%);${byGrowth[0].name_zh}增速最快(+${fmt(byGrowth[0].yoy_growth)}%),是结构升级的主引擎。`, points: lines.map(l => ({ label: l.name_zh, text: `收入 ${fmt(l.revenue)} 亿元(占比 ${fmt(l.share)}%)· 毛利率 ${fmt(l.gross_margin)}% · 同比 +${fmt(l.yoy_growth)}%`, tone: l.gross_margin === byMargin[byMargin.length - 1].gross_margin ? 'warn' as const : undefined, })), actions: [ { label: '模拟高毛利占比提升', ask: '如果高毛利产品占比提升到 40% 会怎样'}, { label: '毛利率归因分析', ask: '毛利率为什么低于目标'}, ], source: SRC_BIZ, }; } /** 异常检测:红色 + 黄色偏离清单 */ function answerAnomaly(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const counts = countAlerts(ctx); const bad = ctx.flat .filter(n => n.level >= 2 && (n.alert_level === 'red' || (n.alert_level === 'yellow' && gapOf(n) < 0))) .sort((a, b) => (a.alert_level === 'red' ? -1 : 1) - (b.alert_level === 'red' ? -1 : 1) || achieveRate(a) - achieveRate(b)) .slice(0, 5); const worst = bad[0]; return { conclusion: `当前红色告警 ${counts.red} 项、黄色偏离 ${counts.yellow} 项。最紧急:${worst ? `「${label(worst)}」达成率仅 ${fmt(achieveRate(worst), 0)}%` : '无'}。`, points: bad.map(n => ({ label: `${label(n)}${n.alert_level === 'red' ? ' 🔴' : ' 🟡'}`, text: `当期 ${fmt(n.value)}${unitOf(n)} / 目标 ${fmt(n.target)}${unitOf(n)}(偏差 ${fmtSigned(gapOf(n))}${gapUnit(n)})· ${n.owner}`, tone: n.alert_level === 'red' ? 'bad' as const : 'warn' as const, })), actions: [ ...(worst ? [{ label: `打开「${label(worst)}」`, code: worst.code }] : []), { label: '查看升级建议', ask: '哪些指标需要升级'}, ], source: SRC_METRIC, }; } /** 升级处置:红色 + 连续 3 期低于目标 */ function answerEscalate(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const streakOf = (n: MetricNode) => { const ts = queryTrend(n.code).slice(0, Math.max(1, ctx.period + 1)); const gaps = ts.map(p => (n.polarity === 'down' ? -(p.actual - p.target) : p.actual - p.target)); let s = 0; for (let i = gaps.length - 1; i >= 0 && gaps[i] < 0; i--) s++; return s; }; const targets = ctx.flat .filter(n => n.level >= 2 && (n.alert_level === 'red' || streakOf(n) >= 3)) .map(n => ({ n, streak: streakOf(n) })) .sort((a, b) => (a.n.alert_level === 'red' ? -1 : 1) - (b.n.alert_level === 'red' ? -1 : 1) || b.streak - a.streak) .slice(0, 4); return { conclusion: `建议升级 ${targets.length} 项:${targets.map(x => label(x.n)).join('、') || '—'}。红色或连续 3 期未达标已触发上报阈值,建议纳入经营例会跟踪。`, points: targets.map(x => ({ label: label(x.n), text: `${x.streak >= 3 ? `连续 ${x.streak} 期低于目标` : '触发预警阈值'} · 责任部门 ${x.n.owner} · 达成率 ${fmt(achieveRate(x.n), 0)}%`, tone: 'bad' as const, })), actions: targets.slice(0, 2).flatMap(x => [ { label: `打开「${label(x.n)}」`, code: x.n.code }, ]), source: SRC_METRIC, }; } /** 行动建议:偏差拉回路径(子因子 top2) */ function answerAdvice(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!; const gap = gapOf(n); const kids = ctx.flat .filter(k => k.parent_code === n.code && gapOf(k) < 0) .sort((a, b) => Math.abs(gapOf(b)) - Math.abs(gapOf(a))) .slice(0, 2); const paths = kids.length ? kids : ctx.flat.filter(k => k.parent_code === n.code).slice(0, 2); return { conclusion: `把「${label(n)}」拉回目标 ${fmt(n.target)}${unitOf(n)} 的两条路径:${paths.map(k => `将「${label(k)}」从 ${fmt(k.value)}${unitOf(k)} 提到 ${fmt(k.target)}${unitOf(k)}`).join(';')}。`, spark: { values: trendOf(n.code, ctx.period), target: n.target, unit: unitOf(n) }, focusCode: n.code, points: [ ...paths.map((k, i) => ({ label: `路径 ${i + 1}`, text: `把「${label(k)}」提到 ${fmt(k.target)}${unitOf(k)}(当前 ${fmt(k.value)}${unitOf(k)},偏差 ${fmtSigned(gapOf(k))}${gapUnit(k)})· 责任部门 ${k.owner}`, tone: 'warn' as const, })), { label: '现状', text: `本指标达成率 ${fmt(achieveRate(n), 0)}%(偏差 ${fmtSigned(gap)}${gapUnit(n)}),${gap >= 0 ? '当前保持达标' : '需要纠偏动作'}`, }, ], actions: [ ...(paths[0] ? [ { label: `模拟路径 1 影响`, ask: `如果${paths[0].name_zh}提升到 ${fmt(paths[0].target)}会怎样`}, { label: `打开「${label(paths[0])}」`, code: paths[0].code }, ] : []), ], source: SRC_METRIC, }; } /** 经营总览:OV + 八维度 + 红黄绿 */ function answerOverview(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply { const ov = ctx.byCode.get('OV')!; const dims = ctx.flat.filter(n => n.level === 1).sort((a, b) => gapOf(b) - gapOf(a)); const counts = countAlerts(ctx); const weakest = dims[dims.length - 1]; const strongest = dims[0]; return { conclusion: `整体经营健康度 ${fmt(ov.value)} 分(目标 ${fmt(ov.target)} 分,达成率 ${fmt(achieveRate(ov), 0)}%)。八大维度 ${dims.filter(d => d.alert_level === 'green').length} 项绿灯,最弱的是「${label(weakest)}」(${fmt(weakest.value)} 分)。`, spark: { values: trendOf('OV', ctx.period), target: ov.target, unit: '分'}, focusCode: 'OV', points: [ { label: '最强维度', text: `「${label(strongest)}」${fmt(strongest.value)} 分(偏差 ${fmtSigned(gapOf(strongest))} 分)`, tone: 'good' }, { label: '最弱维度', text: `「${label(weakest)}」${fmt(weakest.value)} 分(偏差 ${fmtSigned(gapOf(weakest))} 分)· 瓶颈在 AI 渗透与数据资产在线率`, tone: 'bad' }, { label: '指标状态', text: `L2 及以下:红色 ${counts.red} 项 / 黄色 ${counts.yellow} 项 / 绿色 ${counts.green} 项(共 ${counts.total - 9} 项)`}, ], actions: [ { label: `打开「${label(weakest)}」`, code: weakest.code }, { label: '查看异常指标', ask: '哪些指标异常'}, ], source: SRC_METRIC, }; } /** 风险矩阵 */ function answerRisk(_parsed: ParsedAsk, _ctx: AnswerCtx): AiReply { const risks = queryRisks(); const top = risks[0]; const escalated = risks.filter(r => r.status_zh.includes('升级')); return { conclusion: `当前登记风险 ${risks.length} 项。评分最高:${top.name_zh}(概率 ${fmt(top.probability, 1)} × 影响 ${fmt(top.impact, 1)})。${escalated.length ? `已升级 ${escalated.length} 项(${escalated.map(r => r.name_zh).join('、')}),需管理层跟踪。` : ''}`, points: risks.slice(0, 4).map(r => ({ label: r.name_zh, text: `概率 ${fmt(r.probability, 1)} × 影响 ${fmt(r.impact, 1)} · ${r.status_zh}`, tone: (r.probability * r.impact) >= 0.4 ? 'bad' as const : 'warn' as const, })), actions: [{ label: '打开风险敞口指数', code: 'RK01' }], source: SRC_BIZ, }; } /** 兜底:能力引导 */ function answerFallback(_parsed: ParsedAsk, _ctx: AnswerCtx): AiReply { const samples: [string, string][] = ([ ['指标查询', '毛利率现在多少?'], ['归因分析', '毛利率为什么低于目标?'], ['趋势预测', '预测下季度营业收入'], ['假设模拟', '如果高毛利产品占比提升到 40% 会怎样'], ['对比分析', '各产品线毛利率对比'], ]); return { conclusion: '这个问题我暂时没有理解。围绕经营指标,我可以帮你做这些:', points: samples.map(([cap, q]) => ({ label: cap, text: q })), actions: samples.map(([cap, q]) => ({ label: cap, ask: q })), source: SRC_METRIC, }; } /* ── 主入口 ─────────────────────────────────────────────────────────────── */ export function buildAnswer(parsed: ParsedAsk, ctx: AnswerCtx): AiReply { switch (parsed.intent) { case 'query': return answerQuery(parsed, ctx); case 'attribute': return answerAttribute(parsed, ctx); case 'forecast': return answerForecast(parsed, ctx); case 'whatif': return answerWhatIf(parsed, ctx); case 'compare': return answerCompare(parsed, ctx); case 'anomaly': return answerAnomaly(parsed, ctx); case 'escalate': return answerEscalate(parsed, ctx); case 'advice': return answerAdvice(parsed, ctx); case 'overview': return answerOverview(parsed, ctx); case 'risk': return answerRisk(parsed, ctx); default: return answerFallback(parsed, ctx); } }