@tradejs/cli 2.0.15 → 2.0.17

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,255 @@
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/runtimeEvidenceArtifacts.ts
31
+ var runtimeEvidenceArtifacts_exports = {};
32
+ __export(runtimeEvidenceArtifacts_exports, {
33
+ RUNTIME_EVIDENCE_COMPLETE_FILE: () => RUNTIME_EVIDENCE_COMPLETE_FILE,
34
+ RUNTIME_EVIDENCE_MANIFEST_FILE: () => RUNTIME_EVIDENCE_MANIFEST_FILE,
35
+ RUNTIME_EVIDENCE_PAYLOAD_FILE: () => RUNTIME_EVIDENCE_PAYLOAD_FILE,
36
+ discoverRuntimeEvidenceBundles: () => discoverRuntimeEvidenceBundles,
37
+ publishRuntimeEvidenceBundle: () => publishRuntimeEvidenceBundle,
38
+ verifyRuntimeEvidenceBundle: () => verifyRuntimeEvidenceBundle
39
+ });
40
+ module.exports = __toCommonJS(runtimeEvidenceArtifacts_exports);
41
+ var import_node_crypto = require("crypto");
42
+ var import_promises = __toESM(require("fs/promises"));
43
+ var import_node_path = __toESM(require("path"));
44
+ var RUNTIME_EVIDENCE_MANIFEST_FILE = "manifest.json";
45
+ var RUNTIME_EVIDENCE_PAYLOAD_FILE = "runtime-evidence.json";
46
+ var RUNTIME_EVIDENCE_COMPLETE_FILE = ".complete";
47
+ var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
48
+ var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
49
+ var isExistingDestinationError = (error) => {
50
+ const code = error.code;
51
+ return code === "EEXIST" || code === "ENOTEMPTY";
52
+ };
53
+ var safeSegment = (value, fallback) => {
54
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
55
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
56
+ };
57
+ var compactTimestamp = (timestamp) => new Date(timestamp).toISOString().replace(/[-:]/g, "").replace(/\.000Z$/, "Z");
58
+ var dateParts = (timestamp) => {
59
+ const date = new Date(timestamp);
60
+ return [
61
+ String(date.getUTCFullYear()),
62
+ String(date.getUTCMonth() + 1).padStart(2, "0"),
63
+ String(date.getUTCDate()).padStart(2, "0")
64
+ ];
65
+ };
66
+ var assertFiniteTimestamp = (value, label) => {
67
+ if (typeof value !== "number" || !Number.isFinite(value)) {
68
+ throw new Error(`Invalid runtime evidence ${label}`);
69
+ }
70
+ return value;
71
+ };
72
+ var parseManifest = (value) => {
73
+ const manifest = asRecord(value);
74
+ const window = asRecord(manifest?.window);
75
+ const payload = asRecord(manifest?.payload);
76
+ const counts = asRecord(manifest?.counts);
77
+ 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)) {
78
+ throw new Error("Invalid runtime evidence manifest");
79
+ }
80
+ return {
81
+ schemaVersion: 1,
82
+ artifactId: manifest.artifactId,
83
+ reportType: "runtime-evidence",
84
+ deploymentId: manifest.deploymentId,
85
+ userName: manifest.userName,
86
+ createdAt: manifest.createdAt,
87
+ window: {
88
+ startTime: assertFiniteTimestamp(window?.startTime, "window.startTime"),
89
+ endTime: assertFiniteTimestamp(window?.endTime, "window.endTime")
90
+ },
91
+ payload: {
92
+ file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
93
+ sha256: payload.sha256,
94
+ bytes: payload.bytes
95
+ },
96
+ counts: Object.fromEntries(
97
+ Object.entries(counts ?? {}).filter(
98
+ (entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])
99
+ )
100
+ ),
101
+ lineageKeys: manifest.lineageKeys.filter(
102
+ (value2) => typeof value2 === "string" && value2.length > 0
103
+ )
104
+ };
105
+ };
106
+ var publishRuntimeEvidenceBundle = async ({
107
+ publishRoot,
108
+ deploymentId,
109
+ userName,
110
+ startTime,
111
+ endTime,
112
+ artifact,
113
+ counts,
114
+ lineageKeys
115
+ }) => {
116
+ const payload = `${JSON.stringify(artifact, null, 2)}
117
+ `;
118
+ const payloadSha256 = sha256(payload);
119
+ const safeDeploymentId = safeSegment(deploymentId, "default");
120
+ const artifactId = [
121
+ compactTimestamp(startTime),
122
+ compactTimestamp(endTime),
123
+ payloadSha256.slice(0, 16)
124
+ ].join("_");
125
+ const createdAt = Date.now();
126
+ const manifest = {
127
+ schemaVersion: 1,
128
+ artifactId,
129
+ reportType: "runtime-evidence",
130
+ deploymentId: safeDeploymentId,
131
+ userName,
132
+ createdAt,
133
+ window: { startTime, endTime },
134
+ payload: {
135
+ file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
136
+ sha256: payloadSha256,
137
+ bytes: Buffer.byteLength(payload)
138
+ },
139
+ counts,
140
+ lineageKeys: [...new Set(lineageKeys)].sort()
141
+ };
142
+ const incomingRoot = import_node_path.default.join(publishRoot, "incoming");
143
+ const readyRoot = import_node_path.default.join(
144
+ publishRoot,
145
+ "ready",
146
+ safeDeploymentId,
147
+ ...dateParts(endTime)
148
+ );
149
+ const bundleDir = import_node_path.default.join(readyRoot, artifactId);
150
+ const temporaryDir = import_node_path.default.join(
151
+ incomingRoot,
152
+ `${artifactId}.tmp-${(0, import_node_crypto.randomUUID)()}`
153
+ );
154
+ await import_promises.default.mkdir(temporaryDir, { recursive: true });
155
+ try {
156
+ await Promise.all([
157
+ import_promises.default.writeFile(
158
+ import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_PAYLOAD_FILE),
159
+ payload,
160
+ "utf8"
161
+ ),
162
+ import_promises.default.writeFile(
163
+ import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_MANIFEST_FILE),
164
+ `${JSON.stringify(manifest, null, 2)}
165
+ `,
166
+ "utf8"
167
+ )
168
+ ]);
169
+ await import_promises.default.writeFile(
170
+ import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_COMPLETE_FILE),
171
+ `${artifactId}
172
+ `,
173
+ "utf8"
174
+ );
175
+ await import_promises.default.mkdir(readyRoot, { recursive: true });
176
+ try {
177
+ await import_promises.default.rename(temporaryDir, bundleDir);
178
+ } catch (error) {
179
+ if (!isExistingDestinationError(error)) {
180
+ throw error;
181
+ }
182
+ await import_promises.default.rm(temporaryDir, { recursive: true, force: true });
183
+ }
184
+ } catch (error) {
185
+ await import_promises.default.rm(temporaryDir, { recursive: true, force: true });
186
+ throw error;
187
+ }
188
+ return verifyRuntimeEvidenceBundle(bundleDir);
189
+ };
190
+ var verifyRuntimeEvidenceBundle = async (bundleDir) => {
191
+ const manifestPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_MANIFEST_FILE);
192
+ const payloadPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_PAYLOAD_FILE);
193
+ const completePath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_COMPLETE_FILE);
194
+ const [manifestText, payload, completeText] = await Promise.all([
195
+ import_promises.default.readFile(manifestPath, "utf8"),
196
+ import_promises.default.readFile(payloadPath),
197
+ import_promises.default.readFile(completePath, "utf8")
198
+ ]);
199
+ const manifest = parseManifest(JSON.parse(manifestText));
200
+ if (completeText.trim() !== manifest.artifactId) {
201
+ throw new Error(`Invalid completion marker in ${bundleDir}`);
202
+ }
203
+ if (payload.byteLength !== manifest.payload.bytes) {
204
+ throw new Error(`Runtime evidence size mismatch in ${bundleDir}`);
205
+ }
206
+ if (sha256(payload) !== manifest.payload.sha256) {
207
+ throw new Error(`Runtime evidence checksum mismatch in ${bundleDir}`);
208
+ }
209
+ const artifact = asRecord(JSON.parse(payload.toString("utf8")));
210
+ const artifactWindow = asRecord(artifact?.window);
211
+ if (artifact?.reportType !== "runtime-evidence" || artifactWindow?.startTime !== manifest.window.startTime || artifactWindow.endTime !== manifest.window.endTime) {
212
+ throw new Error(`Runtime evidence payload mismatch in ${bundleDir}`);
213
+ }
214
+ return {
215
+ bundleDir,
216
+ manifestPath,
217
+ payloadPath,
218
+ manifest,
219
+ artifact
220
+ };
221
+ };
222
+ var discoverRuntimeEvidenceBundles = async (rootDir) => {
223
+ const bundles = [];
224
+ const visit = async (directory, depth) => {
225
+ if (depth > 8) return;
226
+ let entries;
227
+ try {
228
+ entries = await import_promises.default.readdir(directory, { withFileTypes: true });
229
+ } catch (error) {
230
+ if (error.code === "ENOENT") return;
231
+ throw error;
232
+ }
233
+ const names = new Set(entries.map((entry) => entry.name));
234
+ if (names.has(RUNTIME_EVIDENCE_MANIFEST_FILE) && names.has(RUNTIME_EVIDENCE_PAYLOAD_FILE) && names.has(RUNTIME_EVIDENCE_COMPLETE_FILE)) {
235
+ bundles.push(directory);
236
+ return;
237
+ }
238
+ await Promise.all(
239
+ entries.filter(
240
+ (entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
241
+ ).map((entry) => visit(import_node_path.default.join(directory, entry.name), depth + 1))
242
+ );
243
+ };
244
+ await visit(rootDir, 0);
245
+ return bundles.sort();
246
+ };
247
+ // Annotate the CommonJS export names for ESM import in node:
248
+ 0 && (module.exports = {
249
+ RUNTIME_EVIDENCE_COMPLETE_FILE,
250
+ RUNTIME_EVIDENCE_MANIFEST_FILE,
251
+ RUNTIME_EVIDENCE_PAYLOAD_FILE,
252
+ discoverRuntimeEvidenceBundles,
253
+ publishRuntimeEvidenceBundle,
254
+ verifyRuntimeEvidenceBundle
255
+ });
@@ -0,0 +1,308 @@
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/runtimeEvidenceSync.ts
31
+ var runtimeEvidenceSync_exports = {};
32
+ __export(runtimeEvidenceSync_exports, {
33
+ buildRuntimeEvidenceRsyncArgs: () => buildRuntimeEvidenceRsyncArgs,
34
+ listPendingRuntimeEvidenceBundles: () => listPendingRuntimeEvidenceBundles,
35
+ markRuntimeEvidenceBundleProcessed: () => markRuntimeEvidenceBundleProcessed,
36
+ syncRuntimeEvidenceBundles: () => syncRuntimeEvidenceBundles
37
+ });
38
+ module.exports = __toCommonJS(runtimeEvidenceSync_exports);
39
+ var import_node_child_process = require("child_process");
40
+ var import_promises2 = __toESM(require("fs/promises"));
41
+ var import_node_path2 = __toESM(require("path"));
42
+ var import_node_util = require("util");
43
+
44
+ // src/lib/runtimeEvidenceArtifacts.ts
45
+ var import_node_crypto = require("crypto");
46
+ var import_promises = __toESM(require("fs/promises"));
47
+ var import_node_path = __toESM(require("path"));
48
+ var RUNTIME_EVIDENCE_MANIFEST_FILE = "manifest.json";
49
+ var RUNTIME_EVIDENCE_PAYLOAD_FILE = "runtime-evidence.json";
50
+ var RUNTIME_EVIDENCE_COMPLETE_FILE = ".complete";
51
+ var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
52
+ var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
53
+ var assertFiniteTimestamp = (value, label) => {
54
+ if (typeof value !== "number" || !Number.isFinite(value)) {
55
+ throw new Error(`Invalid runtime evidence ${label}`);
56
+ }
57
+ return value;
58
+ };
59
+ var parseManifest = (value) => {
60
+ const manifest = asRecord(value);
61
+ const window = asRecord(manifest?.window);
62
+ const payload = asRecord(manifest?.payload);
63
+ const counts = asRecord(manifest?.counts);
64
+ 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)) {
65
+ throw new Error("Invalid runtime evidence manifest");
66
+ }
67
+ return {
68
+ schemaVersion: 1,
69
+ artifactId: manifest.artifactId,
70
+ reportType: "runtime-evidence",
71
+ deploymentId: manifest.deploymentId,
72
+ userName: manifest.userName,
73
+ createdAt: manifest.createdAt,
74
+ window: {
75
+ startTime: assertFiniteTimestamp(window?.startTime, "window.startTime"),
76
+ endTime: assertFiniteTimestamp(window?.endTime, "window.endTime")
77
+ },
78
+ payload: {
79
+ file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
80
+ sha256: payload.sha256,
81
+ bytes: payload.bytes
82
+ },
83
+ counts: Object.fromEntries(
84
+ Object.entries(counts ?? {}).filter(
85
+ (entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])
86
+ )
87
+ ),
88
+ lineageKeys: manifest.lineageKeys.filter(
89
+ (value2) => typeof value2 === "string" && value2.length > 0
90
+ )
91
+ };
92
+ };
93
+ var verifyRuntimeEvidenceBundle = async (bundleDir) => {
94
+ const manifestPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_MANIFEST_FILE);
95
+ const payloadPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_PAYLOAD_FILE);
96
+ const completePath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_COMPLETE_FILE);
97
+ const [manifestText, payload, completeText] = await Promise.all([
98
+ import_promises.default.readFile(manifestPath, "utf8"),
99
+ import_promises.default.readFile(payloadPath),
100
+ import_promises.default.readFile(completePath, "utf8")
101
+ ]);
102
+ const manifest = parseManifest(JSON.parse(manifestText));
103
+ if (completeText.trim() !== manifest.artifactId) {
104
+ throw new Error(`Invalid completion marker in ${bundleDir}`);
105
+ }
106
+ if (payload.byteLength !== manifest.payload.bytes) {
107
+ throw new Error(`Runtime evidence size mismatch in ${bundleDir}`);
108
+ }
109
+ if (sha256(payload) !== manifest.payload.sha256) {
110
+ throw new Error(`Runtime evidence checksum mismatch in ${bundleDir}`);
111
+ }
112
+ const artifact = asRecord(JSON.parse(payload.toString("utf8")));
113
+ const artifactWindow = asRecord(artifact?.window);
114
+ if (artifact?.reportType !== "runtime-evidence" || artifactWindow?.startTime !== manifest.window.startTime || artifactWindow.endTime !== manifest.window.endTime) {
115
+ throw new Error(`Runtime evidence payload mismatch in ${bundleDir}`);
116
+ }
117
+ return {
118
+ bundleDir,
119
+ manifestPath,
120
+ payloadPath,
121
+ manifest,
122
+ artifact
123
+ };
124
+ };
125
+ var discoverRuntimeEvidenceBundles = async (rootDir) => {
126
+ const bundles = [];
127
+ const visit = async (directory, depth) => {
128
+ if (depth > 8) return;
129
+ let entries;
130
+ try {
131
+ entries = await import_promises.default.readdir(directory, { withFileTypes: true });
132
+ } catch (error) {
133
+ if (error.code === "ENOENT") return;
134
+ throw error;
135
+ }
136
+ const names = new Set(entries.map((entry) => entry.name));
137
+ if (names.has(RUNTIME_EVIDENCE_MANIFEST_FILE) && names.has(RUNTIME_EVIDENCE_PAYLOAD_FILE) && names.has(RUNTIME_EVIDENCE_COMPLETE_FILE)) {
138
+ bundles.push(directory);
139
+ return;
140
+ }
141
+ await Promise.all(
142
+ entries.filter(
143
+ (entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
144
+ ).map((entry) => visit(import_node_path.default.join(directory, entry.name), depth + 1))
145
+ );
146
+ };
147
+ await visit(rootDir, 0);
148
+ return bundles.sort();
149
+ };
150
+
151
+ // src/lib/runtimeEvidenceSync.ts
152
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
153
+ var isExistingDestinationError = (error) => {
154
+ const code = error.code;
155
+ return code === "EEXIST" || code === "ENOTEMPTY";
156
+ };
157
+ var safeSegment = (value, fallback) => {
158
+ const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
159
+ return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
160
+ };
161
+ var withTrailingSlash = (value) => value.endsWith("/") ? value : `${value}/`;
162
+ var dateParts = (timestamp) => {
163
+ const date = new Date(timestamp);
164
+ return [
165
+ String(date.getUTCFullYear()),
166
+ String(date.getUTCMonth() + 1).padStart(2, "0"),
167
+ String(date.getUTCDate()).padStart(2, "0")
168
+ ];
169
+ };
170
+ var buildRuntimeEvidenceRsyncArgs = ({
171
+ source,
172
+ destination
173
+ }) => [
174
+ "--recursive",
175
+ "--times",
176
+ "--partial",
177
+ "--partial-dir=.rsync-partial",
178
+ "--prune-empty-dirs",
179
+ withTrailingSlash(source),
180
+ withTrailingSlash(destination)
181
+ ];
182
+ var receiptPath = (receiptsRoot, artifactId) => import_node_path2.default.join(receiptsRoot, `${safeSegment(artifactId, "artifact")}.json`);
183
+ var listPendingRuntimeEvidenceBundles = async ({
184
+ evidenceRoot,
185
+ deploymentId
186
+ }) => {
187
+ const safeDeploymentId = safeSegment(deploymentId, "production");
188
+ const artifactsRoot = import_node_path2.default.join(evidenceRoot, "artifacts", safeDeploymentId);
189
+ const receiptsRoot = import_node_path2.default.join(evidenceRoot, "receipts", safeDeploymentId);
190
+ const bundles = await discoverRuntimeEvidenceBundles(artifactsRoot);
191
+ const pending = [];
192
+ for (const bundleDir of bundles) {
193
+ const verified = await verifyRuntimeEvidenceBundle(bundleDir);
194
+ if (verified.manifest.deploymentId !== safeDeploymentId) continue;
195
+ try {
196
+ await import_promises2.default.access(receiptPath(receiptsRoot, verified.manifest.artifactId));
197
+ } catch (error) {
198
+ if (error.code !== "ENOENT") throw error;
199
+ pending.push(verified);
200
+ }
201
+ }
202
+ return pending.sort(
203
+ (left, right) => left.manifest.window.startTime - right.manifest.window.startTime || left.manifest.createdAt - right.manifest.createdAt
204
+ );
205
+ };
206
+ var markRuntimeEvidenceBundleProcessed = async ({
207
+ evidenceRoot,
208
+ deploymentId,
209
+ bundleDir,
210
+ scorecardPath
211
+ }) => {
212
+ const safeDeploymentId = safeSegment(deploymentId, "production");
213
+ const verified = await verifyRuntimeEvidenceBundle(bundleDir);
214
+ if (verified.manifest.deploymentId !== safeDeploymentId) {
215
+ throw new Error(
216
+ `Artifact deployment mismatch: expected ${safeDeploymentId}, received ${verified.manifest.deploymentId}`
217
+ );
218
+ }
219
+ const receiptsRoot = import_node_path2.default.join(evidenceRoot, "receipts", safeDeploymentId);
220
+ const finalPath = receiptPath(receiptsRoot, verified.manifest.artifactId);
221
+ const temporaryPath = `${finalPath}.tmp-${process.pid}`;
222
+ const receipt = {
223
+ schemaVersion: 1,
224
+ artifactId: verified.manifest.artifactId,
225
+ payloadSha256: verified.manifest.payload.sha256,
226
+ processedAt: Date.now(),
227
+ scorecardPath: scorecardPath ?? null
228
+ };
229
+ await import_promises2.default.mkdir(receiptsRoot, { recursive: true });
230
+ await import_promises2.default.writeFile(
231
+ temporaryPath,
232
+ `${JSON.stringify(receipt, null, 2)}
233
+ `,
234
+ "utf8"
235
+ );
236
+ await import_promises2.default.rename(temporaryPath, finalPath);
237
+ return finalPath;
238
+ };
239
+ var syncRuntimeEvidenceBundles = async ({
240
+ source,
241
+ evidenceRoot,
242
+ deploymentId,
243
+ runRsync = async (args) => {
244
+ const result = await execFileAsync("rsync", args, {
245
+ maxBuffer: 10 * 1024 * 1024
246
+ });
247
+ return { stdout: result.stdout, stderr: result.stderr };
248
+ }
249
+ }) => {
250
+ const safeDeploymentId = safeSegment(deploymentId, "production");
251
+ const inboxRoot = import_node_path2.default.join(evidenceRoot, "inbox", safeDeploymentId);
252
+ const artifactsRoot = import_node_path2.default.join(evidenceRoot, "artifacts", safeDeploymentId);
253
+ await Promise.all([
254
+ import_promises2.default.mkdir(inboxRoot, { recursive: true }),
255
+ import_promises2.default.mkdir(artifactsRoot, { recursive: true })
256
+ ]);
257
+ const rsyncArgs = buildRuntimeEvidenceRsyncArgs({
258
+ source,
259
+ destination: inboxRoot
260
+ });
261
+ const transfer = await runRsync(rsyncArgs);
262
+ const discovered = await discoverRuntimeEvidenceBundles(inboxRoot);
263
+ const received = [];
264
+ for (const bundleDir of discovered) {
265
+ const verified = await verifyRuntimeEvidenceBundle(bundleDir);
266
+ if (verified.manifest.deploymentId !== safeDeploymentId) {
267
+ throw new Error(
268
+ `Artifact deployment mismatch: expected ${safeDeploymentId}, received ${verified.manifest.deploymentId}`
269
+ );
270
+ }
271
+ const destinationDir = import_node_path2.default.join(
272
+ artifactsRoot,
273
+ ...dateParts(verified.manifest.window.endTime),
274
+ safeSegment(verified.manifest.artifactId, "artifact")
275
+ );
276
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(destinationDir), { recursive: true });
277
+ try {
278
+ await import_promises2.default.rename(bundleDir, destinationDir);
279
+ } catch (error) {
280
+ if (!isExistingDestinationError(error)) throw error;
281
+ const existing = await verifyRuntimeEvidenceBundle(destinationDir);
282
+ if (existing.manifest.payload.sha256 !== verified.manifest.payload.sha256) {
283
+ throw new Error(
284
+ `Conflicting runtime evidence artifact ${verified.manifest.artifactId}`
285
+ );
286
+ }
287
+ await import_promises2.default.rm(bundleDir, { recursive: true, force: true });
288
+ }
289
+ received.push(await verifyRuntimeEvidenceBundle(destinationDir));
290
+ }
291
+ return {
292
+ rsyncArgs,
293
+ stdout: String(transfer.stdout ?? ""),
294
+ stderr: String(transfer.stderr ?? ""),
295
+ received,
296
+ pending: await listPendingRuntimeEvidenceBundles({
297
+ evidenceRoot,
298
+ deploymentId: safeDeploymentId
299
+ })
300
+ };
301
+ };
302
+ // Annotate the CommonJS export names for ESM import in node:
303
+ 0 && (module.exports = {
304
+ buildRuntimeEvidenceRsyncArgs,
305
+ listPendingRuntimeEvidenceBundles,
306
+ markRuntimeEvidenceBundleProcessed,
307
+ syncRuntimeEvidenceBundles
308
+ });
@@ -24,6 +24,7 @@ __export(runtimeRedis_exports, {
24
24
  isRuntimeStrategyEnabled: () => isRuntimeStrategyEnabled,
25
25
  isRuntimeTradeRecord: () => isRuntimeTradeRecord,
26
26
  loadRuntimeActiveTradeOrderIds: () => loadRuntimeActiveTradeOrderIds,
27
+ loadRuntimeClosedTrades: () => loadRuntimeClosedTrades,
27
28
  loadRuntimeStrategyConfigs: () => loadRuntimeStrategyConfigs,
28
29
  loadRuntimeStrategyNames: () => loadRuntimeStrategyNames,
29
30
  loadRuntimeTrades: () => loadRuntimeTrades,
@@ -132,6 +133,29 @@ var loadRuntimeTrades = async (userName, {
132
133
  const trades = await Promise.all(keys.map((key) => (0, import_redis.getData)(key, null)));
133
134
  return trades.filter(isRuntimeTradeRecord).filter(filterByWindow).sort((left, right) => left.entryTimestamp - right.entryTimestamp);
134
135
  };
136
+ var loadRuntimeClosedTrades = async (userName, {
137
+ startTime,
138
+ endTime
139
+ }) => {
140
+ const dayKeys = (0, import_time.getRuntimeStorageDayKeys)(startTime, endTime);
141
+ const trades = (await Promise.all(
142
+ dayKeys.map(
143
+ (dayKey) => (0, import_redis.getHashJsonValues)(
144
+ import_redis.redisKeys.runtimeClosedTradeBucket(userName, dayKey)
145
+ )
146
+ )
147
+ )).flat();
148
+ const deduped = /* @__PURE__ */ new Map();
149
+ for (const trade of trades) {
150
+ if (!isRuntimeTradeRecord(trade) || trade.status !== "closed" || !Number.isFinite(trade.exitTimestamp) || trade.exitTimestamp < startTime || trade.exitTimestamp >= endTime) {
151
+ continue;
152
+ }
153
+ deduped.set(trade.orderId, trade);
154
+ }
155
+ return [...deduped.values()].sort(
156
+ (left, right) => left.exitTimestamp - right.exitTimestamp
157
+ );
158
+ };
135
159
  var loadRuntimeActiveTradeOrderIds = async (userName) => {
136
160
  const keys = await (0, import_redis.getKeys)(import_redis.redisKeys.runtimeActiveTrades(userName));
137
161
  const refs = await Promise.all(keys.map((key) => (0, import_redis.getData)(key, null)));
@@ -159,6 +183,7 @@ var loadStrategyResultSymbols = async ({
159
183
  isRuntimeStrategyEnabled,
160
184
  isRuntimeTradeRecord,
161
185
  loadRuntimeActiveTradeOrderIds,
186
+ loadRuntimeClosedTrades,
162
187
  loadRuntimeStrategyConfigs,
163
188
  loadRuntimeStrategyNames,
164
189
  loadRuntimeTrades,