Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Wallet8 * File : services/research-runner/test/helpers.ts9 * Module : services10 * Repository : https://git.spboucher.ai/sp-wallet11 * Project Website : https://wallet.spboucher.ai12 * Created : 2026-11-1113 * Last Modified : 2026-11-1114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Shared fixtures of the runner tests: synthetic candles, a job, a runner configuration whose "agent" is the deterministic44// fake (test/fixtures/fake-agent.mjs), launched exactly like the real CLI — same sandbox profile, same environment.45import { randomUUID } from 'node:crypto';46import { copyFileSync, existsSync, mkdtempSync, realpathSync } from 'node:fs';47import { tmpdir } from 'node:os';48import path from 'node:path';49import { fileURLToPath } from 'node:url';50import { ResearchBudgets, jobStrategyName, type RunnerJob } from '@spw/core/research-job';51import type { RunnerConfig } from '../src/config.ts';5253export const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');54export const LAB = path.join(REPO, 'research');55export const PYTHON = path.join(LAB, '.venv/bin/python');56export const labReady = (): boolean => existsSync(PYTHON);5758/** deterministic OHLCV random walk, CSV text with `ts` in seconds (bar-open, hourly, ending well in the past) */59export function candlesCsv(n: number, seed: number, o: { p0?: number; start?: number; stepSec?: number; drift?: number } = {}): string {60 let s = seed >>> 0;61 const rnd = (): number => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 2 ** 32; };62 const gauss = (): number => Math.sqrt(-2 * Math.log(rnd() + 1e-12)) * Math.cos(2 * Math.PI * rnd());63 const step = o.stepSec ?? 3600, start = o.start ?? 1_735_689_600; // 2025-01-01T00:00:00Z64 let close = o.p0 ?? 100;65 const rows = ['ts,open,high,low,close,volume'];66 for (let i = 0; i < n; i++) {67 const open = close; close = open * Math.exp((o.drift ?? 0.00005) + 0.008 * gauss());68 const hi = Math.max(open, close) * (1 + Math.abs(0.002 * gauss())), lo = Math.min(open, close) * (1 - Math.abs(0.002 * gauss()));69 rows.push(`${start + i * step},${open.toFixed(6)},${hi.toFixed(6)},${lo.toFixed(6)},${close.toFixed(6)},${(1 + 9 * rnd()).toFixed(4)}`);70 }71 return rows.join('\n') + '\n';72}7374export function makeJob(o: Partial<Omit<RunnerJob, 'budgets'>> & { bars?: number; budgets?: Partial<RunnerJob['budgets']> } = {}): RunnerJob {75 const id = o.id ?? randomUUID(), bars = o.bars ?? 1500, universe = o.universe ?? ['BTC', 'ETH'];76 return {77 id, token: 't'.repeat(48), kind: 'spot', mission: 'Développe une stratégie statistique BTC/ETH, teste-la sur données historiques et prépare une simulation avec un capital virtuel de 1 000 USDC',78 universe, interval: '1h', capitalUsd: 1000, tools: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'], strategyName: jobStrategyName(id), strategyVersion: '1', labCommit: null,79 holdout: { start: '2025-01-01T00:00:00+00:00', devEnd: '2025-03-04T12:00:00+00:00', end: '2025-03-20T00:00:00+00:00', devBars: bars, testBars: Math.floor(bars / 4) },80 data: { kind: 'spot', source: 'coinbase', interval: '1h', files: universe.map((symbol, i) => ({ symbol, csv: candlesCsv(bars, 7 + 31 * i, { p0: 100 * (i + 1) }) })) },81 ...o, budgets: ResearchBudgets.parse({ wallSeconds: 240, maxTrials: 60, maxDiskMb: 64, ...(o.budgets ?? {}) }),82 };83}8485let fakeDir: string | null = null;86/** the fake agent copied OUT of the repository: a job cannot read the application checkout, so its agent cannot live there */87export function fakeAgentPath(): string {88 if (!fakeDir) { fakeDir = realpathSync(mkdtempSync(path.join(tmpdir(), 'spw-fake-agent-'))); copyFileSync(path.join(REPO, 'services/research-runner/test/fixtures/fake-agent.mjs'), path.join(fakeDir, 'fake-agent.mjs')); }89 return path.join(fakeDir, 'fake-agent.mjs');90}9192export function testConfig(mode: string, extra: unknown = {}, o: Partial<RunnerConfig> = {}): RunnerConfig {93 const home = realpathSync(mkdtempSync(path.join(tmpdir(), 'spw-runner-'))), fake = fakeAgentPath();94 return {95 apiUrl: 'http://127.0.0.1:9', secret: 's'.repeat(48), runnerId: 'test', jobsRoot: path.join(home, 'jobs'), stateRoot: path.join(home, 'state'), labDir: LAB, labPin: 'worktree', python: PYTHON,96 readable: [path.dirname(fake)], agent: { kind: 'command', bin: '', model: null, argv: [process.execPath, fake, mode, JSON.stringify(extra)] },97 sandbox: process.platform === 'darwin' ? 'required' : 'off', model: { upstream: 'http://127.0.0.1:9', credential: null }, pollMs: 50, tickMs: 150, logFlushMs: 200, keepJobs: false, ...o,98 };99}100101export interface Captured { lines: { s: string; t: string }[]; running: number; cancel: boolean }102export const hooks = (c: Captured = { lines: [], running: 0, cancel: false }) => ({ captured: c, hooks: { log: (s: 'out' | 'err' | 'sys', t: string) => { c.lines.push({ s, t }); }, running: () => { c.running += 1; }, cancelRequested: () => c.cancel } });103