import {withStrategyClaim} from '../strategic/scheduling.ts'; import {parseFreescopeInput,type FreescopeInput} from './freescope.ts'; /** * B05 任务宿主:Planner/Worker 调度、领取与生命周期管理。 * 阶段 A 语义(RUNBOOK §2):任务状态/租约/恢复是宿主职责,Pi 只跑单会话 loop。 * 本文件先实现可测核心:CAS 领取、优先级、心跳、model_error 重试、重启恢复。 * plannerLoop/workerLoop 的完整触发/去抖语义在 F03(P2)接 Pi 会话时补全。 */ import type { Pool } from "pg"; import { normalizeHeartbeat } from "./state-machine.ts"; export interface ClaimResult { claimed: boolean; intentId?: number; } /** CAS 领取:UPDATE ... WHERE state='open'。 */ export async function claimNextIntent( pool: Pool, taskId: number, worker: string, intentId?:number, ): Promise { return withStrategyClaim(pool,taskId,async(db,strategyOrder)=>{ const res = await db.query( `UPDATE exploration_nodes SET state='running', claimed_by=$2, claimed_at=now(), heartbeat_at=now(), attempts = attempts + 1, updated_at=now() WHERE id = ( SELECT n.id FROM exploration_nodes n WHERE n.task_id=$1 AND kind='intent' AND state='open' AND n.assessment_state='active' AND NOT EXISTS(SELECT 1 FROM exploration_edges e JOIN exploration_nodes basis ON basis.id=e.src_id WHERE e.dst_id=n.id AND e.rel='derived_from' AND basis.kind IN('fact','finding') AND basis.assessment_state<>'active') AND EXISTS (SELECT 1 FROM tasks WHERE id=$1 AND status='running' AND paused=FALSE AND deleted_at IS NULL AND NOT EXISTS(SELECT 1 FROM explorations WHERE id=tasks.exploration_id AND status='achieved')) AND NOT EXISTS (SELECT 1 FROM intent_dependencies d LEFT JOIN exploration_nodes p ON p.id=d.prerequisite_intent_id LEFT JOIN task_capabilities c ON c.id=d.capability_id WHERE d.intent_id=n.id AND ((d.prerequisite_intent_id IS NOT NULL AND (p.state<>'done' OR p.assessment_state<>'active')) OR (d.capability_id IS NOT NULL AND (c.state<>'active' OR (d.capability_revision IS NOT NULL AND c.revision<>d.capability_revision))))) AND ($3::bigint IS NULL OR n.id=$3) AND NOT EXISTS(SELECT 1 FROM android_login_assistance a WHERE a.state IN('pausing','active','resuming') AND (a.task_id=$1 OR EXISTS(SELECT 1 FROM jsonb_array_elements(a.paused_children) child WHERE child->>'id'=($1::bigint)::text))) ORDER BY CASE n.payload->>'scheduling_class' WHEN 'calibration' THEN 3 WHEN 'unlock' THEN 2 ELSE 0 END DESC, ${strategyOrder}(priority+${strategyOrder?"COALESCE((SELECT LEAST(2,GREATEST(score,COALESCE((details->>'branch_score')::numeric,score))/50.0) FROM exploration_scores WHERE node_id=n.id),0)":'0'}+LEAST(3,EXTRACT(EPOCH FROM(now()-n.created_at))/300) +CASE WHEN n.payload->>'decision_bonus' ~ '^[0-9]+([.][0-9]+)?$' THEN LEAST(2,(n.payload->>'decision_bonus')::numeric) ELSE 0 END) DESC,n.id ASC LIMIT 1 FOR UPDATE SKIP LOCKED ) RETURNING id`, [taskId, worker,intentId??null], ); if (res.rowCount === 0) return { claimed: false }; return { claimed: true, intentId: Number(res.rows[0]!.id) }; }); } /** worker 心跳 */ export async function heartbeat(pool: Pool, intentId: number): Promise { await pool.query("UPDATE exploration_nodes SET heartbeat_at=now() WHERE id=$1", [intentId]); } /** Release legacy blocked intents without reopening a still-running worker. */ export async function releaseModelingIntent(pool:Pool,taskId:number,intentId:number,owner:string):Promise{ const r=await pool.query(`UPDATE exploration_nodes SET state='open',blocked_reason=NULL,claimed_by=NULL,claimed_at=NULL,updated_at=now() WHERE id=$1 AND task_id=$2 AND state='blocked' AND blocked_reason='business_modeling' AND claimed_by=$3 RETURNING id`,[intentId,taskId,owner]);return !!r.rowCount; } export async function recoverModelingIntents(pool:Pool):Promise{ await pool.query(`UPDATE exploration_nodes n SET state='open',blocked_reason=NULL,claimed_by=NULL,claimed_at=NULL,updated_at=now() FROM tasks t WHERE n.task_id=t.id AND t.status IN('created','running','paused') AND t.deleted_at IS NULL AND n.kind='intent' AND n.state='blocked' AND n.blocked_reason='business_modeling'`); await pool.query('UPDATE task_business_models SET initial_gate=false WHERE initial_gate'); } /** model_error 重试:failed → open(attempts 已在领取时 +1);超过 maxAttempts 落 exhausted */ export async function retryIntent(pool: Pool, intentId: number, maxAttempts: number): Promise<"requeued" | "exhausted"|"unchanged"> { // One CAS statement: a concurrent stop/delete must never be resurrected by // a stale model-error handler. Original intent states have no failed stage. const row=(await pool.query(`UPDATE exploration_nodes SET state=CASE WHEN attempts >= $2 THEN 'exhausted' ELSE 'open' END, last_error=CASE WHEN attempts >= $2 THEN last_error ELSE NULL END, claimed_by=NULL,claimed_at=NULL,updated_at=now() WHERE id=$1 AND state='running' RETURNING state`,[intentId,maxAttempts])).rows[0]; return !row?'unchanged':row.state==='open'?'requeued':'exhausted'; } /** 重启恢复:残留 running 意图回退 open(对照 restoreTaskRuntimes),租约清空 */ export async function recoverOnBoot(pool: Pool): Promise<{ intentsReset: number; tasksResumed: number }> { const intents = await pool.query( "UPDATE exploration_nodes SET state='open', claimed_by=NULL, claimed_at=NULL, updated_at=now() WHERE state='running'", ); const tasks = await pool.query( "UPDATE tasks SET updated_at=now() WHERE status='running' AND paused = FALSE", ); return { intentsReset: intents.rowCount ?? 0, tasksResumed: tasks.rowCount ?? 0 }; } /** 任务创建(含排队位与心跳规范化) */ export async function createTask( pool: Pool, input: { name: string; goal: string; queued?: boolean; heartbeatS?: number; deadlineAt?: Date | null } & FreescopeInput, ): Promise { const policy=parseFreescopeInput({...input}); const res = await pool.query<{ id: number }>( `INSERT INTO tasks (name, goal, queued, plan_heartbeat_seconds, deadline_at,freescope,freescope_options) VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb) RETURNING id`, [input.name, input.goal, input.queued ?? false, normalizeHeartbeat(input.heartbeatS), input.deadlineAt ?? null,policy.freescope??false,JSON.stringify(policy.freescope_options??{})], ); return Number(res.rows[0]!.id); } export async function addIntent(pool: Pool, taskId: number, title: string, priority = 0): Promise { const res = await pool.query<{ id: number }>( "INSERT INTO exploration_nodes (task_id, title, priority) VALUES ($1,$2,$3) RETURNING id", [taskId, title, priority], ); return Number(res.rows[0]!.id); }