fix: upgrade directly launched hosts and freeze package QA evidence

This commit is contained in:
Agent Workbench Dev
2026-10-30 14:45:50 +08:00
parent 96de94e722
commit eab5ac077a
7 changed files with 111 additions and 11 deletions
+14 -1
View File
@@ -106,8 +106,21 @@ export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRo
const probe = readUpgradeJson(origin + '/api/health', 15000, 'Observe owned request handler');
probe.catch(() => {});
const event = await within(pausedEvent, 10000, 'Workbench request observation');
const captureExpression = "(() => {"
+ " const currentServer = typeof server !== 'undefined' ? server : typeof server2 !== 'undefined' ? server2 : undefined;"
+ " const currentStore = typeof store !== 'undefined' ? store : typeof store2 !== 'undefined' ? store2 : undefined;"
+ " const currentProvider = typeof provider !== 'undefined' ? provider : typeof provider2 !== 'undefined' ? provider2 : undefined;"
+ " const currentRuntime = typeof runtime !== 'undefined' ? runtime : typeof runtime2 !== 'undefined' ? runtime2 : undefined;"
+ " const currentToken = typeof token !== 'undefined' ? token : typeof token2 !== 'undefined' ? token2 : undefined;"
+ " const currentClients = typeof clients !== 'undefined' ? clients : typeof clients2 !== 'undefined' ? clients2 : undefined;"
+ " const currentStarted = typeof started !== 'undefined' ? started : typeof started2 !== 'undefined' ? started2 : undefined;"
+ " const currentExampleProject = typeof exampleProject !== 'undefined' ? exampleProject : typeof exampleProject2 !== 'undefined' ? exampleProject2 : undefined;"
+ " const currentShutdown = typeof shutdown !== 'undefined' ? shutdown : typeof shutdown2 !== 'undefined' ? shutdown2 : undefined;"
+ " const servers = currentServer ? [currentServer] : process._getActiveHandles().filter(handle => handle?.listening && handle.address?.()?.address === '127.0.0.1' && handle.address?.()?.port === " + new URL(origin).port + ");"
+ " if (servers.length !== 1 || !currentStore || !currentProvider || !currentRuntime || !currentToken || !currentClients || !currentShutdown) throw new Error('The existing Workbench context is incomplete.');"
+ " globalThis.__awUpgradeContext = { server: servers[0], store: currentStore, provider: currentProvider, runtime: currentRuntime, token: currentToken, clients: currentClients, started: currentStarted, exampleProject: currentExampleProject, shutdown: currentShutdown }; return 'context-ready'; })()";
const captured = await protocol.send('Debugger.evaluateOnCallFrame', { callFrameId: event.callFrames[0].callFrameId,
expression: "(() => { const servers = typeof server !== 'undefined' ? [server] : process._getActiveHandles().filter(handle => handle?.listening && handle.address?.()?.address === '127.0.0.1' && handle.address?.()?.port === " + new URL(origin).port + "); if (servers.length !== 1) throw new Error('Owned local server not found uniquely'); globalThis.__awUpgradeContext = { server: servers[0], store, provider, runtime, token, clients, started, exampleProject, shutdown }; return 'context-ready'; })()", returnByValue: true });
expression: captureExpression, returnByValue: true });
if (captured.exceptionDetails || captured.result.value !== 'context-ready') throw new Error('Could not retain the existing runtime objects.');
for (const breakpointId of breakpoints.splice(0)) await protocol.send('Debugger.removeBreakpoint', { breakpointId });
await protocol.send('Debugger.resume'); paused = false; await probe;
+38 -9
View File
@@ -1,8 +1,8 @@
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { spawn, execFileSync } from 'node:child_process';
const workspace = process.cwd();
const evidence = JSON.parse(fs.readFileSync('.qa/archives-validation.json', 'utf8'));
@@ -22,24 +22,52 @@ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => all
const inheritedPath = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] || '';
for (const key of Object.keys(env)) if (key.toLowerCase() === 'path') delete env[key];
env.PATH = [path.dirname(process.execPath), inheritedPath].filter(Boolean).join(path.delimiter);
let stage = 'install';
const directory = path.join(sourceRoot, '.qa', 'package-validation-' + randomUUID());
fs.mkdirSync(directory, { recursive: true });
const inputFolders = ['src', 'tests', 'scripts'];
const inputNames = [...inputFolders.flatMap(folder => files(path.join(sourceRoot, folder)).map(relative => path.join(folder, relative))),
'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'index.html'].sort();
const snapshot = () => inputNames.map(relative => ({ path: relative.replaceAll('\\', '/'), bytes: fs.statSync(path.join(sourceRoot, relative)).size, sha256: digest(path.join(sourceRoot, relative)) }));
const inputs = snapshot(); fs.writeFileSync(path.join(directory, 'inputs.json'), JSON.stringify(inputs, null, 2));
let stage = 'environment preflight', python = null;
const resultFile = path.join(workspace, '.qa/source-package-validation.json');
const logs = [];
function save(result) {
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
fs.writeFileSync(resultFile, JSON.stringify(result, null, 2));
}
function run(args, logName) {
console.log('Source package: ' + stage);
return new Promise((resolve, reject) => {
const outputFile = fs.createWriteStream(path.join(sourceRoot, logName));
const logPath = path.join(directory, logName);
const outputFile = fs.createWriteStream(logPath);
const child = spawn(process.execPath, args, { cwd: sourceRoot, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
let tail = '';
const capture = bytes => { outputFile.write(bytes); tail = (tail + bytes.toString('utf8')).slice(-12000); };
child.stdout.on('data', capture); child.stderr.on('data', capture);
const timer = setTimeout(() => child.kill(), 600000);
child.once('error', error => { clearTimeout(timer); outputFile.end(); reject(error); });
child.once('close', code => { clearTimeout(timer); outputFile.end(); code === 0 ? resolve(tail) : reject(new Error(stage + ' failed (' + code + '): ' + tail)); });
child.once('close', code => { clearTimeout(timer); outputFile.end(() => {
logs.push({ stage, path: logPath, sha256: digest(logPath), bytes: fs.statSync(logPath).size });
code === 0 ? resolve(tail) : reject(new Error(stage + ' failed (' + code + '): ' + tail));
}); });
});
}
try {
assert.equal(JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8')).version, evidence.version);
assert.match(process.version, /^v24\./, 'Source package validation requires Node.js 24.');
if (env.AGENT_WORKBENCH_TEST_PYTHON) {
assert.ok(path.isAbsolute(env.AGENT_WORKBENCH_TEST_PYTHON) && fs.existsSync(env.AGENT_WORKBENCH_TEST_PYTHON), 'AGENT_WORKBENCH_TEST_PYTHON must name an existing absolute QA interpreter.');
const executable = fs.realpathSync.native(env.AGENT_WORKBENCH_TEST_PYTHON);
python = JSON.parse(execFileSync(executable, ['-I', '-c', 'import json,sys,pytest; print(json.dumps({"version":sys.version.split()[0],"pytest":pytest.__version__}))'], { env, windowsHide: true, encoding: 'utf8', timeout: 10000 }));
assert.ok(Number(python.version.split('.')[0]) === 3 && Number(python.version.split('.')[1]) >= 10, 'QA Python must be 3.10 or newer.');
assert.equal(python.pytest, '8.4.2', 'Install the fixed QA requirements before validating the source package.');
python.path = executable; env.AGENT_WORKBENCH_TEST_PYTHON = executable;
}
console.log(JSON.stringify({ sourceRoot, directory, nodeVersion: process.version, python }));
stage = 'install';
await run([npmCli, 'ci', '--offline', '--no-audit', '--no-fund'], 'install.log');
stage = 'build'; await run([npmCli, 'run', 'build'], 'build.log');
const actualFiles = ['dist-client', 'dist-server'].flatMap(folder => files(path.join(sourceRoot, folder)).map(relative => path.join(folder, relative)));
@@ -75,10 +103,11 @@ try {
const output = await run(['--test', '--test-concurrency=2', '--test-reporter=tap', ...files(path.join(sourceRoot, 'tests')).filter(file => !file.includes(path.sep) && file.endsWith('.test.mjs')).map(file => path.join('tests', file))], 'tests.tap');
const stats = Object.fromEntries([...output.matchAll(/^# (tests|pass|fail|cancelled|skipped|todo) (\d+)\s*$/gm)].map(match => [match[1], Number(match[2])]));
assert.ok(stats.tests > 0); assert.equal(stats.pass, stats.tests); for (const key of ['fail', 'cancelled', 'skipped', 'todo']) assert.equal(stats[key], 0);
const result = { success: true, version: evidence.version, testedAt: new Date().toISOString(), sourceRoot, offlineInstall: true,
buildMatchedFiles: Object.keys(expected).length, tests: stats, actualRea, actualEngine, actualBrowser, credentialsHandling: 'Only build/runtime environment paths are inherited; no model configuration or credentials are used.' };
fs.writeFileSync(resultFile, JSON.stringify(result, null, 2)); console.log(JSON.stringify(result, null, 2));
assert.deepEqual(snapshot(), inputs, 'Source package inputs changed during validation.');
const result = { success: true, version: evidence.version, testedAt: new Date().toISOString(), sourceRoot, directory, nodeVersion: process.version, python, offlineInstall: true,
inputs, inputFiles: inputs.length, logs, buildMatchedFiles: Object.keys(expected).length, tests: stats, actualRea, actualEngine, actualBrowser, credentialsHandling: 'Only build/runtime environment paths are inherited; no model configuration or credentials are used.' };
save(result); console.log(JSON.stringify({ success: true, version: result.version, sourceRoot, directory, tests: stats, nodeVersion: process.version, python, inputFiles: inputs.length, buildMatchedFiles: result.buildMatchedFiles, rea: !!actualRea?.success, engine: !!actualEngine?.success, browser: !!actualBrowser?.success }));
} catch (error) {
fs.writeFileSync(resultFile, JSON.stringify({ success: false, version: evidence.version, stage, error: error.message, sourceRoot }, null, 2));
save({ success: false, version: evidence.version, testedAt: new Date().toISOString(), stage, error: error.message, sourceRoot, directory, nodeVersion: process.version, python, inputs, logs });
throw error;
}