@tradejs/cli 3.1.21 → 3.1.22

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,850 @@
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/scripts/runtimeFeedbackReplay.ts
31
+ var runtimeFeedbackReplay_exports = {};
32
+ __export(runtimeFeedbackReplay_exports, {
33
+ main: () => main,
34
+ runtimeFeedbackReplay: () => runtimeFeedbackReplay
35
+ });
36
+ module.exports = __toCommonJS(runtimeFeedbackReplay_exports);
37
+ var import_node_path5 = __toESM(require("path"));
38
+ var import_args = __toESM(require("args"));
39
+ var import_chalk = __toESM(require("chalk"));
40
+
41
+ // src/lib/runtimeFeedbackReplay.ts
42
+ var import_node_child_process = require("child_process");
43
+ var import_promises4 = __toESM(require("fs/promises"));
44
+ var import_node_path4 = __toESM(require("path"));
45
+
46
+ // src/lib/runtimeEvidenceDeployment.ts
47
+ var import_runtimeStrategies = require("@tradejs/node/runtimeStrategies");
48
+ var isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
49
+ var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
50
+ var isPackageVersionMap = (value) => isRecord(value) && Object.keys(value).length > 0 && Object.entries(value).every(
51
+ ([name, version]) => name.startsWith("@tradejs/") && isNonEmptyString(version)
52
+ );
53
+ var INTERVALS = /* @__PURE__ */ new Set([
54
+ "1",
55
+ "3",
56
+ "5",
57
+ "15",
58
+ "30",
59
+ "60",
60
+ "120",
61
+ "240",
62
+ "360",
63
+ "720",
64
+ "D",
65
+ "W",
66
+ "M"
67
+ ]);
68
+ var UNIVERSES = /* @__PURE__ */ new Set(["crypto", "tradfi"]);
69
+ var isRuntimeStrategySelection = (value) => value === void 0 || isRecord(value) && Object.keys(value).length === 1 && Object.keys(value).every((key) => key === "tickers") && Array.isArray(value.tickers) && value.tickers.length > 0 && value.tickers.every((ticker) => isNonEmptyString(ticker));
70
+ var samePackageVersions = (left, right) => {
71
+ if (!left || !right) return false;
72
+ const leftEntries = Object.entries(left).sort(
73
+ ([a], [b]) => a.localeCompare(b)
74
+ );
75
+ const rightEntries = Object.entries(right).sort(
76
+ ([a], [b]) => a.localeCompare(b)
77
+ );
78
+ return JSON.stringify(leftEntries) === JSON.stringify(rightEntries);
79
+ };
80
+ var runtimeLineageMatchesStrategySnapshot = ({
81
+ lineage,
82
+ deployment,
83
+ strategy
84
+ }) => lineage?.schemaVersion === 3 && lineage.strategyRevision === strategy.strategyRevision && lineage.deploymentCompositionId === deployment.deploymentCompositionId && lineage.strategyPackageVersion === strategy.strategyPackageVersion && lineage.runtimePackageVersion === strategy.runtimePackageVersion && samePackageVersions(
85
+ lineage.strategyDependencyVersions,
86
+ strategy.strategyDependencyVersions
87
+ );
88
+ var parseRuntimeEvidenceDeploymentSnapshot = (value) => {
89
+ if (!isRecord(value) || value.schemaVersion !== 2 || !isNonEmptyString(value.id) || !isNonEmptyString(value.deploymentCompositionId) || !/^dc1:[a-f0-9]{16}$/.test(value.deploymentCompositionId) || !isNonEmptyString(value.label) || !isNonEmptyString(value.connectorName) || !isNonEmptyString(value.provider) || !isNonEmptyString(value.accountId) || typeof value.enabled !== "boolean" || !Array.isArray(value.strategies)) {
90
+ throw new Error(
91
+ "Runtime evidence deployment snapshot is missing or invalid"
92
+ );
93
+ }
94
+ const strategies = value.strategies.map((candidate) => {
95
+ if (!isRecord(candidate) || !isNonEmptyString(candidate.strategyName) || !isNonEmptyString(candidate.strategyRevision) || !/^sr1:[a-f0-9]{16}$/.test(candidate.strategyRevision) || typeof candidate.enabled !== "boolean" || !["active", "entries_paused"].includes(String(candidate.controlState)) || !INTERVALS.has(String(candidate.interval)) || !UNIVERSES.has(String(candidate.universe)) || !isNonEmptyString(candidate.strategyPackage) || !isNonEmptyString(candidate.strategyPackageVersion) || !isPackageVersionMap(candidate.strategyDependencyVersions) || !isNonEmptyString(candidate.runtimePackageVersion) || !isRecord(candidate.strategyConfig) || !isRuntimeStrategySelection(candidate.selection)) {
96
+ throw new Error(
97
+ "Runtime evidence deployment strategy snapshot is invalid"
98
+ );
99
+ }
100
+ if (String(candidate.strategyConfig.INTERVAL) !== String(candidate.interval) || String(candidate.strategyConfig.UNIVERSE) !== String(candidate.universe)) {
101
+ throw new Error(
102
+ `Runtime evidence strategy config does not match its scope: ${candidate.strategyName}`
103
+ );
104
+ }
105
+ if (candidate.accountId != null && (!isNonEmptyString(candidate.accountId) || candidate.accountId !== value.accountId)) {
106
+ throw new Error(
107
+ `Runtime evidence strategy account does not match deployment: ${candidate.strategyName}`
108
+ );
109
+ }
110
+ return candidate;
111
+ });
112
+ const identities = /* @__PURE__ */ new Set();
113
+ for (const strategy of strategies) {
114
+ if (identities.has(strategy.strategyName)) {
115
+ throw new Error(
116
+ `Duplicate runtime evidence strategy: ${strategy.strategyName}`
117
+ );
118
+ }
119
+ identities.add(strategy.strategyName);
120
+ }
121
+ return {
122
+ ...value,
123
+ strategies
124
+ };
125
+ };
126
+ var activeRuntimeEvidenceStrategies = (deployment) => deployment.enabled ? deployment.strategies.filter((strategy) => strategy.enabled) : [];
127
+ var unwrapRuntimeEvidenceRows = (value, field) => (Array.isArray(value) ? value : []).map((candidate) => {
128
+ const record = isRecord(candidate) ? candidate : null;
129
+ const nested = record && isRecord(record[field]) ? record[field] : null;
130
+ return nested ?? record;
131
+ }).filter((record) => record != null);
132
+ var assertCurrentRuntimeEvidenceArtifact = (artifact) => {
133
+ if (!isRecord(artifact) || artifact.reportType !== "runtime-evidence") {
134
+ throw new Error("Invalid runtime evidence artifact");
135
+ }
136
+ const deployment = parseRuntimeEvidenceDeploymentSnapshot(
137
+ artifact.deployment
138
+ );
139
+ const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
140
+ if (activeStrategies.length === 0) {
141
+ throw new Error("Runtime evidence deployment has no enabled strategies");
142
+ }
143
+ const runtime = isRecord(artifact.runtime) ? artifact.runtime : null;
144
+ if (!runtime) {
145
+ throw new Error("Runtime evidence payload is missing");
146
+ }
147
+ if ("strategyConfigs" in runtime) {
148
+ throw new Error(
149
+ "Runtime evidence payload contains removed strategyConfigs data"
150
+ );
151
+ }
152
+ if ("evaluationStatsBuckets" in runtime) {
153
+ throw new Error(
154
+ "Runtime evidence payload contains removed lineage-less evaluationStatsBuckets data"
155
+ );
156
+ }
157
+ const rowFields = [
158
+ "trades",
159
+ "signals",
160
+ "evaluations",
161
+ "lineageScopes"
162
+ ];
163
+ for (const field of rowFields) {
164
+ if (!Array.isArray(runtime[field])) {
165
+ throw new Error(`Runtime evidence payload ${field} must be an array`);
166
+ }
167
+ }
168
+ const snapshots = new Map(
169
+ activeStrategies.map((strategy) => [strategy.strategyName, strategy])
170
+ );
171
+ const assertRows = (label, rows, lineageField) => {
172
+ for (const row of rows) {
173
+ const strategyName = String(row.strategy ?? "").trim();
174
+ const strategy = snapshots.get(strategyName);
175
+ if (!strategy || row.deploymentId !== deployment.id || row.accountId !== deployment.accountId || !runtimeLineageMatchesStrategySnapshot({
176
+ lineage: isRecord(row[lineageField]) ? row[lineageField] : void 0,
177
+ deployment,
178
+ strategy
179
+ })) {
180
+ throw new Error(
181
+ `Runtime evidence ${label} row is outside the current embedded deployment lineage`
182
+ );
183
+ }
184
+ }
185
+ };
186
+ assertRows(
187
+ "trade",
188
+ unwrapRuntimeEvidenceRows(runtime.trades, "trade"),
189
+ "runtimeLineage"
190
+ );
191
+ assertRows(
192
+ "signal",
193
+ unwrapRuntimeEvidenceRows(runtime.signals, "signal"),
194
+ "runtimeLineage"
195
+ );
196
+ assertRows(
197
+ "evaluation",
198
+ unwrapRuntimeEvidenceRows(runtime.evaluations, "evaluation"),
199
+ "runtimeLineage"
200
+ );
201
+ assertRows(
202
+ "lineage scope",
203
+ unwrapRuntimeEvidenceRows(runtime.lineageScopes, "lineageScope"),
204
+ "lineage"
205
+ );
206
+ return deployment;
207
+ };
208
+
209
+ // src/lib/runtimeEvidenceArtifacts.ts
210
+ var import_node_crypto = require("crypto");
211
+ var import_promises = __toESM(require("fs/promises"));
212
+ var import_node_path = __toESM(require("path"));
213
+ var RUNTIME_EVIDENCE_MANIFEST_FILE = "manifest.json";
214
+ var RUNTIME_EVIDENCE_PAYLOAD_FILE = "runtime-evidence.json";
215
+ var RUNTIME_EVIDENCE_COMPLETE_FILE = ".complete";
216
+ var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
217
+ var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
218
+ var assertFiniteTimestamp = (value, label) => {
219
+ if (typeof value !== "number" || !Number.isFinite(value)) {
220
+ throw new Error(`Invalid runtime evidence ${label}`);
221
+ }
222
+ return value;
223
+ };
224
+ var parseManifest = (value) => {
225
+ const manifest = asRecord(value);
226
+ const window = asRecord(manifest?.window);
227
+ const payload = asRecord(manifest?.payload);
228
+ const counts = asRecord(manifest?.counts);
229
+ if (manifest?.schemaVersion !== 1 || manifest.reportType !== "runtime-evidence" || typeof manifest.artifactId !== "string" || typeof manifest.deploymentId !== "string" || typeof manifest.userName !== "string" || typeof manifest.createdAt !== "number" || payload?.file !== RUNTIME_EVIDENCE_PAYLOAD_FILE || typeof payload.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(payload.sha256) || typeof payload.bytes !== "number" || !Array.isArray(manifest.lineageKeys)) {
230
+ throw new Error("Invalid runtime evidence manifest");
231
+ }
232
+ return {
233
+ schemaVersion: 1,
234
+ artifactId: manifest.artifactId,
235
+ reportType: "runtime-evidence",
236
+ deploymentId: manifest.deploymentId,
237
+ userName: manifest.userName,
238
+ createdAt: manifest.createdAt,
239
+ window: {
240
+ startTime: assertFiniteTimestamp(window?.startTime, "window.startTime"),
241
+ endTime: assertFiniteTimestamp(window?.endTime, "window.endTime")
242
+ },
243
+ payload: {
244
+ file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
245
+ sha256: payload.sha256,
246
+ bytes: payload.bytes
247
+ },
248
+ counts: Object.fromEntries(
249
+ Object.entries(counts ?? {}).filter(
250
+ (entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])
251
+ )
252
+ ),
253
+ lineageKeys: manifest.lineageKeys.filter(
254
+ (value2) => typeof value2 === "string" && value2.length > 0
255
+ )
256
+ };
257
+ };
258
+ var verifyRuntimeEvidenceBundle = async (bundleDir) => {
259
+ const manifestPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_MANIFEST_FILE);
260
+ const payloadPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_PAYLOAD_FILE);
261
+ const completePath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_COMPLETE_FILE);
262
+ const [manifestText, payload, completeText] = await Promise.all([
263
+ import_promises.default.readFile(manifestPath, "utf8"),
264
+ import_promises.default.readFile(payloadPath),
265
+ import_promises.default.readFile(completePath, "utf8")
266
+ ]);
267
+ const manifest = parseManifest(JSON.parse(manifestText));
268
+ if (completeText.trim() !== manifest.artifactId) {
269
+ throw new Error(`Invalid completion marker in ${bundleDir}`);
270
+ }
271
+ if (payload.byteLength !== manifest.payload.bytes) {
272
+ throw new Error(`Runtime evidence size mismatch in ${bundleDir}`);
273
+ }
274
+ if (sha256(payload) !== manifest.payload.sha256) {
275
+ throw new Error(`Runtime evidence checksum mismatch in ${bundleDir}`);
276
+ }
277
+ const artifact = asRecord(JSON.parse(payload.toString("utf8")));
278
+ const artifactWindow = asRecord(artifact?.window);
279
+ if (artifact?.reportType !== "runtime-evidence" || artifactWindow?.startTime !== manifest.window.startTime || artifactWindow.endTime !== manifest.window.endTime) {
280
+ throw new Error(`Runtime evidence payload mismatch in ${bundleDir}`);
281
+ }
282
+ const deployment = assertCurrentRuntimeEvidenceArtifact(artifact);
283
+ if (deployment.id !== manifest.deploymentId) {
284
+ throw new Error(`Runtime evidence deployment mismatch in ${bundleDir}`);
285
+ }
286
+ return {
287
+ bundleDir,
288
+ manifestPath,
289
+ payloadPath,
290
+ manifest,
291
+ artifact
292
+ };
293
+ };
294
+
295
+ // src/lib/runtimeEvidenceProducer.ts
296
+ var import_node_crypto2 = require("crypto");
297
+ var import_promises2 = __toESM(require("fs/promises"));
298
+ var import_node_path2 = __toESM(require("path"));
299
+ var isRecord2 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
300
+ var sha2562 = (value) => (0, import_node_crypto2.createHash)("sha256").update(value).digest("hex");
301
+ var parseRuntimeEvidenceProducer = (value) => {
302
+ const producer = isRecord2(value) ? value : null;
303
+ const runtimePackageManifest = isRecord2(producer?.runtimePackageManifest) ? producer.runtimePackageManifest : null;
304
+ if (producer?.schemaVersion !== 1 || typeof producer.projectSha !== "string" || !/^[a-f0-9]{40}$/.test(producer.projectSha) || typeof producer.imageDigest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(producer.imageDigest) || runtimePackageManifest?.file !== "runtime-package-manifest.json" || typeof runtimePackageManifest.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(runtimePackageManifest.sha256)) {
305
+ throw new Error("Runtime evidence producer image identity is invalid");
306
+ }
307
+ return producer;
308
+ };
309
+ var resolveRuntimeEvidenceProducer = async ({
310
+ projectRoot: projectRoot2,
311
+ required
312
+ }) => {
313
+ const projectSha = String(process.env.TRADEJS_PROJECT_SHA ?? "").trim();
314
+ const imageDigest = String(
315
+ process.env.TRADEJS_PROJECT_IMAGE_DIGEST ?? ""
316
+ ).trim();
317
+ if (!projectSha && !imageDigest && !required) {
318
+ return null;
319
+ }
320
+ if (!/^[a-f0-9]{40}$/.test(projectSha)) {
321
+ throw new Error(
322
+ "TRADEJS_PROJECT_SHA must be a full lowercase Git SHA before publishing runtime evidence"
323
+ );
324
+ }
325
+ if (!/^sha256:[a-f0-9]{64}$/.test(imageDigest)) {
326
+ throw new Error(
327
+ "TRADEJS_PROJECT_IMAGE_DIGEST must be an immutable sha256 digest before publishing runtime evidence"
328
+ );
329
+ }
330
+ const manifestPath = import_node_path2.default.join(projectRoot2, "runtime-package-manifest.json");
331
+ let manifest;
332
+ try {
333
+ manifest = await import_promises2.default.readFile(manifestPath);
334
+ } catch (error) {
335
+ if (!required && error.code === "ENOENT") {
336
+ return null;
337
+ }
338
+ throw new Error(
339
+ `Runtime package manifest is required for runtime evidence: ${manifestPath}`,
340
+ { cause: error }
341
+ );
342
+ }
343
+ return {
344
+ schemaVersion: 1,
345
+ projectSha,
346
+ imageDigest,
347
+ runtimePackageManifest: {
348
+ file: "runtime-package-manifest.json",
349
+ sha256: sha2562(manifest)
350
+ }
351
+ };
352
+ };
353
+
354
+ // src/lib/runtimeFeedbackArtifacts.ts
355
+ var import_node_crypto3 = require("crypto");
356
+ var import_promises3 = __toESM(require("fs/promises"));
357
+ var import_node_path3 = __toESM(require("path"));
358
+ var RUNTIME_FEEDBACK_MANIFEST_FILE = "manifest.json";
359
+ var RUNTIME_FEEDBACK_REPLAY_FILE = "replay-runtime-evidence.json";
360
+ var RUNTIME_FEEDBACK_LOG_FILE = "replay.log";
361
+ var RUNTIME_FEEDBACK_COMPLETE_FILE = ".complete";
362
+ var isRecord3 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
363
+ var sha2563 = (value) => (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex");
364
+ var safeSegment = (value, fallback) => {
365
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
366
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
367
+ };
368
+ var parsePayload = (value, expectedFile) => {
369
+ const payload = isRecord3(value) ? value : null;
370
+ if (payload?.file !== expectedFile || typeof payload.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(payload.sha256) || typeof payload.bytes !== "number" || !Number.isFinite(payload.bytes) || payload.bytes < 0) {
371
+ throw new Error(`Invalid runtime feedback payload: ${expectedFile}`);
372
+ }
373
+ return payload;
374
+ };
375
+ var parseManifest2 = (value) => {
376
+ const manifest = isRecord3(value) ? value : null;
377
+ const window = isRecord3(manifest?.window) ? manifest.window : null;
378
+ const runtimeEvidence = isRecord3(manifest?.runtimeEvidence) ? manifest.runtimeEvidence : null;
379
+ const safety = isRecord3(manifest?.safety) ? manifest.safety : null;
380
+ const payloads = isRecord3(manifest?.payloads) ? manifest.payloads : null;
381
+ if (manifest?.schemaVersion !== 1 || manifest.reportType !== "runtime-feedback-replay" || typeof manifest.artifactId !== "string" || !manifest.artifactId.trim() || typeof manifest.runId !== "string" || !manifest.runId.trim() || typeof manifest.deploymentId !== "string" || !manifest.deploymentId.trim() || typeof manifest.deploymentCompositionId !== "string" || !/^dc1:[a-f0-9]{16}$/.test(manifest.deploymentCompositionId) || typeof manifest.userName !== "string" || !manifest.userName.trim() || typeof manifest.createdAt !== "number" || typeof window?.startTime !== "number" || typeof window.endTime !== "number" || typeof runtimeEvidence?.artifactId !== "string" || typeof runtimeEvidence.payloadSha256 !== "string" || !/^[a-f0-9]{64}$/.test(runtimeEvidence.payloadSha256) || !Array.isArray(manifest.activeStrategies) || manifest.activeStrategies.length === 0 || !manifest.activeStrategies.every(
382
+ (strategy) => typeof strategy === "string" && strategy.trim()
383
+ ) || typeof manifest.cycleCount !== "number" || !Number.isFinite(manifest.cycleCount) || manifest.cycleCount <= 0 || safety?.cacheOnly !== true || safety.externalOrderPlacement !== false || safety.redis !== "isolated" || safety.timescale !== "read_only") {
384
+ throw new Error("Invalid runtime feedback replay manifest");
385
+ }
386
+ const replayEvidence = parsePayload(
387
+ payloads?.replayEvidence,
388
+ RUNTIME_FEEDBACK_REPLAY_FILE
389
+ );
390
+ const log = parsePayload(payloads?.log, RUNTIME_FEEDBACK_LOG_FILE);
391
+ return {
392
+ ...manifest,
393
+ producer: parseRuntimeEvidenceProducer(manifest.producer),
394
+ payloads: {
395
+ replayEvidence: {
396
+ ...replayEvidence,
397
+ file: RUNTIME_FEEDBACK_REPLAY_FILE
398
+ },
399
+ log: { ...log, file: RUNTIME_FEEDBACK_LOG_FILE }
400
+ }
401
+ };
402
+ };
403
+ var assertReplayMatchesRuntimeEvidence = ({
404
+ replayEvidence,
405
+ runtimeEvidence
406
+ }) => {
407
+ if (replayEvidence.reportType !== "replay-runtime-evidence") {
408
+ throw new Error("Runtime feedback replay payload has the wrong reportType");
409
+ }
410
+ const replayWindow = isRecord3(replayEvidence.window) ? replayEvidence.window : null;
411
+ if (replayWindow?.startTime !== runtimeEvidence.manifest.window.startTime || replayWindow.endTime !== runtimeEvidence.manifest.window.endTime) {
412
+ throw new Error("Runtime feedback replay window does not match evidence");
413
+ }
414
+ const runtimeDeployment = parseRuntimeEvidenceDeploymentSnapshot(
415
+ runtimeEvidence.artifact.deployment
416
+ );
417
+ const replayDeployment = parseRuntimeEvidenceDeploymentSnapshot(
418
+ replayEvidence.deployment
419
+ );
420
+ if (replayDeployment.id !== runtimeDeployment.id || replayDeployment.deploymentCompositionId !== runtimeDeployment.deploymentCompositionId) {
421
+ throw new Error(
422
+ "Runtime feedback replay deployment does not match evidence"
423
+ );
424
+ }
425
+ };
426
+ var sealRuntimeFeedbackReplayBundle = async ({
427
+ bundleDir,
428
+ runId,
429
+ runtimeEvidenceBundle
430
+ }) => {
431
+ const replayEvidencePath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_REPLAY_FILE);
432
+ const logPath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_LOG_FILE);
433
+ const [replayPayload, logPayload] = await Promise.all([
434
+ import_promises3.default.readFile(replayEvidencePath),
435
+ import_promises3.default.readFile(logPath)
436
+ ]);
437
+ const replayEvidence = JSON.parse(replayPayload.toString("utf8"));
438
+ assertReplayMatchesRuntimeEvidence({
439
+ replayEvidence,
440
+ runtimeEvidence: runtimeEvidenceBundle
441
+ });
442
+ const replay = isRecord3(replayEvidence.replay) ? replayEvidence.replay : null;
443
+ const cycleCount = Number(replay?.cycleCount);
444
+ if (!Number.isFinite(cycleCount) || cycleCount <= 0) {
445
+ throw new Error(
446
+ `Runtime feedback replay produced no comparable cycles: ${String(replay?.cycleCount ?? "missing")}`
447
+ );
448
+ }
449
+ const deployment = parseRuntimeEvidenceDeploymentSnapshot(
450
+ runtimeEvidenceBundle.artifact.deployment
451
+ );
452
+ const producer = parseRuntimeEvidenceProducer(
453
+ runtimeEvidenceBundle.artifact.producer
454
+ );
455
+ const safeRunId = safeSegment(runId, "run");
456
+ const artifactId = `${runtimeEvidenceBundle.manifest.artifactId}_${safeRunId}`;
457
+ const manifest = {
458
+ schemaVersion: 1,
459
+ reportType: "runtime-feedback-replay",
460
+ artifactId,
461
+ runId: safeRunId,
462
+ deploymentId: deployment.id,
463
+ deploymentCompositionId: deployment.deploymentCompositionId,
464
+ userName: runtimeEvidenceBundle.manifest.userName,
465
+ createdAt: Date.now(),
466
+ window: { ...runtimeEvidenceBundle.manifest.window },
467
+ runtimeEvidence: {
468
+ artifactId: runtimeEvidenceBundle.manifest.artifactId,
469
+ payloadSha256: runtimeEvidenceBundle.manifest.payload.sha256
470
+ },
471
+ producer,
472
+ activeStrategies: activeRuntimeEvidenceStrategies(deployment).map(
473
+ ({ strategyName }) => strategyName
474
+ ),
475
+ cycleCount,
476
+ safety: {
477
+ cacheOnly: true,
478
+ externalOrderPlacement: false,
479
+ redis: "isolated",
480
+ timescale: "read_only"
481
+ },
482
+ payloads: {
483
+ replayEvidence: {
484
+ file: RUNTIME_FEEDBACK_REPLAY_FILE,
485
+ sha256: sha2563(replayPayload),
486
+ bytes: replayPayload.byteLength
487
+ },
488
+ log: {
489
+ file: RUNTIME_FEEDBACK_LOG_FILE,
490
+ sha256: sha2563(logPayload),
491
+ bytes: logPayload.byteLength
492
+ }
493
+ }
494
+ };
495
+ await import_promises3.default.writeFile(
496
+ import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_MANIFEST_FILE),
497
+ `${JSON.stringify(manifest, null, 2)}
498
+ `,
499
+ "utf8"
500
+ );
501
+ await import_promises3.default.writeFile(
502
+ import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_COMPLETE_FILE),
503
+ `${artifactId}
504
+ `,
505
+ "utf8"
506
+ );
507
+ return verifyRuntimeFeedbackReplayBundle(bundleDir);
508
+ };
509
+ var verifyRuntimeFeedbackReplayBundle = async (bundleDir) => {
510
+ const manifestPath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_MANIFEST_FILE);
511
+ const replayEvidencePath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_REPLAY_FILE);
512
+ const logPath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_LOG_FILE);
513
+ const completePath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_COMPLETE_FILE);
514
+ const [manifestText, replayPayload, logPayload, completeText] = await Promise.all([
515
+ import_promises3.default.readFile(manifestPath, "utf8"),
516
+ import_promises3.default.readFile(replayEvidencePath),
517
+ import_promises3.default.readFile(logPath),
518
+ import_promises3.default.readFile(completePath, "utf8")
519
+ ]);
520
+ const manifest = parseManifest2(JSON.parse(manifestText));
521
+ if (completeText.trim() !== manifest.artifactId) {
522
+ throw new Error(`Invalid runtime feedback completion marker: ${bundleDir}`);
523
+ }
524
+ for (const [payload, descriptor] of [
525
+ [replayPayload, manifest.payloads.replayEvidence],
526
+ [logPayload, manifest.payloads.log]
527
+ ]) {
528
+ if (payload.byteLength !== descriptor.bytes) {
529
+ throw new Error(
530
+ `Runtime feedback payload size mismatch: ${descriptor.file}`
531
+ );
532
+ }
533
+ if (sha2563(payload) !== descriptor.sha256) {
534
+ throw new Error(
535
+ `Runtime feedback payload checksum mismatch: ${descriptor.file}`
536
+ );
537
+ }
538
+ }
539
+ const replayEvidence = JSON.parse(replayPayload.toString("utf8"));
540
+ if (replayEvidence.reportType !== "replay-runtime-evidence") {
541
+ throw new Error("Invalid runtime feedback replay evidence payload");
542
+ }
543
+ const replayWindow = isRecord3(replayEvidence.window) ? replayEvidence.window : null;
544
+ const replay = isRecord3(replayEvidence.replay) ? replayEvidence.replay : null;
545
+ const replayDeployment = parseRuntimeEvidenceDeploymentSnapshot(
546
+ replayEvidence.deployment
547
+ );
548
+ const replayStrategies = activeRuntimeEvidenceStrategies(replayDeployment).map(({ strategyName }) => strategyName).sort();
549
+ if (replayEvidence.userName !== manifest.userName || replayWindow?.startTime !== manifest.window.startTime || replayWindow.endTime !== manifest.window.endTime || replayDeployment.id !== manifest.deploymentId || replayDeployment.deploymentCompositionId !== manifest.deploymentCompositionId || Number(replay?.cycleCount) !== manifest.cycleCount || JSON.stringify(replayStrategies) !== JSON.stringify([...manifest.activeStrategies].sort())) {
550
+ throw new Error("Runtime feedback replay payload does not match manifest");
551
+ }
552
+ return {
553
+ bundleDir,
554
+ manifestPath,
555
+ replayEvidencePath,
556
+ logPath,
557
+ manifest,
558
+ replayEvidence
559
+ };
560
+ };
561
+
562
+ // src/lib/runtimeFeedbackReplay.ts
563
+ var REQUIRED_ENV = {
564
+ RUNTIME_FEEDBACK_ISOLATED_REDIS: "true",
565
+ MAKE_ORDERS: "false",
566
+ TRADEJS_EXTERNAL_ORDER_PLACEMENT: "false"
567
+ };
568
+ var FORBIDDEN_SECRET_ENV = [
569
+ "AGENT_GITHUB_TOKEN",
570
+ "AI_API_KEY",
571
+ "ANTHROPIC_API_KEY",
572
+ "AUTH_SECRET",
573
+ "BYBIT_API_KEY",
574
+ "BYBIT_API_SECRET",
575
+ "COINALYZE_API_KEY",
576
+ "COINMARKETCAP_API_KEY",
577
+ "GITHUB_TOKEN",
578
+ "GIT_SSH_PRIVATE_KEY",
579
+ "NEXTAUTH_SECRET",
580
+ "NPM_TOKEN",
581
+ "OPENAI_API_KEY",
582
+ "OPENROUTER_API_KEY",
583
+ "SSH_PRIVATE_KEY",
584
+ "TG_BOT_TOKEN"
585
+ ];
586
+ var unsafeRedisHosts = /* @__PURE__ */ new Set([
587
+ "127.0.0.1",
588
+ "::1",
589
+ "inv-redis",
590
+ "localhost",
591
+ "redis"
592
+ ]);
593
+ var safeSegment2 = (value, fallback) => {
594
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
595
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
596
+ };
597
+ var assertRuntimeFeedbackReplaySafety = (env) => {
598
+ for (const [name, expected] of Object.entries(REQUIRED_ENV)) {
599
+ if (env[name] !== expected) {
600
+ throw new Error(`Runtime feedback replay requires ${name}=${expected}`);
601
+ }
602
+ }
603
+ const redisHost = String(env.REDIS_HOST ?? "").trim().toLowerCase();
604
+ if (!redisHost || unsafeRedisHosts.has(redisHost)) {
605
+ throw new Error(
606
+ `Runtime feedback replay requires a named isolated Redis host, received ${redisHost || "[missing]"}`
607
+ );
608
+ }
609
+ const pgOptions = String(env.PGOPTIONS ?? "");
610
+ if (!/default_transaction_read_only\s*=\s*on/i.test(pgOptions)) {
611
+ throw new Error(
612
+ "Runtime feedback replay requires PGOPTIONS with default_transaction_read_only=on"
613
+ );
614
+ }
615
+ if (env.TRADEJS_TIMESCALE_READ_ONLY !== "true") {
616
+ throw new Error(
617
+ "Runtime feedback replay requires TRADEJS_TIMESCALE_READ_ONLY=true"
618
+ );
619
+ }
620
+ const exposedSecrets = FORBIDDEN_SECRET_ENV.filter(
621
+ (name) => String(env[name] ?? "").trim()
622
+ );
623
+ if (exposedSecrets.length) {
624
+ throw new Error(
625
+ `Runtime feedback replay received forbidden credentials: ${exposedSecrets.join(", ")}`
626
+ );
627
+ }
628
+ };
629
+ var buildRuntimeFeedbackReplayCommands = ({
630
+ cliPath,
631
+ runtimeEvidencePath,
632
+ replayEvidencePath,
633
+ userName,
634
+ connectorName,
635
+ deploymentId,
636
+ interval,
637
+ startTime,
638
+ endTime
639
+ }) => [
640
+ [
641
+ cliPath,
642
+ "replay",
643
+ "--user",
644
+ userName,
645
+ "--connector",
646
+ connectorName,
647
+ "--deployment",
648
+ deploymentId,
649
+ "--timeframe",
650
+ interval,
651
+ "--startTime",
652
+ String(startTime),
653
+ "--endTime",
654
+ String(endTime),
655
+ "--runtimeEvidence",
656
+ runtimeEvidencePath,
657
+ "--cacheOnly"
658
+ ],
659
+ [
660
+ cliPath,
661
+ "replay-runtime-evidence",
662
+ "--user",
663
+ userName,
664
+ "--runtimeEvidence",
665
+ runtimeEvidencePath,
666
+ "--startTime",
667
+ String(startTime),
668
+ "--endTime",
669
+ String(endTime),
670
+ "--out",
671
+ replayEvidencePath
672
+ ]
673
+ ];
674
+ var runLoggedCommand = async ({
675
+ executable,
676
+ command,
677
+ cwd,
678
+ env,
679
+ logHandle
680
+ }) => {
681
+ await logHandle.write(`
682
+ $ ${[executable, ...command].join(" ")}
683
+ `);
684
+ await new Promise((resolve, reject) => {
685
+ let pendingLogWrite = Promise.resolve();
686
+ const appendLog = (chunk) => {
687
+ pendingLogWrite = pendingLogWrite.then(async () => {
688
+ await logHandle.write(chunk);
689
+ });
690
+ };
691
+ const child = (0, import_node_child_process.spawn)(executable, command, {
692
+ cwd,
693
+ env,
694
+ stdio: ["ignore", "pipe", "pipe"]
695
+ });
696
+ child.stdout.on("data", (chunk) => {
697
+ process.stdout.write(chunk);
698
+ appendLog(chunk);
699
+ });
700
+ child.stderr.on("data", (chunk) => {
701
+ process.stderr.write(chunk);
702
+ appendLog(chunk);
703
+ });
704
+ child.once("error", reject);
705
+ child.once("close", (code, signal) => {
706
+ void pendingLogWrite.then(() => {
707
+ if (code === 0) {
708
+ resolve();
709
+ return;
710
+ }
711
+ reject(
712
+ new Error(
713
+ `Runtime feedback command failed: exit=${String(code)} signal=${String(signal)}`
714
+ )
715
+ );
716
+ }, reject);
717
+ });
718
+ });
719
+ };
720
+ var runRuntimeFeedbackReplay = async ({
721
+ runtimeEvidencePath,
722
+ outDir,
723
+ runId = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${process.pid}`,
724
+ projectRoot: projectRoot2,
725
+ env = process.env,
726
+ executable = process.execPath,
727
+ cliPath = process.argv[1]
728
+ }) => {
729
+ assertRuntimeFeedbackReplaySafety(env);
730
+ if (!cliPath) {
731
+ throw new Error("Cannot resolve the TradeJS CLI executable path");
732
+ }
733
+ const runtimeEvidenceBundle = await verifyRuntimeEvidenceBundle(
734
+ import_node_path4.default.dirname(runtimeEvidencePath)
735
+ );
736
+ if (import_node_path4.default.resolve(runtimeEvidenceBundle.payloadPath) !== runtimeEvidencePath) {
737
+ throw new Error(
738
+ `Runtime evidence must be the verified bundle payload: ${runtimeEvidenceBundle.payloadPath}`
739
+ );
740
+ }
741
+ const deployedProducer = parseRuntimeEvidenceProducer(
742
+ runtimeEvidenceBundle.artifact.producer
743
+ );
744
+ const currentProducer = await resolveRuntimeEvidenceProducer({
745
+ projectRoot: projectRoot2,
746
+ required: true
747
+ });
748
+ if (!currentProducer || currentProducer.projectSha !== deployedProducer.projectSha || currentProducer.imageDigest !== deployedProducer.imageDigest || currentProducer.runtimePackageManifest.sha256 !== deployedProducer.runtimePackageManifest.sha256) {
749
+ throw new Error(
750
+ "Runtime feedback replay image identity does not match runtime evidence"
751
+ );
752
+ }
753
+ const deployment = parseRuntimeEvidenceDeploymentSnapshot(
754
+ runtimeEvidenceBundle.artifact.deployment
755
+ );
756
+ const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
757
+ const intervals = new Set(
758
+ activeStrategies.map(({ interval }) => String(interval))
759
+ );
760
+ if (intervals.size !== 1) {
761
+ throw new Error(
762
+ `Runtime feedback replay requires one interval, received ${[...intervals].join(",")}`
763
+ );
764
+ }
765
+ await import_promises4.default.mkdir(outDir, { recursive: true });
766
+ const existing = await import_promises4.default.readdir(outDir);
767
+ if (existing.length) {
768
+ throw new Error(
769
+ `Runtime feedback output directory must be empty: ${outDir}`
770
+ );
771
+ }
772
+ const replayEvidencePath = import_node_path4.default.join(outDir, RUNTIME_FEEDBACK_REPLAY_FILE);
773
+ const logHandle = await import_promises4.default.open(
774
+ import_node_path4.default.join(outDir, RUNTIME_FEEDBACK_LOG_FILE),
775
+ "wx"
776
+ );
777
+ const commands = buildRuntimeFeedbackReplayCommands({
778
+ cliPath,
779
+ runtimeEvidencePath,
780
+ replayEvidencePath,
781
+ userName: runtimeEvidenceBundle.manifest.userName,
782
+ connectorName: deployment.connectorName,
783
+ deploymentId: deployment.id,
784
+ interval: [...intervals][0],
785
+ startTime: runtimeEvidenceBundle.manifest.window.startTime,
786
+ endTime: runtimeEvidenceBundle.manifest.window.endTime
787
+ });
788
+ try {
789
+ for (const command of commands) {
790
+ await runLoggedCommand({
791
+ executable,
792
+ command,
793
+ cwd: projectRoot2,
794
+ env,
795
+ logHandle
796
+ });
797
+ }
798
+ } finally {
799
+ await logHandle.close();
800
+ }
801
+ return sealRuntimeFeedbackReplayBundle({
802
+ bundleDir: outDir,
803
+ runId: safeSegment2(runId, "run"),
804
+ runtimeEvidenceBundle
805
+ });
806
+ };
807
+
808
+ // src/scripts/runtimeFeedbackReplay.ts
809
+ import_args.default.option("runtimeEvidence", "Verified runtime evidence JSON");
810
+ import_args.default.option("outDir", "New writable directory for replay output");
811
+ import_args.default.option("runId", "Stable identifier for this replay attempt");
812
+ var flags = import_args.default.parse(process.argv);
813
+ var projectRoot = String(process.env.PROJECT_CWD || process.cwd()).trim() || process.cwd();
814
+ var runtimeFeedbackReplay = async () => {
815
+ const runtimeEvidence = String(flags.runtimeEvidence ?? "").trim();
816
+ const outDir = String(flags.outDir ?? "").trim();
817
+ if (!runtimeEvidence || !outDir) {
818
+ throw new Error(
819
+ "Provide --runtimeEvidence and --outDir for runtime feedback replay."
820
+ );
821
+ }
822
+ const verified = await runRuntimeFeedbackReplay({
823
+ runtimeEvidencePath: import_node_path5.default.resolve(projectRoot, runtimeEvidence),
824
+ outDir: import_node_path5.default.resolve(projectRoot, outDir),
825
+ runId: String(flags.runId ?? "").trim() || void 0,
826
+ projectRoot
827
+ });
828
+ console.log(
829
+ import_chalk.default.green(
830
+ `Runtime feedback replay sealed: ${verified.manifest.artifactId}`
831
+ )
832
+ );
833
+ console.log(
834
+ JSON.stringify(
835
+ {
836
+ bundleDir: verified.bundleDir,
837
+ manifestPath: verified.manifestPath,
838
+ replayEvidencePath: verified.replayEvidencePath
839
+ },
840
+ null,
841
+ 2
842
+ )
843
+ );
844
+ };
845
+ var main = runtimeFeedbackReplay;
846
+ // Annotate the CommonJS export names for ESM import in node:
847
+ 0 && (module.exports = {
848
+ main,
849
+ runtimeFeedbackReplay
850
+ });