Files
hermeven/tests/integration/harness.ts
DanandClaude Fable 5.2 e1c02d5266 Address Cody review round 2: all ten findings (CODY-001 to CODY-010)
CODY-001 Bridge URL must be HTTPS (HTTP only to loopback), in the client and
         in manifest generation.
CODY-002 Even host calls stay serialised until the SDK call really settles;
         a microphone start that completes after its timeout is followed by
         a stop.
CODY-003 Request id is stored before the first submit and cleared only on a
         definitive answer; lost replies are treated as ambiguous and
         reconciled under the same id; HUD no longer claims "not sent".
CODY-004 Revoking a device cancels its in-flight turns, aborts
         transcription and asks Hermes to stop, from HTTP and CLI paths.
CODY-005 Speech model pinned to a commit with per-file SHA-256; fetched and
         verified ahead of time; verified on every load; never downloaded
         at run time; no unpinned configuration.
CODY-006 State directory 0700, database/WAL/SHM 0600 regardless of umask.
CODY-007 credential_expired handled like unauthorized on every path.
CODY-008 Approval wait start and paused agent deadline persisted and
         restored across restarts (schema v2).
CODY-009 Exactly one conversation create per epoch, sent in sequence, with
         stale results dropped before persistence.
CODY-010 Wrong pairing guesses no longer consume the outstanding code;
         failures are indistinguishable.

Checks: typecheck clean; npm test 182 passed; client build ok;
test:real-stt 11 passed (including with no network); test:real-hermes 9
passed; test:simulator 6 passed; git diff --check clean.

Not reviewed. No physical-device, droplet or production evidence.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 19:49:14 -08:00

