import assert from 'node:assert/strict'; import { mkdtemp, readFile } from 'node:fs/promises'; import { spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import test from 'node:test'; const DIST_ROOT = new URL('../dist/src/', import.meta.url); const CLI_PATH = new URL('../dist/src/cli.js', import.meta.url); async function importFresh(relativePath) { return import(new URL(`${relativePath}?t=${Date.now()}-${Math.random()}`, DIST_ROOT).href); } async function readFileUntilMatch(filePath, matcher, attempts = 10) { let last = ''; for (let index = 0; index < attempts; index += 1) { last = await readFile(filePath, 'utf8'); if (matcher.test(last)) { return last; } await new Promise((resolve) => setTimeout(resolve, 50)); } return last; } test('runtime, graph, and http server append durable log events', async () => { const home = await mkdtemp(join(tmpdir(), 'template-agent-logs-')); process.env.HOME = home; process.env.PORT = '0'; const { executeTemplateAgentAction, TEMPLATE_AGENT_ACTIONS } = await importFresh('./runtime.js'); const { runAgentGraph } = await importFresh('./agent/graph.js'); const { createTemplateAgentHttpServer } = await importFresh('./a2a-http.js'); await executeTemplateAgentAction( { action: TEMPLATE_AGENT_ACTIONS.HELP }, { surface: 'test', runId: 'runtime-run', requestId: 'runtime-request' }, ); await runAgentGraph( { action: TEMPLATE_AGENT_ACTIONS.HELP }, { runId: 'graph-run', requestId: 'graph-request', context: { source: 'test' } }, ); const handle = createTemplateAgentHttpServer(); await handle.start(); const address = handle.server.address(); const port = typeof address === 'object' && address ? address.port : 0; const response = await fetch(`http://127.0.0.1:${port}/health`); assert.equal(response.status, 200); await handle.stop(); const logPath = join(home, '.config', 'sin', 'sin-code-database', 'events.ndjson'); const content = await readFileUntilMatch(logPath, /http\.request\.succeeded/); assert.match(content, /runtime\.action\.started/); assert.match(content, /runtime\.action\.succeeded/); assert.match(content, /graph\.run\.started/); assert.match(content, /graph\.tools\.succeeded/); assert.match(content, /http\.request\.succeeded/); }); test('cli print-card logs command lifecycle without crashing', async () => { const home = await mkdtemp(join(tmpdir(), 'template-agent-cli-')); const result = spawnSync(process.execPath, [CLI_PATH.pathname, 'print-card'], { env: { ...process.env, HOME: home }, encoding: 'utf8', }); assert.equal(result.status, 0, result.stderr); const logPath = join(home, '.config', 'sin', 'sin-code-database', 'events.ndjson'); const content = await readFile(logPath, 'utf8'); assert.match(content, /cli\.command\.started/); assert.match(content, /cli\.command\.succeeded/); });