-
工程执行 / 分工与引擎
一个目标,独立执行与审查
范围和预算固定,成果核对后进入父工程审查。
+
工程执行 / 分工与引擎
一个目标,明确分工与真实成果
为每个子任务绑定职责与模型,核对真实改动、检查和用量后归集到父工程。
{error &&
{error}
}
{loading && !view &&
正在读取当前任务记录
}
{view?.worker ?
当前是受限子任务:{view.worker.label}
固定范围:{view.worker.paths.join('、')}。开始、停止全部与成果合并在父目标中处理。
: <>
{!!view?.groups.length &&
}
{(!group || creating) &&
-
- {engineMode === 'deepseek' &&
{engineInstallation && {engineReady ? '受控安装可用' : '安装尚不可用'}{engineInstallation.message}
{engineReady &&
Harness {engineInstallation.version} · {engineInstallation.controlledSha256?.slice(0, 16)}}
}模型连接由工作台使用;引擎只提交范围内的提案与检查请求,应用和检查仍需审查。
}
+
+ {engineMode === 'deepseek' &&
{engineInstallation && {engineReady ? '受控安装可用' : '安装尚不可用'}{engineInstallation.message}
{engineReady &&
Harness {engineInstallation.version} · {engineInstallation.controlledSha256?.slice(0, 16)}}
}模型连接由工作台使用;引擎提交范围内的提案与检查请求,按所选访问权限执行。
}
{engineMode === 'deepseek' &&
{ setPurge(value); setError(''); }} busy={!!action} harnessRoot={engineInstallation?.root} />}
- {visibleDrafts.map((child, index) =>
)}
-
- {engineMode === 'deepseek' ? '这个引擎工程使用整份预算。' : '两份预算各分一半。'}续接沿用累计用量与原时限,实际模型尝试也计入轮次限制。来源只检出已提交 HEAD。
- {creating && }
+ {visibleDrafts.map((child, index) =>
)}
+ {openMode && engineMode === 'workbench' && }
+ {!openMode && }
+ {openMode ? '本地额度不限;模型和原生参数在规划时固定,切换新任务默认模型不会改变本计划。' : <>{engineMode === 'deepseek' ? '这个引擎工程使用整份预算。' : '两份预算各分一半。'}续接沿用累计用量与原时限,实际模型尝试也计入轮次限制。来源只检出已提交 HEAD。>}
+ {creating && }
}
{group && !creating && <>
{group.children[0]?.engine?.strategy &&
本计划的 Purge {group.children[0].engine.strategy.kind==='purge-original-restricted-v1'?'原版受限模式':'提示实验'} · {group.children[0].engine.strategy.source.version} · {group.children[0].engine.strategy.sha256.slice(0, 16)}
}
- {group.evaluation &&
本协作属于固定工程评测。执行与采纳请使用「工程评测」;这里保留原任务导航和中断现场核对。
}
{statusLabel(group.status, openGroup, group.merge?.status === 'applied')}{group.source.identity.branch} · {group.source.identity.head.slice(0, 12)}
{group.goal}
{group.summary}
- 模型
- {group.model.mode === 'demo' ? '离线演示' : group.model.model}
- 执行方式
- {group.children[0].engine ? "DeepSeek Harness " + group.children[0].engine.version : "工作台受限子任务"}
- 总预算
- {openGroup ? '不限' : <>{number(group.budget.maxTokens)} tokens / {group.budget.maxSteps} 轮 / {group.budget.maxToolCalls} 次工具>}
- 累计用量
- {number(group.usage?.accountedTokens)} tokens / {group.usage?.steps ?? 0} 轮 / {group.usage?.toolCalls ?? 0} 次工具 / {group.usage?.requests ?? 0} 次模型请求
- 原修改
- {group.source.changedPaths.length ? group.source.changedPaths.map(value => value.path).join('、') : '无未提交修改'}
-
{(group.workers ?? []).map((child, index) =>
通道 {index + 1}{statusLabel(child.sessionStatus === 'awaiting_approval' ? 'awaiting_approval' : child.status)}
{child.label}
{child.engine && DeepSeek Harness {child.engine.version} · 固定安装 {child.engine.controlledSha256?.slice(0, 12)}
}{child.goal}
允许修改{child.paths.map(path => {path})}
{number(child.usage?.accountedTokens)} / {number(child.budget.maxTokens)} tokens · {child.usage?.steps ?? 0}/{child.budget.maxSteps} 轮
{child.summary ?? '先创建独立工作区,再开始子任务。'}
{child.result && {child.result.paths.length} 个原改动 · 当前检查已封存
}{child.status !== 'unprepared' &&
}{!group.evaluation && ['ready', 'paused', 'failed', 'awaiting_review'].includes(child.status) && !running && child.sessionStatus !== 'needs_review' &&
}
)}
+ {group.evaluation &&
本协作属于固定工程评测。执行与采纳请使用「工程评测」;这里保留原任务导航和中断现场核对。
}
{statusLabel(group.status, openGroup, group.merge?.status === 'applied')}{group.source.identity.branch} · {group.source.identity.head.slice(0, 12)}
{group.goal}
{group.summary}
- 模型
- {group.children.some(child => child.assignment) ? '按子任务分别绑定,见下方' : group.model.mode === 'demo' ? '历史演示配置' : group.model.model}
- 执行方式
- {group.children[0].engine ? "DeepSeek Harness " + group.children[0].engine.version : "工作台受限子任务"}
- 总预算
- {openGroup ? '不限' : <>{number(group.budget.maxTokens)} tokens / {group.budget.maxSteps} 轮 / {group.budget.maxToolCalls} 次工具>}
- 累计用量
- {number(group.usage?.totalTokens ?? group.usage?.accountedTokens)} 已报告 tokens{group.usage?.unknownRequests ? <> + {group.usage.unknownRequests} 次用量未知(估算 {number(group.usage.estimatedUnknownTokens)})> : null} / {group.usage?.steps ?? 0} 轮 / {group.usage?.toolCalls ?? 0} 次工具 / {group.usage?.requests ?? 0} 次模型请求
- 原修改
- {group.source.changedPaths.length ? group.source.changedPaths.map(value => value.path).join('、') : '无未提交修改'}
+
{(group.workers ?? []).map((child, index) =>
通道 {index + 1}{statusLabel(child.sessionStatus === 'awaiting_approval' ? 'awaiting_approval' : child.status)}
{child.label}
{child.engine && DeepSeek Harness {child.engine.version} · 固定安装 {child.engine.controlledSha256?.slice(0, 12)}
}{child.assignment && {child.assignment.role}{child.assignment.model.model} · {child.assignment.selection?.type === 'pool' ? '模型池' : '固定连接'}{child.assignment.selectionSource === 'explicit' ? '独立选择' : '规划时的默认选择'} · 原配置已封存
}{child.goal}
{!!child.assignment?.requirements.length && {child.assignment.requirements.map((value, i) => - {value}
)}
}允许修改{child.paths.map(path => {path})}
{number(child.usage?.totalTokens)} 已报告 tokens · {child.usage?.steps ?? 0} 轮{child.usage?.unknownRequests ? <> · {child.usage.unknownRequests} 次用量未知(估算 {number(child.usage.estimatedUnknownTokens)})> : null}{!openGroup && <> · 预算 {number(child.budget.maxTokens)}>}
{child.summary ?? '先创建独立工作区,再开始子任务。'}
{child.result && {child.result.paths.length} 个原改动 · {child.result.checkJobId ? '当前检查已封存' : '检查未验证'}{child.result.quality && ' · 要求语义未评价'}
}{child.status !== 'unprepared' &&
}{!group.evaluation && ['ready', 'paused', 'failed', 'awaiting_review'].includes(child.status) && !running && child.sessionStatus !== 'needs_review' &&
}
)}
{openGroup ? '父工程成果' : '父工程成果审查'}
{group.collection ? <>{group.collection.paths.length} 个路径已核对,原记录 {group.collection.sha256.slice(0, 16)}
{group.collection.conflicts.length > 0 && {group.collection.conflicts.map((conflict, i) => {conflict.path}{conflict.reason} )}
}> : 等待 {group.children.length} 个子任务形成实际成果。重叠路径、来源变化或原证据失效会阻止合并。
}{group.merge?.changeSetId && }
- {!group.evaluation && ['planned', 'partially_prepared'].includes(group.status) &&
}
- {!group.evaluation && ['ready', 'paused', 'awaiting_review'].includes(group.status) &&
}
+ {!group.evaluation && ['planned', 'partially_prepared'].includes(group.status) &&
}
+ {!group.evaluation && ['ready', 'paused', 'awaiting_review'].includes(group.status) &&
}
{running &&
}
{!group.evaluation && ['ready_to_collect', 'collected', 'conflict'].includes(group.status) &&
}
{!group.evaluation && group.status === 'collected' &&
}
@@ -119,7 +125,7 @@ export function WorkerPanel({ session, config, busy, onSession, onNavigate, onRe
{!running && !group.requiresVerification && !['completed', 'discarded', 'resolved_external'].includes(group.status) &&
}
{canPlan &&
}
- {config.mode === 'demo' && ['ready', 'paused'].includes(group.status) &&
当前为离线演示。请先配置可用模型,再新建使用该模型快照的协作计划。
}
+ {group.children.some(child => (child.assignment?.model ?? group.model).mode === 'demo') && ['ready', 'paused'].includes(group.status) &&
当前为离线演示。请先配置可用模型,再新建使用该模型快照的协作计划。
}
>}
>}
独立工作区与受限工具用于约束任务;审批的工程程序仍以本机账户执行。
diff --git a/src/client/types.ts b/src/client/types.ts
index f2df8fcd..23763d4e 100644
--- a/src/client/types.ts
+++ b/src/client/types.ts
@@ -297,11 +297,13 @@ export interface RequirementDraft {
}
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
-export interface WorkerDefinition { id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }
+export interface WorkerAssignment { schemaVersion: number; role: string; requirements: string[]; selection: { type: string; id: string } | null; selectionSource: string; model: ModelSnapshot }
+export interface WorkerQuality { role: string; checks: { status: string; checkJobId: string | null }; requirements: { criterion: string; status: string }[] }
+export interface WorkerDefinition { assignment?: WorkerAssignment; id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }
export interface WorkerRecord extends WorkerDefinition {
collaborationId: string; parentProjectId: string; parentSessionId: string; parentTaskId: string; parentRunId: string;
runId: string; currentRunId: string | null; runIds: string[]; baseCommit: string; fingerprint: string; status: string; requiresVerification: boolean;
- startedAt: string | null; finishedAt: string | null; summary: string; result: { artifactId: string; sha256: string; checkJobId: string; paths: string[] } | null;
+ startedAt: string | null; finishedAt: string | null; summary: string; result: { artifactId: string; sha256: string; checkJobId: string | null; paths: string[]; quality?: WorkerQuality } | null;
usage?: Usage & { accountedTokens: number; steps: number; toolCalls: number }; sessionStatus?: string;
}
export interface WorkerConflict { path: string; reason: string; workerIds: string[] }
@@ -310,7 +312,7 @@ export interface CollaborationGroup {
status: string; phase?: string; requiresVerification: boolean; summary: string; createdAt: string; startedAt: string | null; finishedAt: string | null; deadline: number | null;
model: { mode: string; model: string; baseUrl: string; executionMode?: 'unrestricted' | 'restricted' }; budget: WorkerBudget & { maxDurationMs: number };
source: { identity: { root: string; head: string; branch: string; indexSha256: string }; dirty: boolean; changedPaths: { path: string; status: string }[] };
- children: WorkerDefinition[]; workers?: WorkerRecord[]; usage?: { accountedTokens: number; steps: number; toolCalls: number; requests?: number; unknownRequests: number };
+ children: WorkerDefinition[]; workers?: WorkerRecord[]; usage?: { accountedTokens: number; steps: number; toolCalls: number; requests?: number; unknownRequests: number; totalTokens?: number; estimatedUnknownTokens?: number };
collection: { artifactId: string; sha256: string; conflicts: WorkerConflict[]; paths: string[] } | null;
merge: { status?: string; changeSetId?: string; fingerprint?: string; changeIds?: string[] } | null;
evidence?: { artifactId: string; sha256: string } | null;
diff --git a/src/core/tasks/worker-evidence.mjs b/src/core/tasks/worker-evidence.mjs
new file mode 100644
index 00000000..a5e776f1
--- /dev/null
+++ b/src/core/tasks/worker-evidence.mjs
@@ -0,0 +1,54 @@
+import { workerHash, workerConflict, workerForSession, workerUsage } from '../../shared/contracts/workers.mjs';
+import { verifyPlanEvidence } from '../context/request-plan.mjs';
+
+function dispatchRecord(store, worker, run, plan) {
+ const group = store.core.collaboration.get(worker.collaborationId);
+ const context = store.owned('artifact', plan.artifactId, worker.sessionId);
+ return { schemaVersion: 1, phase: 'prepared', preparedAt: plan.createdAt,
+ workerId: worker.id, workerFingerprint: worker.fingerprint, collaborationId: group.id, groupFingerprint: group.fingerprint,
+ assignmentSha256: workerHash(worker.assignment), projectId: worker.projectId, sessionId: worker.sessionId, taskId: worker.taskId,
+ runId: run.id, stepId: plan.stepId, contextPlanId: plan.id, contextArtifactId: context.id, contextSha256: context.sha256,
+ requestArtifactId: plan.requestArtifactId, requestSha256: plan.requestSha256,
+ toolSurfaceGeneration: plan.requestObservation?.toolSurface?.generation ?? null,
+ model: run.model, budget: run.budget };
+}
+
+// This is preparation evidence. Fetch submission and consumption retain their
+// original identities; a prepared artifact never proves a request was sent.
+export function sealWorkerDispatch(store, session, worker, run, plan) {
+ if (!worker.assignment) return;
+ workerForSession(store, session);
+ const record = dispatchRecord(store, worker, run, plan);
+ const artifact = store.artifactStore.write(session, run, record, { kind: 'worker-dispatch' });
+ store.core.artifact.set(artifact.id, artifact);
+ plan.workerDispatch = { artifactId: artifact.id, sha256: artifact.sha256 };
+ store.save(session, { type: 'worker.dispatch_prepared' });
+}
+
+export function workerQuality(store, session, worker, files, check) {
+ const cache = new Map();
+ const requests = [...store.core.context_plan.values()].filter(plan => plan.taskId === worker.taskId).map(plan => {
+ verifyPlanEvidence(store, session, plan, cache);
+ const run = store.owned('run', plan.runId, session.id), ref = plan.workerDispatch;
+ if (!ref) throw workerConflict('原子任务请求缺少派发准备证据。');
+ const artifact = store.owned('artifact', ref.artifactId, session.id);
+ if (artifact.kind !== 'worker-dispatch' || artifact.taskId !== worker.taskId || artifact.runId !== run.id || artifact.sha256 !== ref.sha256
+ || store.artifactStore.read(artifact) !== JSON.stringify(dispatchRecord(store, worker, run, plan))) throw workerConflict('子任务派发身份、上下文或工具代次与原工件不一致。');
+ return { contextPlanId: plan.id, runId: run.id, dispatch: ref, phase: 'prepared', requestArtifactId: plan.requestArtifactId,
+ requestSha256: plan.requestSha256, toolSurfaceGeneration: plan.requestObservation?.toolSurface?.generation ?? null,
+ status: plan.status, attempts: plan.requestAttempts, error: plan.error ?? null };
+ });
+ const runs = worker.runIds.map(id => {
+ const run = store.owned('run', id, session.id);
+ if (run.taskId !== worker.taskId) throw workerConflict('子任务执行账本归属已变化。');
+ return { id, model: run.model, status: run.status, stopReason: run.stopReason, startedAt: run.startedAt,
+ finishedAt: run.finishedAt, elapsedMs: run.finishedAt ? Date.parse(run.finishedAt) - Date.parse(run.startedAt) : null,
+ usage: run.usage, consumption: run.consumption ?? [] };
+ });
+ return { schemaVersion: 1, role: worker.assignment.role, model: worker.assignment.model,
+ requirements: [worker.goal, ...worker.assignment.requirements].map(criterion => ({ criterion, status: 'not_evaluated', source: 'sealed_assignment' })),
+ changes: files.map(file => ({ path: file.path, beforeSha256: file.beforeSha256, sha256: file.sha256, changeIds: file.changeIds })),
+ checks: { status: check ? 'current_passed' : 'not_verified', checkJobId: check?.id ?? null },
+ usage: workerUsage(store, worker), requests, runs,
+ scope: 'Verified change bytes and current check evidence; requirement semantics and collaboration benefit have not been evaluated.' };
+}
diff --git a/src/core/tasks/worker-manager.mjs b/src/core/tasks/worker-manager.mjs
index 50f95800..41d67de6 100644
--- a/src/core/tasks/worker-manager.mjs
+++ b/src/core/tasks/worker-manager.mjs
@@ -19,12 +19,17 @@ import { readOwnedProcessTree } from '../owned-process-tree.mjs';
import { assertControlledInstallation } from '../engines/controlled-installation.mjs';
import { verifyEngineInput, originalEngineRun, assertEngineWorkerResult } from '../../shared/contracts/engine-execution.mjs';
import { verifyEvaluationSources } from '../evaluation/provenance.mjs';
+import { workerQuality } from './worker-evidence.mjs';
const at = () => new Date().toISOString();
const sourceIdentity = source => Object.fromEntries(['root', 'head', 'reference', 'branch', 'gitDir', 'commonDir', 'indexSha256',
'statusSha256', 'sourceFingerprint', 'treeSha256', 'configuration', 'filterDrivers'].map(key => [key, source[key]]));
-const configView = config => Object.fromEntries(['mode', 'baseUrl', 'model', 'contextLimit', 'maxOutputTokens', 'configRevision',
- 'executionMode', 'approvalMode', 'capacityMode', 'historyPolicy', 'maxSteps', 'maxRunDurationMs', 'maxRunTokens', 'maxTaskTokens', ...(config.protocol ? ['protocol', 'streaming'] : []), ...(config.modelRouting ? ['modelRouting'] : [])].map(key => [key, structuredClone(config[key])]));
+const configView = config => {
+ const { routing, ...snapshot } = modelSnapshot(config);
+ return { ...snapshot, ...(routing ? { modelRouting: routing } : {}),
+ ...(config.upstreamModel ? { upstreamModel: structuredClone(config.upstreamModel) } : {}),
+ ...Object.fromEntries(['maxSteps', 'maxRunDurationMs', 'maxRunTokens', 'maxTaskTokens'].map(key => [key, config[key]])) };
+};
const alive = pid => { if (!pid) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
export class WorkerManager {
@@ -84,8 +89,15 @@ export class WorkerManager {
if (workerForProject(this.store, session.projectId)) throw workerConflict('受限子任务不能创建嵌套协作。');
if (this.groups(session).some(group => !COLLABORATION_CLOSED.has(group.status))
|| [...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 initial = structuredClone(this.store.config), definition = collaborationInput(input, initial), project = this.store.project(session.projectId);
+ const assignments = definition.children.map(child => {
+ const selected = child.modelSelection;
+ const prepared = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig({ ...initial, ...(selected ? { mode: 'compatible' } : {}) }, this.store, selected) : initial;
+ return { schemaVersion: 1, role: child.role, requirements: child.requirements, selection: prepared.modelRouting
+ ? { type: prepared.modelRouting.type, id: prepared.modelRouting.id } : null, selectionSource: selected ? 'explicit' : 'default_at_plan',
+ config: configView(prepared), model: modelSnapshot(prepared) };
+ });
+ const config = assignments[0].config;
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; });
@@ -102,7 +114,7 @@ export class WorkerManager {
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 },
...(evaluation ? { evaluation } : {}),
- children: definition.children.map((child, index) => ({ ...child, ...(engine ? { engine: structuredClone(engine) } : {}),
+ children: definition.children.map((child, index) => ({ ...child, assignment: assignments[index], ...(engine ? { engine: structuredClone(engine) } : {}),
...(evaluation ? { evaluation: { ...evaluation, role: index === 0 ? 'original' : 'candidate' } } : {}),
id: randomUUID(), workspaceId: randomUUID(), projectId: randomUUID(), sessionId: randomUUID(), taskId: randomUUID() })),
status: 'planned', requiresVerification: false, createdAt: at(), updatedAt: at(), startedAt: null, deadline: null, finishedAt: null,
@@ -174,7 +186,7 @@ export class WorkerManager {
const project = this.store.project(child.projectId), session = this.store.session(child.sessionId);
await verifyWorkspaceProject(this.store, project);
if (session.messages.length || session.changes.length) throw workerConflict('新工作区已有其他任务记录,不能覆盖其身份。');
- const config = { ...group.config, maxTaskTokens: child.budget.maxTokens };
+ const config = { ...(child.assignment?.config ?? group.config), maxTaskTokens: child.budget.maxTokens };
let task = this.store.core.task.get(session.taskId), run = this.store.core.run.get(session.runId);
if (session.taskId) {
if (task?.id !== child.taskId || task.goal !== child.goal || task.workerId !== child.id || task.origin !== 'isolated-worker'
@@ -182,7 +194,9 @@ export class WorkerManager {
} else {
task = createTask(session, child.goal, config); task.id = child.taskId; task.origin = 'isolated-worker'; task.workspaceIdentity = projectWorkspaceIdentity(project);
task.budget.maxTokens = child.budget.maxTokens; task.workerId = child.id;
- task.constraints = ['允许修改范围:' + child.paths.join('、'), '只接受原提案应用和当前工程检查;禁止独立Git提交、任意终端及外部工具。'];
+ task.constraints = ['允许修改范围:' + child.paths.join('、'), ...(child.assignment ? ['职责:' + child.assignment.role] : []),
+ unrestricted(config) ? '工程成果按原提案字节链回收;检查是否通过须有原日志。' : '只接受原提案应用和当前工程检查;禁止独立Git提交、任意终端及外部工具。'];
+ if (child.assignment) task.acceptance = [...child.assignment.requirements];
run = createRun(session, task, config); run.workspaceIdentity = projectWorkspaceIdentity(project);
this.store.core.task.set(task.id, task); this.store.core.run.set(run.id, run);
session.taskId = task.id; session.runId = run.id; session.status = 'paused'; this.store.finishRun(session, run, 'worker_prepared');
@@ -190,7 +204,7 @@ export class WorkerManager {
const { files, inspection } = await this.inventory(project), git = await this.workspaces.snapshot(project);
if (git.head !== group.source.identity.head || git.dirty) throw workerConflict('子工作区初始HEAD或源码不符合封存来源。');
const worker = { schemaVersion: 1, ...child, collaborationId: group.id, parentProjectId: group.projectId, parentSessionId: group.sessionId,
- parentTaskId: group.taskId, parentRunId: group.runId, baseCommit: group.source.identity.head, model: group.model,
+ parentTaskId: group.taskId, parentRunId: group.runId, baseCommit: group.source.identity.head, model: child.assignment?.model ?? group.model,
runId: run.id, currentRunId: null, status: 'ready', requiresVerification: false, runIds: [], startedAt: null, finishedAt: null,
ownerPid: null, summary: '独立工作区与原始源码已封存,尚未请求模型。', result: null };
const baseline = this.store.artifactStore.write(session, run, { schemaVersion: 1, workerId: worker.id, collaborationId: group.id,
@@ -208,14 +222,16 @@ export class WorkerManager {
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('模型连接或池快照已变化;不能在原协作中悄悄替换模型。');
- if (unrestricted(group.config)) return { ...group.config, maxSteps: 0, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0 };
+ const frozen = worker.assignment?.config ?? group.config;
+ const initial = structuredClone(worker.assignment ? frozen : this.store.config);
+ const current = this.runtime.provider.prepareConfig ? this.runtime.provider.prepareConfig(initial, this.store, worker.assignment?.selection ?? undefined) : initial;
+ if (JSON.stringify(modelSnapshot(current)) !== JSON.stringify(worker.assignment?.model ?? group.model)) throw workerConflict('原子任务的模型连接、模型池或凭据修订已变化;不会替换原绑定,请保留原记录并新建分工。');
+ if (unrestricted(frozen)) return { ...frozen, maxSteps: 0, maxRunDurationMs: 0, maxRunTokens: 0, maxTaskTokens: 0 };
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
|| 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,
+ return { ...frozen, maxSteps: worker.budget.maxSteps - usage.steps, maxTaskTokens: worker.budget.maxTokens,
maxRunTokens: worker.budget.maxTokens - usage.accountedTokens, maxRunDurationMs: remaining };
}
start(session, id, fingerprint, workerId = null) {
@@ -244,7 +260,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.children.length + ' 个子任务均有实际改动和当前通过的检查,等待父任务核对原成果。'
+ 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;
@@ -269,7 +285,7 @@ export class WorkerManager {
const output = await this.output(session, worker);
const artifact = this.store.artifactStore.write(session, this.store.owned('run', worker.currentRunId, session.id), output, { kind: 'worker-result' });
this.store.core.artifact.set(artifact.id, artifact);
- worker.result = { artifactId: artifact.id, sha256: artifact.sha256, fingerprint: workerHash(output), checkJobId: output.check?.id ?? null, paths: output.files.map(file => file.path) };
+ worker.result = { artifactId: artifact.id, sha256: artifact.sha256, fingerprint: workerHash(output), checkJobId: output.check?.id ?? null, paths: output.files.map(file => file.path), ...(output.quality ? { quality: output.quality } : {}) };
worker.status = 'completed'; worker.summary = '实际改动与原检查证据已封存,等待父任务归集。';
} else worker.summary = unknown.length ? '执行结果或原进程待核对,不会重放。' : session.failure?.message ?? '原子任务已保存,等待审查或继续。';
} catch (error) {
@@ -360,7 +376,8 @@ export class WorkerManager {
id: result.id, name: result.name, tests: result.tests, exitCode: result.exitCode, logArtifactId: result.logArtifactId,
logSha256: this.store.owned('artifact', result.logArtifactId, session.id).sha256,
...(result.metricsArtifactId ? { metricsArtifactId: result.metricsArtifactId, metricsSha256: result.metricsSha256 } : {}),
- })) } : null, usage: workerUsage(this.store, worker), runIds: worker.runIds };
+ })) } : null, usage: workerUsage(this.store, worker), runIds: worker.runIds,
+ ...(worker.assignment ? { quality: workerQuality(this.store, session, worker, files, check) } : {}) };
}
async verifiedResult(group, child) {
const worker = this.store.core.worker.get(child.id), session = this.store.session(child.sessionId);
@@ -414,7 +431,7 @@ export class WorkerManager {
return { schemaVersion: 1, collaborationId: group.id, groupFingerprint: group.fingerprint, projectId: group.projectId,
sessionId: session.id, taskId: group.taskId, runId: group.runId, source: group.source.identity,
workers: proofs.map(proof => ({ workerId: proof.worker.id, artifactId: proof.artifact.id, sha256: proof.artifact.sha256, fingerprint: proof.worker.fingerprint,
- checkJobId: proof.output.check?.id ?? null, paths: proof.output.files.map(file => file.path) })),
+ checkJobId: proof.output.check?.id ?? null, paths: proof.output.files.map(file => file.path), ...(proof.output.quality ? { quality: proof.output.quality } : {}) })),
paths: all.map(file => file.path).sort(), conflicts, targets: targets.sort((a, b) => a.path.localeCompare(b.path)) };
}
collect(session, id, fingerprint, { evaluation = false } = {}) {
diff --git a/src/server/provider.mjs b/src/server/provider.mjs
index 9309f622..32f5d114 100644
--- a/src/server/provider.mjs
+++ b/src/server/provider.mjs
@@ -164,7 +164,7 @@ export class Provider {
}
resumeRequests() { this.requestsClosing = false; if (this.hub?.networkChecks) this.hub.networkChecks.closing = false; }
modelHub(store) { return this.hub ??= new ModelHub(store, this); }
- prepareConfig(config, store) { return this.modelHub(store).prepare(config); }
+ prepareConfig(config, store, selection) { return this.modelHub(store).prepare(config, selection); }
redact(value, key = this.apiKey) {
let text = String(value);
for (const secret of [key, this.apiKey, ...[...(this.credentials?.values() ?? [])].map(value => value.key)].filter(Boolean).sort((a, b) => b.length - a.length)) {
diff --git a/src/server/runtime.mjs b/src/server/runtime.mjs
index f7cd9668..2f251c3f 100644
--- a/src/server/runtime.mjs
+++ b/src/server/runtime.mjs
@@ -64,6 +64,7 @@ import { SkillRegistry, skillToolDefinitions, skillReadInput } from '../core/ski
import { McpRegistry } from '../core/tools/mcp-registry.mjs';
import { mcpToolDefinitions, mcpCallInput, assertMcpResolved } from '../core/tools/mcp-contract.mjs';
import { WorkerManager } from '../core/tasks/worker-manager.mjs';
+import { sealWorkerDispatch } from '../core/tasks/worker-evidence.mjs';
import { EvaluationManager } from '../core/evaluation/evaluation-manager.mjs';
import { WORKER_TOOLS, COLLABORATION_CLOSED, workerForSession, assertWorkerTool, assertWorkersResolved, workerUsage, workerConflict } from '../shared/contracts/workers.mjs';
@@ -426,7 +427,9 @@ export class Runtime {
const fixedRules = projectContext(run.project, { inventory: false, config: run.config });
const workerContract = run.worker ? '\n受限子任务执行契约(宿主权限,不可扩展):' + JSON.stringify({
parent_task_id: run.worker.parentTaskId, worker_id: run.worker.id, write_paths: run.worker.paths, budget: run.worker.budget,
- rule: '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
+ ...(run.worker.assignment ? { role: run.worker.assignment.role, requirements: run.worker.assignment.requirements } : {}),
+ rule: unrestricted(config) ? '成果以范围内的原提案字节链回收;检查通过须有当前日志,模型声明不证明要求达成。'
+ : '只有范围内提案、审查应用和当前工程检查构成完成;不得请求任意终端、独立Git提交、外部工具或嵌套协作。',
}) : '';
const fixedContext = fixedRules + workerContract;
const context = this.provider.redact((stablePrefix ? projectContext(run.project, {config: run.config}).slice(fixedRules.length) : projectContext(run.project, {config: run.config}) + workerContract) + '\n当前项目/会话/任务身份:' + JSON.stringify({
@@ -516,6 +519,7 @@ export class Runtime {
let response, requestStarted = false, responseAccounted = externalEngine;
try {
signal.throwIfAborted(); checkBudget(run.record, task);
+ if (run.worker) sealWorkerDispatch(this.store, session, run.worker, run.record, planned.record);
if (run.worker && !externalEngine) { planned.record.workerDispatchedAt = now(); this.store.save(session, { type: 'worker.request_intent' }); }
requestStarted = true;
const progressHandler = progress => {
diff --git a/src/shared/contracts/anthropic-messages.mjs b/src/shared/contracts/anthropic-messages.mjs
index a05f62a5..51c65ced 100644
--- a/src/shared/contracts/anthropic-messages.mjs
+++ b/src/shared/contracts/anthropic-messages.mjs
@@ -1,4 +1,4 @@
-import { isPassthrough } from './model-capacity.mjs';
+import { isPassthrough, messagesOutputSetting } from './model-capacity.mjs';
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const fail = message => { throw new Error('Messages 请求未发送:' + message); };
@@ -14,6 +14,7 @@ function contentBlocks(content) {
}
export function messagesBody(config, messages, tools, native) {
+ const protocolOutput = messagesOutputSetting(config).value;
if (!isPassthrough(config) && native.nativeParameters.thinking?.type === 'enabled' && native.nativeParameters.thinking.budget_tokens >= config.maxOutputTokens) fail('thinking.budget_tokens 必须小于本次 max_tokens 输出预算。');
const system = [], wire = [];
const append = (role, content) => {
@@ -50,7 +51,11 @@ export function messagesBody(config, messages, tools, native) {
});
return { model: config.model, ...(system.length ? { system } : {}), messages: wire,
...(definitions.length ? { tools: definitions, tool_choice: { type: 'auto' } } : {}),
- ...(!isPassthrough(config) ? { max_tokens: config.maxOutputTokens } : {}), stream: config.streaming === true, ...native.nativeParameters };
+ // Messages requires max_tokens, even in passthrough mode. Prefer the
+ // synchronized upstream maximum; native parameters below remain exact.
+ // A saved connection declaration is a fallback, never a verified maximum.
+ max_tokens: isPassthrough(config) ? protocolOutput : config.maxOutputTokens,
+ stream: config.streaming === true, ...native.nativeParameters };
}
export function messagesHistory(body) {
diff --git a/src/shared/contracts/model-capacity.d.mts b/src/shared/contracts/model-capacity.d.mts
index 7e9f00ef..c26094e6 100644
--- a/src/shared/contracts/model-capacity.d.mts
+++ b/src/shared/contracts/model-capacity.d.mts
@@ -2,3 +2,4 @@ export const DEFAULT_MODEL_CAPACITY: Readonly<{ contextLimit: number; maxOutputT
export const CAPACITY_RANGES: Readonly
>;
export function capacitySettings(input?: { contextLimit?: number; maxOutputTokens?: number }, previous?: { contextLimit?: number; maxOutputTokens?: number }): { contextLimit: number; maxOutputTokens: number };
export function capacityMode(value?: string): 'model' | 'manual';
+export function messagesOutputSetting(config: { model?: string; nativeParameters?: Record; maxOutputTokens?: number; upstreamModel?: { id: string; maxOutputTokens?: number | null } }): { value: unknown; source: string };
diff --git a/src/shared/contracts/model-capacity.mjs b/src/shared/contracts/model-capacity.mjs
index 9096f98b..5f75dfc0 100644
--- a/src/shared/contracts/model-capacity.mjs
+++ b/src/shared/contracts/model-capacity.mjs
@@ -16,6 +16,15 @@ export function capacitySettings(input = {}, previous = DEFAULT_MODEL_CAPACITY,
export const isPassthrough = config => config.capacityMode === 'passthrough';
+export function messagesOutputSetting(config) {
+ const member = config.modelRouting?.members?.find(value => value.id === config.modelConnectionId) ?? config;
+ const native = config.nativeParameters ?? member.nativeParameters ?? {};
+ if (Object.hasOwn(native, 'max_tokens')) return { value: native.max_tokens, source: 'explicit_native' };
+ const upstream = member.upstreamModel;
+ if (upstream?.id === member.model && upstream.maxOutputTokens) return { value: upstream.maxOutputTokens, source: 'upstream_catalog' };
+ return { value: member.maxOutputTokens ?? config.maxOutputTokens ?? DEFAULT_MODEL_CAPACITY.maxOutputTokens, source: 'connection_declaration' };
+}
+
export function capacityMode(value = 'manual') {
if (!['passthrough', 'model', 'manual'].includes(value)) throw Object.assign(new Error('请选择默认透传、按模型容量或手动限制。'), { status: 400 });
return value;
diff --git a/src/shared/contracts/workers.mjs b/src/shared/contracts/workers.mjs
index 075a7fd4..e0ce8325 100644
--- a/src/shared/contracts/workers.mjs
+++ b/src/shared/contracts/workers.mjs
@@ -44,7 +44,11 @@ export function collaborationInput(input, config) {
maxDurationMs: bounded(raw.maxDurationMs, config.maxRunDurationMs ?? 600000, 1000, Math.min(3600000, config.maxRunDurationMs ?? 600000), '总时限'),
};
const children = input.children.map((item, index) => {
- if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).some(key => !['label', 'goal', 'paths', 'budget'].includes(key))) throw workerConflict('子任务字段无效。');
+ if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).some(key => !['label', 'goal', 'paths', 'budget', 'role', 'requirements', 'modelSelection'].includes(key))) throw workerConflict('子任务字段无效。');
+ const selection = item.modelSelection;
+ if (selection !== undefined && (!selection || Array.isArray(selection) || Object.keys(selection).some(key => !['type', 'id'].includes(key))
+ || !['connection', 'pool'].includes(selection.type) || typeof selection.id !== 'string' || !selection.id)) throw workerConflict('请选择模型中心已保存的连接或模型池。');
+ if (item.requirements !== undefined && !Array.isArray(item.requirements)) throw workerConflict('子任务要求需要逐项列出。');
if (!Array.isArray(item.paths) || !item.paths.length || !unrestricted(config) && item.paths.length > 16) throw workerConflict('每个子任务需要1到16个修改范围。');
const paths = item.paths.map(workerPath).sort();
if (new Set(paths.map(workerPathKey)).size !== paths.length) throw workerConflict('子任务范围不能重复。');
@@ -52,6 +56,8 @@ export function collaborationInput(input, config) {
if (!part || Array.isArray(part) || Object.keys(part).some(key => !['maxTokens', 'maxSteps', 'maxToolCalls'].includes(key))) throw workerConflict('子预算字段无效。');
const allocate = key => engine ? budget[key] : index === 0 ? Math.floor(budget[key] / 2) : budget[key] - Math.floor(budget[key] / 2);
return { label: text(item.label, ceiling(config, 64), '子任务名称'), goal: text(item.goal, ceiling(config, 8000), '子目标'), paths,
+ role: text(item.role ?? '工程实现', ceiling(config, 128), '子任务职责'), requirements: (item.requirements ?? []).map(value => text(value, ceiling(config, 8000), '子任务要求')),
+ ...(selection ? { modelSelection: structuredClone(selection) } : {}),
budget: Object.fromEntries(['maxTokens', 'maxSteps', 'maxToolCalls'].map(key => [key, unrestricted(config) ? 0 : bounded(part[key], allocate(key), key === 'maxTokens' ? 500 : 1, budget[key], key)])) };
});
for (const key of ['maxTokens', 'maxSteps', 'maxToolCalls']) if (children.reduce((sum, child) => sum + child.budget[key], 0) > budget[key]) throw workerConflict('子任务预算之和不能超过父预算:' + key);
@@ -69,7 +75,8 @@ export function workerSeal(worker) {
projectId: worker.projectId, sessionId: worker.sessionId, taskId: worker.taskId, workspaceId: worker.workspaceId,
label: worker.label, goal: worker.goal, paths: worker.paths, budget: worker.budget, model: worker.model, baseCommit: worker.baseCommit,
baselineArtifactId: worker.baselineArtifactId, baselineSha256: worker.baselineSha256, baselineRunId: worker.baselineRunId,
- ...(worker.engine ? { engine: worker.engine } : {}), ...(worker.evaluation ? { evaluation: worker.evaluation } : {}) };
+ ...(worker.engine ? { engine: worker.engine } : {}), ...(worker.evaluation ? { evaluation: worker.evaluation } : {}),
+ ...(worker.assignment ? { assignment: worker.assignment } : {}) };
}
export function workerForProject(store, projectId) {
return [...(store.core.worker?.values() ?? [])].find(value => value.projectId === projectId) ?? null;
@@ -84,11 +91,13 @@ export function workerForSession(store, session) {
|| definition.taskId !== worker.taskId || definition.projectId !== worker.projectId || definition.sessionId !== worker.sessionId
|| definition.workspaceId !== worker.workspaceId || JSON.stringify(definition.paths) !== JSON.stringify(worker.paths)
|| JSON.stringify(definition.budget) !== JSON.stringify(worker.budget) || definition.goal !== worker.goal
- || JSON.stringify(group.model) !== JSON.stringify(worker.model)
+ || JSON.stringify(definition.assignment?.model ?? group.model) !== JSON.stringify(worker.model)
+ || JSON.stringify(definition.assignment) !== JSON.stringify(worker.assignment)
|| JSON.stringify(definition.engine) !== JSON.stringify(worker.engine)
|| JSON.stringify(definition.evaluation) !== JSON.stringify(worker.evaluation)) throw workerConflict('子任务与父任务的封存分工不一致。');
const task = store.core.task.get(worker.taskId);
if (!task || task.goal !== worker.goal || task.workerId !== worker.id || task.budget.maxTokens !== worker.budget.maxTokens) throw workerConflict('子任务目标、身份或累计预算已变化。');
+ if (worker.assignment && JSON.stringify(task.acceptance) !== JSON.stringify(worker.assignment.requirements)) throw workerConflict('子任务原要求与封存分工不一致。');
const original = store.owned('artifact', worker.contractArtifactId, session.id);
if (original.kind !== 'worker-contract' || original.taskId !== worker.taskId || original.sha256 !== worker.contractSha256
|| store.artifactStore.read(original) !== JSON.stringify(workerSeal(worker))) throw workerConflict('受限子任务契约与原工件不一致。');
diff --git a/task_plan.md b/task_plan.md
index b6657c3f..61776c40 100644
--- a/task_plan.md
+++ b/task_plan.md
@@ -1055,3 +1055,10 @@ F收尾:57d075e修正独立编译QA路径,6d09ac8封存差异;202610302320
5. [complete] 最终回顾与增量推送完成,38726c65与GitAtlas分支逐SHA一致;回执见docs/gitatlas-experience-1.25.11-push.json。下一F先合成路由/派发归属/父质量回收,真实收益另验。
历史失败、unknown用量、网络异常和Purge收益unknown保持;本阶段不请求真实模型、不续跑旧实验/用户项目、不读真实Key、不委派,不恢复额度。
+
+## F阶段(2026-11-06)
+
+1. [complete] 核对现有worker/模型池/成果回收契约,冻结角色与显式选模、派发身份、质量回收范围;不委派、不请求真实模型。
+2. [complete] 复用原协作记录实现逐子任务角色/模型绑定、实际请求身份及原成果质量核对;兼容原计划/评测/引擎,保持开放策略。
+3. [in_progress] 本机合成HTTP、错误/修订/停止与迟到边界、原worker回归;现有协作面板网页/Electron/390px与恢复。
+4. [pending] 独立1.25.12源码/程序/重建、隔离安装/跨版保持、正式入口、证据封存与增量推送。
diff --git a/tests/messages-required-output.test.mjs b/tests/messages-required-output.test.mjs
new file mode 100644
index 00000000..39b963be
--- /dev/null
+++ b/tests/messages-required-output.test.mjs
@@ -0,0 +1,44 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { fixture, compatibleFixture, until } from './helpers.mjs';
+import { Provider } from '../src/server/provider.mjs';
+import { Runtime } from '../src/server/runtime.mjs';
+import { completionBody, requestVariants } from '../src/shared/contracts/model-request.mjs';
+import { messagesOutputSetting } from '../src/shared/contracts/model-capacity.mjs';
+
+const config = { mode: 'compatible', protocol: 'anthropic-messages', model: 'owned-claude', executionMode: 'unrestricted', capacityMode: 'passthrough', maxOutputTokens: 16384 };
+test('Messages required output uses explicit native value, matching catalog maximum or its own connection declaration', () => {
+ const input = [{ role: 'user', content: 'Complete original input' }];
+ const catalog = { id: config.model, maxOutputTokens: 128000 };
+ assert.equal(completionBody({ ...config, upstreamModel: catalog }, input, []).max_tokens, 128000);
+ assert.equal(completionBody({ ...config, upstreamModel: catalog, nativeParameters: { max_tokens: 234567 } }, input, []).max_tokens, 234567);
+ assert.equal(completionBody({ ...config, upstreamModel: { ...catalog, id: 'different' } }, input, []).max_tokens, 16384);
+ const routing = { members: [
+ { id: 'a', model: 'a', protocol: 'anthropic-messages', maxOutputTokens: 32768 },
+ { id: 'b', model: 'b', protocol: 'anthropic-messages', maxOutputTokens: 65536, upstreamModel: { id: 'b', maxOutputTokens: 256000 } },
+ { id: 'c', model: 'c', protocol: 'chat-completions', maxOutputTokens: 2048 },
+ ] };
+ const variants = requestVariants(completionBody({ ...config, modelRouting: routing }, input, []));
+ assert.deepEqual(variants.map(body => body.max_tokens), [32768, 256000, undefined]);
+ assert.equal(messagesOutputSetting({ ...config, upstreamModel: catalog }).source, 'upstream_catalog');
+});
+
+test('actual passthrough Messages HTTP includes required max_tokens and preserves a different upstream 400 with no retry', { timeout: 30000 }, async t => {
+ let fail = false;
+ const upstream = await compatibleFixture(t, (_url, body) => {
+ assert.equal(body.max_tokens, 98304);
+ assert.ok(body.messages.some(row => row.content.some(block => block.text?.includes('ORIGINAL-END'))));
+ if (fail) return { status: 400, body: { type: 'error', error: { type: 'upstream_error', message: 'owned upstream rejected another option' } } };
+ return { id: 'msg_owned', type: 'message', role: 'assistant', model: config.model, content: [{ type: 'text', text: 'Owned complete response' }], stop_reason: 'end_turn', usage: { input_tokens: 20, output_tokens: 5 } };
+ });
+ const f = fixture(t, { modernDefaults: true }), provider = new Provider(), hub = provider.modelHub(f.store);
+ const connection = hub.upsert({ name: 'Owned Messages', ...config, baseUrl: upstream.baseUrl, requiresKey: false, maxOutputTokens: 98304 });
+ hub.select({ type: 'connection', id: connection.id });
+ const runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
+ runtime.start(f.session.id, 'ORIGINAL-END'); await until(() => !runtime.isActive(f.session.id), 20000);
+ assert.equal(f.session.status, 'completed', JSON.stringify(f.session.failure)); assert.equal(upstream.requests.length, 1);
+ fail = true; runtime.start(f.session.id, 'ORIGINAL-END failure'); await until(() => !runtime.isActive(f.session.id), 20000);
+ assert.equal(upstream.requests.length, 2); assert.equal(f.session.status, 'failed');
+ assert.match(JSON.stringify(f.session.failure), /owned upstream rejected another option/);
+ assert.match(JSON.stringify(f.session.failure), /400/);
+});
diff --git a/tests/role-routing.test.mjs b/tests/role-routing.test.mjs
new file mode 100644
index 00000000..b78ec6b4
--- /dev/null
+++ b/tests/role-routing.test.mjs
@@ -0,0 +1,111 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { fixture, call, compatibleFixture, completion, until } from './helpers.mjs';
+import { Provider } from '../src/server/provider.mjs';
+import { prepareWorkerFixture, ownerBytes } from './fixtures/workers-project.mjs';
+import { workerForSession, workerSeal } from '../src/shared/contracts/workers.mjs';
+
+test('each engineering assignment freezes its role, native settings and independent route without changing the default', { timeout: 120000 }, async t => {
+ const f = fixture(t, { modernDefaults: true });
+ const { manager, provider, requests } = prepareWorkerFixture(f);
+ const hub = provider.modelHub(f.store);
+ const a = hub.upsert({ name: 'A', model: 'owned-a', baseUrl: 'http://127.0.0.1:1/v1', requiresKey: false, nativeParameters: { reasoning_effort: 'high' } });
+ const b = hub.upsert({ name: 'B', model: 'owned-b', baseUrl: 'http://127.0.0.1:2/v1', requiresKey: false, nativeParameters: { reasoning_effort: 'low' } });
+ hub.select({ type: 'connection', id: a.id });
+ const original = ownerBytes(f), selected = structuredClone(hub.state.selected);
+ const pool = hub.pool({ name: 'B pool', members: [{ connectionId: b.id, weight: 1 }], maxAttempts: 1 });
+ const group = await manager.plan(f.session, { goal: 'Owned independent assignments', children: [
+ { label: 'implementation', role: '工程实现', goal: 'Implement A', paths: ['src/a.mjs'], requirements: ['Keep A compatible'] },
+ { label: 'tests', role: '测试完善', goal: 'Improve B', paths: ['src/b.mjs'], modelSelection: { type: 'pool', id: pool.id } },
+ ] });
+ assert.deepEqual(hub.state.selected, selected); assert.equal(requests.length, 0);
+ assert.equal(group.children[0].assignment.model.model, a.model); assert.equal(group.children[1].assignment.model.model, b.model);
+ assert.equal(group.children[1].assignment.config.nativeParameters.reasoning_effort, 'low');
+ await (await manager.prepare(f.session, group.id, group.fingerprint)).promise;
+ assert.equal(group.status, 'ready', group.summary);
+ hub.select({ type: 'connection', id: b.id });
+ for (const child of group.children) {
+ const worker = workerForSession(f.store, f.store.session(child.sessionId));
+ assert.equal(manager.configFor(group, worker).model, child.assignment.model.model);
+ assert.deepEqual(workerSeal(worker).assignment, child.assignment);
+ }
+ hub.upsert({ ...a, revision: a.revision, nativeParameters: { reasoning_effort: 'medium' } });
+ assert.throws(() => manager.configFor(group, f.store.core.worker.get(group.children[0].id)), /修订/);
+ assert.equal(manager.configFor(group, f.store.core.worker.get(group.children[1].id)).model, b.model);
+ assert.deepEqual(ownerBytes(f), original); assert.equal(requests.length, 0);
+});
+
+test('a frozen pool preserves actual HTTP 429, Retry-After and unknown consumption without a hidden replacement', { timeout: 120000 }, async t => {
+ const bad = await compatibleFixture(t, () => ({ status: 429, headers: { 'retry-after': '17' }, body: { error: { message: 'owned rate limit', type: 'rate_limit_error' } } }));
+ const good = await compatibleFixture(t, () => completion([], 'Must not be used to mask the failed request.'));
+ const f = fixture(t, { modernDefaults: true }); f.store.saveConfig({ approvalMode: 'full' });
+ const { manager, provider } = prepareWorkerFixture(f); provider.complete = Provider.prototype.complete.bind(provider);
+ const hub = provider.modelHub(f.store);
+ const a = hub.upsert({ name: 'Rate limited', model: 'owned-a', baseUrl: bad.baseUrl, requiresKey: false });
+ const b = hub.upsert({ name: 'Other', model: 'owned-b', baseUrl: good.baseUrl, requiresKey: false });
+ const pool = hub.pool({ name: 'Frozen pool', members: [{ connectionId: a.id }, { connectionId: b.id }], maxAttempts: 2 });
+ const group = await manager.plan(f.session, { goal: 'Keep failure facts', children: [{ label: 'owned', goal: 'Read A', paths: ['src/a.mjs'], modelSelection: { type: 'pool', id: pool.id } }] });
+ await (await manager.prepare(f.session, group.id, group.fingerprint)).promise;
+ await (await manager.start(f.session, group.id, group.fingerprint)).promise;
+ assert.equal(bad.requests.length, 1); assert.equal(good.requests.length, 0);
+ const worker = f.store.core.worker.get(group.children[0].id), session = f.store.session(worker.sessionId);
+ assert.equal(worker.result, null); assert.equal(session.status, 'failed');
+ assert.match(JSON.stringify(session.failure), /owned rate limit/); assert.match(JSON.stringify(session.failure), /17/);
+ const run = f.store.core.run.get(worker.currentRunId);
+ assert.equal(run.consumption.length, 1); assert.equal(run.consumption[0].usageStatus, 'unknown');
+ assert.equal(run.usage.totalTokens, 0); assert.equal(run.usage.unknownRequests, 1);
+ const plan = [...f.store.core.context_plan.values()].find(row => row.taskId === worker.taskId);
+ assert.ok(plan.workerDispatch); assert.equal(plan.status, 'failed');
+});
+
+test('stopping a routed worker keeps its prepared evidence and a late HTTP tool proposal cannot write files', { timeout: 120000 }, async t => {
+ let release; const held = new Promise(resolve => { release = resolve; });
+ const upstream = await compatibleFixture(t, async () => { await held; return completion([call('late', 'propose_file', { path: 'src/a.mjs', content: 'late', reason: 'late' })]); });
+ t.after(() => release());
+ const f = fixture(t, { modernDefaults: true }); f.store.saveConfig({ approvalMode: 'full' });
+ const { manager, provider } = prepareWorkerFixture(f); provider.complete = Provider.prototype.complete.bind(provider);
+ const hub = provider.modelHub(f.store), connection = hub.upsert({ name: 'Held', model: 'held', baseUrl: upstream.baseUrl, requiresKey: false });
+ const group = await manager.plan(f.session, { goal: 'Stop once', children: [{ label: 'held', goal: 'Read A', paths: ['src/a.mjs'], modelSelection: { type: 'connection', id: connection.id } }] });
+ await (await manager.prepare(f.session, group.id, group.fingerprint)).promise;
+ const started = manager.start(f.session, group.id, group.fingerprint);
+ await until(() => upstream.requests.length === 1, 20000);
+ await manager.stopParent(f.session.id); await started.promise;
+ const session = f.store.session(group.children[0].sessionId), count = session.changes.length;
+ release(); await new Promise(resolve => setTimeout(resolve, 80));
+ assert.equal(session.changes.length, count); assert.equal(count, 0);
+ assert.equal(upstream.requests.length, 1);
+ const plan = [...f.store.core.context_plan.values()].find(row => row.taskId === session.taskId);
+ assert.ok(plan.workerDispatch); assert.equal(plan.status, 'interrupted');
+});
+
+test('parent collection verifies dispatch/tool generation and real bytes, preserving absent checks and unassessed requirements', { timeout: 180000 }, async t => {
+ const f = fixture(t, { modernDefaults: true }); f.store.saveConfig({ approvalMode: 'full' });
+ const { manager } = prepareWorkerFixture(f, { respond: async ({ project }) => {
+ const session = [...f.store.sessions.values()].find(value => value.projectId === project.id);
+ return { message: { role: 'assistant', content: session.changes.length ? 'All requirements passed!' : '',
+ ...(!session.changes.length ? { tool_calls: [call('owned-file', 'propose_file', { path: 'src/a.mjs', content: 'export const value = 7;\n', reason: 'owned fixture' })] } : {}) }, usage: null };
+ } });
+ const original = ownerBytes(f);
+ const group = await manager.plan(f.session, { goal: 'Collect only facts', children: [{ label: 'worker', role: '工程实现', goal: 'Change A', requirements: ['Improve performance'], paths: ['src/a.mjs'] }] });
+ await (await manager.prepare(f.session, group.id, group.fingerprint)).promise;
+ await (await manager.start(f.session, group.id, group.fingerprint)).promise;
+ assert.equal(group.status, 'ready_to_collect', group.summary);
+ const child = group.children[0], worker = f.store.core.worker.get(child.id), session = f.store.session(child.sessionId);
+ const output = await manager.output(session, worker), quality = output.quality;
+ assert.equal(output.check, null); assert.equal(quality.checks.status, 'not_verified');
+ assert.ok(quality.requirements.every(row => row.status === 'not_evaluated'));
+ assert.equal(quality.usage.unknownRequests, 2); assert.equal(quality.usage.totalTokens, 0);
+ assert.equal(quality.requests.length, 2); assert.ok(quality.requests.every(row => row.phase === 'prepared' && row.toolSurfaceGeneration));
+ await (await manager.collect(f.session, group.id, group.fingerprint)).promise;
+ assert.equal(group.status, 'collected', group.summary);
+ const collected = await manager.readCollection(f.session, group);
+ assert.deepEqual(collected.workers[0].quality, quality);
+ const plan = [...f.store.core.context_plan.values()].find(row => row.taskId === worker.taskId);
+ const ref = plan.workerDispatch; plan.workerDispatch = { ...ref, sha256: '0'.repeat(64) };
+ await assert.rejects(manager.output(session, worker), /派发/); plan.workerDispatch = ref;
+ f.store.core.task.get(worker.taskId).acceptance.push('Later requirement');
+ assert.throws(() => workerForSession(f.store, session), /原要求/);
+ f.store.core.task.get(worker.taskId).acceptance.pop();
+ await (await manager.prepareMerge(f.session, group.id, group.fingerprint)).promise;
+ assert.equal(group.merge.status, 'applied', group.summary); assert.deepEqual(ownerBytes(f), original);
+});
diff --git a/tests/unrestricted-execution.test.mjs b/tests/unrestricted-execution.test.mjs
index 4d74c519..d3386624 100644
--- a/tests/unrestricted-execution.test.mjs
+++ b/tests/unrestricted-execution.test.mjs
@@ -45,10 +45,11 @@ test('open change sets apply and restore a file larger than the old four MiB bat
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'large-change.txt'), 'utf8'), before);
});
-for (const protocol of ['chat-completions', 'responses', 'anthropic-messages']) test(protocol + ' default wire omits every output limit while explicit manual settings remain exact', () => {
+for (const protocol of ['chat-completions', 'responses', 'anthropic-messages']) test(protocol + ' passthrough preserves optional limits and Messages required max_tokens while manual settings remain exact', () => {
const config = { ...openDefaults, protocol, model: 'owned', contextLimit: 1000, maxOutputTokens: 256 };
const body = completionBody(config, [{ role: 'user', content: 'original'.repeat(2000) }], []);
- for (const key of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) assert.equal(Object.hasOwn(body, key), false);
+ for (const key of ['max_tokens', 'max_completion_tokens', 'max_output_tokens']) assert.equal(Object.hasOwn(body, key), protocol === 'anthropic-messages' && key === 'max_tokens');
+ if (protocol === 'anthropic-messages') assert.equal(body.max_tokens, config.maxOutputTokens);
const manual = completionBody({ ...config, capacityMode: 'manual', maxOutputTokens: 90000 }, [{ role: 'user', content: 'manual' }], []);
assert.equal(manual[protocol === 'responses' ? 'max_output_tokens' : 'max_tokens'], 90000);
const budget = budgetFor(config); assert.equal(budget.contextLimit, null); assert.equal(budget.inputBudget, null);