184 lines
6.9 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { mkdtempSync, rmSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Writable } from 'node:stream';
import { pino } from 'pino';
import { SCHEMA_VERSION, type DeviceCredential, type TurnResult } from '@hermeven/contracts';
import { LOG_REDACT, createBridge, type Bridge } from '../../services/bridge/src/app.ts';
import { loadConfig, type BridgeConfig } from '../../services/bridge/src/config.ts';
import type { EngineTiming } from '../../services/bridge/src/turns.ts';
import { FakeHermes } from '../fakes/fakeHermes.ts';
import { FakeStt } from '../fakes/fakeStt.ts';
export const FAST: EngineTiming = {
transcribeDeadlineMs: 400,
agentDeadlineMs: 900,
approvalWaitMs: 500,
cancelGraceMs: 400,
pollIntervalMs: 20,
submitRetryMs: 30,
notSentAttempts: 3,
};
export interface Harness {
hermes: FakeHermes;
stt: FakeStt;
bridge: Bridge;
config: BridgeConfig;
url: string;
/** Every log line the bridge wrote, for redaction assertions. */
logs: string[];
dir: string;
pair(name?: string): Promise<DeviceCredential>;
api(method: string, path: string, opts?: { token?: string; json?: unknown; body?: Buffer; headers?: Record<string, string> }): Promise<{ status: number; body: any; headers: Headers }>;
conversation(token: string): Promise<string>;
textTurn(token: string, conversationId: string, text: string, requestId?: string): Promise<{ status: number; body: any }>;
audioTurn(token: string, conversationId: string, pcm: Buffer, requestId?: string, query?: Record<string, string>): Promise<{ status: number; body: any }>;
waitTerminal(token: string, requestId: string, timeoutMs?: number): Promise<TurnResult>;
waitState(token: string, requestId: string, state: string, timeoutMs?: number): Promise<TurnResult>;
/** Stop the bridge process-equivalent and start a new one on the same database. */
restartBridge(): Promise<void>;
close(): Promise<void>;
}
export async function createHarness(
opts: { env?: Record<string, string>; timing?: Partial<EngineTiming>; stt?: boolean } = {},
): Promise<Harness> {
const hermes = new FakeHermes();
const stt = new FakeStt();
await hermes.start();
await stt.start();
const dir = mkdtempSync(join(tmpdir(), 'hermeven-test-'));
const logs: string[] = [];
const sink = new Writable({
write(chunk, _enc, cb) {
logs.push(String(chunk));
cb();
},
});
const env: Record<string, string> = {
HERMEVEN_HOST: '127.0.0.1',
HERMEVEN_PORT: '0',
HERMEVEN_DB_PATH: join(dir, 'bridge.sqlite'),
HERMES_BASE_URL: hermes.url,
HERMES_API_KEY: hermes.apiKey,
HERMEVEN_ALLOWED_ORIGINS: 'https://app.example',
HERMES_REQUEST_TIMEOUT_MS: '300',
...(opts.stt === false
? { STT_PROVIDER: 'none' }
: { STT_PROVIDER: 'openai-compatible', STT_BASE_URL: stt.url, STT_API_KEY: stt.apiKey, STT_MODEL: 'fake-whisper' }),
...opts.env,
};
const config = loadConfig(env);
const timing = { ...FAST, ...opts.timing };
const h = {} as Harness;
const boot = async () => {
h.bridge = await createBridge(config, {
timing,
// Fast sweep so a database-only revocation (the operator CLI path) is seen quickly.
cancelSweepMs: 25,
logger: pino({ level: 'debug', redact: { paths: LOG_REDACT, censor: '[redacted]' } }, sink),
});
await h.bridge.app.listen({ host: '127.0.0.1', port: 0 });
h.url = `http://127.0.0.1:${(h.bridge.app.server.address() as AddressInfo).port}`;
};
Object.assign(h, { hermes, stt, config, logs, dir });
await boot();
h.api = async (method, path, o = {}) => {
const headers: Record<string, string> = { ...(o.headers ?? {}) };
if (o.token) headers.Authorization = `Bearer ${o.token}`;
let body: BodyInit | undefined;
if (o.json !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(o.json);
} else if (o.body) {
headers['Content-Type'] ??= 'application/octet-stream';
body = new Uint8Array(o.body);
}
const res = await fetch(`${h.url}${path}`, { method, headers, body });
const text = await res.text();
let parsed: unknown = text;
try {
parsed = JSON.parse(text);
} catch {
/* keep raw text */
}
return { status: res.status, body: parsed, headers: res.headers };
};
h.pair = async (name = 'test-g2') => {
const { code } = h.bridge.devices.createPairingCode();
const res = await h.api('POST', '/v1/pairing/claim', { json: { schema_version: SCHEMA_VERSION, code, device_name: name } });
if (res.status !== 201) throw new Error(`pairing failed: ${res.status} ${JSON.stringify(res.body)}`);
return res.body as DeviceCredential;
};
h.conversation = async (token) => {
const res = await h.api('POST', '/v1/conversations', { token, json: { schema_version: SCHEMA_VERSION } });
if (res.status !== 201) throw new Error(`conversation failed: ${res.status} ${JSON.stringify(res.body)}`);
return res.body.conversation_id as string;
};
h.textTurn = (token, conversationId, text, requestId = randomUUID()) =>
h.api('POST', '/v1/turns', {
token,
json: {
schema_version: SCHEMA_VERSION,
request_id: requestId,
conversation_id: conversationId,
locale: 'en-US',
input: { kind: 'text', text },
},
});
h.audioTurn = (token, conversationId, pcm, requestId = randomUUID(), query = {}) => {
const q = new URLSearchParams({
schema_version: String(SCHEMA_VERSION),
request_id: requestId,
conversation_id: conversationId,
locale: 'en-US',
input_kind: 'audio',
encoding: 'pcm_s16le',
sample_rate: '16000',
channels: '1',
...query,
});
return h.api('POST', `/v1/turns?${q}`, { token, body: pcm });
};
const waitFor = async (token: string, requestId: string, done: (t: TurnResult) => boolean, timeoutMs: number) => {
const deadline = Date.now() + timeoutMs;
let last: TurnResult | undefined;
while (Date.now() < deadline) {
const res = await h.api('GET', `/v1/turns/${requestId}`, { token });
if (res.status === 200) {
last = res.body as TurnResult;
if (done(last)) return last;
}
await new Promise((r) => setTimeout(r, 15));
}
throw new Error(`timed out waiting for turn ${requestId}; last=${JSON.stringify(last)}`);
};
h.waitTerminal = (token, requestId, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.terminal, timeoutMs);
h.waitState = (token, requestId, state, timeoutMs = 5000) => waitFor(token, requestId, (t) => t.state === state, timeoutMs);
h.restartBridge = async () => {
await h.bridge.close();
await boot();
};
h.close = async () => {
await h.bridge.close().catch(() => undefined);
await hermes.stop();
await stt.stop();
rmSync(dir, { recursive: true, force: true });
};
return h;
}