import { createHash } from "node:crypto"; import type { Pool } from "pg"; import type { DB } from "./settings.ts"; type Row = Record; export interface ValueScore { score: number; previous_score: number | null; delta: number; revision: string; task_id: number; policy: "priority" | "normal" | "low_frequency"; factors: { label: string; points: number }[]; basis_ids: string[]; branch_ids: string[]; branch_score: number; revisit_condition: string; updated_at: string | null; confidence: string; } const hash = (v: unknown) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 24); const clamp = (v: number, min = 0, max = 100) => Math.min(max, Math.max(min, Math.round(v))); const payload = (n: Row): Row => { try { return typeof n.payload === "string" ? JSON.parse(n.payload) : (n.payload ?? {}); } catch { return {}; } }; const causal = new Set(["derived_from", "spawns", "yields"]); export function scoreExploration( taskId: number, nodes: Row[], edges: Row[], caps: Row[] = [], verifications: Row[] = [], costs: Row[] = [], previous: Row[] = [], ) { const byId = new Map(nodes.map((n) => [String(n.id), n])), incoming = new Map(), outgoing = new Map(); for (const e of edges) { const src = String(e.src ?? e.src_id), dst = String(e.dst ?? e.dst_id); if (!causal.has(e.rel) || !byId.has(src) || !byId.has(dst)) continue; incoming.set(dst, [...(incoming.get(dst) || []), src]); outgoing.set(src, [...(outgoing.get(src) || []), dst]); } const kind = (n: Row) => n.type ?? n.kind; const prior = new Map(previous.map((n) => [String(n.node_id), n])); const verified = new Map(verifications.map((n) => [String(n.node_id), n.verification_status])); const spent = new Map(costs.map((n) => [String(n.node_id), Number(n.charged_seconds) || 0])); const capabilityIds = new Set(caps.filter((c) => c.state === "active").map((c) => String(c.evidence_id))); const revision = hash([ nodes.map((n) => [n.id, kind(n), n.state, n.assessment_state, n.priority, n.attempts, n.payload]), edges.map((e) => [e.src ?? e.src_id, e.rel, e.dst ?? e.dst_id]), caps.map((c) => [c.id, c.state, c.revision, c.evidence_id]), verifications, costs.map((c) => [c.node_id, c.charged_seconds]), ]); const result = new Map(); for (const n of nodes) { const id = String(n.id), p = payload(n), k = kind(n), factors: { label: string; points: number }[] = []; const add = (label: string, points: number) => factors.push({ label, points }); add("基础探索机会", k === "intent" ? 40 : k === "finding" ? 35 : 25); if (k === "intent") { add("任务派发优先级", clamp(Number.isFinite(Number(n.priority)) ? Number(n.priority) : 5, 0, 10) * 2); if (p.decision) add("预期判别信息", clamp(Number(p.decision.information_gain) || 0, 0, 3) * 4); const observed = (incoming.get(id) || []) .map((i) => byId.get(i)!) .filter( (a) => kind(a) === "fact" && payload(a).confidence === "observed" && (a.assessment_state ?? "active") === "active", ); if (observed.length) add("已有有效事实前提", Math.min(12, observed.length * 4)); if ((incoming.get(id) || []).some((i) => capabilityIds.has(i))) add("已解锁后续能力", 12); if (["open", "running"].includes(n.state)) add("仍可推进的验证", 8); if (n.state === "done") add("当前步骤已完成", -18); if (["exhausted", "blocked", "stopped"].includes(n.state)) add("当前执行条件或方法受阻", -22); if (Number(n.attempts) > 1) add("重复尝试成本", -Math.min(16, (Number(n.attempts) - 1) * 4)); const seconds = spent.get(id) || 0; if (seconds > 60) add("已消耗执行时间", -Math.min(12, Math.floor(seconds / 120))); } if (k === "fact") { if (p.confidence === "observed") add("实际观察", 18); else if (p.confidence === "inferred") add("待验证假设的探索机会", 5); if (p.evidence || p.detail) add("存在可追溯记录", 7); if (capabilityIds.has(id)) add("可复用的已验证能力", 22); const next = (outgoing.get(id) || []).filter( (i) => kind(byId.get(i)!) === "intent" && ["open", "running"].includes(byId.get(i)!.state), ).length; if (next) add("可支撑后续检查", Math.min(12, next * 4)); } if (k === "finding") { const severity = ({ critical: 20, high: 15, medium: 8, low: 3 } as Record)[String(p.severity)] ?? 0; const state = verified.get(id); add("登记的影响级别", state === "verified" ? severity : Math.min(7, severity)); if (state === "verified") add("独立复核支持", 20); else if (state === "not_reproduced") add("独立复核未复现", -22); else add("尚需独立核实", 5); } if ((n.assessment_state ?? "active") !== "active") add("依据已失效或待校准", -30); if (n.state === "deleted" || n.delete_reason) add("节点已移除", -100); const score = clamp(factors.reduce((sum, f) => sum + f.points, 0)), old = prior.get(id); result.set(id, { score, previous_score: old ? Number(old.score) : null, delta: old ? score - Number(old.score) : 0, revision, task_id: taskId, policy: score >= 70 ? "priority" : score < 35 ? "low_frequency" : "normal", factors, basis_ids: incoming.get(id) || [], branch_ids: [], branch_score: score, revisit_condition: "新事实、能力或模型发生有效变化,或达到等待补偿窗口后重新调度", updated_at: old?.updated_at ? new Date(old.updated_at).toISOString() : null, confidence: k === "finding" ? verified.get(id) || "not_reviewed" : p.confidence || "estimated", }); } // Stable hypotheses, not arbitrary graph walks. Shared evidence is a set in each branch. const branches = new Map< string, { id: string; root: string; label: string; members: Set; score: number; frontier: number } >(); for (const n of nodes.filter((n) => kind(n) === "intent")) { const id = String(n.id), p = payload(n); let hasAncestor = false; const seen = new Set(), queue = [...(incoming.get(id) || [])]; for (let i = 0; i < queue.length && i < 10000; i++) { const parent = queue[i]!; if (seen.has(parent)) continue; seen.add(parent); if (parent !== id && kind(byId.get(parent)!) === "intent") { hasAncestor = true; break; } queue.push(...(incoming.get(parent) || [])); } if (hasAncestor && !p.scenario_id && !p.branch_key) continue; const branch = p.scenario_id ? "scenario:" + p.scenario_id : p.branch_key ? "hypothesis:" + String(p.branch_key) : "intent:" + id; let b = branches.get(branch); if (!b) { b = { id: branch, root: id, label: String(p.hypothesis || p.summary || n.title || id).slice(0, 200), members: new Set(), score: 0, frontier: 0, }; branches.set(branch, b); } const todo = [id]; for (let i = 0; i < todo.length; i++) { const child = todo[i]!; if (b.members.has(child)) continue; b.members.add(child); todo.push(...(outgoing.get(child) || [])); } } // Cyclic imported lineage still receives a finite fallback branch. const covered = new Set([...branches.values()].flatMap((b) => [...b.members])); for (const n of nodes.filter((n) => kind(n) === "intent" && !covered.has(String(n.id)))) { const id = String(n.id); if (covered.has(id)) continue; const members = new Set(), todo = [id]; for (let i = 0; i < todo.length; i++) { const child = todo[i]!; if (members.has(child)) continue; members.add(child); covered.add(child); todo.push(...(outgoing.get(child) || [])); } branches.set("intent:" + id, { id: "intent:" + id, root: id, label: String(payload(n).summary || n.title || id).slice(0, 200), members, score: 0, frontier: 0, }); } for (const b of branches.values()) { const frontier = [...b.members].filter( (id) => kind(byId.get(id)!) === "intent" && ["open", "running"].includes(byId.get(id)!.state), ); b.frontier = frontier.length; const impact = Math.max( 0, ...[...b.members] .filter((id) => kind(byId.get(id)!) === "finding" && verified.get(id) === "verified") .map( (id) => (({ critical: 12, high: 9, medium: 4, low: 1 }) as Record)[ String(payload(byId.get(id)!).severity) ] || 0, ), ); b.score = frontier.length ? clamp(Math.max(...frontier.map((id) => result.get(id)!.score)) + impact) : Math.min(45, Math.max(0, ...[...b.members].map((id) => result.get(id)!.score))); for (const id of b.members) { const s = result.get(id)!; s.branch_ids.push(b.id); s.branch_score = Math.max(s.branch_ids.length === 1 ? 0 : s.branch_score, b.score); } } // Roots/goals describe available future work, never accumulate rewards per ancestor. for (const n of nodes.filter((n) => kind(n) === "goal" || n.state === "origin")) { const s = result.get(String(n.id))!; s.score = Math.max(0, ...[...branches.values()].map((b) => b.score)); s.factors = [{ label: "当前可推进分支的最高价值", points: s.score }]; s.policy = s.score >= 70 ? "priority" : s.score < 35 ? "low_frequency" : "normal"; const old = prior.get(String(n.id)); s.delta = old ? s.score - Number(old.score) : 0; } for (const [id, s] of result) { const old = prior.get(id); if (old && Number(old.score) === s.score) { s.previous_score = old.previous_score === null ? null : Number(old.previous_score); s.delta = Number(old.delta) || 0; } } return { revision, scores: result, branches: [...branches.values()].map(({ members, ...b }) => ({ ...b, node_ids: [...members] })), }; } export class ExplorationValues { constructor(private pool: Pool) {} async project(taskId: number, nodes: Row[], edges: Row[], db: DB = this.pool) { const [caps, checks, costs, previous] = await Promise.all([ db.query("SELECT id,revision,state,evidence_id FROM task_capabilities WHERE task_id=$1 ORDER BY id", [taskId]), db.query("SELECT node_id,verification_status FROM findings WHERE task_id=$1 ORDER BY node_id", [taskId]), db.query( "SELECT node_id,charged_seconds+CASE WHEN finished_at IS NULL THEN GREATEST(0,floor(EXTRACT(EPOCH FROM(now()-claimed_at))/60)*60) ELSE 0 END charged_seconds FROM strategy_dispatch WHERE task_id=$1 ORDER BY node_id", [taskId], ), db.query("SELECT * FROM exploration_scores WHERE task_id=$1 ORDER BY node_id", [taskId]), ]); return scoreExploration(taskId, nodes, edges, caps.rows, checks.rows, costs.rows, previous.rows); } async refresh(taskId: number) { const db = await this.pool.connect(); try { await db.query("BEGIN"); await db.query("SELECT pg_advisory_xact_lock(733774105,$1::int)", [taskId]); const task = (await db.query("SELECT status,paused FROM tasks WHERE id=$1 AND deleted_at IS NULL", [taskId])) .rows[0]; if (!task) { await db.query("ROLLBACK"); return; } const nodes = ( await db.query("SELECT * FROM exploration_nodes WHERE task_id=$1 ORDER BY id LIMIT 10000", [taskId]) ).rows; const edges = ( await db.query( "SELECT e.* FROM exploration_edges e JOIN tasks t ON t.exploration_id=e.exploration_id WHERE t.id=$1 ORDER BY src_id,dst_id,rel LIMIT 40000", [taskId], ) ).rows; const projected = await this.project(taskId, nodes, edges, db); const prior = (await db.query("SELECT score_revision FROM task_strategy_state WHERE task_id=$1", [taskId])) .rows[0]; if (prior?.score_revision === projected.revision) { await db.query("COMMIT"); return; } const existingRows = new Map( (await db.query("SELECT node_id,score,details FROM exploration_scores WHERE task_id=$1", [taskId])).rows.map( (n) => [String(n.node_id), n], ), ); for (const [id, s] of projected.scores) { const existing = existingRows.get(id); const changed = !existing || Number(existing.score) !== s.score || JSON.stringify(existing.details.factors) !== JSON.stringify(s.factors) || existing.details.branch_score !== s.branch_score || JSON.stringify(existing.details.basis_ids) !== JSON.stringify(s.basis_ids) || JSON.stringify(existing.details.branch_ids) !== JSON.stringify(s.branch_ids) || existing.details.confidence !== s.confidence; if (!changed) continue; await db.query( `INSERT INTO exploration_score_history(task_id,node_id,score,previous_score,revision,details) VALUES($1,$2,$3,$4,$5,$6)`, [taskId, id, s.score, existing?.score ?? null, s.revision, JSON.stringify(s)], ); await db.query( `INSERT INTO exploration_scores(task_id,node_id,score,previous_score,delta,revision,details) VALUES($1,$2,$3,$4,$5,$6,$7) ON CONFLICT(node_id) DO UPDATE SET score=EXCLUDED.score,previous_score=EXCLUDED.previous_score,delta=EXCLUDED.delta,revision=EXCLUDED.revision,details=EXCLUDED.details,updated_at=now()`, [ taskId, id, s.score, existing?.score ?? null, existing ? s.score - Number(existing.score) : 0, s.revision, JSON.stringify(s), ], ); } await db.query("UPDATE task_strategy_state SET score_revision=$2,score_updated_at=now() WHERE task_id=$1", [ taskId, projected.revision, ]); await db.query( "DELETE FROM exploration_score_history WHERE id IN(SELECT id FROM(SELECT id,row_number() OVER(PARTITION BY node_id ORDER BY id DESC) n FROM exploration_score_history WHERE task_id=$1) r WHERE n>20)", [taskId], ); await db.query("COMMIT"); } catch (e) { await db.query("ROLLBACK"); throw e; } finally { db.release(); } } async graph(taskId: number, graph: { nodes: Row[]; edges: Row[] }) { const value = await this.project(taskId, graph.nodes, graph.edges); return { ...graph, score_revision: value.revision, branches: value.branches, nodes: graph.nodes.map((n) => ({ ...n, exploration_value: value.scores.get(String(n.id)) })), edges: graph.edges.map((e) => { const src = value.scores.get(String(e.src)), dst = value.scores.get(String(e.dst)); const common = src?.branch_ids.filter((id) => dst?.branch_ids.includes(id)) || []; const branches = value.branches.filter((b) => common.includes(b.id)); return { ...e, ...(branches.length ? { exploration_value: { score: Math.max(...branches.map((b) => b.score)), branch_ids: common, revision: value.revision, }, } : {}), }; }), }; } }