create-tradejs 3.1.29-beta.268 → 3.1.29-beta.270

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 (22) hide show
  1. package/dist/skill-bundle/.codex/skills/ai-train-local-research/SKILL.md +44 -1
  2. package/dist/skill-bundle/.codex/skills/ai-train-local-research/references/gate-ablation.md +303 -0
  3. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs +1650 -16
  4. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/ai-gate-ablation.test.mjs +2125 -14
  5. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/decision-capture-join.mjs +1148 -0
  6. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/decision-capture-join.test.mjs +841 -0
  7. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/decision-capture-storage.mjs +1122 -0
  8. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/decision-capture-storage.test.mjs +656 -0
  9. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.mjs +945 -0
  10. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.test.mjs +1122 -0
  11. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/SKILL.md +33 -1
  12. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.mjs +185 -6
  13. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.test.mjs +314 -3
  14. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/references/final-composition-board.md +139 -0
  15. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/build-final-composition-spec.mjs +137 -1
  16. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/build-final-composition-spec.test.mjs +32 -0
  17. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/executed-composition-report.mjs +2203 -0
  18. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/executed-composition-report.test.mjs +1172 -0
  19. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/final-composition-board.mjs +960 -18
  20. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/scripts/final-composition-board.test.mjs +393 -1
  21. package/dist/skill-bundle/.codex/tradejs-skill-bundle.json +21 -13
  22. package/package.json +1 -1
@@ -7,6 +7,7 @@ import readline from 'node:readline';
7
7
  import { execFileSync } from 'node:child_process';
8
8
  import { createRequire } from 'node:module';
9
9
  import { pathToFileURL } from 'node:url';
10
+ import { createHash } from 'node:crypto';
10
11
 
11
12
  const DAY_MS = 24 * 60 * 60 * 1000;
12
13
  const MONTH_DAYS = 30.4375;
@@ -19,6 +20,21 @@ const DEFAULT_MA_PERIODS = Array.from(
19
20
  (_, index) => (index + 1) * 5,
20
21
  );
21
22
  const VARIANT_MODES = new Set(['filter', 'exclude', 'add', 'replace']);
23
+ const ENTRY_NOTIONAL_AUTHORITY_SCHEMA = 'tradejs-entry-notional-authority/v1';
24
+ const ENTRY_NOTIONAL_METHOD = 'fee-derived-full-closed';
25
+ const ENTRY_NOTIONAL_ROUNDING_POLICY =
26
+ 'decimal-half-unit-plus-binary64-interval-v1';
27
+ const REVIEWED_ENTRY_NOTIONAL_SEMANTICS = Object.freeze({
28
+ receiptSha256:
29
+ '2734c38558d7318106e8ed729c7b403468c9cf06e7b4ff011ddb6cd958ecb0c0',
30
+ receiptSchema: 'tradejs-entry-notional-semantics-receipt/v1',
31
+ semanticsId: 'tradejs-node-backtest-open-fee-unrounded-entry-price-8dp/v1',
32
+ moduleSha256:
33
+ '2b6f586211b9057a73758909cc2816e0df90028f66f6b293362ba8661f24221f',
34
+ packageName: '@tradejs/node',
35
+ relativePath: 'dist/backtest.mjs',
36
+ displayPriceDecimals: 8,
37
+ });
22
38
 
