/** 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; 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; 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; export type CanonicalOwner = z.infer; export type CanonicalStoredInput = z.infer; export type CanonicalBatch = z.infer; export type CanonicalJournalPayload = z.infer; export type CanonicalJournalEntry = { sequence: number; payload: CanonicalJournalPayload }; export interface CanonicalTransaction { account: CanonicalAccount; owners(): Promise; putOwner(owner: CanonicalOwner): Promise; getInput(id: string): Promise; nextInput(): Promise; putInput(input: CanonicalStoredInput): Promise; nextBatch(): Promise; putBatch(batch: CanonicalBatch): Promise; appendJournal(payload: CanonicalJournalPayload): Promise; journal(after: number): Promise; } export interface CanonicalExecutionRepository { initialize(initial: CanonicalAccount, owners: CanonicalOwner[]): Promise; transact(accountId: string, work: (tx: CanonicalTransaction) => Promise): Promise; } export type CanonicalPostgres = Pick; 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' ); } }