- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
240 lines
7.9 KiB
TypeScript
240 lines
7.9 KiB
TypeScript
/** Shared trusted strategy decision staging. Callers own the durable/native commit boundary. */
|
|
import { types } from 'node:util';
|
|
import { z } from 'zod';
|
|
import { parseFinancialStrategyDecision, type FinancialStrategyDecision } from '@stock-bot/types';
|
|
import type {
|
|
DeepReadonly,
|
|
StrategyAdmissionFeedback,
|
|
StrategyDiagnostic,
|
|
StrategyProgram,
|
|
} from '@stock-bot/research/strategy-api';
|
|
import type {
|
|
DecisionContext,
|
|
nativeAdmissionOrders,
|
|
PublishedObservation,
|
|
} from '@stock-bot/stock-config/canonical-replay';
|
|
|
|
export function freeze<T>(value: T): DeepReadonly<T> {
|
|
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
for (const child of Object.values(value)) {
|
|
freeze(child);
|
|
}
|
|
Object.freeze(value);
|
|
}
|
|
return value as DeepReadonly<T>;
|
|
}
|
|
|
|
/** Check descriptors before reading values: JSON.stringify would silently lose
|
|
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
|
|
export function stateCopy(input: unknown): unknown {
|
|
return copyJsonState(input, new Set(), false);
|
|
}
|
|
|
|
/** Validate and detach callback state, freezing each completed container once.
|
|
* Never freeze author-owned input or trust its current frozen status. */
|
|
export function frozenStateCopy(input: unknown): DeepReadonly<unknown> {
|
|
return copyJsonState(input, new Set(), true);
|
|
}
|
|
|
|
function copyJsonState(input: unknown, ancestors: Set<object>, frozen: boolean): unknown {
|
|
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
|
|
return input;
|
|
}
|
|
if (typeof input === 'number' && Number.isFinite(input)) {
|
|
if (Object.is(input, -0)) {
|
|
throw new Error('Strategy state cannot contain negative zero');
|
|
}
|
|
return input;
|
|
}
|
|
const invalid = () => new Error('Strategy state requires finite plain JSON data properties');
|
|
if (!input || typeof input !== 'object' || ancestors.has(input)) {
|
|
throw invalid();
|
|
}
|
|
const array = Array.isArray(input);
|
|
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
|
|
throw invalid();
|
|
}
|
|
const keys = Reflect.ownKeys(input);
|
|
if (keys.some(key => typeof key !== 'string')) {
|
|
throw invalid();
|
|
}
|
|
ancestors.add(input);
|
|
try {
|
|
const data = (key: string): unknown => {
|
|
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
if (!descriptor?.enumerable || !('value' in descriptor)) {
|
|
throw invalid();
|
|
}
|
|
return copyJsonState(descriptor.value, ancestors, frozen);
|
|
};
|
|
let output: unknown[] | Record<string, unknown>;
|
|
if (array) {
|
|
if (keys.length !== input.length + 1) {
|
|
throw invalid();
|
|
}
|
|
const values = new Array<unknown>(input.length);
|
|
for (let index = 0; index < input.length; index++) {
|
|
values[index] = data(String(index));
|
|
}
|
|
output = values;
|
|
} else {
|
|
// fromEntries preserves an own '__proto__' key without changing prototype.
|
|
output = Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
|
|
}
|
|
return frozen ? Object.freeze(output) : output;
|
|
} finally {
|
|
ancestors.delete(input);
|
|
}
|
|
}
|
|
|
|
const id = z
|
|
.string()
|
|
.min(1)
|
|
.refine(value =>
|
|
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
|
|
);
|
|
export const metadataSchema = z
|
|
.object({
|
|
ownerId: id,
|
|
strategyId: id,
|
|
strategyVersion: id,
|
|
mode: z.enum(['target', 'orders']),
|
|
seed: z.number().int().min(0).max(0xffff_ffff),
|
|
})
|
|
.strict();
|
|
export type Metadata = z.infer<typeof metadataSchema>;
|
|
|
|
/** Fresh detached diagnostics; each host retains its own commit/freeze boundary. */
|
|
export function initialStrategyDiagnostic(
|
|
{ ownerId, strategyId, strategyVersion, seed }: Metadata,
|
|
initialState: unknown
|
|
): StrategyDiagnostic {
|
|
return {
|
|
ownerId,
|
|
strategyId,
|
|
strategyVersion,
|
|
nextDecisionSequence: 0,
|
|
state: stateCopy(initialState),
|
|
rng: { algorithm: 'lcg32-v1', seed, state: seed, draws: 0 },
|
|
observationCount: 0,
|
|
previousAdmission: null,
|
|
};
|
|
}
|
|
|
|
/** Project already-validated batch admission into this decision owner's feedback. */
|
|
export function ownerAdmissionFeedback(
|
|
decision: FinancialStrategyDecision['decision'],
|
|
revision: number,
|
|
orders: ReturnType<typeof nativeAdmissionOrders>
|
|
): StrategyAdmissionFeedback {
|
|
return {
|
|
decision,
|
|
revision,
|
|
orders: orders
|
|
.filter(order => order.order.decision.ownerId === decision.ownerId)
|
|
.map(order => ({
|
|
orderId: order.order.orderId,
|
|
instrumentId: order.order.instrumentId,
|
|
decision: order.order.decision,
|
|
status: order.status,
|
|
})),
|
|
};
|
|
}
|
|
|
|
export function increment(value: number, amount = 1): number {
|
|
const next = value + amount;
|
|
if (!Number.isSafeInteger(next) || next < 0) {
|
|
throw new Error('Strategy counter exhausted');
|
|
}
|
|
return next;
|
|
}
|
|
|
|
export function stageStrategyDecision(
|
|
sessionId: string,
|
|
program: Metadata & { decide: StrategyProgram['decide'] },
|
|
diagnostic: DeepReadonly<StrategyDiagnostic>,
|
|
observations: readonly PublishedObservation[],
|
|
context: DecisionContext
|
|
): { ownerId: string; decision: FinancialStrategyDecision; diagnostic: StrategyDiagnostic } {
|
|
let active = true,
|
|
rngState = diagnostic.rng.state,
|
|
draws = diagnostic.rng.draws;
|
|
const random = () => {
|
|
if (!active) {
|
|
throw new Error('Strategy random is only valid during its decision');
|
|
}
|
|
draws = increment(draws);
|
|
rngState = (Math.imul(rngState, 1664525) + 1013904223) >>> 0;
|
|
return rngState / 4294967296;
|
|
};
|
|
let output: ReturnType<StrategyProgram['decide']>;
|
|
try {
|
|
const decide = program.decide;
|
|
output = decide(
|
|
Object.freeze({
|
|
ownerId: program.ownerId,
|
|
strategyId: program.strategyId,
|
|
strategyVersion: program.strategyVersion,
|
|
decisionSequence: diagnostic.nextDecisionSequence,
|
|
now: context.barrier.at,
|
|
barrier: context.barrier,
|
|
portfolio: context.view,
|
|
positions: Object.freeze(
|
|
context.view.portfolio.positions.filter(position => position.ownerId === program.ownerId)
|
|
),
|
|
observations: Object.freeze([...observations]),
|
|
previousAdmission: diagnostic.previousAdmission,
|
|
state: diagnostic.state,
|
|
random,
|
|
})
|
|
);
|
|
} finally {
|
|
active = false;
|
|
}
|
|
if (types.isPromise(output)) {
|
|
// Reject async strategies synchronously, but observe their actual
|
|
// Promise rejection so failed attempts cannot leak unhandled errors.
|
|
// Do not await it or call arbitrary thenable methods.
|
|
Promise.prototype.then.call(output, undefined, () => {});
|
|
throw new Error('Strategy decide must synchronously return nextState and intent');
|
|
}
|
|
if (!output || typeof output !== 'object' || 'then' in output) {
|
|
throw new Error('Strategy decide must synchronously return nextState and intent');
|
|
}
|
|
const state = frozenStateCopy(output.nextState);
|
|
const decision = parseFinancialStrategyDecision({
|
|
version: 1,
|
|
sessionId: sessionId,
|
|
barrierId: context.barrier.barrier_id,
|
|
revision: context.barrier.revision,
|
|
decision: {
|
|
ownerId: program.ownerId,
|
|
decisionId: JSON.stringify([
|
|
'strategy',
|
|
program.ownerId,
|
|
program.strategyId,
|
|
program.strategyVersion,
|
|
diagnostic.nextDecisionSequence,
|
|
]),
|
|
sequence: diagnostic.nextDecisionSequence,
|
|
},
|
|
intent: output.intent,
|
|
});
|
|
if (decision.intent.mode !== program.mode) {
|
|
throw new Error('Strategy intent mode differs from its configured mode');
|
|
}
|
|
return {
|
|
ownerId: program.ownerId,
|
|
decision,
|
|
diagnostic: {
|
|
ownerId: program.ownerId,
|
|
strategyId: program.strategyId,
|
|
strategyVersion: program.strategyVersion,
|
|
state,
|
|
nextDecisionSequence: increment(diagnostic.nextDecisionSequence),
|
|
rng: { algorithm: 'lcg32-v1', seed: program.seed, state: rngState, draws },
|
|
observationCount: increment(diagnostic.observationCount, observations.length),
|
|
previousAdmission: null,
|
|
},
|
|
};
|
|
}
|