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:
Boki 2026-11-27 02:29:24 -05:00
commit 0c0ebb6f44
17 changed files with 1512 additions and 86 deletions

View file

@ -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);

View file

@ -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;

View file

@ -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(

View file

@ -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)
);

View file

@ -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));
}

View file

@ -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)

View file

@ -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);

View file

@ -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);
}

View file

@ -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();
}

View file

@ -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)

View file

@ -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(

View file

@ -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);

View file

@ -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);