197 lines
21 KiB
JavaScript
197 lines
21 KiB
JavaScript
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { randomUUID, createHash } from 'node:crypto';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { fixture, compatibleFixture, call, assertToolPairs } from '../tests/helpers.mjs';
|
|
import { Provider } from '../src/server/provider.mjs';
|
|
import { Runtime } from '../src/server/runtime.mjs';
|
|
import { EngineRunner } from '../src/core/engines/engine-runner.mjs';
|
|
import { resolveControlledInstallation } from '../src/core/engines/controlled-installation.mjs';
|
|
import { originalEngineRun } from '../src/shared/contracts/engine-execution.mjs';
|
|
import { deliveryGit as git, writeDeliveryFile as write } from '../tests/fixtures/delivery-project.mjs';
|
|
import { ownerBytes } from '../tests/fixtures/workers-project.mjs';
|
|
|
|
if (process.argv.includes('--help')) {
|
|
console.log('node scripts/verify-controlled-projects.mjs — actual pinned Harness, owned HTTP model fixture, three real Node/React/Python worktrees, failing tests/repairs, approvals, parent validation, Edge and Git; no configured-model requests. Requires AGENT_WORKBENCH_DEEPSEEK_ROOT and AGENT_WORKBENCH_TEST_PYTHON.'); process.exit(0);
|
|
}
|
|
assert.equal(process.argv.length, 2);
|
|
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
|
|
const directory = path.resolve('.qa', 'controlled-projects-' + randomUUID()), results = [], cases = [];
|
|
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
const installation = resolveControlledInstallation(process.cwd(), process.env.AGENT_WORKBENCH_DEEPSEEK_ROOT);
|
|
assert.equal(installation.controlledStatus, 'available', installation.message);
|
|
const python = process.env.AGENT_WORKBENCH_TEST_PYTHON;
|
|
assert.ok(python && path.isAbsolute(python) && fs.existsSync(python), 'Provide the existing isolated Python 3.10+ interpreter.');
|
|
fs.mkdirSync(directory, { recursive: true });
|
|
const npmCli = path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');
|
|
function inputs() {
|
|
const files = ['package.json', 'package-lock.json'];
|
|
const walk = root => { for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
const file = path.join(root, entry.name); if (entry.isDirectory()) walk(file); else if (entry.isFile()) files.push(file);
|
|
} };
|
|
for (const root of ['src', 'scripts', 'tests', 'benchmarks', 'dist-client', 'dist-server']) walk(root);
|
|
return files.sort().map(file => ({ path: file, sha256: hash(fs.readFileSync(file)) }));
|
|
}
|
|
const frozen = inputs(), mark = message => { cases.push(message); console.log('PASS ' + message); };
|
|
function specification(kind, root) {
|
|
if (kind === 'node') return { tests: 8, checks: ['test', 'build'], initial: null, fixes: {
|
|
'src/add.mjs': 'export function add(left, right) {\n if (!Number.isFinite(left) || !Number.isFinite(right)) throw new TypeError("finite numeric inputs required");\n return left + right;\n}\n',
|
|
'src/range.mjs': 'export function inclusiveRange(start, end) {\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || end < start || end - start >= 10000) throw new RangeError("bounded ascending integer range required");\n return Array.from({ length: end - start + 1 }, (_, index) => start + index);\n}\n',
|
|
} };
|
|
if (kind === 'react') {
|
|
const app = fs.readFileSync(path.join(root, 'src/App.tsx'), 'utf8'); assert.ok(app.includes("toggleTask(current, 'missing')"));
|
|
return { tests: 9, checks: ['test', 'typecheck', 'build'], initial: null, fixes: {
|
|
'src/query.ts': "import type { Task } from './types.ts';\nexport function selectTasks(tasks: Task[], filter: string, query: string): Task[] {\n const text = query.trim().toLocaleLowerCase();\n return tasks.filter(task => (filter === 'done' ? task.done : filter === 'pending' ? !task.done : true) && task.title.toLocaleLowerCase().includes(text));\n}\n",
|
|
'src/summary.ts': "import type { Task } from './types.ts';\nexport function summarizeTasks(tasks: Task[]) {\n return { total: tasks.length, completed: tasks.filter(task => task.done).length, pendingHours: tasks.filter(task => !task.done).reduce((sum, task) => sum + task.hours, 0) };\n}\n",
|
|
'src/transition.ts': "import type { Task } from './types.ts';\nexport function toggleTask(tasks: Task[], id: string): Task[] {\n return tasks.map(task => task.id === id ? { ...task, done: !task.done } : task);\n}\n",
|
|
'src/App.tsx': app.replace("toggleTask(current, 'missing')", 'toggleTask(current, task.id)'),
|
|
} };
|
|
}
|
|
const test = file => fs.readFileSync(path.join('benchmarks/workers-delivery-v1/python-tests', file), 'utf8');
|
|
return { tests: 10, checks: ['python:test', 'python:compile'], initial: {
|
|
'money.py': 'def to_cents(value):\n return int(float(value) * 100)\n',
|
|
'schedule.py': 'def normalize_schedule(values):\n return list(values)\n',
|
|
'tests/test_money.py': test('test_money.py'), 'tests/test_schedule.py': test('test_schedule.py'),
|
|
}, fixes: {
|
|
'money.py': 'from decimal import Decimal, InvalidOperation, ROUND_HALF_UP\n\ndef to_cents(value):\n try:\n amount = Decimal(str(value))\n if not amount.is_finite():\n raise ValueError("finite amount required")\n return int((amount * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))\n except (InvalidOperation, OverflowError, TypeError) as error:\n raise ValueError("valid finite amount required") from error\n',
|
|
'schedule.py': 'import re\nfrom datetime import date\n\ndef normalize_schedule(values):\n dates = []\n for value in values:\n if not isinstance(value, str) or not re.fullmatch(r"\\d{4}-\\d{2}-\\d{2}", value):\n raise ValueError("ISO calendar date required")\n dates.append(date.fromisoformat(value))\n return [value.isoformat() for value in sorted(set(dates))]\n',
|
|
} };
|
|
}
|
|
async function runSample(kind) {
|
|
const disposers = [], t = { after: value => disposers.push(value) }, f = fixture(t), sample = path.join(directory, kind);
|
|
fs.mkdirSync(sample); let runtime, group, result; const reviews = [], modelRequests = [];
|
|
try {
|
|
const baseline = kind === 'react' ? 'benchmarks/react-delivery-v1/baseline' : 'benchmarks/workers-delivery-v1/' + kind;
|
|
fs.cpSync(path.resolve(baseline), f.projectRoot, { recursive: true, filter: file => !file.split(path.sep).includes('node_modules') });
|
|
write(f, '.gitignore', 'node_modules/\ndist/\n.awb-*\n__pycache__/\n.venv/\n.pytest_cache/\n');
|
|
write(f, 'owner-staged.txt', 'Owner baseline\n'); write(f, 'owner-unstaged.txt', 'Owner baseline\n');
|
|
git(f, ['init', '--initial-branch=main']); git(f, ['config', 'core.autocrlf', 'false']); git(f, ['config', 'user.name', 'Workbench QA']); git(f, ['config', 'user.email', 'qa@workbench.invalid']);
|
|
git(f, ['add', '--', '.']); git(f, ['commit', '--no-gpg-sign', '-m', 'Seal ' + kind + ' controlled-engine acceptance']);
|
|
write(f, 'owner-staged.txt', 'Owner staged change\n'); git(f, ['add', '--', 'owner-staged.txt']);
|
|
write(f, 'owner-staged.txt', 'Owner working copy after staging\n'); write(f, 'owner-unstaged.txt', 'Owner unstaged change\n'); write(f, 'owner-untracked.txt', 'Owner untracked file\n');
|
|
const spec = specification(kind, f.projectRoot), writable = [...new Set([...Object.keys(spec.initial ?? {}), ...Object.keys(spec.fixes)])].sort();
|
|
const original = ownerBytes(f), protectedNames = git(f, ['ls-files', '-z']).split('\0').filter(file => file && !writable.includes(file) && !file.startsWith('owner-'));
|
|
const protectedFiles = Object.fromEntries(protectedNames.map(file => [file, fs.readFileSync(path.join(f.projectRoot, file))]));
|
|
const verify = root => { for (const [file, bytes] of Object.entries(protectedFiles)) assert.deepEqual(fs.readFileSync(path.join(root, file)), bytes, 'Protected ' + file); };
|
|
const install = (root, label) => {
|
|
const child = spawnSync(process.execPath, [npmCli, 'ci', '--offline', '--no-audit', '--no-fund'], { cwd: root, windowsHide: true, timeout: 120000, maxBuffer: 8 * 1024 * 1024 });
|
|
fs.writeFileSync(path.join(sample, label + '-npm-ci-log.txt'), child.stdout ?? Buffer.alloc(0)); fs.writeFileSync(path.join(sample, label + '-npm-ci-stderr-log.txt'), child.stderr ?? Buffer.alloc(0));
|
|
if (child.error) throw child.error; assert.equal(child.status, 0, 'Inspect the original offline installation logs.'); verify(root);
|
|
};
|
|
if (kind === 'react') install(f.projectRoot, 'parent');
|
|
let phase = 'new';
|
|
const model = await compatibleFixture(t, async (route, input) => {
|
|
assert.equal(route, '/v1/chat/completions'); assert.equal(input.model, 'owned-controlled-engineering');
|
|
assertToolPairs(input.messages);
|
|
const worker = [...f.store.core.worker.values()][0], session = f.store.session(worker.sessionId);
|
|
const checks = [...f.store.core.check_job.values()].filter(job => job.taskId === worker.taskId), job = checks.at(-1);
|
|
const plan = [...f.store.core.check_plan.values()].filter(plan => plan.taskId === worker.taskId).at(-1);
|
|
const propose = files => Object.entries(files).map(([file, content]) => call(randomUUID(), 'propose_file', { path: file, content, reason: 'Fixed local acceptance repair; retain all tests and declarations.' }));
|
|
let calls = [];
|
|
if (session.changes.some(change => change.status === 'pending')) { /* Explicit review follows native completion. */ }
|
|
else if (phase === 'new' && spec.initial) { calls = propose(spec.initial); phase = 'initial'; }
|
|
else if (phase !== 'fixed' && job) {
|
|
assert.equal(job.status, 'failed', job.summary); assert.ok(job.results.some(result => result.tests?.failed > 0)); calls = propose(spec.fixes); phase = 'fixed';
|
|
} else if (phase === 'fixed' && job?.status === 'passed') assert.equal(job.results[0].tests.passed, spec.tests);
|
|
else if (!plan || job?.planId === plan.id) calls = [call(randomUUID(), 'plan_checks', { names: spec.checks })];
|
|
else calls = [call(randomUUID(), 'run_checks', { plan_id: plan.id })];
|
|
modelRequests.push({ requestBody: input, callIds: calls.map(call => call.id), phase });
|
|
return { choices: [{ message: { role: 'assistant', content: calls.length ? '' : 'Owned native run complete; host proof is still required.', ...(calls.length ? { tool_calls: calls } : {}) },
|
|
finish_reason: calls.length ? 'tool_calls' : 'stop' }], usage: { prompt_tokens: 123, completion_tokens: 45, total_tokens: 168 } };
|
|
});
|
|
f.store.saveConfig({ mode: 'compatible', model: 'owned-controlled-engineering', baseUrl: model.baseUrl, contextLimit: 64000 });
|
|
const provider = new Provider(); provider.setKey('self-owned-controlled-model-fixture'); runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll());
|
|
runtime.controlledEngines = new EngineRunner(f.store, provider, { directoryRoot: path.join(f.root, 'owned-engine-runs') });
|
|
runtime.checkRunner().pythonExecutable = python; const manager = runtime.workerManager();
|
|
group = await manager.plan(f.session, { goal: 'Deliver ' + kind + ' with the pinned controlled Harness, retained failures, explicit review, parent validation and local Git.',
|
|
engine: { id: 'deepseek-harness', root: installation.root, controlledSha256: installation.controlledSha256 },
|
|
budget: { maxTokens: 200000, maxSteps: 64, maxToolCalls: 128, maxDurationMs: 600000 },
|
|
children: [{ label: 'engine-' + kind, goal: 'Repair and validate the complete ' + kind + ' functional suite without replacing tests.', paths: writable }] });
|
|
await (await manager.prepare(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'ready', group.summary);
|
|
const child = group.children[0], childRoot = f.store.project(child.projectId).root;
|
|
assert.notEqual(childRoot, f.projectRoot); assert.deepEqual(ownerBytes(f), original); verify(childRoot); if (kind === 'react') install(childRoot, 'child');
|
|
mark(kind + ': pinned native engine and one owned Git worktree preserve parent staging and protected bytes');
|
|
for (let turn = 0; turn < 4 && group.status !== 'ready_to_collect'; turn++) {
|
|
const session = f.store.session(child.sessionId), ids = session.changes.filter(change => change.status === 'pending').map(change => change.id);
|
|
if (ids.length) {
|
|
assert.equal(group.status, 'awaiting_review', group.summary); const set = await runtime.changeSetManager().prepare(session, ids);
|
|
reviews.push({ operation: 'review child batch', id: set.id, fingerprint: set.fingerprint, paths: set.files.map(file => file.path) });
|
|
await (await runtime.changeSetManager().start(session, set.id, set.fingerprint)).promise; assert.equal(set.status, 'completed', set.summary);
|
|
}
|
|
const started = manager.start(f.session, group.id, group.fingerprint); let done = false, failure;
|
|
started.promise.then(() => { done = true; }, error => { failure = error; done = true; });
|
|
while (!done) {
|
|
for (const approval of session.approvals.filter(approval => approval.status === 'pending')) {
|
|
assert.equal(f.store.core.tool.get(approval.invocationId).tool, 'run_checks');
|
|
const plan = [...f.store.core.check_plan.values()].filter(plan => plan.taskId === child.taskId).at(-1);
|
|
assert.deepEqual(plan.checks.map(check => check.name), spec.checks);
|
|
reviews.push({ operation: 'approve original check', id: approval.id, taskId: child.taskId, planId: plan.id, contractSha256: plan.contractSha256 }); runtime.decide(session.id, approval.id, true);
|
|
}
|
|
await new Promise(resolve => setTimeout(resolve, 30));
|
|
}
|
|
if (failure) throw failure;
|
|
const native = [...f.store.core.engine_run.values()].filter(job => job.taskId === child.taskId).at(-1);
|
|
assert.equal(native.status, 'completed', native.error);
|
|
}
|
|
assert.equal(group.status, 'ready_to_collect', group.summary); assert.deepEqual(ownerBytes(f), original); verify(childRoot);
|
|
const childChecks = [...f.store.core.check_job.values()].filter(job => job.taskId === child.taskId);
|
|
assert.ok(childChecks.some(job => job.status === 'failed' && job.results.some(result => result.tests?.failed > 0)));
|
|
assert.equal(childChecks.at(-1).results[0].tests.passed, spec.tests); assert.equal(childChecks.at(-1).status, 'passed');
|
|
const engineRuns = [...f.store.core.engine_run.values()].filter(job => job.taskId === child.taskId), childSession = f.store.session(child.sessionId);
|
|
for (const job of engineRuns) {
|
|
originalEngineRun(f.store, childSession, job); assert.equal(job.status, 'completed', job.error); assert.equal(job.native.cleanup.treeConfirmed, true);
|
|
assert.equal(job.native.stderr, ''); assert.equal(job.native.activity.endEvents[0].data.reason.kind, 'completed');
|
|
}
|
|
assert.equal(f.store.core.task.get(child.taskId).usage.requests, modelRequests.length);
|
|
assert.equal(f.store.core.task.get(child.taskId).usage.totalTokens, modelRequests.length * 168);
|
|
mark(kind + ': actual Harness uses owned model/tool bridges, retains failing tests, and completes reviewed repairs with one accounting entry per HTTP request');
|
|
await (await manager.collect(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'collected', group.summary);
|
|
const collection = await manager.readCollection(f.session, group); assert.deepEqual(collection.conflicts, []); assert.deepEqual(collection.paths, writable);
|
|
await (await manager.prepareMerge(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'merge_prepared', group.summary);
|
|
const merge = f.store.core.change_set.get(group.merge.changeSetId); reviews.push({ operation: 'review parent batch', id: merge.id, fingerprint: merge.fingerprint });
|
|
await (await runtime.changeSetManager().start(f.session, merge.id, merge.fingerprint)).promise; assert.equal(merge.status, 'completed', merge.summary);
|
|
const checkPlan = await runtime.checkRunner().plan(f.session, spec.checks), check = await (await runtime.checkRunner().start(f.session, checkPlan.id)).promise;
|
|
assert.equal(check.status, 'passed', check.summary); assert.equal(check.results[0].tests.passed, spec.tests); verify(f.projectRoot);
|
|
mark(kind + ': separately reviewed parent merge passes all ' + spec.tests + ' functional tests and actual build/compile');
|
|
const browserJobs = [];
|
|
if (kind === 'react') for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
|
|
const steps = [ { action: 'assert_count', selector: '.task-list article', count: 3 },
|
|
{ action: 'assert_text', selector: '.summary > div:nth-child(3) strong', text: viewport.width > 600 ? '8小时' : '8\n小时' },
|
|
{ action: 'select', selector: 'select[aria-label="任务状态"]', value: 'pending' }, { action: 'assert_count', selector: '.task-list article', count: 2 },
|
|
{ action: 'fill', selector: 'input[aria-label="任务搜索"]', value: ' 编写 ' }, { action: 'assert_count', selector: '.task-list article', count: 1 },
|
|
{ action: 'fill', selector: 'input[aria-label="任务搜索"]', value: '' }, { action: 'select', selector: 'select[aria-label="任务状态"]', value: 'all' },
|
|
{ action: 'click', selector: '.task-list article[data-task="api"] button' }, { action: 'assert_text', selector: '.task-list article[data-task="api"] .tag', text: '已完成' },
|
|
{ action: 'assert_text', selector: '.task-list article[data-task="tests"] .tag', text: '待完成' }, { action: 'assert_text', selector: '.summary > div:nth-child(2) strong', text: '2' },
|
|
{ action: 'assert_text', selector: '.summary > div:nth-child(3) strong', text: viewport.width > 600 ? '5小时' : '5\n小时' } ];
|
|
const plan = await runtime.browserManager().plan(f.session, { viewport, steps }), job = await runtime.browserManager().start(f.session, plan.id).promise;
|
|
assert.equal(job.status, 'passed', job.summary); assert.equal(job.cleanup.exited, true); browserJobs.push(job);
|
|
for (const image of job.screenshots) fs.writeFileSync(path.join(sample, 'page-' + viewport.width + '-' + image.artifactId + '.png'), f.store.artifactStore.readBytes(f.store.core.artifact.get(image.artifactId)));
|
|
}
|
|
if (kind === 'react') mark('react: real Edge desktop/390px filtering, trimmed search, one-task toggle and complete totals pass');
|
|
const deliveryPlan = await runtime.gitDelivery().plan(f.session, { message: 'Reviewed ' + kind + ' controlled-engine delivery' }), delivery = await (await runtime.gitDelivery().start(f.session, deliveryPlan.id)).promise;
|
|
assert.equal(delivery.status, 'completed', delivery.summary); await manager.finalize(f.session, group.id, group.fingerprint); assert.equal(group.status, 'completed');
|
|
assert.deepEqual(ownerBytes(f).files, original.files); assert.equal(git(f, ['show', ':owner-staged.txt']), 'Owner staged change\n');
|
|
assert.deepEqual(git(f, ['show', '--format=', '--name-only', delivery.commit]).trim().split(/\r?\n/).sort(), writable);
|
|
mark(kind + ': local Git contains only reviewed functional changes and preserves original staged/unstaged owner bytes');
|
|
result = { success: true, scope: 'actual-native-Harness-with-owned-HTTP-model-fixture', version, kind, parentTaskId: group.taskId, groupId: group.id,
|
|
child: f.store.core.worker.get(child.id), engineRuns, checks: [...f.store.core.check_job.values()], parentCheck: check, browserJobs, commit: delivery.commit,
|
|
writable, reviews, modelRequests, protectedFiles: Object.fromEntries(Object.entries(protectedFiles).map(([file, bytes]) => [file, hash(bytes)])), realModelRequests: 0 };
|
|
return result;
|
|
} catch (error) { result = { success: false, version, kind, error: error.stack, group, reviews, modelRequests, engineRuns: [...f.store.core.engine_run.values()], checks: [...f.store.core.check_job.values()], realModelRequests: 0 }; throw error; }
|
|
finally {
|
|
await runtime?.stopAll(); f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
|
fs.cpSync(f.root, path.join(sample, 'original-fixture'), { recursive: true, filter: file => !file.split(path.sep).includes('node_modules') });
|
|
for (const session of f.store.sessions.values()) fs.writeFileSync(path.join(sample, 'session-' + session.id + '.json'), JSON.stringify({ project: f.store.project(session.projectId), session, execution: f.store.executionSnapshot(session) }, null, 2));
|
|
fs.writeFileSync(path.join(sample, 'result.json'), JSON.stringify(result, null, 2));
|
|
for (const dispose of disposers.reverse()) await dispose();
|
|
}
|
|
}
|
|
let report;
|
|
try {
|
|
for (const kind of ['node', 'react', 'python']) results.push(await runSample(kind)); assert.deepEqual(inputs(), frozen);
|
|
report = { success: true, targetVersion: '1.14.0', testedVersion: version, directory, installation, cases, results, inputs: frozen, realModelRequests: 0,
|
|
scope: 'Pinned actual Harness and workbench execution with an owned HTTP model fixture. Checks, approvals, failures, parent merges, Edge and Git are real. Model reasoning and Purge benefit remain separate.' };
|
|
} catch (error) { report = { success: false, targetVersion: '1.14.0', testedVersion: version, directory, installation, cases, results, inputs: frozen, error: error.stack, realModelRequests: 0 }; process.exitCode = 1; }
|
|
finally { fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(report, null, 2)); fs.writeFileSync('.qa/controlled-projects-location.json', JSON.stringify({ directory, result: path.join(directory, 'result.json') })); console.log(JSON.stringify({ success: report.success, cases: cases.length, directory, realModelRequests: 0, error: report.error ?? null })); }
|