Files
Agent-Workbench/scripts/retained-host-state.mjs
T

63 lines
5.8 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { snapshotPersistentData } from '../src/core/desktop/install-manager.mjs';
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
export const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
export const digest = value => hash(JSON.stringify(canonical(value)));
export function databaseSnapshot(dataRoot) {
const database = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true }); database.exec('BEGIN');
try {
assert.equal(database.prepare('PRAGMA quick_check').get().quick_check, 'ok');
const tables = {};
for (const { name, sql } of database.prepare("SELECT name,sql FROM sqlite_schema WHERE type='table' ORDER BY name").all()) {
assert.match(name, /^[a-z_]+$/);
const rows = database.prepare('SELECT * FROM "' + name + '" ORDER BY rowid').all().filter(row => !(name === 'metadata' && row.key === 'runtimeOwner'));
tables[name] = { count: rows.length, schemaSha256: hash(sql), sha256: digest(rows), rows: rows.map((row, index) => ({ id: row.id ?? row.key ?? row.seq ?? index, ...(row.kind ? { kind: row.kind } : {}), sha256: digest(row) })) };
}
const sessionIds = database.prepare('SELECT id FROM sessions ORDER BY id').all().map(row => row.id);
const owner = database.prepare("SELECT value FROM metadata WHERE key='runtimeOwner'").get();
return { tables, sessionIds, ownerSha256: owner ? digest(owner) : null, scope: 'Every original table schema and row field hashed, excluding only runtimeOwner lifecycle metadata. No row payload or credential is returned.' };
} finally { database.exec('ROLLBACK'); database.close(); }
}
export async function publicSnapshot(url, dataRoot) {
const healthResponse = await fetch(url + '/api/health', { headers: { Connection: 'close' }, signal: AbortSignal.timeout(20000) }); assert.equal(healthResponse.status, 200);
const health = await healthResponse.json(), bootResponse = await fetch(url + '/api/bootstrap', { headers: { Connection: 'close' }, signal: AbortSignal.timeout(20000) }); assert.equal(bootResponse.status, 200);
const bootstrap = await bootResponse.json(); const token = bootstrap.token;
const api = async route => { const response = await fetch(url + '/api' + route, { headers: { 'X-Workbench-Token': token, Connection: 'close' }, signal: AbortSignal.timeout(20000) }); assert.ok(response.ok, route + ': HTTP ' + response.status); return response.json(); };
const database = databaseSnapshot(dataRoot), exports = [];
for (const id of database.sessionIds) {
const report = await api('/sessions/' + id + '/export');
exports.push({ id, project: digest(report.project), session: digest(report.session), execution: digest(report.execution) });
}
const center = await api('/model-center');
// This is the documented public model-center view; Provider's private map and
// API key are never accessed. Only this public object is retained for schema-aware comparison.
const modelCenter = structuredClone(center);
return { observedAt: new Date().toISOString(), version: health.version, pid: health.pid, runtimeRoot: bootstrap.runtimeRoot,
configSha256: digest(bootstrap.config), projectsSha256: digest(bootstrap.projects), sessionsSha256: digest(bootstrap.sessions), modelCenterSha256: digest(modelCenter), modelCenter,
projects: bootstrap.projects.length, visibleSessions: bootstrap.sessions.length, hasKey: !!bootstrap.config.hasKey,
active: bootstrap.sessions.filter(value => ['running', 'awaiting_approval', 'stopping'].includes(value.status)).map(value => ({ id: value.id, status: value.status })),
storage: bootstrap.storage, eventCursor: bootstrap.eventCursor, database, exports, persistent: snapshotPersistentData(dataRoot),
scope: 'Read-only public state, every original session export digest, original table/row/schema hashes and every original artifact byte hash. No credential extraction, model probe, execution or mutation.' };
}
export function compareOriginalState(before, after, { modelCenterSchemaChange = false } = {}) {
for (const field of ['pid', 'hasKey', 'configSha256', 'projectsSha256', 'sessionsSha256', 'eventCursor']) assert.deepEqual(after[field], before[field], field);
assert.deepEqual(canonical(after.database.tables), canonical(before.database.tables), 'All original table schemas and every persistent row');
assert.deepEqual(after.database.sessionIds, before.database.sessionIds); assert.deepEqual(after.exports, before.exports);
assert.deepEqual(after.persistent, before.persistent, 'Every original artifact byte, persistent row and public disk config');
if (modelCenterSchemaChange) {
const original = structuredClone(before.modelCenter), next = structuredClone(after.modelCenter);
// 1.15 changes only the public explanatory text about optional DPAPI storage.
// Existing IDs, routes, revisions, credentials-present bits and all original attempts remain exact.
assert.match(next.storage.restart, /临时凭据.*已明确本机加密保存/);
next.storage.restart = original.storage.restart;
assert.deepEqual(next, original, 'Original public model center, except versioned storage explanation');
return { modelCenterChange: { path: '/storage/restart', original: before.modelCenter.storage.restart, actual: after.modelCenter.storage.restart }, originalRows: 'exact', originalExports: 'exact', originalArtifactBytes: 'exact' };
}
assert.equal(after.modelCenterSha256, before.modelCenterSha256);
return { originalRows: 'exact', originalExports: 'exact', originalArtifactBytes: 'exact', originalModelCenter: 'exact' };
}