import { createHash } from 'node:crypto'; import { isId } from './execution.mjs'; export const TASK_PLAN_LIMITS = Object.freeze({ steps: 12, text: 6000, revisions: 24 }); export const PLAN_READ_TOOLS = ['inspect_project', 'read_file', 'list_files', 'search_files', 'index_project', 'query_code', 'read_research_evidence', 'inspect_engine_checks', 'read_browser_result']; export const planHash = value => createHash('sha256').update(typeof value === 'string' || Buffer.isBuffer(value) ? value : JSON.stringify(value)).digest('hex'); export const planError = (message, code = 'invalid', status = 409) => Object.assign(new Error(message), { status, code }); const object = value => value && typeof value === 'object' && !Array.isArray(value); const keyPattern = /^[a-z][a-z0-9_-]{0,39}$/; const text = (value, max, label) => { if (typeof value !== 'string' || !value.trim() || value.length > max || /\0/.test(value)) throw planError(label + '需要1–' + max + '字文本。', 'input', 400); return value.trim(); }; const unique = (values, label, max = 32) => { if (!Array.isArray(values) || values.length > max || values.some(value => typeof value !== 'string' || !value || value.length > 160) || new Set(values).size !== values.length) throw planError(label + '需要不重复的文本列表。', 'input', 400); return [...values]; }; export function taskPlanInput(input) { if (!object(input) || Object.keys(input).some(key => !['expected_revision', 'steps'].includes(key)) || !Number.isSafeInteger(input.expected_revision) || input.expected_revision < 0) throw planError('任务计划需要expected_revision和steps,不能添加执行命令或完成状态。', 'input', 400); if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > TASK_PLAN_LIMITS.steps) throw planError('任务计划需要1–12个步骤。', 'input', 400); const steps = input.steps.map(value => { if (!object(value) || Object.keys(value).some(key => !['key', 'title', 'criterion', 'kind', 'depends_on', 'tools', 'paths', 'checks', 'viewport_width', 'actions'].includes(key)) || typeof value.key !== 'string' || !keyPattern.test(value.key) || !['analysis', 'changes', 'results', 'checks', 'browser'].includes(value.kind)) throw planError('步骤需要key、title、criterion和有效证据类别。', 'input', 400); const step = { key: value.key, title: text(value.title, 100, '步骤标题'), criterion: text(value.criterion, 300, '通过条件'), kind: value.kind, depends_on: unique(value.depends_on ?? [], '前置依赖', TASK_PLAN_LIMITS.steps).sort() }; const allowed = value.kind === 'analysis' ? ['tools'] : ['changes', 'results'].includes(value.kind) ? ['paths'] : value.kind === 'checks' ? ['checks'] : ['viewport_width', 'actions']; if (['tools', 'paths', 'checks', 'viewport_width', 'actions'].some(key => value[key] !== undefined && !allowed.includes(key))) throw planError('步骤证据字段与类别不一致。', 'input', 400); if (value.kind === 'analysis') { step.tools = unique(value.tools, '读取工具', PLAN_READ_TOOLS.length).sort(); if (!step.tools.length || step.tools.some(tool => !PLAN_READ_TOOLS.includes(tool))) throw planError('工程读取只能引用已声明的实际只读工具。', 'input', 400); } else if (['changes', 'results'].includes(value.kind)) { step.paths = unique(value.paths, '文件范围').sort(); if (!step.paths.length || step.paths.some(file => /[\\:\0]/.test(file) || file.startsWith('/') || file.split('/').some(part => !part || part === '..' || ['.git', '.hg', '.svn'].includes(part)))) throw planError('源码步骤需要项目内常规相对文件路径。', 'input', 400); } else if (value.kind === 'checks') { step.checks = unique(value.checks, '检查名称', 6).sort(); if (!step.checks.length) throw planError('检查步骤必须固定至少一个实际检查名称。', 'input', 400); } else { if (!Number.isSafeInteger(value.viewport_width) || value.viewport_width < 320 || value.viewport_width > 1440) throw planError('页面步骤需要320–1440像素的固定视口宽度。', 'input', 400); step.viewport_width = value.viewport_width; step.actions = unique(value.actions ?? [], '页面必要操作', 6).sort(); if (step.actions.some(action => !['fill', 'select', 'click', 'assert_text', 'assert_count', 'assert_visible'].includes(action))) throw planError('页面必要操作无效。', 'input', 400); } return step; }); const keys = new Set(steps.map(step => step.key)); if (keys.size !== steps.length) throw planError('步骤key必须唯一。', 'input', 400); for (const step of steps) if (step.depends_on.some(key => !keys.has(key) || key === step.key)) throw planError('前置步骤必须存在,且不能引用自己。', 'input', 400); const visiting = new Set(), done = new Set(); const walk = key => { if (visiting.has(key)) throw planError('任务步骤依赖不能形成循环。', 'input', 400); if (done.has(key)) return; visiting.add(key); for (const dependency of steps.find(step => step.key === key).depends_on) walk(dependency); visiting.delete(key); done.add(key); }; for (const step of steps) walk(step.key); if (steps.reduce((sum, step) => sum + step.title.length + step.criterion.length, 0) > TASK_PLAN_LIMITS.text) throw planError('计划文本超过保留预算,请缩小单个任务范围。', 'input', 400); return { expected_revision: input.expected_revision, steps }; } export function taskProofInput(input) { if (!object(input) || Object.keys(input).some(key => !['plan_id', 'step_key', 'evidence_id', 'expected_revision'].includes(key)) || !isId(input.plan_id) || typeof input.step_key !== 'string' || !keyPattern.test(input.step_key) || !isId(input.evidence_id) || !Number.isSafeInteger(input.expected_revision) || input.expected_revision < 1) throw planError('核验需要当前计划ID、步骤key、原证据ID和expected_revision,不能传入完成结论。', 'input', 400); return { ...input }; } export const taskRequirements = task => ({ goal: task.goal, instructions: (task.instructions ?? []).filter(value => value.source !== 'review-action') .map(value => ({ id: value.id, content: value.content, ...(value.source ? { source: value.source } : {}) })), constraints: task.constraints ?? [], acceptance: task.acceptance ?? [], workspace: task.workspaceIdentity ?? null }); export const taskPlanContract = plan => ({ schemaVersion: 1, kind: 'task-plan-contract', id: plan.id, sessionId: plan.sessionId, projectId: plan.projectId, taskId: plan.taskId, runId: plan.runId, revision: plan.revision, parentPlanId: plan.parentPlanId, createdAt: plan.createdAt, requirements: plan.requirements, requirementsSha256: plan.requirementsSha256, steps: plan.steps }); export const taskProofContract = proof => ({ schemaVersion: 1, kind: 'task-step-proof', id: proof.id, sessionId: proof.sessionId, projectId: proof.projectId, taskId: proof.taskId, runId: proof.runId, planId: proof.planId, stepKey: proof.stepKey, stepSha256: proof.stepSha256, planContractSha256: proof.planContractSha256, requirementsSha256: proof.requirementsSha256, status: proof.status, evidenceId: proof.evidenceId, outcome: proof.outcome, error: proof.error, createdAt: proof.createdAt });