@tradejs/cli 3.1.29-beta.282 → 3.1.29-beta.283

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1736 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/scripts/runtimeFeedbackProcess.ts
32
+ var runtimeFeedbackProcess_exports = {};
33
+ __export(runtimeFeedbackProcess_exports, {
34
+ main: () => main
35
+ });
36
+ module.exports = __toCommonJS(runtimeFeedbackProcess_exports);
37
+ var import_args = __toESM(require("args"));
38
+ var import_node_path3 = __toESM(require("path"));
39
+
40
+ // src/lib/runtimeFeedbackProcess.ts
41
+ var import_promises2 = __toESM(require("fs/promises"));
42
+ var import_node_path2 = __toESM(require("path"));
43
+ var import_node_crypto2 = require("crypto");
44
+ var import_diagnostics = require("@tradejs/node/diagnostics");
45
+
46
+ // src/lib/executionCalibration.ts
47
+ var import_constants = require("@tradejs/core/constants");
48
+ var import_data = require("@tradejs/core/data");
49
+ var import_trade = require("@tradejs/core/trade");
50
+ var roundMetric = (value, decimals = 6) => typeof value === "number" && Number.isFinite(value) ? Number(value.toFixed(decimals)) : null;
51
+ var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
52
+ var asArray = (value) => Array.isArray(value) ? value : [];
53
+ var finiteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
54
+ var finiteString = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
55
+ var finiteDirection = (value) => value === "LONG" || value === "SHORT" ? value : null;
56
+ var metricValues = (samples, key) => samples.map((sample) => sample[key]).filter(
57
+ (value) => typeof value === "number" && Number.isFinite(value)
58
+ );
59
+ var quantile = (values, probability) => {
60
+ if (!values.length) {
61
+ return null;
62
+ }
63
+ const sorted = [...values].sort((left, right) => left - right);
64
+ const index = (sorted.length - 1) * probability;
65
+ const lowerIndex = Math.floor(index);
66
+ const upperIndex = Math.ceil(index);
67
+ const lower = sorted[lowerIndex];
68
+ const upper = sorted[upperIndex];
69
+ if (lower == null || upper == null) {
70
+ return null;
71
+ }
72
+ if (lowerIndex === upperIndex) {
73
+ return lower;
74
+ }
75
+ return lower + (upper - lower) * (index - lowerIndex);
76
+ };
77
+ var summarizeNumbers = (values) => {
78
+ const finite = values.filter((value) => Number.isFinite(value));
79
+ if (!finite.length) {
80
+ return {
81
+ count: 0,
82
+ min: null,
83
+ max: null,
84
+ avg: null,
85
+ p50: null,
86
+ p75: null,
87
+ p90: null,
88
+ p95: null
89
+ };
90
+ }
91
+ const total = finite.reduce((sum2, value) => sum2 + value, 0);
92
+ return {
93
+ count: finite.length,
94
+ min: roundMetric(Math.min(...finite)),
95
+ max: roundMetric(Math.max(...finite)),
96
+ avg: roundMetric(total / finite.length),
97
+ p50: roundMetric(quantile(finite, 0.5)),
98
+ p75: roundMetric(quantile(finite, 0.75)),
99
+ p90: roundMetric(quantile(finite, 0.9)),
100
+ p95: roundMetric(quantile(finite, 0.95))
101
+ };
102
+ };
103
+ var getIntervalMs = (interval) => {
104
+ if (!interval) {
105
+ return null;
106
+ }
107
+ try {
108
+ return (0, import_data.intervalToMs)(interval);
109
+ } catch {
110
+ return null;
111
+ }
112
+ };
113
+ var getSignalKey = ({
114
+ strategy,
115
+ symbol,
116
+ timestamp
117
+ }) => strategy && symbol && timestamp != null ? `${strategy}:${symbol}:${timestamp}` : null;
118
+ var addSignalToMap = (signalsById, signalsByShape, signal) => {
119
+ if (!signal) {
120
+ return;
121
+ }
122
+ const signalId = finiteString(signal.signalId);
123
+ if (signalId) {
124
+ signalsById.set(signalId, signal);
125
+ }
126
+ const shapeKey = getSignalKey({
127
+ strategy: finiteString(signal.strategy),
128
+ symbol: finiteString(signal.symbol),
129
+ timestamp: finiteNumber(signal.timestamp)
130
+ });
131
+ if (shapeKey) {
132
+ signalsByShape.set(shapeKey, signal);
133
+ }
134
+ };
135
+ var getRuntimePayload = ({
136
+ runtimeArtifact,
137
+ replayEvidenceArtifact
138
+ }) => {
139
+ const explicitRuntime = asRecord(runtimeArtifact);
140
+ if (explicitRuntime) {
141
+ return asRecord(explicitRuntime.runtime) ?? explicitRuntime;
142
+ }
143
+ const replayEvidence = asRecord(replayEvidenceArtifact);
144
+ return asRecord(replayEvidence?.runtime);
145
+ };
146
+ var extractRuntimeTradeRows = (runtimePayload2) => {
147
+ if (!runtimePayload2) {
148
+ return [];
149
+ }
150
+ const signalsById = /* @__PURE__ */ new Map();
151
+ const signalsByShape = /* @__PURE__ */ new Map();
152
+ for (const signalRow of asArray(runtimePayload2.signals)) {
153
+ const record = asRecord(signalRow);
154
+ addSignalToMap(
155
+ signalsById,
156
+ signalsByShape,
157
+ asRecord(record?.signal) ?? record
158
+ );
159
+ }
160
+ return asArray(runtimePayload2.trades).map((row) => {
161
+ const record = asRecord(row);
162
+ if (!record) {
163
+ return null;
164
+ }
165
+ const redisValues = asRecord(record.redisValues);
166
+ const trade = asRecord(record.trade) ?? asRecord(redisValues?.trade) ?? record;
167
+ const signalId = finiteString(trade.signalId);
168
+ const shapeKey = getSignalKey({
169
+ strategy: finiteString(trade.strategy),
170
+ symbol: finiteString(trade.symbol),
171
+ timestamp: finiteNumber(trade.signalTimestamp ?? trade.entryTimestamp)
172
+ });
173
+ const signal = asRecord(redisValues?.signal) ?? (signalId ? signalsById.get(signalId) ?? null : null) ?? (shapeKey ? signalsByShape.get(shapeKey) ?? null : null);
174
+ return {
175
+ trade,
176
+ signal,
177
+ runtimeLineage: asRecord(trade.runtimeLineage) ?? null
178
+ };
179
+ }).filter((row) => row != null);
180
+ };
181
+ var normalizeReplayMatch = (value) => {
182
+ const item = asRecord(value);
183
+ if (!item) {
184
+ return null;
185
+ }
186
+ const runtime = asRecord(item.runtime);
187
+ const backtest = asRecord(item.backtest);
188
+ return {
189
+ orderId: finiteString(
190
+ item.orderId ?? runtime?.orderId ?? backtest?.orderId
191
+ ),
192
+ orderLinkId: finiteString(item.orderLinkId ?? runtime?.orderLinkId),
193
+ signalId: finiteString(item.signalId ?? backtest?.signalId),
194
+ strategy: finiteString(
195
+ item.strategy ?? backtest?.strategy ?? runtime?.inferredStrategy
196
+ ),
197
+ symbol: finiteString(item.symbol ?? backtest?.symbol ?? runtime?.symbol),
198
+ direction: finiteDirection(
199
+ item.direction ?? backtest?.direction ?? runtime?.direction
200
+ ),
201
+ backtestPrice: finiteNumber(item.backtestPrice ?? backtest?.price),
202
+ runtimePrice: finiteNumber(item.runtimePrice ?? runtime?.price)
203
+ };
204
+ };
205
+ var extractReplayMatches = (replayEvidenceArtifact) => {
206
+ const artifact = asRecord(replayEvidenceArtifact);
207
+ if (!artifact) {
208
+ return [];
209
+ }
210
+ const replay = asRecord(artifact.replay) ?? artifact;
211
+ const runtimeComparison = asRecord(replay.runtimeComparison);
212
+ const details = asRecord(runtimeComparison?.details);
213
+ const matched = asArray(runtimeComparison?.matched).length ? asArray(runtimeComparison?.matched) : asArray(details?.matched);
214
+ return matched.map(normalizeReplayMatch).filter((match) => match != null);
215
+ };
216
+ var buildReplayMatchMaps = (matches) => {
217
+ const maps = {
218
+ byOrderId: /* @__PURE__ */ new Map(),
219
+ bySignalId: /* @__PURE__ */ new Map()
220
+ };
221
+ for (const match of matches) {
222
+ for (const orderId of [match.orderLinkId, match.orderId]) {
223
+ if (orderId) {
224
+ maps.byOrderId.set(orderId, match);
225
+ }
226
+ }
227
+ if (match.signalId) {
228
+ maps.bySignalId.set(match.signalId, match);
229
+ }
230
+ }
231
+ return maps;
232
+ };
233
+ var getSignalCandles = (signal, interval) => {
234
+ const indicators = asRecord(signal?.indicators);
235
+ if (!indicators) {
236
+ return null;
237
+ }
238
+ const intervalKey = (() => {
239
+ switch (interval) {
240
+ case "15":
241
+ return "candles15m";
242
+ case "60":
243
+ return "candles1h";
244
+ case "240":
245
+ return "candles4h";
246
+ case "D":
247
+ return "candles1d";
248
+ default:
249
+ return null;
250
+ }
251
+ })();
252
+ const keys = [
253
+ intervalKey,
254
+ "candles15m",
255
+ "candles1h",
256
+ "candles4h",
257
+ "candles1d",
258
+ "candles"
259
+ ].filter((key) => Boolean(key));
260
+ for (const key of keys) {
261
+ const value = indicators[key];
262
+ if (Array.isArray(value) && value.length > 1) {
263
+ return value;
264
+ }
265
+ }
266
+ const candle = indicators.candle;
267
+ const prevCandle = indicators.prevCandle;
268
+ return prevCandle && candle ? [prevCandle, candle] : null;
269
+ };
270
+ var adverseEntryBps = ({
271
+ direction,
272
+ expectedPrice,
273
+ actualPrice
274
+ }) => {
275
+ if (!direction || expectedPrice == null || actualPrice == null || expectedPrice <= 0 || actualPrice <= 0) {
276
+ return null;
277
+ }
278
+ const value = direction === "LONG" ? (actualPrice / expectedPrice - 1) * 1e4 : (expectedPrice / actualPrice - 1) * 1e4;
279
+ return roundMetric(value);
280
+ };
281
+ var feeBps = ({
282
+ fee,
283
+ fillAvgPrice,
284
+ qty
285
+ }) => {
286
+ const notional = fillAvgPrice != null && qty != null && fillAvgPrice > 0 && qty > 0 ? fillAvgPrice * qty : null;
287
+ return fee != null && notional != null && notional > 0 ? roundMetric(fee / notional * 1e4) : null;
288
+ };
289
+ var latencyDelta = (end, start) => end != null && start != null ? roundMetric(end - start, 3) : null;
290
+ var resolveTelemetryQuality = ({
291
+ signalClosePrice,
292
+ arrivalMid,
293
+ orderSubmitTime,
294
+ orderAckTime,
295
+ fillAvgPrice,
296
+ fillTime
297
+ }) => {
298
+ if (signalClosePrice != null && arrivalMid != null && orderSubmitTime != null && orderAckTime != null && fillAvgPrice != null && fillTime != null) {
299
+ return "full";
300
+ }
301
+ if (fillAvgPrice != null && (arrivalMid != null || orderSubmitTime != null)) {
302
+ return "partial";
303
+ }
304
+ if (fillAvgPrice != null) {
305
+ return "price_only";
306
+ }
307
+ return "none";
308
+ };
309
+ var finiteTelemetryQuality = (value) => {
310
+ const raw = finiteString(value);
311
+ return raw === "full" || raw === "partial" || raw === "price_only" || raw === "none" ? raw : null;
312
+ };
313
+ var countBy = (samples, keyGetter) => {
314
+ const counts = /* @__PURE__ */ new Map();
315
+ for (const sample of samples) {
316
+ const key = keyGetter(sample) ?? "unknown";
317
+ counts.set(key, (counts.get(key) ?? 0) + 1);
318
+ }
319
+ return Object.fromEntries(
320
+ [...counts.entries()].sort(([left], [right]) => left.localeCompare(right))
321
+ );
322
+ };
323
+ var toLatencyBucket = (sample) => {
324
+ const latencyMs = sample.signalCloseToSubmitMs ?? sample.signalToSubmitMs;
325
+ if (latencyMs == null || !Number.isFinite(latencyMs)) return "unknown";
326
+ if (latencyMs <= 1e3) return "0-1s";
327
+ if (latencyMs <= 5e3) return "1-5s";
328
+ if (latencyMs <= 3e4) return "5-30s";
329
+ if (latencyMs <= 12e4) return "30-120s";
330
+ return "120s+";
331
+ };
332
+ var toSpreadBucket = (sample) => {
333
+ const spreadBps = sample.spreadBps;
334
+ if (spreadBps == null || !Number.isFinite(spreadBps)) return "unknown";
335
+ if (spreadBps <= 5) return "0-5bps";
336
+ if (spreadBps <= 20) return "5-20bps";
337
+ if (spreadBps <= 50) return "20-50bps";
338
+ return "50bps+";
339
+ };
340
+ var buildSample = ({
341
+ row,
342
+ match
343
+ }) => {
344
+ const { trade, signal } = row;
345
+ const strategy = finiteString(trade.strategy ?? signal?.strategy);
346
+ const symbol = finiteString(trade.symbol ?? signal?.symbol);
347
+ const interval = finiteString(trade.interval ?? signal?.interval);
348
+ const direction = finiteDirection(trade.direction ?? signal?.direction);
349
+ const orderId = finiteString(trade.orderId);
350
+ const signalId = finiteString(trade.signalId ?? signal?.signalId);
351
+ const qty = finiteNumber(trade.qty);
352
+ const signalTimestamp = finiteNumber(
353
+ trade.signalTimestamp ?? signal?.timestamp
354
+ );
355
+ const intervalMs = getIntervalMs(interval);
356
+ const signalCloseTimestamp = signalTimestamp != null && intervalMs != null ? signalTimestamp + intervalMs : signalTimestamp;
357
+ const signalClosePrice = finiteNumber(trade.signalClosePrice);
358
+ const arrivalSnapshotTime = finiteNumber(trade.arrivalSnapshotTime);
359
+ const arrivalSource = finiteString(trade.arrivalSource);
360
+ const arrivalMid = finiteNumber(trade.arrivalMid);
361
+ const bid = finiteNumber(trade.bid);
362
+ const ask = finiteNumber(trade.ask);
363
+ const spreadBps = finiteNumber(trade.spreadBps);
364
+ const orderSubmitTime = finiteNumber(trade.orderSubmitTime);
365
+ const orderAckTime = finiteNumber(trade.orderAckTime);
366
+ const fillAvgPrice = finiteNumber(trade.fillAvgPrice);
367
+ const fillSource = finiteString(trade.fillSource);
368
+ const fillTime = finiteNumber(trade.fillTime);
369
+ const telemetryQuality = finiteTelemetryQuality(trade.telemetryQuality) ?? resolveTelemetryQuality({
370
+ signalClosePrice,
371
+ arrivalMid,
372
+ orderSubmitTime,
373
+ orderAckTime,
374
+ fillAvgPrice,
375
+ fillTime
376
+ });
377
+ const fee = finiteNumber(trade.fee ?? trade.openFee);
378
+ const arrivalSnapshotAgeMs = latencyDelta(
379
+ orderSubmitTime,
380
+ arrivalSnapshotTime
381
+ );
382
+ const signalToSubmitMs = latencyDelta(orderSubmitTime, signalTimestamp);
383
+ const signalCloseToSubmitMs = latencyDelta(
384
+ orderSubmitTime,
385
+ signalCloseTimestamp
386
+ );
387
+ const submitToAckMs = latencyDelta(orderAckTime, orderSubmitTime);
388
+ const submitToFillMs = latencyDelta(fillTime, orderSubmitTime);
389
+ const orderAckToFillMs = latencyDelta(fillTime, orderAckTime);
390
+ const signalToFillMs = latencyDelta(fillTime, signalTimestamp);
391
+ const observedDelayMs = signalCloseToSubmitMs != null && signalCloseToSubmitMs >= 0 ? signalCloseToSubmitMs : signalToSubmitMs != null && signalToSubmitMs >= 0 ? signalToSubmitMs : null;
392
+ const candles = getSignalCandles(signal, interval);
393
+ const currentDelayRiskBps = roundMetric(
394
+ (0, import_trade.calculateDelayRiskBps)({
395
+ candles,
396
+ intervalMs
397
+ })
398
+ );
399
+ const rawConfiguredDelayRiskBps = roundMetric(
400
+ (0, import_trade.calculateDelayRiskBps)({
401
+ candles,
402
+ intervalMs,
403
+ multiplier: 1,
404
+ maxBps: Number.POSITIVE_INFINITY
405
+ })
406
+ );
407
+ const rawObservedDelayRiskBps = roundMetric(
408
+ (0, import_trade.calculateDelayRiskBps)({
409
+ candles,
410
+ intervalMs,
411
+ expectedDelayMs: observedDelayMs,
412
+ multiplier: 1,
413
+ maxBps: Number.POSITIVE_INFINITY
414
+ })
415
+ );
416
+ const signalToArrivalAdverseBps = adverseEntryBps({
417
+ direction,
418
+ expectedPrice: signalClosePrice,
419
+ actualPrice: arrivalMid
420
+ });
421
+ const arrivalToFillAdverseBps = adverseEntryBps({
422
+ direction,
423
+ expectedPrice: arrivalMid,
424
+ actualPrice: fillAvgPrice
425
+ });
426
+ const signalToFillAdverseBps = adverseEntryBps({
427
+ direction,
428
+ expectedPrice: signalClosePrice,
429
+ actualPrice: fillAvgPrice
430
+ });
431
+ const currentModelEntrySlippageBps = signalToFillAdverseBps != null ? roundMetric(
432
+ import_constants.BACKTEST_BASE_SLIPPAGE_BPS + (spreadBps ?? 0) * import_constants.BACKTEST_SPREAD_SLIPPAGE_MULTIPLIER + import_constants.BACKTEST_MARKET_IMPACT_BPS + (currentDelayRiskBps ?? 0)
433
+ ) : null;
434
+ const residualVsCurrentModelBps = signalToFillAdverseBps != null && currentModelEntrySlippageBps != null ? roundMetric(signalToFillAdverseBps - currentModelEntrySlippageBps) : null;
435
+ return {
436
+ strategy,
437
+ symbol,
438
+ interval,
439
+ direction,
440
+ orderId,
441
+ signalId,
442
+ qty,
443
+ signalTimestamp,
444
+ signalCloseTimestamp,
445
+ signalClosePrice,
446
+ arrivalSnapshotTime,
447
+ arrivalSource,
448
+ arrivalMid,
449
+ bid,
450
+ ask,
451
+ spreadBps,
452
+ orderSubmitTime,
453
+ orderAckTime,
454
+ fillAvgPrice,
455
+ fillSource,
456
+ fillTime,
457
+ telemetryQuality,
458
+ fee,
459
+ feeBps: feeBps({ fee, fillAvgPrice, qty }),
460
+ arrivalSnapshotAgeMs,
461
+ signalToSubmitMs,
462
+ signalCloseToSubmitMs,
463
+ submitToAckMs,
464
+ submitToFillMs,
465
+ orderAckToFillMs,
466
+ signalToFillMs,
467
+ signalToArrivalAdverseBps,
468
+ arrivalToFillAdverseBps,
469
+ signalToFillAdverseBps,
470
+ currentDelayRiskBps,
471
+ rawConfiguredDelayRiskBps,
472
+ rawObservedDelayRiskBps,
473
+ currentModelEntrySlippageBps,
474
+ residualVsCurrentModelBps,
475
+ replayEntryResidualBps: adverseEntryBps({
476
+ direction: direction ?? match?.direction ?? null,
477
+ expectedPrice: match?.backtestPrice ?? null,
478
+ actualPrice: match?.runtimePrice ?? null
479
+ }),
480
+ runtimeLineage: row.runtimeLineage
481
+ };
482
+ };
483
+ var buildReplayOnlySample = (match) => ({
484
+ strategy: match.strategy,
485
+ symbol: match.symbol,
486
+ interval: null,
487
+ direction: match.direction,
488
+ orderId: match.orderLinkId ?? match.orderId,
489
+ signalId: match.signalId,
490
+ qty: null,
491
+ signalTimestamp: null,
492
+ signalCloseTimestamp: null,
493
+ signalClosePrice: null,
494
+ arrivalSnapshotTime: null,
495
+ arrivalSource: null,
496
+ arrivalMid: null,
497
+ bid: null,
498
+ ask: null,
499
+ spreadBps: null,
500
+ orderSubmitTime: null,
501
+ orderAckTime: null,
502
+ fillAvgPrice: match.runtimePrice,
503
+ fillSource: "replay_runtime_price",
504
+ fillTime: null,
505
+ telemetryQuality: match.runtimePrice != null ? "price_only" : "none",
506
+ fee: null,
507
+ feeBps: null,
508
+ arrivalSnapshotAgeMs: null,
509
+ signalToSubmitMs: null,
510
+ signalCloseToSubmitMs: null,
511
+ submitToAckMs: null,
512
+ submitToFillMs: null,
513
+ orderAckToFillMs: null,
514
+ signalToFillMs: null,
515
+ signalToArrivalAdverseBps: null,
516
+ arrivalToFillAdverseBps: null,
517
+ signalToFillAdverseBps: null,
518
+ currentDelayRiskBps: null,
519
+ rawConfiguredDelayRiskBps: null,
520
+ rawObservedDelayRiskBps: null,
521
+ currentModelEntrySlippageBps: null,
522
+ residualVsCurrentModelBps: null,
523
+ replayEntryResidualBps: adverseEntryBps({
524
+ direction: match.direction,
525
+ expectedPrice: match.backtestPrice,
526
+ actualPrice: match.runtimePrice
527
+ }),
528
+ runtimeLineage: null
529
+ });
530
+ var hasTelemetry = (sample) => sample.signalClosePrice != null || sample.arrivalMid != null || sample.orderSubmitTime != null || sample.fillAvgPrice != null || sample.fillTime != null || sample.fee != null;
531
+ var hasFullTelemetry = (sample) => sample.signalClosePrice != null && sample.arrivalMid != null && sample.orderSubmitTime != null && sample.orderAckTime != null && sample.fillAvgPrice != null && sample.fillTime != null;
532
+ var buildGroupSummary = (samples) => ({
533
+ trades: samples.length,
534
+ fullTelemetryTrades: samples.filter(hasFullTelemetry).length,
535
+ replayMatchedTrades: metricValues(samples, "replayEntryResidualBps").length,
536
+ telemetryQuality: countBy(samples, (sample) => sample.telemetryQuality),
537
+ fillSource: countBy(samples, (sample) => sample.fillSource),
538
+ arrivalSource: countBy(samples, (sample) => sample.arrivalSource),
539
+ signalToArrivalAdverseBps: summarizeNumbers(
540
+ metricValues(samples, "signalToArrivalAdverseBps")
541
+ ),
542
+ arrivalToFillAdverseBps: summarizeNumbers(
543
+ metricValues(samples, "arrivalToFillAdverseBps")
544
+ ),
545
+ signalToFillAdverseBps: summarizeNumbers(
546
+ metricValues(samples, "signalToFillAdverseBps")
547
+ ),
548
+ residualVsCurrentModelBps: summarizeNumbers(
549
+ metricValues(samples, "residualVsCurrentModelBps")
550
+ ),
551
+ replayEntryResidualBps: summarizeNumbers(
552
+ metricValues(samples, "replayEntryResidualBps")
553
+ ),
554
+ spreadBps: summarizeNumbers(metricValues(samples, "spreadBps")),
555
+ feeBps: summarizeNumbers(metricValues(samples, "feeBps")),
556
+ arrivalSnapshotAgeMs: summarizeNumbers(
557
+ metricValues(samples, "arrivalSnapshotAgeMs")
558
+ ),
559
+ signalToSubmitMs: summarizeNumbers(metricValues(samples, "signalToSubmitMs")),
560
+ signalCloseToSubmitMs: summarizeNumbers(
561
+ metricValues(samples, "signalCloseToSubmitMs")
562
+ ),
563
+ submitToAckMs: summarizeNumbers(metricValues(samples, "submitToAckMs")),
564
+ submitToFillMs: summarizeNumbers(metricValues(samples, "submitToFillMs")),
565
+ orderAckToFillMs: summarizeNumbers(metricValues(samples, "orderAckToFillMs")),
566
+ currentDelayRiskBps: summarizeNumbers(
567
+ metricValues(samples, "currentDelayRiskBps")
568
+ ),
569
+ rawConfiguredDelayRiskBps: summarizeNumbers(
570
+ metricValues(samples, "rawConfiguredDelayRiskBps")
571
+ ),
572
+ rawObservedDelayRiskBps: summarizeNumbers(
573
+ metricValues(samples, "rawObservedDelayRiskBps")
574
+ )
575
+ });
576
+ var groupSamples = (samples, keyGetter) => {
577
+ const groups = /* @__PURE__ */ new Map();
578
+ for (const sample of samples) {
579
+ const key = keyGetter(sample);
580
+ if (!key) {
581
+ continue;
582
+ }
583
+ groups.set(key, [...groups.get(key) ?? [], sample]);
584
+ }
585
+ return Object.fromEntries(
586
+ [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([key, group]) => [key, buildGroupSummary(group)])
587
+ );
588
+ };
589
+ var positiveMetricValues = (samples, key) => metricValues(samples, key).filter((value) => value > 0);
590
+ var buildRecommendation = (samples) => {
591
+ const fullTelemetrySamples = samples.filter(hasFullTelemetry);
592
+ const notes = [];
593
+ if (!fullTelemetrySamples.length) {
594
+ return {
595
+ confidence: "none",
596
+ baseSlippageBps: null,
597
+ spreadMultiplier: null,
598
+ delayRiskMultiplier: null,
599
+ delayRiskMaxBps: null,
600
+ expectedDelayMs: null,
601
+ notes: [
602
+ "No full live execution telemetry was found. Use a newer runtime debug artifact collected after telemetry persistence was enabled.",
603
+ "Replay residuals can still diagnose model drift, but they are not enough to calibrate signal-to-arrival and arrival-to-fill components separately."
604
+ ]
605
+ };
606
+ }
607
+ if (fullTelemetrySamples.length < 20) {
608
+ notes.push(
609
+ "Sample is small; treat recommendations as diagnostic until at least 20-50 live fills are available."
610
+ );
611
+ }
612
+ const spreadRatios = fullTelemetrySamples.map((sample) => {
613
+ if (sample.arrivalToFillAdverseBps == null || sample.spreadBps == null || sample.spreadBps <= 0) {
614
+ return null;
615
+ }
616
+ return Math.max(0, sample.arrivalToFillAdverseBps) / sample.spreadBps;
617
+ }).filter(
618
+ (value) => value != null && Number.isFinite(value)
619
+ );
620
+ const spreadMultiplier = roundMetric(quantile(spreadRatios, 0.75), 4);
621
+ const baseResiduals = fullTelemetrySamples.map((sample) => {
622
+ if (sample.arrivalToFillAdverseBps == null) {
623
+ return null;
624
+ }
625
+ return Math.max(
626
+ 0,
627
+ sample.arrivalToFillAdverseBps - (sample.spreadBps ?? 0) * (spreadMultiplier ?? import_constants.BACKTEST_SPREAD_SLIPPAGE_MULTIPLIER)
628
+ );
629
+ }).filter(
630
+ (value) => value != null && Number.isFinite(value)
631
+ );
632
+ const closeDelayMs = positiveMetricValues(
633
+ fullTelemetrySamples,
634
+ "signalCloseToSubmitMs"
635
+ );
636
+ const fallbackDelayMs = positiveMetricValues(
637
+ fullTelemetrySamples,
638
+ "signalToSubmitMs"
639
+ );
640
+ if (!spreadRatios.length) {
641
+ notes.push(
642
+ "Spread multiplier could not be calibrated because spreadBps or arrival-to-fill telemetry is missing."
643
+ );
644
+ }
645
+ notes.push(
646
+ "Delay risk bps is disabled; signal-to-arrival latency is modeled by next-bar-open backtest fills."
647
+ );
648
+ return {
649
+ confidence: fullTelemetrySamples.length >= 50 ? "high" : fullTelemetrySamples.length >= 20 ? "medium" : "low",
650
+ baseSlippageBps: roundMetric(quantile(baseResiduals, 0.75), 2),
651
+ spreadMultiplier,
652
+ delayRiskMultiplier: null,
653
+ delayRiskMaxBps: null,
654
+ expectedDelayMs: roundMetric(
655
+ quantile(closeDelayMs.length ? closeDelayMs : fallbackDelayMs, 0.5),
656
+ 0
657
+ ),
658
+ notes
659
+ };
660
+ };
661
+ var buildExecutionCalibrationReport = ({
662
+ runtimeArtifact,
663
+ replayEvidenceArtifact,
664
+ sourcePaths = {},
665
+ nowMs = Date.now()
666
+ }) => {
667
+ const runtimePayload2 = getRuntimePayload({
668
+ runtimeArtifact,
669
+ replayEvidenceArtifact
670
+ });
671
+ const runtimeRows = extractRuntimeTradeRows(runtimePayload2);
672
+ const replayMatches = extractReplayMatches(replayEvidenceArtifact);
673
+ const replayMaps = buildReplayMatchMaps(replayMatches);
674
+ const usedReplayMatches = /* @__PURE__ */ new Set();
675
+ const samples = runtimeRows.map((row) => {
676
+ const orderId = finiteString(row.trade.orderId);
677
+ const signalId = finiteString(row.trade.signalId);
678
+ const match = (orderId ? replayMaps.byOrderId.get(orderId) ?? null : null) ?? (signalId ? replayMaps.bySignalId.get(signalId) ?? null : null);
679
+ if (match) {
680
+ usedReplayMatches.add(match);
681
+ }
682
+ return buildSample({ row, match });
683
+ });
684
+ const replayOnlySamples = replayMatches.filter((match) => !usedReplayMatches.has(match)).map(buildReplayOnlySample);
685
+ return {
686
+ reportType: "execution-calibration",
687
+ generatedAt: nowMs,
688
+ sources: sourcePaths,
689
+ currentModel: {
690
+ baseSlippageBps: import_constants.BACKTEST_BASE_SLIPPAGE_BPS,
691
+ spreadMultiplier: import_constants.BACKTEST_SPREAD_SLIPPAGE_MULTIPLIER,
692
+ marketImpactBps: import_constants.BACKTEST_MARKET_IMPACT_BPS
693
+ },
694
+ counts: {
695
+ runtimeTrades: runtimeRows.length,
696
+ telemetryTrades: samples.filter(hasTelemetry).length,
697
+ fullTelemetryTrades: samples.filter(hasFullTelemetry).length,
698
+ replayMatched: replayMatches.length,
699
+ replayMatchedRuntimeTrades: usedReplayMatches.size,
700
+ replayOnlyMatches: replayOnlySamples.length
701
+ },
702
+ summary: {
703
+ all: buildGroupSummary([...samples, ...replayOnlySamples]),
704
+ byStrategy: groupSamples(
705
+ [...samples, ...replayOnlySamples],
706
+ (sample) => sample.strategy
707
+ ),
708
+ bySymbol: groupSamples(samples, (sample) => sample.symbol),
709
+ byInterval: groupSamples(samples, (sample) => sample.interval),
710
+ byTelemetryQuality: groupSamples(
711
+ [...samples, ...replayOnlySamples],
712
+ (sample) => sample.telemetryQuality
713
+ ),
714
+ byFillSource: groupSamples(
715
+ [...samples, ...replayOnlySamples],
716
+ (sample) => sample.fillSource
717
+ ),
718
+ byLatencyBucket: groupSamples(samples, toLatencyBucket),
719
+ bySpreadBucket: groupSamples(samples, toSpreadBucket)
720
+ },
721
+ recommendation: buildRecommendation(samples),
722
+ samples,
723
+ replayOnlySamples
724
+ };
725
+ };
726
+
727
+ // src/lib/runtimeLineage.ts
728
+ var import_node_crypto = require("crypto");
729
+ var normalizeForStableJson = (value) => {
730
+ if (Array.isArray(value)) {
731
+ return value.map(normalizeForStableJson);
732
+ }
733
+ if (value && typeof value === "object") {
734
+ return Object.fromEntries(
735
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, normalizeForStableJson(entry)])
736
+ );
737
+ }
738
+ return value;
739
+ };
740
+ var fingerprintRuntimeValue = (value) => (0, import_node_crypto.createHash)("sha256").update(JSON.stringify(normalizeForStableJson(value))).digest("hex").slice(0, 16);
741
+ var runtimeLineageKey = (lineage) => [
742
+ "v3",
743
+ lineage.deploymentCompositionId,
744
+ lineage.strategyRevision,
745
+ lineage.strategyPackageVersion,
746
+ `deps:${fingerprintRuntimeValue(lineage.strategyDependencyVersions).slice(0, 16)}`,
747
+ lineage.runtimePackageVersion
748
+ ].join(":");
749
+
750
+ // src/lib/runtimeEvidenceDeployment.ts
751
+ var runtimeEvidenceDeployment_exports = {};
752
+ __reExport(runtimeEvidenceDeployment_exports, require("@tradejs/node/diagnostics"));
753
+
754
+ // src/lib/runtimeScorecard.ts
755
+ var asRecord2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
756
+ var asArray2 = (value) => Array.isArray(value) ? value : [];
757
+ var finiteNumber2 = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
758
+ var finiteString2 = (value) => typeof value === "string" && value.trim() ? value.trim() : null;
759
+ var packageVersionMap = (value) => {
760
+ const record = asRecord2(value);
761
+ if (!record || Object.keys(record).length === 0) return null;
762
+ const entries = Object.entries(record);
763
+ if (entries.some(
764
+ ([name, version]) => !name.startsWith("@tradejs/") || finiteString2(version) == null
765
+ )) {
766
+ return null;
767
+ }
768
+ return Object.fromEntries(
769
+ entries.map(([name, version]) => [name, String(version).trim()]).sort(([left], [right]) => left.localeCompare(right))
770
+ );
771
+ };
772
+ var round = (value, decimals = 6) => Number(value.toFixed(decimals));
773
+ var unwrapRows = (value, key) => asArray2(value).map((item) => asRecord2(asRecord2(item)?.[key]) ?? asRecord2(item)).filter((item) => item != null);
774
+ var runtimePayload = (artifact) => {
775
+ const root = asRecord2(artifact) ?? {};
776
+ return asRecord2(root.runtime) ?? root;
777
+ };
778
+ var runtimeWindow = (artifact) => {
779
+ const root = asRecord2(artifact) ?? {};
780
+ return asRecord2(root.window) ?? asRecord2(runtimePayload(artifact).window) ?? {};
781
+ };
782
+ var extractRuntimeRows = (artifact) => {
783
+ const runtime = runtimePayload(artifact);
784
+ return {
785
+ evaluations: unwrapRows(runtime.evaluations, "evaluation"),
786
+ signals: unwrapRows(runtime.signals, "signal"),
787
+ trades: unwrapRows(runtime.trades, "trade"),
788
+ lineageScopes: unwrapRows(runtime.lineageScopes, "lineageScope")
789
+ };
790
+ };
791
+ var buildEmbeddedLineageScope = ({
792
+ artifact,
793
+ rows,
794
+ strategy
795
+ }) => {
796
+ const deployment = asRecord2(asRecord2(artifact)?.deployment);
797
+ if (finiteNumber2(deployment?.schemaVersion) !== 2) return null;
798
+ const deploymentId = finiteString2(deployment?.id);
799
+ const accountId = finiteString2(deployment?.accountId);
800
+ const deploymentCompositionId = finiteString2(
801
+ deployment?.deploymentCompositionId
802
+ );
803
+ if (!deploymentId || !accountId || !deploymentCompositionId) return null;
804
+ const snapshots = asArray2(deployment?.strategies).map(asRecord2).filter((item) => item != null).filter((item) => item.enabled === true).filter(
805
+ (item) => !strategy || finiteString2(item.strategyName) === strategy
806
+ );
807
+ const targetSeeds = snapshots.map((snapshot) => {
808
+ const strategyName = finiteString2(snapshot.strategyName);
809
+ const strategyRevision = finiteString2(snapshot.strategyRevision);
810
+ const strategyPackageVersion = finiteString2(
811
+ snapshot.strategyPackageVersion
812
+ );
813
+ const strategyDependencyVersions = packageVersionMap(
814
+ snapshot.strategyDependencyVersions
815
+ );
816
+ const runtimePackageVersion = finiteString2(
817
+ snapshot.runtimePackageVersion
818
+ );
819
+ return strategyName && strategyRevision && strategyPackageVersion && strategyDependencyVersions && runtimePackageVersion ? {
820
+ strategyName,
821
+ strategyRevision,
822
+ deploymentCompositionId,
823
+ strategyPackageVersion,
824
+ strategyDependencyVersions,
825
+ runtimePackageVersion
826
+ } : null;
827
+ }).filter((item) => item != null);
828
+ if (targetSeeds.length !== snapshots.length || targetSeeds.length === 0) {
829
+ return null;
830
+ }
831
+ const lineageRows = [
832
+ ...rows.evaluations,
833
+ ...rows.signals,
834
+ ...rows.trades,
835
+ ...rows.lineageScopes.map((scope) => ({
836
+ strategy: scope.strategy,
837
+ deploymentId: scope.deploymentId,
838
+ accountId: scope.accountId,
839
+ runtimeLineage: scope.lineage
840
+ }))
841
+ ];
842
+ const identityMatches = (lineage, target) => finiteNumber2(lineage?.schemaVersion) === 3 && finiteString2(lineage?.strategyRevision) === target.strategyRevision && finiteString2(lineage?.deploymentCompositionId) === target.deploymentCompositionId && finiteString2(lineage?.strategyPackageVersion) === target.strategyPackageVersion && JSON.stringify(packageVersionMap(lineage?.strategyDependencyVersions)) === JSON.stringify(target.strategyDependencyVersions) && finiteString2(lineage?.runtimePackageVersion) === target.runtimePackageVersion;
843
+ const targets = /* @__PURE__ */ new Map();
844
+ for (const seed of targetSeeds) {
845
+ const matchingRows = lineageRows.filter(
846
+ (row) => finiteString2(row.strategy) === seed.strategyName && finiteString2(row.deploymentId) === deploymentId && finiteString2(row.accountId) === accountId && identityMatches(asRecord2(row.runtimeLineage), seed)
847
+ );
848
+ const riskValues = new Set(
849
+ matchingRows.map((row) => finiteNumber2(asRecord2(row.runtimeLineage)?.maxLossValue)).filter((value) => value != null)
850
+ );
851
+ targets.set(seed.strategyName, {
852
+ ...seed,
853
+ maxLossValue: riskValues.size === 1 ? [...riskValues][0] : null,
854
+ rowsWithLineage: matchingRows.length,
855
+ riskConflict: riskValues.size > 1
856
+ });
857
+ }
858
+ const belongs = (row) => {
859
+ const strategyName = finiteString2(row.strategy);
860
+ const target = strategyName ? targets.get(strategyName) : null;
861
+ const lineage = asRecord2(row.runtimeLineage);
862
+ return Boolean(
863
+ target && target.maxLossValue != null && identityMatches(lineage, target) && finiteNumber2(lineage?.maxLossValue) === target.maxLossValue
864
+ );
865
+ };
866
+ const targetValues = [...targets.values()];
867
+ const coverageComplete = targetValues.every(
868
+ (target) => target.rowsWithLineage > 0 && target.maxLossValue != null
869
+ );
870
+ const commonRiskValues = new Set(
871
+ targetValues.map((target) => target.maxLossValue).filter((value) => value != null)
872
+ );
873
+ const singleTarget = targetValues.length === 1 ? targetValues[0] : null;
874
+ const singleLineage = singleTarget?.maxLossValue != null ? {
875
+ schemaVersion: 3,
876
+ strategyRevision: singleTarget.strategyRevision,
877
+ deploymentCompositionId: singleTarget.deploymentCompositionId,
878
+ strategyPackageVersion: singleTarget.strategyPackageVersion,
879
+ strategyDependencyVersions: singleTarget.strategyDependencyVersions,
880
+ runtimePackageVersion: singleTarget.runtimePackageVersion,
881
+ maxLossValue: singleTarget.maxLossValue
882
+ } : null;
883
+ return {
884
+ belongs,
885
+ summary: {
886
+ complete: coverageComplete,
887
+ identityComplete: true,
888
+ coverageComplete,
889
+ conflicts: targetValues.some((target) => target.riskConflict),
890
+ rows: lineageRows.length,
891
+ rowsWithLineage: targetValues.reduce(
892
+ (total, target) => total + target.rowsWithLineage,
893
+ 0
894
+ ),
895
+ schemaVersion: 3,
896
+ lineageKey: singleLineage ? runtimeLineageKey(singleLineage) : null,
897
+ strategyRevision: singleTarget?.strategyRevision ?? null,
898
+ deploymentCompositionId,
899
+ strategyPackageVersion: singleTarget?.strategyPackageVersion ?? null,
900
+ strategyDependencyVersions: singleTarget?.strategyDependencyVersions ?? null,
901
+ runtimePackageVersion: singleTarget?.runtimePackageVersion ?? null,
902
+ maxLossValue: commonRiskValues.size === 1 ? [...commonRiskValues][0] : null,
903
+ strategyScopes: Object.fromEntries(
904
+ targetValues.map((target) => [
905
+ target.strategyName,
906
+ {
907
+ strategyRevision: target.strategyRevision,
908
+ rowsWithLineage: target.rowsWithLineage,
909
+ maxLossValue: target.maxLossValue,
910
+ complete: target.rowsWithLineage > 0 && target.maxLossValue != null
911
+ }
912
+ ])
913
+ )
914
+ }
915
+ };
916
+ };
917
+ var runtimeDeploymentBinding = (artifact) => {
918
+ const deployment = asRecord2(asRecord2(artifact)?.deployment);
919
+ return {
920
+ deploymentId: finiteString2(deployment?.id),
921
+ accountId: finiteString2(deployment?.accountId)
922
+ };
923
+ };
924
+ var belongsToRuntimeDeployment = (row, binding) => binding.deploymentId == null && binding.accountId == null ? true : finiteString2(row.deploymentId) === binding.deploymentId && finiteString2(row.accountId) === binding.accountId;
925
+ var belongsToStrategy = (row, strategy) => strategy == null || finiteString2(row.strategy) === strategy;
926
+ var filterArtifactByStrategy = (artifact, strategy) => {
927
+ if (!strategy) return artifact;
928
+ const root = asRecord2(artifact) ?? {};
929
+ const runtime = runtimePayload(artifact);
930
+ return {
931
+ ...root,
932
+ runtime: {
933
+ ...runtime,
934
+ evaluations: asArray2(runtime.evaluations).filter(
935
+ (item) => belongsToStrategy(
936
+ asRecord2(asRecord2(item)?.evaluation) ?? asRecord2(item) ?? {},
937
+ strategy
938
+ )
939
+ ),
940
+ signals: asArray2(runtime.signals).filter(
941
+ (item) => belongsToStrategy(
942
+ asRecord2(asRecord2(item)?.signal) ?? asRecord2(item) ?? {},
943
+ strategy
944
+ )
945
+ ),
946
+ trades: asArray2(runtime.trades).filter(
947
+ (item) => belongsToStrategy(
948
+ asRecord2(asRecord2(item)?.trade) ?? asRecord2(item) ?? {},
949
+ strategy
950
+ )
951
+ ),
952
+ lineageScopes: asArray2(runtime.lineageScopes).filter(
953
+ (item) => belongsToStrategy(asRecord2(item) ?? {}, strategy)
954
+ )
955
+ }
956
+ };
957
+ };
958
+ var countBy2 = (items, getter) => {
959
+ const counts = {};
960
+ for (const item of items) {
961
+ const key = getter(item);
962
+ if (!key) continue;
963
+ counts[key] = (counts[key] ?? 0) + 1;
964
+ }
965
+ return Object.fromEntries(
966
+ Object.entries(counts).sort(([left], [right]) => left.localeCompare(right))
967
+ );
968
+ };
969
+ var resolveGateDecision = (evaluation) => {
970
+ const analysis = asRecord2(evaluation.aiAnalysis);
971
+ const explicit = finiteString2(analysis?.gateDecision);
972
+ if (explicit === "approved" || explicit === "rejected") {
973
+ return { decision: explicit, source: "gate_decision" };
974
+ }
975
+ if (typeof analysis?.approved === "boolean") {
976
+ return {
977
+ decision: analysis.approved ? "approved" : "rejected",
978
+ source: "legacy_approved_fallback"
979
+ };
980
+ }
981
+ return null;
982
+ };
983
+ var buildDistributions = ({
984
+ evaluations,
985
+ signals
986
+ }) => {
987
+ const candidates = evaluations.filter(
988
+ (evaluation) => evaluation.status === "signal"
989
+ );
990
+ return {
991
+ candidatesByStrategy: countBy2(
992
+ candidates,
993
+ (evaluation) => finiteString2(evaluation.strategy)
994
+ ),
995
+ orderStatus: countBy2(signals, (signal) => finiteString2(signal.orderStatus)),
996
+ skipReasons: countBy2(
997
+ signals,
998
+ (signal) => finiteString2(signal.orderSkipReason)
999
+ ),
1000
+ aiQuality: countBy2(candidates, (evaluation) => {
1001
+ const quality = finiteNumber2(asRecord2(evaluation.aiAnalysis)?.quality);
1002
+ return quality == null ? null : String(quality);
1003
+ })
1004
+ };
1005
+ };
1006
+ var buildDistributionDelta = (current, previous) => {
1007
+ const currentTotal = Object.values(current).reduce(
1008
+ (total, value) => total + value,
1009
+ 0
1010
+ );
1011
+ const previousTotal = Object.values(previous).reduce(
1012
+ (total, value) => total + value,
1013
+ 0
1014
+ );
1015
+ const keys = [
1016
+ .../* @__PURE__ */ new Set([...Object.keys(current), ...Object.keys(previous)])
1017
+ ].sort((left, right) => left.localeCompare(right));
1018
+ return Object.fromEntries(
1019
+ keys.map((key) => {
1020
+ const currentCount = current[key] ?? 0;
1021
+ const previousCount = previous[key] ?? 0;
1022
+ const currentShare = currentTotal > 0 ? currentCount / currentTotal : 0;
1023
+ const previousShare = previousTotal > 0 ? previousCount / previousTotal : 0;
1024
+ return [
1025
+ key,
1026
+ {
1027
+ currentCount,
1028
+ previousCount,
1029
+ currentShare: round(currentShare),
1030
+ previousShare: round(previousShare),
1031
+ shareDelta: round(currentShare - previousShare)
1032
+ }
1033
+ ];
1034
+ })
1035
+ );
1036
+ };
1037
+ var sum = (values) => round(values.reduce((total, value) => total + (value ?? 0), 0));
1038
+ var tradeTimestamp = (trade) => finiteNumber2(trade.exitTimestamp) ?? finiteNumber2(trade.lastSyncedAt) ?? finiteNumber2(trade.entryTimestamp) ?? 0;
1039
+ var dedupeTrades = (artifacts) => {
1040
+ const tradesByOrderId = /* @__PURE__ */ new Map();
1041
+ for (const artifact of artifacts) {
1042
+ for (const trade of extractRuntimeRows(artifact).trades) {
1043
+ const orderId = finiteString2(trade.orderId);
1044
+ if (!orderId) continue;
1045
+ const existing = tradesByOrderId.get(orderId);
1046
+ if (!existing || tradeTimestamp(trade) >= tradeTimestamp(existing)) {
1047
+ tradesByOrderId.set(orderId, trade);
1048
+ }
1049
+ }
1050
+ }
1051
+ return [...tradesByOrderId.values()];
1052
+ };
1053
+ var maxDrawdown = (trades) => {
1054
+ let cumulative = 0;
1055
+ let peak = 0;
1056
+ let drawdown = 0;
1057
+ for (const trade of trades.sort(
1058
+ (left, right) => tradeTimestamp(left) - tradeTimestamp(right)
1059
+ )) {
1060
+ cumulative += finiteNumber2(trade.closedPnl) ?? 0;
1061
+ peak = Math.max(peak, cumulative);
1062
+ drawdown = Math.max(drawdown, peak - cumulative);
1063
+ }
1064
+ return round(drawdown);
1065
+ };
1066
+ var buildRollingPerformance = ({
1067
+ trades,
1068
+ anchorTime,
1069
+ days
1070
+ }) => {
1071
+ const startTime = anchorTime - days * 24 * 60 * 60 * 1e3;
1072
+ const closed = trades.filter((trade) => {
1073
+ const exitTimestamp = finiteNumber2(trade.exitTimestamp);
1074
+ return trade.status === "closed" && exitTimestamp != null && exitTimestamp >= startTime && exitTimestamp < anchorTime;
1075
+ });
1076
+ const realizedPnl = sum(closed.map((trade) => finiteNumber2(trade.closedPnl)));
1077
+ return {
1078
+ days,
1079
+ closedTrades: closed.length,
1080
+ realizedPnl,
1081
+ expectancy: closed.length > 0 ? round(realizedPnl / closed.length) : null,
1082
+ maxDrawdown: maxDrawdown(closed)
1083
+ };
1084
+ };
1085
+ var getReplayComparison = (artifact) => {
1086
+ const root = asRecord2(artifact) ?? {};
1087
+ return asRecord2(asRecord2(root.replay)?.runtimeComparison) ?? null;
1088
+ };
1089
+ var replayCountsForStrategy = (replayComparison, strategy) => {
1090
+ if (strategy) {
1091
+ const byStrategy = asRecord2(replayComparison?.byStrategy);
1092
+ const strategyCounts = asRecord2(byStrategy?.[strategy]);
1093
+ if (strategyCounts) {
1094
+ return {
1095
+ matched: finiteNumber2(strategyCounts.matched) ?? 0,
1096
+ backtestOnly: finiteNumber2(strategyCounts.backtestOnly) ?? 0,
1097
+ runtimeOnly: finiteNumber2(strategyCounts.runtimeOnly) ?? 0
1098
+ };
1099
+ }
1100
+ }
1101
+ const counts = asRecord2(replayComparison?.counts);
1102
+ return {
1103
+ matched: finiteNumber2(counts?.matched) ?? 0,
1104
+ backtestOnly: finiteNumber2(counts?.backtestOnly) ?? 0,
1105
+ runtimeOnly: finiteNumber2(counts?.runtimeOnly) ?? 0
1106
+ };
1107
+ };
1108
+ var getProspectiveSummary = (artifact) => {
1109
+ const root = asRecord2(artifact);
1110
+ if (!root || root.reportType !== "strategy-prospective-evidence") return null;
1111
+ return {
1112
+ rawCoreExpectancy: finiteNumber2(root.rawCoreExpectancy),
1113
+ aiGateExpectancy: finiteNumber2(root.aiGateExpectancy),
1114
+ regimeCoverage: finiteNumber2(root.regimeCoverage)
1115
+ };
1116
+ };
1117
+ var buildRuntimeScorecard = ({
1118
+ runtimeArtifact,
1119
+ replayEvidenceArtifact,
1120
+ calibrationArtifact,
1121
+ prospectiveEvidenceArtifact,
1122
+ historyRuntimeArtifacts = [],
1123
+ thresholds = {
1124
+ minimumParityRatio: 0.95,
1125
+ maximumSlippageResidualBps: 3,
1126
+ minimumClosedTrades: 20,
1127
+ minimumExpectancy: 0
1128
+ },
1129
+ generatedAt = Date.now(),
1130
+ strategy = null,
1131
+ llmComparatorPolicy = "ai_approved_only"
1132
+ }) => {
1133
+ (0, runtimeEvidenceDeployment_exports.assertCurrentRuntimeEvidenceArtifact)(runtimeArtifact);
1134
+ for (const artifact of historyRuntimeArtifacts) {
1135
+ (0, runtimeEvidenceDeployment_exports.assertCurrentRuntimeEvidenceArtifact)(artifact);
1136
+ }
1137
+ const scopedRuntimeArtifact = filterArtifactByStrategy(
1138
+ runtimeArtifact,
1139
+ strategy
1140
+ );
1141
+ const scopedHistoryArtifacts = historyRuntimeArtifacts.map(
1142
+ (artifact) => filterArtifactByStrategy(artifact, strategy)
1143
+ );
1144
+ const deploymentBinding = runtimeDeploymentBinding(runtimeArtifact);
1145
+ const rows = extractRuntimeRows(scopedRuntimeArtifact);
1146
+ const embeddedLineageScope = buildEmbeddedLineageScope({
1147
+ artifact: runtimeArtifact,
1148
+ rows,
1149
+ strategy
1150
+ });
1151
+ if (!embeddedLineageScope) {
1152
+ throw new Error(
1153
+ "Runtime scorecard requires the current embedded deployment lineage"
1154
+ );
1155
+ }
1156
+ const runtimeLineage = embeddedLineageScope.summary;
1157
+ const window = runtimeWindow(runtimeArtifact);
1158
+ const startTime = finiteNumber2(window.startTime) ?? generatedAt - 864e5;
1159
+ const endTime = finiteNumber2(window.endTime) ?? generatedAt;
1160
+ const signalEvaluations = rows.evaluations.filter(
1161
+ (evaluation) => evaluation.status === "signal"
1162
+ );
1163
+ const gateDecisions = signalEvaluations.map(resolveGateDecision).filter(
1164
+ (decision) => Boolean(decision)
1165
+ );
1166
+ const llmEligibleEvaluations = llmComparatorPolicy === "disabled" ? [] : llmComparatorPolicy === "ai_approved_only" ? signalEvaluations.filter(
1167
+ (evaluation) => resolveGateDecision(evaluation)?.decision === "approved"
1168
+ ) : signalEvaluations;
1169
+ const gateComparisons = llmEligibleEvaluations.map((evaluation) => {
1170
+ const analysis = asRecord2(evaluation.aiAnalysis);
1171
+ const gateDecision = resolveGateDecision(evaluation)?.decision ?? null;
1172
+ const llmDecision = finiteString2(analysis?.llmDecision);
1173
+ if (gateDecision !== "approved" && gateDecision !== "rejected" || llmDecision !== "approved" && llmDecision !== "rejected") {
1174
+ return null;
1175
+ }
1176
+ return { gateDecision, llmDecision };
1177
+ }).filter(
1178
+ (comparison) => Boolean(comparison)
1179
+ );
1180
+ const allocatorDecisions = signalEvaluations.map((evaluation) => asRecord2(evaluation.allocatorDecision)).filter((item) => item != null);
1181
+ const riskDecisions = signalEvaluations.map((evaluation) => asRecord2(evaluation.riskDecision)).filter((item) => item != null);
1182
+ const orderAttempts = rows.signals.filter(
1183
+ (signal) => signal.orderStatus === "completed" || signal.orderStatus === "failed"
1184
+ );
1185
+ const currentClosedTrades = rows.trades.filter((trade) => {
1186
+ const exitTimestamp = finiteNumber2(trade.exitTimestamp);
1187
+ return trade.status === "closed" && exitTimestamp != null && exitTimestamp >= startTime && exitTimestamp < endTime;
1188
+ });
1189
+ const replayComparison = getReplayComparison(replayEvidenceArtifact);
1190
+ const replayCounts = replayCountsForStrategy(replayComparison, strategy);
1191
+ const matched = replayCounts.matched;
1192
+ const backtestOnly = replayCounts.backtestOnly;
1193
+ const runtimeOnly = replayCounts.runtimeOnly;
1194
+ const comparisonTotal = matched + backtestOnly + runtimeOnly;
1195
+ const parityRatio = comparisonTotal > 0 ? matched / comparisonTotal : null;
1196
+ const lineage = asRecord2(replayComparison?.lineage);
1197
+ const lineageReason = finiteString2(lineage?.reason);
1198
+ const calibrationRoot = asRecord2(calibrationArtifact) ?? {};
1199
+ const calibrationSamples = asArray2(calibrationRoot.samples).map(asRecord2).filter((item) => item != null).filter((item) => !strategy || finiteString2(item.strategy) === strategy).filter((item) => embeddedLineageScope.belongs(item));
1200
+ const averageSampleMetric = (field) => {
1201
+ const values = calibrationSamples.map((sample) => finiteNumber2(sample[field])).filter((value) => value != null);
1202
+ return values.length ? round(sum(values) / values.length) : null;
1203
+ };
1204
+ const actualSlippageBps = averageSampleMetric("signalToFillAdverseBps");
1205
+ const residualVsModelBps = averageSampleMetric("residualVsCurrentModelBps");
1206
+ const signalToArrivalAdverseBps = averageSampleMetric(
1207
+ "signalToArrivalAdverseBps"
1208
+ );
1209
+ const arrivalToFillAdverseBps = averageSampleMetric(
1210
+ "arrivalToFillAdverseBps"
1211
+ );
1212
+ const averageSignalCloseToSubmitMs = averageSampleMetric(
1213
+ "signalCloseToSubmitMs"
1214
+ );
1215
+ const averageSubmitToFillMs = averageSampleMetric("submitToFillMs");
1216
+ const fullTelemetryTrades = calibrationSamples.filter(
1217
+ (sample) => finiteString2(sample.telemetryQuality) === "full"
1218
+ ).length;
1219
+ const arrivalQuoteTrades = calibrationSamples.filter(
1220
+ (sample) => finiteNumber2(sample.arrivalMid) != null
1221
+ ).length;
1222
+ const arrivalQuoteCoverage = calibrationSamples.length ? round(arrivalQuoteTrades / calibrationSamples.length) : null;
1223
+ const hasTelemetryQuality = calibrationSamples.some(
1224
+ (sample) => finiteString2(sample.telemetryQuality) != null
1225
+ );
1226
+ const maximumSignalCloseToSubmitMs = thresholds.maximumSignalCloseToSubmitMs ?? 3e4;
1227
+ const prospective = getProspectiveSummary(prospectiveEvidenceArtifact);
1228
+ const historyTrades = dedupeTrades([
1229
+ ...scopedHistoryArtifacts,
1230
+ scopedRuntimeArtifact
1231
+ ]);
1232
+ const comparableHistoryTrades = historyTrades.filter(
1233
+ (trade) => belongsToRuntimeDeployment(trade, deploymentBinding) && embeddedLineageScope.belongs(trade)
1234
+ );
1235
+ const comparableCurrentClosedTrades = currentClosedTrades.filter(
1236
+ (trade) => belongsToRuntimeDeployment(trade, deploymentBinding) && embeddedLineageScope.belongs(trade)
1237
+ );
1238
+ const comparableFills = rows.trades.filter(
1239
+ (trade) => belongsToRuntimeDeployment(trade, deploymentBinding) && embeddedLineageScope.belongs(trade)
1240
+ );
1241
+ const currentDistributions = buildDistributions(rows);
1242
+ const previousArtifact = scopedHistoryArtifacts.map((artifact) => ({ artifact, window: runtimeWindow(artifact) })).filter(({ window: candidateWindow }) => {
1243
+ const candidateEndTime = finiteNumber2(candidateWindow.endTime);
1244
+ return candidateEndTime != null && candidateEndTime <= startTime;
1245
+ }).sort(
1246
+ (left, right) => (finiteNumber2(right.window.endTime) ?? 0) - (finiteNumber2(left.window.endTime) ?? 0)
1247
+ )[0];
1248
+ const previousDistributions = previousArtifact ? buildDistributions(extractRuntimeRows(previousArtifact.artifact)) : null;
1249
+ const rolling = [7, 30, 90].map(
1250
+ (days) => buildRollingPerformance({
1251
+ trades: [...comparableHistoryTrades],
1252
+ anchorTime: endTime,
1253
+ days
1254
+ })
1255
+ );
1256
+ const sevenDay = rolling[0];
1257
+ const reactions = [];
1258
+ if (lineageReason) {
1259
+ reactions.push({
1260
+ code: "LINEAGE_NOT_COMPARABLE",
1261
+ severity: "blocking",
1262
+ message: lineageReason
1263
+ });
1264
+ }
1265
+ if (!runtimeLineage.complete) {
1266
+ reactions.push({
1267
+ code: "RUNTIME_LINEAGE_INCOMPLETE",
1268
+ severity: "blocking",
1269
+ message: "Runtime rows do not share one complete composition lineage."
1270
+ });
1271
+ }
1272
+ if (parityRatio != null && parityRatio < thresholds.minimumParityRatio) {
1273
+ reactions.push({
1274
+ code: "PARITY_REGRESSION",
1275
+ severity: "blocking",
1276
+ message: `Parity ${round(parityRatio * 100, 2)}% is below ${round(thresholds.minimumParityRatio * 100, 2)}%.`
1277
+ });
1278
+ }
1279
+ if (residualVsModelBps != null && residualVsModelBps > thresholds.maximumSlippageResidualBps) {
1280
+ reactions.push({
1281
+ code: "SLIPPAGE_DRIFT",
1282
+ severity: "warning",
1283
+ message: `Signal-close-to-fill residual ${round(residualVsModelBps, 2)} bps exceeds ${thresholds.maximumSlippageResidualBps} bps.`
1284
+ });
1285
+ }
1286
+ if (averageSignalCloseToSubmitMs != null && averageSignalCloseToSubmitMs > maximumSignalCloseToSubmitMs) {
1287
+ reactions.push({
1288
+ code: "PRE_SUBMIT_LATENCY",
1289
+ severity: "warning",
1290
+ message: `Average signal-close-to-submit latency ${round(averageSignalCloseToSubmitMs, 3)} ms exceeds ${maximumSignalCloseToSubmitMs} ms.`
1291
+ });
1292
+ }
1293
+ if (hasTelemetryQuality && calibrationSamples.length > 0 && fullTelemetryTrades < calibrationSamples.length) {
1294
+ reactions.push({
1295
+ code: "EXECUTION_TELEMETRY_INCOMPLETE",
1296
+ severity: "info",
1297
+ message: `Full arrival and fill telemetry is available for ${fullTelemetryTrades}/${calibrationSamples.length} trades.`
1298
+ });
1299
+ }
1300
+ if (riskDecisions.some((decision) => decision.status === "rejected")) {
1301
+ reactions.push({
1302
+ code: "RISK_PLAN_EXCEEDS_DECLARED_LIMIT",
1303
+ severity: "warning",
1304
+ message: "At least one observed order plan exceeds its declared MAX_LOSS_VALUE; telemetry is not yet enforced."
1305
+ });
1306
+ }
1307
+ if (sevenDay.closedTrades >= thresholds.minimumClosedTrades && sevenDay.expectancy != null && sevenDay.expectancy < thresholds.minimumExpectancy) {
1308
+ reactions.push({
1309
+ code: "EXPECTANCY_DEGRADATION",
1310
+ severity: "blocking",
1311
+ message: `7d expectancy ${sevenDay.expectancy} is below ${thresholds.minimumExpectancy}.`
1312
+ });
1313
+ }
1314
+ if (sevenDay.closedTrades < thresholds.minimumClosedTrades) {
1315
+ reactions.push({
1316
+ code: "INSUFFICIENT_RECENT_SAMPLE",
1317
+ severity: "info",
1318
+ message: `Only ${sevenDay.closedTrades} closed trades in 7d; ${thresholds.minimumClosedTrades} required for expectancy reaction.`
1319
+ });
1320
+ }
1321
+ const promotionStatus = reactions.some(
1322
+ (reaction) => reaction.severity === "blocking"
1323
+ ) ? "PROMOTION_BLOCKED" : reactions.some((reaction) => reaction.severity === "warning") ? "REVIEW_REQUIRED" : "OBSERVE";
1324
+ return {
1325
+ reportType: "runtime-scorecard",
1326
+ schemaVersion: 1,
1327
+ generatedAt,
1328
+ window: { startTime, endTime },
1329
+ strategy,
1330
+ deployment: deploymentBinding,
1331
+ lineage: runtimeLineage,
1332
+ promotionStatus,
1333
+ thresholds: {
1334
+ ...thresholds,
1335
+ maximumSignalCloseToSubmitMs
1336
+ },
1337
+ funnel: {
1338
+ evaluations: rows.evaluations.length,
1339
+ coreCandidates: signalEvaluations.length,
1340
+ gate: {
1341
+ available: gateDecisions.length > 0,
1342
+ approved: gateDecisions.filter(
1343
+ ({ decision }) => decision === "approved"
1344
+ ).length,
1345
+ rejected: gateDecisions.filter(
1346
+ ({ decision }) => decision === "rejected"
1347
+ ).length,
1348
+ coverage: signalEvaluations.length ? round(gateDecisions.length / signalEvaluations.length) : null,
1349
+ legacyApprovedFallback: gateDecisions.filter(
1350
+ ({ source }) => source === "legacy_approved_fallback"
1351
+ ).length
1352
+ },
1353
+ allocator: {
1354
+ available: allocatorDecisions.length > 0,
1355
+ approved: allocatorDecisions.filter(
1356
+ (decision) => decision.status === "approved"
1357
+ ).length,
1358
+ rejected: allocatorDecisions.filter(
1359
+ (decision) => decision.status === "rejected"
1360
+ ).length,
1361
+ notApplicable: allocatorDecisions.filter(
1362
+ (decision) => decision.status === "not_applicable"
1363
+ ).length,
1364
+ unavailable: allocatorDecisions.filter(
1365
+ (decision) => decision.status === "unavailable"
1366
+ ).length
1367
+ },
1368
+ risk: {
1369
+ available: riskDecisions.length > 0,
1370
+ approved: riskDecisions.filter(
1371
+ (decision) => decision.status === "approved"
1372
+ ).length,
1373
+ rejected: riskDecisions.filter(
1374
+ (decision) => decision.status === "rejected"
1375
+ ).length,
1376
+ unavailable: riskDecisions.filter(
1377
+ (decision) => decision.status === "unavailable"
1378
+ ).length,
1379
+ enforced: riskDecisions.some((decision) => decision.enforced === true)
1380
+ },
1381
+ orderAttempts: orderAttempts.length,
1382
+ orderFailures: orderAttempts.filter(
1383
+ (signal) => signal.orderStatus === "failed"
1384
+ ).length,
1385
+ balanceRejects: rows.signals.filter(
1386
+ (signal) => /BALANCE|MARGIN/i.test(
1387
+ `${finiteString2(signal.orderSkipReason) ?? ""} ${finiteString2(signal.orderFailureReason) ?? ""}`
1388
+ )
1389
+ ).length,
1390
+ fills: comparableFills.length,
1391
+ nonComparableFills: rows.trades.length - comparableFills.length,
1392
+ closedTrades: currentClosedTrades.length,
1393
+ comparableClosedTrades: comparableCurrentClosedTrades.length,
1394
+ nonComparableClosedTrades: currentClosedTrades.length - comparableCurrentClosedTrades.length
1395
+ },
1396
+ realized: {
1397
+ pnl: sum(
1398
+ comparableCurrentClosedTrades.map(
1399
+ (trade) => finiteNumber2(trade.closedPnl)
1400
+ )
1401
+ ),
1402
+ fees: sum(
1403
+ comparableCurrentClosedTrades.map(
1404
+ (trade) => finiteNumber2(trade.totalFee)
1405
+ )
1406
+ ),
1407
+ funding: sum(
1408
+ comparableCurrentClosedTrades.map(
1409
+ (trade) => finiteNumber2(trade.fundingFee)
1410
+ )
1411
+ )
1412
+ },
1413
+ gateComparison: {
1414
+ policy: llmComparatorPolicy,
1415
+ eligible: llmEligibleEvaluations.length,
1416
+ compared: gateComparisons.length,
1417
+ coverage: llmEligibleEvaluations.length ? round(gateComparisons.length / llmEligibleEvaluations.length) : null,
1418
+ agreements: gateComparisons.filter(
1419
+ (comparison) => comparison.gateDecision === comparison.llmDecision
1420
+ ).length,
1421
+ disagreements: gateComparisons.filter(
1422
+ (comparison) => comparison.gateDecision !== comparison.llmDecision
1423
+ ).length,
1424
+ gateApprovedLlmRejected: gateComparisons.filter(
1425
+ (comparison) => comparison.gateDecision === "approved" && comparison.llmDecision === "rejected"
1426
+ ).length,
1427
+ gateRejectedLlmApproved: gateComparisons.filter(
1428
+ (comparison) => comparison.gateDecision === "rejected" && comparison.llmDecision === "approved"
1429
+ ).length
1430
+ },
1431
+ parity: {
1432
+ available: comparisonTotal > 0,
1433
+ matched,
1434
+ backtestOnly,
1435
+ runtimeOnly,
1436
+ ratio: parityRatio == null ? null : round(parityRatio),
1437
+ lineageReason
1438
+ },
1439
+ execution: {
1440
+ available: actualSlippageBps != null || residualVsModelBps != null,
1441
+ metricScope: arrivalToFillAdverseBps == null ? "signal_close_to_fill" : "signal_and_exchange_components",
1442
+ samples: calibrationSamples.length,
1443
+ fullTelemetryTrades,
1444
+ arrivalQuoteCoverage,
1445
+ actualSignalToFillSlippageBps: actualSlippageBps,
1446
+ residualVsCurrentModelBps: residualVsModelBps,
1447
+ signalToArrivalAdverseBps,
1448
+ arrivalToFillAdverseBps,
1449
+ averageSignalCloseToSubmitMs,
1450
+ averageSubmitToFillMs
1451
+ },
1452
+ prospective,
1453
+ rolling,
1454
+ distributions: currentDistributions,
1455
+ distributionChanges: {
1456
+ available: previousDistributions != null,
1457
+ baselineWindow: previousArtifact ? {
1458
+ startTime: finiteNumber2(previousArtifact.window.startTime),
1459
+ endTime: finiteNumber2(previousArtifact.window.endTime)
1460
+ } : null,
1461
+ metrics: previousDistributions ? Object.fromEntries(
1462
+ Object.entries(currentDistributions).map(([name, current]) => [
1463
+ name,
1464
+ buildDistributionDelta(
1465
+ current,
1466
+ previousDistributions[name]
1467
+ )
1468
+ ])
1469
+ ) : {}
1470
+ },
1471
+ reactions
1472
+ };
1473
+ };
1474
+ var formatRuntimeScorecardMarkdown = (scorecard) => {
1475
+ const rollingRows = scorecard.rolling.map(
1476
+ (row) => `| ${row.days}d | ${row.closedTrades} | ${row.realizedPnl} | ${row.expectancy ?? "n/a"} | ${row.maxDrawdown} |`
1477
+ ).join("\n");
1478
+ const reactions = scorecard.reactions.length ? scorecard.reactions.map(
1479
+ (reaction) => `- ${reaction.severity.toUpperCase()} \`${reaction.code}\`: ${reaction.message}`
1480
+ ).join("\n") : "- No automatic reactions.";
1481
+ const distributionChanges = Object.entries(
1482
+ scorecard.distributionChanges.metrics
1483
+ ).flatMap(
1484
+ ([metric, values]) => Object.entries(values).map(([value, change]) => ({
1485
+ metric,
1486
+ value,
1487
+ shareDelta: change.shareDelta
1488
+ }))
1489
+ ).sort(
1490
+ (left, right) => Math.abs(right.shareDelta) - Math.abs(left.shareDelta)
1491
+ ).slice(0, 10).map(
1492
+ (change) => `- ${change.metric}.${change.value}: ${change.shareDelta >= 0 ? "+" : ""}${round(change.shareDelta * 100, 2)} pp`
1493
+ ).join("\n");
1494
+ return `# Runtime scorecard
1495
+
1496
+ Status: **${scorecard.promotionStatus}**
1497
+
1498
+ Window: ${new Date(scorecard.window.startTime).toISOString()} \u2014 ${new Date(scorecard.window.endTime).toISOString()}
1499
+
1500
+ ## Funnel
1501
+
1502
+ - Evaluations: ${scorecard.funnel.evaluations}
1503
+ - Core candidates: ${scorecard.funnel.coreCandidates}
1504
+ - Gate approvals/rejects: ${scorecard.funnel.gate.approved}/${scorecard.funnel.gate.rejected} (legacy fallback: ${scorecard.funnel.gate.legacyApprovedFallback})
1505
+ - AI / LLM disagreement: ${scorecard.gateComparison.disagreements}/${scorecard.gateComparison.compared}
1506
+ - Runtime admission approved/rejected/not-applicable: ${scorecard.funnel.allocator.available ? `${scorecard.funnel.allocator.approved}/${scorecard.funnel.allocator.rejected}/${scorecard.funnel.allocator.notApplicable}` : "unavailable"}
1507
+ - Risk assessment within/exceeds/unavailable: ${scorecard.funnel.risk.available ? `${scorecard.funnel.risk.approved}/${scorecard.funnel.risk.rejected}/${scorecard.funnel.risk.unavailable}` : "unavailable"} (enforced: ${scorecard.funnel.risk.enforced})
1508
+ - Order attempts/failures: ${scorecard.funnel.orderAttempts}/${scorecard.funnel.orderFailures}
1509
+ - Fills: ${scorecard.funnel.fills}
1510
+ - Closed trades: ${scorecard.funnel.closedTrades}
1511
+
1512
+ ## Replay and execution
1513
+
1514
+ - Parity: ${scorecard.parity.ratio == null ? "n/a" : `${round(scorecard.parity.ratio * 100, 2)}%`}
1515
+ - Runtime/replay mismatches: ${scorecard.parity.backtestOnly + scorecard.parity.runtimeOnly}
1516
+ - Execution metric scope: ${scorecard.execution.metricScope}
1517
+ - Telemetry samples/full/arrival coverage: ${scorecard.execution.samples}/${scorecard.execution.fullTelemetryTrades}/${scorecard.execution.arrivalQuoteCoverage == null ? "n/a" : `${round(scorecard.execution.arrivalQuoteCoverage * 100, 2)}%`}
1518
+ - Signal-close-to-fill adverse move: ${scorecard.execution.actualSignalToFillSlippageBps ?? "n/a"} bps
1519
+ - Signal-to-arrival adverse move: ${scorecard.execution.signalToArrivalAdverseBps ?? "n/a"} bps
1520
+ - Arrival-to-fill exchange slippage: ${scorecard.execution.arrivalToFillAdverseBps ?? "n/a"} bps
1521
+ - Residual vs current model: ${scorecard.execution.residualVsCurrentModelBps ?? "n/a"} bps
1522
+ - Average signal-close-to-submit: ${scorecard.execution.averageSignalCloseToSubmitMs ?? "n/a"} ms
1523
+ - Average submit-to-fill: ${scorecard.execution.averageSubmitToFillMs ?? "n/a"} ms
1524
+
1525
+ ## Rolling performance
1526
+
1527
+ | Window | Closed | Realized PnL | Expectancy | Max drawdown |
1528
+ | --- | ---: | ---: | ---: | ---: |
1529
+ ${rollingRows}
1530
+
1531
+ ## Distribution changes
1532
+
1533
+ ${scorecard.distributionChanges.available ? distributionChanges || "- No distribution changes." : "- Previous comparable artifact is unavailable."}
1534
+
1535
+ ## Reactions
1536
+
1537
+ ${reactions}
1538
+ `;
1539
+ };
1540
+
1541
+ // src/lib/runtimeEvidenceSync.ts
1542
+ var import_node_child_process = require("child_process");
1543
+ var import_promises = __toESM(require("fs/promises"));
1544
+ var import_node_path = __toESM(require("path"));
1545
+ var import_node_util = require("util");
1546
+
1547
+ // src/lib/runtimeEvidenceArtifacts.ts
1548
+ var runtimeEvidenceArtifacts_exports = {};
1549
+ __reExport(runtimeEvidenceArtifacts_exports, require("@tradejs/node/diagnostics"));
1550
+
1551
+ // src/lib/runtimeEvidenceSync.ts
1552
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
1553
+ var safeSegment = (value, fallback) => {
1554
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
1555
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
1556
+ };
1557
+ var receiptPath = (receiptsRoot, artifactId) => import_node_path.default.join(receiptsRoot, `${safeSegment(artifactId, "artifact")}.json`);
1558
+ var markRuntimeEvidenceBundleProcessed = async ({
1559
+ evidenceRoot,
1560
+ deploymentId,
1561
+ bundleDir,
1562
+ scorecardPath,
1563
+ runtimeFeedback
1564
+ }) => {
1565
+ const safeDeploymentId = safeSegment(deploymentId, "production");
1566
+ const verified = await (0, runtimeEvidenceArtifacts_exports.verifyRuntimeEvidenceBundle)(bundleDir);
1567
+ if (verified.manifest.deploymentId !== safeDeploymentId) {
1568
+ throw new Error(
1569
+ `Artifact deployment mismatch: expected ${safeDeploymentId}, received ${verified.manifest.deploymentId}`
1570
+ );
1571
+ }
1572
+ const receiptsRoot = import_node_path.default.join(evidenceRoot, "receipts", safeDeploymentId);
1573
+ const finalPath = receiptPath(receiptsRoot, verified.manifest.artifactId);
1574
+ const temporaryPath = `${finalPath}.tmp-${process.pid}`;
1575
+ const receipt = {
1576
+ schemaVersion: runtimeFeedback ? 2 : 1,
1577
+ artifactId: verified.manifest.artifactId,
1578
+ payloadSha256: verified.manifest.payload.sha256,
1579
+ processedAt: Date.now(),
1580
+ scorecardPath: scorecardPath ?? null,
1581
+ ...runtimeFeedback ? {
1582
+ runtimeFeedbackArtifactId: runtimeFeedback.artifactId,
1583
+ replayEvidenceSha256: runtimeFeedback.replayEvidenceSha256
1584
+ } : {}
1585
+ };
1586
+ await import_promises.default.mkdir(receiptsRoot, { recursive: true });
1587
+ await import_promises.default.writeFile(
1588
+ temporaryPath,
1589
+ `${JSON.stringify(receipt, null, 2)}
1590
+ `,
1591
+ "utf8"
1592
+ );
1593
+ await import_promises.default.rename(temporaryPath, finalPath);
1594
+ return finalPath;
1595
+ };
1596
+
1597
+ // src/lib/runtimeFeedbackProcess.ts
1598
+ var processRuntimeFeedbackPair = async ({
1599
+ runtimeDir,
1600
+ replayDir,
1601
+ evidenceRoot,
1602
+ outputRoot,
1603
+ historyDir
1604
+ }) => {
1605
+ const { runtimeEvidence, feedback } = await (0, import_diagnostics.verifyRuntimeFeedbackReplaySource)(
1606
+ { bundleDir: replayDir, runtimeEvidenceBundleDir: runtimeDir }
1607
+ );
1608
+ const { artifactId, deploymentId } = runtimeEvidence.manifest;
1609
+ const snapshot = (0, import_diagnostics.parseRuntimeEvidenceDeploymentSnapshot)(
1610
+ runtimeEvidence.artifact.deployment
1611
+ );
1612
+ if (!snapshot)
1613
+ throw new Error("Runtime evidence requires a deployment snapshot");
1614
+ const strategies = (0, import_diagnostics.activeRuntimeEvidenceStrategies)(snapshot);
1615
+ for (const segment of [
1616
+ artifactId,
1617
+ deploymentId,
1618
+ ...strategies.map((s) => s.strategyName)
1619
+ ]) {
1620
+ if (!/^[A-Za-z0-9._:-]+$/.test(segment) || segment === "." || segment === "..")
1621
+ throw new Error("Invalid feedback output path identity");
1622
+ }
1623
+ const receiptPath2 = import_node_path2.default.join(
1624
+ evidenceRoot,
1625
+ "receipts",
1626
+ deploymentId,
1627
+ `${artifactId}.json`
1628
+ );
1629
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(receiptPath2), { recursive: true });
1630
+ const lock = receiptPath2 + ".processing";
1631
+ await import_promises2.default.mkdir(lock);
1632
+ try {
1633
+ const previous = await import_promises2.default.readFile(receiptPath2, "utf8").catch((error) => {
1634
+ if (error.code !== "ENOENT") throw error;
1635
+ return null;
1636
+ });
1637
+ if (previous) {
1638
+ const receipt = JSON.parse(previous);
1639
+ if (!receipt || typeof receipt !== "object" || !("schemaVersion" in receipt) || receipt.schemaVersion !== 2 || !("payloadSha256" in receipt) || !("runtimeFeedbackArtifactId" in receipt) || !("replayEvidenceSha256" in receipt) || !("scorecardPath" in receipt) || receipt.payloadSha256 !== runtimeEvidence.manifest.payload.sha256 || receipt.runtimeFeedbackArtifactId !== feedback.manifest.artifactId || receipt.replayEvidenceSha256 !== feedback.manifest.payloads.replayEvidence.sha256 || typeof receipt.scorecardPath !== "string")
1640
+ throw new Error("Processing receipt conflicts with the exact pair");
1641
+ await import_promises2.default.access(receipt.scorecardPath);
1642
+ return {
1643
+ processed: false,
1644
+ receiptPath: receiptPath2,
1645
+ scorecardPath: receipt.scorecardPath
1646
+ };
1647
+ }
1648
+ const history = [];
1649
+ if (historyDir)
1650
+ for (const directory of await (0, import_diagnostics.discoverRuntimeEvidenceBundles)(historyDir))
1651
+ history.push((await (0, import_diagnostics.verifyRuntimeEvidenceBundle)(directory)).artifact);
1652
+ const runId = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:.]/g, "") + "-" + (0, import_node_crypto2.randomUUID)();
1653
+ const runDir = import_node_path2.default.join(outputRoot, artifactId, runId);
1654
+ await import_promises2.default.mkdir(runDir, { recursive: true });
1655
+ const calibration = buildExecutionCalibrationReport({
1656
+ runtimeArtifact: runtimeEvidence.artifact,
1657
+ replayEvidenceArtifact: feedback.replayEvidence
1658
+ });
1659
+ await import_promises2.default.writeFile(
1660
+ import_node_path2.default.join(runDir, "execution-calibration.json"),
1661
+ JSON.stringify(calibration, null, 2)
1662
+ );
1663
+ const inputs = {
1664
+ runtimeArtifact: runtimeEvidence.artifact,
1665
+ replayEvidenceArtifact: feedback.replayEvidence,
1666
+ calibrationArtifact: calibration,
1667
+ historyRuntimeArtifacts: history
1668
+ };
1669
+ for (const strategy of [...strategies.map((s) => s.strategyName), null]) {
1670
+ const scorecard = buildRuntimeScorecard({ ...inputs, strategy });
1671
+ const base = import_node_path2.default.join(
1672
+ runDir,
1673
+ strategy ? `runtime-scorecard-${strategy}` : "runtime-scorecard"
1674
+ );
1675
+ await import_promises2.default.writeFile(base + ".json", JSON.stringify(scorecard, null, 2));
1676
+ await import_promises2.default.writeFile(
1677
+ base + ".md",
1678
+ formatRuntimeScorecardMarkdown(scorecard)
1679
+ );
1680
+ }
1681
+ await (0, import_diagnostics.verifyRuntimeFeedbackReplaySource)({
1682
+ bundleDir: replayDir,
1683
+ runtimeEvidenceBundleDir: runtimeDir
1684
+ });
1685
+ const scorecardPath = import_node_path2.default.join(runDir, "runtime-scorecard.json");
1686
+ await markRuntimeEvidenceBundleProcessed({
1687
+ evidenceRoot,
1688
+ deploymentId,
1689
+ bundleDir: runtimeDir,
1690
+ scorecardPath,
1691
+ runtimeFeedback: {
1692
+ artifactId: feedback.manifest.artifactId,
1693
+ replayEvidenceSha256: feedback.manifest.payloads.replayEvidence.sha256
1694
+ }
1695
+ });
1696
+ return { processed: true, receiptPath: receiptPath2, scorecardPath };
1697
+ } finally {
1698
+ await import_promises2.default.rmdir(lock);
1699
+ }
1700
+ };
1701
+
1702
+ // src/scripts/runtimeFeedbackProcess.ts
1703
+ import_args.default.option(
1704
+ "runtimeDir",
1705
+ "Directory containing the complete downloaded runtime evidence bundle"
1706
+ );
1707
+ import_args.default.option(
1708
+ "replayDir",
1709
+ "Directory containing the complete downloaded production replay bundle"
1710
+ );
1711
+ import_args.default.option(
1712
+ "historyDir",
1713
+ "Directory containing verified historical runtime bundles",
1714
+ "data/runtime-evidence/artifacts/production"
1715
+ );
1716
+ var flags = import_args.default.parse(process.argv);
1717
+ var main = async () => {
1718
+ if (!flags.runtimeDir || !flags.replayDir)
1719
+ throw new Error("Provide --runtimeDir and --replayDir");
1720
+ const root = process.env.PROJECT_CWD || process.cwd();
1721
+ console.log(
1722
+ JSON.stringify(
1723
+ await processRuntimeFeedbackPair({
1724
+ runtimeDir: import_node_path3.default.resolve(root, String(flags.runtimeDir)),
1725
+ replayDir: import_node_path3.default.resolve(root, String(flags.replayDir)),
1726
+ evidenceRoot: import_node_path3.default.join(root, "data/runtime-evidence"),
1727
+ outputRoot: import_node_path3.default.join(root, "output/runtime-feedback"),
1728
+ historyDir: import_node_path3.default.resolve(root, String(flags.historyDir))
1729
+ })
1730
+ )
1731
+ );
1732
+ };
1733
+ // Annotate the CommonJS export names for ESM import in node:
1734
+ 0 && (module.exports = {
1735
+ main
1736
+ });