@tradejs/cli 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.
Files changed (32) hide show
  1. package/README.md +47 -8
  2. package/dist/cli.js +990 -1448
  3. package/dist/lib/aiPocketSearch.js +16 -0
  4. package/dist/lib/aiPocketSearchCli.js +3 -3
  5. package/dist/lib/jevMicroReferences.js +73 -0
  6. package/dist/lib/jevResearch.js +11 -0
  7. package/dist/lib/runtimeEvidenceArtifacts.js +3 -416
  8. package/dist/lib/runtimeEvidenceCompositionSnapshots.js +42 -211
  9. package/dist/lib/runtimeEvidenceCompositions.js +33 -310
  10. package/dist/lib/runtimeEvidenceDeployment.js +3 -315
  11. package/dist/lib/runtimeEvidenceProducer.js +3 -77
  12. package/dist/lib/runtimeEvidenceSync.js +32 -299
  13. package/dist/lib/runtimeFeedbackArtifacts.js +3 -545
  14. package/dist/lib/runtimeFeedbackNotification.js +7 -195
  15. package/dist/lib/runtimeFeedbackReplay.js +26 -525
  16. package/dist/lib/runtimeFeedbackSync.js +26 -219
  17. package/dist/lib/runtimeScorecard.js +5 -163
  18. package/dist/scripts/aiPocketSearch.js +101 -23
  19. package/dist/scripts/backtest.js +10 -1
  20. package/dist/scripts/jev.js +11 -0
  21. package/dist/scripts/mcpWorker.js +273 -0
  22. package/dist/scripts/replay.js +14 -250
  23. package/dist/scripts/replayRunner.js +14 -250
  24. package/dist/scripts/runtimeEvidence.js +47 -597
  25. package/dist/scripts/runtimeEvidenceSync.js +29 -296
  26. package/dist/scripts/runtimeFeedbackNotify.js +10 -188
  27. package/dist/scripts/runtimeFeedbackReplay.js +29 -528
  28. package/dist/scripts/runtimeFeedbackSync.js +28 -221
  29. package/dist/scripts/runtimeScorecard.js +88 -503
  30. package/dist/scripts/signals.js +55 -224
  31. package/dist/scripts/signalsDaemon.js +55 -224
  32. package/package.json +9 -8
@@ -17,6 +17,7 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
21
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
22
  // If the importer is in node compatibility mode or this is not an ESM
22
23
  // file that has been converted to a CommonJS file using a Babel-
@@ -34,8 +35,8 @@ __export(runtimeEvidence_exports, {
34
35
  runtimeEvidence: () => runtimeEvidence
35
36
  });
36
37
  module.exports = __toCommonJS(runtimeEvidence_exports);
37
- var import_promises4 = __toESM(require("fs/promises"));
38
- var import_node_path4 = __toESM(require("path"));
38
+ var import_promises2 = __toESM(require("fs/promises"));
39
+ var import_node_path2 = __toESM(require("path"));
39
40
  var import_args = __toESM(require("args"));
40
41
  var import_chalk = __toESM(require("chalk"));
41
42
 
@@ -384,582 +385,31 @@ var buildRuntimeEvidenceReportPayload = ({
384
385
  });
385
386
 
386
387
  // src/lib/runtimeEvidenceArtifacts.ts
388
+ var runtimeEvidenceArtifacts_exports = {};
389
+ __reExport(runtimeEvidenceArtifacts_exports, require("@tradejs/node/diagnostics"));
390
+
391
+ // src/lib/runtimeEvidenceCompositionSnapshots.ts
387
392
  var import_node_crypto = require("crypto");
388
393
  var import_promises = __toESM(require("fs/promises"));
389
394
  var import_node_path = __toESM(require("path"));
390
395
 
391
396
  // src/lib/runtimeEvidenceDeployment.ts
