@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,350 @@
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/lib/runtimeFeedbackSync.ts
31
+ var runtimeFeedbackSync_exports = {};
32
+ __export(runtimeFeedbackSync_exports, {
33
+ syncRuntimeFeedbackReplayBundles: () => syncRuntimeFeedbackReplayBundles
34
+ });
35
+ module.exports = __toCommonJS(runtimeFeedbackSync_exports);
36
+ var import_node_child_process2 = require("child_process");
37
+ var import_promises5 = __toESM(require("fs/promises"));
38
+ var import_node_path5 = __toESM(require("path"));
39
+ var import_node_util2 = require("util");
40
+
41
+ // src/lib/runtimeFeedbackArtifacts.ts
42
+ var import_node_crypto3 = require("crypto");
43
+ var import_promises3 = __toESM(require("fs/promises"));
44
+ var import_node_path3 = __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 parseRuntimeEvidenceDeploymentSnapshot = (value) => {
71
+ 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)) {
72
+ throw new Error(
73
+ "Runtime evidence deployment snapshot is missing or invalid"
74
+ );
75
+ }
76
+ const strategies = value.strategies.map((candidate) => {
77
+ 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)) {
78
+ throw new Error(
79
+ "Runtime evidence deployment strategy snapshot is invalid"
80
+ );
81
+ }
82
+ if (String(candidate.strategyConfig.INTERVAL) !== String(candidate.interval) || String(candidate.strategyConfig.UNIVERSE) !== String(candidate.universe)) {
83
+ throw new Error(
84
+ `Runtime evidence strategy config does not match its scope: ${candidate.strategyName}`
85
+ );
86
+ }
87
+ if (candidate.accountId != null && (!isNonEmptyString(candidate.accountId) || candidate.accountId !== value.accountId)) {
88
+ throw new Error(
89
+ `Runtime evidence strategy account does not match deployment: ${candidate.strategyName}`
90
+ );
91
+ }
92
+ return candidate;
93
+ });
94
+ const identities = /* @__PURE__ */ new Set();
95
+ for (const strategy of strategies) {
96
+ if (identities.has(strategy.strategyName)) {
97
+ throw new Error(
98
+ `Duplicate runtime evidence strategy: ${strategy.strategyName}`
99
+ );
100
+ }
101
+ identities.add(strategy.strategyName);
102
+ }
103
+ return {
104
+ ...value,
105
+ strategies
106
+ };
107
+ };
108
+ var activeRuntimeEvidenceStrategies = (deployment) => deployment.enabled ? deployment.strategies.filter((strategy) => strategy.enabled) : [];
109
+
110
+ // src/lib/runtimeEvidenceArtifacts.ts
111
+ var import_node_crypto = require("crypto");
112
+ var import_promises = __toESM(require("fs/promises"));
113
+ var import_node_path = __toESM(require("path"));
114
+
115
+ // src/lib/runtimeEvidenceProducer.ts
116
+ var import_node_crypto2 = require("crypto");
117
+ var import_promises2 = __toESM(require("fs/promises"));
118
+ var import_node_path2 = __toESM(require("path"));
119
+ var isRecord2 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
120
+ var parseRuntimeEvidenceProducer = (value) => {
121
+ const producer = isRecord2(value) ? value : null;
122
+ const runtimePackageManifest = isRecord2(producer?.runtimePackageManifest) ? producer.runtimePackageManifest : null;
123
+ 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)) {
124
+ throw new Error("Runtime evidence producer image identity is invalid");
125
+ }
126
+ return producer;
127
+ };
128
+
129
+ // src/lib/runtimeFeedbackArtifacts.ts
130
+ var RUNTIME_FEEDBACK_MANIFEST_FILE = "manifest.json";
131
+ var RUNTIME_FEEDBACK_REPLAY_FILE = "replay-runtime-evidence.json";
132
+ var RUNTIME_FEEDBACK_LOG_FILE = "replay.log";
133
+ var RUNTIME_FEEDBACK_COMPLETE_FILE = ".complete";
134
+ var isRecord3 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
135
+ var sha256 = (value) => (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex");
136
+ var parsePayload = (value, expectedFile) => {
137
+ const payload = isRecord3(value) ? value : null;
138
+ 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) {
139
+ throw new Error(`Invalid runtime feedback payload: ${expectedFile}`);
140
+ }
141
+ return payload;
142
+ };
143
+ var parseManifest = (value) => {
144
+ const manifest = isRecord3(value) ? value : null;
145
+ const window = isRecord3(manifest?.window) ? manifest.window : null;
146
+ const runtimeEvidence = isRecord3(manifest?.runtimeEvidence) ? manifest.runtimeEvidence : null;
147
+ const safety = isRecord3(manifest?.safety) ? manifest.safety : null;
148
+ const payloads = isRecord3(manifest?.payloads) ? manifest.payloads : null;
149
+ 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(
150
+ (strategy) => typeof strategy === "string" && strategy.trim()
151
+ ) || typeof manifest.cycleCount !== "number" || !Number.isFinite(manifest.cycleCount) || manifest.cycleCount <= 0 || safety?.cacheOnly !== true || safety.externalOrderPlacement !== false || safety.redis !== "isolated" || safety.timescale !== "read_only") {
152
+ throw new Error("Invalid runtime feedback replay manifest");
153
+ }
154
+ const replayEvidence = parsePayload(
155
+ payloads?.replayEvidence,
156
+ RUNTIME_FEEDBACK_REPLAY_FILE
157
+ );
158
+ const log = parsePayload(payloads?.log, RUNTIME_FEEDBACK_LOG_FILE);
159
+ return {
160
+ ...manifest,
161
+ producer: parseRuntimeEvidenceProducer(manifest.producer),
162
+ payloads: {
163
+ replayEvidence: {
164
+ ...replayEvidence,
165
+ file: RUNTIME_FEEDBACK_REPLAY_FILE
166
+ },
167
+ log: { ...log, file: RUNTIME_FEEDBACK_LOG_FILE }
168
+ }
169
+ };
170
+ };
171
+ var verifyRuntimeFeedbackReplayBundle = async (bundleDir) => {
172
+ const manifestPath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_MANIFEST_FILE);
173
+ const replayEvidencePath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_REPLAY_FILE);
174
+ const logPath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_LOG_FILE);
175
+ const completePath = import_node_path3.default.join(bundleDir, RUNTIME_FEEDBACK_COMPLETE_FILE);
176
+ const [manifestText, replayPayload, logPayload, completeText] = await Promise.all([
177
+ import_promises3.default.readFile(manifestPath, "utf8"),
178
+ import_promises3.default.readFile(replayEvidencePath),
179
+ import_promises3.default.readFile(logPath),
180
+ import_promises3.default.readFile(completePath, "utf8")
181
+ ]);
182
+ const manifest = parseManifest(JSON.parse(manifestText));
183
+ if (completeText.trim() !== manifest.artifactId) {
184
+ throw new Error(`Invalid runtime feedback completion marker: ${bundleDir}`);
185
+ }
186
+ for (const [payload, descriptor] of [
187
+ [replayPayload, manifest.payloads.replayEvidence],
188
+ [logPayload, manifest.payloads.log]
189
+ ]) {
190
+ if (payload.byteLength !== descriptor.bytes) {
191
+ throw new Error(
192
+ `Runtime feedback payload size mismatch: ${descriptor.file}`
193
+ );
194
+ }
195
+ if (sha256(payload) !== descriptor.sha256) {
196
+ throw new Error(
197
+ `Runtime feedback payload checksum mismatch: ${descriptor.file}`
198
+ );
199
+ }
200
+ }
201
+ const replayEvidence = JSON.parse(replayPayload.toString("utf8"));
202
+ if (replayEvidence.reportType !== "replay-runtime-evidence") {
203
+ throw new Error("Invalid runtime feedback replay evidence payload");
204
+ }
205
+ const replayWindow = isRecord3(replayEvidence.window) ? replayEvidence.window : null;
206
+ const replay = isRecord3(replayEvidence.replay) ? replayEvidence.replay : null;
207
+ const replayDeployment = parseRuntimeEvidenceDeploymentSnapshot(
208
+ replayEvidence.deployment
209
+ );
210
+ const replayStrategies = activeRuntimeEvidenceStrategies(replayDeployment).map(({ strategyName }) => strategyName).sort();
211
+ 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())) {
212
+ throw new Error("Runtime feedback replay payload does not match manifest");
213
+ }
214
+ return {
215
+ bundleDir,
216
+ manifestPath,
217
+ replayEvidencePath,
218
+ logPath,
219
+ manifest,
220
+ replayEvidence
221
+ };
222
+ };
223
+ var discoverRuntimeFeedbackReplayBundles = async (rootDir) => {
224
+ const bundles = [];
225
+ const visit = async (directory, depth) => {
226
+ if (depth > 10) return;
227
+ let entries;
228
+ try {
229
+ entries = await import_promises3.default.readdir(directory, { withFileTypes: true });
230
+ } catch (error) {
231
+ if (error.code === "ENOENT") return;
232
+ throw error;
233
+ }
234
+ const names = new Set(entries.map((entry) => entry.name));
235
+ if (names.has(RUNTIME_FEEDBACK_MANIFEST_FILE) && names.has(RUNTIME_FEEDBACK_REPLAY_FILE) && names.has(RUNTIME_FEEDBACK_LOG_FILE) && names.has(RUNTIME_FEEDBACK_COMPLETE_FILE)) {
236
+ bundles.push(directory);
237
+ return;
238
+ }
239
+ await Promise.all(
240
+ entries.filter(
241
+ (entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
242
+ ).map((entry) => visit(import_node_path3.default.join(directory, entry.name), depth + 1))
243
+ );
244
+ };
245
+ await visit(rootDir, 0);
246
+ return bundles.sort();
247
+ };
248
+
249
+ // src/lib/runtimeEvidenceSync.ts
250
+ var import_node_child_process = require("child_process");
251
+ var import_promises4 = __toESM(require("fs/promises"));
252
+ var import_node_path4 = __toESM(require("path"));
253
+ var import_node_util = require("util");
254
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
255
+ var withTrailingSlash = (value) => value.endsWith("/") ? value : `${value}/`;
256
+ var buildRuntimeEvidenceRsyncArgs = ({
257
+ source,
258
+ destination
259
+ }) => [
260
+ "--recursive",
261
+ "--times",
262
+ "--partial",
263
+ "--partial-dir=.rsync-partial",
264
+ "--prune-empty-dirs",
265
+ withTrailingSlash(source),
266
+ withTrailingSlash(destination)
267
+ ];
268
+
269
+ // src/lib/runtimeFeedbackSync.ts
270
+ var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process2.execFile);
271
+ var isExistingDestinationError = (error) => {
272
+ const code = error.code;
273
+ return code === "EEXIST" || code === "ENOTEMPTY";
274
+ };
275
+ var safeSegment = (value, fallback) => {
276
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
277
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
278
+ };
279
+ var dateParts = (timestamp) => {
280
+ const date = new Date(timestamp);
281
+ return [
282
+ String(date.getUTCFullYear()),
283
+ String(date.getUTCMonth() + 1).padStart(2, "0"),
284
+ String(date.getUTCDate()).padStart(2, "0")
285
+ ];
286
+ };
287
+ var syncRuntimeFeedbackReplayBundles = async ({
288
+ source,
289
+ feedbackRoot,
290
+ deploymentId,
291
+ runRsync = async (args) => {
292
+ const result = await execFileAsync2("rsync", args, {
293
+ maxBuffer: 10 * 1024 * 1024
294
+ });
295
+ return { stdout: result.stdout, stderr: result.stderr };
296
+ }
297
+ }) => {
298
+ const safeDeploymentId = safeSegment(deploymentId, "production");
299
+ const inboxRoot = import_node_path5.default.join(feedbackRoot, "inbox", safeDeploymentId);
300
+ const artifactsRoot = import_node_path5.default.join(feedbackRoot, "artifacts", safeDeploymentId);
301
+ await Promise.all([
302
+ import_promises5.default.mkdir(inboxRoot, { recursive: true }),
303
+ import_promises5.default.mkdir(artifactsRoot, { recursive: true })
304
+ ]);
305
+ const rsyncArgs = buildRuntimeEvidenceRsyncArgs({
306
+ source,
307
+ destination: inboxRoot
308
+ });
309
+ const transfer = await runRsync(rsyncArgs);
310
+ const discovered = await discoverRuntimeFeedbackReplayBundles(inboxRoot);
311
+ const received = [];
312
+ for (const bundleDir of discovered) {
313
+ const verified = await verifyRuntimeFeedbackReplayBundle(bundleDir);
314
+ if (verified.manifest.deploymentId !== safeDeploymentId) {
315
+ throw new Error(
316
+ `Runtime feedback deployment mismatch: expected ${safeDeploymentId}, received ${verified.manifest.deploymentId}`
317
+ );
318
+ }
319
+ const destinationDir = import_node_path5.default.join(
320
+ artifactsRoot,
321
+ ...dateParts(verified.manifest.window.endTime),
322
+ safeSegment(verified.manifest.runtimeEvidence.artifactId, "artifact"),
323
+ safeSegment(verified.manifest.runId, "run")
324
+ );
325
+ await import_promises5.default.mkdir(import_node_path5.default.dirname(destinationDir), { recursive: true });
326
+ try {
327
+ await import_promises5.default.rename(bundleDir, destinationDir);
328
+ } catch (error) {
329
+ if (!isExistingDestinationError(error)) throw error;
330
+ const existing = await verifyRuntimeFeedbackReplayBundle(destinationDir);
331
+ if (existing.manifest.payloads.replayEvidence.sha256 !== verified.manifest.payloads.replayEvidence.sha256) {
332
+ throw new Error(
333
+ `Conflicting runtime feedback replay ${verified.manifest.artifactId}`
334
+ );
335
+ }
336
+ await import_promises5.default.rm(bundleDir, { recursive: true, force: true });
337
+ }
338
+ received.push(await verifyRuntimeFeedbackReplayBundle(destinationDir));
339
+ }
340
+ return {
341
+ rsyncArgs,
342
+ stdout: String(transfer.stdout ?? ""),
343
+ stderr: String(transfer.stderr ?? ""),
344
+ received
345
+ };
346
+ };
347
+ // Annotate the CommonJS export names for ESM import in node:
348
+ 0 && (module.exports = {
349
+ syncRuntimeFeedbackReplayBundles
350
+ });
@@ -4888,12 +4888,15 @@ var getReplayRuntimeUnmatchedCount = (row) => row.orderFailed + row.runtimeOnly
4888
4888
  var buildReplayStrategyConfig = ({
4889
4889
  strategyConfig,
4890
4890
  interval
4891
- }) => buildRuntimeModeStrategyConfig({
4892
- strategyConfig,
4893
- env: "PARITY",
4894
- interval,
4895
- makeOrders: true,
4896
- recordRuntimeTrades: false
4891
+ }) => ({
4892
+ ...buildRuntimeModeStrategyConfig({
4893
+ strategyConfig,
4894
+ env: "PARITY",
4895
+ interval,
4896
+ makeOrders: false,
4897
+ recordRuntimeTrades: false
4898
+ }),
4899
+ SIMULATE_ORDERS: true
4897
4900
  });
