feat: connect controlled engines to owned Tasks, approvals and budget ledger
This commit is contained in:
@@ -15,6 +15,8 @@ import { parseTestEvidence } from '../check-runner.mjs';
|
||||
import { verifyPlanEvidence } from '../context/request-plan.mjs';
|
||||
import { repairToolPairs } from '../../server/store.mjs';
|
||||
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
|
||||
import { assertControlledInstallation } from '../engines/controlled-installation.mjs';
|
||||
import { verifyEngineInput, originalEngineRun, assertEngineWorkerResult } from '../../shared/contracts/engine-execution.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const sourceIdentity = source => Object.fromEntries(['root', 'head', 'reference', 'branch', 'gitDir', 'commonDir', 'indexSha256',
|
||||
@@ -81,6 +83,7 @@ export class WorkerManager {
|
||||
|| [...this.store.core.collaboration.values()].some(group => group.projectId === session.projectId && !COLLABORATION_CLOSED.has(group.status))) throw workerConflict('项目已有未收尾的父协作,请先完成或明确保留原成果。');
|
||||
const initial = structuredClone(this.store.config), config = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store) : initial;
|
||||
const definition = collaborationInput(input, config), project = this.store.project(session.projectId);
|
||||
const engine = definition.engine ? this.runtime.engineRunner().selected(definition.engine) : null;
|
||||
const temporaryId = randomUUID(), controller = new AbortController(), active = { sessionId: session.id, projectId: project.id, group: { children: [], status: 'planning' }, controller };
|
||||
active.promise = new Promise(resolve => { active.settle = resolve; });
|
||||
this.active.set(temporaryId, active);
|
||||
@@ -95,7 +98,7 @@ export class WorkerManager {
|
||||
const group = { schemaVersion: 1, id: randomUUID(), projectId: project.id, sessionId: session.id, taskId: session.taskId, runId: run.id,
|
||||
goal: definition.goal, budget: definition.budget, model: modelSnapshot(config), config: configView(config),
|
||||
source: { identity: sourceIdentity(source), changedPaths: source.changedPaths, dirty: source.dirty, scope: source.scope },
|
||||
children: definition.children.map(child => ({ ...child, id: randomUUID(), workspaceId: randomUUID(), projectId: randomUUID(), sessionId: randomUUID(), taskId: randomUUID() })),
|
||||
children: definition.children.map(child => ({ ...child, ...(engine ? { engine: structuredClone(engine) } : {}), id: randomUUID(), workspaceId: randomUUID(), projectId: randomUUID(), sessionId: randomUUID(), taskId: randomUUID() })),
|
||||
status: 'planned', requiresVerification: false, createdAt: at(), updatedAt: at(), startedAt: null, deadline: null, finishedAt: null,
|
||||
summary: '父子目标、范围、模型和预算已封存,尚未创建工作区或请求模型。', collection: null, merge: null };
|
||||
group.fingerprint = workerHash(collaborationSeal(group));
|
||||
@@ -141,7 +144,7 @@ export class WorkerManager {
|
||||
await this.initializeChild(group, child); this.save(session, group, 'workspace_registered');
|
||||
await this.faultInjector?.('workspace_registered', group, child); signal.throwIfAborted();
|
||||
}
|
||||
await this.sourceFor(group); group.status = 'ready'; group.summary = '两个独立工作区已核对,来源HEAD、索引和已有修改保持。可以开始受限子任务。';
|
||||
await this.sourceFor(group); group.status = 'ready'; group.summary = group.children.length + ' 个独立工作区已核对,来源HEAD、索引和已有修改保持。可以开始受限子任务。';
|
||||
} catch (error) {
|
||||
const uncertain = group.children.some(child => { const workspace = this.store.core.workspace.get(child.workspaceId); return workspace && (workspace.status !== 'ready'
|
||||
|| !this.store.core.worker.has(child.id) && this.store.sessions.get(child.sessionId)?.taskId); });
|
||||
@@ -195,11 +198,16 @@ export class WorkerManager {
|
||||
this.store.putRecord('worker', session, worker, 'worker.ready'); return worker;
|
||||
}
|
||||
configFor(group, worker) {
|
||||
if (worker.engine) {
|
||||
assertControlledInstallation(worker.engine);
|
||||
for (const job of this.store.core.engine_run.values()) if (job.workerId === worker.id) verifyEngineInput(this.store, this.store.session(worker.sessionId), job);
|
||||
}
|
||||
const initial = structuredClone(this.store.config), current = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store) : initial;
|
||||
if (JSON.stringify(modelSnapshot(current)) !== JSON.stringify(group.model)) throw workerConflict('模型连接或池快照已变化;不能在原协作中悄悄替换模型。');
|
||||
const usage = workerUsage(this.store, worker), remaining = group.deadline - Date.now();
|
||||
if (remaining <= 0) throw new BudgetExceeded('time_limit', '父协作总时限已用完,原任务与成果保留。');
|
||||
if (usage.accountedTokens >= worker.budget.maxTokens || usage.steps >= worker.budget.maxSteps || usage.toolCalls >= worker.budget.maxToolCalls) throw new BudgetExceeded('worker_budget', '子任务累计预算已用完,续接不能重置预算。');
|
||||
if (usage.accountedTokens >= worker.budget.maxTokens || usage.steps >= worker.budget.maxSteps || usage.toolCalls >= worker.budget.maxToolCalls
|
||||
|| worker.engine && usage.requests >= worker.budget.maxSteps) throw new BudgetExceeded('worker_budget', '子任务累计预算已用完,续接不能重置预算。');
|
||||
return { ...group.config, maxSteps: worker.budget.maxSteps - usage.steps, maxTaskTokens: worker.budget.maxTokens,
|
||||
maxRunTokens: worker.budget.maxTokens - usage.accountedTokens, maxRunDurationMs: remaining };
|
||||
}
|
||||
@@ -227,7 +235,7 @@ export class WorkerManager {
|
||||
group.requiresVerification = outcomes.some(outcome => outcome.status === 'rejected') || workers.some(worker => worker.requiresVerification || ['running', 'stopping'].includes(worker.status));
|
||||
group.status = group.requiresVerification ? 'unknown' : workers.every(worker => worker.status === 'completed') ? 'ready_to_collect'
|
||||
: workers.some(worker => this.store.session(worker.sessionId).status === 'needs_review') ? 'awaiting_review' : 'paused';
|
||||
group.summary = group.status === 'ready_to_collect' ? '两个子任务均有实际改动和当前通过的检查,等待父任务核对原成果。'
|
||||
group.summary = group.status === 'ready_to_collect' ? group.children.length + ' 个子任务均有实际改动和当前通过的检查,等待父任务核对原成果。'
|
||||
: group.status === 'awaiting_review' ? '子任务提案已保存,请分别审查应用后继续;完成状态以实际检查为准。' : '子任务已停止或需要处理,已完成结果保留。';
|
||||
} catch (error) { group.status = 'paused'; group.summary = this.runtime.provider.redact(error.message ?? String(error)); }
|
||||
session.status = group.status === 'awaiting_review' ? 'needs_review' : 'paused'; this.save(session, group, group.status); return group;
|
||||
@@ -263,7 +271,7 @@ export class WorkerManager {
|
||||
return worker;
|
||||
}
|
||||
uncertain(worker) {
|
||||
return ['tool', 'check_job', 'change_set', 'delivery_job'].flatMap(kind => [...this.store.core[kind].values()]
|
||||
return ['tool', 'check_job', 'change_set', 'delivery_job', 'engine_run'].flatMap(kind => [...this.store.core[kind].values()]
|
||||
.filter(value => value.taskId === worker.taskId && (value.requiresVerification || value.status === 'unknown' || value.state === 'unknown'))
|
||||
.map(value => ({ kind, id: value.id })));
|
||||
}
|
||||
@@ -283,6 +291,7 @@ export class WorkerManager {
|
||||
const baseline = this.baseline(session, worker), project = this.store.project(worker.projectId);
|
||||
await verifyWorkspaceProject(this.store, project);
|
||||
if (this.uncertain(worker).length) throw workerConflict('子任务仍有结果未知的工具、检查或文件批次');
|
||||
assertEngineWorkerResult(this.store, session, worker);
|
||||
if (session.changes.some(change => ['pending', 'conflict'].includes(change.status))) throw workerConflict('子任务仍有未审查改动');
|
||||
const before = new Map(baseline.files.map(file => [workerPathKey(file.path), file]));
|
||||
const { inspection, files: current } = await this.inventory(project), after = new Map(current.map(file => [workerPathKey(file.path), file]));
|
||||
@@ -546,6 +555,24 @@ export class WorkerManager {
|
||||
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null })) });
|
||||
}
|
||||
const session = this.store.sessions.get(child.sessionId);
|
||||
const engines = [];
|
||||
for (const job of this.store.core.engine_run.values()) if (job.taskId === child.taskId) {
|
||||
verifyEngineInput(this.store, session, job);
|
||||
if (job.reportArtifactId) originalEngineRun(this.store, session, job);
|
||||
const processInfo = job.process ?? job.native?.process;
|
||||
let tree = null;
|
||||
if (job.requiresVerification || job.status === 'unknown') {
|
||||
if (processInfo) {
|
||||
tree = await readOwnedProcessTree(processInfo);
|
||||
if (!tree.supported || tree.processes.length) throw workerConflict('原引擎进程树仍存活或无法核对,请先人工核对原创建身份;不会按历史PID停止。');
|
||||
}
|
||||
}
|
||||
engines.push({ id: job.id, status: job.status, requiresVerification: !!job.requiresVerification,
|
||||
inputArtifactId: job.inputArtifactId, inputSha256: job.inputSha256, reportArtifactId: job.reportArtifactId ?? null,
|
||||
reportSha256: job.reportSha256 ?? null, process: processInfo ?? null, remainingProcesses: tree?.processes ?? null,
|
||||
missingProcessIdentity: !processInfo && job.status === 'unknown', requests: job.requests, calls: job.calls,
|
||||
originalOutcome: job.originalOutcome ?? null, error: job.error ?? null });
|
||||
}
|
||||
const tools = [...this.store.core.tool.values()].filter(value => value.taskId === child.taskId && value.requiresVerification).map(tool => {
|
||||
const call = session?.providerMessages.flatMap(message => message.tool_calls ?? []).find(call => call.id === tool.callId);
|
||||
const input = call?.function.arguments;
|
||||
@@ -562,7 +589,7 @@ export class WorkerManager {
|
||||
children.push({ id: child.id, workspaceId: child.workspaceId, workspaceStatus: workspace?.status ?? 'absent',
|
||||
workerStatus: worker?.status ?? 'absent', taskId: child.taskId, sessionId: child.sessionId, projectId: child.projectId,
|
||||
inventoryFingerprint: inventory ? workerHash(inventory.files) : null, sourceFingerprint: inventory?.inspection.sourceFingerprint ?? null, inventoryError,
|
||||
tools, checks, changes, changeSets: [...this.store.core.change_set.values()].filter(set => set.taskId === child.taskId).map(set => ({ id: set.id, status: set.status, requiresVerification: !!set.requiresVerification, observationFingerprint: set.observationFingerprint ?? null })) });
|
||||
tools, checks, changes, ...(engines.length ? { engines } : {}), changeSets: [...this.store.core.change_set.values()].filter(set => set.taskId === child.taskId).map(set => ({ id: set.id, status: set.status, requiresVerification: !!set.requiresVerification, observationFingerprint: set.observationFingerprint ?? null })) });
|
||||
}
|
||||
const parent = this.store.session(group.sessionId);
|
||||
return { schemaVersion: 1, kind: 'worker-recovery-observation', collaborationId: group.id, groupFingerprint: group.fingerprint,
|
||||
@@ -612,10 +639,15 @@ export class WorkerManager {
|
||||
if (!retain && !merged && JSON.stringify(current.source) !== JSON.stringify(group.source.identity)) throw workerConflict('父来源已经变化,只能明确保留现场后重新规划。');
|
||||
if (current.children.some(child => !['ready', 'absent', 'prepared', 'discarded', 'resolved_external'].includes(child.workspaceStatus))) throw workerConflict('原工作区仍需专门核对,不能开始子执行或结束恢复。');
|
||||
if (!retain && current.children.some(child => ['discarded', 'resolved_external'].includes(child.workspaceStatus))) throw workerConflict('原工作区没有核对为可执行,只能明确保留现场结束。');
|
||||
if (!retain && current.children.some(child => child.engines?.some(job => job.missingProcessIdentity))) throw workerConflict('引擎原进程创建身份没有封存,只能人工处理后明确保留现场结束。');
|
||||
if (!retain) await this.recoverMerge(session, group);
|
||||
for (const child of group.children) {
|
||||
const worker = this.store.core.worker.get(child.id); if (!worker) continue;
|
||||
const childSession = this.store.session(child.sessionId);
|
||||
for (const job of this.store.core.engine_run.values()) if (job.taskId === child.taskId && job.requiresVerification) {
|
||||
job.review = { source: 'user', evidenceSha256, reviewedAt: at(), result: 'unknown-preserved' };
|
||||
job.status = 'resolved_external'; job.requiresVerification = false;
|
||||
}
|
||||
for (const tool of this.store.core.tool.values()) if (tool.taskId === child.taskId && tool.requiresVerification) {
|
||||
tool.originalState = tool.state; tool.state = 'resolved_external'; tool.requiresVerification = false;
|
||||
tool.review = { source: 'user', evidenceSha256, reviewedAt: at(), result: 'unknown-preserved' };
|
||||
|
||||
Reference in New Issue
Block a user