392
- var import_runtimeStrategies = require("@tradejs/node/runtimeStrategies");
393
- var isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
394
- var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
395
- var isPackageVersionMap = (value) => isRecord(value) && Object.keys(value).length > 0 && Object.entries(value).every(
396
- ([name, version]) => name.startsWith("@tradejs/") && isNonEmptyString(version)
397
- );
398
- var INTERVALS = /* @__PURE__ */ new Set([
399
- "1",
400
- "3",
401
- "5",
402
- "15",
403
- "30",
404
- "60",
405
- "120",
406
- "240",
407
- "360",
408
- "720",
409
- "D",
410
- "W",
411
- "M"
412
- ]);
413
- var UNIVERSES = /* @__PURE__ */ new Set(["crypto", "tradfi"]);
414
- 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));
415
- var samePackageVersions = (left, right) => {
416
- if (!left || !right) return false;
417
- const leftEntries = Object.entries(left).sort(
418
- ([a], [b]) => a.localeCompare(b)
419
- );
420
- const rightEntries = Object.entries(right).sort(
421
- ([a], [b]) => a.localeCompare(b)
422
- );
423
- return JSON.stringify(leftEntries) === JSON.stringify(rightEntries);
424
- };
425
- var runtimeLineageMatchesStrategySnapshot = ({
426
- lineage,
427
- deployment,
428
- strategy
429
- }) => lineage?.schemaVersion === 3 && lineage.strategyRevision === strategy.strategyRevision && lineage.deploymentCompositionId === deployment.deploymentCompositionId && lineage.strategyPackageVersion === strategy.strategyPackageVersion && lineage.runtimePackageVersion === strategy.runtimePackageVersion && samePackageVersions(
430
- lineage.strategyDependencyVersions,
431
- strategy.strategyDependencyVersions
432
- );
433
- var parseRuntimeEvidenceDeploymentSnapshot = (value) => {
434
- 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)) {
435
- throw new Error(
436
- "Runtime evidence deployment snapshot is missing or invalid"
437
- );
438
- }
439
- const strategies = value.strategies.map((candidate) => {
440
- 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)) {
441
- throw new Error(
442
- "Runtime evidence deployment strategy snapshot is invalid"
443
- );
444
- }
445
- if (String(candidate.strategyConfig.INTERVAL) !== String(candidate.interval) || String(candidate.strategyConfig.UNIVERSE) !== String(candidate.universe)) {
446
- throw new Error(
447
- `Runtime evidence strategy config does not match its scope: ${candidate.strategyName}`
448
- );
449
- }
450
- if (candidate.accountId != null && (!isNonEmptyString(candidate.accountId) || candidate.accountId !== value.accountId)) {
451
- throw new Error(
452
- `Runtime evidence strategy account does not match deployment: ${candidate.strategyName}`
453
- );
454
- }
455
- return candidate;
456
- });
457
- const identities = /* @__PURE__ */ new Set();
458
- for (const strategy of strategies) {
459
- if (identities.has(strategy.strategyName)) {
460
- throw new Error(
461
- `Duplicate runtime evidence strategy: ${strategy.strategyName}`
462
- );
463
- }
464
- identities.add(strategy.strategyName);
465
- }
466
- return {
467
- ...value,
468
- strategies
469
- };
470
- };
471
- var activeRuntimeEvidenceStrategies = (deployment) => deployment.enabled ? deployment.strategies.filter((strategy) => strategy.enabled) : [];
472
- var unwrapRuntimeEvidenceRows = (value, field) => (Array.isArray(value) ? value : []).map((candidate) => {
473
- const record = isRecord(candidate) ? candidate : null;
474
- const nested = record && isRecord(record[field]) ? record[field] : null;
475
- return nested ?? record;
476
- }).filter((record) => record != null);
477
- var assertCurrentRuntimeEvidenceArtifact = (artifact) => {
478
- if (!isRecord(artifact) || artifact.reportType !== "runtime-evidence") {
479
- throw new Error("Invalid runtime evidence artifact");
480
- }
481
- const deployment = parseRuntimeEvidenceDeploymentSnapshot(
482
- artifact.deployment
483
- );
484
- const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
485
- if (activeStrategies.length === 0) {
486
- throw new Error("Runtime evidence deployment has no enabled strategies");
487
- }
488
- const runtime = isRecord(artifact.runtime) ? artifact.runtime : null;
489
- if (!runtime) {
490
- throw new Error("Runtime evidence payload is missing");
491
- }
492
- if ("strategyConfigs" in runtime) {
493
- throw new Error(
494
- "Runtime evidence payload contains removed strategyConfigs data"
495
- );
496
- }
497
- if ("evaluationStatsBuckets" in runtime) {
498
- throw new Error(
499
- "Runtime evidence payload contains removed lineage-less evaluationStatsBuckets data"
500
- );
501
- }
502
- const rowFields = [
503
- "trades",
504
- "signals",
505
- "evaluations",
506
- "lineageScopes"
507
- ];
508
- for (const field of rowFields) {
509
- if (!Array.isArray(runtime[field])) {
510
- throw new Error(`Runtime evidence payload ${field} must be an array`);
511
- }
512
- }
513
- const snapshots = new Map(
514
- activeStrategies.map((strategy) => [strategy.strategyName, strategy])
515
- );
516
- const assertRows = (label, rows, lineageField) => {
517
- for (const row of rows) {
518
- const strategyName = String(row.strategy ?? "").trim();
519
- const strategy = snapshots.get(strategyName);
520
- if (!strategy || row.deploymentId !== deployment.id || row.accountId !== deployment.accountId || !runtimeLineageMatchesStrategySnapshot({
521
- lineage: isRecord(row[lineageField]) ? row[lineageField] : void 0,
522
- deployment,
523
- strategy
524
- })) {
525
- throw new Error(
526
- `Runtime evidence ${label} row is outside the current embedded deployment lineage`
527
- );
528
- }
529
- }
530
- };
531
- assertRows(
532
- "trade",
533
- unwrapRuntimeEvidenceRows(runtime.trades, "trade"),
534
- "runtimeLineage"
535
- );
536
- assertRows(
537
- "signal",
538
- unwrapRuntimeEvidenceRows(runtime.signals, "signal"),
539
- "runtimeLineage"
540
- );
541
- assertRows(
542
- "evaluation",
543
- unwrapRuntimeEvidenceRows(runtime.evaluations, "evaluation"),
544
- "runtimeLineage"
545
- );
546
- assertRows(
547
- "lineage scope",
548
- unwrapRuntimeEvidenceRows(runtime.lineageScopes, "lineageScope"),
549
- "lineage"
550
- );
551
- return deployment;
552
- };
553
- var resolveRuntimeEvidenceTickerUniverse = ({
554
- deployment,
555
- lineageScopes,
556
- fallbackTickers
557
- }) => {
558
- const declaredTickers = deployment.tickers?.filter(isNonEmptyString) ?? [];
559
- if (declaredTickers.length > 0) {
560
- return {
561
- ...deployment,
562
- tickers: [
563
- ...new Set(declaredTickers.map((ticker) => ticker.trim()))
564
- ].sort()
565
- };
566
- }
567
- const activeStrategies = activeRuntimeEvidenceStrategies(deployment);
568
- if (activeStrategies.length > 0 && activeStrategies.every((strategy) => strategy.selection?.tickers?.length)) {
569
- return {
570
- ...deployment,
571
- tickers: [
572
- ...new Set(
573
- activeStrategies.flatMap(
574
- (strategy) => strategy.selection?.tickers ?? []
575
- )
576
- )
577
- ].sort()
578
- };
579
- }
580
- const strategiesByName = new Map(
581
- activeStrategies.map((strategy) => [strategy.strategyName, strategy])
582
- );
583
- const tickers = /* @__PURE__ */ new Set();
584
- for (const scope of lineageScopes) {
585
- const strategy = strategiesByName.get(scope.strategy);
586
- if (!strategy || scope.deploymentId !== deployment.id || scope.accountId !== deployment.accountId || !isNonEmptyString(scope.symbol) || !runtimeLineageMatchesStrategySnapshot({
587
- lineage: scope.lineage,
588
- deployment,
589
- strategy
590
- })) {
591
- continue;
592
- }
593
- tickers.add(scope.symbol.trim());
594
- }
595
- if (tickers.size === 0) {
596
- const verifiedFallbackTickers = fallbackTickers?.filter(isNonEmptyString) ?? [];
597
- if (verifiedFallbackTickers.length > 0) {
598
- return {
599
- ...deployment,
600
- tickers: [
601
- ...new Set(verifiedFallbackTickers.map((ticker) => ticker.trim()))
602
- ].sort()
603
- };
604
- }
605
- throw new Error(
606
- "Runtime evidence has no immutable ticker universe for the embedded deployment composition"
607
- );
608
- }
609
- return { ...deployment, tickers: [...tickers].sort() };
610
- };
611
- var resolveRuntimeEvidenceDeploymentSnapshot = async ({
612
- userName,
613
- projectRoot: projectRoot2,
614
- deploymentId
615
- }) => {
616
- const [deployment, strategies] = await Promise.all([
617
- (0, import_runtimeStrategies.getRuntimeDeployment)({ userName, projectRoot: projectRoot2, deploymentId }),
618
- (0, import_runtimeStrategies.loadResolvedRuntimeStrategies)({ userName, projectRoot: projectRoot2, deploymentId })
619
- ]);
620
- if (!deployment) {
621
- throw new Error(`Runtime deployment not found: ${deploymentId}`);
622
- }
623
- return {
624
- schemaVersion: 2,
625
- id: deployment.id,
626
- deploymentCompositionId: deployment.deploymentCompositionId,
627
- label: deployment.label,
628
- connectorName: deployment.connectorName,
629
- provider: deployment.provider,
630
- accountId: deployment.accountId,
631
- enabled: deployment.enabled,
632
- strategies: strategies.map(
633
- ({
634
- strategyName,
635
- strategyRevision,
636
- enabled,
637
- controlState,
638
- interval,
639
- universe,
640
- accountId,
641
- strategyPackage,
642
- strategyPackageVersion,
643
- strategyDependencyVersions,
644
- runtimePackageVersion,
645
- strategyConfig,
646
- selection
647
- }) => ({
648
- strategyName,
649
- strategyRevision,
650
- enabled,
651
- controlState,
652
- interval,
653
- universe,
654
- ...accountId ? { accountId } : {},
655
- strategyPackage,
656
- strategyPackageVersion,
657
- strategyDependencyVersions,
658
- runtimePackageVersion,
659
- strategyConfig,
660
- ...selection ? { selection } : {}
661
- })
662
- ),
663
- ...deployment.assetClasses ? { assetClasses: [...deployment.assetClasses] } : {},
664
- ...deployment.tickers ? { tickers: [...deployment.tickers] } : {}
665
- };
666
- };
667
-
668
- // src/lib/runtimeEvidenceArtifacts.ts
669
- var RUNTIME_EVIDENCE_MANIFEST_FILE = "manifest.json";
670
- var RUNTIME_EVIDENCE_PAYLOAD_FILE = "runtime-evidence.json";
671
- var RUNTIME_EVIDENCE_COMPLETE_FILE = ".complete";
672
- var asRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : null;
673
- var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
674
- var runtimeEvidenceIdentitySha256 = (artifact) => {
675
- const identityArtifact = { ...artifact };
676
- delete identityArtifact.generatedAt;
677
- const runtime = asRecord(identityArtifact.runtime);
678
- if (runtime) {
679
- const identityRuntime = { ...runtime };
680
- delete identityRuntime.generatedAt;
681
- identityArtifact.runtime = identityRuntime;
682
- }
683
- return sha256(JSON.stringify(identityArtifact));
684
- };
685
- var isExistingDestinationError = (error) => {
686
- const code = error.code;
687
- return code === "EEXIST" || code === "ENOTEMPTY";
688
- };
689
- var safeSegment = (value, fallback) => {
690
- const normalized = value.trim().replace(/[^a-zA-Z0-9._-]+/g, "-");
691
- return normalized && normalized !== "." && normalized !== ".." ? normalized : fallback;
692
- };
693
- var compactTimestamp = (timestamp) => new Date(timestamp).toISOString().replace(/[-:]/g, "").replace(/\.000Z$/, "Z");
694
- var dateParts = (timestamp) => {
695
- const date = new Date(timestamp);
696
- return [
697
- String(date.getUTCFullYear()),
698
- String(date.getUTCMonth() + 1).padStart(2, "0"),
699
- String(date.getUTCDate()).padStart(2, "0")
700
- ];
701
- };
702
- var assertFiniteTimestamp = (value, label) => {
703
- if (typeof value !== "number" || !Number.isFinite(value)) {
704
- throw new Error(`Invalid runtime evidence ${label}`);
705
- }
706
- return value;
707
- };
708
- var parseManifest = (value) => {
709
- const manifest = asRecord(value);
710
- const window = asRecord(manifest?.window);
711
- const payload = asRecord(manifest?.payload);
712
- const counts = asRecord(manifest?.counts);
713
- 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)) {
714
- throw new Error("Invalid runtime evidence manifest");
715
- }
716
- return {
717
- schemaVersion: 1,
718
- artifactId: manifest.artifactId,
719
- reportType: "runtime-evidence",
720
- deploymentId: manifest.deploymentId,
721
- userName: manifest.userName,
722
- createdAt: manifest.createdAt,
723
- window: {
724
- startTime: assertFiniteTimestamp(window?.startTime, "window.startTime"),
725
- endTime: assertFiniteTimestamp(window?.endTime, "window.endTime")
726
- },
727
- payload: {
728
- file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
729
- sha256: payload.sha256,
730
- bytes: payload.bytes
731
- },
732
- counts: Object.fromEntries(
733
- Object.entries(counts ?? {}).filter(
734
- (entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])
735
- )
736
- ),
737
- lineageKeys: manifest.lineageKeys.filter(
738
- (value2) => typeof value2 === "string" && value2.length > 0
739
- )
740
- };
741
- };
742
- var publishRuntimeEvidenceBundle = async ({
743
- publishRoot,
744
- deploymentId,
745
- userName,
746
- startTime,
747
- endTime,
748
- artifact,
749
- counts,
750
- lineageKeys
751
- }) => {
752
- assertCurrentRuntimeEvidenceArtifact(artifact);
753
- const payload = `${JSON.stringify(artifact, null, 2)}
754
- `;
755
- const payloadSha256 = sha256(payload);
756
- const identitySha256 = runtimeEvidenceIdentitySha256(artifact);
757
- const safeDeploymentId = safeSegment(deploymentId, "default");
758
- const artifactId = [
759
- compactTimestamp(startTime),
760
- compactTimestamp(endTime),
761
- identitySha256.slice(0, 16)
762
- ].join("_");
763
- const createdAt = Date.now();
764
- const manifest = {
765
- schemaVersion: 1,
766
- artifactId,
767
- reportType: "runtime-evidence",
768
- deploymentId: safeDeploymentId,
769
- userName,
770
- createdAt,
771
- window: { startTime, endTime },
772
- payload: {
773
- file: RUNTIME_EVIDENCE_PAYLOAD_FILE,
774
- sha256: payloadSha256,
775
- bytes: Buffer.byteLength(payload)
776
- },
777
- counts,
778
- lineageKeys: [...new Set(lineageKeys)].sort()
779
- };
780
- const incomingRoot = import_node_path.default.join(publishRoot, "incoming");
781
- const readyRoot = import_node_path.default.join(
782
- publishRoot,
783
- "ready",
784
- safeDeploymentId,
785
- ...dateParts(endTime)
786
- );
787
- const bundleDir = import_node_path.default.join(readyRoot, artifactId);
788
- const temporaryDir = import_node_path.default.join(
789
- incomingRoot,
790
- `${artifactId}.tmp-${(0, import_node_crypto.randomUUID)()}`
791
- );
792
- await import_promises.default.mkdir(temporaryDir, { recursive: true });
793
- try {
794
- await Promise.all([
795
- import_promises.default.writeFile(
796
- import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_PAYLOAD_FILE),
797
- payload,
798
- "utf8"
799
- ),
800
- import_promises.default.writeFile(
801
- import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_MANIFEST_FILE),
802
- `${JSON.stringify(manifest, null, 2)}
803
- `,
804
- "utf8"
805
- )
806
- ]);
807
- await import_promises.default.writeFile(
808
- import_node_path.default.join(temporaryDir, RUNTIME_EVIDENCE_COMPLETE_FILE),
809
- `${artifactId}
810
- `,
811
- "utf8"
812
- );
813
- await import_promises.default.mkdir(readyRoot, { recursive: true });
814
- try {
815
- await import_promises.default.rename(temporaryDir, bundleDir);
816
- } catch (error) {
817
- if (!isExistingDestinationError(error)) {
818
- throw error;
819
- }
820
- await import_promises.default.rm(temporaryDir, { recursive: true, force: true });
821
- }
822
- } catch (error) {
823
- await import_promises.default.rm(temporaryDir, { recursive: true, force: true });
824
- throw error;
825
- }
826
- return verifyRuntimeEvidenceBundle(bundleDir);
827
- };
828
- var verifyRuntimeEvidenceBundle = async (bundleDir) => {
829
- const manifestPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_MANIFEST_FILE);
830
- const payloadPath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_PAYLOAD_FILE);
831
- const completePath = import_node_path.default.join(bundleDir, RUNTIME_EVIDENCE_COMPLETE_FILE);
832
- const [manifestText, payload, completeText] = await Promise.all([
833
- import_promises.default.readFile(manifestPath, "utf8"),
834
- import_promises.default.readFile(payloadPath),
835
- import_promises.default.readFile(completePath, "utf8")
836
- ]);
837
- const manifest = parseManifest(JSON.parse(manifestText));
838
- if (completeText.trim() !== manifest.artifactId) {
839
- throw new Error(`Invalid completion marker in ${bundleDir}`);
840
- }
841
- if (payload.byteLength !== manifest.payload.bytes) {
842
- throw new Error(`Runtime evidence size mismatch in ${bundleDir}`);
843
- }
844
- if (sha256(payload) !== manifest.payload.sha256) {
845
- throw new Error(`Runtime evidence checksum mismatch in ${bundleDir}`);
846
- }
847
- const artifact = asRecord(JSON.parse(payload.toString("utf8")));
848
- const artifactWindow = asRecord(artifact?.window);
849
- if (artifact?.reportType !== "runtime-evidence" || artifactWindow?.startTime !== manifest.window.startTime || artifactWindow.endTime !== manifest.window.endTime) {
850
- throw new Error(`Runtime evidence payload mismatch in ${bundleDir}`);
851
- }
852
- const deployment = assertCurrentRuntimeEvidenceArtifact(artifact);
853
- if (deployment.id !== manifest.deploymentId) {
854
- throw new Error(`Runtime evidence deployment mismatch in ${bundleDir}`);
855
- }
856
- return {
857
- bundleDir,
858
- manifestPath,
859
- payloadPath,
860
- manifest,
861
- artifact
862
- };
863
- };
864
- var discoverRuntimeEvidenceBundles = async (rootDir) => {
865
- const bundles = [];
866
- const visit = async (directory, depth) => {
867
- if (depth > 8) return;
868
- let entries;
869
- try {
870
- entries = await import_promises.default.readdir(directory, { withFileTypes: true });
871
- } catch (error) {
872
- if (error.code === "ENOENT") return;
873
- throw error;
874
- }
875
- const names = new Set(entries.map((entry) => entry.name));
876
- if (names.has(RUNTIME_EVIDENCE_MANIFEST_FILE) && names.has(RUNTIME_EVIDENCE_PAYLOAD_FILE) && names.has(RUNTIME_EVIDENCE_COMPLETE_FILE)) {
877
- bundles.push(directory);
878
- return;
879
- }
880
- await Promise.all(
881
- entries.filter(
882
- (entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
883
- ).map((entry) => visit(import_node_path.default.join(directory, entry.name), depth + 1))
884
- );
885
- };
886
- await visit(rootDir, 0);
887
- return bundles.sort();
888
- };
889
-
890
- // src/lib/runtimeEvidenceCompositionSnapshots.ts
891
- var import_node_crypto3 = require("crypto");
892
- var import_promises3 = __toESM(require("fs/promises"));
893
- var import_node_path3 = __toESM(require("path"));
397
+ var runtimeEvidenceDeployment_exports = {};
398
+ __reExport(runtimeEvidenceDeployment_exports, require("@tradejs/node/diagnostics"));
894
399
 
895
400
  // src/lib/runtimeEvidenceProducer.ts
896
- var import_node_crypto2 = require("crypto");
897
- var import_promises2 = __toESM(require("fs/promises"));
898
- var import_node_path2 = __toESM(require("path"));
899
- var isRecord2 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
900
- var sha2562 = (value) => (0, import_node_crypto2.createHash)("sha256").update(value).digest("hex");
901
- var parseRuntimeEvidenceProducer = (value) => {
902
- const producer = isRecord2(value) ? value : null;
903
- const runtimePackageManifest = isRecord2(producer?.runtimePackageManifest) ? producer.runtimePackageManifest : null;
904
- 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)) {
905
- throw new Error("Runtime evidence producer image identity is invalid");
906
- }
907
- return producer;
908
- };
909
- var resolveRuntimeEvidenceProducer = async ({
910
- projectRoot: projectRoot2,
911
- required
912
- }) => {
913
- const projectSha = String(process.env.TRADEJS_PROJECT_SHA ?? "").trim();
914
- const imageDigest = String(
915
- process.env.TRADEJS_PROJECT_IMAGE_DIGEST ?? ""
916
- ).trim();
917
- if (!projectSha && !imageDigest && !required) {
918
- return null;
919
- }
920
- if (!/^[a-f0-9]{40}$/.test(projectSha)) {
921
- throw new Error(
922
- "TRADEJS_PROJECT_SHA must be a full lowercase Git SHA before publishing runtime evidence"
923
- );
924
- }
925
- if (!/^sha256:[a-f0-9]{64}$/.test(imageDigest)) {
926
- throw new Error(
927
- "TRADEJS_PROJECT_IMAGE_DIGEST must be an immutable sha256 digest before publishing runtime evidence"
928
- );
929
- }
930
- const manifestPath = import_node_path2.default.join(projectRoot2, "runtime-package-manifest.json");
931
- let manifest;
932
- try {
933
- manifest = await import_promises2.default.readFile(manifestPath);
934
- } catch (error) {
935
- if (!required && error.code === "ENOENT") {
936
- return null;
937
- }
938
- throw new Error(
939
- `Runtime package manifest is required for runtime evidence: ${manifestPath}`,
940
- { cause: error }
941
- );
942
- }
943
- return {
944
- schemaVersion: 1,
945
- projectSha,
946
- imageDigest,
947
- runtimePackageManifest: {
948
- file: "runtime-package-manifest.json",
949
- sha256: sha2562(manifest)
950
- }
951
- };
952
- };
401
+ var runtimeEvidenceProducer_exports = {};
402
+ __reExport(runtimeEvidenceProducer_exports, require("@tradejs/node/diagnostics"));
953
403
 
