Files
Agent-Workbench/docs/live-model-identity-j-evidence/drivers/preflight-j.mjs
T
2026-11-03 13:32:06 +08:00

209 lines
14 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { DatabaseSync } from 'node:sqlite';
import { publicSnapshot, hash, digest, canonical } from './desktop-f-state.mjs';
const root = path.resolve('.qa/live-retest-j');
const origin = 'http://127.0.0.1:4318';
const dataRoot = 'C:/Users/wangy/AppData/Local/Packages/OpenAI.Codex_2p2nqsd0c76g0/LocalCache/Local/AgentWorkbench';
const connectionId = '09b0293b-faad-45c3-832d-7c8b615813aa';
assert.equal(fs.existsSync(root), false, 'Do not overwrite or replay a real sample.');
fs.mkdirSync(root);
const save = (name, value) => fs.writeFileSync(path.join(root, name), JSON.stringify(value, null, 2) + '\n', { flag: 'wx' });
const boot = await (await fetch(origin + '/api/bootstrap')).json();
const api = async (route, input) => {
const response = await fetch(origin + '/api' + route, {
method: input === undefined ? 'GET' : 'POST',
headers: { 'X-Workbench-Token': boot.token, 'Content-Type': 'application/json', Connection: 'close' },
...(input === undefined ? {} : { body: JSON.stringify(input) }), signal: AbortSignal.timeout(30000),
});
const value = await response.json();
assert.ok(response.ok, route + ': ' + (value.error ?? response.status));
return value;
};
const readMeta = name => {
const db = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true });
try { return JSON.parse(db.prepare('SELECT value FROM metadata WHERE key=?').get(name).value); }
finally { db.close(); }
};
const attemptsBefore = readMeta('modelAttempts');
const registryBefore = readMeta('modelRegistry');
const configBefore = readMeta('config');
const release = JSON.parse(fs.readFileSync('docs/delivery-integrity-i-release-identity.json'));
assert.equal(boot.version, '1.24.2');
assert.equal(boot.runtimeRoot, release.installedRuntimeRoot);
const host = await api('/host/status');
assert.equal(host.activity.active, false);
assert.equal(host.identity.pid, 36552);
const before = await publicSnapshot(origin, dataRoot);
assert.deepEqual(before.active, []);
const centerBefore = await api('/model-center');
const original = centerBefore.connections.find(c => c.id === connectionId);
assert.equal(original.name, 'apikey');
assert.equal(original.model, 'claude-opus-5-5');
assert.equal(original.protocol, 'chat-completions');
assert.equal(original.hasKey, true);
assert.equal(original.enabled, true);
const installedManifest = JSON.parse(fs.readFileSync(path.join(boot.runtimeRoot, 'MANIFEST.json')));
const runtimeFiles = installedManifest.files.filter(f => f.path.startsWith('dist-') || f.path === 'package.json');
assert.ok(runtimeFiles.length >= 22);
for (const file of runtimeFiles) assert.equal(hash(fs.readFileSync(path.join(boot.runtimeRoot, file.path))), file.sha256, file.path);
save('before.json', before);
save('setup.json', { version: boot.version, pid: before.pid, runtime: boot.runtimeRoot, connection: original,
originalConfig: boot.config, originalSelection: centerBefore.selected, originalRegistry: registryBefore,
originalAttempts: attemptsBefore, originalDiskConfig: configBefore,
sourceCommit: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8', windowsHide: true }).trim(),
runtimeFiles, startedAt: new Date().toISOString(), keyHandling: 'Original Provider only; no credential extraction, copy, decryption, or restart.' });
const nonce = randomUUID();
save('contract.json', { schema: 1, kind: 'single-real-model-identity-preflight', connectionId,
requestedModel: original.model, endpoint: original.baseUrl, protocol: original.protocol,
modelIdentityPolicy: 'require-match', aliases: [], maxRequests: 1, maxOutputTokens: 256,
maxTaskTokens: 16000, contextLimit: 16000, maxDurationMs: 320000, maxAttempts: 1,
poolSwitching: false, automaticReplay: false, engineeringImplementationSupplied: false,
prompt: '这是独立连接身份预检,不是工程任务。只回复 OK ' + nonce + ',不要调用工具、读写文件或执行命令。',
nonce, baselineSha256: hash(fs.readFileSync(path.join(root, 'before.json'))),
originalIdentityDefaultAbsent: !Object.hasOwn(original, 'modelIdentityPolicy'),
restoration: 'Restore original parameters/selection through public APIs; absent identity settings become explicit equivalent record/[]/empty defaults. Preserve monotonic revisions and disclose this additive normalization.' });
const fields = ['id', 'name', 'brand', 'model', 'protocol', 'baseUrl', 'enabled', 'requiresKey', 'streaming',
'capabilityDeclarations', 'nativeParameters', 'outputTokenField', 'contextLimit', 'maxOutputTokens', 'concurrency',
'modelIdentityPolicy', 'modelIdentityAliases', 'modelIdentityAliasSource'];
const connectionInput = value => Object.fromEntries(fields.filter(k => Object.hasOwn(value, k)).map(k => [k, value[k]]));
let configured, project, session, state, result, configurationChanged = false;
const observedStatuses = [];
try {
configured = await api('/model-center/connections', { ...connectionInput(original), revision: original.revision,
modelIdentityPolicy: 'require-match', modelIdentityAliases: [], modelIdentityAliasSource: '' });
configurationChanged = true;
assert.equal(configured.hasKey, true);
assert.equal(configured.credentialRevision, original.credentialRevision);
await api('/config', { ...boot.config, maxSteps: 1, maxOutputTokens: 256, contextLimit: 16000,
maxRunTokens: 16000, maxTaskTokens: 16000, maxRunDurationMs: 320000 });
await api('/model-center/select', { type: 'connection', id: connectionId });
const frozenCenter = await api('/model-center');
assert.deepEqual(frozenCenter.selected, { type: 'connection', id: connectionId });
save('connection-frozen.json', configured);
const projectRoot = path.join(root, 'identity-only');
fs.mkdirSync(projectRoot);
fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Isolated identity preflight\nNo engineering task or commands are authorized in this sample.\n', { flag: 'wx' });
project = await api('/projects', { root: projectRoot });
session = await api('/sessions', { projectId: project.id });
save('owned.json', { project, session });
const contract = JSON.parse(fs.readFileSync(path.join(root, 'contract.json')));
await api('/sessions/' + session.id + '/messages', { content: contract.prompt });
const deadline = Date.now() + 340000;
while (true) {
state = await api('/sessions/' + session.id);
const attempts = readMeta('modelAttempts').filter(a => !attemptsBefore.some(old => old.id === a.id));
assert.ok(attempts.length <= 1, 'Never dispatch more than the sealed single request.');
for (const attempt of attempts) {
assert.equal(attempt.sessionId, session.id);
assert.equal(attempt.connectionId, connectionId);
assert.equal(attempt.ordinal, 1);
}
const progress = { status: state.status, attempts: attempts.length,
identity: attempts[0]?.modelIdentity?.status ?? null, reportedTokens: attempts[0]?.usage?.total_tokens ?? null };
if (!observedStatuses.length || JSON.stringify(progress) !== JSON.stringify(observedStatuses.at(-1))) {
observedStatuses.push(progress); console.log(JSON.stringify(progress));
}
if (!['running', 'stopping'].includes(state.status)) break;
assert.ok(Date.now() < deadline, 'Single-request preflight deadline reached; do not retry.');
await new Promise(resolve => setTimeout(resolve, 500));
}
const attempts = readMeta('modelAttempts').filter(a => !attemptsBefore.some(old => old.id === a.id));
save('attempts.json', attempts);
save('session.json', state);
save('session-export.json', await api('/sessions/' + session.id + '/export'));
const captures = [];
for (const attempt of attempts) for (const kind of ['request', 'response']) {
const id = attempt[kind + 'ArtifactId'];
if (!id) continue;
let content = '', page, offset = 0;
do { page = await api('/artifacts/' + id + '?session=' + session.id + '&offset=' + offset + '&limit=16000');
content += page.content; offset += page.content.length;
} while (page.truncated);
assert.equal(hash(content), page.sha256, 'Captured original artifact SHA');
const file = kind + (kind === 'request' ? '.json' : attempt.streaming ? '.sse' : '.txt');
fs.writeFileSync(path.join(root, file), content, { flag: 'wx' });
captures.push({ kind, file, id, sha256: page.sha256, bytes: Buffer.byteLength(content) });
if (kind === 'request') {
const body = JSON.parse(content);
assert.equal(body.model, original.model);
assert.equal(body.max_tokens ?? body.max_completion_tokens, 256);
assert.equal(hash(JSON.stringify(body)), attempt.requestSha256);
} else assert.equal(page.sha256, attempt.responseSha256);
}
const attempt = attempts[0];
const usage = state.execution.task?.usage;
const actualTools = state.execution.progress.totalTools;
const identityPassed = attempts.length === 1 && attempt.status === 'completed'
&& attempt.modelIdentity?.status === 'matched' && attempt.modelIdentity.complete === true
&& attempt.modelIdentity.policy === 'require-match' && attempt.responseRedacted === false
&& captures.length === 2 && attempt.usageStatus === 'reported' && attempt.usage?.total_tokens <= 16000
&& actualTools === 0;
result = { identityPassed, engineeringTestAllowed: identityPassed,
testedAt: new Date().toISOString(), version: boot.version, pid: before.pid, connectionId,
connectionName: original.name, requestedModel: original.model, reportedModels: attempt?.modelIdentity?.reportedModels ?? [],
identityStatus: attempt?.modelIdentity?.status ?? 'not-dispatched', sessionId: session.id,
taskId: state.execution.task?.id, sessionStatus: state.status, stopReason: state.failure?.kind ?? state.execution.runs?.at(-1)?.stopReason,
requests: attempts.length, usageStatus: attempt?.usageStatus ?? 'not_dispatched', usage: attempt?.usage ?? null,
taskUsage: usage, actualTools, captures,
noRetry: attempts.length <= 1, noPoolSwitch: attempts.every(a => a.connectionId === connectionId && !a.poolId),
reportedIdentifierOnly: true, modelWeightsAuthenticated: false, realEngineeringDeliveryTested: false,
purgeBenefitTested: false, observedStatuses };
save('result.json', result);
console.log(JSON.stringify(result));
} catch (error) {
save('driver-error.json', { name: error.name, message: error.message, stack: error.stack, at: new Date().toISOString() });
throw error;
} finally {
if (session) {
const live = await api('/sessions/' + session.id);
if (['running', 'stopping', 'awaiting_approval'].includes(live.status)) await api('/sessions/' + session.id + '/stop', {});
}
assert.equal((await api('/host/status')).activity.active, false, 'Do not override another active task.');
if (configurationChanged) {
const current = (await api('/model-center')).connections.find(c => c.id === connectionId);
assert.equal(current.revision, configured.revision, 'Do not overwrite a user connection edit.');
const restored = await api('/model-center/connections', { ...connectionInput(original), revision: current.revision,
modelIdentityPolicy: original.modelIdentityPolicy ?? 'record', modelIdentityAliases: original.modelIdentityAliases ?? [],
modelIdentityAliasSource: original.modelIdentityAliasSource ?? '' });
assert.equal(restored.hasKey, true);
assert.equal(restored.credentialRevision, original.credentialRevision);
await api('/config', boot.config);
await api('/model-center/select', centerBefore.selected);
save('connection-restored.json', restored);
}
const after = await publicSnapshot(origin, dataRoot);
save('after.json', after);
assert.equal(after.pid, before.pid); assert.equal(after.version, before.version);
assert.equal(after.runtimeRoot, before.runtimeRoot); assert.equal(after.hasKey, before.hasKey); assert.deepEqual(after.active, []);
for (const item of before.exports) assert.deepEqual(after.exports.find(e => e.id === item.id), item, 'Original session export ' + item.id);
const artifactMap = new Map(after.persistent.artifacts.map(a => [a.path, a]));
for (const artifact of before.persistent.artifacts) assert.deepEqual(artifactMap.get(artifact.path), artifact, 'Original artifact bytes ' + artifact.path);
for (const name of ['records', 'events', 'outbox', 'sessions']) {
const rows = new Map(after.database.tables[name].rows.map(r => [r.id, r]));
for (const row of before.database.tables[name].rows) assert.deepEqual(rows.get(row.id), row, 'Original ' + name + '/' + row.id);
}
const restoredBoot = await api('/bootstrap');
const restoredConfig = { ...restoredBoot.config }; restoredConfig.configRevision = boot.config.configRevision;
assert.deepEqual(canonical(restoredConfig), canonical(boot.config));
assert.deepEqual(after.modelCenter.selected, centerBefore.selected);
assert.deepEqual(after.modelCenter.pools, centerBefore.pools);
const afterAttempts = readMeta('modelAttempts');
for (const attempt of attemptsBefore) assert.deepEqual(afterAttempts.find(a => a.id === attempt.id), attempt, 'Original attempt ' + attempt.id);
save('restoration.json', { passed: true, pid: after.pid, version: after.version, hasKey: after.hasKey, runtimeRoot: after.runtimeRoot,
originalExports: before.exports.length, originalArtifactFiles: before.persistent.artifacts.length,
originalAttempts: attemptsBefore.length, addedAttempts: afterAttempts.length - attemptsBefore.length,
originalRowsExact: ['records', 'events', 'outbox', 'sessions'], originalSelectionRestored: true,
originalConfigRestoredExceptMonotonicRevision: true, originalCredentialRevision: original.credentialRevision,
restoredCredentialRevision: after.modelCenter.connections.find(c => c.id === connectionId).credentialRevision,
publicIdentityDefaultMadeExplicit: !Object.hasOwn(original, 'modelIdentityPolicy'),
afterSha256: hash(fs.readFileSync(path.join(root, 'after.json'))) });
console.log(JSON.stringify({ restorationPassed: true, requests: afterAttempts.length - attemptsBefore.length,
originalExports: before.exports.length, originalArtifactFiles: before.persistent.artifacts.length }));
}