@tradejs/node 3.1.29-beta.261 → 3.1.29-beta.263
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.
- package/dist/backtest.js +189 -75
- package/dist/backtest.mjs +3 -3
- package/dist/{chunk-ZZQLTUTP.mjs → chunk-GHSLOJLE.mjs} +195 -69
- package/dist/chunk-JQOLTLEY.mjs +0 -0
- package/dist/{chunk-WGL7XJ3W.mjs → chunk-SKY2HNZU.mjs} +1 -1
- package/dist/{chunk-3BBXGZ7M.mjs → chunk-YR55Q355.mjs} +11 -11
- package/dist/chunk-ZUMUI37V.mjs +0 -0
- package/dist/connectors.mjs +1 -0
- package/dist/diagnostics.d.mts +182 -0
- package/dist/diagnostics.d.ts +182 -0
- package/dist/diagnostics.js +9060 -0
- package/dist/diagnostics.mjs +867 -0
- package/dist/jev.d.mts +64 -69
- package/dist/jev.d.ts +64 -69
- package/dist/jev.js +193 -75
- package/dist/jev.mjs +6 -2
- package/dist/{jevTraining-JYXUVAZG.mjs → jevTraining-J4Y4VCM4.mjs} +1 -1
- package/dist/mcp.d.mts +203 -0
- package/dist/mcp.d.ts +203 -0
- package/dist/mcp.js +9257 -0
- package/dist/mcp.mjs +584 -0
- package/dist/registry.js +189 -75
- package/dist/registry.mjs +4 -3
- package/dist/runtimeDashboard.js +189 -75
- package/dist/runtimeDashboard.mjs +7 -7
- package/dist/runtimeStrategies.js +189 -75
- package/dist/runtimeStrategies.mjs +3 -3
- package/dist/strategies.js +189 -75
- package/dist/strategies.mjs +3 -3
- package/package.json +17 -6
|
@@ -0,0 +1,867 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getRuntimeDeployment,
|
|
3
|
+
loadResolvedRuntimeStrategies
|
|
4
|
+
} from "./chunk-BO42QWAB.mjs";
|
|
5
|
+
import "./chunk-SKY2HNZU.mjs";
|
|
6
|
+
import "./chunk-UL5Z46JL.mjs";
|
|
7
|
+
import "./chunk-LZDXRXIU.mjs";
|
|
8
|
+
import "./chunk-YR55Q355.mjs";
|
|
9
|
+
import "./chunk-GHSLOJLE.mjs";
|
|
10
|
+
import "./chunk-Y6FXYEAI.mjs";
|
|
11
|
+
|
|
12
|
+
// src/diagnostics/runtimeEvidenceArtifacts.ts
|
|
13
|
+
import { createHash, randomUUID } from "crypto";
|
|
14
|
+
import fs from "fs/promises";
|
|
15
|
+
import path from "path";
|
|
16
|
+
|
|
17
|
+
// src/diagnostics/runtimeEvidenceDeployment.ts
|
|
18
|
+
var isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
|
|
19
|
+
var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
|
|
20
|
+
var isPackageVersionMap = (value) => isRecord(value) && Object.keys(value).length > 0 && Object.entries(value).every(
|
|
21
|
+
([name, version]) => name.startsWith("@tradejs/") && isNonEmptyString(version)
|
|
22
|
+
);
|
|
23
|
+
var INTERVALS = /* @__PURE__ */ new Set([
|
|
24
|
+
"1",
|
|
25
|
+
"3",
|
|
26
|
+
"5",
|
|
27
|
+
"15",
|
|
28
|
+
"30",
|
|
29
|
+
"60",
|
|
30
|
+
"120",
|
|
31
|
+
"240",
|
|
32
|
+
"360",
|
|
33
|
+
"720",
|
|
34
|
+
"D",
|
|
35
|
+
"W",
|
|
36
|
+
"M"
|
|
37
|
+
]);
|
|
38
|
+
var UNIVERSES = /* @__PURE__ */ new Set(["crypto", "tradfi"]);
|
|
39
|
+
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));
|
|
40
|
+
var samePackageVersions = (left, right) => {
|
|
41
|
+
if (!left || !right) return false;
|
|
42
|
+
const leftEntries = Object.entries(left).sort(
|
|
43
|
+
([a], [b]) => a.localeCompare(b)
|
|
44
|
+
);
|
|
45
|
+
const rightEntries = Object.entries(right).sort(
|
|
46
|
+
([a], [b]) => a.localeCompare(b)
|
|
47
|
+
);
|
|
48
|
+
return JSON.stringify(leftEntries) === JSON.stringify(rightEntries);
|
|
49
|
+
};
|
|
50
|
+
var runtimeLineageMatchesStrategySnapshot = ({
|
|
51
|
+
lineage,
|
|
52
|
+
deployment,
|
|
53
|
+
strategy
|
|
54
|
+
}) => lineage?.schemaVersion === 3 && lineage.strategyRevision === strategy.strategyRevision && lineage.deploymentCompositionId === deployment.deploymentCompositionId && lineage.strategyPackageVersion === strategy.strategyPackageVersion && lineage.runtimePackageVersion === strategy.runtimePackageVersion && samePackageVersions(
|
|
55
|
+
lineage.strategyDependencyVersions,
|
|
56
|
+
strategy.strategyDependencyVersions
|
|
57
|
+
);
|
|
58
|
+
var parseRuntimeEvidenceDeploymentSnapshot = (value) => {
|
|
59
|
+
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)) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
"Runtime evidence deployment snapshot is missing or invalid"
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const strategies = value.strategies.map((candidate) => {
|
|
65
|
+
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)) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
"Runtime evidence deployment strategy snapshot is invalid"
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (String(candidate.strategyConfig.INTERVAL) !== String(candidate.interval) || String(candidate.strategyConfig.UNIVERSE) !== String(candidate.universe)) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Runtime evidence strategy config does not match its scope: ${candidate.strategyName}`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (candidate.accountId != null && (!isNonEmptyString(candidate.accountId) || candidate.accountId !== value.accountId)) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
`Runtime evidence strategy account does not match deployment: ${candidate.strategyName}`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
return candidate;
|
|
81
|
+
});
|
|
82
|
+
const identities = /* @__PURE__ */ new Set();
|
|
83
|
+
for (const strategy of strategies) {
|
|
84
|
+
if (identities.has(strategy.strategyName)) {
|
|
85
|
+
throw new Error(
|
|
86
|
+
`Duplicate runtime evidence strategy: ${strategy.strategyName}`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
identities.add(strategy.strategyName);
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
...value,
|
|
93
|
+
strategies
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
var activeRuntimeEvidenceStrategies = (deployment) => deployment.enabled ? deployment.strategies.filter((strategy) => strategy.enabled) : [];
|
|
97
|
+
var unwrapRuntimeEvidenceRows = (value, field) => (Array.isArray(value) ? value : []).map((candidate) => {
|
|
98
|
+
const record = isRecord(candidate) ? candidate : null;
|
|
99
|
+
const nested = record && isRecord(record[field]) ? record[field] : null;
|
|
100
|
+
return nested ?? record;
|
|
101
|
+
}).filter((record) => record != null);
|
|
102
|
+
var assertCurrentRuntimeEvidenceArtifact = (artifact) => {
|
|
103
|
+
if (!isRecord(artifact) || artifact.reportType !== "runtime-evidence") {
|
|
104
|
+
throw new Error("Invalid runtime evidence artifact");
|
|
105
|
+
}
|
|
106
|
+
const deployment = parseRuntimeEvidenceDeploymentSnapshot(
|
|
107
|
+
artifact.deployment
|
|
108
|
+
);
|
|
109
|
+
const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
|
|
110
|
+
if (activeStrategies.length === 0) {
|
|
111
|
+
throw new Error("Runtime evidence deployment has no enabled strategies");
|
|
112
|
+
}
|
|
113
|
+
const runtime = isRecord(artifact.runtime) ? artifact.runtime : null;
|
|
114
|
+
if (!runtime) {
|
|
115
|
+
throw new Error("Runtime evidence payload is missing");
|
|
116
|
+
}
|
|
117
|
+
if ("strategyConfigs" in runtime) {
|
|
118
|
+
throw new Error(
|
|
119
|
+
"Runtime evidence payload contains removed strategyConfigs data"
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
if ("evaluationStatsBuckets" in runtime) {
|
|
123
|
+
throw new Error(
|
|
124
|
+
"Runtime evidence payload contains removed lineage-less evaluationStatsBuckets data"
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
const rowFields = [
|
|
128
|
+
"trades",
|
|
129
|
+
"signals",
|
|
130
|
+
"evaluations",
|
|
131
|
+
"lineageScopes"
|
|
132
|
+
];
|
|
133
|
+
for (const field of rowFields) {
|
|
134
|
+
if (!Array.isArray(runtime[field])) {
|
|
135
|
+
throw new Error(`Runtime evidence payload ${field} must be an array`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const snapshots = new Map(
|
|
139
|
+
activeStrategies.map((strategy) => [strategy.strategyName, strategy])
|
|
140
|
+
);
|
|
141
|
+
const assertRows = (label, rows, lineageField) => {
|
|
142
|
+
for (const row of rows) {
|
|
143
|
+
const strategyName = String(row.strategy ?? "").trim();
|
|
144
|
+
const strategy = snapshots.get(strategyName);
|
|
145
|
+
if (!strategy || row.deploymentId !== deployment.id || row.accountId !== deployment.accountId || !runtimeLineageMatchesStrategySnapshot({
|
|
146
|
+
lineage: isRecord(row[lineageField]) ? row[lineageField] : void 0,
|
|
147
|
+
deployment,
|
|
148
|
+
strategy
|
|
149
|
+
})) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
`Runtime evidence ${label} row is outside the current embedded deployment lineage`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
assertRows(
|
|
157
|
+
"trade",
|
|
158
|
+
unwrapRuntimeEvidenceRows(runtime.trades, "trade"),
|
|
159
|
+
"runtimeLineage"
|
|
160
|
+
);
|
|
161
|
+
assertRows(
|
|
162
|
+
"signal",
|
|
163
|
+
unwrapRuntimeEvidenceRows(runtime.signals, "signal"),
|
|
164
|
+
"runtimeLineage"
|
|
165
|
+
);
|
|
166
|
+
assertRows(
|
|
167
|
+
"evaluation",
|
|
168
|
+
unwrapRuntimeEvidenceRows(runtime.evaluations, "evaluation"),
|
|
169
|
+
"runtimeLineage"
|
|
170
|
+
);
|
|
171
|
+
assertRows(
|
|
172
|
+
"lineage scope",
|
|
173
|
+
unwrapRuntimeEvidenceRows(runtime.lineageScopes, "lineageScope"),
|
|
174
|
+
"lineage"
|
|
175
|
+
);
|
|
176
|
+
return deployment;
|
|
177
|
+
};
|
|
178
|
+
var resolveRuntimeEvidenceTickerUniverse = ({
|
|
179
|
+
deployment,
|
|
180
|
+
lineageScopes,
|
|
181
|
+
fallbackTickers
|
|
182
|
+
}) => {
|
|
183
|
+
const declaredTickers = deployment.tickers?.filter(isNonEmptyString) ?? [];
|
|
184
|
+
if (declaredTickers.length > 0) {
|
|
185
|
+
return {
|
|
186
|
+
...deployment,
|
|
187
|
+
tickers: [
|
|
188
|
+
...new Set(declaredTickers.map((ticker) => ticker.trim()))
|
|
189
|
+
].sort()
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
|
|
193
|
+
if (activeStrategies.length > 0 && activeStrategies.every((strategy) => strategy.selection?.tickers?.length)) {
|
|
194
|
+
return {
|
|
195
|
+
...deployment,
|
|
196
|
+
tickers: [
|
|
197
|
+
...new Set(
|
|
198
|
+
activeStrategies.flatMap(
|
|
199
|
+
(strategy) => strategy.selection?.tickers ?? []
|
|
200
|
+
)
|
|
201
|
+
)
|
|
202
|
+
].sort()
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
const strategiesByName = new Map(
|
|
206
|
+
activeStrategies.map((strategy) => [strategy.strategyName, strategy])
|
|
207
|
+
);
|
|
208
|
+
const tickers = /* @__PURE__ */ new Set();
|
|
209
|
+
for (const scope of lineageScopes) {
|
|
210
|
+
const strategy = strategiesByName.get(scope.strategy);
|
|
211
|
+
if (!strategy || scope.deploymentId !== deployment.id || scope.accountId !== deployment.accountId || !isNonEmptyString(scope.symbol) || !runtimeLineageMatchesStrategySnapshot({
|
|
212
|
+
lineage: scope.lineage,
|
|
213
|
+
deployment,
|
|
214
|
+
strategy
|
|
215
|
+
})) {
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
tickers.add(scope.symbol.trim());
|
|
219
|
+
}
|
|
220
|
+
if (tickers.size === 0) {
|
|
221
|
+
const verifiedFallbackTickers = fallbackTickers?.filter(isNonEmptyString) ?? [];
|
|
222
|
+
if (verifiedFallbackTickers.length > 0) {
|
|
223
|
+
return {
|
|
224
|
+
...deployment,
|
|
225
|
+
tickers: [
|
|
226
|
+
...new Set(verifiedFallbackTickers.map((ticker) => ticker.trim()))
|
|
227
|
+
].sort()
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
throw new Error(
|
|
231
|
+
"Runtime evidence has no immutable ticker universe for the embedded deployment composition"
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
return { ...deployment, tickers: [...tickers].sort() };
|
|
235
|
+
};
|
|
236
|
+
var runtimeDeploymentFromEvidence = (deployment) => ({
|
|
237
|
+
id: deployment.id,
|
|
238
|
+
deploymentCompositionId: deployment.deploymentCompositionId,
|
|
239
|
+
label: deployment.label,
|
|
240
|
+
connectorName: deployment.connectorName,
|
|
241
|
+
provider: deployment.provider,
|
|
242
|
+
accountId: deployment.accountId,
|
|
243
|
+
enabled: deployment.enabled,
|
|
244
|
+
strategies: deployment.strategies.map(
|
|
245
|
+
({ strategyName, strategyRevision, enabled, controlState, selection }) => ({
|
|
246
|
+
strategyName,
|
|
247
|
+
strategyRevision,
|
|
248
|
+
enabled,
|
|
249
|
+
controlState,
|
|
250
|
+
...selection ? { selection } : {}
|
|
251
|
+
})
|
|
252
|
+
),
|
|
253
|
+
...deployment.assetClasses ? { assetClasses: [...deployment.assetClasses] } : {},
|
|
254
|
+
...deployment.tickers ? { tickers: [...deployment.tickers] } : {}
|
|
255
|
+
});
|
|
256
|
+
var resolveRuntimeEvidenceDeploymentSnapshot = async ({
|
|
257
|
+
userName,
|
|
258
|
+
projectRoot,
|
|
259
|
+
deploymentId
|
|
260
|
+
}) => {
|
|
261
|
+
const [deployment, strategies] = await Promise.all([
|
|
262
|
+
getRuntimeDeployment({ userName, projectRoot, deploymentId }),
|
|
263
|
+
loadResolvedRuntimeStrategies({ userName, projectRoot, deploymentId })
|
|
264
|
+
]);
|
|
265
|
+
if (!deployment) {
|
|
266
|
+
throw new Error(`Runtime deployment not found: ${deploymentId}`);
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
schemaVersion: 2,
|
|
270
|
+
id: deployment.id,
|
|
271
|
+
deploymentCompositionId: deployment.deploymentCompositionId,
|
|
272
|
+
label: deployment.label,
|
|
273
|
+
connectorName: deployment.connectorName,
|
|
274
|
+
provider: deployment.provider,
|
|
275
|
+
accountId: deployment.accountId,
|
|
276
|
+
enabled: deployment.enabled,
|
|
277
|
+
strategies: strategies.map(
|
|
278
|
+
({
|
|
279
|
+
strategyName,
|
|
280
|
+
strategyRevision,
|
|
281
|
+
enabled,
|
|
282
|
+
controlState,
|
|
283
|
+
interval,
|
|
284
|
+
universe,
|
|
285
|
+
accountId,
|
|
286
|
+
strategyPackage,
|
|
287
|
+
strategyPackageVersion,
|
|
288
|
+
strategyDependencyVersions,
|
|
289
|
+
runtimePackageVersion,
|
|
290
|
+
strategyConfig,
|
|
291
|
+
selection
|
|
292
|
+
}) => ({
|
|
293
|
+
strategyName,
|
|
294
|
+
strategyRevision,
|
|
295
|
+
enabled,
|
|
296
|
+
controlState,
|
|
297
|
+
interval,
|
|
298
|
+
universe,
|
|
299
|
+
...accountId ? { accountId } : {},
|
|
300
|
+
strategyPackage,
|
|
301
|
+
strategyPackageVersion,
|
|
302
|
+
strategyDependencyVersions,
|
|
303
|
+
runtimePackageVersion,
|
|
304
|
+
strategyConfig,
|
|
305
|
+
...selection ? { selection } : {}
|
|
306
|
+
})
|
|
307
|
+
),
|
|
308
|
+
...deployment.assetClasses ? { assetClasses: [...deployment.assetClasses] } : {},
|
|
309
|
+
...deployment.tickers ? { tickers: [...deployment.tickers] } : {}
|
|
310
|
+
};
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
// src/diagnostics/runtimeEvidenceArtifacts.ts
|
|
314
|
+
var RUNTIME_EVIDENCE_MANIFEST_FILE = "manifest.json";
|
|
315
|
+
var RUNTIME_EVIDENCE_PAYLOAD_FILE = "runtime-evidence.json";
|
|
316
|
+
var RUNTIME_EVIDENCE_COMPLETE_FILE = ".complete";
|
|
317
|
+
var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
318
|
+
var sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
319
|
+
var runtimeEvidenceIdentitySha256 = (artifact) => {
|
|
320
|
+
const identityArtifact = { ...artifact };
|
|
321
|
+
delete identityArtifact.generatedAt;
|
|
322
|
+
const runtime = asRecord(identityArtifact.runtime);
|
|
323
|
+
if (runtime) {
|
|
324
|
+
const identityRuntime = { ...runtime };
|
|
325
|
+
delete identityRuntime.generatedAt;
|
|
326
|
+
identityArtifact.runtime = identityRuntime;
|
|
327
|
+
}
|
|
328
|
+
return sha256(JSON.stringify(identityArtifact));
|
|
329
|
+
};
|
|
330
|
+
var isExistingDestinationError = (error) => {
|
|
331
|
+
const code = error.code;
|
|
332
|
+
return code === "EEXIST" || code === "ENOTEMPTY";
|
|
333
|
+
};
|
|
334
|
+
var safeSegment = (value, fallback) => {
|
|
335
|
+
const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
|
|
336
|
+
return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
|
|
337
|
+
};
|
|
338
|
+
var compactTimestamp = (timestamp) => new Date(timestamp).toISOString().replace(/[-:]/g, "").replace(/\.000Z$/, "Z");
|
|
339
|
+
var dateParts = (timestamp) => {
|
|
340
|
+
const date = new Date(timestamp);
|
|
341
|
+
return [
|
|
342
|
+
String(date.getUTCFullYear()),
|
|
343
|
+
String(date.getUTCMonth() + 1).padStart(2, "0"),
|
|
344
|
+
String(date.getUTCDate()).padStart(2, "0")
|
|
345
|
+
];
|
|
346
|
+
};
|
|
347
|
+
var assertFiniteTimestamp = (value, label) => {
|
|
348
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
349
|
+
throw new Error(`Invalid runtime evidence ${label}`);
|
|
350
|
+
}
|
|
351
|
+
return value;
|
|
352
|
+
};
|
|
353
|
+
var parseManifest = (value) => {
|
|
354
|
+
const manifest = asRecord(value);
|
|
355
|
+
const window = asRecord(manifest?.window);
|
|
356
|
+
const payload = asRecord(manifest?.payload);
|
|
357
|
+
const counts = asRecord(manifest?.counts);
|
|
358
|
+
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)) {
|
|
359
|
+
throw new Error("Invalid runtime evidence manifest");
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
schemaVersion: 1,
|
|
363
|
+
artifactId: manifest.artifactId,
|
|
364
|
+
reportType: "runtime-evidence",
|
|
365
|
+
deploymentId: manifest.deploymentId,
|
|
366
|
+
userName: manifest.userName,
|
|
367
|
+
createdAt: manifest.createdAt,
|
|
368
|
+
window: {
|
|
369
|
+
startTime: assertFiniteTimestamp(window?.startTime, "window.startTime"),
|
|
370
|
+
endTime: assertFiniteTimestamp(window?.endTime, "window.endTime")
|
|
371
|
+
},
|
|
372
|
+
payload: {
|
|
373
|
+
file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
|
|
374
|
+
sha256: payload.sha256,
|
|
375
|
+
bytes: payload.bytes
|
|
376
|
+
},
|
|
377
|
+
counts: Object.fromEntries(
|
|
378
|
+
Object.entries(counts ?? {}).filter(
|
|
379
|
+
(entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])
|
|
380
|
+
)
|
|
381
|
+
),
|
|
382
|
+
lineageKeys: manifest.lineageKeys.filter(
|
|
383
|
+
(value2) => typeof value2 === "string" && value2.length > 0
|
|
384
|
+
)
|
|
385
|
+
};
|
|
386
|
+
};
|
|
387
|
+
var publishRuntimeEvidenceBundle = async ({
|
|
388
|
+
publishRoot,
|
|
389
|
+
deploymentId,
|
|
390
|
+
userName,
|
|
391
|
+
startTime,
|
|
392
|
+
endTime,
|
|
393
|
+
artifact,
|
|
394
|
+
counts,
|
|
395
|
+
lineageKeys
|
|
396
|
+
}) => {
|
|
397
|
+
assertCurrentRuntimeEvidenceArtifact(artifact);
|
|
398
|
+
const payload = `${JSON.stringify(artifact, null, 2)}
|
|
399
|
+
`;
|
|
400
|
+
const payloadSha256 = sha256(payload);
|
|
401
|
+
const identitySha256 = runtimeEvidenceIdentitySha256(artifact);
|
|
402
|
+
const safeDeploymentId = safeSegment(deploymentId, "default");
|
|
403
|
+
const artifactId = [
|
|
404
|
+
compactTimestamp(startTime),
|
|
405
|
+
compactTimestamp(endTime),
|
|
406
|
+
identitySha256.slice(0, 16)
|
|
407
|
+
].join("_");
|
|
408
|
+
const createdAt = Date.now();
|
|
409
|
+
const manifest = {
|
|
410
|
+
schemaVersion: 1,
|
|
411
|
+
artifactId,
|
|
412
|
+
reportType: "runtime-evidence",
|
|
413
|
+
deploymentId: safeDeploymentId,
|
|
414
|
+
userName,
|
|
415
|
+
createdAt,
|
|
416
|
+
window: { startTime, endTime },
|
|
417
|
+
payload: {
|
|
418
|
+
file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
|
|
419
|
+
sha256: payloadSha256,
|
|
420
|
+
bytes: Buffer.byteLength(payload)
|
|
421
|
+
},
|
|
422
|
+
counts,
|
|
423
|
+
lineageKeys: [...new Set(lineageKeys)].sort()
|
|
424
|
+
};
|
|
425
|
+
const incomingRoot = path.join(publishRoot, "incoming");
|
|
426
|
+
const readyRoot = path.join(
|
|
427
|
+
publishRoot,
|
|
428
|
+
"ready",
|
|
429
|
+
safeDeploymentId,
|
|
430
|
+
...dateParts(endTime)
|
|
431
|
+
);
|
|
432
|
+
const bundleDir = path.join(readyRoot, artifactId);
|
|
433
|
+
const temporaryDir = path.join(
|
|
434
|
+
incomingRoot,
|
|
435
|
+
`${artifactId}.tmp-${randomUUID()}`
|
|
436
|
+
);
|
|
437
|
+
await fs.mkdir(temporaryDir, { recursive: true });
|
|
438
|
+
try {
|
|
439
|
+
await Promise.all([
|
|
440
|
+
fs.writeFile(
|
|
441
|
+
path.join(temporaryDir, RUNTIME_EVIDENCE_PAYLOAD_FILE),
|
|
442
|
+
payload,
|
|
443
|
+
"utf8"
|
|
444
|
+
),
|
|
445
|
+
fs.writeFile(
|
|
446
|
+
path.join(temporaryDir, RUNTIME_EVIDENCE_MANIFEST_FILE),
|
|
447
|
+
`${JSON.stringify(manifest, null, 2)}
|
|
448
|
+
`,
|
|
449
|
+
"utf8"
|
|
450
|
+
)
|
|
451
|
+
]);
|
|
452
|
+
await fs.writeFile(
|
|
453
|
+
path.join(temporaryDir, RUNTIME_EVIDENCE_COMPLETE_FILE),
|
|
454
|
+
`${artifactId}
|
|
455
|
+
`,
|
|
456
|
+
"utf8"
|
|
457
|
+
);
|
|
458
|
+
await fs.mkdir(readyRoot, { recursive: true });
|
|
459
|
+
try {
|
|
460
|
+
await fs.rename(temporaryDir, bundleDir);
|
|
461
|
+
} catch (error) {
|
|
462
|
+
if (!isExistingDestinationError(error)) {
|
|
463
|
+
throw error;
|
|
464
|
+
}
|
|
465
|
+
await fs.rm(temporaryDir, { recursive: true, force: true });
|
|
466
|
+
}
|
|
467
|
+
} catch (error) {
|
|
468
|
+
await fs.rm(temporaryDir, { recursive: true, force: true });
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
return verifyRuntimeEvidenceBundle(bundleDir);
|
|
472
|
+
};
|
|
473
|
+
var verifyRuntimeEvidenceBundle = async (bundleDir) => {
|
|
474
|
+
const manifestPath = path.join(bundleDir, RUNTIME_EVIDENCE_MANIFEST_FILE);
|
|
475
|
+
const payloadPath = path.join(bundleDir, RUNTIME_EVIDENCE_PAYLOAD_FILE);
|
|
476
|
+
const completePath = path.join(bundleDir, RUNTIME_EVIDENCE_COMPLETE_FILE);
|
|
477
|
+
const [manifestText, payload, completeText] = await Promise.all([
|
|
478
|
+
fs.readFile(manifestPath, "utf8"),
|
|
479
|
+
fs.readFile(payloadPath),
|
|
480
|
+
fs.readFile(completePath, "utf8")
|
|
481
|
+
]);
|
|
482
|
+
const manifest = parseManifest(JSON.parse(manifestText));
|
|
483
|
+
if (completeText.trim() !== manifest.artifactId) {
|
|
484
|
+
throw new Error(`Invalid completion marker in ${bundleDir}`);
|
|
485
|
+
}
|
|
486
|
+
if (payload.byteLength !== manifest.payload.bytes) {
|
|
487
|
+
throw new Error(`Runtime evidence size mismatch in ${bundleDir}`);
|
|
488
|
+
}
|
|
489
|
+
if (sha256(payload) !== manifest.payload.sha256) {
|
|
490
|
+
throw new Error(`Runtime evidence checksum mismatch in ${bundleDir}`);
|
|
491
|
+
}
|
|
492
|
+
const artifact = asRecord(JSON.parse(payload.toString("utf8")));
|
|
493
|
+
const artifactWindow = asRecord(artifact?.window);
|
|
494
|
+
if (artifact?.reportType !== "runtime-evidence" || artifactWindow?.startTime !== manifest.window.startTime || artifactWindow.endTime !== manifest.window.endTime) {
|
|
495
|
+
throw new Error(`Runtime evidence payload mismatch in ${bundleDir}`);
|
|
496
|
+
}
|
|
497
|
+
const deployment = assertCurrentRuntimeEvidenceArtifact(artifact);
|
|
498
|
+
if (deployment.id !== manifest.deploymentId) {
|
|
499
|
+
throw new Error(`Runtime evidence deployment mismatch in ${bundleDir}`);
|
|
500
|
+
}
|
|
501
|
+
return {
|
|
502
|
+
bundleDir,
|
|
503
|
+
manifestPath,
|
|
504
|
+
payloadPath,
|
|
505
|
+
manifest,
|
|
506
|
+
artifact
|
|
507
|
+
};
|
|
508
|
+
};
|
|
509
|
+
var discoverRuntimeEvidenceBundles = async (rootDir) => {
|
|
510
|
+
const bundles = [];
|
|
511
|
+
const visit = async (directory, depth) => {
|
|
512
|
+
if (depth > 8) return;
|
|
513
|
+
let entries;
|
|
514
|
+
try {
|
|
515
|
+
entries = await fs.readdir(directory, { withFileTypes: true });
|
|
516
|
+
} catch (error) {
|
|
517
|
+
if (error.code === "ENOENT") return;
|
|
518
|
+
throw error;
|
|
519
|
+
}
|
|
520
|
+
const names = new Set(entries.map((entry) => entry.name));
|
|
521
|
+
if (names.has(RUNTIME_EVIDENCE_MANIFEST_FILE) && names.has(RUNTIME_EVIDENCE_PAYLOAD_FILE) && names.has(RUNTIME_EVIDENCE_COMPLETE_FILE)) {
|
|
522
|
+
bundles.push(directory);
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
await Promise.all(
|
|
526
|
+
entries.filter(
|
|
527
|
+
(entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
|
|
528
|
+
).map((entry) => visit(path.join(directory, entry.name), depth + 1))
|
|
529
|
+
);
|
|
530
|
+
};
|
|
531
|
+
await visit(rootDir, 0);
|
|
532
|
+
return bundles.sort();
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
// src/diagnostics/runtimeEvidenceProducer.ts
|
|
536
|
+
import { createHash as createHash2 } from "crypto";
|
|
537
|
+
import fs2 from "fs/promises";
|
|
538
|
+
import path2 from "path";
|
|
539
|
+
var isRecord2 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
|
|
540
|
+
var sha2562 = (value) => createHash2("sha256").update(value).digest("hex");
|
|
541
|
+
var parseRuntimeEvidenceProducer = (value) => {
|
|
542
|
+
const producer = isRecord2(value) ? value : null;
|
|
543
|
+
const runtimePackageManifest = isRecord2(producer?.runtimePackageManifest) ? producer.runtimePackageManifest : null;
|
|
544
|
+
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)) {
|
|
545
|
+
throw new Error("Runtime evidence producer image identity is invalid");
|
|
546
|
+
}
|
|
547
|
+
return producer;
|
|
548
|
+
};
|
|
549
|
+
var resolveRuntimeEvidenceProducer = async ({
|
|
550
|
+
projectRoot,
|
|
551
|
+
required
|
|
552
|
+
}) => {
|
|
553
|
+
const projectSha = String(process.env.TRADEJS_PROJECT_SHA ?? "").trim();
|
|
554
|
+
const imageDigest = String(
|
|
555
|
+
process.env.TRADEJS_PROJECT_IMAGE_DIGEST ?? ""
|
|
556
|
+
).trim();
|
|
557
|
+
if (!projectSha && !imageDigest && !required) {
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
if (!/^[a-f0-9]{40}$/.test(projectSha)) {
|
|
561
|
+
throw new Error(
|
|
562
|
+
"TRADEJS_PROJECT_SHA must be a full lowercase Git SHA before publishing runtime evidence"
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
if (!/^sha256:[a-f0-9]{64}$/.test(imageDigest)) {
|
|
566
|
+
throw new Error(
|
|
567
|
+
"TRADEJS_PROJECT_IMAGE_DIGEST must be an immutable sha256 digest before publishing runtime evidence"
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
const manifestPath = path2.join(projectRoot, "runtime-package-manifest.json");
|
|
571
|
+
let manifest;
|
|
572
|
+
try {
|
|
573
|
+
manifest = await fs2.readFile(manifestPath);
|
|
574
|
+
} catch (error) {
|
|
575
|
+
if (!required && error.code === "ENOENT") {
|
|
576
|
+
return null;
|
|
577
|
+
}
|
|
578
|
+
throw new Error(
|
|
579
|
+
`Runtime package manifest is required for runtime evidence: ${manifestPath}`,
|
|
580
|
+
{ cause: error }
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
schemaVersion: 1,
|
|
585
|
+
projectSha,
|
|
586
|
+
imageDigest,
|
|
587
|
+
runtimePackageManifest: {
|
|
588
|
+
file: "runtime-package-manifest.json",
|
|
589
|
+
sha256: sha2562(manifest)
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
};
|
|
593
|
+
|
|
594
|
+
// src/diagnostics/runtimeFeedbackArtifacts.ts
|
|
595
|
+
import { createHash as createHash3 } from "crypto";
|
|
596
|
+
import fs3 from "fs/promises";
|
|
597
|
+
import path3 from "path";
|
|
598
|
+
var RUNTIME_FEEDBACK_MANIFEST_FILE = "manifest.json";
|
|
599
|
+
var RUNTIME_FEEDBACK_REPLAY_FILE = "replay-runtime-evidence.json";
|
|
600
|
+
var RUNTIME_FEEDBACK_LOG_FILE = "replay.log";
|
|
601
|
+
var RUNTIME_FEEDBACK_COMPLETE_FILE = ".complete";
|
|
602
|
+
var isRecord3 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
|
|
603
|
+
var sha2563 = (value) => createHash3("sha256").update(value).digest("hex");
|
|
604
|
+
var safeSegment2 = (value, fallback) => {
|
|
605
|
+
const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
|
|
606
|
+
return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
|
|
607
|
+
};
|
|
608
|
+
var parsePayload = (value, expectedFile) => {
|
|
609
|
+
const payload = isRecord3(value) ? value : null;
|
|
610
|
+
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) {
|
|
611
|
+
throw new Error(`Invalid runtime feedback payload: ${expectedFile}`);
|
|
612
|
+
}
|
|
613
|
+
return payload;
|
|
614
|
+
};
|
|
615
|
+
var parseManifest2 = (value) => {
|
|
616
|
+
const manifest = isRecord3(value) ? value : null;
|
|
617
|
+
const window = isRecord3(manifest?.window) ? manifest.window : null;
|
|
618
|
+
const runtimeEvidence = isRecord3(manifest?.runtimeEvidence) ? manifest.runtimeEvidence : null;
|
|
619
|
+
const safety = isRecord3(manifest?.safety) ? manifest.safety : null;
|
|
620
|
+
const payloads = isRecord3(manifest?.payloads) ? manifest.payloads : null;
|
|
621
|
+
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(
|
|
622
|
+
(strategy) => typeof strategy === "string" && strategy.trim()
|
|
623
|
+
) || typeof manifest.cycleCount !== "number" || !Number.isFinite(manifest.cycleCount) || manifest.cycleCount <= 0 || safety?.cacheOnly !== true || safety.externalOrderPlacement !== false || safety.redis !== "isolated" || safety.timescale !== "read_only") {
|
|
624
|
+
throw new Error("Invalid runtime feedback replay manifest");
|
|
625
|
+
}
|
|
626
|
+
const replayEvidence = parsePayload(
|
|
627
|
+
payloads?.replayEvidence,
|
|
628
|
+
RUNTIME_FEEDBACK_REPLAY_FILE
|
|
629
|
+
);
|
|
630
|
+
const log = parsePayload(payloads?.log, RUNTIME_FEEDBACK_LOG_FILE);
|
|
631
|
+
return {
|
|
632
|
+
...manifest,
|
|
633
|
+
producer: parseRuntimeEvidenceProducer(manifest.producer),
|
|
634
|
+
payloads: {
|
|
635
|
+
replayEvidence: {
|
|
636
|
+
...replayEvidence,
|
|
637
|
+
file: RUNTIME_FEEDBACK_REPLAY_FILE
|
|
638
|
+
},
|
|
639
|
+
log: { ...log, file: RUNTIME_FEEDBACK_LOG_FILE }
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
};
|
|
643
|
+
var assertReplayMatchesRuntimeEvidence = ({
|
|
644
|
+
replayEvidence,
|
|
645
|
+
runtimeEvidence
|
|
646
|
+
}) => {
|
|
647
|
+
if (replayEvidence.reportType !== "replay-runtime-evidence") {
|
|
648
|
+
throw new Error("Runtime feedback replay payload has the wrong reportType");
|
|
649
|
+
}
|
|
650
|
+
const replayWindow = isRecord3(replayEvidence.window) ? replayEvidence.window : null;
|
|
651
|
+
if (replayWindow?.startTime !== runtimeEvidence.manifest.window.startTime || replayWindow.endTime !== runtimeEvidence.manifest.window.endTime) {
|
|
652
|
+
throw new Error("Runtime feedback replay window does not match evidence");
|
|
653
|
+
}
|
|
654
|
+
const runtimeDeployment = parseRuntimeEvidenceDeploymentSnapshot(
|
|
655
|
+
runtimeEvidence.artifact.deployment
|
|
656
|
+
);
|
|
657
|
+
const replayDeployment = parseRuntimeEvidenceDeploymentSnapshot(
|
|
658
|
+
replayEvidence.deployment
|
|
659
|
+
);
|
|
660
|
+
if (replayDeployment.id !== runtimeDeployment.id || replayDeployment.deploymentCompositionId !== runtimeDeployment.deploymentCompositionId) {
|
|
661
|
+
throw new Error(
|
|
662
|
+
"Runtime feedback replay deployment does not match evidence"
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
var sealRuntimeFeedbackReplayBundle = async ({
|
|
667
|
+
bundleDir,
|
|
668
|
+
runId,
|
|
669
|
+
runtimeEvidenceBundle
|
|
670
|
+
}) => {
|
|
671
|
+
const replayEvidencePath = path3.join(bundleDir, RUNTIME_FEEDBACK_REPLAY_FILE);
|
|
672
|
+
const logPath = path3.join(bundleDir, RUNTIME_FEEDBACK_LOG_FILE);
|
|
673
|
+
const [replayPayload, logPayload] = await Promise.all([
|
|
674
|
+
fs3.readFile(replayEvidencePath),
|
|
675
|
+
fs3.readFile(logPath)
|
|
676
|
+
]);
|
|
677
|
+
const replayEvidence = JSON.parse(replayPayload.toString("utf8"));
|
|
678
|
+
assertReplayMatchesRuntimeEvidence({
|
|
679
|
+
replayEvidence,
|
|
680
|
+
runtimeEvidence: runtimeEvidenceBundle
|
|
681
|
+
});
|
|
682
|
+
const replay = isRecord3(replayEvidence.replay) ? replayEvidence.replay : null;
|
|
683
|
+
const cycleCount = Number(replay?.cycleCount);
|
|
684
|
+
if (!Number.isFinite(cycleCount) || cycleCount <= 0) {
|
|
685
|
+
throw new Error(
|
|
686
|
+
`Runtime feedback replay produced no comparable cycles: ${String(replay?.cycleCount ?? "missing")}`
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
const deployment = parseRuntimeEvidenceDeploymentSnapshot(
|
|
690
|
+
runtimeEvidenceBundle.artifact.deployment
|
|
691
|
+
);
|
|
692
|
+
const producer = parseRuntimeEvidenceProducer(
|
|
693
|
+
runtimeEvidenceBundle.artifact.producer
|
|
694
|
+
);
|
|
695
|
+
const safeRunId = safeSegment2(runId, "run");
|
|
696
|
+
const artifactId = `${runtimeEvidenceBundle.manifest.artifactId}_${safeRunId}`;
|
|
697
|
+
const manifest = {
|
|
698
|
+
schemaVersion: 1,
|
|
699
|
+
reportType: "runtime-feedback-replay",
|
|
700
|
+
artifactId,
|
|
701
|
+
runId: safeRunId,
|
|
702
|
+
deploymentId: deployment.id,
|
|
703
|
+
deploymentCompositionId: deployment.deploymentCompositionId,
|
|
704
|
+
userName: runtimeEvidenceBundle.manifest.userName,
|
|
705
|
+
createdAt: Date.now(),
|
|
706
|
+
window: { ...runtimeEvidenceBundle.manifest.window },
|
|
707
|
+
runtimeEvidence: {
|
|
708
|
+
artifactId: runtimeEvidenceBundle.manifest.artifactId,
|
|
709
|
+
payloadSha256: runtimeEvidenceBundle.manifest.payload.sha256
|
|
710
|
+
},
|
|
711
|
+
producer,
|
|
712
|
+
activeStrategies: activeRuntimeEvidenceStrategies(deployment).map(
|
|
713
|
+
({ strategyName }) => strategyName
|
|
714
|
+
),
|
|
715
|
+
cycleCount,
|
|
716
|
+
safety: {
|
|
717
|
+
cacheOnly: true,
|
|
718
|
+
externalOrderPlacement: false,
|
|
719
|
+
redis: "isolated",
|
|
720
|
+
timescale: "read_only"
|
|
721
|
+
},
|
|
722
|
+
payloads: {
|
|
723
|
+
replayEvidence: {
|
|
724
|
+
file: RUNTIME_FEEDBACK_REPLAY_FILE,
|
|
725
|
+
sha256: sha2563(replayPayload),
|
|
726
|
+
bytes: replayPayload.byteLength
|
|
727
|
+
},
|
|
728
|
+
log: {
|
|
729
|
+
file: RUNTIME_FEEDBACK_LOG_FILE,
|
|
730
|
+
sha256: sha2563(logPayload),
|
|
731
|
+
bytes: logPayload.byteLength
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
await fs3.writeFile(
|
|
736
|
+
path3.join(bundleDir, RUNTIME_FEEDBACK_MANIFEST_FILE),
|
|
737
|
+
`${JSON.stringify(manifest, null, 2)}
|
|
738
|
+
`,
|
|
739
|
+
"utf8"
|
|
740
|
+
);
|
|
741
|
+
await fs3.writeFile(
|
|
742
|
+
path3.join(bundleDir, RUNTIME_FEEDBACK_COMPLETE_FILE),
|
|
743
|
+
`${artifactId}
|
|
744
|
+
`,
|
|
745
|
+
"utf8"
|
|
746
|
+
);
|
|
747
|
+
return verifyRuntimeFeedbackReplayBundle(bundleDir);
|
|
748
|
+
};
|
|
749
|
+
var verifyRuntimeFeedbackReplayBundle = async (bundleDir) => {
|
|
750
|
+
const manifestPath = path3.join(bundleDir, RUNTIME_FEEDBACK_MANIFEST_FILE);
|
|
751
|
+
const replayEvidencePath = path3.join(bundleDir, RUNTIME_FEEDBACK_REPLAY_FILE);
|
|
752
|
+
const logPath = path3.join(bundleDir, RUNTIME_FEEDBACK_LOG_FILE);
|
|
753
|
+
const completePath = path3.join(bundleDir, RUNTIME_FEEDBACK_COMPLETE_FILE);
|
|
754
|
+
const [manifestText, replayPayload, logPayload, completeText] = await Promise.all([
|
|
755
|
+
fs3.readFile(manifestPath, "utf8"),
|
|
756
|
+
fs3.readFile(replayEvidencePath),
|
|
757
|
+
fs3.readFile(logPath),
|
|
758
|
+
fs3.readFile(completePath, "utf8")
|
|
759
|
+
]);
|
|
760
|
+
const manifest = parseManifest2(JSON.parse(manifestText));
|
|
761
|
+
if (completeText.trim() !== manifest.artifactId) {
|
|
762
|
+
throw new Error(`Invalid runtime feedback completion marker: ${bundleDir}`);
|
|
763
|
+
}
|
|
764
|
+
for (const [payload, descriptor] of [
|
|
765
|
+
[replayPayload, manifest.payloads.replayEvidence],
|
|
766
|
+
[logPayload, manifest.payloads.log]
|
|
767
|
+
]) {
|
|
768
|
+
if (payload.byteLength !== descriptor.bytes) {
|
|
769
|
+
throw new Error(
|
|
770
|
+
`Runtime feedback payload size mismatch: ${descriptor.file}`
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
if (sha2563(payload) !== descriptor.sha256) {
|
|
774
|
+
throw new Error(
|
|
775
|
+
`Runtime feedback payload checksum mismatch: ${descriptor.file}`
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const replayEvidence = JSON.parse(replayPayload.toString("utf8"));
|
|
780
|
+
if (replayEvidence.reportType !== "replay-runtime-evidence") {
|
|
781
|
+
throw new Error("Invalid runtime feedback replay evidence payload");
|
|
782
|
+
}
|
|
783
|
+
const replayWindow = isRecord3(replayEvidence.window) ? replayEvidence.window : null;
|
|
784
|
+
const replay = isRecord3(replayEvidence.replay) ? replayEvidence.replay : null;
|
|
785
|
+
const replayDeployment = parseRuntimeEvidenceDeploymentSnapshot(
|
|
786
|
+
replayEvidence.deployment
|
|
787
|
+
);
|
|
788
|
+
const replayStrategies = activeRuntimeEvidenceStrategies(replayDeployment).map(({ strategyName }) => strategyName).sort();
|
|
789
|
+
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())) {
|
|
790
|
+
throw new Error("Runtime feedback replay payload does not match manifest");
|
|
791
|
+
}
|
|
792
|
+
return {
|
|
793
|
+
bundleDir,
|
|
794
|
+
manifestPath,
|
|
795
|
+
replayEvidencePath,
|
|
796
|
+
logPath,
|
|
797
|
+
manifest,
|
|
798
|
+
replayEvidence
|
|
799
|
+
};
|
|
800
|
+
};
|
|
801
|
+
var discoverRuntimeFeedbackReplayBundles = async (rootDir) => {
|
|
802
|
+
const bundles = [];
|
|
803
|
+
const visit = async (directory, depth) => {
|
|
804
|
+
if (depth > 10) return;
|
|
805
|
+
let entries;
|
|
806
|
+
try {
|
|
807
|
+
entries = await fs3.readdir(directory, { withFileTypes: true });
|
|
808
|
+
} catch (error) {
|
|
809
|
+
if (error.code === "ENOENT") return;
|
|
810
|
+
throw error;
|
|
811
|
+
}
|
|
812
|
+
const names = new Set(entries.map((entry) => entry.name));
|
|
813
|
+
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)) {
|
|
814
|
+
bundles.push(directory);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
await Promise.all(
|
|
818
|
+
entries.filter(
|
|
819
|
+
(entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
|
|
820
|
+
).map((entry) => visit(path3.join(directory, entry.name), depth + 1))
|
|
821
|
+
);
|
|
822
|
+
};
|
|
823
|
+
await visit(rootDir, 0);
|
|
824
|
+
return bundles.sort();
|
|
825
|
+
};
|
|
826
|
+
var verifyRuntimeFeedbackReplaySource = async ({
|
|
827
|
+
bundleDir,
|
|
828
|
+
runtimeEvidenceBundleDir
|
|
829
|
+
}) => {
|
|
830
|
+
const [feedback, runtimeEvidence] = await Promise.all([
|
|
831
|
+
verifyRuntimeFeedbackReplayBundle(bundleDir),
|
|
832
|
+
verifyRuntimeEvidenceBundle(runtimeEvidenceBundleDir)
|
|
833
|
+
]);
|
|
834
|
+
if (feedback.manifest.runtimeEvidence.artifactId !== runtimeEvidence.manifest.artifactId || feedback.manifest.runtimeEvidence.payloadSha256 !== runtimeEvidence.manifest.payload.sha256) {
|
|
835
|
+
throw new Error("Runtime feedback bundle references different evidence");
|
|
836
|
+
}
|
|
837
|
+
assertReplayMatchesRuntimeEvidence({
|
|
838
|
+
replayEvidence: feedback.replayEvidence,
|
|
839
|
+
runtimeEvidence
|
|
840
|
+
});
|
|
841
|
+
return { feedback, runtimeEvidence };
|
|
842
|
+
};
|
|
843
|
+
export {
|
|
844
|
+
RUNTIME_EVIDENCE_COMPLETE_FILE,
|
|
845
|
+
RUNTIME_EVIDENCE_MANIFEST_FILE,
|
|
846
|
+
RUNTIME_EVIDENCE_PAYLOAD_FILE,
|
|
847
|
+
RUNTIME_FEEDBACK_COMPLETE_FILE,
|
|
848
|
+
RUNTIME_FEEDBACK_LOG_FILE,
|
|
849
|
+
RUNTIME_FEEDBACK_MANIFEST_FILE,
|
|
850
|
+
RUNTIME_FEEDBACK_REPLAY_FILE,
|
|
851
|
+
activeRuntimeEvidenceStrategies,
|
|
852
|
+
assertCurrentRuntimeEvidenceArtifact,
|
|
853
|
+
discoverRuntimeEvidenceBundles,
|
|
854
|
+
discoverRuntimeFeedbackReplayBundles,
|
|
855
|
+
parseRuntimeEvidenceDeploymentSnapshot,
|
|
856
|
+
parseRuntimeEvidenceProducer,
|
|
857
|
+
publishRuntimeEvidenceBundle,
|
|
858
|
+
resolveRuntimeEvidenceDeploymentSnapshot,
|
|
859
|
+
resolveRuntimeEvidenceProducer,
|
|
860
|
+
resolveRuntimeEvidenceTickerUniverse,
|
|
861
|
+
runtimeDeploymentFromEvidence,
|
|
862
|
+
runtimeLineageMatchesStrategySnapshot,
|
|
863
|
+
sealRuntimeFeedbackReplayBundle,
|
|
864
|
+
verifyRuntimeEvidenceBundle,
|
|
865
|
+
verifyRuntimeFeedbackReplayBundle,
|
|
866
|
+
verifyRuntimeFeedbackReplaySource
|
|
867
|
+
};
|