import { createHash } from 'node:crypto'; import { constants } from 'node:fs'; import { appendFile, mkdir, open, readFile, rename, stat, unlink, writeFile, } from 'node:fs/promises'; import { join } from 'node:path'; import { agentStateDir } from '../context/agentHome.js'; import { GoalRuntimeError } from './errors.js'; import type { Goal, GoalEvent, GoalScope } from './types.js'; function safeSegment(value: string): string { const readable = value.replace(/[^a-zA-Z0-9._-]/g, '-').slice(0, 48) || 'default'; const hash = createHash('sha256').update(value).digest('hex').slice(0, 10); return `${readable}-${hash}`; } export interface GoalStoreOptions { stateRoot?: string; lockTimeoutMs?: number; } export class GoalStore { private readonly root: string; private readonly lockTimeoutMs: number; constructor(options: GoalStoreOptions = {}) { this.root = options.stateRoot ?? join(agentStateDir(), 'goals'); this.lockTimeoutMs = options.lockTimeoutMs ?? 2_000; } directory(scope: GoalScope): string { return join( this.root, safeSegment(scope.workspaceId), safeSegment(scope.sessionId), ); } async read(scope: GoalScope): Promise { let snapshot: Goal | null = null; try { snapshot = JSON.parse( await readFile(join(this.directory(scope), 'current.json'), 'utf8'), ) as Goal; } catch (error) { if ( (error as NodeJS.ErrnoException).code !== 'ENOENT' && !(error instanceof SyntaxError) ) { throw error; } } const projected = this.project(scope, await this.readEvents(scope)); if (!projected) return snapshot; return !snapshot || projected.revision > snapshot.revision ? projected : snapshot; } async readEvents(scope: GoalScope): Promise { try { const raw = await readFile(join(this.directory(scope), 'events.jsonl'), 'utf8'); const lines = raw.split('\n'); const events: GoalEvent[] = []; for (const [index, line] of lines.entries()) { if (!line.trim()) continue; try { const parsed = JSON.parse(line) as GoalEvent | GoalEvent[]; events.push(...(Array.isArray(parsed) ? parsed : [parsed])); } catch (error) { // appendFile 崩溃最多可能留下最后一条不完整记录。旧的完整投影仍 // 可用;中间损坏则必须响亮失败,不能悄悄跳过历史。 const isLastRecord = lines.slice(index + 1).every((item) => !item.trim()); if (!isLastRecord || raw.endsWith('\n')) throw error; } } return events; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; } } private project(scope: GoalScope, events: GoalEvent[]): Goal | null { let goal: Goal | null = null; let lastRevision = 0; for (const event of events) { if (event.type === 'goal.created') { goal = { goalId: event.goalId, scope, source: event.source, status: 'active', revision: event.revision ?? 1, contracts: [event.contract], currentContractVersion: event.contract.version, attempts: [], createdBy: event.createdBy, acceptorHumanIds: event.acceptorHumanIds, createdAt: event.at, updatedAt: event.at, usage: { inputTokens: 0, outputTokens: 0, elapsedMs: 0 }, }; lastRevision = goal.revision; continue; } if (!goal || event.goalId !== goal.goalId) continue; const revision = event.revision ?? lastRevision + 1; if (event.type === 'goal.contract_revised') { goal.contracts = [ ...goal.contracts.filter((item) => item.version !== event.contract.version), event.contract, ]; goal.currentContractVersion = event.contract.version; } else if (event.type === 'goal.status_changed') { goal.status = event.to; goal.statusReason = event.reason; } else if (event.type === 'goal.attempt_started') { const index = goal.attempts.findIndex((item) => item.attemptId === event.attempt.attemptId); if (index >= 0) goal.attempts[index] = structuredClone(event.attempt); else goal.attempts.push(structuredClone(event.attempt)); } else if (event.type === 'goal.attempt_finished') { const attempt = goal.attempts.find((item) => item.attemptId === event.attemptId); if (attempt) { attempt.status = event.status; attempt.finishedAt = event.at; attempt.artifacts = event.artifacts; attempt.evidence = event.evidence; attempt.blocker = event.blocker; } } else if (event.type === 'goal.resources_recorded') { goal.usage.inputTokens += event.usage.inputTokens ?? 0; goal.usage.outputTokens += event.usage.outputTokens ?? 0; goal.usage.elapsedMs += event.usage.elapsedMs ?? 0; } goal.revision = Math.max(goal.revision, revision); goal.updatedAt = Math.max(goal.updatedAt, event.at); lastRevision = Math.max(lastRevision, revision); } return goal; } async mutate(scope: GoalScope, action: () => Promise): Promise { const dir = this.directory(scope); await mkdir(dir, { recursive: true }); const lockPath = join(dir, '.write.lock'); const deadline = Date.now() + this.lockTimeoutMs; let handle: Awaited> | null = null; while (handle === null) { try { handle = await open(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY); await handle.writeFile(`${process.pid}\n`, 'utf8'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; if (await this.clearStaleLock(lockPath)) continue; if (Date.now() >= deadline) { throw new GoalRuntimeError( 'GOAL_STORE_LOCKED', '当前 Session 的 Goal 正由另一个进程更新,请稍后重试。', ); } await new Promise((resolve) => setTimeout(resolve, 25)); } } try { return await action(); } finally { await handle.close().catch(() => undefined); await unlink(lockPath).catch(() => undefined); } } private async clearStaleLock(lockPath: string): Promise { try { const [raw, info] = await Promise.all([ readFile(lockPath, 'utf8'), stat(lockPath), ]); const pid = Number.parseInt(raw.trim(), 10); let alive = Number.isInteger(pid) && pid > 0; if (alive) { try { process.kill(pid, 0); } catch (error) { alive = (error as NodeJS.ErrnoException).code !== 'ESRCH'; } } if (alive && Date.now() - info.mtimeMs < 30_000) return false; await unlink(lockPath); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT'; } } async commit(scope: GoalScope, goal: Goal, events: GoalEvent[]): Promise { const dir = this.directory(scope); await mkdir(dir, { recursive: true }); if (events.length > 0) { await appendFile( join(dir, 'events.jsonl'), // 同一次 revision 的所有事件是一条 JSONL 记录,避免崩溃后只重放 // 半次状态变更。readEvents 仍兼容旧版逐事件记录。 `${JSON.stringify(events)}\n`, 'utf8', ); } const current = join(dir, 'current.json'); const temp = `${current}.${process.pid}.${goal.revision}.tmp`; await writeFile(temp, `${JSON.stringify(goal, null, 2)}\n`, 'utf8'); await rename(temp, current); } }