- 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
207 lines
7.3 KiB
TypeScript
207 lines
7.3 KiB
TypeScript
/** Durable custody contracts. Financial values and transitions belong to Rust. */
|
|
import { z } from 'zod';
|
|
import type { PostgresClient } from '@stock-bot/services';
|
|
import { paperDeploymentBindingSchema } from '@stock-bot/stock-config/paper-deployments';
|
|
import {
|
|
canonicalExecutionCheckpointSchema,
|
|
financialTransactionResultSchema,
|
|
matchingCommandSchema,
|
|
} from '@stock-bot/stock-config/canonical-execution';
|
|
import {
|
|
nativeFinancialViewSchema,
|
|
nativeManagedOrderSchema,
|
|
stepSchema,
|
|
} from '@stock-bot/stock-config/canonical-replay';
|
|
import { paperConfigurationSchema, paperConnectionSchema } from '@stock-bot/stock-config/paper-runtime';
|
|
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
|
|
|
|
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
const time = matchingCommandSchema.shape.key.shape.at;
|
|
const json = z.unknown().transform(value => stateCopy(value));
|
|
const observation = stepSchema.shape.observations.element;
|
|
const barrier = stepSchema.shape.step.options[1].shape.barrier;
|
|
const definition = metadataSchema.extend({ initialState: json }).strict();
|
|
const quoteClock = z
|
|
.object({ instrumentId: z.string(), observedAt: time, sourceSequence: counter })
|
|
.strict();
|
|
/** Host controls are deliberately outside the native financial checkpoint. */
|
|
export const canonicalPaperHostSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
configuration: paperConfigurationSchema,
|
|
deployment: paperDeploymentBindingSchema.optional(),
|
|
generation: z.string().min(1),
|
|
active: z.boolean(),
|
|
operatorHalted: z.boolean(),
|
|
haltReason: z.string().nullable(),
|
|
diagnostic: z.string().nullable(),
|
|
connection: paperConnectionSchema.nullable(),
|
|
lastReceivedAt: time.nullable(),
|
|
lastAvailableAt: time.nullable(),
|
|
lastSequence: counter.nullable(),
|
|
quotes: z.array(quoteClock),
|
|
quoteHighWater: z.array(quoteClock),
|
|
frames: z.record(
|
|
z
|
|
.object({ fingerprint: z.string(), disposition: z.enum(['health-only', 'admitted']) })
|
|
.strict()
|
|
),
|
|
observations: z.record(z.string()),
|
|
physicalQuotes: z.record(z.string()),
|
|
})
|
|
.strict();
|
|
export type CanonicalPaperHost = z.infer<typeof canonicalPaperHostSchema>;
|
|
const feedback = z
|
|
.object({
|
|
decision: nativeManagedOrderSchema.shape.order.shape.decision,
|
|
revision: counter,
|
|
orders: z.array(
|
|
z
|
|
.object({
|
|
orderId: z.string(),
|
|
instrumentId: z.string(),
|
|
decision: nativeManagedOrderSchema.shape.order.shape.decision,
|
|
status: nativeManagedOrderSchema.shape.status,
|
|
})
|
|
.strict()
|
|
),
|
|
})
|
|
.strict();
|
|
export const canonicalOwnerSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
definition,
|
|
cursor: counter,
|
|
diagnostic: z
|
|
.object({
|
|
ownerId: z.string(),
|
|
strategyId: z.string(),
|
|
strategyVersion: z.string(),
|
|
nextDecisionSequence: counter,
|
|
state: json,
|
|
rng: z
|
|
.object({
|
|
algorithm: z.literal('lcg32-v1'),
|
|
seed: metadataSchema.shape.seed,
|
|
state: metadataSchema.shape.seed,
|
|
draws: counter,
|
|
})
|
|
.strict(),
|
|
observationCount: counter,
|
|
previousAdmission: feedback.nullable(),
|
|
})
|
|
.strict()
|
|
.transform(value => ({ ...value, state: value.state })),
|
|
pendingObservations: z.array(observation),
|
|
})
|
|
.strict();
|
|
export const canonicalAccountSchema = z
|
|
.object({
|
|
kind: z.literal('canonical-paper'),
|
|
version: z.literal(1),
|
|
identity: financialTransactionResultSchema.shape.identity,
|
|
definitions: z.array(definition),
|
|
checkpoint: canonicalExecutionCheckpointSchema,
|
|
view: nativeFinancialViewSchema,
|
|
inputSequence: counter,
|
|
journalSequence: counter,
|
|
observed: counter,
|
|
pendingDecisionSequence: counter.nullable(),
|
|
latestObservations: z.array(observation),
|
|
host: canonicalPaperHostSchema.optional(),
|
|
})
|
|
.strict();
|
|
export const canonicalPaperInputSchema = z
|
|
.object({
|
|
command: matchingCommandSchema,
|
|
observations: z.array(observation),
|
|
decision: z
|
|
.object({
|
|
commandId: z.string().min(1),
|
|
key: matchingCommandSchema.shape.key,
|
|
barrierId: z.string().min(1),
|
|
ownerIds: z.array(z.string().min(1)).min(1),
|
|
inputs: barrier.shape.inputs,
|
|
})
|
|
.strict()
|
|
.optional(),
|
|
})
|
|
.strict();
|
|
export type CanonicalPaperInput = z.input<typeof canonicalPaperInputSchema>;
|
|
export const canonicalStoredInputSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
id: z.string(),
|
|
sequence: counter,
|
|
fingerprint: z.string(),
|
|
status: z.enum(['pending', 'applied']),
|
|
input: canonicalPaperInputSchema,
|
|
})
|
|
.strict();
|
|
export const canonicalBatchSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
id: z.string(),
|
|
sequence: counter,
|
|
status: z.enum(['pending', 'dispatched', 'failed']),
|
|
command: matchingCommandSchema,
|
|
})
|
|
.strict();
|
|
export const canonicalJournalSchema = z.discriminatedUnion('kind', [
|
|
z
|
|
.object({
|
|
kind: z.literal('effect'),
|
|
commandId: z.string(),
|
|
fact: financialTransactionResultSchema.shape.journal.element,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
kind: z.literal('command'),
|
|
command: matchingCommandSchema,
|
|
outcome: financialTransactionResultSchema.shape.outcome,
|
|
view: nativeFinancialViewSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
kind: z.literal('decision'),
|
|
commandId: z.string(),
|
|
key: matchingCommandSchema.shape.key,
|
|
context: stepSchema.shape.step.options[1],
|
|
})
|
|
.strict(),
|
|
]);
|
|
export type CanonicalAccount = z.infer<typeof canonicalAccountSchema>;
|
|
export type CanonicalOwner = z.infer<typeof canonicalOwnerSchema>;
|
|
export type CanonicalStoredInput = z.infer<typeof canonicalStoredInputSchema>;
|
|
export type CanonicalBatch = z.infer<typeof canonicalBatchSchema>;
|
|
export type CanonicalJournalPayload = z.infer<typeof canonicalJournalSchema>;
|
|
export type CanonicalJournalEntry = { sequence: number; payload: CanonicalJournalPayload };
|
|
export interface CanonicalTransaction {
|
|
account: CanonicalAccount;
|
|
owners(): Promise<CanonicalOwner[]>;
|
|
putOwner(owner: CanonicalOwner): Promise<void>;
|
|
getInput(id: string): Promise<CanonicalStoredInput | undefined>;
|
|
nextInput(): Promise<CanonicalStoredInput | undefined>;
|
|
putInput(input: CanonicalStoredInput): Promise<void>;
|
|
nextBatch(): Promise<CanonicalBatch | undefined>;
|
|
putBatch(batch: CanonicalBatch): Promise<void>;
|
|
appendJournal(payload: CanonicalJournalPayload): Promise<CanonicalJournalEntry>;
|
|
journal(after: number): Promise<CanonicalJournalEntry[]>;
|
|
}
|
|
export interface CanonicalExecutionRepository {
|
|
initialize(initial: CanonicalAccount, owners: CanonicalOwner[]): Promise<void>;
|
|
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
|
|
}
|
|
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
|
|
export class ExecutionConflictError extends Error {}
|
|
export { compareEventKeys } from '@stock-bot/stock-config/canonical-execution';
|
|
/** Legacy callers must never reinterpret any version of a canonical envelope. */
|
|
export function refuseCanonicalAccount(state: unknown): void {
|
|
if (state && typeof state === 'object' && 'kind' in state) {
|
|
throw new Error(
|
|
'Versioned execution account requires its canonical adapter; use an explicit migration or a new account ID'
|
|
);
|
|
}
|
|
}
|