23
39
  const usage = `Usage:
24
40
  node .codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs [options]
@@ -38,12 +54,20 @@ Options:
38
54
  --testSince <timestamp> Exact UTC boundary where test starts
39
55
  --windowStart <timestamp> Common comparison start, inclusive
40
56
  --windowEnd <timestamp> Common comparison end, exclusive
57
+ --labelEndBefore <timestamp> Discovery only: purge unknown/crossing exits before gate evaluation; must equal windowEnd
58
+ --runtimeCheckpoint <json> Verify and execute the frozen Project-installed framework runtime
59
+ --strategyArtifactAuthority <json> Explicit frozen standalone source/build/artifact authority; requires runtimeCheckpoint
60
+ --materializeDiscoveryExport <jsonl> Raw-only immutable maturity-purged discovery view; no gate or feature evaluation
61
+ --timestampPartitionMetadata <json> Immutable timestamp-only outer 60/40 boundary; no outcomes/runtime
41
62
  --capacities <list> Capacity stress limits (default: 1,3,5)
42
63
  --maxLossValue <n> Per-order loss budget for capacity stress
43
64
  --featurePattern <regex> Inventory matching causal feature paths
44
65
  --cohortPath <path> Audit feature availability by UTC year/direction/payload cohort
45
66
  --costStressBps <list> Additional slippage per entry and exit, diagnostics only
67
+ --roundTripCostStressBps <list> Extra round-trip bps on actual entry notional; requires realizedMetrics
68
+ --entryNotionalAuthority <json> Opt-in checksum-bound fee-derived full-closure notional for round-trip stress
46
69
  --realizedMetrics Additional completed-trade metrics ordered by actual exit time
70
+ --symbolCohorts <path> Disjoint frozen symbol groups, diagnostic realized metrics only
47
71
  --monthlyCohorts Calendar monthly export/gate funnel by direction and payload cohort
48
72
  --compareTo <variant> Exact added/removed approval slices versus a named variant
49
73
  --includeGateContext Include current gate output fields for audits only
@@ -100,11 +124,19 @@ export const parseCliArgs = (argv) => {
100
124
  testSplit: 0.4,
101
125
  tuningSince: null,
102
126
  testSince: null,
127
+ labelEndBefore: null,
128
+ runtimeCheckpoint: null,
129
+ strategyArtifactAuthority: null,
130
+ materializeDiscoveryExport: null,
131
+ timestampPartitionMetadata: null,
103
132
  capacities: DEFAULT_CAPACITIES,
104
133
  maxLossValue: null,
105
134
  cohortPath: null,
106
135
  costStressBps: [],
136
+ roundTripCostStressBps: [],
137
+ entryNotionalAuthority: null,
107
138
  realizedMetrics: false,
139
+ symbolCohorts: null,
108
140
  monthlyCohorts: false,
109
141
  compareTo: null,
110
142
  variants: [],
@@ -169,7 +201,7 @@ export const parseCliArgs = (argv) => {
169
201
  );
170
202
  } else if (name === 'terminalWindows') {
171
203
  options.terminalWindows = parseNumberList(value, DEFAULT_WINDOWS);
172
- } else if (name === 'costStressBps') {
204
+ } else if (['costStressBps', 'roundTripCostStressBps'].includes(name)) {
173
205
  const values = String(value).split(',').map(Number);
174
206
  if (
175
207
  !values.length ||
@@ -179,7 +211,7 @@ export const parseCliArgs = (argv) => {
179
211
  `Invalid positive basis points for --${name}: ${value}`,
180
212
  );
181
213
  }
182
- options.costStressBps = [...new Set(values)];
214
+ options[name] = [...new Set(values)];
183
215
  } else if (name === 'validationSplit') {
184
216
  const parsed = Number(value);
185
217
  options.validationSplit = Number.isFinite(parsed)
@@ -190,6 +222,23 @@ export const parseCliArgs = (argv) => {
190
222
  options.testSplit = Number.isFinite(parsed)
191
223
  ? Math.max(0, Math.min(0.9, parsed))
192
224
  : 0;
225
+ } else if (name === 'labelEndBefore') {
226
+ const parsed = /^\d+$/.test(value) ? Number(value) : Date.parse(value);
227
+ if (
228
+ !Number.isSafeInteger(parsed) ||
229
+ parsed < 0 ||
230
+ parsed > 8.64e15 ||
231
+ (!/^\d+$/.test(value) &&
232
+ (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(
233
+ value,
234
+ ) ||
235
+ new Date(parsed).toISOString().slice(0, 10) !== value.slice(0, 10)))
236
+ ) {
237
+ throw new Error(
238
+ 'labelEndBefore requires valid UTC ISO ending in Z or epoch milliseconds',
239
+ );
240
+ }
241
+ options.labelEndBefore = parsed;
193
242
  } else if (
194
243
  ['tuningSince', 'testSince', 'windowStart', 'windowEnd'].includes(name)
195
244
  ) {
@@ -249,6 +298,12 @@ export const parseCliArgs = (argv) => {
249
298
  'cohortPath',
250
299
  'compareTo',
251
300
  'output',
301
+ 'runtimeCheckpoint',
302
+ 'strategyArtifactAuthority',
303
+ 'entryNotionalAuthority',
304
+ 'materializeDiscoveryExport',
305
+ 'timestampPartitionMetadata',
306
+ 'symbolCohorts',
252
307
  ].includes(name)
253
308
  ) {
254
309
  options[name] = value;
@@ -257,6 +312,36 @@ export const parseCliArgs = (argv) => {
257
312
  }
258
313
  }
259
314
 
315
+ if (options.timestampPartitionMetadata) {
316
+ const allowed = new Set([
317
+ 'timestampPartitionMetadata',
318
+ 'file',
319
+ 'strategy',
320
+ 'outDir',
321
+ 'windowStart',
322
+ 'windowEnd',
323
+ 'validationSplit',
324
+ 'testSplit',
325
+ 'json',
326
+ 'help',
327
+ ]);
328
+ const names = argv
329
+ .filter((value) => value.startsWith('--'))
330
+ .map((value) => value.slice(2).split('=')[0]);
331
+ if (
332
+ names.some((name) => !allowed.has(name)) ||
333
+ !names.includes('validationSplit') ||
334
+ !names.includes('testSplit') ||
335
+ options.validationSplit !== 0 ||
336
+ options.testSplit !== 0.4 ||
337
+ !Number.isSafeInteger(options.windowStart) ||
338
+ !Number.isSafeInteger(options.windowEnd)
339
+ )
340
+ throw new Error(
341
+ '--timestampPartitionMetadata requires explicit window, validationSplit 0 and testSplit 0.4; metadata options only',
342
+ );
343
+ validateResearchWindow(options.windowStart, options.windowEnd);
344
+ }
260
345
  if (options.cohortPath && !options.featurePattern) {
261
346
  throw new Error(
262
347
  '--cohortPath requires --featurePattern for the diagnostic inventory',
@@ -265,6 +350,74 @@ export const parseCliArgs = (argv) => {
265
350
  if (options.monthlyCohorts && !options.cohortPath) {
266
351
  throw new Error('--monthlyCohorts requires --cohortPath');
267
352
  }
353
+ if (
354
+ options.symbolCohorts &&
355
+ (!options.realizedMetrics ||
356
+ options.crossStrategy ||
357
+ options.movingAverageStudy)
358
+ ) {
359
+ throw new Error('--symbolCohorts requires single-core --realizedMetrics');
360
+ }
361
+ if (
362
+ options.labelEndBefore != null &&
363
+ (options.crossStrategy ||
364
+ options.windowStart == null ||
365
+ options.windowEnd !== options.labelEndBefore ||
366
+ options.testSince !== options.labelEndBefore ||
367
+ options.validationSplit !== 0 ||
368
+ options.tuningSince != null)
369
+ ) {
370
+ throw new Error(
371
+ '--labelEndBefore requires a single-core discovery window and testSince ending at the same cutoff, with validationSplit 0',
372
+ );
373
+ }
374
+ if (
375
+ options.strategyArtifactAuthority &&
376
+ (!options.runtimeCheckpoint || options.crossStrategy)
377
+ ) {
378
+ throw new Error(
379
+ '--strategyArtifactAuthority requires --runtimeCheckpoint and single-core mode',
380
+ );
381
+ }
382
+ if (
383
+ options.entryNotionalAuthority &&
384
+ (!options.runtimeCheckpoint ||
385
+ !options.roundTripCostStressBps.length ||
386
+ !options.realizedMetrics ||
387
+ options.windowStart == null ||
388
+ options.windowEnd == null ||
389
+ options.crossStrategy ||
390
+ options.movingAverageStudy ||
391
+ options.materializeDiscoveryExport)
392
+ ) {
393
+ throw new Error(
394
+ '--entryNotionalAuthority requires single-core --runtimeCheckpoint, --roundTripCostStressBps, --realizedMetrics and explicit window bounds',
395
+ );
396
+ }
397
+ if (options.materializeDiscoveryExport) {
398
+ const allowed = new Set([
399
+ 'materializeDiscoveryExport',
400
+ 'file',
401
+ 'strategy',
402
+ 'outDir',
403
+ 'windowStart',
404
+ 'windowEnd',
405
+ 'testSince',
406
+ 'labelEndBefore',
407
+ 'validationSplit',
408
+ 'testSplit',
409
+ 'json',
410
+ 'help',
411
+ ]);
412
+ const disallowed = argv
413
+ .filter((value) => value.startsWith('--'))
414
+ .map((value) => value.slice(2).split('=')[0])
415
+ .filter((name) => !allowed.has(name));
416
+ if (options.labelEndBefore == null || disallowed.length)
417
+ throw new Error(
418
+ '--materializeDiscoveryExport requires exact discovery label bounds and cannot accept evaluation/runtime options',
419
+ );
420
+ }
268
421
  return options;
269
422
  };
270
423
 
@@ -1476,14 +1629,218 @@ const resolveStandaloneStrategyEntrypoint = (sourceRepositoryRoot) => {
1476
1629
  return { entrypoint, packageJson };
1477
1630
  };
1478
1631
 
1479
- export const loadStandaloneStrategyEntries = async (sourceRepositoryRoot) => {
1632
+ export const verifyStrategyArtifactAuthority = ({
1633
+ sourceRepositoryRoot,
1634
+ projectRoot,
1635
+ strategyArtifactAuthority,
1636
+ executionRuntime,
1637
+ }) => {
1638
+ if (!executionRuntime)
1639
+ throw new Error(
1640
+ 'Strategy artifact authority requires verified runtime checkpoint',
1641
+ );
1642
+ const authorityPath = projectBoundPath(
1643
+ strategyArtifactAuthority,
1644
+ projectRoot,
1645
+ );
1646
+ const authorityBytes = fs.readFileSync(authorityPath);
1647
+ const authority = JSON.parse(authorityBytes);
1648
+ if (authority.schema !== 'tradejs-strategy-artifact-authority/v1')
1649
+ throw new Error('Unsupported strategy artifact authority schema');
1650
+ const base = path.dirname(authorityPath);
1651
+ const exactSource = resolveExactGitCheckout(
1652
+ sourceRepositoryRoot,
1653
+ 'strategy source',
1654
+ );
1655
+ const authorizedSource = resolveExactGitCheckout(
1656
+ path.resolve(base, authority.sourceRepositoryRoot),
1657
+ 'authority source',
1658
+ );
1659
+ if (
1660
+ authorizedSource !== exactSource ||
1661
+ getSourceRepositoryKind(exactSource) !== 'strategy'
1662
+ )
1663
+ throw new Error('Strategy artifact source mismatch');
1664
+ const head = execFileSync('git', ['-C', exactSource, 'rev-parse', 'HEAD'], {
1665
+ encoding: 'utf8',
1666
+ }).trim();
1667
+ if (
1668
+ !/^[a-f0-9]{40}$/.test(authority.sourceGitSha ?? '') ||
1669
+ head !== authority.sourceGitSha
1670
+ )
1671
+ throw new Error('Strategy artifact source Git SHA mismatch');
1672
+ const sourceDiff = checkedAuthorityFile(
1673
+ authority.sourceDiff,
1674
+ projectRoot,
1675
+ base,
1676
+ );
1677
+ const buildReceipt = checkedAuthorityFile(
1678
+ authority.buildReceipt,
1679
+ projectRoot,
1680
+ base,
1681
+ );
1682
+ const checkpoint = checkedAuthorityFile(
1683
+ authority.runtimeCheckpoint,
1684
+ projectRoot,
1685
+ base,
1686
+ );
1687
+ if (
1688
+ checkpoint.path !== executionRuntime.checkpoint.path ||
1689
+ checkpoint.sha256 !== executionRuntime.checkpoint.sha256
1690
+ )
1691
+ throw new Error('Strategy artifact runtime checkpoint mismatch');
1692
+ const packageRoot = projectBoundPath(
1693
+ authority.packageRoot,
1694
+ projectRoot,
1695
+ base,
1696
+ );
1697
+ if (packageRoot.startsWith(`${fs.realpathSync(projectRoot)}/node_modules/`))
1698
+ throw new Error(
1699
+ 'Strategy artifact must be an explicit compiled evidence package, not installed Project strategy',
1700
+ );
1701
+ const packageBytes = fs.readFileSync(
1702
+ projectBoundPath(path.join(packageRoot, 'package.json'), projectRoot),
1703
+ );
1704
+ if (artifactSha256(packageBytes) !== authority.packageJsonSha256)
1705
+ throw new Error('Strategy artifact package checksum mismatch');
1706
+ const packageJson = JSON.parse(packageBytes);
1707
+ const baselinePackage = JSON.parse(
1708
+ execFileSync('git', ['-C', exactSource, 'show', `${head}:package.json`], {
1709
+ encoding: 'utf8',
1710
+ }),
1711
+ );
1712
+ if (
1713
+ packageJson.name !== baselinePackage.name ||
1714
+ packageJson.name !== readRepositoryPackage(exactSource)?.name
1715
+ )
1716
+ throw new Error('Strategy artifact target package name mismatch');
1717
+ const distRoot = projectBoundPath(
1718
+ path.join(packageRoot, 'dist'),
1719
+ projectRoot,
1720
+ );
1721
+ if (
1722
+ distRoot !== path.join(packageRoot, 'dist') ||
1723
+ hashArtifactDist(distRoot) !== authority.distSha256
1724
+ )
1725
+ throw new Error('Strategy artifact dist checksum mismatch');
1726
+ const build = JSON.parse(buildReceipt.bytes);
1727
+ if (
1728
+ build.schema !== 'tradejs-source-development-dependency-overlay/v1' ||
1729
+ build.status !== 'passed' ||
1730
+ build.restored !== true ||
1731
+ fs.realpathSync(build.sourceRoot) !== exactSource ||
1732
+ build.builtDistTreeSha256 !== authority.distSha256
1733
+ )
1734
+ throw new Error('Strategy artifact build receipt mismatch');
1735
+ for (const name of ['core', 'types', 'strategy-kit']) {
1736
+ const dependency = build.packages?.find((item) => item.name === name);
1737
+ const expected = executionRuntime.packages[`@tradejs/${name}`];
1738
+ if (
1739
+ !dependency?.restored ||
1740
+ dependency.executedVersion !== expected?.version ||
1741
+ dependency.executedTreeSha256 !== hashArtifactDist(expected.packageRoot)
1742
+ )
1743
+ throw new Error(`Strategy artifact build dependency mismatch: ${name}`);
1744
+ }
1745
+ const { entrypoint } = resolveStandaloneStrategyEntrypoint(packageRoot);
1746
+ if (
1747
+ projectBoundPath(entrypoint, projectRoot) !== entrypoint ||
1748
+ !entrypoint.startsWith(`${distRoot}${path.sep}`)
1749
+ )
1750
+ throw new Error(
1751
+ 'Strategy artifact entrypoint must remain in its frozen dist',
1752
+ );
1753
+ const externalImports = new Map();
1754
+ const walk = (directory) => {
1755
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1756
+ const full = path.join(directory, entry.name);
1757
+ if (entry.isDirectory()) walk(full);
1758
+ else if (/\.[cm]?js$/.test(entry.name)) {
1759
+ const require = createRequire(full);
1760
+ const text = fs.readFileSync(full, 'utf8');
1761
+ for (const match of text.matchAll(
1762
+ /\b(?:from\s*|import\s*(?:\(\s*)?|require\s*\(\s*)['"]([^'"]+)['"]/g,
1763
+ )) {
1764
+ const specifier = match[1];
1765
+ if (specifier.startsWith('.')) {
1766
+ const resolved = fs.realpathSync(
1767
+ path.resolve(path.dirname(full), specifier),
1768
+ );
1769
+ if (!resolved.startsWith(`${distRoot}${path.sep}`))
1770
+ throw new Error('Strategy artifact relative import escapes dist');
1771
+ continue;
1772
+ }
1773
+ if (specifier.startsWith('node:')) continue;
1774
+ const resolved = require.resolve(specifier);
1775
+ if (!path.isAbsolute(resolved)) continue;
1776
+ const real = fs.realpathSync(resolved);
1777
+ const projectModules = `${fs.realpathSync(projectRoot)}/node_modules/`;
1778
+ if (!real.startsWith(projectModules))
1779
+ throw new Error(
1780
+ `Foreign strategy artifact dependency: ${specifier}`,
1781
+ );
1782
+ if (specifier.startsWith('@tradejs/')) {
1783
+ const name = specifier.split('/').slice(0, 2).join('/');
1784
+ const expected = executionRuntime.packages[name];
1785
+ if (!expected || !real.startsWith(`${expected.packageRoot}/dist/`))
1786
+ throw new Error(
1787
+ `Unbound strategy artifact dependency: ${specifier}`,
1788
+ );
1789
+ }
1790
+ externalImports.set(`${full}:${specifier}`, {
1791
+ importer: full,
1792
+ specifier,
1793
+ resolved: real,
1794
+ sha256: artifactSha256(fs.readFileSync(real)),
1795
+ });
1796
+ }
1797
+ }
1798
+ }
1799
+ };
1800
+ walk(distRoot);
1801
+ return {
1802
+ entrypoint,
1803
+ strategyArtifact: {
1804
+ role: 'historical frozen core source identity; explicitly authorized compiled gate artifact imported under current checkpoint',
1805
+ authority: {
1806
+ path: authorityPath,
1807
+ sha256: artifactSha256(authorityBytes),
1808
+ },
1809
+ sourceRepositoryRoot: exactSource,
1810
+ sourceGitSha: head,
1811
+ sourceDiff: { path: sourceDiff.path, sha256: sourceDiff.sha256 },
1812
+ buildReceipt: { path: buildReceipt.path, sha256: buildReceipt.sha256 },
1813
+ packageRoot,
1814
+ packageName: packageJson.name,
1815
+ packageJsonSha256: authority.packageJsonSha256,
1816
+ distSha256: authority.distSha256,
1817
+ entrypoint,
1818
+ runtimeCheckpoint: { path: checkpoint.path, sha256: checkpoint.sha256 },
1819
+ externalImports: [...externalImports.values()],
1820
+ liveDirtyDiffComparedToHistoricalPatch: false,
1821
+ },
1822
+ };
1823
+ };
1824
+
1825
+ export const loadStandaloneStrategyEntries = async (
1826
+ sourceRepositoryRoot,
1827
+ options = null,
1828
+ ) => {
1480
1829
  if (getSourceRepositoryKind(sourceRepositoryRoot) !== 'strategy') {
1481
1830
  throw new Error(
1482
1831
  `Expected a standalone TradeJS strategy repository: ${sourceRepositoryRoot}`,
1483
1832
  );
1484
1833
  }
1485
- const { entrypoint, packageJson } =
1834
+ if (options?.executionRuntime && !options.strategyArtifactAuthority)
1835
+ throw new Error(
1836
+ 'Checkpoint execution requires explicit --strategyArtifactAuthority for standalone source',
1837
+ );
1838
+ const artifact = options?.strategyArtifactAuthority
1839
+ ? verifyStrategyArtifactAuthority({ ...options, sourceRepositoryRoot })
1840
+ : null;
1841
+ const { entrypoint: sourceEntrypoint, packageJson } =
1486
1842
  resolveStandaloneStrategyEntrypoint(sourceRepositoryRoot);
1843
+ const entrypoint = artifact?.entrypoint ?? sourceEntrypoint;
1487
1844
  let outputStat;
1488
1845
  try {
1489
1846
  outputStat = await fsp.stat(entrypoint);
@@ -1495,7 +1852,7 @@ export const loadStandaloneStrategyEntries = async (sourceRepositoryRoot) => {
1495
1852
  const sourceMtime = await newestSourceMtime(
1496
1853
  path.join(sourceRepositoryRoot, 'src'),
1497
1854
  );
1498
- if (sourceMtime > outputStat.mtimeMs) {
1855
+ if (!artifact && sourceMtime > outputStat.mtimeMs) {
1499
1856
  throw new Error(
1500
1857
  `Stale ${path.relative(sourceRepositoryRoot, entrypoint)} for ${packageJson.name}. Run yarn build in TRADEJS_SOURCE_REPOSITORY_ROOT first.`,
1501
1858
  );
@@ -1512,10 +1869,498 @@ export const loadStandaloneStrategyEntries = async (sourceRepositoryRoot) => {
1512
1869
  entrypoint,
1513
1870
  packageName: packageJson.name,
1514
1871
  strategyEntries,
1872
+ ...(artifact ? { strategyArtifact: artifact.strategyArtifact } : {}),
1873
+ };
1874
+ };
1875
+
1876
+ const artifactSha256 = (bytes) =>
1877
+ createHash('sha256').update(bytes).digest('hex');
1878
+ const CHECKPOINT_TREE_ALGORITHM =
1879
+ 'SHA256 of sorted SHA256(relativefilebytes) space relativepath newline';
1880
+
1881
+ export const hashArtifactDist = (directory) => {
1882
+ const files = [];
1883
+ const walk = (current) => {
1884
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
1885
+ const full = path.join(current, entry.name);
1886
+ if (entry.isSymbolicLink())
1887
+ throw new Error(`Artifact dist cannot contain symlinks: ${full}`);
1888
+ if (entry.isDirectory()) walk(full);
1889
+ else if (entry.isFile()) files.push(full);
1890
+ else throw new Error(`Unsupported artifact dist entry: ${full}`);
1891
+ }
1892
+ };
1893
+ walk(directory);
1894
+ return artifactSha256(
1895
+ files
1896
+ .sort()
1897
+ .map(
1898
+ (file) =>
1899
+ `${artifactSha256(fs.readFileSync(file))} ${path.relative(directory, file)}\n`,
1900
+ )
1901
+ .join(''),
1902
+ );
1903
+ };
1904
+
1905
+ const projectBoundPath = (value, projectRoot, baseDirectory = projectRoot) => {
1906
+ if (typeof value !== 'string' || !value.trim())
1907
+ throw new Error('Authority requires an explicit path');
1908
+ const actual = fs.realpathSync(path.resolve(baseDirectory, value));
1909
+ const root = fs.realpathSync(projectRoot);
1910
+ if (!actual.startsWith(`${root}${path.sep}`))
1911
+ throw new Error(`Authority path must remain inside Project: ${actual}`);
1912
+ return actual;
1913
+ };
1914
+
1915
+ const checkedAuthorityFile = (reference, projectRoot, baseDirectory) => {
1916
+ if (!/^[a-f0-9]{64}$/.test(reference?.sha256 ?? ''))
1917
+ throw new Error('Authority requires a SHA256 checksum');
1918
+ const filePath = projectBoundPath(reference.path, projectRoot, baseDirectory);
1919
+ const bytes = fs.readFileSync(filePath);
1920
+ if (artifactSha256(bytes) !== reference.sha256)
1921
+ throw new Error(`Authority checksum mismatch: ${filePath}`);
1922
+ return { path: filePath, sha256: reference.sha256, bytes };
1923
+ };
1924
+
1925
+ const canonicalizeEntryNotionalJson = (value) => {
1926
+ if (Array.isArray(value)) return value.map(canonicalizeEntryNotionalJson);
1927
+ if (value && typeof value === 'object') {
1928
+ return Object.fromEntries(
1929
+ Object.keys(value)
1930
+ .sort()
1931
+ .map((key) => [key, canonicalizeEntryNotionalJson(value[key])]),
1932
+ );
1933
+ }
1934
+ return value;
1935
+ };
1936
+
1937
+ export const canonicalEntryNotionalJsonSha256 = (value) =>
1938
+ artifactSha256(
1939
+ Buffer.from(JSON.stringify(canonicalizeEntryNotionalJson(value)), 'utf8'),
1940
+ );
1941
+
1942
+ const readJsonPointer = (value, pointer) => {
1943
+ if (typeof pointer !== 'string' || !pointer.startsWith('/'))
1944
+ throw new Error('Entry-notional config requires an absolute JSON pointer');
1945
+ return pointer
1946
+ .slice(1)
1947
+ .split('/')
1948
+ .map((token) => {
1949
+ if (/~(?:[^01]|$)/.test(token))
1950
+ throw new Error(
1951
+ 'Entry-notional config contains an invalid JSON pointer',
1952
+ );
1953
+ return token.replaceAll('~1', '/').replaceAll('~0', '~');
1954
+ })
1955
+ .reduce((current, key) => current?.[key], value);
1956
+ };
1957
+
1958
+ const assertPositiveEqualEntryFees = (declared, resolved) => {
1959
+ const declaredMaker = declared?.makerRate;
1960
+ const declaredTaker = declared?.takerRate;
1961
+ const resolvedMaker = resolved?.makerRate;
1962
+ const resolvedTaker = resolved?.takerRate;
1963
+ if (
1964
+ ![declaredMaker, declaredTaker, resolvedMaker, resolvedTaker].every(
1965
+ (value) =>
1966
+ typeof value === 'number' && Number.isFinite(value) && value > 0,
1967
+ ) ||
1968
+ declaredMaker !== declaredTaker ||
1969
+ resolvedMaker !== resolvedTaker ||
1970
+ declaredMaker !== resolvedMaker
1971
+ ) {
1972
+ throw new Error(
1973
+ 'Entry-notional authority requires exactly equal positive maker/taker fees in authority and resolved config',
1974
+ );
1975
+ }
1976
+ return declaredMaker;
1977
+ };
1978
+
1979
+ export const verifyEntryNotionalAuthority = async ({
1980
+ projectRoot,
1981
+ entryNotionalAuthority,
1982
+ executionRuntime,
1983
+ filePaths,
1984
+ reviewedSemanticsPolicy = REVIEWED_ENTRY_NOTIONAL_SEMANTICS,
1985
+ }) => {
1986
+ if (
1987
+ !executionRuntime?.checkpoint ||
1988
+ !executionRuntime?.packages?.['@tradejs/node']
1989
+ )
1990
+ throw new Error(
1991
+ 'Entry-notional authority requires a verified runtime checkpoint',
1992
+ );
1993
+ const authorityPath = projectBoundPath(entryNotionalAuthority, projectRoot);
1994
+ const authorityBytes = fs.readFileSync(authorityPath);
1995
+ const authority = JSON.parse(authorityBytes);
1996
+ if (
1997
+ authority.schema !== ENTRY_NOTIONAL_AUTHORITY_SCHEMA ||
1998
+ authority.method !== ENTRY_NOTIONAL_METHOD
1999
+ )
2000
+ throw new Error('Unsupported entry-notional authority contract');
2001
+ if (
2002
+ authority.displayPriceDecimals !==
2003
+ reviewedSemanticsPolicy.displayPriceDecimals ||
2004
+ authority.roundingPolicy?.id !== ENTRY_NOTIONAL_ROUNDING_POLICY
2005
+ )
2006
+ throw new Error('Unsupported entry-notional rounding contract');
2007
+ const base = path.dirname(authorityPath);
2008
+ const checkpoint = checkedAuthorityFile(
2009
+ authority.runtimeCheckpoint,
2010
+ projectRoot,
2011
+ base,
2012
+ );
2013
+ if (
2014
+ checkpoint.path !== executionRuntime.checkpoint.path ||
2015
+ checkpoint.sha256 !== executionRuntime.checkpoint.sha256
2016
+ )
2017
+ throw new Error('Entry-notional runtime checkpoint mismatch');
2018
+
2019
+ const receipt = checkedAuthorityFile(
2020
+ authority.semanticsReceipt,
2021
+ projectRoot,
2022
+ base,
2023
+ );
2024
+ const receiptValue = JSON.parse(receipt.bytes);
2025
+ if (
2026
+ receipt.sha256 !== reviewedSemanticsPolicy.receiptSha256 ||
2027
+ receiptValue.schema !== reviewedSemanticsPolicy.receiptSchema ||
2028
+ receiptValue.semanticsId !== reviewedSemanticsPolicy.semanticsId ||
2029
+ receiptValue.reviewedModule?.packageName !==
2030
+ reviewedSemanticsPolicy.packageName ||
2031
+ receiptValue.reviewedModule?.relativePath !==
2032
+ reviewedSemanticsPolicy.relativePath ||
2033
+ receiptValue.reviewedModule?.sha256 !==
2034
+ reviewedSemanticsPolicy.moduleSha256 ||
2035
+ receiptValue.reviewedSemantics?.displayPriceDecimals !==
2036
+ reviewedSemanticsPolicy.displayPriceDecimals
2037
+ )
2038
+ throw new Error('Unsupported reviewed semantics receipt');
2039
+
2040
+ const module = authority.executionModule;
2041
+ if (
2042
+ module?.packageName !== reviewedSemanticsPolicy.packageName ||
2043
+ module?.relativePath !== reviewedSemanticsPolicy.relativePath ||
2044
+ module?.sha256 !== reviewedSemanticsPolicy.moduleSha256
2045
+ )
2046
+ throw new Error('Entry-notional execution module mismatch');
2047
+ const nodePackageRoot = projectBoundPath(
2048
+ executionRuntime.packages['@tradejs/node'].packageRoot,
2049
+ projectRoot,
2050
+ );
2051
+ const modulePath = projectBoundPath(
2052
+ path.join(nodePackageRoot, module.relativePath),
2053
+ projectRoot,
2054
+ );
2055
+ if (
2056
+ modulePath !==
2057
+ path.join(nodePackageRoot, reviewedSemanticsPolicy.relativePath) ||
2058
+ artifactSha256(fs.readFileSync(modulePath)) !== module.sha256
2059
+ )
2060
+ throw new Error('Entry-notional execution module mismatch');
2061
+
2062
+ const config = checkedAuthorityFile(
2063
+ authority.resolvedExecutionConfig,
2064
+ projectRoot,
2065
+ base,
2066
+ );
2067
+ const configValue = JSON.parse(config.bytes);
2068
+ const costs = readJsonPointer(
2069
+ configValue,
2070
+ authority.resolvedExecutionConfig.executionCostsJsonPointer,
2071
+ );
2072
+ if (!costs || typeof costs !== 'object' || Array.isArray(costs))
2073
+ throw new Error('Entry-notional resolved executionCosts are missing');
2074
+ const costsSha256 = canonicalEntryNotionalJsonSha256(costs);
2075
+ if (
2076
+ !/^[a-f0-9]{64}$/.test(
2077
+ authority.resolvedExecutionConfig.executionCostsCanonicalSha256 ?? '',
2078
+ ) ||
2079
+ costsSha256 !==
2080
+ authority.resolvedExecutionConfig.executionCostsCanonicalSha256
2081
+ )
2082
+ throw new Error('Entry-notional resolved executionCosts checksum mismatch');
2083
+ const entryFeeRate = assertPositiveEqualEntryFees(
2084
+ authority.resolvedExecutionConfig.fees,
2085
+ costs.fees,
2086
+ );
2087
+
2088
+ if (
2089
+ !Array.isArray(authority.sourceExports) ||
2090
+ !authority.sourceExports.length ||
2091
+ !Array.isArray(filePaths) ||
2092
+ authority.sourceExports.length !== filePaths.length
2093
+ )
2094
+ throw new Error('Entry-notional ordered source export mismatch');
2095
+ const actualPaths = filePaths.map((filePath) =>
2096
+ projectBoundPath(filePath, projectRoot),
2097
+ );
2098
+ if (new Set(actualPaths).size !== actualPaths.length)
2099
+ throw new Error('Entry-notional source exports must be unique');
2100
+ const expectedPaths = authority.sourceExports.map((reference) => {
2101
+ if (!/^[a-f0-9]{64}$/.test(reference?.sha256 ?? ''))
2102
+ throw new Error('Entry-notional source export requires SHA256');
2103
+ return projectBoundPath(reference.path, projectRoot, base);
2104
+ });
2105
+ if (expectedPaths.some((filePath, index) => filePath !== actualPaths[index]))
2106
+ throw new Error('Entry-notional ordered source export mismatch');
2107
+ const sourceFilesBefore = await Promise.all(
2108
+ actualPaths.map(streamArtifactFileHash),
2109
+ );
2110
+ for (let index = 0; index < sourceFilesBefore.length; index += 1)
2111
+ if (
2112
+ sourceFilesBefore[index].sha256 !== authority.sourceExports[index].sha256
2113
+ )
2114
+ throw new Error(
2115
+ `Entry-notional source export checksum mismatch: ${actualPaths[index]}`,
2116
+ );
2117
+
2118
+ return {
2119
+ mode: ENTRY_NOTIONAL_METHOD,
2120
+ method: ENTRY_NOTIONAL_METHOD,
2121
+ authority: {
2122
+ path: authorityPath,
2123
+ sha256: artifactSha256(authorityBytes),
2124
+ },
2125
+ runtimeCheckpoint: { path: checkpoint.path, sha256: checkpoint.sha256 },
2126
+ semanticsReceipt: { path: receipt.path, sha256: receipt.sha256 },
2127
+ semanticsId: reviewedSemanticsPolicy.semanticsId,
2128
+ executionModule: {
2129
+ packageName: module.packageName,
2130
+ relativePath: module.relativePath,
2131
+ path: modulePath,
2132
+ sha256: module.sha256,
2133
+ },
2134
+ resolvedExecutionConfig: {
2135
+ path: config.path,
2136
+ sha256: config.sha256,
2137
+ executionCostsJsonPointer:
2138
+ authority.resolvedExecutionConfig.executionCostsJsonPointer,
2139
+ executionCostsCanonicalSha256: costsSha256,
2140
+ },
2141
+ entryFeeRate,
2142
+ displayPriceDecimals: authority.displayPriceDecimals,
2143
+ roundingPolicy: {
2144
+ id: ENTRY_NOTIONAL_ROUNDING_POLICY,
2145
+ unitRoundoff: Number.EPSILON / 2,
2146
+ nextRepresentable: 'DataView-based IEEE-754 binary64 nextUp/nextDown',
2147
+ ulpDefinition:
2148
+ 'max(x - nextDown(x), nextUp(x) - x) for finite positive x',
2149
+ displayAllowance: 'qty * 0.5 * 10 ** (-displayPriceDecimals)',
2150
+ binary64Allowance:
2151
+ 'ulp(openFee) / entryFeeRate + ulp(openFee / entryFeeRate) + abs(entryPrice) * ulp(qty) + abs(qty) * ulp(entryPrice) + ulp(qty * entryPrice)',
2152
+ },
2153
+ sourceExports: sourceFilesBefore,
2154
+ sourceFilesBefore,
2155
+ sourceFilesAfter: null,
2156
+ inputStabilityVerified: false,
2157
+ };
2158
+ };
2159
+
2160
+ export const verifyEntryNotionalInputStability = async (authority) => {
2161
+ if (
2162
+ authority?.method !== ENTRY_NOTIONAL_METHOD ||
2163
+ !Array.isArray(authority.sourceFilesBefore) ||
2164
+ !authority.sourceFilesBefore.length
2165
+ )
2166
+ throw new Error('Invalid verified entry-notional authority');
2167
+ const sourceFilesAfter = await Promise.all(
2168
+ authority.sourceFilesBefore.map(({ path: filePath }) =>
2169
+ streamArtifactFileHash(filePath),
2170
+ ),
2171
+ );
2172
+ if (
2173
+ JSON.stringify(sourceFilesAfter) !==
2174
+ JSON.stringify(authority.sourceFilesBefore)
2175
+ )
2176
+ throw new Error('Entry-notional source inputs changed during evaluation');
2177
+ return {
2178
+ ...authority,
2179
+ sourceFilesAfter,
2180
+ inputStabilityVerified: true,
2181
+ };
2182
+ };
2183
+
2184
+ export const normalizeSymbolCohorts = (input) => {
2185
+ if (
2186
+ input?.schema !== 'tradejs-symbol-cohorts/v1' ||
2187
+ !Array.isArray(input.groups) ||
2188
+ !input.groups.length
2189
+ ) {
2190
+ throw new Error(
2191
+ 'Symbol cohorts require tradejs-symbol-cohorts/v1 and nonempty groups',
2192
+ );
2193
+ }
2194
+ const ids = new Set();
2195
+ const symbols = new Set();
2196
+ const groups = input.groups.map((group) => {
2197
+ if (
2198
+ typeof group.id !== 'string' ||
2199
+ !group.id.trim() ||
2200
+ ids.has(group.id) ||
2201
+ !Array.isArray(group.symbols) ||
2202
+ !group.symbols.length
2203
+ ) {
2204
+ throw new Error(
2205
+ 'Symbol cohort IDs and symbol lists must be nonempty and unique',
2206
+ );
2207
+ }
2208
+ ids.add(group.id);
2209
+ for (const symbol of group.symbols) {
2210
+ if (
2211
+ typeof symbol !== 'string' ||
2212
+ !symbol.trim() ||
2213
+ symbol !== symbol.trim() ||
2214
+ symbols.has(symbol)
2215
+ ) {
2216
+ throw new Error(
2217
+ 'Symbol cohorts must contain valid disjoint unique symbols',
2218
+ );
2219
+ }
2220
+ symbols.add(symbol);
2221
+ }
2222
+ return { id: group.id, symbols: [...group.symbols] };
2223
+ });
2224
+ return { schema: input.schema, groups };
2225
+ };
2226
+
2227
+ export const loadSymbolCohorts = ({ projectRoot, file }) => {
2228
+ const filePath = projectBoundPath(file, projectRoot);
2229
+ const bytes = fs.readFileSync(filePath);
2230
+ return {
2231
+ ...normalizeSymbolCohorts(JSON.parse(bytes)),
2232
+ authority: { path: filePath, sha256: artifactSha256(bytes) },
2233
+ };
2234
+ };
2235
+
2236
+ const resolveCheckpointRuntime = ({ projectRoot, runtimeCheckpoint }) => {
2237
+ const checkpointPath = projectBoundPath(runtimeCheckpoint, projectRoot);
2238
+ const bytes = fs.readFileSync(checkpointPath);
2239
+ const checkpoint = JSON.parse(bytes);
2240
+ if (
2241
+ checkpoint.treeHashAlgorithm !== CHECKPOINT_TREE_ALGORITHM ||
2242
+ typeof checkpoint.generation !== 'string' ||
2243
+ !checkpoint.packages
2244
+ )
2245
+ throw new Error('Unsupported runtime checkpoint contract');
2246
+ const requiredPackages = [
2247
+ 'cli',
2248
+ 'core',
2249
+ 'node',
2250
+ 'types',
2251
+ 'infra',
2252
+ 'indicators',
2253
+ 'connectors',
2254
+ 'strategy-kit',
2255
+ ].map((name) => `@tradejs/${name}`);
2256
+ for (const name of requiredPackages)
2257
+ if (!checkpoint.packages[name])
2258
+ throw new Error(`Missing runtime checkpoint package: ${name}`);
2259
+ const packages = {};
2260
+ for (const [name, expected] of Object.entries(checkpoint.packages)) {
2261
+ if (!/^@tradejs\/[a-z0-9-]+$/.test(name))
2262
+ throw new Error(`Invalid runtime checkpoint package: ${name}`);
2263
+ const packageRoot = projectBoundPath(
2264
+ path.join(projectRoot, 'node_modules', name),
2265
+ projectRoot,
2266
+ );
2267
+ if (
2268
+ !packageRoot.startsWith(`${fs.realpathSync(projectRoot)}/node_modules/`)
2269
+ )
2270
+ throw new Error(`Foreign runtime package: ${name}`);
2271
+ const packageBytes = fs.readFileSync(
2272
+ path.join(packageRoot, 'package.json'),
2273
+ );
2274
+ const packageJson = JSON.parse(packageBytes);
2275
+ const distRoot = projectBoundPath(
2276
+ path.join(packageRoot, 'dist'),
2277
+ projectRoot,
2278
+ );
2279
+ if (distRoot !== path.join(packageRoot, 'dist'))
2280
+ throw new Error(`Foreign runtime dist: ${name}`);
2281
+ const actual = {
2282
+ version: packageJson.version,
2283
+ packageSha256: artifactSha256(packageBytes),
2284
+ distSha256: hashArtifactDist(distRoot),
2285
+ };
2286
+ if (
2287
+ packageJson.name !== name ||
2288
+ actual.version !== expected.version ||
2289
+ actual.packageSha256 !== expected.packageSha256 ||
2290
+ actual.distSha256 !== expected.distSha256
2291
+ )
2292
+ throw new Error(`Runtime checkpoint mismatch: ${name}`);
2293
+ if (
2294
+ requiredPackages.includes(name) &&
2295
+ name !== '@tradejs/strategy-kit' &&
2296
+ actual.version !== checkpoint.generation
2297
+ )
2298
+ throw new Error(`Runtime generation mismatch: ${name}`);
2299
+ packages[name] = { ...actual, packageRoot };
2300
+ }
2301
+ const nodeRoot = packages['@tradejs/node'].packageRoot;
2302
+ const projectTracked = {};
2303
+ if (checkpoint.projectTracked != null) {
2304
+ if (
2305
+ typeof checkpoint.projectTracked !== 'object' ||
2306
+ Array.isArray(checkpoint.projectTracked)
2307
+ )
2308
+ throw new Error('Invalid runtime checkpoint projectTracked');
2309
+ for (const [relativePath, expected] of Object.entries(
2310
+ checkpoint.projectTracked,
2311
+ )) {
2312
+ if (
2313
+ !['package.json', 'yarn.lock', 'tradejs.config.ts'].includes(
2314
+ relativePath,
2315
+ ) ||
2316
+ !/^[a-f0-9]{64}$/.test(expected)
2317
+ )
2318
+ throw new Error(
2319
+ `Invalid checkpoint Project path/checksum: ${relativePath}`,
2320
+ );
2321
+ const filePath = projectBoundPath(relativePath, projectRoot);
2322
+ const actual = artifactSha256(fs.readFileSync(filePath));
2323
+ if (actual !== expected)
2324
+ throw new Error(
2325
+ `Runtime checkpoint Project checksum mismatch: ${relativePath}`,
2326
+ );
2327
+ projectTracked[relativePath] = { path: filePath, sha256: actual };
2328
+ }
2329
+ }
2330
+ const cliRoot = packages['@tradejs/cli'].packageRoot;
2331
+ const modules = {
2332
+ aiModulePath: path.join(nodeRoot, 'dist/ai.mjs'),
2333
+ registryModulePath: path.join(nodeRoot, 'dist/registry.mjs'),
2334
+ pocketModulePath: path.join(cliRoot, 'dist/lib/aiPocketSearch.js'),
2335
+ };
2336
+ for (const filePath of Object.values(modules))
2337
+ if (projectBoundPath(filePath, projectRoot) !== filePath)
2338
+ throw new Error(`Foreign runtime module: ${filePath}`);
2339
+ return {
2340
+ ...modules,
2341
+ executionRuntime: {
2342
+ mode: 'verified-project-runtime-checkpoint',
2343
+ projectRoot: fs.realpathSync(projectRoot),
2344
+ checkpoint: { path: checkpointPath, sha256: artifactSha256(bytes) },
2345
+ generation: checkpoint.generation,
2346
+ treeHashAlgorithm: checkpoint.treeHashAlgorithm,
2347
+ packages,
2348
+ projectTracked,
2349
+ modules: Object.fromEntries(
2350
+ Object.entries(modules).map(([key, filePath]) => [
2351
+ key,
2352
+ { path: filePath, sha256: artifactSha256(fs.readFileSync(filePath)) },
2353
+ ]),
2354
+ ),
2355
+ },
1515
2356
  };
1516
2357
  };
1517
2358
 
1518
- export const ensureRuntimeBuild = async (frameworkRepositoryRoot) => {
2359
+ export const ensureRuntimeBuild = async (
2360
+ frameworkRepositoryRoot,
2361
+ options = null,
2362
+ ) => {
2363
+ if (options?.runtimeCheckpoint) return resolveCheckpointRuntime(options);
1519
2364
  const aiModulePath = path.join(
1520
2365
  frameworkRepositoryRoot,
1521
2366
  'packages/node/dist/ai.mjs',
@@ -1626,6 +2471,123 @@ export const getCostStressNotional = (tradeResult) => {
1626
2471
  return quantity * (entryPrice + exitPrice);
1627
2472
  };
1628
2473
 
2474
+ export const getEntryStressNotional = (tradeResult) => {
2475
+ if (!tradeResult || typeof tradeResult !== 'object') return null;
2476
+ const quantity = tradeResult.closedQty ?? tradeResult.qty;
2477
+ if (
2478
+ ![tradeResult.entryPrice, quantity].every(
2479
+ (value) =>
2480
+ typeof value === 'number' && Number.isFinite(value) && value > 0,
2481
+ ) ||
2482
+ (tradeResult.qty != null &&
2483
+ (!Number.isFinite(tradeResult.qty) || quantity > tradeResult.qty))
2484
+ )
2485
+ return null;
2486
+ return quantity * tradeResult.entryPrice;
2487
+ };
2488
+
2489
+ const adjacentBinary64 = (value, direction) => {
2490
+ if (!Number.isFinite(value)) return value;
2491
+ if (value === 0) return direction > 0 ? Number.MIN_VALUE : -Number.MIN_VALUE;
2492
+ const buffer = new ArrayBuffer(8);
2493
+ const view = new DataView(buffer);
2494
+ view.setFloat64(0, value, false);
2495
+ let bits = view.getBigUint64(0, false);
2496
+ bits += value > 0 === direction > 0 ? 1n : -1n;
2497
+ view.setBigUint64(0, bits, false);
2498
+ return view.getFloat64(0, false);
2499
+ };
2500
+
2501
+ const binary64Ulp = (value) =>
2502
+ Math.max(
2503
+ value - adjacentBinary64(value, -1),
2504
+ adjacentBinary64(value, 1) - value,
2505
+ );
2506
+
2507
+ const missingEntryStressNotional = (reason, audit = null) => ({
2508
+ status: 'missing',
2509
+ reason,
2510
+ notional: null,
2511
+ audit,
2512
+ });
2513
+
2514
+ export const deriveFeeEntryStressNotional = (tradeResult, authority) => {
2515
+ if (
2516
+ authority?.roundingPolicy?.id !== ENTRY_NOTIONAL_ROUNDING_POLICY ||
2517
+ authority?.displayPriceDecimals !== 8 ||
2518
+ typeof authority?.entryFeeRate !== 'number' ||
2519
+ !Number.isFinite(authority.entryFeeRate) ||
2520
+ authority.entryFeeRate <= 0
2521
+ )
2522
+ throw new Error('Invalid verified fee-derived entry-notional authority');
2523
+ if (!tradeResult || typeof tradeResult !== 'object')
2524
+ return missingEntryStressNotional('missing-trade-result');
2525
+ const readPositive = (field) => {
2526
+ const value = tradeResult[field];
2527
+ if (value == null) return { reason: `missing-${field}` };
2528
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0)
2529
+ return { reason: `invalid-${field}` };
2530
+ return { value };
2531
+ };
2532
+ const fields = [
2533
+ ['qty', 'qty'],
2534
+ ['closedQty', 'closed-qty'],
2535
+ ['openFee', 'open-fee'],
2536
+ ['entryPrice', 'entry-price'],
2537
+ ];
2538
+ const values = {};
2539
+ for (const [field, reasonField] of fields) {
2540
+ const result = readPositive(field);
2541
+ if (result.reason)
2542
+ return missingEntryStressNotional(
2543
+ result.reason.replace(field, reasonField),
2544
+ );
2545
+ values[field] = result.value;
2546
+ }
2547
+ if (values.closedQty !== values.qty)
2548
+ return missingEntryStressNotional('not-fully-closed');
2549
+ const feeDerivedNotional = values.openFee / authority.entryFeeRate;
2550
+ if (!Number.isFinite(feeDerivedNotional) || feeDerivedNotional <= 0)
2551
+ return missingEntryStressNotional('nonfinite-fee-derived-notional');
2552
+ const displayedNotional = values.qty * values.entryPrice;
2553
+ if (!Number.isFinite(displayedNotional) || displayedNotional <= 0)
2554
+ return missingEntryStressNotional('invalid-displayed-notional');
2555
+ const displayAllowance =
2556
+ values.qty * 0.5 * 10 ** -authority.displayPriceDecimals;
2557
+ const binary64Allowance =
2558
+ binary64Ulp(values.openFee) / authority.entryFeeRate +
2559
+ binary64Ulp(feeDerivedNotional) +
2560
+ Math.abs(values.entryPrice) * binary64Ulp(values.qty) +
2561
+ Math.abs(values.qty) * binary64Ulp(values.entryPrice) +
2562
+ binary64Ulp(displayedNotional);
2563
+ const totalAllowance = displayAllowance + binary64Allowance;
2564
+ const difference = Math.abs(feeDerivedNotional - displayedNotional);
2565
+ const audit = {
2566
+ feeDerivedNotional,
2567
+ displayedNotional,
2568
+ difference,
2569
+ displayAllowance,
2570
+ binary64Allowance,
2571
+ totalAllowance,
2572
+ };
2573
+ if (
2574
+ ![displayAllowance, binary64Allowance, totalAllowance, difference].every(
2575
+ Number.isFinite,
2576
+ ) ||
2577
+ difference > totalAllowance
2578
+ )
2579
+ return missingEntryStressNotional(
2580
+ 'display-reconciliation-outside-analytical-bound',
2581
+ audit,
2582
+ );
2583
+ return {
2584
+ status: 'complete',
2585
+ reason: null,
2586
+ notional: feeDerivedNotional,
2587
+ audit,
2588
+ };
2589
+ };
2590
+
1629
2591
  export const buildFeatureAvailabilityAudit = (rows) => {
1630
2592
  const paths = [
1631
2593
  ...new Set(rows.flatMap((row) => Object.keys(row.auditFeatures ?? {}))),
@@ -1705,20 +2667,63 @@ export const validateResearchWindow = (windowStart, windowEnd) => {
1705
2667
  return { start: windowStart, end: windowEnd };
1706
2668
  };
1707
2669
 
2670
+ export const classifyDiscoveryLabelHorizon = (
2671
+ timestamp,
2672
+ tradeResult,
2673
+ cutoff,
2674
+ ) => {
2675
+ if (
2676
+ !Number.isFinite(timestamp) ||
2677
+ !Number.isFinite(cutoff) ||
2678
+ timestamp >= cutoff
2679
+ ) {
2680
+ throw new Error(
2681
+ 'Discovery decision must be finite and earlier than its label cutoff',
2682
+ );
2683
+ }
2684
+ const exit = tradeResult?.exitTimestamp;
2685
+ if (typeof exit !== 'number' || !Number.isFinite(exit)) return 'unknown';
2686
+ if (exit < timestamp)
2687
+ throw new Error('Completed label exits before decision timestamp');
2688
+ return exit >= cutoff ? 'crossing' : 'eligible';
2689
+ };
2690
+
1708
2691
  // Yield only selected sources: no payload, gate or feature work may precede this boundary.
1709
2692
  export async function* readWindowedResearchSources({
1710
2693
  filePaths,
1711
2694
  windowStart = null,
1712
2695
  windowEnd = null,
2696
+ labelEndBefore = null,
2697
+ strictTimestamp = false,
1713
2698
  scan = {},
1714
2699
  }) {
1715
2700
  const window = validateResearchWindow(windowStart, windowEnd);
2701
+ if (
2702
+ labelEndBefore != null &&
2703
+ (!Number.isFinite(labelEndBefore) ||
2704
+ !window ||
2705
+ window.end !== labelEndBefore)
2706
+ ) {
2707
+ throw new Error(
2708
+ '--labelEndBefore requires an explicit discovery window ending at the same cutoff',
2709
+ );
2710
+ }
1716
2711
  Object.assign(scan, {
1717
2712
  rowsRead: 0,
1718
2713
  beforeWindow: 0,
1719
2714
  atOrAfterWindowEnd: 0,
1720
2715
  invalidTimestamp: 0,
1721
2716
  selectedRows: 0,
2717
+ ...(labelEndBefore != null
2718
+ ? {
2719
+ labelHorizon: {
2720
+ cutoff: labelEndBefore,
2721
+ crossing: 0,
2722
+ unknown: 0,
2723
+ eligible: 0,
2724
+ },
2725
+ }
2726
+ : {}),
1722
2727
  });
1723
2728
  let sequence = 0;
1724
2729
  for (const filePath of filePaths) {
@@ -1731,6 +2736,13 @@ export async function* readWindowedResearchSources({
1731
2736
  const source = JSON.parse(line);
1732
2737
  const sourceSequence = sequence++;
1733
2738
  scan.rowsRead += 1;
2739
+ if (
2740
+ (labelEndBefore != null || strictTimestamp) &&
2741
+ (typeof source.timestamp !== 'number' ||
2742
+ !Number.isFinite(source.timestamp))
2743
+ ) {
2744
+ throw new Error('Discovery requires a finite numeric source timestamp');
2745
+ }
1734
2746
  const timestamp =
1735
2747
  source.timestamp == null ||
1736
2748
  typeof source.timestamp === 'boolean' ||
@@ -1751,13 +2763,255 @@ export async function* readWindowedResearchSources({
1751
2763
  scan.atOrAfterWindowEnd += 1;
1752
2764
  continue;
1753
2765
  }
2766
+ if (labelEndBefore != null) {
2767
+ const labelStatus = classifyDiscoveryLabelHorizon(
2768
+ timestamp,
2769
+ source.tradeResult,
2770
+ labelEndBefore,
2771
+ );
2772
+ scan.labelHorizon[labelStatus] += 1;
2773
+ if (labelStatus !== 'eligible') continue;
2774
+ }
1754
2775
  scan.selectedRows += 1;
1755
2776
  yield { source, sequence: sourceSequence, timestamp };
1756
2777
  }
1757
2778
  }
1758
2779
  }
1759
2780
 
1760
- const loadResearchRows = async ({
2781
+ const streamArtifactFileHash = async (filePath) => {
2782
+ const hash = createHash('sha256');
2783
+ let sizeBytes = 0;
2784
+ for await (const chunk of fs.createReadStream(filePath)) {
2785
+ hash.update(chunk);
2786
+ sizeBytes += chunk.length;
2787
+ }
2788
+ return { path: filePath, sha256: hash.digest('hex'), sizeBytes };
2789
+ };
2790
+
2791
+ export const timestampPartitionMetadata = async ({
2792
+ projectRoot,
2793
+ filePaths,
2794
+ outputPath,
2795
+ windowStart,
2796
+ windowEnd,
2797
+ validationSplit = 0,
2798
+ testSplit = 0.4,
2799
+ }) => {
2800
+ validateResearchWindow(windowStart, windowEnd);
2801
+ if (
2802
+ !Number.isSafeInteger(windowStart) ||
2803
+ !Number.isSafeInteger(windowEnd) ||
2804
+ validationSplit !== 0 ||
2805
+ testSplit !== 0.4
2806
+ )
2807
+ throw new Error(
2808
+ 'Timestamp metadata requires explicit window and outer 60/40',
2809
+ );
2810
+ const project = fs.realpathSync(projectRoot);
2811
+ const output = path.resolve(project, outputPath);
2812
+ if (!output.startsWith(`${project}${path.sep}`))
2813
+ throw new Error('Timestamp metadata output must remain inside Project');
2814
+ let ancestor = path.dirname(output);
2815
+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor);
2816
+ const realAncestor = fs.realpathSync(ancestor);
2817
+ if (
2818
+ realAncestor !== project &&
2819
+ !realAncestor.startsWith(`${project}${path.sep}`)
2820
+ )
2821
+ throw new Error('Timestamp metadata parent escapes Project');
2822
+ await fsp.mkdir(path.dirname(output), { recursive: true });
2823
+ if (fs.realpathSync(path.dirname(output)) !== path.dirname(output))
2824
+ throw new Error('Timestamp metadata parent cannot traverse symlinks');
2825
+ if (fs.existsSync(output))
2826
+ throw new Error('Timestamp metadata must be a new immutable file');
2827
+ const inputs = filePaths.map((file) => projectBoundPath(file, project));
2828
+ if (
2829
+ !inputs.length ||
2830
+ new Set(inputs).size !== inputs.length ||
2831
+ inputs.includes(output)
2832
+ )
2833
+ throw new Error('Timestamp metadata requires unique nonempty source files');
2834
+ const sourceFiles = await Promise.all(inputs.map(streamArtifactFileHash));
2835
+ const scan = {};
2836
+ const rows = [];
2837
+ for await (const { timestamp } of readWindowedResearchSources({
2838
+ filePaths: inputs,
2839
+ windowStart,
2840
+ windowEnd,
2841
+ strictTimestamp: true,
2842
+ scan,
2843
+ }))
2844
+ rows.push({ timestamp });
2845
+ rows.sort((a, b) => a.timestamp - b.timestamp);
2846
+ if (new Set(rows.map((row) => row.timestamp)).size < 2)
2847
+ throw new Error(
2848
+ 'Timestamp metadata requires at least two independent groups',
2849
+ );
2850
+ const split = splitRowsByTimestamp(rows, validationSplit, testSplit);
2851
+ const testSince = split.test[0].timestamp;
2852
+ const count = (partition) => ({
2853
+ rows: partition.length,
2854
+ events: new Set(partition.map((row) => row.timestamp)).size,
2855
+ });
2856
+ const after = await Promise.all(inputs.map(streamArtifactFileHash));
2857
+ if (JSON.stringify(after) !== JSON.stringify(sourceFiles))
2858
+ throw new Error('Timestamp metadata source inputs changed');
2859
+ const metadata = {
2860
+ schema: 'tradejs-timestamp-partition-metadata/v1',
2861
+ sourceFiles,
2862
+ inputStabilityVerified: true,
2863
+ comparisonWindow: {
2864
+ start: windowStart,
2865
+ end: windowEnd,
2866
+ interval: '[start, end)',
2867
+ },
2868
+ validationSplit,
2869
+ testSplit,
2870
+ testSince,
2871
+ testSinceUtc: new Date(testSince).toISOString(),
2872
+ sourceSelection: scan,
2873
+ development: count(split.train),
2874
+ test: count(split.test),
2875
+ outcomeEvaluationPerformed: false,
2876
+ gateEvaluationPerformed: false,
2877
+ featureEvaluationPerformed: false,
2878
+ runtimeLoaded: false,
2879
+ };
2880
+ const bytes = `${JSON.stringify(metadata, null, 2)}\n`;
2881
+ await fsp.writeFile(output, bytes, { flag: 'wx' });
2882
+ const artifact = await streamArtifactFileHash(output);
2883
+ if (artifact.sha256 !== artifactSha256(bytes))
2884
+ throw new Error('Timestamp metadata output checksum mismatch');
2885
+ return { ...metadata, artifact };
2886
+ };
2887
+
2888
+ export const materializeDiscoveryExport = async ({
2889
+ projectRoot,
2890
+ filePaths,
2891
+ outputPath,
2892
+ windowStart,
2893
+ windowEnd,
2894
+ testSince,
2895
+ labelEndBefore,
2896
+ validationSplit = 0,
2897
+ }) => {
2898
+ validateResearchWindow(windowStart, windowEnd);
2899
+ if (
2900
+ !Number.isSafeInteger(windowStart) ||
2901
+ !Number.isSafeInteger(windowEnd) ||
2902
+ !Number.isSafeInteger(labelEndBefore) ||
2903
+ labelEndBefore !== windowEnd ||
2904
+ testSince !== windowEnd ||
2905
+ validationSplit !== 0
2906
+ )
2907
+ throw new Error(
2908
+ 'Materialization requires exact discovery window/test/label cutoff and validationSplit 0',
2909
+ );
2910
+ const project = fs.realpathSync(projectRoot);
2911
+ const output = path.resolve(project, outputPath);
2912
+ if (!output.startsWith(`${project}${path.sep}`))
2913
+ throw new Error('Discovery output must remain inside Project');
2914
+ let ancestor = path.dirname(output);
2915
+ while (!fs.existsSync(ancestor)) ancestor = path.dirname(ancestor);
2916
+ const realAncestor = fs.realpathSync(ancestor);
2917
+ if (
2918
+ realAncestor !== project &&
2919
+ !realAncestor.startsWith(`${project}${path.sep}`)
2920
+ )
2921
+ throw new Error('Discovery output parent escapes Project');
2922
+ await fsp.mkdir(path.dirname(output), { recursive: true });
2923
+ if (fs.realpathSync(path.dirname(output)) !== path.dirname(output))
2924
+ throw new Error('Discovery output parent cannot traverse symlinks');
2925
+ const receiptPath = `${output}.receipt.json`;
2926
+ if (fs.existsSync(output) || fs.existsSync(receiptPath))
2927
+ throw new Error('Discovery output and receipt must be new immutable files');
2928
+ const inputs = filePaths.map((filePath) =>
2929
+ projectBoundPath(filePath, project),
2930
+ );
2931
+ if (
2932
+ !inputs.length ||
2933
+ new Set(inputs).size !== inputs.length ||
2934
+ inputs.includes(output)
2935
+ )
2936
+ throw new Error('Discovery inputs must be a non-empty unique source group');
2937
+ const sourceFiles = await Promise.all(inputs.map(streamArtifactFileHash));
2938
+ const scan = {};
2939
+ const handle = await fsp.open(output, 'wx');
2940
+ const outputHash = createHash('sha256');
2941
+ let outputRows = 0;
2942
+ let sizeBytes = 0;
2943
+ try {
2944
+ for await (const { source } of readWindowedResearchSources({
2945
+ filePaths: inputs,
2946
+ windowStart,
2947
+ windowEnd,
2948
+ labelEndBefore,
2949
+ scan,
2950
+ })) {
2951
+ const line = `${JSON.stringify(source)}\n`;
2952
+ await handle.writeFile(line);
2953
+ outputHash.update(line);
2954
+ sizeBytes += Buffer.byteLength(line);
2955
+ outputRows += 1;
2956
+ }
2957
+ if (!outputRows) throw new Error('Discovery export has zero eligible rows');
2958
+ const after = await Promise.all(inputs.map(streamArtifactFileHash));
2959
+ if (JSON.stringify(after) !== JSON.stringify(sourceFiles))
2960
+ throw new Error('Discovery source inputs changed during materialization');
2961
+ await handle.sync();
2962
+ const outputSha256 = outputHash.digest('hex');
2963
+ const readback = await streamArtifactFileHash(output);
2964
+ if (readback.sha256 !== outputSha256 || readback.sizeBytes !== sizeBytes)
2965
+ throw new Error('Discovery output checksum mismatch');
2966
+ const receipt = {
2967
+ schema: 'tradejs-discovery-export-materialization/v1',
2968
+ createdAt: new Date().toISOString(),
2969
+ role: 'Raw maturity-purged development source view; not a gate replay or new core export',
2970
+ sourceFiles,
2971
+ sourceFilesAfter: after,
2972
+ inputStabilityVerified: true,
2973
+ output: {
2974
+ path: output,
2975
+ sha256: outputSha256,
2976
+ sizeBytes,
2977
+ rows: outputRows,
2978
+ },
2979
+ comparisonWindow: {
2980
+ start: windowStart,
2981
+ end: windowEnd,
2982
+ interval: '[start, end)',
2983
+ },
2984
+ testSince,
2985
+ labelEndBefore,
2986
+ validationSplit,
2987
+ sourceSelection: scan,
2988
+ gateEvaluationPerformed: false,
2989
+ featureEvaluationPerformed: false,
2990
+ sourceObjectsModified: false,
2991
+ nativeAiTrain: {
2992
+ file: output,
2993
+ since: windowStart,
2994
+ until: windowEnd - 1,
2995
+ sourceSha256s: [outputSha256],
2996
+ warning:
2997
+ 'Native lineage hashes this view, not its parent full exports; bind this receipt and original core/config authority separately.',
2998
+ },
2999
+ };
3000
+ await fsp.writeFile(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, {
3001
+ flag: 'wx',
3002
+ });
3003
+ return { ...receipt, receiptPath };
3004
+ } catch (error) {
3005
+ throw new Error(
3006
+ `Discovery materialization failed; partial output retained without a success receipt at ${output}: ${error.message}`,
3007
+ { cause: error },
3008
+ );
3009
+ } finally {
3010
+ await handle.close();
3011
+ }
3012
+ };
3013
+
3014
+ export const loadResearchRows = async ({
1761
3015
  projectRoot,
1762
3016
  sourceRepositoryRoot,
1763
3017
  frameworkRepositoryRoot,
@@ -1769,17 +3023,45 @@ const loadResearchRows = async ({
1769
3023
  cohortPath,
1770
3024
  windowStart = null,
1771
3025
  windowEnd = null,
3026
+ labelEndBefore = null,
3027
+ runtimeCheckpoint = null,
3028
+ strategyArtifactAuthority = null,
3029
+ entryNotionalAuthority = null,
1772
3030
  }) => {
1773
3031
  validateResearchWindow(windowStart, windowEnd);
1774
- const { aiModulePath, registryModulePath, pocketModulePath } =
1775
- await ensureRuntimeBuild(frameworkRepositoryRoot);
3032
+ const {
3033
+ aiModulePath,
3034
+ registryModulePath,
3035
+ pocketModulePath,
3036
+ executionRuntime,
3037
+ } = await ensureRuntimeBuild(frameworkRepositoryRoot, {
3038
+ projectRoot,
3039
+ runtimeCheckpoint,
3040
+ });
3041
+ const verifiedEntryNotionalAuthority = entryNotionalAuthority
3042
+ ? await verifyEntryNotionalAuthority({
3043
+ projectRoot,
3044
+ entryNotionalAuthority,
3045
+ executionRuntime,
3046
+ filePaths,
3047
+ })
3048
+ : null;
3049
+ const loadedStrategy =
3050
+ getSourceRepositoryKind(sourceRepositoryRoot) === 'strategy'
3051
+ ? await loadStandaloneStrategyEntries(sourceRepositoryRoot, {
3052
+ projectRoot,
3053
+ executionRuntime,
3054
+ strategyArtifactAuthority,
3055
+ })
3056
+ : null;
3057
+ if (strategyArtifactAuthority && !loadedStrategy)
3058
+ throw new Error('Strategy artifact authority requires standalone source');
1776
3059
  const aiModule = await import(pathToFileURL(aiModulePath).href);
1777
3060
  const registryModule = await import(pathToFileURL(registryModulePath).href);
1778
3061
  const require = createRequire(import.meta.url);
1779
3062
  const { collectAiPocketFeatures } = require(pocketModulePath);
1780
- if (getSourceRepositoryKind(sourceRepositoryRoot) === 'strategy') {
1781
- const { strategyEntries } =
1782
- await loadStandaloneStrategyEntries(sourceRepositoryRoot);
3063
+ if (loadedStrategy) {
3064
+ const { strategyEntries } = loadedStrategy;
1783
3065
  registryModule.resetStrategyRegistryCache(projectRoot);
1784
3066
  registryModule.registerStrategyEntries(strategyEntries, projectRoot);
1785
3067
  } else {
@@ -1799,6 +3081,7 @@ const loadResearchRows = async ({
1799
3081
  filePaths,
1800
3082
  windowStart,
1801
3083
  windowEnd,
3084
+ labelEndBefore,
1802
3085
  scan: sourceSelection,
1803
3086
  })) {
1804
3087
  try {
@@ -1824,6 +3107,12 @@ const loadResearchRows = async ({
1824
3107
  return Number.isFinite(parsed) ? parsed : null;
1825
3108
  };
1826
3109
  const rawContext = payload.additionalIndicators?.baseContext?.raw ?? {};
3110
+ const entryStressNotionalEvidence = verifiedEntryNotionalAuthority
3111
+ ? deriveFeeEntryStressNotional(
3112
+ source.tradeResult,
3113
+ verifiedEntryNotionalAuthority,
3114
+ )
3115
+ : null;
1827
3116
  rows.push({
1828
3117
  sequence,
1829
3118
  signalId: source.signalId,
@@ -1843,6 +3132,10 @@ const loadResearchRows = async ({
1843
3132
  ? readDiagnosticPath(payload, cohortPath)
1844
3133
  : null,
1845
3134
  costStressNotional: getCostStressNotional(source.tradeResult),
3135
+ entryStressNotional: verifiedEntryNotionalAuthority
3136
+ ? entryStressNotionalEvidence.notional
3137
+ : getEntryStressNotional(source.tradeResult),
3138
+ ...(entryStressNotionalEvidence ? { entryStressNotionalEvidence } : {}),
1846
3139
  completedTrade:
1847
3140
  source.tradeResult == null
1848
3141
  ? null
@@ -1889,11 +3182,21 @@ const loadResearchRows = async ({
1889
3182
  if (rows.some((row) => row.timestamp == null)) {
1890
3183
  throw new Error('At least one evaluated row has no finite timestamp');
1891
3184
  }
3185
+ const stableEntryNotionalAuthority = verifiedEntryNotionalAuthority
3186
+ ? await verifyEntryNotionalInputStability(verifiedEntryNotionalAuthority)
3187
+ : null;
1892
3188
  return {
1893
3189
  rows,
1894
3190
  failed,
1895
3191
  featureInventory: finalizeFeatureInventory(featureInventory),
1896
3192
  sourceSelection,
3193
+ ...(executionRuntime ? { executionRuntime } : {}),
3194
+ ...(stableEntryNotionalAuthority
3195
+ ? { entryNotionalAuthority: stableEntryNotionalAuthority }
3196
+ : {}),
3197
+ ...(loadedStrategy?.strategyArtifact
3198
+ ? { strategyArtifact: loadedStrategy.strategyArtifact }
3199
+ : {}),
1897
3200
  };
1898
3201
  };
1899
3202
 
@@ -3836,7 +5139,17 @@ export const buildCrossStrategyReport = async ({
3836
5139
  minFeatureCoverage,
3837
5140
  minBenchmarkFeatureCoverage,
3838
5141
  portfolioCapacity = 5,
5142
+ runtimeCheckpoint = null,
5143
+ strategyArtifactAuthority = null,
3839
5144
  }) => {
5145
+ if (strategyArtifactAuthority)
5146
+ throw new Error('Strategy artifact authority requires single-core mode');
5147
+ const checkpointRuntime = runtimeCheckpoint
5148
+ ? await ensureRuntimeBuild(frameworkRepositoryRoot, {
5149
+ projectRoot,
5150
+ runtimeCheckpoint,
5151
+ })
5152
+ : null;
3840
5153
  if (groups.length < 2) {
3841
5154
  throw new Error('Cross-strategy research requires at least two exports');
3842
5155
  }
@@ -3848,10 +5161,12 @@ export const buildCrossStrategyReport = async ({
3848
5161
  let searchAiPockets = searchAiPocketsOverride;
3849
5162
  if (!searchAiPockets) {
3850
5163
  const require = createRequire(import.meta.url);
3851
- const pocketModulePath = path.join(
3852
- frameworkRepositoryRoot,
3853
- 'packages/cli/dist/lib/aiPocketSearch.js',
3854
- );
5164
+ const pocketModulePath =
5165
+ checkpointRuntime?.pocketModulePath ??
5166
+ path.join(
5167
+ frameworkRepositoryRoot,
5168
+ 'packages/cli/dist/lib/aiPocketSearch.js',
5169
+ );
3855
5170
  await fsp.access(pocketModulePath);
3856
5171
  ({ searchAiPockets } = require(pocketModulePath));
3857
5172
  }
@@ -4194,6 +5509,9 @@ export const buildCrossStrategyReport = async ({
4194
5509
  generatedAt: new Date().toISOString(),
4195
5510
  run: {
4196
5511
  mode: 'profiled cross-strategy saved-snapshot feasibility',
5512
+ ...(checkpointRuntime
5513
+ ? { executionRuntime: checkpointRuntime.executionRuntime }
5514
+ : {}),
4197
5515
  sourceRepositoryRoot,
4198
5516
  frameworkRepositoryRoot,
4199
5517
  evidenceStatus:
@@ -4274,7 +5592,21 @@ export const buildRealizedReport = ({
4274
5592
  summaryOptions,
4275
5593
  testSince = null,
4276
5594
  tuningSince = null,
5595
+ symbolCohorts = null,
4277
5596
  }) => {
5597
+ const cohortDefinition = symbolCohorts
5598
+ ? normalizeSymbolCohorts(symbolCohorts)
5599
+ : null;
5600
+ if (cohortDefinition) {
5601
+ const declaredSymbols = new Set(
5602
+ cohortDefinition.groups.flatMap((group) => group.symbols),
5603
+ );
5604
+ if (rows.some((row) => !declaredSymbols.has(row.symbol))) {
5605
+ throw new Error(
5606
+ 'Every source row must belong to a declared symbol cohort',
5607
+ );
5608
+ }
5609
+ }
4278
5610
  const approved = selectRows(rows, selector);
4279
5611
  const identities = new Set();
4280
5612
  for (const row of approved) {
@@ -4392,6 +5724,37 @@ export const buildRealizedReport = ({
4392
5724
  ...provenance,
4393
5725
  excludedOutsideWindow: approved.length - realizedRows.length,
4394
5726
  partitionCalendarBounds: partitionBounds,
5727
+ ...(cohortDefinition
5728
+ ? {
5729
+ symbolCohorts: {
5730
+ role: 'diagnostic only; globally frozen approvals, partitions and calendar denominators; no cohort-dependent gate or capacity reranking',
5731
+ authority: symbolCohorts.authority ?? null,
5732
+ groups: cohortDefinition.groups.map((group) => {
5733
+ const symbols = new Set(group.symbols);
5734
+ const cohortRows = rows.filter((row) => symbols.has(row.symbol));
5735
+ return {
5736
+ id: group.id,
5737
+ declaredSymbols: group.symbols.length,
5738
+ observedSymbols: new Set(cohortRows.map((row) => row.symbol))
5739
+ .size,
5740
+ sourceRows: cohortRows.length,
5741
+ realized: buildRealizedReport({
5742
+ rows: cohortRows,
5743
+ selector: (row) => selected.has(row),
5744
+ minTimestamp,
5745
+ maxTimestamp,
5746
+ terminalWindows,
5747
+ split,
5748
+ stabilityBlocks,
5749
+ summaryOptions,
5750
+ testSince,
5751
+ tuningSince,
5752
+ }),
5753
+ };
5754
+ }),
5755
+ },
5756
+ }
5757
+ : {}),
4395
5758
  periods: buildPeriodSummaries({
4396
5759
  rows: realizedRows,
4397
5760
  selector: () => true,
@@ -4445,6 +5808,129 @@ export const buildRealizedReport = ({
4445
5808
  };
4446
5809
  };
4447
5810
 
5811
+ export const buildRoundTripCostStressReport = ({
5812
+ rows,
5813
+ selector,
5814
+ basisPoints,
5815
+ split,
5816
+ stabilityBlocks,
5817
+ entryNotionalAuthority = null,
5818
+ ...realizedOptions
5819
+ }) => {
5820
+ // Freeze the approval set before any outcome adjustment, including capacity ranking.
5821
+ const approved = new Set(selectRows(rows, selector));
5822
+ return basisPoints.map((bps) => {
5823
+ const copies = new Map(
5824
+ rows.map((row) => {
5825
+ const validNotional =
5826
+ Number.isFinite(row.entryStressNotional) &&
5827
+ row.entryStressNotional > 0;
5828
+ const validProfit =
5829
+ typeof row.completedTrade?.netProfit === 'number' &&
5830
+ Number.isFinite(row.completedTrade.netProfit) &&
5831
+ Math.abs(row.completedTrade.netProfit - row.profit) < 1e-9;
5832
+ const additionalCost = validNotional
5833
+ ? (row.entryStressNotional * bps) / 10000
5834
+ : null;
5835
+ return [
5836
+ row,
5837
+ {
5838
+ ...row,
5839
+ stressApproved: approved.has(row),
5840
+ profit:
5841
+ additionalCost == null ? row.profit : row.profit - additionalCost,
5842
+ completedTrade:
5843
+ validNotional && validProfit
5844
+ ? {
5845
+ ...row.completedTrade,
5846
+ netProfit: row.completedTrade.netProfit - additionalCost,
5847
+ }
5848
+ : null,
5849
+ },
5850
+ ];
5851
+ }),
5852
+ );
5853
+ const adjustedRows = rows.map((row) => copies.get(row));
5854
+ const options = {
5855
+ ...realizedOptions,
5856
+ rows: adjustedRows,
5857
+ split: Object.fromEntries(
5858
+ Object.entries(split).map(([name, cohort]) => [
5859
+ name,
5860
+ cohort.map((row) => copies.get(row)),
5861
+ ]),
5862
+ ),
5863
+ stabilityBlocks: stabilityBlocks.map((cohort) =>
5864
+ cohort.map((row) => copies.get(row)),
5865
+ ),
5866
+ };
5867
+ const selectedRows = rows.filter((row) => approved.has(row));
5868
+ const missingNotional = selectedRows.filter(
5869
+ (row) =>
5870
+ !(
5871
+ Number.isFinite(row.entryStressNotional) &&
5872
+ row.entryStressNotional > 0
5873
+ ),
5874
+ ).length;
5875
+ const missingNotionalReasonCounts = Object.fromEntries(
5876
+ [
5877
+ ...selectedRows
5878
+ .filter(
5879
+ (row) =>
5880
+ !(
5881
+ Number.isFinite(row.entryStressNotional) &&
5882
+ row.entryStressNotional > 0
5883
+ ),
5884
+ )
5885
+ .reduce((counts, row) => {
5886
+ const reason =
5887
+ row.entryStressNotionalEvidence?.reason ??
5888
+ 'unknown-missing-notional';
5889
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
5890
+ return counts;
5891
+ }, new Map()),
5892
+ ].sort(([left], [right]) => left.localeCompare(right)),
5893
+ );
5894
+ return {
5895
+ basisPointsRoundTrip: bps,
5896
+ formula:
5897
+ entryNotionalAuthority == null
5898
+ ? 'closedQty (or qty when absent) * actual entryPrice * roundTripBps / 10000'
5899
+ : 'tradeResult.openFee / frozen equal maker/taker entry fee rate * roundTripBps / 10000',
5900
+ role: 'fixed arithmetic cost stress; original approval identities, historical quantity and risk unchanged; exit-time economics',
5901
+ approvedN: selectedRows.length,
5902
+ missingNotionalRows: missingNotional,
5903
+ ...(entryNotionalAuthority
5904
+ ? {
5905
+ entryNotionalMethod: entryNotionalAuthority.method,
5906
+ completeNotionalRows: selectedRows.length - missingNotional,
5907
+ missingNotionalReasonCounts,
5908
+ }
5909
+ : {}),
5910
+ additionalCost: missingNotional
5911
+ ? null
5912
+ : selectedRows.reduce(
5913
+ (sum, row) => sum + (row.entryStressNotional * bps) / 10000,
5914
+ 0,
5915
+ ),
5916
+ realized: buildRealizedReport({
5917
+ ...options,
5918
+ selector: (row) => row.stressApproved,
5919
+ }),
5920
+ byDirection: Object.fromEntries(
5921
+ ['LONG', 'SHORT'].map((direction) => [
5922
+ direction,
5923
+ buildRealizedReport({
5924
+ ...options,
5925
+ selector: (row) =>
5926
+ row.stressApproved && row.direction === direction,
5927
+ }),
5928
+ ]),
5929
+ ),
5930
+ };
5931
+ });
5932
+ };
5933
+
4448
5934
  export const buildCostStressReport = ({
4449
5935
  rows,
4450
5936
  selector,
@@ -4651,9 +6137,14 @@ export const buildAblationReport = ({
4651
6137
  featureInventory = [],
4652
6138
  cohortPath = null,
4653
6139
  costStressBps = [],
6140
+ roundTripCostStressBps = [],
4654
6141
  realizedMetrics = false,
6142
+ symbolCohorts = null,
4655
6143
  monthlyCohorts = false,
4656
6144
  compareTo = null,
6145
+ executionRuntime = null,
6146
+ strategyArtifact = null,
6147
+ entryNotionalAuthority = null,
4657
6148
  }) => {
4658
6149
  if (!rows.length) throw new Error('No rows were evaluated');
4659
6150
  if ((windowStart == null) !== (windowEnd == null)) {
@@ -4672,6 +6163,17 @@ export const buildAblationReport = ({
4672
6163
  '--realizedMetrics requires explicit --windowStart and --windowEnd',
4673
6164
  );
4674
6165
  }
6166
+ if (roundTripCostStressBps.length && !realizedMetrics) {
6167
+ throw new Error('--roundTripCostStressBps requires --realizedMetrics');
6168
+ }
6169
+ if (symbolCohorts && !realizedMetrics) {
6170
+ throw new Error('Symbol cohorts require realizedMetrics');
6171
+ }
6172
+ if (roundTripCostStressBps.some((bps) => !Number.isFinite(bps) || bps <= 0)) {
6173
+ throw new Error(
6174
+ 'roundTripCostStressBps must contain positive finite values',
6175
+ );
6176
+ }
4675
6177
  if (
4676
6178
  explicitWindow &&
4677
6179
  (!Number.isFinite(windowStart) ||
@@ -4755,6 +6257,7 @@ export const buildAblationReport = ({
4755
6257
  summaryOptions,
4756
6258
  testSince,
4757
6259
  tuningSince,
6260
+ symbolCohorts,
4758
6261
  });
4759
6262
  const approvedSignalTrace = (selector) =>
4760
6263
  selectRows(rows, selector).map((row) => ({
@@ -4765,7 +6268,26 @@ export const buildAblationReport = ({
4765
6268
  direction: row.direction,
4766
6269
  profit: row.profit,
4767
6270
  }));
6271
+ const roundTripCostStress = (selector) =>
6272
+ buildRoundTripCostStressReport({
6273
+ rows,
6274
+ selector,
6275
+ basisPoints: roundTripCostStressBps,
6276
+ split,
6277
+ stabilityBlocks,
6278
+ minTimestamp,
6279
+ maxTimestamp,
6280
+ terminalWindows,
6281
+ summaryOptions,
6282
+ testSince,
6283
+ tuningSince,
6284
+ symbolCohorts,
6285
+ entryNotionalAuthority,
6286
+ });
4768
6287
  const baseline = {
6288
+ ...(roundTripCostStressBps.length
6289
+ ? { roundTripCostStress: roundTripCostStress(baselineSelector) }
6290
+ : {}),
4769
6291
  ...(realizedMetrics ? { realized: realized(baselineSelector) } : {}),
4770
6292
  ...(costStressBps.length
4771
6293
  ? { costStress: costStress(baselineSelector) }
@@ -4832,6 +6354,9 @@ export const buildAblationReport = ({
4832
6354
  !baselineSelector(row) && candidateSelector(row);
4833
6355
  return {
4834
6356
  name: variant.name,
6357
+ ...(roundTripCostStressBps.length
6358
+ ? { roundTripCostStress: roundTripCostStress(candidateSelector) }
6359
+ : {}),
4835
6360
  ...(realizedMetrics ? { realized: realized(candidateSelector) } : {}),
4836
6361
  ...(costStressBps.length
4837
6362
  ? { costStress: costStress(candidateSelector) }
@@ -4927,6 +6452,9 @@ export const buildAblationReport = ({
4927
6452
  test: summarizeSplit(split.test, selector, summaryOptions),
4928
6453
  developmentStability: stabilitySummary(selector),
4929
6454
  ...(costStressBps.length ? { costStress: costStress(selector) } : {}),
6455
+ ...(roundTripCostStressBps.length
6456
+ ? { roundTripCostStress: roundTripCostStress(selector) }
6457
+ : {}),
4930
6458
  ...(realizedMetrics ? { realized: realized(selector) } : {}),
4931
6459
  });
4932
6460
  comparisons = [...selectors]
@@ -4947,6 +6475,9 @@ export const buildAblationReport = ({
4947
6475
  sourceRepositoryRoot,
4948
6476
  frameworkRepositoryRoot,
4949
6477
  sourceRepositoryKind,
6478
+ ...(executionRuntime ? { executionRuntime } : {}),
6479
+ ...(strategyArtifact ? { strategyArtifact } : {}),
6480
+ ...(entryNotionalAuthority ? { entryNotionalAuthority } : {}),
4950
6481
  rows: rows.length,
4951
6482
  failed,
4952
6483
  minQuality,
@@ -4970,7 +6501,9 @@ export const buildAblationReport = ({
4970
6501
  maxLossValue,
4971
6502
  ...(cohortPath ? { cohortPath } : {}),
4972
6503
  ...(costStressBps.length ? { costStressBps } : {}),
6504
+ ...(roundTripCostStressBps.length ? { roundTripCostStressBps } : {}),
4973
6505
  ...(realizedMetrics ? { realizedMetrics: true } : {}),
6506
+ ...(symbolCohorts ? { symbolCohorts } : {}),
4974
6507
  ...(monthlyCohorts ? { monthlyCohorts: true } : {}),
4975
6508
  ...(compareTo != null ? { compareTo } : {}),
4976
6509
  trainRows: split.train.length,
@@ -5476,6 +7009,30 @@ export const formatMarkdownReport = (report) => {
5476
7009
  ['source_root', report.run.sourceRepositoryRoot ?? 'n/a'],
5477
7010
  ['source_kind', report.run.sourceRepositoryKind ?? 'n/a'],
5478
7011
  ['framework_root', report.run.frameworkRepositoryRoot ?? 'n/a'],
7012
+ [
7013
+ 'execution_runtime',
7014
+ report.run.executionRuntime?.mode ?? 'source-build',
7015
+ ],
7016
+ [
7017
+ 'runtime_checkpoint_sha256',
7018
+ report.run.executionRuntime?.checkpoint?.sha256 ?? 'n/a',
7019
+ ],
7020
+ [
7021
+ 'historical_strategy_source_sha',
7022
+ report.run.strategyArtifact?.sourceGitSha ?? 'n/a',
7023
+ ],
7024
+ [
7025
+ 'historical_strategy_diff_sha256',
7026
+ report.run.strategyArtifact?.sourceDiff?.sha256 ?? 'n/a',
7027
+ ],
7028
+ [
7029
+ 'imported_strategy_dist_sha256',
7030
+ report.run.strategyArtifact?.distSha256 ?? 'n/a',
7031
+ ],
7032
+ [
7033
+ 'strategy_artifact_authority_sha256',
7034
+ report.run.strategyArtifact?.authority?.sha256 ?? 'n/a',
7035
+ ],
5479
7036
  ['range', `${report.run.minTimestamp} .. ${report.run.maxTimestamp}`],
5480
7037
  ['span_days', formatNumber(report.run.spanDays)],
5481
7038
  ['min_quality', report.run.minQuality],
@@ -6294,6 +7851,45 @@ export const main = async () => {
6294
7851
  }
6295
7852
  const projectRoot = resolveArtifactProjectRoot();
6296
7853
  const outDir = path.resolve(projectRoot, options.outDir);
7854
+ if (options.timestampPartitionMetadata) {
7855
+ const filePaths = await resolveDatasetFiles({
7856
+ projectRoot,
7857
+ outDir: options.outDir,
7858
+ file: options.file,
7859
+ strategy: options.strategy,
7860
+ });
7861
+ const metadata = await timestampPartitionMetadata({
7862
+ projectRoot,
7863
+ filePaths,
7864
+ outputPath: options.timestampPartitionMetadata,
7865
+ windowStart: options.windowStart,
7866
+ windowEnd: options.windowEnd,
7867
+ validationSplit: options.validationSplit,
7868
+ testSplit: options.testSplit,
7869
+ });
7870
+ process.stdout.write(`${JSON.stringify(metadata, null, 2)}\n`);
7871
+ return;
7872
+ }
7873
+ if (options.materializeDiscoveryExport) {
7874
+ const filePaths = await resolveDatasetFiles({
7875
+ projectRoot,
7876
+ outDir: options.outDir,
7877
+ file: options.file,
7878
+ strategy: options.strategy,
7879
+ });
7880
+ const receipt = await materializeDiscoveryExport({
7881
+ projectRoot,
7882
+ filePaths,
7883
+ outputPath: options.materializeDiscoveryExport,
7884
+ windowStart: options.windowStart,
7885
+ windowEnd: options.windowEnd,
7886
+ testSince: options.testSince,
7887
+ labelEndBefore: options.labelEndBefore,
7888
+ validationSplit: options.validationSplit,
7889
+ });
7890
+ process.stdout.write(`${JSON.stringify(receipt, null, 2)}\n`);
7891
+ return;
7892
+ }
6297
7893
  if (options.list) {
6298
7894
  const groups = await listDatasetGroups(outDir);
6299
7895
  const strategyToken = normalizeStrategyToken(options.strategy);
@@ -6312,6 +7908,28 @@ export const main = async () => {
6312
7908
  const sourceRepositoryKind = getSourceRepositoryKind(sourceRepositoryRoot);
6313
7909
  const frameworkRepositoryRoot =
6314
7910
  findFrameworkRepositoryRoot(sourceRepositoryRoot);
7911
+ // Resolve all executable authorities before resolving or reading any export.
7912
+ if (options.runtimeCheckpoint) {
7913
+ const runtime = await ensureRuntimeBuild(frameworkRepositoryRoot, {
7914
+ projectRoot,
7915
+ runtimeCheckpoint: options.runtimeCheckpoint,
7916
+ });
7917
+ if (!options.crossStrategy && sourceRepositoryKind === 'strategy') {
7918
+ if (!options.strategyArtifactAuthority)
7919
+ throw new Error(
7920
+ 'Checkpoint execution requires explicit --strategyArtifactAuthority for standalone source',
7921
+ );
7922
+ verifyStrategyArtifactAuthority({
7923
+ projectRoot,
7924
+ sourceRepositoryRoot,
7925
+ strategyArtifactAuthority: options.strategyArtifactAuthority,
7926
+ executionRuntime: runtime.executionRuntime,
7927
+ });
7928
+ } else if (options.strategyArtifactAuthority)
7929
+ throw new Error(
7930
+ 'Strategy artifact authority requires standalone single-core source',
7931
+ );
7932
+ }
6315
7933
  if (options.crossStrategy) {
6316
7934
  if (options.tuningSince != null || options.testSince != null) {
6317
7935
  throw new Error(
@@ -6326,6 +7944,7 @@ export const main = async () => {
6326
7944
  sourceRepositoryRoot,
6327
7945
  frameworkRepositoryRoot,
6328
7946
  groups,
7947
+ runtimeCheckpoint: options.runtimeCheckpoint,
6329
7948
  validationSplit: options.validationSplit,
6330
7949
  testSplit: options.testSplit,
6331
7950
  maxDepth: options.maxDepth,
@@ -6361,6 +7980,9 @@ export const main = async () => {
6361
7980
  return;
6362
7981
  }
6363
7982
  let variants = await loadVariants(options.variants, options.spec);
7983
+ const symbolCohorts = options.symbolCohorts
7984
+ ? loadSymbolCohorts({ projectRoot, file: options.symbolCohorts })
7985
+ : null;
6364
7986
  if (options.movingAverageStudy && variants.length) {
6365
7987
  throw new Error(
6366
7988
  '--movingAverageStudy cannot be combined with --variant or --spec',
@@ -6399,6 +8021,10 @@ export const main = async () => {
6399
8021
  cohortPath: options.cohortPath,
6400
8022
  windowStart: options.windowStart,
6401
8023
  windowEnd: options.windowEnd,
8024
+ labelEndBefore: options.labelEndBefore,
8025
+ runtimeCheckpoint: options.runtimeCheckpoint,
8026
+ strategyArtifactAuthority: options.strategyArtifactAuthority,
8027
+ entryNotionalAuthority: options.entryNotionalAuthority,
6402
8028
  });
6403
8029
  let movingAverageCoverage = null;
6404
8030
  if (options.movingAverageStudy) {
@@ -6431,7 +8057,9 @@ export const main = async () => {
6431
8057
  maxLossValue: options.maxLossValue,
6432
8058
  cohortPath: options.cohortPath,
6433
8059
  costStressBps: options.costStressBps,
8060
+ roundTripCostStressBps: options.roundTripCostStressBps,
6434
8061
  realizedMetrics: options.realizedMetrics,
8062
+ symbolCohorts,
6435
8063
  monthlyCohorts: options.monthlyCohorts,
6436
8064
  compareTo: options.compareTo,
6437
8065
  sourceRepositoryRoot,
@@ -6448,6 +8076,12 @@ export const main = async () => {
6448
8076
  interval: '[start, end)',
6449
8077
  filteredBeforeGateEvaluation: true,
6450
8078
  };
8079
+ if (options.labelEndBefore != null) {
8080
+ report.run.discoveryOnly = true;
8081
+ report.run.labelEndBefore = new Date(options.labelEndBefore).toISOString();
8082
+ report.run.labelHorizonRole =
8083
+ 'Unknown or crossing completed labels excluded before payload, feature and gate evaluation. Outer test remains unopened.';
8084
+ }
6451
8085
  if (options.movingAverageStudy) {
6452
8086
  report.movingAverageStudy = summarizeMovingAverageStudy({
6453
8087
  rows: loaded.rows,