import { createHash, randomUUID } from 'node:crypto'; import { GoalRuntimeError } from './errors.js'; import { GoalStore } from './goalStore.js'; import type { Goal, GoalAttempt, GoalAttemptStatus, GoalContract, GoalContractInput, GoalEvent, GoalExecutionContext, GoalResourceUsage, GoalScope, GoalSource, GoalStatus, } from './types.js'; import { isGoalFinished } from './types.js'; const TRANSITIONS: Record> = { active: new Set(['paused', 'blocked', 'usage_limited', 'budget_limited', 'ready_for_acceptance', 'cancelled']), // paused → budget_limited 同样是**精化**:finishAttempt 把 attempt 结局 'stopped' // 统一派生成 Goal.paused(与用户主动 action=pause 共用同一落点),控制器识别出 // 「stopped 是因为预算耗尽」后再精化一步——否则「用户暂停」与「系统按预算停」 // 会被压成同一个状态,桌面端没法分开渲染,用户也不知道该不该加预算再续。 paused: new Set(['active', 'cancelled', 'budget_limited']), // blocked → usage_limited 是**精化**不是倒退:两者都表示「卡住了」, // 后者多一条「原因明确是服务端配额/授权」的信息。attempt 失败会先落 blocked, // 控制器识别出配额类错误后再精化 —— 允许这条边才能让 usage_limited 真的可达 // (此前它只在类型里存在,没有任何代码能推到它,而桌面端已经在渲染它了)。 blocked: new Set(['active', 'usage_limited', 'cancelled']), usage_limited: new Set(['active', 'cancelled']), budget_limited: new Set(['active', 'cancelled']), ready_for_acceptance: new Set(['active', 'accepted', 'cancelled']), accepted: new Set(), cancelled: new Set(), }; /** * 预算值规整:非有限数 / ≤0 一律视为「不限」。 * * ⚠️ 用 `null` 而不是 `0` 表示无限。0 会被 `used >= limit` 判成「一开始就超了」, * 于是没设预算的 Goal 一轮都跑不了 —— 这类「哨兵值撞上真实值」的坑, * 本仓库在 `undefined ≠ 0` 那条缓存字段纪律上已经吃过一次。 */ function normalizeTokenBudget(value: number | null | undefined): number | null { if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null; return Math.round(value); } /** * 版本化契约的补丁合并规则:undefined 表示保留,null 表示清空可选字段。 * 合并必须发生在 Runtime 内,避免只修改 objective 的入口清空预算、交付物和 * 来源引用。 */ export function mergeGoalContractInput( previous: GoalContract, input: GoalContractInput, ): GoalContractInput { return { objective: input.objective ?? previous.objective, deliverables: input.deliverables === undefined ? previous.deliverables : input.deliverables, acceptanceCriteria: input.acceptanceCriteria === undefined ? previous.acceptanceCriteria : input.acceptanceCriteria, scope: input.scope === undefined ? previous.scope : input.scope, sourceRefs: input.sourceRefs === undefined ? previous.sourceRefs : input.sourceRefs, confirmedBy: input.confirmedBy ?? previous.confirmedBy, tokenBudget: input.tokenBudget === undefined ? previous.tokenBudget : input.tokenBudget, }; } export interface GoalRuntimeOptions { store?: GoalStore; now?: () => number; id?: () => string; } export class GoalRuntime { readonly store: GoalStore; private readonly now: () => number; private readonly id: () => string; constructor(options: GoalRuntimeOptions = {}) { this.store = options.store ?? new GoalStore(); this.now = options.now ?? Date.now; this.id = options.id ?? randomUUID; } get(scope: GoalScope): Promise { return this.store.read(scope); } async create(input: { scope: GoalScope; contract: GoalContractInput; source?: GoalSource; createdBy?: string; acceptorHumanIds?: string[]; }): Promise { return this.store.mutate(input.scope, async () => { const current = await this.store.read(input.scope); if (current && !isGoalFinished(current.status)) { throw new GoalRuntimeError( 'GOAL_CONFLICT', `Session 已有未完成 Goal「${this.currentContract(current).objective}」(${current.status})。请继续、更新或取消它。`, ); } const now = this.now(); const goalId = this.id(); const createdBy = input.createdBy ?? 'local-human'; const contract = this.makeContract(input.contract, 1, now, createdBy); const goal: Goal = { goalId, scope: input.scope, source: input.source ?? { kind: 'standalone' }, status: 'active', revision: 1, contracts: [contract], currentContractVersion: 1, attempts: [], createdBy, acceptorHumanIds: input.acceptorHumanIds?.length ? [...new Set(input.acceptorHumanIds)] : [createdBy], createdAt: now, updatedAt: now, usage: { inputTokens: 0, outputTokens: 0, elapsedMs: 0 }, }; const event: GoalEvent = { type: 'goal.created', eventId: this.id(), at: now, goalId, contract, source: goal.source, createdBy, acceptorHumanIds: goal.acceptorHumanIds, revision: 1, }; await this.store.commit(input.scope, goal, [event]); return goal; }); } async revise( scope: GoalScope, expectedGoalId: string, expectedRevision: number, input: GoalContractInput, ): Promise { return this.change(scope, expectedGoalId, expectedRevision, (goal, now) => { this.ensureNotFinished(goal); const running = goal.attempts.find((attempt) => attempt.status === 'running'); if (running) { running.status = 'superseded'; running.finishedAt = now; } const contract = this.makeContract( mergeGoalContractInput(this.currentContract(goal), input), goal.currentContractVersion + 1, now, input.confirmedBy ?? goal.createdBy, ); goal.contracts.push(contract); goal.currentContractVersion = contract.version; goal.status = 'active'; goal.statusReason = undefined; const events: GoalEvent[] = []; if (running) { events.push({ type: 'goal.attempt_finished', eventId: this.id(), at: now, goalId: goal.goalId, attemptId: running.attemptId, status: running.status, artifacts: running.artifacts, evidence: running.evidence, }); } events.push({ type: 'goal.contract_revised', eventId: this.id(), at: now, goalId: goal.goalId, contract, }); return events; }); } async transition( scope: GoalScope, expectedGoalId: string, expectedRevision: number, to: GoalStatus, options: { reason?: string; actorId?: string } = {}, ): Promise { return this.change(scope, expectedGoalId, expectedRevision, (goal, now) => { const from = goal.status; if (from === to) return []; if (!TRANSITIONS[from].has(to)) { throw new GoalRuntimeError( 'GOAL_INVALID_TRANSITION', `Goal 不能从 ${from} 变为 ${to}。`, ); } if (to === 'accepted') { const actor = options.actorId ?? ''; if (!actor || !goal.acceptorHumanIds.includes(actor)) { throw new GoalRuntimeError( 'GOAL_ACCEPTOR_REQUIRED', '只有 Goal 契约指定的人类验收人可以最终通过成果。', ); } } const events: GoalEvent[] = []; if (to === 'paused' || to === 'cancelled') { for (const attempt of goal.attempts.filter((item) => item.status === 'running')) { attempt.status = 'stopped'; attempt.finishedAt = now; attempt.blocker = options.reason; events.push({ type: 'goal.attempt_finished', eventId: this.id(), at: now, goalId: goal.goalId, attemptId: attempt.attemptId, status: attempt.status, artifacts: attempt.artifacts, evidence: attempt.evidence, blocker: attempt.blocker, }); } } goal.status = to; goal.statusReason = options.reason; events.push({ type: 'goal.status_changed', eventId: this.id(), at: now, goalId: goal.goalId, from, to, ...options, }); return events; }); } async startAttempt( scope: GoalScope, expectedGoalId: string, expectedRevision: number, workflow: string, ): Promise<{ goal: Goal; execution: GoalExecutionContext }> { let execution: GoalExecutionContext | null = null; const goal = await this.change(scope, expectedGoalId, expectedRevision, (draft, now) => { if (draft.status !== 'active') { throw new GoalRuntimeError( 'GOAL_INVALID_TRANSITION', `Goal 当前是 ${draft.status},不能开始执行。`, ); } if (draft.attempts.some((attempt) => attempt.status === 'running')) { throw new GoalRuntimeError( 'GOAL_ATTEMPT_CONFLICT', '同一个 Session 已有正在运行的 Goal Attempt。', ); } const resumable = [...draft.attempts].reverse().find( (attempt) => (attempt.status === 'stopped' || attempt.status === 'failed') && attempt.contractVersion === draft.currentContractVersion && attempt.workflow === workflow, ); const attempt: GoalAttempt = resumable ?? { attemptId: this.id(), contractVersion: draft.currentContractVersion, workflow, status: 'running', startedAt: now, artifacts: [], evidence: [], }; if (resumable) { attempt.status = 'running'; attempt.finishedAt = undefined; attempt.blocker = undefined; } else { draft.attempts.push(attempt); } const contract = this.currentContract(draft); execution = { goalId: draft.goalId, contractVersion: contract.version, attemptId: attempt.attemptId, contract, ...(draft.source.kind === 'group-task' ? { groupId: draft.source.groupId, taskId: draft.source.taskId } : {}), }; return [{ type: 'goal.attempt_started', eventId: this.id(), at: now, goalId: draft.goalId, attempt, }]; }); return { goal, execution: execution as unknown as GoalExecutionContext }; } /** * 把 Goal Workflow 在首次 Attempt 的契约阶段生成、并经人类确认的完整契约 * 固化下来。它不是执行中的目标转向,因此不会 supersede 当前 Attempt;Attempt * 从生产阶段开始即绑定新版本。后续的人类目标修改必须走 revise()。 */ async materializeAttemptContract( scope: GoalScope, expectedGoalId: string, expectedRevision: number, attemptId: string, input: GoalContractInput, ): Promise { return this.change(scope, expectedGoalId, expectedRevision, (goal, now) => { const attempt = goal.attempts.find((item) => item.attemptId === attemptId); if (!attempt || attempt.status !== 'running') { throw new GoalRuntimeError( 'GOAL_ATTEMPT_CONFLICT', '只有当前正在运行的 Attempt 可以固化执行契约。', ); } const previous = this.currentContract(goal); const candidate = this.makeContract( mergeGoalContractInput(previous, input), previous.version + 1, now, input.confirmedBy ?? previous.confirmedBy, ); if (candidate.hash === previous.hash) return []; goal.contracts.push(candidate); goal.currentContractVersion = candidate.version; attempt.contractVersion = candidate.version; return [ { type: 'goal.contract_revised', eventId: this.id(), at: now, goalId: goal.goalId, contract: candidate, }, { type: 'goal.attempt_started', eventId: this.id(), at: now, goalId: goal.goalId, attempt: structuredClone(attempt), }, ]; }); } async finishAttempt(input: { scope: GoalScope; expectedGoalId: string; expectedRevision: number; attemptId: string; status: GoalAttemptStatus; artifacts?: string[]; evidence?: string[]; blocker?: string; }): Promise { return this.change( input.scope, input.expectedGoalId, input.expectedRevision, (goal, now) => { const attempt = goal.attempts.find((item) => item.attemptId === input.attemptId); if (!attempt) { throw new GoalRuntimeError('GOAL_NOT_FOUND', `找不到 Attempt ${input.attemptId}。`); } attempt.status = input.status; attempt.finishedAt = now; attempt.artifacts = [...new Set(input.artifacts ?? [])]; attempt.evidence = [...new Set(input.evidence ?? [])]; attempt.blocker = input.blocker; const from = goal.status; if (!isGoalFinished(goal.status)) { if (input.status === 'verified') goal.status = 'ready_for_acceptance'; else if (input.status === 'failed') goal.status = 'blocked'; else if (input.status === 'stopped') goal.status = 'paused'; goal.statusReason = input.blocker; } const events: GoalEvent[] = [{ type: 'goal.attempt_finished', eventId: this.id(), at: now, goalId: goal.goalId, attemptId: attempt.attemptId, status: attempt.status, artifacts: attempt.artifacts, evidence: attempt.evidence, blocker: attempt.blocker, }]; if (from !== goal.status) { events.push({ type: 'goal.status_changed', eventId: this.id(), at: now, goalId: goal.goalId, from, to: goal.status, reason: input.blocker, }); } return events; }, ); } async recordUsage( scope: GoalScope, expectedGoalId: string, expectedRevision: number, usage: Partial, ): Promise { return this.change(scope, expectedGoalId, expectedRevision, (goal, now) => { goal.usage.inputTokens += usage.inputTokens ?? 0; goal.usage.outputTokens += usage.outputTokens ?? 0; goal.usage.elapsedMs += usage.elapsedMs ?? 0; return [{ type: 'goal.resources_recorded', eventId: this.id(), at: now, goalId: goal.goalId, usage, }]; }); } currentContract(goal: Goal): GoalContract { const contract = goal.contracts.find( (item) => item.version === goal.currentContractVersion, ); if (!contract) throw new GoalRuntimeError('GOAL_NOT_FOUND', 'Goal 当前契约不存在。'); return contract; } private async change( scope: GoalScope, expectedGoalId: string, expectedRevision: number, mutate: (goal: Goal, now: number) => GoalEvent[], ): Promise { return this.store.mutate(scope, async () => { const current = await this.store.read(scope); if (!current || current.goalId !== expectedGoalId) { throw new GoalRuntimeError('GOAL_NOT_FOUND', '当前 Session 的 Goal 已改变或不存在。'); } if (current.revision !== expectedRevision) { throw new GoalRuntimeError( 'GOAL_REVISION_CONFLICT', `Goal 已被更新(期望 revision ${expectedRevision},实际 ${current.revision})。`, ); } const now = this.now(); const events = mutate(current, now); if (events.length === 0) return current; current.revision++; current.updatedAt = now; for (const event of events) event.revision = current.revision; await this.store.commit(scope, current, events); return current; }); } private makeContract( input: GoalContractInput, version: number, at: number, confirmedBy: string, ): GoalContract { const objective = input.objective.trim(); if (!objective) throw new GoalRuntimeError('GOAL_NOT_FOUND', 'Goal 目标不能为空。'); const normalized = { objective, deliverables: [...new Set(input.deliverables?.map((item) => item.trim()).filter(Boolean) ?? [])], acceptanceCriteria: [...new Set(input.acceptanceCriteria?.map((item) => item.trim()).filter(Boolean) ?? [])], scope: input.scope?.trim() || undefined, sourceRefs: [...new Set(input.sourceRefs?.map((item) => item.trim()).filter(Boolean) ?? [])], // ⚠️ tokenBudget 必须进 normalized(从而进 hash):改预算就是改契约, // 得产生新版本、留下痕迹。若不进 hash,「把预算调大」会被 // `candidate.hash === previous.hash` 判成没变化而被整条丢弃(见 275 行)。 tokenBudget: normalizeTokenBudget(input.tokenBudget), }; return { version, ...normalized, confirmedBy, confirmedAt: at, hash: createHash('sha256').update(JSON.stringify(normalized)).digest('hex'), }; } private ensureNotFinished(goal: Goal): void { if (isGoalFinished(goal.status)) { throw new GoalRuntimeError('GOAL_INVALID_TRANSITION', `Goal 已是 ${goal.status}。`); } } }