From 3a63b2039e8f6b874d5cb1e1748c688a10f98c11 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 14:42:58 -0400 Subject: [PATCH] feat(strategies): publish type-only strategy authoring API (CL31) --- .../src/contracts/canonical-strategy.ts | 114 ++---------------- .../architecture-cleanup-execution.md | 2 + docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 12 +- docs/development/backlog/tasks/CL31.md | 4 + docs/guide/README.md | 2 +- docs/guide/code-reading.md | 2 +- docs/guide/strategy-development.md | 10 +- libs/research/examples/fresh-position.ts | 39 ++++++ libs/research/package.json | 3 +- libs/research/src/strategy-api.ts | 107 ++++++++++++++++ scripts/test/public-strategy-api.test.ts | 105 ++++++++++++++++ test/contracts/strategy-runtime.type-test.ts | 19 ++- 13 files changed, 300 insertions(+), 121 deletions(-) create mode 100644 libs/research/examples/fresh-position.ts create mode 100644 libs/research/src/strategy-api.ts create mode 100644 scripts/test/public-strategy-api.test.ts diff --git a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts b/apps/stock/orchestrator/src/contracts/canonical-strategy.ts index ebdcb4d9..ad1c3773 100644 --- a/apps/stock/orchestrator/src/contracts/canonical-strategy.ts +++ b/apps/stock/orchestrator/src/contracts/canonical-strategy.ts @@ -1,105 +1,9 @@ -/** - * Strategy-facing types for synchronous decisions on the canonical engine. - * StrategyController supplies these values; the native replay host owns time, - * order admission and accounting. Implementations return intent, not broker calls. - */ -import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types'; -import type { - DecisionContext, - NativeOrderStatus, - PublishedObservation, - ReplayIdentity, -} from './native-replay'; - -export type DeepReadonly = T extends string | number | boolean | null | undefined - ? T - : T extends object - ? { readonly [Key in keyof T]: DeepReadonly } - : T; - -/** - * Order outcomes copied when the previous decision batch was admitted. - * These are not later fill notifications: inspect current positions and the - * account view to learn what has executed since that decision. - */ -export interface StrategyAdmissionFeedback { - decision: DecisionIdentity; - revision: number; - orders: { - orderId: string; - instrumentId: string; - decision: DecisionIdentity; - status: NativeOrderStatus; - }[]; -} - -/** Read-only input to one owner at an engine-defined decision barrier. */ -export interface StrategyContext { - readonly ownerId: string; - readonly strategyId: string; - readonly strategyVersion: string; - /** Monotonic per-owner identity; advances after confirmed batch admission. */ - readonly decisionSequence: number; - /** Engine availability time in milliseconds, never the host's wall clock. */ - readonly now: number; - /** Due owners, account revision and freshness of the required input series. */ - readonly barrier: DeepReadonly; - /** The exact same read-only account view is shared by all due callbacks. */ - readonly portfolio: DeepReadonly; - /** Already filtered to this owner; portfolio contains the account-wide view. */ - readonly positions: DeepReadonly; - /** Published since this owner's last callback, buffered across slower cadences. */ - readonly observations: readonly DeepReadonly[]; - readonly previousAdmission: DeepReadonly | null; - /** Last confirmed JSON state, or initialState before the first decision. */ - readonly state: DeepReadonly; - /** Valid only during this synchronous callback; never use Math.random for decisions. */ - readonly random: () => number; -} - -/** - * One strategy instance bound to one configured financial owner and intent mode. - * Keep decision history in explicit state so a fresh attempt can recompute it. - * Native risk rules still apply to every returned intent. - */ -export interface StrategyProgram { - readonly ownerId: string; - readonly strategyId: string; - readonly strategyVersion: string; - readonly mode: 'target' | 'orders'; - readonly seed: number; - /** Finite plain JSON, checked and detached before the native attempt starts. */ - readonly initialState: State; - /** - * Propose the next JSON state and target holdings or explicit order actions. - * A target quantity is this owner's desired total, not an incremental buy. - * Return synchronously: state and seeded RNG advances become confirmed only - * after Rust acknowledges the whole decision batch, including any rejections. - */ - decide(context: StrategyContext): { - nextState: State; - intent: FinancialStrategyIntent; - }; -} - -/** Confirmed callback state for inspection; it does not contain the native ledger. */ -export interface StrategyDiagnostic { - ownerId: string; - strategyId: string; - strategyVersion: string; - nextDecisionSequence: number; - state: unknown; - rng: { algorithm: 'lcg32-v1'; seed: number; state: number; draws: number }; - observationCount: number; - previousAdmission: StrategyAdmissionFeedback | null; -} - -/** Last confirmed strategy transitions only. This cannot restore financial state. - * Retry always starts a fresh native session and recomputes from original inputs. */ -export interface StrategyDiagnosticSnapshot { - version: 1; - identity: ReplayIdentity; - committedBarriers: number; - lastBarrierId: string | null; - strategies: StrategyDiagnostic[]; -} +/** Compatibility type export. Authors use @stock-bot/research/strategy-api. */ +export type { + DeepReadonly, + StrategyAdmissionFeedback, + StrategyContext, + StrategyProgram, + StrategyDiagnostic, + StrategyDiagnosticSnapshot, +} from '@stock-bot/research/strategy-api'; diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index 181a6e45..22ac6b8c 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -27,3 +27,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL35:** Actual FastAPI app/lifespan and optional capability tests: 11 passed. Missing scientific/multipart dependencies do not prevent unrelated routes; unavailable initialization returns503, health observes state. Successful optimizer/model paths tested with stubs; load-to-list output shape corrected and covered. No heavy scientific packages installed. - **CL30:** Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved. + +- **CL31:** Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index bfac71d4..b5d1dc6f 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (10/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (11/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 9a4131fb..0fe75ad7 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3913,7 +3913,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL30"], - "completed_commit": null, + "completed_commit": "a411f9a6659014a3a2f1cedd7f3d4ed5f23dbe54", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -3926,7 +3926,7 @@ "epic": "E13", "priority": "P2", "severity": "Medium", - "status": "ready", + "status": "done", "dependencies": ["CL26"], "decision_dependencies": [], "task_file": "backlog/tasks/CL31.md", @@ -3936,7 +3936,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export." }, { "id": "CL32", @@ -10401,7 +10403,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 10, - "last_verification": "Independent workspace/finding UI suites: 203 passed, 1306 assertions; agent full relevant UI set344 passed, 2143 assertions. Full source typecheck and scoped lint/format passed. Extracted feature-owned read/draft/write hooks; neutral styles and unsaved warning imports replace cross-feature dependencies; custody and uncertainty behavior preserved." + "completed": 11, + "last_verification": "Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export." } } diff --git a/docs/development/backlog/tasks/CL31.md b/docs/development/backlog/tasks/CL31.md index dcc4b399..f2daaa15 100644 --- a/docs/development/backlog/tasks/CL31.md +++ b/docs/development/backlog/tasks/CL31.md @@ -18,3 +18,7 @@ Standalone example compilation; packaging; canonical strategy and state regressi No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Independent public-author/runtime suite:25 passed,363 assertions; standalone compilation uses no repository aliases or orchestrator/native implementation types. Source and packaged strategies produce identical native traces/checkpoints; contract compilation and scoped lint/format passed. Old contract path is a type-only compatibility export. diff --git a/docs/guide/README.md b/docs/guide/README.md index e2c90370..55d18ae2 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -75,7 +75,7 @@ This fixture does not need a provider connection or running databases. For initi ## Deeper references - [Calculation library](../../libs/calculations/README.md): reviewed indicators and analytics, plus clearly separated preserved legacy functions. -- [TypeScript strategy contract](../../apps/stock/orchestrator/src/contracts/canonical-strategy.ts): the actual callback context and output types. +- [TypeScript strategy contract](../../libs/research/src/strategy-api.ts): the actual callback context and output types. - [Research product reference](../development/architecture/research-product.md): API policies, provenance and paper setup. Its original design examples and later implementation notes need to be read in context. - [Architecture decisions](../development/architecture/decisions): why the boundaries were chosen. These record decisions and migration context, not a substitute for the current runtime map. - [Backlog](../development/backlog/README.md) and [roadmap](../development/ROADMAP.md): work history, completion evidence and conditional future tasks. diff --git a/docs/guide/code-reading.md b/docs/guide/code-reading.md index 8211e951..5ed023d6 100644 --- a/docs/guide/code-reading.md +++ b/docs/guide/code-reading.md @@ -15,7 +15,7 @@ This guide follows **functions and state**, rather than application boxes. The l ## 1. Begin with the decision contract -Open [canonical-strategy.ts](../../apps/stock/orchestrator/src/contracts/canonical-strategy.ts). `StrategyProgram` describes the object a strategy factory returns. Its `decide(context)` callback returns two things: +Open [strategy-api.ts](../../libs/research/src/strategy-api.ts). `StrategyProgram` describes the object a strategy factory returns. Its `decide(context)` callback returns two things: - `nextState`: what the strategy wants to remember for its next decision. - `intent`: what exposure or orders it wants the financial engine to consider. diff --git a/docs/guide/strategy-development.md b/docs/guide/strategy-development.md index 797885b7..5582cf71 100644 --- a/docs/guide/strategy-development.md +++ b/docs/guide/strategy-development.md @@ -8,7 +8,7 @@ A strategy is a TypeScript function that reads observations and account state, t | File | What to look for | | --- | --- | -| [canonical-strategy.ts](../../apps/stock/orchestrator/src/contracts/canonical-strategy.ts) | `StrategyProgram`, its `decide` callback, and the read-only `StrategyContext`. | +| [strategy-api.ts](../../libs/research/src/strategy-api.ts) | `StrategyProgram`, its `decide` callback, and the read-only `StrategyContext`. | | [canonical-sma.ts](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts) | A complete strategy: validated parameters, versioned state, history, crossover, target quantity. | | [canonical-mean-reversion.ts](../../apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts) | Trend, momentum, volatility regime, entry filters, and exits composed in TypeScript. | | [canonical-builtins.ts](../../apps/stock/orchestrator/src/strategies/canonical-builtins.ts) | The small built-in factory and checks binding each strategy owner to its instrument and observation series. | @@ -33,12 +33,14 @@ Keep history in explicit state, use engine time instead of `Date.now()`, and avo ## A minimal callback shape -This is a deliberately simple **in-repository source example**, using imports as if placed beside `canonical-sma.ts`. It requests one share when its series is fresh; it is not an investment strategy or a ready-to-upload candidate package. +Import author types from `@stock-bot/research/strategy-api`. This subpath contains only types; it exposes no native sessions, execution controllers, brokers, or storage services. Existing host imports of `contracts/canonical-strategy.ts` remain compatible. + +This simple callback requests one share when its series is fresh. It demonstrates the authoring contract; it is not a validated investment strategy or a ready-to-upload candidate package. ```ts import { parseFinancialDecimal } from '@stock-bot/types'; import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution'; -import type { StrategyProgram } from '../contracts/canonical-strategy'; +import type { StrategyProgram } from '@stock-bot/research/strategy-api'; export function createStrategy( selection: RetainedProgramSelection @@ -73,6 +75,8 @@ export function createStrategy( } ``` +For a self-contained source with no runtime imports, use [fresh-position.ts](../../libs/research/examples/fresh-position.ts). Its `shares` parameter must be a nonnegative safe integer; the example converts that checked integer to a fixed eight-decimal quantity. All imports erase during TypeScript transformation. [The public API tests](../../scripts/test/public-strategy-api.test.ts) compile the example outside the monorepo without path aliases, check the emitted module, and compare source and packaged decisions/state through the same Rust replay. Production candidate packaging still uses the existing isolated CLI; this test does not replace isolation or approval. + `quantity` is a desired **total holding for this owner**, not “buy this many more.” `parseFinancialDecimal('1')` creates the validated financial string `"1.00000000"`. Numeric arrays remain useful for features; financial postings use the decimal contract. An empty target list means no new target update. An explicit zero target requests an exit. Neither guarantees a fill: Rust reconciles the target with holdings and pending orders, applies risk checks, and uses eligible future execution events. Never report a position change merely because the callback requested one. diff --git a/libs/research/examples/fresh-position.ts b/libs/research/examples/fresh-position.ts new file mode 100644 index 00000000..bc867d4b --- /dev/null +++ b/libs/research/examples/fresh-position.ts @@ -0,0 +1,39 @@ +import type { FinancialDecimal, StrategyProgram } from '@stock-bot/research/strategy-api'; +import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution'; + +/** Authoring example only: request a fixed holding when the selected series is fresh. + * This demonstrates the callback contract, not a validated trading hypothesis. */ +export function createStrategy( + selection: RetainedProgramSelection +): StrategyProgram<{ decisions: number }> { + const shares = selection.parameters.shares; + if (typeof shares !== 'number' || !Number.isSafeInteger(shares) || shares < 0) { + throw new Error('shares must be a nonnegative safe integer'); + } + // The checked integer gives an exact canonical decimal with no runtime imports. + // Rust still validates intent quantities and enforces all financial constraints. + const quantity = `${shares}.00000000` as FinancialDecimal; + return { + ownerId: selection.ownerId, + strategyId: selection.strategyId, + strategyVersion: selection.strategyVersion, + seed: selection.seed, + mode: 'target', + initialState: { decisions: 0 }, + decide(context) { + const fresh = context.barrier.inputs.some( + input => + input.series_id === selection.seriesId && + typeof input.availability === 'object' && + 'Fresh' in input.availability + ); + return { + nextState: { decisions: context.state.decisions + 1 }, + intent: { + mode: 'target', + targets: fresh ? [{ instrumentId: selection.instrumentId, quantity }] : [], + }, + }; + }, + }; +} diff --git a/libs/research/package.json b/libs/research/package.json index da426bc4..5c40161b 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,7 +10,8 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", - "./results": "./src/results.ts" + "./results": "./src/results.ts", + "./strategy-api": "./src/strategy-api.ts" }, "scripts": { "build": "tsc" diff --git a/libs/research/src/strategy-api.ts b/libs/research/src/strategy-api.ts new file mode 100644 index 00000000..62eeb50d --- /dev/null +++ b/libs/research/src/strategy-api.ts @@ -0,0 +1,107 @@ +/** + * Strategy-facing types for synchronous decisions on the canonical engine. + * The execution host supplies these values and owns time, + * order admission and accounting. Implementations return intent, not broker calls. + */ +import type { + DecisionContext, + NativeOrderStatus, + PublishedObservation, + ReplayIdentity, +} from '@stock-bot/stock-config/canonical-replay'; +import type { DecisionIdentity, FinancialStrategyIntent } from '@stock-bot/types'; + +export type { DecisionIdentity, FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types'; + +export type DeepReadonly = T extends string | number | boolean | null | undefined + ? T + : T extends object + ? { readonly [Key in keyof T]: DeepReadonly } + : T; + +/** + * Order outcomes copied when the previous decision batch was admitted. + * These are not later fill notifications: inspect current positions and the + * account view to learn what has executed since that decision. + */ +export interface StrategyAdmissionFeedback { + decision: DecisionIdentity; + revision: number; + orders: { + orderId: string; + instrumentId: string; + decision: DecisionIdentity; + status: NativeOrderStatus; + }[]; +} + +/** Read-only input to one owner at an engine-defined decision barrier. */ +export interface StrategyContext { + readonly ownerId: string; + readonly strategyId: string; + readonly strategyVersion: string; + /** Monotonic per-owner identity; advances after confirmed batch admission. */ + readonly decisionSequence: number; + /** Engine availability time in milliseconds, never the host's wall clock. */ + readonly now: number; + /** Due owners, account revision and freshness of the required input series. */ + readonly barrier: DeepReadonly; + /** The exact same read-only account view is shared by all due callbacks. */ + readonly portfolio: DeepReadonly; + /** Already filtered to this owner; portfolio contains the account-wide view. */ + readonly positions: DeepReadonly; + /** Published since this owner's last callback, buffered across slower cadences. */ + readonly observations: readonly DeepReadonly[]; + readonly previousAdmission: DeepReadonly | null; + /** Last confirmed JSON state, or initialState before the first decision. */ + readonly state: DeepReadonly; + /** Valid only during this synchronous callback; never use Math.random for decisions. */ + readonly random: () => number; +} + +/** + * One strategy instance bound to one configured financial owner and intent mode. + * Keep decision history in explicit state so a fresh attempt can recompute it. + * Native risk rules still apply to every returned intent. + */ +export interface StrategyProgram { + readonly ownerId: string; + readonly strategyId: string; + readonly strategyVersion: string; + readonly mode: 'target' | 'orders'; + readonly seed: number; + /** Finite plain JSON, checked and detached before the native attempt starts. */ + readonly initialState: State; + /** + * Propose the next JSON state and target holdings or explicit order actions. + * A target quantity is this owner's desired total, not an incremental buy. + * Return synchronously: state and seeded RNG advances become confirmed only + * after Rust acknowledges the whole decision batch, including any rejections. + */ + decide(context: StrategyContext): { + nextState: State; + intent: FinancialStrategyIntent; + }; +} + +/** Confirmed callback state for inspection; it does not contain the native ledger. */ +export interface StrategyDiagnostic { + ownerId: string; + strategyId: string; + strategyVersion: string; + nextDecisionSequence: number; + state: unknown; + rng: { algorithm: 'lcg32-v1'; seed: number; state: number; draws: number }; + observationCount: number; + previousAdmission: StrategyAdmissionFeedback | null; +} + +/** Last confirmed strategy transitions only. This cannot restore financial state. + * Retry always starts a fresh native session and recomputes from original inputs. */ +export interface StrategyDiagnosticSnapshot { + version: 1; + identity: ReplayIdentity; + committedBarriers: number; + lastBarrierId: string | null; + strategies: StrategyDiagnostic[]; +} diff --git a/scripts/test/public-strategy-api.test.ts b/scripts/test/public-strategy-api.test.ts new file mode 100644 index 00000000..9002767e --- /dev/null +++ b/scripts/test/public-strategy-api.test.ts @@ -0,0 +1,105 @@ +import { mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { expect, test } from 'bun:test'; +import ts from 'typescript'; +import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution'; +import { parseFinancialDecimal } from '@stock-bot/types'; +import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay'; +import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime'; +import { createStrategy } from '../../libs/research/examples/fresh-position'; +import { nativeReplayFixture } from '../../test/fixtures/native-replay'; +import { runtimeImports } from '../runtime-imports'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const example = join(root, 'libs/research/examples/fresh-position.ts'); + +test('a standalone author compiles against package exports without workspace aliases or private host sources', async () => { + const directory = await mkdtemp(join(tmpdir(), 'stock-bot-public-strategy-types-')); + try { + await symlink(join(root, 'node_modules'), join(directory, 'node_modules'), 'dir'); + const entry = join(directory, 'strategy.ts'); + await writeFile(entry, await readFile(example)); + const program = ts.createProgram([entry], { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + strict: true, + noUncheckedIndexedAccess: true, + verbatimModuleSyntax: true, + skipLibCheck: true, + noEmit: true, + types: [], + }); + const diagnostics = ts.getPreEmitDiagnostics(program); + expect( + diagnostics.map(item => ts.flattenDiagnosticMessageText(item.messageText, '\n')) + ).toEqual([]); + const files = program.getSourceFiles().map(file => file.fileName); + expect(files.some(file => file.endsWith('/research/src/strategy-api.ts'))).toBe(true); + expect(files.some(file => file.includes('/apps/stock/orchestrator/'))).toBe(false); + expect(files.some(file => file.includes('/apps/stock/engine/'))).toBe(false); + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test('the public authoring entrypoint has no runtime imports or exported runtime capabilities', async () => { + const path = join(root, 'libs/research/src/strategy-api.ts'); + const source = await readFile(path, 'utf8'); + expect(runtimeImports(path, source)).toEqual([]); + const transformed = new Bun.Transpiler({ loader: 'ts', target: 'browser' }).transformSync(source); + expect(runtimeImports('strategy-api.js', transformed)).toEqual([]); + expect(Object.keys(await import('@stock-bot/research/strategy-api'))).toEqual([]); +}); + +test('public-only author source packages without runtime imports and preserves native decisions and checkpoints', async () => { + const directory = await mkdtemp(join(tmpdir(), 'stock-bot-public-strategy-package-')); + try { + const source = await readFile(example, 'utf8'); + const transformed = new Bun.Transpiler({ loader: 'ts', target: 'browser' }).transformSync( + source + ); + expect(runtimeImports('strategy.mjs', transformed)).toEqual([]); + for (const forbidden of ['@stock-bot/', 'engine.node', 'process.env', 'StrategyController']) { + expect(transformed).not.toContain(forbidden); + } + const artifact = join(directory, 'strategy.mjs'); + await writeFile(artifact, transformed); + const { createStrategy: packaged } = (await import(pathToFileURL(artifact).href)) as { + createStrategy: typeof createStrategy; + }; + const selection: RetainedProgramSelection = { + ownerId: 'A', + strategyId: 'fresh-position-example', + strategyVersion: '1', + seed: 7, + instrumentId: 'X0.US', + seriesId: 'X0.US:1m', + ownerBudget: parseFinancialDecimal('100'), + parameters: { shares: 1 }, + }; + const f = nativeReplayFixture(6, 1, ['A']); + // Derive the exact fixture series ID; authored code still sees only published inputs. + selection.seriesId = f.config.cadence[0]!.series_ids[0]!; + const load = prepareReplayLoad(f.dataset, f.config); + const expected = runStrategyReplay(load, [createStrategy(selection)], { + resultFormat: 'trace', + }); + const actual = runStrategyReplay(load, [packaged(selection)], { resultFormat: 'trace' }); + expect(actual.result).toEqual(expected.result); + expect(actual.diagnostics).toEqual(expected.diagnostics); + expect(actual.diagnostics.strategies[0]?.nextDecisionSequence).toBeGreaterThan(0); + expect(actual.diagnostics.strategies[0]?.state).toEqual({ + decisions: actual.diagnostics.strategies[0]?.nextDecisionSequence, + }); + for (const shares of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, '1']) { + expect(() => packaged({ ...selection, parameters: { shares } })).toThrow( + 'shares must be a nonnegative safe integer' + ); + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); diff --git a/test/contracts/strategy-runtime.type-test.ts b/test/contracts/strategy-runtime.type-test.ts index bdecf45a..36cf6b76 100644 --- a/test/contracts/strategy-runtime.type-test.ts +++ b/test/contracts/strategy-runtime.type-test.ts @@ -1,8 +1,8 @@ +import type { StrategyContext, StrategyProgram } from '@stock-bot/research/strategy-api'; +import type * as AuthorAPI from '@stock-bot/research/strategy-api'; import type { FinancialDecimal, FinancialStrategyIntent } from '@stock-bot/types'; -import type { - StrategyContext, - StrategyProgram, -} from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; +// Existing hosts keep the same contract while external authors use the public subpath. +import type { StrategyProgram as LegacyProgram } from '../../apps/stock/orchestrator/src/contracts/canonical-strategy'; type State = { count: number; indicator: { values: number[] } }; @@ -61,3 +61,14 @@ const asynchronous: StrategyProgram = { }), }; void asynchronous; + +const legacyProgram: LegacyProgram = valid; +const publicProgram: StrategyProgram = legacyProgram; +void publicProgram; + +// @ts-expect-error The author package exposes no strategy execution controller. +type _Controller = AuthorAPI.StrategyController; +// @ts-expect-error Native replay handles remain host-private. +type _NativeSession = AuthorAPI.NativeReplaySession; +// @ts-expect-error Strategy decisions cannot construct a paper runtime. +type _PaperRuntime = AuthorAPI.CanonicalPaperRuntime;