import { expect, mock, test } from 'bun:test'; import { Hono } from 'hono'; import { createHttpSecurity, getCredentialHttpPrincipal, getResearchHttpPrincipal, } from '@stock-bot/di'; import type { IServiceContainer } from '@stock-bot/services'; import { createResearchAgentSchema } from '@stock-bot/stock-config/research-agents'; import { createResearchRoutes } from '../../apps/stock/web-api/src/routes/research.routes'; import { createResearchAgentRoutes } from '../../apps/stock/web-api/src/routes/research-agents.routes'; import { researchAgentDatabaseError } from '../../apps/stock/web-api/src/services/research-agent-budget'; import { ResearchAgentsService } from '../../apps/stock/web-api/src/services/research-agents.service'; import { ResearchService } from '../../apps/stock/web-api/src/services/research.service'; const fixtureUuid = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`; const agent = `agent:${fixtureUuid(1)}` as const; const token = 'sb-research.fixture-token'; const adminToken = 'operator-test-secret-12345678901234567890'; const serviceToken = 'service-test-secret-123456789012345678901'; const limits = { maxActiveTrials: 2, maxTrialsPerExperiment: 4, maxBarEvaluationsPerExperiment: 1000, maxAttemptWallMs: 1000, maxAttempts: 2, }; function boundary(disabled = false, resolver = true) { const resolve = mock(async () => ({ principal: agent })); const security = createHttpSecurity({ adminToken, serviceToken, disabled, environment: 'test', browserSessions: true, ...(resolver ? { resolveResearchCredential: resolve } : {}), }); const app = new Hono(); security.mount(app); app.all('/api/v2/experiments', c => c.json({ principal: getResearchHttpPrincipal(c.req.raw), privileged: getCredentialHttpPrincipal(c.req.raw) ?? null, }) ); return { app, security, resolve }; } test('research HTTP identity is distinct; Origin and upgrades are fenced before asynchronous resolution', async () => { const f = boundary(); for (const headers of [{ Origin: 'https://evil.invalid' }, { Upgrade: 'websocket' }] as Record< string, string >[]) { const response = await f.app.request('/api/v2/experiments', { method: 'POST', headers: { Authorization: `Bearer ${token}`, ...headers }, }); expect(response.status).toBe(403); expect(response.headers.get('cache-control')).toBe('no-store'); } expect(f.resolve).toHaveBeenCalledTimes(0); const response = await f.app.request('/api/v2/experiments', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, }); expect(response.status).toBe(200); expect(await response.json()).toEqual({ principal: agent, privileged: null }); expect( f.security.authorize( new Request('http://localhost/api/v2/experiments', { headers: { Authorization: `Bearer ${token}` }, }) )?.status ).toBe(403); }); test('research credential never becomes a privileged session or bypasses disabled/unrelated authentication', async () => { for (const f of [boundary(true), boundary(false, false)]) { const response = await f.app.request('/api/v2/experiments', { headers: { Authorization: `Bearer ${token}` }, }); expect(response.status).toBe(403); expect(f.resolve).toHaveBeenCalledTimes(0); expect(f.security.researchEnabled).toBe(false); const login = await f.app.request('/api/auth/session', { method: 'POST', headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); expect(login.status).toBe(403); expect(login.headers.get('set-cookie')).toBeNull(); } const f = boundary(); const login = await f.app.request('/api/auth/session', { method: 'POST', headers: { Origin: 'http://localhost', 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), }); expect(login.status).toBe(403); expect(login.headers.get('set-cookie')).toBeNull(); }); test('operator-only provisioning fails closed without enabled research authentication before storage', async () => { const query = mock(async () => { throw new Error('denied operation touched storage'); }); const container = { postgres: { query }, logger: { error: mock(() => {}) }, } as unknown as IServiceContainer; for (const disabled of [false, true]) { const f = boundary(disabled); f.app.route('/', createResearchAgentRoutes(container, f.security.researchEnabled)); for (const bearer of [token, serviceToken, ...(disabled ? [adminToken] : [])]) { const response = await f.app.request('/api/v2/research-agents', { method: 'POST', headers: { Authorization: `Bearer ${bearer}`, 'Content-Type': 'application/json' }, body: '{}', }); expect(response.status).toBe(403); } } expect(query).toHaveBeenCalledTimes(0); }); test('resolver denies all dataset operations including canonical dataset exports', async () => { const query = mock(async () => ({ rows: [{ id: agent, enabled: true, policy: {} }] })); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const hash = 'a'.repeat(64); const check = (path: string, method = 'GET') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const [path, method] of [ [`/api/v2/datasets/canonical/${hash}/export`, 'GET'], [`/api/v2/datasets/canonical/${hash}/export`, 'HEAD'], ['/api/v2/datasets/canonical', 'GET'], [`/api/v2/datasets/canonical/${hash}`, 'GET'], [`/api/v2/datasets/canonical/${hash}/export/extra`, 'GET'], [`/api/v2/datasets/canonical/${hash.toUpperCase()}/export`, 'GET'], ['/api/v2/datasets/canonical/invalid/export', 'GET'], ['/api/v2/datasets/stored-eod/coverage', 'GET'], ['/api/v2/datasets/canonical/preview', 'POST'], ['/api/v2/datasets/canonical/retain', 'POST'], ['/api/v2/datasets/canonical/stored-source', 'POST'], ['/api/v2/datasets/stored-eod/inspect', 'POST'], [`/api/v2/datasets/canonical/${hash}/export`, 'POST'], ]) { const response = (await check(path!, method)) as Response; expect(response).toBeInstanceOf(Response); expect(response.status).toBe(403); expect(response.headers.get('cache-control')).toBe('no-store'); } }); test('resolver exact write capabilities refuse trading, operators, foreign evidence and ownership impersonation', async () => { const projectId = fixtureUuid(2), experimentId = fixtureUuid(3), familyId = fixtureUuid(4); const query = mock(async (sql: string) => ({ rows: sql.includes('token_hash') ? [{ id: agent, enabled: true, policy: { allowedProjectIds: [projectId] } }] : [{ submission_principal: 'operator', owner_principal: 'operator', project_id: projectId }], })); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const check = (path: string, method = 'POST') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const path of [ '/api/v2/research-agents', '/api/v2/backtests', '/api/v2/datasets/retain', '/api/v2/strategy-versions/' + familyId + '/review', '/api/operations/start', '/api/v2/runs/' + experimentId + '/reproduce', `/api/v2/experiments/${experimentId}/cancel`, `/api/v2/strategies/${familyId}/versions`, `/api/v2/research-projects/${fixtureUuid(5)}/hypotheses`, ]) { expect(await check(path)).toBeInstanceOf(Response); expect(((await check(path)) as Response).status).toBe(403); } expect(await check(`/api/v2/research-projects/${projectId}/hypotheses`)).toEqual({ principal: agent, }); expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent }); expect(((await check(`/api/v2/experiments/${experimentId}`, 'GET')) as Response).status).toBe( 403 ); expect(await check('/api/v2/research-agents', 'GET')).toBeInstanceOf(Response); }); test('resolver scopes GET and HEAD reads to granted projects, templates and owned resources', async () => { const grantedProject = fixtureUuid(10), ungrantedProject = fixtureUuid(11), grantedBacktest = fixtureUuid(12), ungrantedBacktest = fixtureUuid(13), grantedHypothesis = fixtureUuid(14), ungrantedHypothesis = fixtureUuid(15), missingHypothesis = fixtureUuid(16), grantedArtifact = fixtureUuid(17), ungrantedArtifact = fixtureUuid(18), ownedExperiment = fixtureUuid(19), ownedExperiment2 = fixtureUuid(20), foreignExperiment = fixtureUuid(21), ownedWalkForward = fixtureUuid(22), foreignWalkForward = fixtureUuid(23), ownedRun = fixtureUuid(24), foreignRun = fixtureUuid(25), permittedStrategy = fixtureUuid(26), unpermittedStrategy = fixtureUuid(27), permittedVersion = fixtureUuid(28), unpermittedVersion = fixtureUuid(29); const query = mock(async (sql: string, values?: unknown[]) => { if (sql.includes('FROM research_agents WHERE token_hash=')) { return { rows: [ { id: agent, enabled: true, policy: { allowedProjectIds: [grantedProject], grants: [{ backtestId: grantedBacktest }], }, }, ], }; } if (sql.startsWith('SELECT project_id FROM research_hypotheses')) { if (values?.[0] === grantedHypothesis) { return { rows: [{ project_id: grantedProject }] }; } if (values?.[0] === ungrantedHypothesis) { return { rows: [{ project_id: ungrantedProject }] }; } return { rows: [] }; } if (sql.startsWith('SELECT project_id FROM analysis_artifacts')) { if (values?.[0] === grantedArtifact) { return { rows: [{ project_id: grantedProject }] }; } if (values?.[0] === ungrantedArtifact) { return { rows: [{ project_id: ungrantedProject }] }; } return { rows: [] }; } if (sql.startsWith('SELECT id,submission_principal FROM research_experiments')) { const ids = (values?.[0] as string[]) ?? []; return { rows: ids .filter(id => [ownedExperiment, ownedExperiment2, foreignExperiment].includes(id)) .map(id => ({ id, submission_principal: id === foreignExperiment ? 'operator' : agent, })), }; } if (sql.startsWith('SELECT submission_principal FROM research_experiments')) { if (values?.[0] === ownedExperiment) { return { rows: [{ submission_principal: agent }] }; } if (values?.[0] === foreignExperiment) { return { rows: [{ submission_principal: 'operator' }] }; } return { rows: [] }; } if (sql.startsWith('SELECT submission_principal FROM research_walk_forwards')) { if (values?.[0] === ownedWalkForward) { return { rows: [{ submission_principal: agent }] }; } if (values?.[0] === foreignWalkForward) { return { rows: [{ submission_principal: 'operator' }] }; } return { rows: [] }; } if (sql.startsWith('SELECT research_agent_id FROM runs')) { if (values?.[0] === ownedRun) { return { rows: [{ research_agent_id: agent }] }; } if (values?.[0] === foreignRun) { return { rows: [{ research_agent_id: null }] }; } return { rows: [] }; } if (sql.includes('FROM strategies s')) { return { rows: values?.[0] === permittedStrategy ? [{ '?column?': 1 }] : [] }; } if (sql.includes('FROM strategy_versions sv')) { return { rows: values?.[0] === permittedVersion ? [{ '?column?': 1 }] : [] }; } throw new Error(`Unexpected SQL: ${sql}`); }); const service = new ResearchAgentsService({ postgres: { query }, } as unknown as IServiceContainer); const check = (path: string, method: 'GET' | 'HEAD' = 'GET') => service.authenticate( new Request(`http://localhost${path}`, { method, headers: { Authorization: `Bearer ${token}` }, }) ); for (const method of ['GET', 'HEAD'] as const) { for (const allowedPath of [ '/api/v2/research-projects', `/api/v2/research-projects/${grantedProject}`, `/api/v2/research-projects/${grantedProject}/strategies`, `/api/v2/research-projects/${grantedProject}/hypotheses`, `/api/v2/research-projects/${grantedProject}/analysis-artifacts`, `/api/v2/hypotheses/${grantedHypothesis}`, `/api/v2/hypotheses/${grantedHypothesis}/revisions`, `/api/v2/analysis-artifacts/${grantedArtifact}`, `/api/v2/analysis-artifacts/${grantedArtifact}/revisions`, '/api/v2/backtests', `/api/v2/backtests/${grantedBacktest}`, `/api/v2/backtests/${grantedBacktest}/canonical-capability`, `/api/v2/backtests/${grantedBacktest}/runs`, '/api/v2/experiments', `/api/v2/experiments?backtestId=${grantedBacktest}`, '/api/v2/experiments/validation', `/api/v2/experiments/validation?backtestId=${grantedBacktest}`, '/api/v2/experiments/walk-forward', `/api/v2/experiments/walk-forward?backtestId=${grantedBacktest}`, `/api/v2/experiments/${ownedExperiment}`, `/api/v2/experiments/${ownedExperiment}/trials/${ownedRun}/retries`, `/api/v2/experiments/validation/${ownedExperiment}`, `/api/v2/experiments/walk-forward/${ownedWalkForward}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=${ownedExperiment2}`, `/api/v2/experiments/compare?leftId=${ownedExperiment.toUpperCase()}&rightId=${ownedExperiment2.toUpperCase()}`, `/api/v2/research-projects/${grantedProject.toUpperCase()}`, `/api/v2/backtests/${grantedBacktest.toUpperCase()}`, `/api/v2/runs/${ownedRun}`, `/api/v2/runs/${ownedRun}/results`, '/api/v2/strategies', `/api/v2/strategies/${permittedStrategy}`, `/api/v2/strategies/${permittedStrategy}/versions`, `/api/v2/strategy-versions/${permittedVersion}`, `/api/v2/strategy-versions/${permittedVersion}/artifact`, ]) { expect(await check(allowedPath, method)).toEqual({ principal: agent }); } for (const deniedPath of [ `/api/v2/research-projects/${ungrantedProject}`, `/api/v2/research-projects/${ungrantedProject}/strategies`, `/api/v2/research-projects/${ungrantedProject}/hypotheses`, `/api/v2/research-projects/${ungrantedProject}/analysis-artifacts`, '/api/v2/research-projects/not-a-uuid', `/api/v2/hypotheses/${ungrantedHypothesis}`, `/api/v2/hypotheses/${ungrantedHypothesis}/revisions`, `/api/v2/hypotheses/${missingHypothesis}`, '/api/v2/hypotheses/not-a-uuid', `/api/v2/analysis-artifacts/${ungrantedArtifact}`, `/api/v2/analysis-artifacts/${ungrantedArtifact}/revisions`, '/api/v2/analysis-artifacts/not-a-uuid', `/api/v2/backtests/${ungrantedBacktest}`, `/api/v2/backtests/${ungrantedBacktest}/canonical-capability`, `/api/v2/backtests/${ungrantedBacktest}/runs`, '/api/v2/backtests/not-a-uuid', `/api/v2/experiments?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/validation?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/walk-forward?backtestId=${ungrantedBacktest}`, `/api/v2/experiments/${foreignExperiment}`, `/api/v2/experiments/${foreignExperiment}/trials/${foreignRun}/retries`, `/api/v2/experiments/validation/${foreignExperiment}`, `/api/v2/experiments/walk-forward/${foreignWalkForward}`, '/api/v2/experiments/not-a-uuid', '/api/v2/experiments/validation/not-a-uuid', '/api/v2/experiments/walk-forward/not-a-uuid', `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=${foreignExperiment}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}&leftId=${ownedExperiment2}&rightId=${ownedExperiment2}`, '/api/v2/experiments/compare?leftId=not-a-uuid&rightId=not-a-uuid', '/api/v2/experiments/compare', `/api/v2/experiments/compare?rightId=${ownedExperiment2}`, `/api/v2/experiments/compare?leftId=&rightId=${ownedExperiment2}`, `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=`, '/api/v2/experiments/compare?leftId=&rightId=', `/api/v2/experiments/compare?leftId=${ownedExperiment}&rightId=${ownedExperiment2}&rightId=${ownedExperiment2}`, `/api/v2/experiments/compare?leftId=${foreignExperiment}&rightId=${ownedExperiment2}`, `/api/v2/research-projects/${ungrantedProject.toUpperCase()}`, `/api/v2/backtests/${ungrantedBacktest.toUpperCase()}`, `/api/v2/runs/${foreignRun}`, `/api/v2/runs/${foreignRun}/results`, '/api/v2/runs/not-a-uuid', `/api/v2/strategies/${unpermittedStrategy}`, `/api/v2/strategies/${unpermittedStrategy}/versions`, '/api/v2/strategies/not-a-uuid', `/api/v2/strategy-versions/${unpermittedVersion}`, `/api/v2/strategy-versions/${unpermittedVersion}/artifact`, '/api/v2/strategy-versions/not-a-uuid', ]) { const response = (await check(deniedPath, method)) as Response; expect(response).toBeInstanceOf(Response); expect(response.status).toBe(403); } } }); test('quota diagnostics remain distinguishable from arbitrary database failures; policy is strict and bounded', () => { expect( researchAgentDatabaseError({ code: 'P0001', message: 'research_budget:capacity' })?.status ).toBe(429); expect( researchAgentDatabaseError({ code: 'P0001', message: 'research_access:denied' })?.status ).toBe(403); expect(researchAgentDatabaseError(new Error('database unavailable'))).toBeNull(); expect( researchAgentDatabaseError({ code: '23514', message: 'research_budget:spoof' }) ).toBeNull(); expect( createResearchAgentSchema.parse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits, }).limits ).toEqual(limits); for (const bad of [ { ...limits, maxAttempts: 4 }, { ...limits, maxActiveTrials: 0 }, { ...limits, maxAttemptWallMs: 2147483648 }, ]) { expect( createResearchAgentSchema.safeParse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits: bad, }).success ).toBe(false); } expect( createResearchAgentSchema.safeParse({ name: 'Agent', allowedProjectIds: [], allowedBacktestIds: [], limits, ownerPrincipal: 'operator', }).success ).toBe(false); }); test('artifact reads check run ownership before resolving evidence for research agents while preserving operator access', async () => { const projectId = fixtureUuid(30), artifactId = fixtureUuid(31), revisionId = fixtureUuid(32), foreignRunId = fixtureUuid(33), now = new Date().toISOString(); const resolveAll = mock(async () => [ { runId: foreignRunId, backtestId: fixtureUuid(34), metricsVersion: 'canonical-analytics/v1' as const, metricPath: 'analytics.metrics.sharpeRatio' as const, strategyVersionId: null, value: 2.45, unit: 'ratio' as const, availability: 'available' as const, unavailableReason: null, resultKind: 'canonical' as const, financialEngine: 'rust' as const, datasetHash: 'b'.repeat(64), limitations: [], }, ]); const artifactRow = { id: artifactId, project_id: projectId, hypothesis_revision_id: null, kind: 'finding', owner_principal: 'operator', updated_by: 'operator', archived_at: null, created_at: now, updated_at: now, }; const revisionRow = { id: revisionId, artifact_id: artifactId, ordinal: 1, title: 'Holdout finding', body: 'Operator holdout sharpe', submitted_by: 'operator', content_origin: 'human', source: null, created_at: now, }; const clientQuery = mock(async (sql: string, values?: unknown[]) => { if (sql.startsWith('SET TRANSACTION')) { return { rows: [] }; } if (sql.includes('FROM research_projects WHERE id=$1')) { return { rows: [{ id: projectId }] }; } if (sql.includes('FROM analysis_artifacts WHERE id=$1')) { return { rows: [artifactRow] }; } if (sql.includes('FROM analysis_artifacts a') && sql.includes('NOT EXISTS')) { expect(sql).toContain('ORDER BY rev.ordinal DESC'); expect(sql).toContain('LIMIT 1'); expect(values).toEqual([projectId, false, agent]); return { rows: [] }; } if (sql.includes('FROM analysis_artifacts WHERE project_id=$1')) { return { rows: [artifactRow] }; } if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1')) { return { rows: [revisionRow] }; } if (sql.includes('FROM analysis_evidence WHERE revision_id=$1')) { return { rows: [ { run_id: foreignRunId, metrics_version: 'canonical-analytics/v1', metric_path: 'analytics.metrics.sharpeRatio', strategy_version_id: null, }, ], }; } if (sql.includes('SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])')) { return { rows: [{ id: foreignRunId, research_agent_id: null }] }; } if (sql.includes('SELECT id,backtest_id,status FROM runs WHERE id=$1')) { return { rows: [ { id: values?.[0], backtest_id: '55555555-5555-4555-8555-555555555555', status: 'completed', }, ], }; } throw new Error(`Unexpected SQL: ${sql}`); }); let queriesAfterRelease = 0; const container = { postgres: { query: clientQuery, transaction: async (fn: (client: { query: typeof clientQuery }) => Promise) => { let released = false; let queue = Promise.resolve(); const txClient = { query: ((sql: string, values?: unknown[]) => { const run = queue.then(async () => { if (released) { queriesAfterRelease += 1; throw new Error(`Query executed on released transaction client: ${sql}`); } return clientQuery(sql, values); }); queue = run.then( () => undefined, () => undefined ); return run; }) as typeof clientQuery, }; try { return await fn(txClient); } finally { released = true; } }, }, logger: { error: mock(() => {}) }, } as unknown as IServiceContainer; const service = new ResearchService(container, { evidence: { resolveAll }, catalog: { getStrategy: mock(async () => ({}) as never) }, }); const f = boundary(); f.app.route('/', createResearchRoutes(container, service)); // Agent item and revision reads must fail closed with 403 before resolving evidence for (const method of ['GET', 'HEAD'] as const) { for (const path of [ `/api/v2/analysis-artifacts/${artifactId}`, `/api/v2/analysis-artifacts/${artifactId}/revisions`, ]) { const response = await f.app.request(path, { method, headers: { Authorization: `Bearer ${token}` }, }); expect(response.status).toBe(403); expect(response.headers.get('cache-control')).toBe('no-store'); } } // Agent project-list read omits artifacts referencing foreign runs without resolving evidence const agentList = await f.app.request(`/api/v2/research-projects/${projectId}/analysis-artifacts`, { headers: { Authorization: `Bearer ${token}` }, }); expect(agentList.status).toBe(200); expect(await agentList.json()).toEqual({ artifacts: [] }); expect(resolveAll).toHaveBeenCalledTimes(0); // Operator access remains intact and resolves evidence const opItem = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}`, { headers: { Authorization: `Bearer ${adminToken}` }, }); expect(opItem.status).toBe(200); const opBody = (await opItem.json()) as { artifact: { latestRevision: { evidence: { value: number }[] } }; }; expect(opBody.artifact.latestRevision.evidence[0]?.value).toBe(2.45); expect(resolveAll).toHaveBeenCalledTimes(1); expect(queriesAfterRelease).toBe(0); }); test('mixed artifact revision history allows latest-revision list and item reads while blocking history reads of foreign evidence', async () => { const projectId = '11111111-1111-4111-8111-111111111111'; const artifactId = '22222222-2222-4222-8222-222222222222'; const rev1Id = '33333333-3333-4333-8333-333333333333'; const rev2Id = '33333333-3333-4333-8333-333333333334'; const foreignRunId = '44444444-4444-4444-8444-444444444444'; const ownedRunId = '44444444-4444-4444-8444-444444444445'; const now = new Date('2026-01-01T00:00:00Z'); const resolveAll = mock( async ( refs: { runId: string }[], _source: unknown, db?: { query: (sql: string, values?: unknown[]) => Promise<{ rows: unknown[] }> } ) => { if (db) { await db.query('SELECT id,backtest_id,status FROM runs WHERE id=$1', [refs[0]?.runId]); } return refs.map(ref => ({ runId: ref.runId, datasetHash: 'a'.repeat(64), metricsVersion: 'canonical-analytics/v1', metricPath: 'analytics.metrics.sharpeRatio', value: ref.runId === foreignRunId ? 2.45 : 1.15, strategyVersionId: null, })); } ); const artifactRow = { id: artifactId, project_id: projectId, hypothesis_revision_id: null, kind: 'finding', owner_principal: 'operator', updated_by: 'operator', archived_at: null, created_at: now, updated_at: now, }; const rev1Row = { id: rev1Id, artifact_id: artifactId, ordinal: 1, title: 'Initial holdout finding', body: 'Operator holdout sharpe', submitted_by: 'operator', content_origin: 'human', source: null, created_at: now, }; const rev2Row = { id: rev2Id, artifact_id: artifactId, ordinal: 2, title: 'Sanitized finding', body: 'Agent-visible sharpe', submitted_by: 'operator', content_origin: 'human', source: null, created_at: now, }; const clientQuery = mock(async (sql: string, values?: unknown[]) => { if (sql.startsWith('SET TRANSACTION')) { return { rows: [] }; } if (sql.includes('FROM research_projects WHERE id=$1')) { return { rows: [{ id: projectId }] }; } if (sql.includes('FROM analysis_artifacts WHERE id=$1')) { return { rows: [artifactRow] }; } if (sql.includes('FROM analysis_artifacts a') && sql.includes('NOT EXISTS')) { expect(sql).toContain('ORDER BY rev.ordinal DESC'); expect(sql).toContain('LIMIT 1'); expect(values).toEqual([projectId, false, agent]); return { rows: [artifactRow] }; } if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal DESC LIMIT 1')) { return { rows: [rev2Row] }; } if (sql.includes('FROM analysis_artifact_revisions WHERE artifact_id=$1 ORDER BY ordinal')) { return { rows: [rev1Row, rev2Row] }; } if (sql.includes('FROM analysis_evidence WHERE revision_id=$1')) { const runId = values?.[0] === rev1Id ? foreignRunId : ownedRunId; return { rows: [ { run_id: runId, metrics_version: 'canonical-analytics/v1', metric_path: 'analytics.metrics.sharpeRatio', strategy_version_id: null, }, ], }; } if (sql.includes('SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])')) { const ids = (values?.[0] as string[]) ?? []; return { rows: ids.map(id => ({ id, research_agent_id: id === ownedRunId ? agent : null, })), }; } if (sql.includes('SELECT id,backtest_id,status FROM runs WHERE id=$1')) { return { rows: [ { id: values?.[0], backtest_id: '55555555-5555-4555-8555-555555555555', status: 'completed', }, ], }; } throw new Error(`Unexpected SQL: ${sql}`); }); let queriesAfterRelease = 0; const container = { postgres: { query: clientQuery, transaction: async (fn: (client: { query: typeof clientQuery }) => Promise) => { let released = false; let queue = Promise.resolve(); const txClient = { query: ((sql: string, values?: unknown[]) => { const run = queue.then(async () => { if (released) { queriesAfterRelease += 1; throw new Error(`Query executed on released transaction client: ${sql}`); } return clientQuery(sql, values); }); queue = run.then( () => undefined, () => undefined ); return run; }) as typeof clientQuery, }; try { return await fn(txClient); } finally { released = true; } }, }, logger: { error: mock(() => {}) }, } as unknown as IServiceContainer; const service = new ResearchService(container, { evidence: { resolveAll }, catalog: { getStrategy: mock(async () => ({}) as never) }, }); const f = boundary(); f.app.route('/', createResearchRoutes(container, service)); // Project list and item read succeed for the agent because latest revision (ordinal 2) uses ownedRunId const listResp = await f.app.request(`/api/v2/research-projects/${projectId}/analysis-artifacts`, { headers: { Authorization: `Bearer ${token}` }, }); expect(listResp.status).toBe(200); expect( ((await listResp.json()) as { artifacts: { id: string; latestRevision: { ordinal: number } }[] }) .artifacts ).toMatchObject([{ id: artifactId, latestRevision: { ordinal: 2 } }]); const itemResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}`, { headers: { Authorization: `Bearer ${token}` }, }); expect(itemResp.status).toBe(200); expect( ((await itemResp.json()) as { artifact: { latestRevision: { evidence: { runId: string }[] } } }) .artifact.latestRevision.evidence[0]?.runId ).toBe(ownedRunId); // History endpoint still fails closed with 403 because revision 1 references foreignRunId, // and must not leak dangling queries onto the released transaction client. const historyResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, { headers: { Authorization: `Bearer ${token}` }, }); expect(historyResp.status).toBe(403); expect(historyResp.headers.get('cache-control')).toBe('no-store'); await new Promise(resolve => setTimeout(resolve, 10)); expect(queriesAfterRelease).toBe(0); // Subsequent operator history read succeeds cleanly on a fresh transaction const opHistoryResp = await f.app.request(`/api/v2/analysis-artifacts/${artifactId}/revisions`, { headers: { Authorization: `Bearer ${adminToken}` }, }); expect(opHistoryResp.status).toBe(200); expect( ((await opHistoryResp.json()) as { revisions: { ordinal: number }[] }).revisions ).toHaveLength(2); });