Files
Agent-Workbench/scripts/verify-workers-projects.mjs
T
2026-10-31 02:28:09 +08:00

228 lines
24 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, call } from '../tests/helpers.mjs';
import { Provider } from '../src/server/provider.mjs';
import { Runtime } from '../src/server/runtime.mjs';
import { deliveryGit as git, writeDeliveryFile as write } from '../tests/fixtures/delivery-project.mjs';
import { ownerBytes } from '../tests/fixtures/workers-project.mjs';
import { releaseEvidencePrefix } from './qa-evidence.mjs';
if (process.argv.includes('--help')) { console.log('node scripts/verify-workers-projects.mjs — three owned Node/React/Python projects; fixed functional tests, real isolated worktrees, initial failures, reviewed repairs, parent checks/browser and local Git. No real model requests.'); process.exit(0); }
assert.equal(process.argv.length, 2, 'Use --help for supported options.');
const version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version, prefix = releaseEvidencePrefix(version);
const qaPython = process.env.AGENT_WORKBENCH_TEST_PYTHON;
assert.ok(typeof qaPython === 'string' && path.isAbsolute(qaPython) && fs.existsSync(qaPython), 'Provide the existing absolute independent Python 3.10+ interpreter in AGENT_WORKBENCH_TEST_PYTHON.');
const directory = path.resolve('.qa', 'workers-projects-' + randomUUID()), cases = [], results = [];
fs.mkdirSync(directory, { recursive: true });
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
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(), npmCli = path.join(path.dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');
const mark = value => { cases.push(value); console.log('PASS ' + value); };
const read = relative => fs.readFileSync(path.join('benchmarks', 'workers-delivery-v1', relative), 'utf8');
function definition(kind, root) {
if (kind === 'node') return {
lanes: [{ label: 'numbers', paths: ['src/add.mjs'], checks: ['test:add', 'build'], tests: 4,
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' } },
{ label: 'ranges', paths: ['src/range.mjs'], checks: ['test:range', 'build'], tests: 4,
fixes: { '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' } }], checks: ['test', 'build'], tests: 8 };
if (kind === 'react') {
const app = fs.readFileSync(path.join(root, 'src/App.tsx'), 'utf8');
assert.ok(app.includes("toggleTask(current, 'missing')"));
return { lanes: [{ label: 'query', paths: ['src/query.ts', 'src/App.tsx'], checks: ['test:query', 'typecheck', 'build'], tests: 5,
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/App.tsx': app.replace("toggleTask(current, 'missing')", 'toggleTask(current, task.id)') } },
{ label: 'state', paths: ['src/summary.ts', 'src/transition.ts'], checks: ['test:state', 'typecheck', 'build'], tests: 4,
fixes: { '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" } }], checks: ['test', 'typecheck', 'build'], tests: 9 };
}
return { lanes: [{ label: 'money', paths: ['money.py', 'tests/test_money.py'], checks: ['python:test', 'python:compile'], tests: 6,
initial: { 'money.py': 'def to_cents(value):\n return int(float(value) * 100)\n', 'tests/test_money.py': read('python-tests/test_money.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' } },
{ label: 'schedule', paths: ['schedule.py', 'tests/test_schedule.py'], checks: ['python:test', 'python:compile'], tests: 6,
initial: { 'schedule.py': 'def normalize_schedule(values):\n return list(values)\n', 'tests/test_schedule.py': read('python-tests/test_schedule.py') },
fixes: { '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' } }], checks: ['python:test', 'python:compile'], tests: 10 };
}
function preserve(root, names) { return Object.fromEntries(names.map(file => [file, fs.readFileSync(path.join(root, file))])); }
function verify(root, saved) { for (const [file, bytes] of Object.entries(saved)) assert.deepEqual(fs.readFileSync(path.join(root, file)), bytes, 'Protected ' + file); }
async function runSample(kind) {
const disposers = [], t = { after: value => disposers.push(value) }, f = fixture(t), sampleDir = path.join(directory, kind);
fs.mkdirSync(sampleDir); let runtime, group, result;
const requests = [], reviews = [], state = new Map();
try {
const baseline = kind === 'react' ? path.resolve('benchmarks/react-delivery-v1/baseline') : path.resolve('benchmarks/workers-delivery-v1', kind);
fs.cpSync(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');
if (kind === 'react') {
const file = path.join(f.projectRoot, 'package.json'), meta = JSON.parse(fs.readFileSync(file, 'utf8'));
meta.scripts['test:query'] = 'node --test --test-name-pattern="filter|pending shows|done shows|search" test/domain.test.mjs';
meta.scripts['test:state'] = 'node --test --test-name-pattern="actual totals|toggle|unknown identity" test/domain.test.mjs';
fs.writeFileSync(file, JSON.stringify(meta, null, 2) + '\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 + ' worker functional 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 = definition(kind, f.projectRoot), writable = spec.lanes.flatMap(lane => lane.paths), original = ownerBytes(f);
const protectedNames = git(f, ['ls-files', '-z']).split('\0').filter(file => file && !writable.includes(file) && !file.startsWith('owner-'));
const protectedBytes = preserve(f.projectRoot, protectedNames);
const install = (root, label) => {
const log = path.join(sampleDir, label + '-npm-ci-log.txt'), stderrLog = path.join(sampleDir, label + '-npm-ci-stderr-log.txt');
const output = spawnSync(process.execPath, [npmCli, 'ci', '--offline', '--no-audit', '--no-fund'], { cwd: root, windowsHide: true, timeout: 120000, maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
fs.writeFileSync(log, output.stdout ?? Buffer.alloc(0)); fs.writeFileSync(stderrLog, output.stderr ?? Buffer.alloc(0));
if (output.error) throw output.error; assert.equal(output.status, 0, 'Owned offline installation failed; inspect both original logs.');
verify(root, protectedBytes); reviews.push({ operation: 'owned offline dependency install', root, log, sha256: hash(fs.readFileSync(log)), stderrLog, stderrSha256: hash(fs.readFileSync(stderrLog)) });
};
if (kind === 'react') install(f.projectRoot, 'parent');
f.store.saveConfig({ mode: 'compatible', model: 'owned-workers-engineering', baseUrl: 'http://127.0.0.1:1/v1' });
const provider = new Provider(); provider.setKey('self-owned-workers-project-fixture');
provider.complete = async (config, messages, project, signal, progress, planned, tools) => {
signal.throwIfAborted();
const worker = [...f.store.core.worker.values()].find(value => value.projectId === project.id), session = f.store.session(worker.sessionId);
const lane = spec.lanes.find(value => value.label === worker.label), taskJobs = [...f.store.core.check_job.values()].filter(value => value.taskId === worker.taskId);
const job = taskJobs.at(-1), plan = [...f.store.core.check_plan.values()].filter(value => value.taskId === worker.taskId).at(-1);
let phase = state.get(worker.id) ?? 'new', calls = [];
const propose = files => Object.entries(files).map(([file, content]) => call(randomUUID(), 'propose_file', { path: file, content, reason: 'Owned fixed functional acceptance repair; retain every test and declaration' }));
if (session.changes.some(change => change.status === 'pending')) { /* Explicit QA review outside the model loop. */ }
else if (phase === 'new' && lane.initial) { calls = propose(lane.initial); state.set(worker.id, 'initial'); }
else if (phase !== 'fixed' && job) {
assert.equal(job.status, 'failed', job.summary); assert.ok(job.results.some(value => value.tests?.failed > 0));
calls = propose(lane.fixes); state.set(worker.id, 'fixed');
} else if (phase === 'fixed' && job?.status === 'passed') { assert.equal(job.results[0].tests.passed, lane.tests); }
else if (!plan || job?.planId === plan.id) calls = [call(randomUUID(), 'plan_checks', { names: lane.checks })];
else calls = [call(randomUUID(), 'run_checks', { plan_id: plan.id })];
requests.push({ projectId: project.id, taskId: worker.taskId, label: worker.label, tools: tools.map(value => value.function.name), calls: calls.map(value => value.function.name), phase, model: config.model });
return { message: { role: 'assistant', content: calls.length ? '' : 'Owned fixture completion requires actual host verification.', ...(calls.length ? { tool_calls: calls } : {}) }, usage: { total_tokens: 168, prompt_tokens: 123, completion_tokens: 45 } };
};
runtime = new Runtime(f.store, provider); f.onCleanup(() => runtime.stopAll()); const manager = runtime.workerManager();
runtime.checkRunner().pythonExecutable = qaPython;
group = await manager.plan(f.session, { goal: 'Deliver ' + kind + ' functional modules through two isolated workers, retained tests, parent validation and local Git',
budget: { maxTokens: 200000, maxSteps: 64, maxToolCalls: 128, maxDurationMs: 600000 },
children: spec.lanes.map(lane => ({ label: lane.label, goal: 'Implement and validate ' + lane.label + ' functional cases while preserving tests and declaration bytes.', paths: lane.paths })) });
await (await manager.prepare(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'ready', group.summary);
assert.equal(new Set(group.children.map(child => f.store.project(child.projectId).root)).size, 2); assert.deepEqual(ownerBytes(f), original);
for (const child of group.children) { const root = f.store.project(child.projectId).root; verify(root, protectedBytes); if (kind === 'react') install(root, child.label); }
mark(kind + ': two actual independent Git worktrees preserve source HEAD, owner staging and protected declarations/tests');
for (let turn = 0; turn < 4 && group.status !== 'ready_to_collect'; turn++) {
const pending = group.children.flatMap(child => f.store.session(child.sessionId).changes.filter(value => value.status === 'pending'));
if (pending.length) {
assert.equal(group.status, 'awaiting_review', group.summary);
for (const child of group.children) {
const session = f.store.session(child.sessionId), ids = session.changes.filter(value => value.status === 'pending').map(value => value.id);
if (!ids.length) continue;
const set = await runtime.changeSetManager().prepare(session, ids);
reviews.push({ operation: 'explicit child batch review', taskId: child.taskId, changeSetId: set.id, fingerprint: set.fingerprint, paths: set.files.map(value => value.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 child of group.children) {
const session = f.store.session(child.sessionId);
for (const approval of session.approvals.filter(value => value.status === 'pending')) {
assert.equal(f.store.core.tool.get(approval.invocationId)?.tool, 'run_checks');
const plan = [...f.store.core.check_plan.values()].filter(value => value.taskId === child.taskId).at(-1);
assert.deepEqual(plan.checks.map(value => value.name), spec.lanes.find(value => value.label === child.label).checks);
reviews.push({ operation: 'explicit owned check approval', taskId: child.taskId, planId: plan.id, contractSha256: plan.contractSha256, commands: plan.checks.map(value => value.command) });
runtime.decide(session.id, approval.id, true);
}
}
await new Promise(resolve => setTimeout(resolve, 20));
}
if (failure) throw failure;
}
assert.equal(group.status, 'ready_to_collect', group.summary); assert.deepEqual(ownerBytes(f), original);
for (const child of group.children) {
const lane = spec.lanes.find(value => value.label === child.label), root = f.store.project(child.projectId).root;
verify(root, protectedBytes);
for (const [file, text] of Object.entries({ ...lane.initial, ...lane.fixes })) assert.equal(fs.readFileSync(path.join(root, file), 'utf8'), text);
const jobs = [...f.store.core.check_job.values()].filter(value => value.taskId === child.taskId);
assert.ok(jobs.some(job => job.status === 'failed' && job.results.some(value => value.tests?.failed > 0)));
assert.equal(jobs.at(-1).status, 'passed'); assert.equal(jobs.at(-1).results[0].tests.passed, lane.tests);
}
mark(kind + ': both workers retain actual failing tests and pass their fixed functional scope after reviewed repairs');
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.slice().sort());
await (await manager.prepareMerge(f.session, group.id, group.fingerprint)).promise; assert.equal(group.status, 'merge_prepared', group.summary);
const merged = f.store.core.change_set.get(group.merge.changeSetId);
reviews.push({ operation: 'explicit parent batch review', taskId: group.taskId, changeSetId: merged.id, fingerprint: merged.fingerprint, paths: merged.files.map(value => value.path) });
await (await runtime.changeSetManager().start(f.session, merged.id, merged.fingerprint)).promise; assert.equal(merged.status, 'completed', merged.summary);
const plan = await runtime.checkRunner().plan(f.session, spec.checks), check = await (await runtime.checkRunner().start(f.session, plan.id)).promise;
assert.equal(check.status, 'passed', check.summary); assert.equal(check.results[0].tests.passed, spec.tests); verify(f.projectRoot, protectedBytes);
mark(kind + ': a separately reviewed parent batch passes the complete ' + spec.tests + '-test functional suite and actual build/compile');
const browserJobs = [], screenshots = [];
if (kind === 'react') {
const steps = [
{ action: 'assert_count', selector: '.task-list article', count: 3 },
{ action: 'assert_text', selector: '.summary > div:nth-child(2) strong', text: '1' },
{ action: 'assert_text', selector: '.summary > div:nth-child(3) strong', text: '8\n小时' },
{ action: 'select', selector: 'select[aria-label="任务状态"]', value: 'pending' },
{ action: 'assert_count', selector: '.task-list article', count: 2 },
{ action: 'select', selector: 'select[aria-label="任务状态"]', value: 'done' },
{ action: 'fill', selector: 'input[aria-label="任务搜索"]', value: ' 验证 ' },
{ action: 'assert_count', selector: '.task-list article', count: 1 },
{ action: 'fill', selector: 'input[aria-label="任务搜索"]', value: '不存在' },
{ action: 'assert_count', selector: '.task-list article', count: 0 },
{ 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: '5\n小时' },
];
for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
const viewportSteps = steps.map(step => step.action === 'assert_text' && step.selector === '.summary > div:nth-child(3) strong' && viewport.width > 600
? { ...step, text: step.text.replace('\n', '') } : step);
const browser = runtime.browserManager(), plan = await browser.plan(f.session, { viewport, steps: viewportSteps }), job = await browser.start(f.session, plan.id).promise;
assert.equal(job.status, 'passed', job.summary); assert.equal(job.cleanup.exited, true); assert.ok(job.assertions.passed >= 8); browserJobs.push(job);
for (const image of job.screenshots) {
const artifact = f.store.owned('artifact', image.artifactId, f.session.id), bytes = f.store.artifactStore.readBytes(artifact);
const file = path.join(sampleDir, 'page-' + viewport.width + '-' + image.artifactId + '.png'); fs.writeFileSync(file, bytes); screenshots.push({ file, artifactId: artifact.id, sha256: hash(bytes) });
}
}
mark('react: the integrated browser observes actual desktop/390px filtering, trimmed search, empty state, one-task toggle and updated totals');
}
const deliveryPlan = await runtime.gitDelivery().plan(f.session, { message: 'Reviewed ' + kind + ' isolated-worker functional delivery' });
const 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.slice().sort());
mark(kind + ': local Git commits only reviewed functional files while retaining original owner working/staged bytes and complete evidence');
result = { success: true, version, kind, groupId: group.id, parentTaskId: group.taskId, parentChecks: check, browserJobs, screenshots, commit: delivery.commit,
paths: writable, children: group.children.map(child => f.store.core.worker.get(child.id)), checkJobs: [...f.store.core.check_job.values()], reviews, requests,
protectedFiles: Object.fromEntries(Object.entries(protectedBytes).map(([file, bytes]) => [file, hash(bytes)])), realModelRequests: 0 };
return result;
} catch (error) { result = { success: false, version, kind, error: error.stack, group, reviews, requests, checkJobs: [...f.store.core.check_job.values()], realModelRequests: 0 }; throw error; }
finally {
await runtime?.stopAll(); f.store.storage.database.exec('PRAGMA wal_checkpoint(TRUNCATE)');
const archive = path.join(sampleDir, 'original-fixture'); fs.cpSync(f.root, archive, { recursive: true, filter: file => !file.split(path.sep).includes('node_modules') });
const exports = [];
for (const session of f.store.sessions.values()) {
const file = path.join(sampleDir, 'session-' + session.id + '.json');
const value = { schemaVersion: 1, executionSchemaVersion: 1, exportedAt: new Date().toISOString(), project: f.store.project(session.projectId), session, execution: f.store.executionSnapshot(session) };
fs.writeFileSync(file, JSON.stringify(value, null, 2)); exports.push({ file, sha256: hash(fs.readFileSync(file)) });
}
if (result) { result.originalFixture = archive; result.exports = exports; result.archiveExcludes = ['node_modules']; }
fs.writeFileSync(path.join(sampleDir, '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, version, createdAt: new Date().toISOString(), directory, cases, results, inputs: frozen, realModelRequests: 0,
scope: 'Three owned functional projects. A predefined local Provider fixture supplies repairs; all worktrees, failures, approvals, files, checks, Edge interactions and commits are real. Configured-model reasoning and autonomous task success remain separately unaccepted.' };
} catch (error) { report = { success: false, version, directory, cases, results, error: error.stack, inputs: frozen, realModelRequests: 0 }; process.exitCode = 1; }
finally { fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(report, null, 2)); if (report.success) fs.writeFileSync('docs/' + prefix + '-projects-validation.json', JSON.stringify(report, null, 2)); console.log('EVIDENCE ' + directory); }