import { spawnSync } from 'node:child_process'; import { chmodSync, cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { BuiltinWhisperStt } from '../../services/bridge/src/stt/builtinWhisper.ts'; import { fetchModel, modelPath, verifyModel, type ModelManifest } from '../../services/bridge/src/stt/modelStore.mjs'; import { createHarness, type Harness } from '../integration/harness.ts'; /** * REAL SPEECH-TO-TEXT. The bridge's built-in Whisper model, really loaded and really run on * this machine's CPU, transcribing a real human speech recording that is uploaded through the * bridge's HTTP API exactly as the glasses app uploads a capture. * * Still fake: Hermes (tests/fakes/fakeHermes.ts) and the glasses. The recording is a clean * archive clip, not audio from a G2 microphone. */ const here = dirname(fileURLToPath(import.meta.url)); const speech = readFileSync(resolve(here, 'fixtures/jfk.wav')).subarray(44); // strip the WAV header: raw PCM const store = resolve(here, '.cache'); let h: Harness; let token: string; let conversation: string; let manifest: ModelManifest; const scratch: string[] = []; function chmodTree(path: string, dirMode: number, fileMode: number): void { chmodSync(path, dirMode); for (const entry of readdirSync(path, { withFileTypes: true })) { const child = join(path, entry.name); if (entry.isDirectory()) chmodTree(child, dirMode, fileMode); else chmodSync(child, fileMode); } } /** A private copy of the verified model store, so a test can damage or lock it. */ function copyStore(): string { const dir = mkdtempSync(join(tmpdir(), 'hermeven-model-copy-')); scratch.push(dir); cpSync(store, dir, { recursive: true }); return dir; } beforeAll(async () => { h = await createHarness({ stt: false, env: { STT_PROVIDER: 'builtin', STT_MODEL_DIR: store, HERMEVEN_CAPTURE_MAX_SECONDS: '30', }, timing: { transcribeDeadlineMs: 120_000, agentDeadlineMs: 30_000 }, }); expect(h.bridge.stt).toBeInstanceOf(BuiltinWhisperStt); manifest = h.config.stt.manifest!; // The deployment step: fetch the pinned revision from the real hub and verify every file // against the SHA-256 values committed in services/bridge/models/. Files already present and // correct are not downloaded again. const fetched = await fetchModel(store, manifest); console.info(`[real-stt] pinned ${manifest.model}@${manifest.revision}: ${fetched.verified} files verified, ${fetched.downloaded} downloaded`); const started = Date.now(); await (h.bridge.stt as BuiltinWhisperStt).warm(); console.info(`[real-stt] model verified and loaded in ${Date.now() - started} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`); token = (await h.pair()).token; conversation = await h.conversation(token); }); afterAll(async () => { await h?.close(); for (const dir of scratch) { if (existsSync(dir)) chmodTree(dir, 0o700, 0o600); rmSync(dir, { recursive: true, force: true }); } }); describe('built-in Whisper speech-to-text', () => { it('transcribes real speech uploaded as a capture and sends the words to the agent', async () => { // Watch the event loop while the model runs: the bridge must stay responsive. let worstLag = 0; let last = performance.now(); const probe = setInterval(() => { const now = performance.now(); worstLag = Math.max(worstLag, now - last - 20); last = now; }, 20); const res = await h.audioTurn(token, conversation, Buffer.from(speech)); expect(res.status).toBe(202); const health = await h.api('GET', '/healthz'); expect(health.status).toBe(200); const done = await h.waitTerminal(token, res.body.request_id, 120_000); clearInterval(probe); console.info( `[real-stt] ${(speech.length / 32000).toFixed(1)} s of speech transcribed in ${done.timings.transcribe_ms} ms; ` + `worst event-loop stall ${Math.round(worstLag)} ms; rss ${Math.round(process.memoryUsage().rss / 1e6)} MB`, ); console.info(`[real-stt] transcript: ${JSON.stringify(done.input_text)}`); expect(done.outcome).toBe('succeeded'); const heard = (done.input_text ?? '').toLowerCase().replace(/[^a-z ]/g, ''); expect(heard).toContain('ask not what your country can do for you'); expect(heard).toContain('ask what you can do for your country'); // The agent received exactly the transcript. expect(h.hermes.lastRun()!.input).toBe(done.input_text); expect(h.hermes.executions).toBe(1); }); it('a silent capture is reported as "no speech" and never reaches the agent', async () => { const before = h.hermes.executions; const res = await h.audioTurn(token, conversation, Buffer.alloc(3 * 32000)); const done = await h.waitTerminal(token, res.body.request_id, 60_000); expect(done.outcome).toBe('failed'); expect(done.error?.code).toBe('stt_empty'); expect(h.hermes.executions).toBe(before); }); it('a very quiet room-noise capture is also treated as no speech', async () => { const noise = Buffer.alloc(3 * 32000); for (let i = 0; i < noise.length / 2; i++) noise.writeInt16LE(Math.round((Math.random() - 0.5) * 40), i * 2); const res = await h.audioTurn(token, conversation, noise); const done = await h.waitTerminal(token, res.body.request_id, 60_000); expect(done.error?.code).toBe('stt_empty'); }); it('two recordings submitted together are both transcribed, one after the other', async () => { const other = await h.pair('second-device'); const otherConversation = await h.conversation(other.token); const [a, b] = await Promise.all([ h.audioTurn(token, conversation, Buffer.from(speech)), h.audioTurn(other.token, otherConversation, Buffer.from(speech)), ]); const [doneA, doneB] = await Promise.all([ h.waitTerminal(token, a.body.request_id, 120_000), h.waitTerminal(other.token, b.body.request_id, 120_000), ]); expect(doneA.input_text).toContain('fellow Americans'); expect(doneB.input_text).toContain('fellow Americans'); }); it('closing the adapter stops its worker thread, and a closed adapter refuses further work', async () => { const stt = new BuiltinWhisperStt({ manifest, modelDir: store }); const signal = new AbortController().signal; expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans'); await stt.close(); await stt.close(); await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); }); it('a second recording is transcribed with the model already warm', async () => { const res = await h.audioTurn(token, conversation, Buffer.from(speech.subarray(0, 6 * 32000))); const done = await h.waitTerminal(token, res.body.request_id, 120_000); console.info(`[real-stt] warm: 6.0 s of speech in ${done.timings.transcribe_ms} ms -> ${JSON.stringify(done.input_text)}`); expect(done.outcome).toBe('succeeded'); expect((done.input_text ?? '').toLowerCase()).toContain('fellow americans'); }); describe('deployment checks (CODY-005): pinned, verified, offline, read-only', () => { const signal = new AbortController().signal; it('the real artifacts on disk match the committed pins', async () => { expect(await verifyModel(store, manifest)).toEqual({ ok: true }); expect(manifest.revision).toMatch(/^[0-9a-f]{40}$/); }); it('one changed byte in the real model: load is refused as a mismatch, speech is unavailable, the bridge keeps running', async () => { const dir = copyStore(); const target = join(modelPath(dir, manifest), 'onnx/encoder_model_quantized.onnx'); const bytes = readFileSync(target); const middle = bytes.length >> 1; bytes[middle] = bytes[middle]! ^ 0x01; writeFileSync(target, bytes); expect(await verifyModel(dir, manifest)).toEqual({ ok: false, reason: 'mismatch', path: 'onnx/encoder_model_quantized.onnx' }); const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); try { await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); expect(stt.lastLoadFailure).toBe('mismatch'); } finally { await stt.close(); } expect((await h.api('GET', '/healthz')).status).toBe(200); }); it('a missing file is refused as missing, with no attempt to download it', async () => { const dir = copyStore(); rmSync(join(modelPath(dir, manifest), 'tokenizer.json')); const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); try { await expect(stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).rejects.toMatchObject({ kind: 'unavailable' }); expect(stt.lastLoadFailure).toBe('missing'); } finally { await stt.close(); } expect(existsSync(join(modelPath(dir, manifest), 'tokenizer.json'))).toBe(false); }); it('transcribes from a read-only model store and writes nothing into it', async () => { const dir = copyStore(); chmodTree(dir, 0o500, 0o400); const before = readdirSync(modelPath(dir, manifest), { recursive: true }).sort(); const stt = new BuiltinWhisperStt({ manifest, modelDir: dir }); try { expect(await stt.transcribe({ pcm: Buffer.from(speech), locale: 'en-US', signal })).toContain('fellow Americans'); } finally { await stt.close(); } expect(readdirSync(modelPath(dir, manifest), { recursive: true }).sort()).toEqual(before); }); it('verifies and transcribes with no network at all (network namespace with no interfaces)', () => { const probe = spawnSync( 'unshare', ['-rn', process.execPath, '--import', 'tsx', resolve(here, 'offlineProbe.mts'), store, resolve(here, 'fixtures/jfk.wav')], { encoding: 'utf8', cwd: resolve(here, '../../services/bridge'), timeout: 120_000 }, ); if (probe.error || (probe.status !== 0 && /unshare|Operation not permitted/i.test(probe.stderr))) { // Reported, not hidden: on this machine the offline proof could not be run. console.info(`[real-stt] OFFLINE CHECK NOT RUN: unprivileged network namespaces are unavailable (${(probe.stderr || String(probe.error)).trim().slice(0, 120)})`); return; } expect(probe.status, probe.stderr.slice(-500)).toBe(0); const out = JSON.parse(probe.stdout.trim().split('\n').at(-1)!); console.info(`[real-stt] offline run: networkReachable=${out.networkReachable} transcript=${JSON.stringify(out.text)}`); expect(out.networkReachable).toBe(false); expect(out.error).toBeNull(); expect(out.revision).toBe(manifest.revision); expect(out.text).toContain('ask not what your country can do for you'); }); }); });