import fs from 'node:fs'; import path from 'node:path'; import net from 'node:net'; import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { DatabaseSync, backup } from 'node:sqlite'; import { publicSnapshot, compareWaitState, hash } from './model-wait-state.mjs'; import { InstallationManager, validateInstalledVersion } from '../src/core/desktop/install-manager.mjs'; import { inspectHostInstallation } from '../src/core/desktop/app-installation.mjs'; import { HostController } from '../src/core/desktop/host-controller.mjs'; import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs'; import { projectEnvironment } from '../src/core/process-environment.mjs'; import { upgradeRunning } from '../scripts/upgrade-running.mjs'; const read = file => JSON.parse(fs.readFileSync(file, 'utf8')); const save = (file, value) => fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', { flag: 'wx' }); const mode = process.argv[2]; assert.ok(['stage', 'upgrade', 'activate', 'verify'].includes(mode)); const release = read('releases/latest.json'); assert.equal(release.installer.version, '1.20.2'); assert.equal(release.installer.qaFixture, null); assert.equal(hash(fs.readFileSync(release.installer.path)), release.installer.sha256); const validated = read('.qa/model-wait-package-validation.json'); assert.equal(validated.success, true); assert.equal(validated.setupSha256, release.installer.sha256); const installRoot = 'C:/Users/wangy/AppData/Local/Programs/AgentWorkbench', originalPointer = read(path.join(installRoot, 'current.json')); const dataRoot = fs.realpathSync.native(originalPointer.dataRoot), candidate = path.resolve(installRoot, 'versions', release.installer.candidateDirectory); const url = 'http://127.0.0.1:4318', port = 4318, expectedPid = 36552, prefix = '.qa/model-wait-formal-c-'; const output = prefix + mode + '.json', beforeFile = prefix + 'before.json'; assert.equal(fs.existsSync(output), false, 'Do not repeat a sealed phase'); const startedAt = new Date().toISOString(); const originalProcess = () => { const value = observeWindowsProcess(expectedPid); assert.ok(value); assert.equal(value.createdAt, '2026-10-31T06:30:34.359Z'); assert.equal(hash(fs.readFileSync(value.executable)), 'd702daa815eabbff763c7d3808e235cf031cf2ca70211b56847bc72f51e240e5'); return value; }; async function inspectorClosed() { return new Promise((resolve, reject) => { const socket = net.createConnection({ host: '127.0.0.1', port: 9229 }); socket.setTimeout(1500); socket.once('connect', () => { socket.destroy(); reject(Error('An inspector is open')); }); socket.once('timeout', () => { socket.destroy(); reject(Error('Inspector state unknown')); }); socket.once('error', error => { socket.destroy(); error.code === 'ECONNREFUSED' ? resolve(true) : reject(error); }); }); } let result; try { originalProcess(); await inspectorClosed(); if (mode === 'stage') { assert.equal(fs.existsSync(candidate), false); assert.equal(fs.existsSync(beforeFile), false); const before = await publicSnapshot(url, dataRoot); assert.equal(before.version, '1.20.1'); assert.equal(before.pid, expectedPid); assert.deepEqual(before.active, []); const controller = new HostController({ appRoot: before.runtimeRoot, dataRoot, port, nodePath: process.execPath }); assert.ok(await controller.connect()); const status = await controller.status(); assert.equal(status.desktopWindows.count, 0); assert.equal(status.activity.active, false); const gateway = await controller.api('/companion'); assert.equal(gateway.enabled, false); assert.deepEqual(gateway.devices, []); save(beforeFile, before); save(prefix + 'original-pointer.json', originalPointer); const db = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true }), backupPath = path.resolve(prefix + 'original.sqlite'); assert.equal(fs.existsSync(backupPath), false); try { await backup(db, backupPath); } finally { db.close(); } const copy = new DatabaseSync(backupPath, { readOnly: true }); try { assert.equal(copy.prepare('PRAGMA quick_check').get().quick_check, 'ok'); } finally { copy.close(); } save(prefix + 'private-backup-receipt.json', { path: backupPath, bytes: fs.statSync(backupPath).size, sha256: hash(fs.readFileSync(backupPath)), committed: false, credentialsExtracted: false }); compareWaitState(before, await publicSnapshot(url, dataRoot)); const log = path.resolve(prefix + 'setup.log'); assert.equal(fs.existsSync(log), false); await promisify(execFile)(release.installer.path, ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/TASKS=desktopicon', '/DIR=' + installRoot, '/DATA_ROOT=' + dataRoot, '/PORT=' + port, '/STAGE_ONLY=1', '/LOG=' + log], { windowsHide: true, env: projectEnvironment(), timeout: 900000, maxBuffer: 1048576 }); const identity = validateInstalledVersion(candidate), after = await publicSnapshot(url, dataRoot), retained = compareWaitState(before, after); assert.equal(after.version, '1.20.1'); assert.deepEqual(read(path.join(installRoot, 'current.json')), originalPointer); result = { success: true, phase: 'staged', version: '1.20.2', candidateIdentity: identity.identitySha256, manifestSha256: identity.manifestSha256, retained, setupLog: log, setupLogSha256: hash(fs.readFileSync(log)) }; } else { const staged = read(prefix + 'stage.json'), before = read(beforeFile); assert.equal(staged.success, true); assert.equal(staged.setupSha256, release.installer.sha256); // Stage already verified every immutable candidate file; subsequent phase // gates bind the unchanged manifest and loaded inputs to that sealed proof. // Product activation still independently runs all of its full validations. const identity = inspectHostInstallation(candidate); assert.equal(identity.identitySha256, staged.candidateIdentity); assert.equal(identity.manifestSha256, staged.manifestSha256); const current = await publicSnapshot(url, dataRoot); compareWaitState(before, current); assert.deepEqual(current.active, []); if (mode === 'upgrade') { assert.equal(current.version, '1.20.1'); const info = read(path.join(dataRoot, 'service-info.json')); assert.equal(info.pid, expectedPid); const upgraded = await upgradeRunning({ url, pid: expectedPid, currentRoot: info.appRoot, handlerRoot: current.runtimeRoot, newRoot: candidate }); assert.equal(upgraded.connectionPreserved, true); const after = await publicSnapshot(url, dataRoot), retained = compareWaitState(before, after); assert.equal(after.version, '1.20.2'); assert.equal(after.runtimeRoot, candidate); await inspectorClosed(); save(prefix + 'after-upgrade.json', after); result = { success: true, phase: 'upgraded', version: '1.20.2', upgraded, retained, currentProviderPreserved: true }; } else { assert.equal(read(prefix + 'upgrade.json').success, true); assert.equal(current.version, '1.20.2'); assert.equal(current.runtimeRoot, candidate); let activated = null; if (mode === 'activate') { activated = await new InstallationManager({ installRoot, dataRoot, candidateRoot: candidate, port }).activate(); assert.equal(activated.phase, 'activated'); assert.equal(activated.hostRetained, false); } const controller = new HostController({ appRoot: candidate, dataRoot, port, nodePath: process.execPath }); assert.ok(await controller.connect()); const status = await controller.status(); assert.equal(status.identity.pid, expectedPid); assert.equal(status.activity.active, false); const gateway = await controller.api('/companion'); assert.equal(gateway.enabled, false); assert.deepEqual(gateway.devices, []); assert.equal(gateway.certificate, null); const pointer = read(path.join(installRoot, 'current.json')); assert.equal(pointer.active.directory, release.installer.candidateDirectory); assert.equal(pointer.active.runtimeIdentity, identity.identitySha256); assert.equal(fs.realpathSync.native(pointer.dataRoot), dataRoot); assert.equal(hash(fs.readFileSync(path.join(installRoot, 'AgentWorkbench.exe'))), hash(fs.readFileSync(path.join(candidate, 'AgentWorkbench.exe')))); const after = await publicSnapshot(url, dataRoot), retained = compareWaitState(before, after); await inspectorClosed(); save(prefix + 'after-' + mode + '.json', after); result = { success: true, phase: mode, activated, identity: status.identity, pointer, retained, currentProviderPreserved: true, companion: { enabled: gateway.enabled, devices: gateway.devices.length, certificate: gateway.certificate }, counts: { projects: after.projects, visibleSessions: after.visibleSessions, sessions: after.database.sessionIds.length, records: after.database.tables.records.count, events: after.database.tables.events.count, artifacts: after.persistent.artifacts.length }, inspectorClosed: true }; } } } catch (error) { result = { success: false, phase: mode, error: error.stack }; process.exitCode = 1; } save(output, { ...result, startedAt, finishedAt: new Date().toISOString(), installRoot, dataRoot, candidate, setupSha256: release.installer.sha256, originalProcess: originalProcess(), realModelRequests: 0 }); console.log(JSON.stringify({ success: result.success, phase: result.phase, output, error: result.error }));