4898
4901
  var toRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
4899
4902
  var compactReplayAdditionalIndicators = (additionalIndicators) => {
@@ -4891,12 +4891,15 @@ var getReplayRuntimeUnmatchedCount = (row) => row.orderFailed + row.runtimeOnly
4891
4891
  var buildReplayStrategyConfig = ({
4892
4892
  strategyConfig,
4893
4893
  interval
4894
- }) => buildRuntimeModeStrategyConfig({
4895
- strategyConfig,
4896
- env: "PARITY",
4897
- interval,
4898
- makeOrders: true,
4899
- recordRuntimeTrades: false
4894
+ }) => ({
4895
+ ...buildRuntimeModeStrategyConfig({
4896
+ strategyConfig,
4897
+ env: "PARITY",
4898
+ interval,
4899
+ makeOrders: false,
4900
+ recordRuntimeTrades: false
4901
+ }),
4902
+ SIMULATE_ORDERS: true
4900
4903
  });
4901
4904
  var toRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
4902
4905
  var compactReplayAdditionalIndicators = (additionalIndicators) => {
@@ -728,6 +728,10 @@ var replayRuntimeEvidence = async () => {
728
728
  availableKeys: replay.availableKeys,
729
729
  startedAt: replayValue.startedAt ?? null,
730
730
  finishedAt: replayValue.finishedAt ?? null,
731
+ durationSeconds: replayValue.durationSeconds ?? null,
732
+ cycleCount: replayValue.cycleCount ?? null,
733
+ abortedCycles: replayValue.abortedCycles ?? null,
734
+ signalsCount: replayValue.signalsCount ?? null,
731
735
  resultsByStrategies: asArray(replayValue.resultsByStrategies).filter(
732
736
  (row) => !strategies.length || strategies.includes(String(row.strategyName ?? ""))
733
737
  ),
@@ -34,8 +34,8 @@ __export(runtimeEvidence_exports, {
34
34
  runtimeEvidence: () => runtimeEvidence
35
35
  });
36
36
  module.exports = __toCommonJS(runtimeEvidence_exports);
37
- var import_promises2 = __toESM(require("fs/promises"));
38
- var import_node_path2 = __toESM(require("path"));
37
+ var import_promises3 = __toESM(require("fs/promises"));
38
+ var import_node_path3 = __toESM(require("path"));
39
39
  var import_args = __toESM(require("args"));
40
40
  var import_chalk = __toESM(require("chalk"));
41
41
 
@@ -874,6 +874,56 @@ var runtimeLineageKey = (lineage) => [
874
874
  lineage.runtimePackageVersion
875
875
  ].join(":");
876
876
 
877
+ // src/lib/runtimeEvidenceProducer.ts
878
+ var import_node_crypto3 = require("crypto");
879
+ var import_promises2 = __toESM(require("fs/promises"));
880
+ var import_node_path2 = __toESM(require("path"));
881
+ var sha2562 = (value) => (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex");
882
+ var resolveRuntimeEvidenceProducer = async ({
883
+ projectRoot: projectRoot2,
884
+ required
885
+ }) => {
886
+ const projectSha = String(process.env.TRADEJS_PROJECT_SHA ?? "").trim();
887
+ const imageDigest = String(
888
+ process.env.TRADEJS_PROJECT_IMAGE_DIGEST ?? ""
889
+ ).trim();
890
+ if (!projectSha && !imageDigest && !required) {
891
+ return null;
892
+ }
893
+ if (!/^[a-f0-9]{40}$/.test(projectSha)) {
894
+ throw new Error(
895
+ "TRADEJS_PROJECT_SHA must be a full lowercase Git SHA before publishing runtime evidence"
896
+ );
897
+ }
898
+ if (!/^sha256:[a-f0-9]{64}$/.test(imageDigest)) {
899
+ throw new Error(
900
+ "TRADEJS_PROJECT_IMAGE_DIGEST must be an immutable sha256 digest before publishing runtime evidence"
901
+ );
902
+ }
903
+ const manifestPath = import_node_path2.default.join(projectRoot2, "runtime-package-manifest.json");
904
+ let manifest;
905
+ try {
906
+ manifest = await import_promises2.default.readFile(manifestPath);
907
+ } catch (error) {
908
+ if (!required && error.code === "ENOENT") {
909
+ return null;
910
+ }
911
+ throw new Error(
912
+ `Runtime package manifest is required for runtime evidence: ${manifestPath}`,
913
+ { cause: error }
914
+ );
915
+ }
916
+ return {
917
+ schemaVersion: 1,
918
+ projectSha,
919
+ imageDigest,
920
+ runtimePackageManifest: {
921
+ file: "runtime-package-manifest.json",
922
+ sha256: sha2562(manifest)
923
+ }
924
+ };
925
+ };
926
+
877
927
  // src/scripts/runtimeEvidence.ts
878
928
  import_args.default.option(["u", "user"], "Use user config", "root");
879
929
  import_args.default.option(
@@ -954,6 +1004,11 @@ var parseStrategyFilter = (value) => String(value ?? "").split(",").map((item) =
954
1004
  var runtimeEvidence = async () => {
955
1005
  const { startTime, endTime, source } = resolveWindow();
956
1006
  const deploymentId = String(flags.deployment);
1007
+ const publishDir = String(flags.publishDir ?? "").trim();
1008
+ const producer = await resolveRuntimeEvidenceProducer({
1009
+ projectRoot,
1010
+ required: Boolean(publishDir)
1011
+ });
957
1012
  const deploymentSnapshot = await resolveRuntimeEvidenceDeploymentSnapshot({
958
1013
  userName: String(flags.user),
959
1014
  projectRoot,
@@ -1025,6 +1080,7 @@ var runtimeEvidence = async () => {
1025
1080
  const artifact = {
1026
1081
  reportType: "runtime-evidence",
1027
1082
  generatedAt: Date.now(),
1083
+ ...producer ? { producer } : {},
1028
1084
  userName: flags.user,
1029
1085
  window: {
1030
1086
  startTime,
@@ -1037,13 +1093,12 @@ var runtimeEvidence = async () => {
1037
1093
  deployment,
1038
1094
  runtime
1039
1095
  };
1040
- const outPath = import_node_path2.default.resolve(projectRoot, String(flags.out));
1041
- await import_promises2.default.mkdir(import_node_path2.default.dirname(outPath), { recursive: true });
1042
- await import_promises2.default.writeFile(outPath, `${JSON.stringify(artifact, null, 2)}
1096
+ const outPath = import_node_path3.default.resolve(projectRoot, String(flags.out));
1097
+ await import_promises3.default.mkdir(import_node_path3.default.dirname(outPath), { recursive: true });
1098
+ await import_promises3.default.writeFile(outPath, `${JSON.stringify(artifact, null, 2)}
1043
1099
  `, "utf8");
1044
- const publishDir = String(flags.publishDir ?? "").trim();
1045
1100
  const published = publishDir ? await publishRuntimeEvidenceBundle({
1046
- publishRoot: import_node_path2.default.resolve(projectRoot, publishDir),
1101
+ publishRoot: import_node_path3.default.resolve(projectRoot, publishDir),
1047
1102
  deploymentId,
1048
1103
  userName: String(flags.user),
1049
1104
  startTime,