UNPKG

kestrel.markets

Version:

A typed, token-efficient language + runtime for agentic trading: agents author bounded plans, the runtime fires them at the tick. CLI + typed library + MCP server.

579 lines 40.7 kB
/** * # session/sim — the sim Session driver + graded report (RUNTIME §7) * * The one object that owns a `sim` run, wired end to end over the shipped substrate. It reads a * recorded/synthetic bus **as its clock** (`now` = each event's `ts`, RUNTIME §0), drives the * canonical market state and the {@link PlanEngine} trigger sweep, routes the engine's orders * through the **Gate** into a {@link SimFillEngine} (the judge, RUNTIME §6), reassesses resting * orders on every BOOK event (and resting SPOT orders on every SPOT tick carrying an NBBO, * ADR-0017), feeds the resulting fills **back** into the engine's org facts and onto the emitted * bus, cash-settles held inventory off the final spot — options at intrinsic, spot inventory * mark-to-market (ADR-0017) — and returns a graded {@link EpisodeReport}. * * One code path, one gate (RUNTIME §7): swapping the gate adapter is what turns this into paper * or live; nothing else changes. Every mode crosses the same fill model, so grades compare on * fills, not on fill assumptions (ARCHITECTURE §4). * * ## The per-event pass (no look-ahead — state at event N is a function of events ≤ N) * For each bus event, in order: * 1. **clock** — the gate's `now` is pinned to the event's `ts` (the Gate seam is `now`-less; * the driver owns the injected clock, RUNTIME §0). * 2. **canonical state** — {@link CanonicalState.applyEvent} folds SPOT/HEARTBEAT into the * signal instrument's one causal coordinate (the market-fact substrate the triggers read). * 3. **fill reassessment (BOOK only, BEFORE the sweep)** — the market acts first: every leg of * the book reassesses the matching resting orders through {@link SimFillEngine.onBook}; a * strict-cross floor fill is emitted **and fed back** into the engine (`engine.onEvent(fill)`) * so inventory, basis, and TP maintenance advance — all **before** the engine reacts to that * book. This is the load-bearing ordering (RUNTIME §7): a plan can never cancel/reprice an * order the same book would have filled. * 4. **engine sweep** — {@link PlanEngine.onEvent} arms/fires/manages; its PLAN + WAKE land on * the emitted bus, its order submits/cancels go through the {@link SimGate} into the fill * engine (each `place`/`cancel` ORDER event drained onto the emitted bus at submission time). * Orders placed *by this sweep* rest for the **next** book (fills are reassessed on book * events, one book at a time). * * At session end the fill engines **settle** at the final exec spot: filled option inventory * settles at intrinsic, filled spot inventory marks to the final spot (ADR-0017 — no expiry, no * intrinsic), still-resting orders expire worthless-unfilled ($0 floor). The report carries the * floor outcome and the E[$] under `pFill` side by side (RUNTIME §6). * * ## Determinism (RUNTIME §0/§7 — a test, not a hope) * Everything on the path is pure and injected-time; the emitted stream is stamped with a * monotonic `seq` in emission order and serialized canonically. `determinism_hash` is the * sha256 of that serialization: two runs on the same inputs produce the identical hash, and a * zero-documents run produces a stable pass-through hash. * * ## Fail-closed (RUNTIME §8, all loud) * No META header → refuse (a well-formed bus opens with exactly one META). Unknown fill model → * refuse to grade (never default silently). No instruments → refuse. Bus corruption surfaces * from {@link readBus} as a loud, line-located error. */ import type { BookState, BusEvent, ExperimentalEnvelope, Fidelity, FillModelStamp, InstanceIdentity, MetaEvent, Mode, NewBusEvent, OrderEvent, PlanOutcome, PlanState, Right, SampledQualificationClaim } from "../bus/index.ts"; import { CanonicalState, type SeriesProvider } from "../series/index.ts"; import { PlanEngine, type Gate, type InstrumentSpec, type OrderIntent, type OrderRole } from "../engine/index.ts"; import { type FairTauProvider } from "./clock.ts"; import { requireMeta, resolveSpecs, specFromMeta } from "./specs.ts"; import { SimFillEngine, SpotFillEngine, type EpisodeSigmoidParams, type FillModel, type SettleMark, type SpotSettleReport } from "../fill/index.ts"; import { type KestrelNode, type Module, type PlanStatement } from "../lang/index.ts"; import { type Blotter } from "../blotter/index.ts"; import { type HeadlinePnl } from "../grade/headline.ts"; import type { AgentConfig } from "./agent.ts"; import type { CarriedLot } from "../fill/index.ts"; import type { SessionCarry } from "./carry.ts"; /** The two shipped, named fill models (RUNTIME §6). Any other name is refused (fail-closed). */ export type FillModelName = "strict-cross-v1" | "maker-fair-v1"; /** * The machine-readable reason code a session de-arms under when the exec book's time-to-expiry is * unknowable (kestrel-wcnd) — it prefixes the CONTROL `disarm` note, which the Blotter projects as * a reason-carrying de-arm record (`disarms[].reason`, kestrel-2pl). Exported so a consumer (and * the guard fixture) matches the CODE rather than scraping prose. */ export declare const FAIR_TAU_UNKNOWN_CODE: "fair-tau-unknown"; /** Options for {@link runSimSession}. Exactly one of `busPath`/`events` supplies the bus. * `documents` are already-parsed Kestrel nodes (a bare statement or a full module — both are * normalized to a module and armed). Instrument contract facts are not on the v1 bus META, so * they are derived from the asset class (tick `0.01`, strike step `1`, multiplier `100` for an * option-underlier else `1`, role carried from META) unless `instruments` overrides them. * `fairTauYears` injects time-to-expiry so `@fair` (and the maker-fair hazard) can be built; * **absent, it defaults to the CONTRACT-expiry tau** ({@link expiryTauYears}: `max(0, 16:00 ET on * the book's OWN expiry − now)`, RUNTIME §4) — so `@fair` is buildable by default, decays toward * the contract's expiry (not this session's close, kestrel-wcnd), and goes UNKNOWN (fail-closed, * see {@link SessionCore.step}) when a book names no resolvable expiry. */ export interface RunSimOptions { readonly busPath?: string; readonly events?: readonly BusEvent[]; readonly documents: readonly KestrelNode[]; readonly fillModel: FillModelName; readonly rUsd: number; readonly out?: string; readonly instruments?: readonly InstrumentSpec[]; readonly fairTauYears?: FairTauProvider; /** Calibrated maker-fair fill params (the `episode-sigmoid-u-v1` form). When present with * `fillModel: "maker-fair-v1"`, the session grades under the calibrated curve instead of the * uncalibrated default hazard (RUNTIME §6). Ignored by `strict-cross-v1`. */ readonly makerFairParams?: EpisodeSigmoidParams; /** An optional agent config (kestrel-5zl.6). When supplied AND it declares an authoring identity, its * a57.14 experimental envelope is captured (`envelopeForConfig`) and stamped on the graded META. A * config-less run (the default) stamps no envelope — byte-identical to before (backward-compatible). */ readonly config?: AgentConfig; } /** One transition in a plan's lifecycle trace (RUNTIME §5), reconstructed from the emitted PLAN * stream. */ export interface PlanLifecycleStep { readonly ts: number; readonly state: PlanState; readonly outcome?: PlanOutcome; readonly reason?: string; } /** A plan's lifecycle trace + its terminal state (the outcome when `done`, else the last * lifecycle state). ONE trace is one exact Plan **instance** (kestrel-22j.15): a legal same-name replacement * is its OWN trace beside its predecessor, never collapsed into it. */ export interface PlanTrace { /** The authored plan NAME — the Lineage aggregation key (a name may legally recur; NOT the instance id). */ readonly plan: string; /** The exact Plan-instance identity this trace belongs to (kestrel-22j.15) — the id the engine minted, * carried on the emitted PLAN stream. Distinct per instance, so two same-name instances are two traces. */ readonly plan_instance: string; readonly lifecycle: readonly PlanLifecycleStep[]; readonly final_state: PlanState | PlanOutcome; } /** One gate order, joined across the intent (resolution annotation, role), the engine child * (esc stage), and the fill engine outcome (`pFill`, floor fill, settle P&L). */ export interface OrderReport { readonly ref: string; readonly plan: string; /** The authoring plan's exact INSTANCE identity (kestrel-22j.15) — carried from the order intent so an * order joins its exact instance, not merely its recurring name. */ readonly plan_instance: string; readonly role: OrderRole; readonly instrument: string; readonly side: "buy" | "sell"; readonly qty: number; /** The option strike; ABSENT for a spot/equity order (ADR-0017 — no fictional strike). */ readonly strike?: number; /** The option right; ABSENT for a spot/equity order (ADR-0017). */ readonly right?: Right; readonly px: number; /** The price-resolution annotation (`fair=fallback(mid)`, …) — a silent mid is forbidden, * RUNTIME §4. */ readonly annotation: string; /** The esc stage this resting order occupied (RUNTIME §4/§5) — the ladder rung, NOT a count of * reprices (the honest session-wide reprice tally is `session.reprice_count`, F6). */ readonly esc_stages: number; /** Expected fill probability `1 − survival` (`1` on a floor fill). */ readonly pFill: number; /** Did the strict-cross floor fire? */ readonly filled: boolean; /** The floor fill price, else `null`. */ readonly fillPx: number | null; /** Realized $ under the floor (0 unless floor-filled). */ readonly floorPnl: number; /** E[$] under `pFill`. */ readonly expectedPnl: number; /** Present + `true` when the order was cancelled mid-session (esc-replaced, TTL/INVALIDATE * pulled, or CANCEL-IF) rather than filled or settled. */ readonly cancelled?: boolean; } /** The graded sim report (RUNTIME §7). Stamps its judge (`fill_model`) and carries the * determinism hash of the emitted event stream. */ export interface EpisodeReport { readonly session: { readonly date: string; readonly instruments: readonly string[]; readonly mode: "sim"; readonly fill_model: string; readonly bus_events: number; /** sha256 of the emitted PLAN/WAKE/ORDER stream — pins the engine's OUTPUT (RUNTIME §0/§7). */ readonly determinism_hash: string; /** sha256 of the raw INPUT bus (serialized events) — pins what the run was graded against, so * determinism_hash (output) and bus_sha256 (input) together bind the whole computation (F6). */ readonly bus_sha256: string; /** Count of actual cancel/replace reprice submissions across the session (peg + esc), from the * engine — the honest reprice tally (F6; `orders[].esc_stages` is the ladder rung, not a count). */ readonly reprice_count: number; /** The **last bus event `ts`** — the session clock's final value (settle time). Injected, never * wall-clock (RUNTIME §0); the natural deterministic `now` for recording this run into the * ledger (ADR-0006). Equals `firstTs` for an empty bus. */ readonly settle_ts: number; }; readonly plans: readonly PlanTrace[]; readonly orders: readonly OrderReport[]; /** The three-channel P&L contract (kestrel-9gu.12): floor + expected always, sampled on a seeded run, * and the HEADLINE selected by the fail-closed qualification gate (floor until 9gu.8.6 passes). */ readonly totals: { /** Realized $ under the deterministic strict-cross floor — the honest lower bound. */ readonly realized_floor_usd: number; /** E[$] under the survival product — the analytic bound beside the realization. */ readonly expected_usd: number; /** The seeded causal realization (one ensemble replicate, ADR-0016). Present ONLY on a `fillSeed` * run — an un-run channel is never conflated with a zero outcome (kestrel-9gu.12). */ readonly sampled_usd?: number; readonly premium_spent: number; /** The settle mark's provenance + fail-closed staleness verdict + annotated recovery * (kestrel-xwf): the spot the book cash-settled against (`px` — the parity-recovered value when * `source: "parity"`), WHEN the primary mark's value was last established on the input tape * (`as_of_ts`; a frozen feed re-printing the same px does not refresh it), its age vs the settle * instant, and the `stale` verdict under the declared threshold. `stale: true` means the totals * above are graded against a mark the tape stopped supporting — NON-BANKABLE (a parity recovery * annotates, it does not pardon), never a silently fresh-looking number (the taint also rides the * Blotter's `totals.headline`). `source`/`mark_uncertain`/`note` are the recovery annotation: * `"parity"` = recovered honestly from a two-sided closing book; `"stale"` = refused — * `mark_uncertain: true`, the last mark retained. Explicit `null`s (never omitted keys) so the * report's shape is fixed. */ readonly settle_mark: { readonly px: number; readonly as_of_ts: number | null; readonly last_observed_ts: number | null; readonly age_ms: number | null; readonly stale_after_ms: number; readonly stale: boolean; readonly source: "market" | "parity" | "stale"; readonly mark_uncertain: boolean; readonly note: string | null; }; /** WHICH channel is the headline + the gate verdict that selected it + the xwf settle taint * ({@link HeadlinePnl}, kestrel-9gu.12). `floor` today; `sampled` once the 9gu.8.6 qualification is * on the record (never with extrapolated-support sampled realizations — bankableEv stays). The * settle-mark staleness verdict above feeds this headline's taint (a stale mark — including a * parity-recovered one — taints whichever channel leads). */ readonly headline: HeadlinePnl; }; readonly emitted: Readonly<Record<string, number>>; } /** * @deprecated Renamed to {@link EpisodeReport} (kestrel-markets-jcn0): the * deterministic execution unit is an **Episode**, not a "Kestrel Session" * ("session" is now reserved for the stateful TerminalSession seat, * PLAT-ADR-0052). This alias keeps `engine.session.SessionReport` type-importers * compiling across the rename; it will be removed after the 0.8.0 public cutover. * The on-the-wire report shape (its `session` payload field, `sessionId` keys) is * unchanged — this is a type-name-only rename, wire contract untouched. */ export type SessionReport = EpisodeReport; /** The canonical parse-print text of an armed document set — the byte-stable printer projection * (ADR-0001), documents joined by a blank line (matching the CLI's canonical plans text / the ledger's * `plans_sha256` input). Its sha256 is {@link InstanceIdentity.version}. A `Module` is a `KestrelNode`, * so this is the {@link canonicalPlansText} owner (canonical/plans) applied to an armed module set. */ export declare function canonicalPlansTextOf(modules: readonly Module[]): string; /** The fill-model judge stamp for a GRADED bus's META. `name`/`version` are the model's identity; * `calibration_sha` is a stable digest of the calibration descriptor; `self_limitation` is what the judge * DECLARES it could not observe (a57.4) — stamped verbatim so the projector never re-guesses it from `name` * (the mislabel of the calibrated judge, kestrel-o32) ({@link FillModelStamp}). */ export declare function fillModelStampOf(model: FillModel): FillModelStamp; /** The Instance identity for a GRADED bus's META (ADR-0011 recommendation 1, ADR-0006 names-are-data): * `lineage` = the authored NAME (the Pod's when the document set runs a Pod, else the first authored * plan/book statement's), `version` = `plans_sha256`, `mode` = the session mode, `pod` present ONLY for * an actual Pod document. A zero-document grade authors nothing ⇒ an empty `lineage`. */ export declare function instanceIdentityOf(modules: readonly Module[], mode: Mode): InstanceIdentity; /** Fidelity level for a mode (CONTEXT: Fidelity): sim/paper are `modeled`, live is `realized`. */ export declare function fidelityOf(mode: Mode): Fidelity; /** Stamp a GRADED bus's opening META: the input session header + the judge self-description * (`fill_model` + `instance` + `fidelity`) and, when supplied, the author's a57.14 experimental * `envelope` (the config's captured identity — kestrel-5zl.6) plus the FULL `config_id` * (`sha256(canonical AgentConfig)` — the sampling-axis-complete identity the grid CellKey keys on, * m9i.2 owner tweak). Advertises the current {@link BUS_SCHEMA} (v6 — a graded bus is the ONLY stamping * site that follows the bump; input tapes keep their pinned literal, clock-honest wakes §1) and, for a * verified clock-honest session, the `clock_honest: true` attestation (ADR-0040 — `true` or ABSENT, * never `false`). Keeps the input META's `seq`/`ts`. Pure. Only a GRADED bus carries these; an INPUT * tape's META stays judge-less (the two-bus rule, ADR-0011). The `envelope`/`config_id` keys are OMITTED * entirely when absent — a config-less graded bus is byte-identical to before (backward-compatible; * a57.14 leaves it `certified`). */ export declare function stampGradedMeta(inputMeta: MetaEvent, judge: { fillModel: FillModelStamp; instance: InstanceIdentity; fidelity: Fidelity; envelope?: ExperimentalEnvelope; configId?: string; cellConfigId?: string; sampledQualification?: SampledQualificationClaim; /** The clock-honest attestation (ADR-0040 / kestrel-w7la.1): pass `true` ONLY when the session ran * clocked semantics AND the data-floor verification held. The stamp is `true` or ABSENT — never * `false` (`false` is reserved platform-side as a revocation value; clock-honest wakes §5). */ clockHonest?: true; }): MetaEvent; /** Assemble the canonical GRADED bus for a session: the judge-stamped opening META (seq 0) followed by * the engine's emitted reactions (PLAN/WAKE/ORDER/TELEMETRY, incl. the settle-outcome records), * re-stamped `seq` 1..N so the stream is gap-free from 0 and opens with exactly one META — a well-formed * bus {@link readBus} accepts. This is the self-describing artifact the Blotter projector (slice 2) will * consume; slice 1 uses it to PROVE totals{floor,expected} + orders[].support re-derive from bus bytes * with no engine-state scrape. Pure. */ export declare function assembleGradedBus(gradedMeta: MetaEvent, emitted: readonly BusEvent[]): BusEvent[]; /** The append-only emitted stream: stamps a monotonic `seq` in emission order and serializes * canonically (the determinism substrate, RUNTIME §0/§1). */ declare class EmittedStream { #private; readonly events: BusEvent[]; /** Stamp the next `seq` and land the event in CANONICAL field order. The canonicalization is * {@link canonicalEnvelope} — the SAME owner {@link import("../bus/write.ts").BusWriter} stamps * through, never a second copy of the order — because a bare `{ seq: this.#seq++, ...ev }` would * preserve the CALLER's key order verbatim: an emitter spreading a payload that carries * `ts`/`stream`/`type` mid-object then serializes a non-canonical record onto the graded bus * (`serializeEvent` is `JSON.stringify`, insertion-order-dependent). That was kestrel-pta5 — * `theta_bleed` put `ts` after `type` — patched at the one call site with the class left open; * kestrel-byfl closes the class here, so no present or future emitter can reintroduce it. */ emit(ev: NewBusEvent): BusEvent; hash(): string; } /** The sim Gate: rests engine order intents in the {@link SimFillEngine} — or, for a SPOT/equity * intent (no strike/right, ADR-0017 / kestrel-20f.14), in the instrument-keyed * {@link SpotFillEngine} — and cancels them, pinning the injected clock (`now`) the driver sets * each event. Every `place`/`cancel` drains the fill engines' fresh ORDER events onto the * emitted bus at submission time. */ export declare class SimGate implements Gate { private readonly fill; private readonly spotFill; /** Whether spot orders may grade in this session — only the strict-cross family has a spot * judge today; a spot order under `maker-fair-v1` is REFUSED loudly (no spot hazard model * exists — never grade under a judge that cannot assess the instrument, RUNTIME §8). */ private readonly spotAllowed; private readonly drain; now: number; readonly intents: OrderIntent[]; constructor(fill: SimFillEngine, spotFill: SpotFillEngine, /** Whether spot orders may grade in this session — only the strict-cross family has a spot * judge today; a spot order under `maker-fair-v1` is REFUSED loudly (no spot hazard model * exists — never grade under a judge that cannot assess the instrument, RUNTIME §8). */ spotAllowed: boolean, drain: () => void); submit(intent: OrderIntent): string; cancel(ref: string): boolean; } /** * Derive a closing settle spot from **put-call parity** on a two-sided book: at (near-)expiry the * forward ≈ spot, so `C − P = S − K ⇒ S = K + (C_mid − P_mid)` for the strike nearest `nearSpot` that * quotes BOTH a two-sided call and a two-sided put. Returns the parity spot + the strike used, or * `null` when no strike has both sides two-sided (parity not derivable → fail-closed to a taint). * * Mids are used ONLY as a settle-mark of last resort when the primary feed died — never as an * execution anchor (the never-a-mid-anchor rule governs FILL prices, RUNTIME §4) — and the result is * always flagged as recovered-from-stale, never silently banked as a live mark. * * The caller supplies the CLOSING legs: {@link SessionCore} feeds this only quotes whose values are * FRESH at the settle instant (carried on a BOOK event within the declared settle-mark staleness * threshold, {@link SETTLE_MARK_STALE_AFTER_MS}) — a two-sided pair surviving in the FOLDED book * from hours before the option feed died is NOT a closing strike, and "recovering" from its stale * mids would launder one dead feed through another (the DEGRADED-DATA cell's dark-to-close shape). */ export declare function closingParitySpot(book: Pick<BookState, "legs"> | undefined, nearSpot: number): { spot: number; strike: number; } | null; /** The wired core internals a {@link SessionCoreOptions.liveGate} factory is handed to build its Gate. * It reads canonical state / the folded books the core already owns (never a second copy) and appends * the venue's own ORDER events onto the session's single live bus. */ export interface LiveGateWiring { readonly state: CanonicalState; readonly execSpec: InstrumentSpec; readonly signalSpec: InstrumentSpec; /** The core's folded option books (per instrument) — the same map a Frame renders, read by a paper * gate's price-anchor wall so the driver keeps no second book of its own. */ readonly books: ReadonlyMap<string, BookState>; /** Append ONE venue-emitted ORDER event onto the session's single live bus (stamps `seq`, stripping * any venue-local one), returning the stamped event. A `fill` is additionally queued to be fed back * into the engine AFTER the sweep (the broker fills-after-sweep ordering — the venue acts, the engine * reacts next). */ appendVenueEvent(ev: BusEvent | NewBusEvent): BusEvent; } /** What a {@link SessionCoreOptions.liveGate} factory returns — the injected Gate plus the two thin * hooks the live progression needs the core's per-event pass to call. Every field but `gate` is * optional; the sim path uses none of this. */ export interface LiveGateBinding { /** The gate orders route through (the L0-clamped paper/live gate) — REPLACES the reference SimGate. * Its `now` is pinned by the core each event exactly as `SimGate.now` is (RUNTIME §0). */ readonly gate: Gate & { now: number; }; /** Wrap the core's canonical series provider before the engine reads it — the paper path wraps it in * the feed-death staleness gate so a plan cannot fire off a dead line. Absent ⇒ the bare provider. */ wrapSeriesProvider?(base: SeriesProvider): SeriesProvider; /** Fold a venue fill into the driver's expected-position ledger (the reconciliation input), called * per fill BEFORE it is fed back to the engine. */ onVenueFill?(fill: OrderEvent): void; /** Run the engine sweep (+ the post-sweep venue-fill feedback) inside the driver's own error boundary * — the paper path maps a wall's `ClampRefused`/`IbkrOrderRefused` throw into a typed session * STAND_DOWN here. Absent ⇒ the sweep runs bare and any throw propagates. */ guardSweep?(apply: () => void): void; } /** What a {@link SessionCore} is constructed from — the pieces both the one-shot * {@link runSimSession} and the stepped {@link import("./day.ts").runDaySession} agree on. */ export interface SessionCoreOptions { readonly meta: MetaEvent; readonly specs: readonly InstrumentSpec[]; readonly fillModel: FillModelName; readonly rUsd: number; readonly fairTauYears: FairTauProvider; readonly makerFairParams?: EpisodeSigmoidParams; /** The initial injected clock (the first bus event's `ts`). */ readonly firstTs: number; /** The author's a57.14 experimental envelope, captured from the run's config (kestrel-5zl.6), stamped on * the graded META at open. Absent for a config-less run (a NO-LLM Backtest / day session) ⇒ no envelope. */ readonly envelope?: ExperimentalEnvelope; /** The FULL `ConfigId` of the run's config (`deriveConfigId(canonicalizeConfig(config))`, kestrel-5zl.6), * stamped on the graded META alongside `envelope` (m9i.2 owner tweak — the seeded RUN identity feeding * `SimRunId`). Supplied under the SAME condition as `envelope`; absent ⇒ no stamp. */ readonly configId?: string; /** The **cell config axis** (`cellConfigId(config)` — the full ConfigId with the `fillSeed` REPLICATE axis * stripped, kestrel-9gu.8.1 / ADR-0016 §3), stamped as `meta.cell_config_id`. Supplied ONLY when it DIVERGES * from {@link configId} (the config carried a `fillSeed`); absent for a seedless run, whose cell axis equals * `config_id` (so the graded bus stays byte-identical). The config axis the grid `cellOf` keys the cell on: * seed-only replicates share it. */ readonly cellConfigId?: string; /** The prior session's {@link SessionCarry} (the multi-session horizon design, kestrel-5zl.16). When present with non-empty * `positions`, this session OPENS with that carried inventory seeded into the fill engine at its * carry-mark basis (emitting an opening `place`+`fill` per lot). **Absent — or an `emptyCarry()` — * seeds nothing, so every existing single-session caller (and a length-1 sequence) is byte-identical * to today's flat open.** The standing-document re-arm is the driver's concern, not the core's. */ readonly openingCarry?: SessionCarry; /** The SamplingConfig fill-realization seed (kestrel-9gu.8.1/.8.3, ADR-0016). Present ⇒ the fill engine * draws CAUSAL sampled fills off a `fillSeed`-keyed per-episode substream; absent ⇒ the sampled channel is * OFF (fail-closed — floor + expected only). Derived from the run's config via `fillSeedOf`. */ readonly fillSeed?: number; /** The owner-recorded sampled-channel qualification claim (kestrel-9gu.8.6 → 9gu.12), derived from the * run's config via `sampledQualificationOf`. Present ⇒ stamped on the graded META and judged by the * headline gate. REFUSED LOUDLY (RUNTIME §8) when structurally contradictory: a claim on an unseeded run * (nothing to qualify) or under an uncalibrated judge (never an uncalibrated headline). Absent — every * run today — ⇒ the gate fails closed and strict-cross floor stays the headline (9gu.8 AC#7). */ readonly sampledQualification?: SampledQualificationClaim; /** The complete regime-scope vocabulary of the tape (kestrel-ocyf), pre-scanned from the full bus by * callers that hold it up front (`runSimSession` / `runSimulateSession`). Threaded to the engine so * `armDocument` can issue the DEFINITIVE dead-on-arrival notice for a regime gate whose scope is * never written on this tape (vs the conditional not-yet-written notice when the future is unknown). */ readonly tapeRegimeScopes?: readonly string[]; /** The clock-honest attestation input (ADR-0040 / kestrel-w7la.1): the driver passes `true` ONLY when * the session ran clocked semantics AND the §4 data-floor verification held (it refuses at open * otherwise, so a constructed core with this flag is an attested one). Stamped as the graded META's * `clock_honest: true`; absent ⇒ latency-blind ⇒ no stamp, byte-identical META. */ readonly clockHonest?: true; /** The LIVE-gate seam (OSS-ADR-0053): a factory that, given the wired core internals, returns the * gate a NON-sim progression (paper/live) routes orders through, plus its venue-fill hooks. Present * ONLY for the paper/live drivers; ABSENT for every sim/day/simulate caller — and when absent the * core builds its reference SimGate over its own fill engine and its per-event pass is byte-identical * to before (the sim corpus never sees this field). The factory is called ONCE at construction, after * canonical state + the emitted stream exist. */ readonly liveGate?: (wiring: LiveGateWiring) => LiveGateBinding; } /** * The sim runtime wired end to end — the ONE place the load-bearing per-event pass lives * (RUNTIME §7). Owns the fill engine (the judge), the emitted stream (determinism substrate), * the Gate, canonical market state, and the {@link PlanEngine}. Documents are armed * incrementally ({@link SessionCore.arm}); {@link SessionCore.step} advances one bus event with * **fills-before-sweep** ordering; {@link SessionCore.settle} cash-settles and drains. Both the * one-shot driver and the stepped day runner drive the identical core, so their emitted streams — * and therefore their determinism hashes — are produced by exactly the same code (no duplicated * event loop to drift). */ export declare class SessionCore { #private; readonly meta: MetaEvent; readonly emitted: EmittedStream; readonly fill: SimFillEngine; /** The instrument-keyed resting-order engine for SPOT/equity orders (ADR-0017, * kestrel-20f.14) — the spot sibling of {@link fill}; the Gate routes an intent with no * strike/right here. Idle (zero events, zero settle outcomes) on an options-only session. */ readonly spotFill: SpotFillEngine; readonly gate: SimGate; readonly engine: PlanEngine; readonly state: CanonicalState; readonly execSpec: InstrumentSpec; readonly signalSpec: InstrumentSpec; constructor(opts: SessionCoreOptions); /** Arm one already-normalized document module (RUNTIME §5). Retained (in arm order) as the source * of the GRADED bus's Instance identity (lineage = the authored name; version = plans_sha256). */ arm(mod: Module, opts?: { synthesizedOrder?: boolean; }): void; /** Cancel a resting order by its real Gate ref on behalf of an agent `cancelOrder` (kestrel-5zl.5 / #3c). * Pins the injected clock and routes through the engine so the engine dump (the wake snapshot's * `resting[]` source) and the emitted bus (the ORDER `cancel`) stay consistent in the SAME snapshot — * never one wake late. Returns whether a resting order was actually removed (fail-closed refuse on a * ref that matches nothing currently resting). */ cancelOrder(ref: string, now: number): boolean; /** FLATTEN an instrument on behalf of an agent `flatten` action (bd if0 / 75n). Pins the injected clock * and routes through the engine, which — for every managing plan holding the instrument — cancels the * plan's resting orders (neutralizing the rolling TP re-post) AND crosses a COVERED close through the * SAME Gate a fired Plan uses (never-naked holds; SELL floored at intrinsic). The gate drains its ORDER * cancel/place onto the emitted stream in the same step, so the wake snapshot's `resting[]` (engine dump) * and `engineLog` (bus projection) agree within one snapshot. Returns the closed contracts + plans * flattened (the driver's audit; a flat book returns `{0,0}` — a clean no-op). */ flatten(instrument: string, now: number): { closedQty: number; plansFlattened: number; }; /** The judge-stamped opening META of this session's GRADED bus (ADR-0011 part B): the input header * plus `fill_model` + `instance` + `fidelity`, self-describing the judge that produced these fills. * A pure derivation of the session inputs (fill model, armed documents, mode) — known at open. */ get gradedMeta(): MetaEvent; /** The canonical GRADED bus: the judge-stamped META (seq 0) + every emitted engine reaction (incl. * the settle-outcome telemetry), re-stamped gap-free from 0 — the self-describing artifact a Blotter * projector consumes, and the bus slice 1's enabling-property proof re-derives totals + support from. */ gradedBus(): BusEvent[]; /** * Project this session's canonical GRADED bus into its {@link Blotter} (kestrel-a57.1 slice 2, * ADR-0011). A pure projection of {@link gradedBus} — the Bus is the truth, the Blotter its * regenerable projection (ADR-0010); no engine-state scrape. The existing {@link EpisodeReport} * (see {@link buildReport}) and the CLI/Ledger stand UNCHANGED beside it — the report→Blotter * unification is a later cleanup. Call at finalize (after {@link settle}), as the driver does. */ blotter(): Blotter; /** Supersede the standing document set at `now` (RUNTIME §5, "document supersession"): de-arm * un-fired plans, halt acquisition + cancel unfilled children, inventory + TP/EXIT ride. The * caller {@link arm}s the replacement immediately after. */ supersede(now: number): void; /** Emit a raw (seq-less) bus event onto the emitted stream — the day driver's CONTROL/WAKE * handshake records (never ORDER; those come from the gate/fill engine). */ emit(ev: NewBusEvent): BusEvent; /** * Advance one bus event with the load-bearing ordering (RUNTIME §7): pin the clock, fold * canonical state, then — on a BOOK event — reassess resting orders for fills (the market acts * FIRST, fills fed back into the engine) BEFORE the engine sweep reacts to that same book. */ step(ev: BusEvent): void; /** Cash-settle at the final exec spot (RUNTIME §6): held OPTION inventory → intrinsic; held * SPOT inventory → mark-to-final-spot (ADR-0017 — no expiry, no intrinsic; the mark carries the * kestrel-xwf as-of watermark, so a stale final print is flagged, never silently marked to); * resting → $0. Threads the settle mark's provenance so the settle spot never grades without its * as-of/staleness verdict (kestrel-xwf). Drains the expired-unfilled cancels + settle telemetry * onto the emitted stream. Call once, * after the last step. * * `opts.carry` (the multi-session horizon design, kestrel-5zl.16.3) — a NON-final session of a multi-session Instance — * marks held OPTION inventory to close and lets it SURVIVE into {@link carriedInventory} (the emitted bus is * byte-identical to an intrinsic settle; only the bus-silent carried hand-off differs). Absent / `false` * — the final or a standalone session — is today's terminal intrinsic settle exactly (the position dies), * so a length-1 sequence is byte-for-byte unchanged. SPOT inventory carry (the overnight equity swing) is * NOT built yet (kestrel-20f.8): a carry settle that would strand a net spot position REFUSES loudly * rather than silently terminal-marking it (fail-closed, RUNTIME §8); a flat/closed spot book carries fine. * * kestrel-xwf: the mark's provenance is threaded to the engine, which grades it fail-closed (stale = * unstated as-of OR older than the declared threshold) and — when STALE — applies the closing * put-call-parity candidate derived here from the last folded two-sided book of the exec symbol * (the ANNOTATED recovery: `source: "parity"`, the book settles against the recovered spot) or * honestly refuses (`source: "stale"`, mark-uncertain, the last mark retained). The unified * `settle_mark` TELEMETRY record rides the graded bus whenever at least one order settled. */ settle(opts?: { readonly carry?: boolean; }): ReturnType<SimFillEngine["settle"]>; /** The carry-mark lots a `settle({ carry: true })` marked-and-kept — this session's contribution to the * next session's opening book (the multi-session horizon design). Empty after a final / intrinsic settle. */ carriedInventory(): readonly CarriedLot[]; /** The spot settle report (mark-to-final-spot, ADR-0017), after {@link settle}. Empty outcomes * on an options-only session. */ get spotSettle(): SpotSettleReport | undefined; /** The standing AUTHORED module at session end — the last authored View/Wake/Plan book (the carried * standing document, re-armed fresh next session), or `undefined` if this session authored no book * (synthesized one-shot orders do not count). */ get standingModule(): Module | undefined; /** Every armed plan STATEMENT the core holds, in arm order (kestrel-wa0j.29) — the typed ASTs the sim * driver captures the ENFORCED terms from for the `armed-plan` pane (the watcher's role-keyed percept: * it manages plans whose document text it otherwise never sees). A read-only projection of the armed * module set — it holds the SAME ASTs the engine armed, never a re-parse. */ get armedPlanStatements(): readonly PlanStatement[]; /** The resolved settle-mark provenance + verdict + annotated recovery (kestrel-xwf), available * after {@link settle} (the engine's {@link SettleMark}, unchanged). */ get settleMark(): SettleMark | undefined; /** Build the graded report (after {@link settle}). `busEventCount` and `busSha256` pin the * input bus alongside the emitted-stream determinism hash (F6). */ buildReport(busEventCount: number, busSha256: string): EpisodeReport; /** The latest folded option book per instrument — the chain a Frame renders. */ get books(): ReadonlyMap<string, BookState>; /** The current injected clock (the last stepped event's `ts`, or `firstTs` before any step). */ get settleTs(): number; } export { requireMeta, resolveSpecs, specFromMeta }; /** The sha256 of the serialized input bus — pins WHAT a run was graded against (F6). */ export declare function busSha256Of(events: readonly BusEvent[]): string; /** The tape's complete regime-scope vocabulary (kestrel-ocyf): every scope any REGIME event on the * bus writes, de-duplicated. Callers holding the full bus pass this to the engine so `armDocument` * can prove a regime gate dead on arrival (scope outside this set ⇒ it can never arm on this tape). */ export declare function tapeRegimeScopesOf(events: readonly BusEvent[]): string[]; /** * Drive one `sim` session end to end and return its graded {@link EpisodeReport} (RUNTIME §7). * Pure with respect to its inputs (given `events`, no I/O at all); with `busPath` it reads the * bus once. If `out` is given, the report is also written there as pretty JSON. Fails closed on * a missing META, an unknown fill model, or no instruments (RUNTIME §8). A thin driver over * {@link SessionCore}: arm all documents up front, step every event, settle, build. */ export declare function runSimSession(opts: RunSimOptions): EpisodeReport; /** Serialize + write a report to a path as pretty JSON (used by {@link runSimSession}'s `out` * and the CLI). */ export declare function writeReport(path: string, report: EpisodeReport): void; //# sourceMappingURL=sim.d.ts.map