T-4: Close research-agent holdout leak
Merge a8c5fe2d using host Build #221 and PostgreSQL Test #222 as sign-off. Keep the dev branch bun.lock.
This commit is contained in:
commit
0c0ebb6f44
17 changed files with 1512 additions and 86 deletions
|
|
@ -1,12 +1,17 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getCredentialHttpPrincipal, getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import {
|
||||
getCredentialHttpPrincipal,
|
||||
getResearchHttpPrincipal,
|
||||
getVerifiedHttpPrincipal,
|
||||
} from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
isBacktestRequestError,
|
||||
rejectCatalogVersionReferences,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { isResearchAgent } from '@stock-bot/types';
|
||||
import {
|
||||
BacktestRetentionError,
|
||||
BacktestServiceV2,
|
||||
|
|
@ -21,6 +26,10 @@ const logger = getLogger('backtests-v2-routes');
|
|||
export function createBacktestV2Routes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const backtestService = new BacktestServiceV2(container);
|
||||
const agentScope = (request: Request) => {
|
||||
const principal = getResearchHttpPrincipal(request);
|
||||
return principal && isResearchAgent(principal) ? principal : undefined;
|
||||
};
|
||||
|
||||
// Backtest endpoints
|
||||
app.get('/api/v2/backtests', async c => {
|
||||
|
|
@ -31,10 +40,12 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
if (archiveQuery !== undefined && archiveQuery !== 'true' && archiveQuery !== 'false') {
|
||||
return c.json({ error: 'includeArchived must be true or false' }, 400);
|
||||
}
|
||||
const agentId = agentScope(c.req.raw);
|
||||
const backtests = await backtestService.listBacktests({
|
||||
limit,
|
||||
offset,
|
||||
includeArchived: archiveQuery === 'true',
|
||||
...(agentId ? { agentId } : {}),
|
||||
});
|
||||
return c.json(backtests);
|
||||
} catch (error) {
|
||||
|
|
@ -138,7 +149,10 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
// Run endpoints
|
||||
app.get('/api/v2/backtests/:backtestId/runs', async c => {
|
||||
try {
|
||||
const runs = await backtestService.listRuns(c.req.param('backtestId'));
|
||||
const runs = await backtestService.listRuns(
|
||||
c.req.param('backtestId'),
|
||||
agentScope(c.req.raw)
|
||||
);
|
||||
return c.json(runs);
|
||||
} catch (error) {
|
||||
logger.error('Failed to list runs', error);
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { z } from 'zod';
|
|||
import { getResearchHttpPrincipal } from '@stock-bot/di';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { isResearchAgent } from '@stock-bot/types';
|
||||
import {
|
||||
parseCostSensitivityInput,
|
||||
parseCostSensitivitySubmission,
|
||||
|
|
@ -68,6 +69,10 @@ export function createExperimentRoutes(
|
|||
logger.error('Experiment operation failed', error);
|
||||
return c.json({ error: 'Experiment operation unavailable' }, 500);
|
||||
});
|
||||
const agentScope = (request: Request) => {
|
||||
const principal = getResearchHttpPrincipal(request);
|
||||
return principal && isResearchAgent(principal) ? principal : undefined;
|
||||
};
|
||||
const body = async (request: Request): Promise<unknown> => {
|
||||
try {
|
||||
return await request.json();
|
||||
|
|
@ -116,7 +121,9 @@ export function createExperimentRoutes(
|
|||
return c.json({ walkForward }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/walk-forward', async c =>
|
||||
c.json({ walkForwards: await walkForwards.list(c.req.query('backtestId')) })
|
||||
c.json({
|
||||
walkForwards: await walkForwards.list(c.req.query('backtestId'), agentScope(c.req.raw)),
|
||||
})
|
||||
);
|
||||
app.get('/api/v2/experiments/walk-forward/:id', async c =>
|
||||
c.json({ walkForward: await walkForwards.get(experimentId(c.req.param('id'))) })
|
||||
|
|
@ -167,7 +174,9 @@ export function createExperimentRoutes(
|
|||
return c.json({ validation }, 202);
|
||||
});
|
||||
app.get('/api/v2/experiments/validation', async c =>
|
||||
c.json({ validations: await validations.list(c.req.query('backtestId')) })
|
||||
c.json({
|
||||
validations: await validations.list(c.req.query('backtestId'), agentScope(c.req.raw)),
|
||||
})
|
||||
);
|
||||
app.get('/api/v2/experiments/validation/:id', async c =>
|
||||
c.json({ validation: await validations.get(experimentId(c.req.param('id'))) })
|
||||
|
|
@ -235,7 +244,7 @@ export function createExperimentRoutes(
|
|||
if (filter !== undefined) {
|
||||
experimentId(filter);
|
||||
}
|
||||
return c.json({ experiments: await service.list(filter) });
|
||||
return c.json({ experiments: await service.list(filter, agentScope(c.req.raw)) });
|
||||
});
|
||||
app.get('/api/v2/experiments/compare', async c => {
|
||||
const params = new URL(c.req.url).searchParams;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { z } from 'zod';
|
|||
import { getResearchHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { archiveResearchSchema, parseResearchInput } from '@stock-bot/stock-config/research';
|
||||
import { isResearchAgent } from '@stock-bot/types';
|
||||
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
|
||||
import { ResearchError } from '../services/research-errors';
|
||||
import { createResearchServices } from '../services/research-services';
|
||||
|
|
@ -75,9 +76,17 @@ export function createResearchRoutes(
|
|||
return principal;
|
||||
};
|
||||
|
||||
const agentScope = (request: Request) => {
|
||||
const principal = getResearchHttpPrincipal(request);
|
||||
return principal && isResearchAgent(principal) ? principal : undefined;
|
||||
};
|
||||
|
||||
app.get('/api/v2/research-projects', async c =>
|
||||
c.json({
|
||||
projects: await service.listProjects(includeArchived(c.req.query('includeArchived'))),
|
||||
projects: await service.listProjects(
|
||||
includeArchived(c.req.query('includeArchived')),
|
||||
agentScope(c.req.raw)
|
||||
),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/research-projects', async c =>
|
||||
|
|
@ -157,7 +166,8 @@ export function createResearchRoutes(
|
|||
c.json({
|
||||
artifacts: await service.listArtifacts(
|
||||
c.req.param('id'),
|
||||
includeArchived(c.req.query('includeArchived'))
|
||||
includeArchived(c.req.query('includeArchived')),
|
||||
agentScope(c.req.raw)
|
||||
),
|
||||
})
|
||||
);
|
||||
|
|
@ -174,10 +184,12 @@ export function createResearchRoutes(
|
|||
)
|
||||
);
|
||||
app.get('/api/v2/analysis-artifacts/:id', async c =>
|
||||
c.json({ artifact: await service.getArtifact(c.req.param('id')) })
|
||||
c.json({ artifact: await service.getArtifact(c.req.param('id'), agentScope(c.req.raw)) })
|
||||
);
|
||||
app.get('/api/v2/analysis-artifacts/:id/revisions', async c =>
|
||||
c.json({ revisions: await service.listArtifactRevisions(c.req.param('id')) })
|
||||
c.json({
|
||||
revisions: await service.listArtifactRevisions(c.req.param('id'), agentScope(c.req.raw)),
|
||||
})
|
||||
);
|
||||
app.post('/api/v2/analysis-artifacts/:id/revisions', async c =>
|
||||
c.json(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { Hono, type MiddlewareHandler } from 'hono';
|
|||
import { z } from 'zod';
|
||||
import { getResearchHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { isResearchAgent } from '@stock-bot/types';
|
||||
import { researchAgentDatabaseError, ResearchAgentError } from '../services/research-agent-budget';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from '../services/strategy-catalog.service';
|
||||
|
||||
|
|
@ -61,7 +62,13 @@ export function createStrategyRoutes(
|
|||
}
|
||||
return value;
|
||||
};
|
||||
app.get('/api/v2/strategies', async c => c.json({ strategies: await service.listStrategies() }));
|
||||
const agentScope = (request: Request) => {
|
||||
const principal = getResearchHttpPrincipal(request);
|
||||
return principal && isResearchAgent(principal) ? principal : undefined;
|
||||
};
|
||||
app.get('/api/v2/strategies', async c =>
|
||||
c.json({ strategies: await service.listStrategies(agentScope(c.req.raw)) })
|
||||
);
|
||||
app.post('/api/v2/strategies', async c =>
|
||||
c.json({ strategy: await service.createStrategy(await c.req.json(), actor(c.req.raw)) }, 201)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -142,13 +142,21 @@ export class BacktestRuns {
|
|||
return mapRun(at(result.rows, 0));
|
||||
}
|
||||
|
||||
async listRuns(backtestId: string): Promise<Run[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM runs
|
||||
WHERE backtest_id = $1
|
||||
ORDER BY run_number DESC`,
|
||||
[backtestId]
|
||||
);
|
||||
async listRuns(backtestId: string, agentId?: string): Promise<Run[]> {
|
||||
const result =
|
||||
agentId !== undefined
|
||||
? await this.container.postgres.query(
|
||||
`SELECT * FROM runs
|
||||
WHERE backtest_id = $1 AND research_agent_id = $2
|
||||
ORDER BY run_number DESC`,
|
||||
[backtestId, agentId]
|
||||
)
|
||||
: await this.container.postgres.query(
|
||||
`SELECT * FROM runs
|
||||
WHERE backtest_id = $1
|
||||
ORDER BY run_number DESC`,
|
||||
[backtestId]
|
||||
);
|
||||
|
||||
return result.rows.map(row => mapRun(row));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -191,7 +191,23 @@ export class BacktestTemplates {
|
|||
limit: number;
|
||||
offset: number;
|
||||
includeArchived?: boolean;
|
||||
agentId?: string;
|
||||
}): Promise<Backtest[]> {
|
||||
if (params.agentId !== undefined) {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT b.* FROM backtests b
|
||||
JOIN research_agents a ON a.id = $4
|
||||
WHERE ($3::boolean OR b.archived_at IS NULL)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(a.policy->'grants') g
|
||||
WHERE g->>'backtestId' = b.id::text
|
||||
)
|
||||
ORDER BY b.created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset, params.includeArchived === true, params.agentId]
|
||||
);
|
||||
return result.rows.map(row => mapBacktest(row));
|
||||
}
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
WHERE ($3::boolean OR archived_at IS NULL)
|
||||
|
|
|
|||
|
|
@ -198,13 +198,23 @@ export class ChronologicalValidationService {
|
|||
await this.insertRuns(client, identity.id, train);
|
||||
return true;
|
||||
}
|
||||
async list(backtestId?: string): Promise<ChronologicalValidationSummary[]> {
|
||||
async list(backtestId?: string, agentId?: string): Promise<ChronologicalValidationSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const conditions = ["validation_phase='train'"];
|
||||
const values: unknown[] = [];
|
||||
if (backtestId !== undefined) {
|
||||
values.push(backtestId);
|
||||
conditions.push(`backtest_id=$${values.length}`);
|
||||
}
|
||||
if (agentId !== undefined) {
|
||||
values.push(agentId);
|
||||
conditions.push(`submission_principal=$${values.length}`);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT * FROM research_experiments WHERE validation_phase='train' ${backtestId === undefined ? '' : 'AND backtest_id=$1'} ORDER BY created_at DESC,id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
`SELECT * FROM research_experiments WHERE ${conditions.join(' AND ')} ORDER BY created_at DESC,id DESC`,
|
||||
values
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
retainedValidationPreview(row.validation_manifest);
|
||||
|
|
|
|||
|
|
@ -333,14 +333,24 @@ export class ExperimentsService {
|
|||
return this.readDetail(client, experimentId);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<ExperimentSummary[]> {
|
||||
async list(backtestId?: string, agentId?: string): Promise<ExperimentSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const conditions = ['e.validation_phase IS NULL'];
|
||||
const values: unknown[] = [];
|
||||
if (backtestId !== undefined) {
|
||||
values.push(backtestId);
|
||||
conditions.push(`e.backtest_id=$${values.length}`);
|
||||
}
|
||||
if (agentId !== undefined) {
|
||||
values.push(agentId);
|
||||
conditions.push(`e.submission_principal=$${values.length}`);
|
||||
}
|
||||
const rows = await this.database.query(
|
||||
`SELECT ${summaryColumns} FROM research_experiments e
|
||||
WHERE e.validation_phase IS NULL ${backtestId === undefined ? '' : 'AND e.backtest_id=$1'} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
WHERE ${conditions.join(' AND ')} ORDER BY e.created_at DESC,e.id DESC`,
|
||||
values
|
||||
);
|
||||
return rows.rows.map(summary);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,8 @@ function record(row: QueryResultRow): ResearchAgentRecord {
|
|||
updatedAt: new Date(row.updated_at).toISOString(),
|
||||
};
|
||||
}
|
||||
const uuid = '[0-9a-fA-F-]{36}';
|
||||
const uuid = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
|
||||
const strictUuid = new RegExp(`^${uuid}$`);
|
||||
function permitted(request: Request): boolean {
|
||||
const path = new URL(request.url).pathname,
|
||||
method = request.method;
|
||||
|
|
@ -47,9 +48,7 @@ function permitted(request: Request): boolean {
|
|||
return (
|
||||
/^\/api\/v2\/(research-projects|hypotheses|analysis-artifacts|strategies|strategy-versions|experiments|backtests|runs)(\/|$)/.test(
|
||||
path
|
||||
) ||
|
||||
/^\/api\/v2\/datasets\/canonical\/[a-f0-9]{64}\/export$/.test(path) ||
|
||||
path === '/api/v2/research-agent/budget'
|
||||
) || path === '/api/v2/research-agent/budget'
|
||||
);
|
||||
}
|
||||
if (method === 'PUT') {
|
||||
|
|
@ -311,12 +310,156 @@ export class ResearchAgentsService {
|
|||
if (!permitted(request)) {
|
||||
return deny();
|
||||
}
|
||||
if (!['GET', 'HEAD'].includes(request.method)) {
|
||||
const path = new URL(request.url).pathname;
|
||||
const project = new RegExp(`^/api/v2/research-projects/(${uuid})/`).exec(path);
|
||||
if (project && !row.policy.allowedProjectIds.includes(project[1]?.toLowerCase())) {
|
||||
const allowedProjectIds = Array.isArray(row.policy?.allowedProjectIds)
|
||||
? row.policy.allowedProjectIds
|
||||
.filter((id: unknown): id is string => typeof id === 'string')
|
||||
.map((id: string) => id.toLowerCase())
|
||||
: [];
|
||||
const grantedBacktestIds = Array.isArray(row.policy?.grants)
|
||||
? row.policy.grants
|
||||
.map((grant: unknown) =>
|
||||
grant && typeof grant === 'object' && 'backtestId' in grant
|
||||
? (grant as { backtestId?: unknown }).backtestId
|
||||
: undefined
|
||||
)
|
||||
.filter((id: unknown): id is string => typeof id === 'string')
|
||||
.map((id: string) => id.toLowerCase())
|
||||
: [];
|
||||
const url = new URL(request.url);
|
||||
const path = url.pathname;
|
||||
const project = /^\/api\/v2\/research-projects\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (project && !allowedProjectIds.includes(project[1]!.toLowerCase())) {
|
||||
return deny();
|
||||
}
|
||||
if (request.method === 'GET' || request.method === 'HEAD') {
|
||||
const narrative = /^\/api\/v2\/(hypotheses|analysis-artifacts)\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (narrative) {
|
||||
const narrativeId = narrative[2]!;
|
||||
if (!strictUuid.test(narrativeId)) {
|
||||
return deny();
|
||||
}
|
||||
const table = narrative[1] === 'hypotheses' ? 'research_hypotheses' : 'analysis_artifacts';
|
||||
const owned = (
|
||||
await this.database.query(`SELECT project_id FROM ${table} WHERE id=$1`, [narrativeId])
|
||||
).rows[0];
|
||||
if (!owned || !allowedProjectIds.includes(String(owned.project_id).toLowerCase())) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
const backtest = /^\/api\/v2\/backtests\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (backtest && !grantedBacktestIds.includes(backtest[1]!.toLowerCase())) {
|
||||
return deny();
|
||||
}
|
||||
if (path === '/api/v2/experiments/compare') {
|
||||
const leftIds = url.searchParams.getAll('leftId');
|
||||
const rightIds = url.searchParams.getAll('rightId');
|
||||
if (
|
||||
leftIds.length !== 1 ||
|
||||
rightIds.length !== 1 ||
|
||||
!strictUuid.test(leftIds[0]!) ||
|
||||
!strictUuid.test(rightIds[0]!)
|
||||
) {
|
||||
return deny();
|
||||
}
|
||||
const uniqueIds = [...new Set([leftIds[0]!.toLowerCase(), rightIds[0]!.toLowerCase()])];
|
||||
const rows = (
|
||||
await this.database.query(
|
||||
'SELECT id,submission_principal FROM research_experiments WHERE id=ANY($1::uuid[])',
|
||||
[uniqueIds]
|
||||
)
|
||||
).rows;
|
||||
if (
|
||||
rows.length !== uniqueIds.length ||
|
||||
rows.some(item => item.submission_principal !== row.id)
|
||||
) {
|
||||
return deny();
|
||||
}
|
||||
} else if (
|
||||
path === '/api/v2/experiments' ||
|
||||
path === '/api/v2/experiments/validation' ||
|
||||
path === '/api/v2/experiments/walk-forward'
|
||||
) {
|
||||
const backtestIds = url.searchParams.getAll('backtestId');
|
||||
if (backtestIds.some(id => !grantedBacktestIds.includes(id.toLowerCase()))) {
|
||||
return deny();
|
||||
}
|
||||
} else {
|
||||
const experiment =
|
||||
/^\/api\/v2\/experiments\/(walk-forward\/|validation\/)?([^/]+)(?:\/|$)/.exec(path);
|
||||
if (experiment) {
|
||||
const experimentId = experiment[2]!;
|
||||
if (!strictUuid.test(experimentId)) {
|
||||
return deny();
|
||||
}
|
||||
const table =
|
||||
experiment[1] === 'walk-forward/' ? 'research_walk_forwards' : 'research_experiments';
|
||||
const owned = (
|
||||
await this.database.query(`SELECT submission_principal FROM ${table} WHERE id=$1`, [
|
||||
experimentId,
|
||||
])
|
||||
).rows[0];
|
||||
if (owned?.submission_principal !== row.id) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
}
|
||||
const run = /^\/api\/v2\/runs\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (run) {
|
||||
const runId = run[1]!;
|
||||
if (!strictUuid.test(runId)) {
|
||||
return deny();
|
||||
}
|
||||
const owned = (
|
||||
await this.database.query('SELECT research_agent_id FROM runs WHERE id=$1', [runId])
|
||||
).rows[0];
|
||||
if (owned?.research_agent_id !== row.id) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
const strategy = /^\/api\/v2\/strategies\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (strategy) {
|
||||
const strategyId = strategy[1]!;
|
||||
if (!strictUuid.test(strategyId)) {
|
||||
return deny();
|
||||
}
|
||||
const permittedStrategy = (
|
||||
await this.database.query(
|
||||
`SELECT 1 FROM strategies s
|
||||
WHERE s.id=$1 AND (
|
||||
s.owner_principal=$2
|
||||
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
|
||||
OR EXISTS(SELECT 1 FROM strategy_versions sv JOIN backtests b ON b.strategy_version_id=sv.id WHERE sv.strategy_id=s.id AND b.id=ANY($4::uuid[]))
|
||||
)`,
|
||||
[strategyId, row.id, allowedProjectIds, grantedBacktestIds]
|
||||
)
|
||||
).rows[0];
|
||||
if (!permittedStrategy) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
const strategyVersion = /^\/api\/v2\/strategy-versions\/([^/]+)(?:\/|$)/.exec(path);
|
||||
if (strategyVersion) {
|
||||
const versionId = strategyVersion[1]!;
|
||||
if (!strictUuid.test(versionId)) {
|
||||
return deny();
|
||||
}
|
||||
const permittedVersion = (
|
||||
await this.database.query(
|
||||
`SELECT 1 FROM strategy_versions sv
|
||||
JOIN strategies s ON s.id=sv.strategy_id
|
||||
WHERE sv.id=$1 AND (
|
||||
s.owner_principal=$2
|
||||
OR EXISTS(SELECT 1 FROM research_project_strategies rps WHERE rps.strategy_id=s.id AND rps.project_id=ANY($3::uuid[]))
|
||||
OR EXISTS(SELECT 1 FROM strategy_versions sv2 JOIN backtests b ON b.strategy_version_id=sv2.id WHERE sv2.strategy_id=s.id AND b.id=ANY($4::uuid[]))
|
||||
)`,
|
||||
[versionId, row.id, allowedProjectIds, grantedBacktestIds]
|
||||
)
|
||||
).rows[0];
|
||||
if (!permittedVersion) {
|
||||
return deny();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const experiment = new RegExp(
|
||||
`^/api/v2/experiments/(walk-forward/|validation/)?(${uuid})/`
|
||||
).exec(path);
|
||||
|
|
@ -355,7 +498,7 @@ export class ResearchAgentsService {
|
|||
).rows[0];
|
||||
if (
|
||||
owned?.owner_principal !== row.id ||
|
||||
!row.policy.allowedProjectIds.includes(owned.project_id)
|
||||
!allowedProjectIds.includes(String(owned.project_id).toLowerCase())
|
||||
) {
|
||||
return deny();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -138,7 +138,11 @@ export class ResearchEvidenceResolver {
|
|||
database: BacktestResultQuery
|
||||
): Promise<ResearchEvidence[]> {
|
||||
if (!source) {
|
||||
return Promise.all(references.map(reference => this.resolve(reference, database)));
|
||||
const resolved: ResearchEvidence[] = [];
|
||||
for (const reference of references) {
|
||||
resolved.push(await this.resolve(reference, database));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
const results = await verifyResearchSource(source, references, database, (id, query) =>
|
||||
this.results.getRunResults(id, query)
|
||||
|
|
|
|||
|
|
@ -14,21 +14,22 @@ import {
|
|||
reviseResearchHypothesisSchema,
|
||||
updateResearchProjectSchema,
|
||||
} from '@stock-bot/stock-config/research';
|
||||
import type {
|
||||
ResearchActor,
|
||||
ResearchArtifact,
|
||||
ResearchArtifactRevision,
|
||||
ResearchAuthorship,
|
||||
ResearchContentOrigin,
|
||||
ResearchEvidence,
|
||||
ResearchEvidenceReference,
|
||||
ResearchFindingSource,
|
||||
ResearchHypothesis,
|
||||
ResearchHypothesisRevision,
|
||||
ResearchProject,
|
||||
StrategyRecord,
|
||||
import {
|
||||
isResearchAgent,
|
||||
type ResearchActor,
|
||||
type ResearchArtifact,
|
||||
type ResearchArtifactRevision,
|
||||
type ResearchAuthorship,
|
||||
type ResearchContentOrigin,
|
||||
type ResearchEvidence,
|
||||
type ResearchEvidenceReference,
|
||||
type ResearchFindingSource,
|
||||
type ResearchHypothesis,
|
||||
type ResearchHypothesisRevision,
|
||||
type ResearchProject,
|
||||
type StrategyRecord,
|
||||
} from '@stock-bot/types';
|
||||
import { lockResearchAgent } from './research-agent-budget';
|
||||
import { lockResearchAgent, ResearchAgentError } from './research-agent-budget';
|
||||
import { ResearchError } from './research-errors';
|
||||
import type { ResearchEvidenceResolver } from './research-evidence';
|
||||
import type { StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
|
@ -146,7 +147,19 @@ export class ResearchService {
|
|||
this.catalog = collaborators.catalog;
|
||||
}
|
||||
|
||||
async listProjects(includeArchived = false): Promise<ResearchProject[]> {
|
||||
async listProjects(includeArchived = false, agentId?: string): Promise<ResearchProject[]> {
|
||||
if (agentId !== undefined) {
|
||||
return (
|
||||
await this.database.query(
|
||||
`SELECT p.* FROM research_projects p
|
||||
JOIN research_agents a ON a.id = $2
|
||||
WHERE ($1::boolean OR p.archived_at IS NULL)
|
||||
AND (a.policy->'allowedProjectIds' ? p.id::text)
|
||||
ORDER BY p.created_at DESC, p.id`,
|
||||
[includeArchived, agentId]
|
||||
)
|
||||
).rows.map(project);
|
||||
}
|
||||
return (
|
||||
await this.database.query(
|
||||
'SELECT * FROM research_projects WHERE ($1::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
|
||||
|
|
@ -370,18 +383,47 @@ export class ResearchService {
|
|||
});
|
||||
}
|
||||
|
||||
async listArtifacts(projectId: string, includeArchived = false): Promise<ResearchArtifact[]> {
|
||||
async listArtifacts(
|
||||
projectId: string,
|
||||
includeArchived = false,
|
||||
agentId?: string
|
||||
): Promise<ResearchArtifact[]> {
|
||||
researchIdSchema.parse(projectId);
|
||||
return this.database.transaction(async client => {
|
||||
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
await this.projectRow(client, projectId);
|
||||
const rows = (
|
||||
await client.query(
|
||||
'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
|
||||
[projectId, includeArchived]
|
||||
)
|
||||
agentId !== undefined
|
||||
? await client.query(
|
||||
`SELECT a.* FROM analysis_artifacts a
|
||||
WHERE a.project_id=$1
|
||||
AND ($2::boolean OR a.archived_at IS NULL)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM analysis_evidence ev
|
||||
LEFT JOIN runs r ON r.id = ev.run_id
|
||||
WHERE ev.revision_id = (
|
||||
SELECT rev.id
|
||||
FROM analysis_artifact_revisions rev
|
||||
WHERE rev.artifact_id = a.id
|
||||
ORDER BY rev.ordinal DESC
|
||||
LIMIT 1
|
||||
)
|
||||
AND r.research_agent_id IS DISTINCT FROM $3
|
||||
)
|
||||
ORDER BY a.created_at DESC, a.id`,
|
||||
[projectId, includeArchived, agentId]
|
||||
)
|
||||
: await client.query(
|
||||
'SELECT * FROM analysis_artifacts WHERE project_id=$1 AND ($2::boolean OR archived_at IS NULL) ORDER BY created_at DESC,id',
|
||||
[projectId, includeArchived]
|
||||
)
|
||||
).rows;
|
||||
return Promise.all(rows.map(row => this.artifact(client, row)));
|
||||
const artifacts: ResearchArtifact[] = [];
|
||||
for (const row of rows) {
|
||||
artifacts.push(await this.artifact(client, row, undefined, agentId));
|
||||
}
|
||||
return artifacts;
|
||||
});
|
||||
}
|
||||
async createArtifact(
|
||||
|
|
@ -428,14 +470,14 @@ export class ResearchService {
|
|||
return this.artifact(client, row, revision);
|
||||
});
|
||||
}
|
||||
async getArtifact(id: string): Promise<ResearchArtifact> {
|
||||
async getArtifact(id: string, agentId?: string): Promise<ResearchArtifact> {
|
||||
researchIdSchema.parse(id);
|
||||
return this.database.transaction(async client => {
|
||||
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
return this.artifact(client, await this.artifactRow(client, id));
|
||||
return this.artifact(client, await this.artifactRow(client, id), undefined, agentId);
|
||||
});
|
||||
}
|
||||
async listArtifactRevisions(id: string): Promise<ResearchArtifactRevision[]> {
|
||||
async listArtifactRevisions(id: string, agentId?: string): Promise<ResearchArtifactRevision[]> {
|
||||
researchIdSchema.parse(id);
|
||||
return this.database.transaction(async client => {
|
||||
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
|
|
@ -446,7 +488,11 @@ export class ResearchService {
|
|||
[id]
|
||||
)
|
||||
).rows;
|
||||
return Promise.all(rows.map(row => this.artifactRevision(client, row)));
|
||||
const revisions: ResearchArtifactRevision[] = [];
|
||||
for (const row of rows) {
|
||||
revisions.push(await this.artifactRevision(client, row, agentId));
|
||||
}
|
||||
return revisions;
|
||||
});
|
||||
}
|
||||
async reviseArtifact(
|
||||
|
|
@ -609,7 +655,8 @@ export class ResearchService {
|
|||
private async artifact(
|
||||
database: Database,
|
||||
row: QueryResultRow,
|
||||
resolved?: ResearchArtifactRevision
|
||||
resolved?: ResearchArtifactRevision,
|
||||
agentId?: string
|
||||
): Promise<ResearchArtifact> {
|
||||
const latest =
|
||||
resolved ??
|
||||
|
|
@ -623,7 +670,8 @@ export class ResearchService {
|
|||
)
|
||||
).rows[0],
|
||||
'Artifact revision'
|
||||
)
|
||||
),
|
||||
agentId
|
||||
));
|
||||
return {
|
||||
id: row.id,
|
||||
|
|
@ -638,9 +686,35 @@ export class ResearchService {
|
|||
latestRevision: latest,
|
||||
};
|
||||
}
|
||||
private async assertAgentOwnsEvidenceRuns(
|
||||
database: Database,
|
||||
references: ResearchEvidenceReference[],
|
||||
agentId: string
|
||||
): Promise<void> {
|
||||
const uniqueRunIds = [...new Set(references.map(ref => ref.runId))];
|
||||
if (uniqueRunIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
const rows = (
|
||||
await database.query<{ id: string; research_agent_id: string | null }>(
|
||||
'SELECT id, research_agent_id FROM runs WHERE id = ANY($1::uuid[])',
|
||||
[uniqueRunIds]
|
||||
)
|
||||
).rows;
|
||||
if (
|
||||
rows.length !== uniqueRunIds.length ||
|
||||
rows.some(item => item.research_agent_id !== agentId)
|
||||
) {
|
||||
throw new ResearchAgentError(
|
||||
403,
|
||||
'Research credential does not permit accessing foreign run evidence'
|
||||
);
|
||||
}
|
||||
}
|
||||
private async artifactRevision(
|
||||
database: Database,
|
||||
row: QueryResultRow
|
||||
row: QueryResultRow,
|
||||
agentId?: string
|
||||
): Promise<ResearchArtifactRevision> {
|
||||
const references: ResearchEvidenceReference[] = (
|
||||
await database.query(
|
||||
|
|
@ -653,6 +727,9 @@ export class ResearchService {
|
|||
metricPath: item.metric_path,
|
||||
strategyVersionId: item.strategy_version_id,
|
||||
}));
|
||||
if (agentId !== undefined && references.length > 0) {
|
||||
await this.assertAgentOwnsEvidenceRuns(database, references, agentId);
|
||||
}
|
||||
const source = findingSource(row.source);
|
||||
let evidence;
|
||||
try {
|
||||
|
|
@ -687,6 +764,9 @@ export class ResearchService {
|
|||
...reference,
|
||||
strategyVersionId: reference.strategyVersionId ?? null,
|
||||
}));
|
||||
if (isResearchAgent(author.submittedBy) && references.length > 0) {
|
||||
await this.assertAgentOwnsEvidenceRuns(client, references, author.submittedBy);
|
||||
}
|
||||
const evidence = await this.evidence.resolveAll(references, data.source, client);
|
||||
const revisionId = randomUUID();
|
||||
const row = required(
|
||||
|
|
|
|||
|
|
@ -175,7 +175,31 @@ export class StrategyCatalogService {
|
|||
return strategy(row);
|
||||
});
|
||||
}
|
||||
async listStrategies(): Promise<StrategyRecord[]> {
|
||||
async listStrategies(agentId?: string): Promise<StrategyRecord[]> {
|
||||
if (agentId !== undefined) {
|
||||
return (
|
||||
await this.database.query(
|
||||
`SELECT s.* FROM strategies s
|
||||
JOIN research_agents a ON a.id = $1
|
||||
WHERE s.owner_principal = $1
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM research_project_strategies rps
|
||||
WHERE rps.strategy_id = s.id AND (a.policy->'allowedProjectIds' ? rps.project_id::text)
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM strategy_versions sv
|
||||
JOIN backtests b ON b.strategy_version_id = sv.id
|
||||
WHERE sv.strategy_id = s.id
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(a.policy->'grants') g
|
||||
WHERE g->>'backtestId' = b.id::text
|
||||
)
|
||||
)
|
||||
ORDER BY s.created_at DESC, s.id`,
|
||||
[agentId]
|
||||
)
|
||||
).rows.map(strategy);
|
||||
}
|
||||
return (
|
||||
await this.database.query('SELECT * FROM strategies ORDER BY created_at DESC,id')
|
||||
).rows.map(strategy);
|
||||
|
|
|
|||
|
|
@ -191,14 +191,25 @@ export class WalkForwardService {
|
|||
return this.readDetail(client, id);
|
||||
});
|
||||
}
|
||||
async list(backtestId?: string): Promise<WalkForwardSummary[]> {
|
||||
async list(backtestId?: string, agentId?: string): Promise<WalkForwardSummary[]> {
|
||||
if (backtestId !== undefined) {
|
||||
experimentId(backtestId);
|
||||
}
|
||||
const conditions: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
if (backtestId !== undefined) {
|
||||
values.push(backtestId);
|
||||
conditions.push(`w.backtest_id=$${values.length}`);
|
||||
}
|
||||
if (agentId !== undefined) {
|
||||
values.push(agentId);
|
||||
conditions.push(`w.submission_principal=$${values.length}`);
|
||||
}
|
||||
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
|
||||
const rows = await this.database.query(
|
||||
`SELECT w.*,(SELECT count(*)::int FROM research_experiments e WHERE e.walk_forward_id=w.id AND e.validation_report IS NOT NULL) AS reported
|
||||
FROM research_walk_forwards w ${backtestId === undefined ? '' : 'WHERE w.backtest_id=$1'} ORDER BY w.created_at DESC,w.id DESC`,
|
||||
backtestId === undefined ? [] : [backtestId]
|
||||
FROM research_walk_forwards w ${where} ORDER BY w.created_at DESC,w.id DESC`,
|
||||
values
|
||||
);
|
||||
return rows.rows.map(row => {
|
||||
checkedHeader(row);
|
||||
|
|
|
|||
|
|
@ -282,14 +282,16 @@ describe('validated canonical dataset export', () => {
|
|||
).rejects.toThrow('cancelled after query');
|
||||
});
|
||||
|
||||
test('read, admin, service, browser and research credentials export; anonymous and revoked credentials do not', async () => {
|
||||
test('read, admin, service and browser credentials export; research, anonymous and revoked credentials do not', async () => {
|
||||
const f = fixture();
|
||||
expect((await f.request(baseline.manifest.hash, {})).status).toBe(401);
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
for (const token of [tokens.read, tokens.admin, tokens.service, tokens.research]) {
|
||||
expect(
|
||||
(await f.request(baseline.manifest.hash, { Authorization: `Bearer ${token}` })).status
|
||||
).toBe(200);
|
||||
for (const token of [tokens.read, tokens.admin, tokens.service]) {
|
||||
const response = await f.request(baseline.manifest.hash, {
|
||||
Authorization: `Bearer ${token}`,
|
||||
});
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual(baseline);
|
||||
}
|
||||
for (const token of [tokens.read, tokens.admin]) {
|
||||
const login = await f.app.request('/api/auth/session', {
|
||||
|
|
@ -300,19 +302,31 @@ describe('validated canonical dataset export', () => {
|
|||
expect(login.status).toBe(200);
|
||||
const cookie = login.headers.get('Set-Cookie')?.split(';')[0];
|
||||
expect(cookie).toBeDefined();
|
||||
expect((await f.request(baseline.manifest.hash, { Cookie: cookie! })).status).toBe(200);
|
||||
const response = await f.request(baseline.manifest.hash, { Cookie: cookie! });
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual(baseline);
|
||||
}
|
||||
const before = f.payloadRead.mock.calls.length;
|
||||
const beforeResearch = f.payloadRead.mock.calls.length;
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
const forbidden = await f.app.request(path(baseline.manifest.hash), {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${tokens.research}` },
|
||||
});
|
||||
expect(forbidden.status).toBe(403);
|
||||
expect(forbidden.headers.get('Cache-Control')).toBe('no-store');
|
||||
expect(forbidden.headers.get('Content-Disposition')).toBeNull();
|
||||
}
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(beforeResearch);
|
||||
f.revokeResearch();
|
||||
const denied = await f.request(baseline.manifest.hash, {
|
||||
Authorization: `Bearer ${tokens.research}`,
|
||||
});
|
||||
expect(denied.status).toBe(401);
|
||||
expect(denied.headers.get('Content-Disposition')).toBeNull();
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(before);
|
||||
expect(f.payloadRead).toHaveBeenCalledTimes(beforeResearch);
|
||||
expect(
|
||||
f.query.mock.calls.filter(call => call[0].includes('FROM research_agents'))
|
||||
).toHaveLength(2);
|
||||
).toHaveLength(3);
|
||||
expect(f.sourceRead).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,9 +8,11 @@ import {
|
|||
} 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 agent = `agent:${randomUUID()}` as const;
|
||||
const token = 'sb-research.fixture-token';
|
||||
|
|
@ -118,7 +120,7 @@ test('operator-only provisioning fails closed without enabled research authentic
|
|||
}
|
||||
expect(query).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
test('resolver grants only exact immutable dataset exports among dataset operations', async () => {
|
||||
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 },
|
||||
|
|
@ -131,12 +133,9 @@ test('resolver grants only exact immutable dataset exports among dataset operati
|
|||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
);
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
expect(await check(`/api/v2/datasets/canonical/${hash}/export`, method)).toEqual({
|
||||
principal: agent,
|
||||
});
|
||||
}
|
||||
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'],
|
||||
|
|
@ -149,7 +148,10 @@ test('resolver grants only exact immutable dataset exports among dataset operati
|
|||
['/api/v2/datasets/stored-eod/inspect', 'POST'],
|
||||
[`/api/v2/datasets/canonical/${hash}/export`, 'POST'],
|
||||
]) {
|
||||
expect(((await check(path!, method)) as Response).status).toBe(403);
|
||||
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');
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -190,9 +192,208 @@ test('resolver exact write capabilities refuse trading, operators, foreign evide
|
|||
principal: agent,
|
||||
});
|
||||
expect(await check('/api/v2/experiments/preview')).toEqual({ principal: agent });
|
||||
expect(await check(`/api/v2/experiments/${experimentId}`, 'GET')).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 = randomUUID(),
|
||||
ungrantedProject = randomUUID(),
|
||||
grantedBacktest = randomUUID(),
|
||||
ungrantedBacktest = randomUUID(),
|
||||
grantedHypothesis = randomUUID(),
|
||||
ungrantedHypothesis = randomUUID(),
|
||||
missingHypothesis = randomUUID(),
|
||||
grantedArtifact = randomUUID(),
|
||||
ungrantedArtifact = randomUUID(),
|
||||
ownedExperiment = randomUUID(),
|
||||
ownedExperiment2 = randomUUID(),
|
||||
foreignExperiment = randomUUID(),
|
||||
ownedWalkForward = randomUUID(),
|
||||
foreignWalkForward = randomUUID(),
|
||||
ownedRun = randomUUID(),
|
||||
foreignRun = randomUUID(),
|
||||
permittedStrategy = randomUUID(),
|
||||
unpermittedStrategy = randomUUID(),
|
||||
permittedVersion = randomUUID(),
|
||||
unpermittedVersion = randomUUID();
|
||||
|
||||
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/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/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
|
||||
|
|
@ -236,3 +437,375 @@ test('quota diagnostics remain distinguishable from arbitrary database failures;
|
|||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('artifact reads check run ownership before resolving evidence for research agents while preserving operator access', async () => {
|
||||
const projectId = randomUUID(),
|
||||
artifactId = randomUUID(),
|
||||
revisionId = randomUUID(),
|
||||
foreignRunId = randomUUID(),
|
||||
now = new Date().toISOString();
|
||||
|
||||
const resolveAll = mock(async () => [
|
||||
{
|
||||
runId: foreignRunId,
|
||||
backtestId: randomUUID(),
|
||||
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 <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => {
|
||||
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 <T>(fn: (client: { query: typeof clientQuery }) => Promise<T>) => {
|
||||
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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ const options = {
|
|||
origins: ['http://ui.test'],
|
||||
};
|
||||
const agentId = 'agent:00000000-0000-4000-8000-000000000001';
|
||||
const grantedProjectId = '11111111-1111-4111-8111-111111111111';
|
||||
const ungrantedProjectId = '22222222-2222-4222-8222-222222222222';
|
||||
const token = 'sb-research.server-composition-fixture';
|
||||
const bearer = (value = token) => ({ Authorization: `Bearer ${value}` });
|
||||
|
||||
|
|
@ -28,10 +30,27 @@ function fixture(disabled = false, supplied = false) {
|
|||
return {
|
||||
rows:
|
||||
values?.[0] === createHash('sha256').update(token).digest('hex')
|
||||
? [{ id: agentId, enabled, policy: { allowedProjectIds: [] } }]
|
||||
? [{ id: agentId, enabled, policy: { allowedProjectIds: [grantedProjectId] } }]
|
||||
: [],
|
||||
};
|
||||
}
|
||||
if (sql === 'SELECT * FROM research_projects WHERE id=$1' && values?.[0] === grantedProjectId) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
id: grantedProjectId,
|
||||
title: 'Granted project',
|
||||
description: '',
|
||||
revision: 1,
|
||||
owner_principal: 'operator',
|
||||
updated_by: 'operator',
|
||||
archived_at: null,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (sql.startsWith('SELECT a.*,(SELECT count(*)::integer FROM runs')) {
|
||||
return {
|
||||
rows: [
|
||||
|
|
@ -205,3 +224,34 @@ test('web composition preserves token, environment, origin and browser-session v
|
|||
expect(preflight.headers.get('access-control-allow-origin')).toBe('http://ui.test');
|
||||
expect(f.query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('web security denies agent dataset export and ungranted project reads before touching storage', async () => {
|
||||
const f = fixture();
|
||||
const hash = 'a'.repeat(64);
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
const exported = await f.app.request(`/api/v2/datasets/canonical/${hash}/export`, {
|
||||
method,
|
||||
headers: bearer(),
|
||||
});
|
||||
expect(exported.status).toBe(403);
|
||||
expect(exported.headers.get('cache-control')).toBe('no-store');
|
||||
|
||||
const ungranted = await f.app.request(`/api/v2/research-projects/${ungrantedProjectId}`, {
|
||||
method,
|
||||
headers: bearer(),
|
||||
});
|
||||
expect(ungranted.status).toBe(403);
|
||||
expect(ungranted.headers.get('cache-control')).toBe('no-store');
|
||||
}
|
||||
expect(
|
||||
f.query.mock.calls.every(call =>
|
||||
String(call[0]).startsWith('SELECT id,enabled,policy FROM research_agents WHERE token_hash=')
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
const granted = await f.app.request(`/api/v2/research-projects/${grantedProjectId}`, {
|
||||
headers: bearer(),
|
||||
});
|
||||
expect(granted.status).toBe(200);
|
||||
expect(await granted.json()).toMatchObject({ project: { id: grantedProjectId } });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,9 +5,10 @@ import { Hono } from 'hono';
|
|||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type {
|
||||
CanonicalRunRequest,
|
||||
CanonicalRunResult,
|
||||
import {
|
||||
isCanonicalRunResult,
|
||||
type CanonicalRunRequest,
|
||||
type CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
|
|
@ -1048,4 +1049,444 @@ describe.skipIf(!url)('authoritative research principals and budgets', () => {
|
|||
await f.agents.update(p.agent.id, { expectedRevision: 2, allowedBacktestIds: [f.draft.id] });
|
||||
expect((await f.experiments.submit(changed, receipt(p.agent.id))).trials).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('HTTP read scoping blocks dataset export, ungranted projects/narratives/templates and foreign experiments/runs/strategies', async () => {
|
||||
const f = await fixture(4),
|
||||
p = await provision(f);
|
||||
const security = createWebApiSecurity(f.container, {
|
||||
adminToken: operatorToken,
|
||||
serviceToken: 'service-test-secret-123456789012345678901',
|
||||
environment: 'test',
|
||||
});
|
||||
const app = createRoutes(f.container, security);
|
||||
const req = (path: string, token: string, method: 'GET' | 'HEAD' = 'GET') =>
|
||||
app.request(path, { method, headers: { Authorization: `Bearer ${token}` } });
|
||||
|
||||
// 1. Dataset export: 403 for agent (GET/HEAD), 200 for operator
|
||||
const exportPath = `/api/v2/datasets/canonical/${f.dataset.manifest.hash}/export`;
|
||||
for (const method of ['GET', 'HEAD'] as const) {
|
||||
const agentExport = await req(exportPath, p.token, method);
|
||||
expect(agentExport.status).toBe(403);
|
||||
expect(agentExport.headers.get('cache-control')).toBe('no-store');
|
||||
expect(agentExport.headers.get('content-disposition')).toBeNull();
|
||||
}
|
||||
expect((await req(exportPath, operatorToken)).status).toBe(200);
|
||||
|
||||
// 2. Projects & narratives: granted vs ungranted
|
||||
const ungrantedProject = await f.research.createProject(
|
||||
{ title: 'Operator secret project' },
|
||||
'operator'
|
||||
);
|
||||
const grantedHypothesis = await f.research.createHypothesis(
|
||||
p.project.id,
|
||||
{ title: 'Granted H', proposition: 'Visible to agent' },
|
||||
'operator'
|
||||
);
|
||||
const ungrantedHypothesis = await f.research.createHypothesis(
|
||||
ungrantedProject.id,
|
||||
{ title: 'Secret H', proposition: 'Hidden from agent' },
|
||||
'operator'
|
||||
);
|
||||
const grantedArtifact = await f.research.createArtifact(
|
||||
p.project.id,
|
||||
{ kind: 'note', title: 'Granted A', body: 'Visible note', evidence: [] },
|
||||
'operator'
|
||||
);
|
||||
const ungrantedArtifact = await f.research.createArtifact(
|
||||
ungrantedProject.id,
|
||||
{ kind: 'note', title: 'Secret A', body: 'Hidden note', evidence: [] },
|
||||
'operator'
|
||||
);
|
||||
|
||||
const agentProjects = await req('/api/v2/research-projects', p.token);
|
||||
expect(agentProjects.status).toBe(200);
|
||||
expect(((await agentProjects.json()) as { projects: { id: string }[] }).projects.map(x => x.id)).toEqual([
|
||||
p.project.id,
|
||||
]);
|
||||
const opProjects = await req('/api/v2/research-projects', operatorToken);
|
||||
expect(opProjects.status).toBe(200);
|
||||
expect(((await opProjects.json()) as { projects: { id: string }[] }).projects).toHaveLength(2);
|
||||
|
||||
for (const allowedPath of [
|
||||
`/api/v2/research-projects/${p.project.id}`,
|
||||
`/api/v2/research-projects/${p.project.id}/strategies`,
|
||||
`/api/v2/research-projects/${p.project.id}/hypotheses`,
|
||||
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
|
||||
`/api/v2/hypotheses/${grantedHypothesis.id}`,
|
||||
`/api/v2/hypotheses/${grantedHypothesis.id}/revisions`,
|
||||
`/api/v2/analysis-artifacts/${grantedArtifact.id}`,
|
||||
`/api/v2/analysis-artifacts/${grantedArtifact.id}/revisions`,
|
||||
]) {
|
||||
expect((await req(allowedPath, p.token)).status).toBe(200);
|
||||
}
|
||||
for (const deniedPath of [
|
||||
`/api/v2/research-projects/${ungrantedProject.id}`,
|
||||
`/api/v2/research-projects/${ungrantedProject.id}/strategies`,
|
||||
`/api/v2/research-projects/${ungrantedProject.id}/hypotheses`,
|
||||
`/api/v2/research-projects/${ungrantedProject.id}/analysis-artifacts`,
|
||||
`/api/v2/hypotheses/${ungrantedHypothesis.id}`,
|
||||
`/api/v2/hypotheses/${ungrantedHypothesis.id}/revisions`,
|
||||
`/api/v2/analysis-artifacts/${ungrantedArtifact.id}`,
|
||||
`/api/v2/analysis-artifacts/${ungrantedArtifact.id}/revisions`,
|
||||
'/api/v2/research-projects/not-a-uuid',
|
||||
'/api/v2/hypotheses/not-a-uuid',
|
||||
'/api/v2/analysis-artifacts/not-a-uuid',
|
||||
]) {
|
||||
expect((await req(deniedPath, p.token)).status).toBe(403);
|
||||
}
|
||||
|
||||
// 3. Backtests, experiments & runs (including shared granted template)
|
||||
const ungrantedBacktest = await f.api.createBacktest(
|
||||
{ ...f.definition, name: 'Ungranted template' },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const agentBacktests = await req('/api/v2/backtests', p.token);
|
||||
expect(agentBacktests.status).toBe(200);
|
||||
expect(((await agentBacktests.json()) as { id: string }[]).map(b => b.id)).toEqual([
|
||||
f.draft.id,
|
||||
]);
|
||||
expect((await req(`/api/v2/backtests/${f.draft.id}`, p.token)).status).toBe(200);
|
||||
expect((await req(`/api/v2/backtests/${ungrantedBacktest.id}`, p.token)).status).toBe(403);
|
||||
expect((await req(`/api/v2/backtests/${ungrantedBacktest.id}/runs`, p.token)).status).toBe(403);
|
||||
|
||||
const agentExp = await f.experiments.submit(
|
||||
await preparation(f, 'Agent exp', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const opExp = await f.experiments.submit(
|
||||
await preparation(f, 'Operator exp', f.draft.id, { fastPeriod: [2] }),
|
||||
receipt('operator')
|
||||
);
|
||||
const agentRunId = required(agentExp.trials[0]!.runId);
|
||||
const opRunId = required(opExp.trials[0]!.runId);
|
||||
|
||||
const agentExpList = await req('/api/v2/experiments', p.token);
|
||||
expect(agentExpList.status).toBe(200);
|
||||
expect(
|
||||
((await agentExpList.json()) as { experiments: { id: string }[] }).experiments.map(e => e.id)
|
||||
).toEqual([agentExp.id]);
|
||||
expect((await req(`/api/v2/experiments?backtestId=${f.draft.id}`, p.token)).status).toBe(200);
|
||||
expect(
|
||||
(await req(`/api/v2/experiments?backtestId=${ungrantedBacktest.id}`, p.token)).status
|
||||
).toBe(403);
|
||||
expect((await req(`/api/v2/experiments/${agentExp.id}`, p.token)).status).toBe(200);
|
||||
expect((await req(`/api/v2/experiments/${opExp.id}`, p.token)).status).toBe(403);
|
||||
expect(
|
||||
(
|
||||
await req(
|
||||
`/api/v2/experiments/compare?leftId=${agentExp.id}&rightId=${opExp.id}`,
|
||||
p.token
|
||||
)
|
||||
).status
|
||||
).toBe(403);
|
||||
|
||||
const agentRuns = await req(`/api/v2/backtests/${f.draft.id}/runs`, p.token);
|
||||
expect(agentRuns.status).toBe(200);
|
||||
expect(((await agentRuns.json()) as { id: string }[]).map(r => r.id)).toEqual([agentRunId]);
|
||||
expect((await req(`/api/v2/runs/${agentRunId}`, p.token)).status).toBe(200);
|
||||
expect((await req(`/api/v2/runs/${opRunId}`, p.token)).status).toBe(403);
|
||||
expect((await req('/api/v2/runs/not-a-uuid', p.token)).status).toBe(403);
|
||||
|
||||
// 4. Strategies & strategy-versions: granted/owned vs unlinked foreign
|
||||
const foreignStrategy = await f.catalog.cloneVersion(
|
||||
f.version.id,
|
||||
{ name: 'Foreign operator strategy' },
|
||||
'operator',
|
||||
randomUUID()
|
||||
);
|
||||
const ownedStrategy = await f.catalog.cloneVersion(
|
||||
f.version.id,
|
||||
{ name: 'Agent owned strategy' },
|
||||
p.agent.id as `agent:${string}`,
|
||||
randomUUID()
|
||||
);
|
||||
const agentStrategies = await req('/api/v2/strategies', p.token);
|
||||
expect(agentStrategies.status).toBe(200);
|
||||
const visibleStrategyIds = (
|
||||
(await agentStrategies.json()) as { strategies: { id: string }[] }
|
||||
).strategies.map(s => s.id);
|
||||
expect(visibleStrategyIds).toContain(f.version.strategyId);
|
||||
expect(visibleStrategyIds).toContain(ownedStrategy.strategy.id);
|
||||
expect(visibleStrategyIds).not.toContain(foreignStrategy.strategy.id);
|
||||
|
||||
expect((await req(`/api/v2/strategies/${f.version.strategyId}`, p.token)).status).toBe(200);
|
||||
expect((await req(`/api/v2/strategies/${ownedStrategy.strategy.id}`, p.token)).status).toBe(200);
|
||||
expect((await req(`/api/v2/strategies/${foreignStrategy.strategy.id}`, p.token)).status).toBe(
|
||||
403
|
||||
);
|
||||
expect((await req(`/api/v2/strategy-versions/${ownedStrategy.version.id}`, p.token)).status).toBe(
|
||||
200
|
||||
);
|
||||
expect(
|
||||
(await req(`/api/v2/strategy-versions/${foreignStrategy.version.id}`, p.token)).status
|
||||
).toBe(403);
|
||||
expect((await req('/api/v2/strategies/not-a-uuid', p.token)).status).toBe(403);
|
||||
expect((await req('/api/v2/strategy-versions/not-a-uuid', p.token)).status).toBe(403);
|
||||
});
|
||||
|
||||
test('granted project artifacts cannot leak foreign holdout run evidence to research agents while preserving operator access', async () => {
|
||||
const data = walkForwardDataset(),
|
||||
f = await fixture(4, true, data.dataset),
|
||||
p = await provision(f, { maxActiveTrials: 4 });
|
||||
const security = createWebApiSecurity(f.container, {
|
||||
adminToken: operatorToken,
|
||||
serviceToken: 'service-test-secret-123456789012345678901',
|
||||
environment: 'test',
|
||||
});
|
||||
const app = createRoutes(f.container, security);
|
||||
const req = (
|
||||
path: string,
|
||||
token: string,
|
||||
method: 'GET' | 'HEAD' | 'POST' = 'GET',
|
||||
body?: unknown
|
||||
) =>
|
||||
app.request(path, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
|
||||
// Execute a real operator-owned chronological validation and its test holdout phase
|
||||
const { validations } = createResearchServices(f.container);
|
||||
const validationInput = {
|
||||
backtestId: f.draft.id,
|
||||
name: 'Operator chronological holdout',
|
||||
grid: { fastPeriod: [1, 2] },
|
||||
recipe: data.windows[0]!,
|
||||
};
|
||||
const prepared = await f.experiments.previewValidation(validationInput);
|
||||
const train = await validations.submit(
|
||||
{ ...validationInput, previewHash: prepared.previewHash },
|
||||
receipt('operator')
|
||||
);
|
||||
for (const trial of required(train.phases[0]?.experiment).trials) {
|
||||
await f.execute(required(trial.runId));
|
||||
}
|
||||
const selected = await validations.select(
|
||||
train.id,
|
||||
{ previewHash: prepared.previewHash },
|
||||
receipt('operator')
|
||||
);
|
||||
const holdoutPhase = required(
|
||||
selected.validation.phases.find(phase => phase.phase === 'test')
|
||||
);
|
||||
const opRunId = required(required(holdoutPhase.experiment).trials[0]?.runId);
|
||||
await f.execute(opRunId);
|
||||
const holdoutDatasetHash = required(
|
||||
prepared.partitions.find(partition => partition.phase === 'test')?.dataset.hash
|
||||
);
|
||||
|
||||
const agentExp = await f.experiments.submit(
|
||||
await preparation(f, 'Agent search', f.draft.id, { fastPeriod: [1] }),
|
||||
receipt(p.agent.id)
|
||||
);
|
||||
const agentRunId = required(agentExp.trials[0]!.runId);
|
||||
await f.execute(agentRunId);
|
||||
|
||||
// Operator attaches the holdout phase run's total return to a finding in the agent's granted project
|
||||
const opFinding = await f.research.createArtifact(
|
||||
p.project.id,
|
||||
{
|
||||
kind: 'finding',
|
||||
title: 'Operator holdout finding',
|
||||
body: 'Holdout total return from operator test phase',
|
||||
evidence: [
|
||||
{
|
||||
runId: opRunId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
},
|
||||
'operator'
|
||||
);
|
||||
const agentFinding = await f.research.createArtifact(
|
||||
p.project.id,
|
||||
{
|
||||
kind: 'finding',
|
||||
title: 'Agent finding',
|
||||
body: 'Total return from agent-owned run',
|
||||
evidence: [
|
||||
{
|
||||
runId: agentRunId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
},
|
||||
p.agent.id as `agent:${string}`
|
||||
);
|
||||
const plainNote = await f.research.createArtifact(
|
||||
p.project.id,
|
||||
{ kind: 'note', title: 'Shared note', body: 'No run evidence', evidence: [] },
|
||||
'operator'
|
||||
);
|
||||
|
||||
// Agent cannot read operator holdout run results directly
|
||||
expect((await req(`/api/v2/runs/${opRunId}/results`, p.token)).status).toBe(403);
|
||||
|
||||
// Agent cannot read the operator holdout finding or its revisions via GET or HEAD
|
||||
for (const method of ['GET', 'HEAD'] as const) {
|
||||
for (const path of [
|
||||
`/api/v2/analysis-artifacts/${opFinding.id}`,
|
||||
`/api/v2/analysis-artifacts/${opFinding.id}/revisions`,
|
||||
]) {
|
||||
const denied = await req(path, p.token, method);
|
||||
expect(denied.status).toBe(403);
|
||||
expect(denied.headers.get('cache-control')).toBe('no-store');
|
||||
if (method === 'GET') {
|
||||
expect(await denied.text()).not.toContain(holdoutDatasetHash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Agent project-list omits the operator holdout finding while keeping owned/non-evidence artifacts
|
||||
const agentList = await req(
|
||||
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
|
||||
p.token
|
||||
);
|
||||
expect(agentList.status).toBe(200);
|
||||
const agentArtifactIds = (
|
||||
(await agentList.json()) as { artifacts: { id: string }[] }
|
||||
).artifacts.map(a => a.id);
|
||||
expect(agentArtifactIds).toContain(agentFinding.id);
|
||||
expect(agentArtifactIds).toContain(plainNote.id);
|
||||
expect(agentArtifactIds).not.toContain(opFinding.id);
|
||||
|
||||
// Agent can still read its own finding and revisions
|
||||
const ownItem = await req(`/api/v2/analysis-artifacts/${agentFinding.id}`, p.token);
|
||||
expect(ownItem.status).toBe(200);
|
||||
expect(
|
||||
(
|
||||
(await ownItem.json()) as {
|
||||
artifact: { latestRevision: { evidence: { runId: string }[] } };
|
||||
}
|
||||
).artifact.latestRevision.evidence[0]?.runId
|
||||
).toBe(agentRunId);
|
||||
expect(
|
||||
(await req(`/api/v2/analysis-artifacts/${agentFinding.id}/revisions`, p.token)).status
|
||||
).toBe(200);
|
||||
|
||||
// Agent cannot attach an operator-owned holdout run as evidence when creating an artifact
|
||||
const forged = await req(
|
||||
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
|
||||
p.token,
|
||||
'POST',
|
||||
{
|
||||
kind: 'finding',
|
||||
title: 'Attempted exfiltration',
|
||||
body: 'Refers to operator holdout run',
|
||||
evidence: [
|
||||
{
|
||||
runId: opRunId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
expect(forged.status).toBe(403);
|
||||
|
||||
// Operator retains full read access to the holdout finding, its retained metric, and holdout dataset hash
|
||||
const holdoutResult = await f.api.getRunResults(opRunId);
|
||||
if (!holdoutResult || !isCanonicalRunResult(holdoutResult)) {
|
||||
throw new Error('Expected canonical holdout run result');
|
||||
}
|
||||
expect(Number.isFinite(holdoutResult.analytics.metrics.totalReturn)).toBe(true);
|
||||
|
||||
const opItem = await req(`/api/v2/analysis-artifacts/${opFinding.id}`, operatorToken);
|
||||
expect(opItem.status).toBe(200);
|
||||
const opArtifact = (
|
||||
(await opItem.json()) as {
|
||||
artifact: {
|
||||
latestRevision: {
|
||||
evidence: { runId: string; datasetHash: string; value: number }[];
|
||||
};
|
||||
};
|
||||
}
|
||||
).artifact;
|
||||
expect(opArtifact.latestRevision.evidence[0]?.runId).toBe(opRunId);
|
||||
expect(opArtifact.latestRevision.evidence[0]?.datasetHash).toBe(holdoutDatasetHash);
|
||||
expect(opArtifact.latestRevision.evidence[0]?.value).toBe(
|
||||
holdoutResult.analytics.metrics.totalReturn
|
||||
);
|
||||
|
||||
expect(
|
||||
(await req(`/api/v2/analysis-artifacts/${opFinding.id}/revisions`, operatorToken)).status
|
||||
).toBe(200);
|
||||
|
||||
const opList = await req(
|
||||
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
|
||||
operatorToken
|
||||
);
|
||||
expect(opList.status).toBe(200);
|
||||
expect(
|
||||
((await opList.json()) as { artifacts: { id: string }[] }).artifacts.map(a => a.id)
|
||||
).toEqual(expect.arrayContaining([opFinding.id, agentFinding.id, plainNote.id]));
|
||||
|
||||
// Mixed revision history: after operator revises the finding to reference only the agent's run,
|
||||
// the latest revision becomes visible in the project list and by ID, while /revisions still fails closed (403)
|
||||
await f.research.reviseArtifact(
|
||||
opFinding.id,
|
||||
{
|
||||
expectedRevision: opFinding.latestRevision.ordinal,
|
||||
title: 'Sanitized finding',
|
||||
body: 'Replaced holdout reference with agent-owned run',
|
||||
evidence: [
|
||||
{
|
||||
runId: agentRunId,
|
||||
metricsVersion: 'canonical-analytics/v1',
|
||||
metricPath: 'analytics.metrics.totalReturn',
|
||||
},
|
||||
],
|
||||
},
|
||||
'operator'
|
||||
);
|
||||
|
||||
const agentListAfterRev = await req(
|
||||
`/api/v2/research-projects/${p.project.id}/analysis-artifacts`,
|
||||
p.token
|
||||
);
|
||||
expect(agentListAfterRev.status).toBe(200);
|
||||
expect(
|
||||
((await agentListAfterRev.json()) as { artifacts: { id: string }[] }).artifacts.map(a => a.id)
|
||||
).toEqual(expect.arrayContaining([opFinding.id, agentFinding.id, plainNote.id]));
|
||||
|
||||
const agentItemAfterRev = await req(`/api/v2/analysis-artifacts/${opFinding.id}`, p.token);
|
||||
expect(agentItemAfterRev.status).toBe(200);
|
||||
const sanitizedText = await agentItemAfterRev.text();
|
||||
expect(sanitizedText).not.toContain(holdoutDatasetHash);
|
||||
expect(
|
||||
(
|
||||
JSON.parse(sanitizedText) as {
|
||||
artifact: { latestRevision: { ordinal: number; evidence: { runId: string }[] } };
|
||||
}
|
||||
).artifact.latestRevision
|
||||
).toMatchObject({ ordinal: 2, evidence: [{ runId: agentRunId }] });
|
||||
|
||||
const agentHistoryAfterRev = await req(
|
||||
`/api/v2/analysis-artifacts/${opFinding.id}/revisions`,
|
||||
p.token
|
||||
);
|
||||
expect(agentHistoryAfterRev.status).toBe(403);
|
||||
expect(agentHistoryAfterRev.headers.get('cache-control')).toBe('no-store');
|
||||
expect(await agentHistoryAfterRev.text()).not.toContain(holdoutDatasetHash);
|
||||
|
||||
const opHistoryAfterRev = await req(
|
||||
`/api/v2/analysis-artifacts/${opFinding.id}/revisions`,
|
||||
operatorToken
|
||||
);
|
||||
expect(opHistoryAfterRev.status).toBe(200);
|
||||
const opRevisions = (
|
||||
(await opHistoryAfterRev.json()) as {
|
||||
revisions: { ordinal: number; evidence: { runId: string; datasetHash: string }[] }[];
|
||||
}
|
||||
).revisions;
|
||||
expect(opRevisions).toHaveLength(2);
|
||||
expect(opRevisions[0]?.evidence[0]?.datasetHash).toBe(holdoutDatasetHash);
|
||||
expect(opRevisions[1]?.evidence[0]?.runId).toBe(agentRunId);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue