import type { Pool, PoolClient } from "pg"; import { strategicSettings, type StrategicSettings } from "./settings.ts"; export function strategicOrder(cfg: StrategicSettings) { const lane = "CASE WHEN n.payload->>'authored_by' IN('business_logic','counter_planner') THEN n.payload->>'authored_by' ELSE 'planner' END"; const weight = "CASE " + lane + " WHEN 'business_logic' THEN " + cfg.business_weight + " WHEN 'counter_planner' THEN " + cfg.counter_weight + " ELSE " + (100 - cfg.business_weight - cfg.counter_weight) + " END"; // Aging compensation wins before lane accounting, while calibration/unlock // remain the host's first ordering term. Missing lanes never reserve slots. return ( "CASE WHEN n.created_at" + cfg.revisit_seconds + ") THEN 1 ELSE 0 END DESC, CASE WHEN n.created_at" + cfg.revisit_seconds + ") THEN n.created_at END ASC, (SELECT COALESCE(sum(d.charged_seconds+CASE WHEN d.finished_at IS NULL THEN GREATEST(d.estimated_seconds,EXTRACT(EPOCH FROM(now()-d.claimed_at))) ELSE 0 END),0) FROM strategy_dispatch d WHERE d.task_id=n.task_id AND d.source_role=" + lane + ")/NULLIF(" + weight + ",0) ASC," ); } /** Serialize short claim transactions, never hold a lock during execution. */ export async function withStrategyClaim( pool: Pool, taskId: number, claim: (db: Pool | PoolClient, order: string) => Promise, ): Promise { const cfg = await strategicSettings(pool); if ( !cfg.enabled || !(await pool.query("SELECT 1 FROM task_strategy_state WHERE task_id=$1 AND enabled", [taskId])).rowCount ) return claim(pool, ""); const db = await pool.connect(); try { await db.query("BEGIN"); await db.query("SELECT pg_advisory_xact_lock(733774106,$1::int)", [taskId]); const result = await claim(db, strategicOrder(cfg)); if (result.claimed && result.intentId) await db.query( `INSERT INTO strategy_dispatch(node_id,task_id,source_role,estimated_seconds) SELECT id,task_id,CASE WHEN payload->>'authored_by' IN('business_logic','counter_planner') THEN payload->>'authored_by' ELSE 'planner' END,CASE WHEN payload->'decision'->>'estimated_seconds' ~ '^[0-9]+$' THEN LEAST(3600,GREATEST(1,(payload->'decision'->>'estimated_seconds')::int)) ELSE 60 END FROM exploration_nodes WHERE id=$1 ON CONFLICT(node_id) DO UPDATE SET claimed_at=now(),finished_at=NULL`, [result.intentId], ); await db.query("COMMIT"); return result; } catch (e) { await db.query("ROLLBACK"); throw e; } finally { db.release(); } } export async function finishStrategyDispatch(pool: Pool, nodeId: number) { await pool.query( "UPDATE strategy_dispatch SET charged_seconds=charged_seconds+GREATEST(0,EXTRACT(EPOCH FROM(now()-claimed_at))),finished_at=now() WHERE node_id=$1 AND finished_at IS NULL", [nodeId], ); }