954
404
  // src/lib/runtimeEvidenceCompositionSnapshots.ts
955
405
  var SNAPSHOT_FILE = "snapshot.json";
956
406
  var MANIFEST_FILE = "manifest.json";
957
407
  var COMPLETE_FILE = ".complete";
958
- var isRecord3 = (value) => value != null && typeof value === "object" && !Array.isArray(value);
959
- var sha2563 = (value) => (0, import_node_crypto3.createHash)("sha256").update(value).digest("hex");
960
- var parseManifest2 = (value) => {
961
- const manifest = isRecord3(value) ? value : null;
962
- const payload = isRecord3(manifest?.payload) ? manifest.payload : null;
408
+ var isRecord = (value) => value != null && typeof value === "object" && !Array.isArray(value);
409
+ var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest("hex");
410
+ var parseManifest = (value) => {
411
+ const manifest = isRecord(value) ? value : null;
412
+ const payload = isRecord(manifest?.payload) ? manifest.payload : null;
963
413
  if (manifest?.schemaVersion !== 1 || manifest.reportType !== "runtime-evidence-composition-snapshot" || typeof manifest.createdAt !== "number" || typeof manifest.userName !== "string" || typeof manifest.deploymentId !== "string" || typeof manifest.deploymentCompositionId !== "string" || payload?.file !== SNAPSHOT_FILE || typeof payload.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(payload.sha256) || typeof payload.bytes !== "number") {
964
414
  throw new Error("Invalid runtime evidence composition snapshot manifest");
965
415
  }
@@ -967,28 +417,28 @@ var parseManifest2 = (value) => {
967
417
  };
968
418
  var verifyRuntimeEvidenceCompositionSnapshot = async (bundleDir) => {
969
419
  const [manifestText, payload, completeText] = await Promise.all([
970
- import_promises3.default.readFile(import_node_path3.default.join(bundleDir, MANIFEST_FILE), "utf8"),
971
- import_promises3.default.readFile(import_node_path3.default.join(bundleDir, SNAPSHOT_FILE)),
972
- import_promises3.default.readFile(import_node_path3.default.join(bundleDir, COMPLETE_FILE), "utf8")
420
+ import_promises.default.readFile(import_node_path.default.join(bundleDir, MANIFEST_FILE), "utf8"),
421
+ import_promises.default.readFile(import_node_path.default.join(bundleDir, SNAPSHOT_FILE)),
422
+ import_promises.default.readFile(import_node_path.default.join(bundleDir, COMPLETE_FILE), "utf8")
973
423
  ]);
974
- const manifest = parseManifest2(JSON.parse(manifestText));
424
+ const manifest = parseManifest(JSON.parse(manifestText));
975
425
  if (completeText.trim() !== manifest.deploymentCompositionId) {
976
426
  throw new Error(`Invalid completion marker in ${bundleDir}`);
977
427
  }
978
- if (payload.byteLength !== manifest.payload.bytes || sha2563(payload) !== manifest.payload.sha256) {
428
+ if (payload.byteLength !== manifest.payload.bytes || sha256(payload) !== manifest.payload.sha256) {
979
429
  throw new Error(
980
430
  `Runtime evidence snapshot checksum mismatch in ${bundleDir}`
981
431
  );
982
432
  }
983
433
  const value = JSON.parse(payload.toString("utf8"));
984
- const record = isRecord3(value) ? value : null;
434
+ const record = isRecord(value) ? value : null;
985
435
  if (record?.schemaVersion !== 1 || record.reportType !== "runtime-evidence-composition-snapshot" || record.userName !== manifest.userName) {
986
436
  throw new Error(
987
437
  `Invalid runtime evidence snapshot payload in ${bundleDir}`
988
438
  );
989
439
  }
990
- const deployment = parseRuntimeEvidenceDeploymentSnapshot(record.deployment);
991
- const producer = parseRuntimeEvidenceProducer(record.producer);
440
+ const deployment = (0, runtimeEvidenceDeployment_exports.parseRuntimeEvidenceDeploymentSnapshot)(record.deployment);
441
+ const producer = (0, runtimeEvidenceProducer_exports.parseRuntimeEvidenceProducer)(record.producer);
992
442
  if (deployment.id !== manifest.deploymentId || deployment.deploymentCompositionId !== manifest.deploymentCompositionId) {
993
443
  throw new Error(
994
444
  `Runtime evidence snapshot identity mismatch in ${bundleDir}`
@@ -997,24 +447,24 @@ var verifyRuntimeEvidenceCompositionSnapshot = async (bundleDir) => {
997
447
  return { bundleDir, deployment, producer };
998
448
  };
999
449
  var discoverRuntimeEvidenceCompositionSnapshots = async (evidenceRoot) => {
1000
- const rootDir = import_node_path3.default.join(evidenceRoot, "snapshots");
450
+ const rootDir = import_node_path.default.join(evidenceRoot, "snapshots");
1001
451
  const bundleDirs = [];
1002
452
  let deployments;
1003
453
  try {
1004
- deployments = await import_promises3.default.readdir(rootDir, { withFileTypes: true });
454
+ deployments = await import_promises.default.readdir(rootDir, { withFileTypes: true });
1005
455
  } catch (error) {
1006
456
  if (error.code === "ENOENT") return [];
1007
457
  throw error;
1008
458
  }
1009
459
  for (const deployment of deployments.filter((entry) => entry.isDirectory())) {
1010
- const deploymentDir = import_node_path3.default.join(rootDir, deployment.name);
1011
- const compositions = await import_promises3.default.readdir(deploymentDir, {
460
+ const deploymentDir = import_node_path.default.join(rootDir, deployment.name);
461
+ const compositions = await import_promises.default.readdir(deploymentDir, {
1012
462
  withFileTypes: true
1013
463
  });
1014
464
  bundleDirs.push(
1015
465
  ...compositions.filter(
1016
466
  (entry) => entry.isDirectory() && !entry.name.startsWith(".") && !entry.name.includes(".tmp-")
1017
- ).map((entry) => import_node_path3.default.join(deploymentDir, entry.name))
467
+ ).map((entry) => import_node_path.default.join(deploymentDir, entry.name))
1018
468
  );
1019
469
  }
1020
470
  return Promise.all(
@@ -1056,17 +506,17 @@ var loadRuntimeEvidenceCompositionSnapshots = async ({
1056
506
  producer: snapshot.producer
1057
507
  });
1058
508
  }
1059
- const bundleDirs = await discoverRuntimeEvidenceBundles(publishRoot);
509
+ const bundleDirs = await (0, runtimeEvidenceArtifacts_exports.discoverRuntimeEvidenceBundles)(publishRoot);
1060
510
  for (const bundleDir of bundleDirs) {
1061
- const bundle = await verifyRuntimeEvidenceBundle(bundleDir);
1062
- const deployment = parseRuntimeEvidenceDeploymentSnapshot(
511
+ const bundle = await (0, runtimeEvidenceArtifacts_exports.verifyRuntimeEvidenceBundle)(bundleDir);
512
+ const deployment = (0, runtimeEvidenceDeployment_exports.parseRuntimeEvidenceDeploymentSnapshot)(
1063
513
  bundle.artifact.deployment
1064
514
  );
1065
515
  if (deployment.id !== currentDeployment.id) continue;
1066
516
  if (bundle.artifact.producer == null) continue;
1067
517
  register({
1068
518
  deployment: { ...deployment, tickers: void 0 },
1069
- producer: parseRuntimeEvidenceProducer(bundle.artifact.producer),
519
+ producer: (0, runtimeEvidenceProducer_exports.parseRuntimeEvidenceProducer)(bundle.artifact.producer),
1070
520
  // A historical composition may reappear through a position that closes
1071
521
  // in this window even without current-window lineage scopes. Its latest
1072
522
  // checksum-verified universe is only a fallback; fresh scopes win.
@@ -1101,11 +551,11 @@ var rowTimestamp = (row) => {
1101
551
  return Number.POSITIVE_INFINITY;
1102
552
  };
1103
553
  var belongsToSnapshot = (row, deployment) => {
1104
- const strategy = activeRuntimeEvidenceStrategies(deployment).find(
554
+ const strategy = (0, runtimeEvidenceDeployment_exports.activeRuntimeEvidenceStrategies)(deployment).find(
1105
555
  (candidate) => candidate.strategyName === row.strategy
1106
556
  );
1107
557
  return Boolean(
1108
- strategy && row.deploymentId === deployment.id && row.accountId === deployment.accountId && runtimeLineageMatchesStrategySnapshot({
558
+ strategy && row.deploymentId === deployment.id && row.accountId === deployment.accountId && (0, runtimeEvidenceDeployment_exports.runtimeLineageMatchesStrategySnapshot)({
1109
559
  lineage: row.runtimeLineage ?? row.lineage,
1110
560
  deployment,
1111
561
  strategy
@@ -1176,7 +626,7 @@ var splitRuntimeEvidenceByComposition = ({
1176
626
  };
1177
627
 
1178
628
  // src/lib/runtimeLineage.ts
1179
- var import_node_crypto4 = require("crypto");
629
+ var import_node_crypto2 = require("crypto");
1180
630
  var normalizeForStableJson = (value) => {
1181
631
  if (Array.isArray(value)) {
1182
632
  return value.map(normalizeForStableJson);
@@ -1188,7 +638,7 @@ var normalizeForStableJson = (value) => {
1188
638
  }
1189
639
  return value;
1190
640
  };
1191
- var fingerprintRuntimeValue = (value) => (0, import_node_crypto4.createHash)("sha256").update(JSON.stringify(normalizeForStableJson(value))).digest("hex").slice(0, 16);
641
+ var fingerprintRuntimeValue = (value) => (0, import_node_crypto2.createHash)("sha256").update(JSON.stringify(normalizeForStableJson(value))).digest("hex").slice(0, 16);
1192
642
  var runtimeLineageKey = (lineage) => [
1193
643
  "v3",
1194
644
  lineage.deploymentCompositionId,
@@ -1279,11 +729,11 @@ var runtimeEvidence = async () => {
1279
729
  const { startTime, endTime, source } = resolveWindow();
1280
730
  const deploymentId = String(flags.deployment);
1281
731
  const publishDir = String(flags.publishDir ?? "").trim();
1282
- const producer = await resolveRuntimeEvidenceProducer({
732
+ const producer = await (0, runtimeEvidenceProducer_exports.resolveRuntimeEvidenceProducer)({
1283
733
  projectRoot,
1284
734
  required: Boolean(publishDir)
1285
735
  });
1286
- const deploymentSnapshot = await resolveRuntimeEvidenceDeploymentSnapshot({
736
+ const deploymentSnapshot = await (0, runtimeEvidenceDeployment_exports.resolveRuntimeEvidenceDeploymentSnapshot)({
1287
737
  userName: String(flags.user),
1288
738
  projectRoot,
1289
739
  deploymentId
@@ -1297,7 +747,7 @@ var runtimeEvidence = async () => {
1297
747
  deploymentId
1298
748
  });
1299
749
  const snapshots = publishDir && producer ? await loadRuntimeEvidenceCompositionSnapshots({
1300
- publishRoot: import_node_path4.default.resolve(projectRoot, publishDir),
750
+ publishRoot: import_node_path2.default.resolve(projectRoot, publishDir),
1301
751
  currentDeployment: deploymentSnapshot,
1302
752
  currentProducer: producer
1303
753
  }) : /* @__PURE__ */ new Map([
@@ -1326,7 +776,7 @@ var runtimeEvidence = async () => {
1326
776
  ignoreUnknownCompositions: !publishDir
1327
777
  });
1328
778
  const artifacts = compositionRows.map((composition) => {
1329
- const strategies = activeRuntimeEvidenceStrategies(composition.deployment).map(({ strategyName }) => strategyName).filter(
779
+ const strategies = (0, runtimeEvidenceDeployment_exports.activeRuntimeEvidenceStrategies)(composition.deployment).map(({ strategyName }) => strategyName).filter(
1330
780
  (strategyName) => !requestedStrategies.length || requestedStrategies.includes(strategyName)
1331
781
  );
1332
782
  const runtime = buildRuntimeEvidenceReportPayload({
@@ -1338,7 +788,7 @@ var runtimeEvidence = async () => {
1338
788
  trades: composition.trades,
1339
789
  lineageScopes: composition.lineageScopes
1340
790
  });
1341
- const deployment = resolveRuntimeEvidenceTickerUniverse({
791
+ const deployment = (0, runtimeEvidenceDeployment_exports.resolveRuntimeEvidenceTickerUniverse)({
1342
792
  deployment: composition.deployment,
1343
793
  lineageScopes: composition.lineageScopes,
1344
794
  fallbackTickers: composition.fallbackTickers
@@ -1371,14 +821,14 @@ var runtimeEvidence = async () => {
1371
821
  throw new Error("Runtime evidence window has no versioned runtime rows");
1372
822
  }
1373
823
  const artifact = current.artifact;
1374
- const outPath = import_node_path4.default.resolve(projectRoot, String(flags.out));
1375
- await import_promises4.default.mkdir(import_node_path4.default.dirname(outPath), { recursive: true });
1376
- await import_promises4.default.writeFile(outPath, `${JSON.stringify(artifact, null, 2)}
824
+ const outPath = import_node_path2.default.resolve(projectRoot, String(flags.out));
825
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(outPath), { recursive: true });
826
+ await import_promises2.default.writeFile(outPath, `${JSON.stringify(artifact, null, 2)}
1377
827
  `, "utf8");
1378
828
  const published = publishDir ? await Promise.all(
1379
829
  artifacts.map(
1380
- ({ artifact: artifact2, composition }) => publishRuntimeEvidenceBundle({
1381
- publishRoot: import_node_path4.default.resolve(projectRoot, publishDir),
830
+ ({ artifact: artifact2, composition }) => (0, runtimeEvidenceArtifacts_exports.publishRuntimeEvidenceBundle)({
831
+ publishRoot: import_node_path2.default.resolve(projectRoot, publishDir),
1382
832
  deploymentId,
1383
833
  userName: String(flags.user),
1384
834
  startTime,