create-tradejs 3.1.29-beta.275 → 3.1.29-beta.277

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -65,6 +65,7 @@ var PROJECT_SKILL_NAMES = [
65
65
  "strategy-forward-start",
66
66
  "strategy-forward-status",
67
67
  "tradejs-mcp",
68
+ "tradejs-docs",
68
69
  "strategy-risk-scale",
69
70
  "strategy-release"
70
71
  ];
@@ -638,6 +638,17 @@ Every new AI-gate study must:
638
638
  - downgrade `reproduction` from `complete` when any displayed metric or lineage
639
639
  cannot be recovered from the note after export deletion.
640
640
 
641
+ ## Completed study storage
642
+
643
+ Follow
644
+ [`../strategy-backtest-research/references/research-retention.md`](../strategy-backtest-research/references/research-retention.md)
645
+ at the final handoff. Preserve candidate gate code/config and structured
646
+ raw/approved/partition/terminal metrics, rejected hypotheses, test exposure and
647
+ final charts. Remove trade/feature exports and intermediate datasets after all
648
+ consumers finish. If this gate board is part of an ongoing improvement study,
649
+ return its temporary-file inventory to that study's orchestrator instead of
650
+ deleting shared inputs during the gate stage.
651
+
641
652
  ## Current repo conventions
642
653
 
643
654
  - Prefer `GPT-5 Mini` by default for non-local AI replay unless the user names another model.
@@ -0,0 +1,160 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createRequire } from 'node:module';
7
+ import { pathToFileURL, fileURLToPath } from 'node:url';
8
+ import { fork, execFileSync } from 'node:child_process';
9
+ import {
10
+ checkActivation,
11
+ installEntryGateBridge,
12
+ validateExecutionObservationOptions,
13
+ secretFreeProcessReceipt,
14
+ verifyExecutionObservationModules,
15
+ } from './research-entry-gate-bridge.mjs';
16
+ import {
17
+ canonicalJson,
18
+ objectSha256,
19
+ sha256,
20
+ } from './decision-capture-join.mjs';
21
+ import {
22
+ createShardedCaptureSink,
23
+ readStorageManifest,
24
+ } from './decision-capture-storage.mjs';
25
+
26
+ const installedRoot = process.env.TRADEJS_BETA268_FIXTURE_ROOT;
27
+ if (!installedRoot || !path.isAbsolute(installedRoot)) throw new Error('TRADEJS_BETA268_FIXTURE_ROOT must name an isolated exact beta268 installation');
28
+ const executionOptions = () => ({
29
+ schema: 'tradejs-entry-execution-observations/v1',
30
+ enabled: true,
31
+ runtimeVersion: '3.1.29-beta.268',
32
+ runtimeModule: {
33
+ relativePath: 'dist/chunk-SKY2HNZU.mjs',
34
+ sha256: 'a471d1def1ca8f8ae5956539ae5de6efbe909f5f03d2b012b29c4e819dba003e',
35
+ },
36
+ publicModule: {
37
+ relativePath: 'dist/strategies.mjs',
38
+ sha256: 'fe4c6de6260ca322060d3128caa5020792064a123ba879aa21155cb783dfb768',
39
+ },
40
+ typesModule: {
41
+ relativePath: 'dist/index.d.ts',
42
+ sha256: '4cfa0d2af91b3e37d51d7cdf7f7f8d8d9245535adfbec931850b79063385e9d3',
43
+ },
44
+ maxPendingInvocations: 2,
45
+ maxPendingBytes: 8192,
46
+ maxIdentityBytes: 256,
47
+ maxResultBytes: 1024,
48
+ });
49
+ test('installed beta268 module/types SHA binds modeled hook context and public export', () => {
50
+ const base =
51
+ path.join(installedRoot, 'node_modules/@tradejs/');
52
+ const options = executionOptions();
53
+ for (const [name, pkg] of [
54
+ ['runtimeModule', 'node'],
55
+ ['publicModule', 'node'],
56
+ ['typesModule', 'types'],
57
+ ])
58
+ assert.equal(
59
+ sha256(fs.readFileSync(base + pkg + '/' + options[name].relativePath)),
60
+ options[name].sha256,
61
+ );
62
+ const runtime = fs.readFileSync(
63
+ base + 'node/' + options.runtimeModule.relativePath,
64
+ 'utf8',
65
+ );
66
+ const types = fs.readFileSync(
67
+ base + 'types/' + options.typesModule.relativePath,
68
+ 'utf8',
69
+ );
70
+ assert.match(runtime, /order:\s*\{\s*result: signal/);
71
+ assert.match(runtime, /order:\s*\{\s*result: decision.code/);
72
+ assert.match(runtime, /const projectBlock = projectResults.find/);
73
+ assert.match(types, /result: Signal \| string/);
74
+ assert.ok(
75
+ runtime.indexOf('await invokeProjectHooks(stage, params, errorContext)') <
76
+ runtime.indexOf('return invokeHook(stage, hook, params, errorContext)'),
77
+ );
78
+ });
79
+ for (const [delay, projectVeto] of [
80
+ [0, false],
81
+ [1, false],
82
+ [0, true],
83
+ [0, 'prior-manifest'],
84
+ ])
85
+ test(
86
+ 'isolated actual public createStrategyRuntime fixture delay=' +
87
+ delay +
88
+ ' ProjectVeto=' +
89
+ projectVeto,
90
+ (t) => {
91
+ const root = fs.realpathSync(
92
+ fs.mkdtempSync(path.join(os.tmpdir(), 'public-runtime-bridge-unit-')),
93
+ );
94
+ t.after(() => fs.rmSync(root, { recursive: true }));
95
+ fs.writeFileSync(
96
+ path.join(root, 'package.json'),
97
+ JSON.stringify({ name: 'synthetic-research-only' }),
98
+ { flag: 'wx' },
99
+ );
100
+ fs.writeFileSync(
101
+ path.join(root, 'tradejs.config.ts'),
102
+ 'export default {strategies:[],indicators:[],connectors:[],hooks:{beforePlaceOrder:async p=>{p.decision.signal.unitProjectBefore=(p.decision.signal.unitProjectBefore||0)+1;},afterPlaceOrder:async p=>{p.decision.signal.unitProjectAfter=(p.decision.signal.unitProjectAfter||0)+1;},' +
103
+ (projectVeto === true
104
+ ? 'beforeEntryGate:async()=>({allow:false,reason:"UNIT_PROJECT_VETO"})'
105
+ : '') +
106
+ '}};',
107
+ { flag: 'wx' },
108
+ );
109
+ const fixture = path.join(root, 'fixture.mjs');
110
+ fs.writeFileSync(
111
+ fixture,
112
+ "// Unit fixture only: public installed export, own synthetic config/connector/data.\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport assert from 'node:assert/strict';\nimport {pathToFileURL} from 'node:url';\nimport {installEntryGateBridge} from BRIDGE_URL;\nimport {objectSha256,sha256} from JOIN_URL;\nconst base=FROZEN_NODE_DIST;\nassert.equal(sha256(fs.readFileSync(base+'chunk-SKY2HNZU.mjs')),'a471d1def1ca8f8ae5956539ae5de6efbe909f5f03d2b012b29c4e819dba003e');\nassert.equal(sha256(fs.readFileSync(base+'strategies.mjs')),'fe4c6de6260ca322060d3128caa5020792064a123ba879aa21155cb783dfb768');\nlet networkAttempts=0;\n// Test-only denial at OS socket seam, before public package import. No runtime/private module patch.\nnet.Socket.prototype.connect=function(){networkAttempts++;throw Error('UNIT_NETWORK_DENIED');};\nconst {createStrategyRuntime}=await import(pathToFileURL(base+'strategies.mjs'));\nconst delay=Number(process.argv[2]);const projectVeto=process.argv[3]==='veto';const priorManifestVeto=process.argv[3]==='prior-veto';\nconst candle=ts=>({timestamp:ts,dt:new Date(ts).toISOString(),open:100,close:100,high:101,low:99,volume:100,turnover:10000});\nconst firstTs=300*900000;const data=Array.from({length:300},(_,i)=>candle(i*900000));\nconst signal={signalId:'synthetic-public-signal',symbol:'BTCUSDT',direction:'LONG',timestamp:firstTs,interval:'15',strategy:'SyntheticBridge',prices:{currentPrice:100,stopLossPrice:99,takeProfitPrice:102},figures:{},indicators:{},additionalIndicators:{},userName:'synthetic'};\nconst decision={kind:'entry',code:'UNIT_ENTRY',signal,entryContext:{strategy:'SyntheticBridge',direction:'LONG',timestamp:firstTs,prices:signal.prices},orderPlan:{qty:1,stopLossPrice:99,takeProfits:[{price:102,percentage:100}]},runtime:{ai:{enabled:false,minQuality:4},ml:{enabled:false}}};\nconst calls=[],records=[],executions=[];let cfg,gateParams,beforeParams;let placed=0;let coreCalls=0;\nconst manifest={name:'SyntheticBridge',hooks:{onInit:p=>{cfg=p.ctx.strategyConfig;},beforeEntryGate:async p=>{gateParams=p;if(priorManifestVeto)return {allow:false,reason:'UNIT_PRIOR_MANIFEST_VETO'};},beforePlaceOrder:async p=>{assert.equal(p.decision.signal.unitProjectBefore,1);for(const field of ['ctx','decision','policy','ml','ai'])assert.equal(p[field],gateParams[field]);assert.equal(p.entry===gateParams.entry,delay===0);assert.equal(p.market===gateParams.market,delay===0);beforeParams=p;calls.push({stage:'manifest-before',timestamp:p.market.candle.timestamp,signal:p.decision.signal.signalId,entryTimestamp:p.decision.entryContext.timestamp});},afterPlaceOrder:async p=>{assert.equal(p.decision.signal.unitProjectAfter,1);for(const field of ['ctx','decision','entry','policy','ml','ai','market'])assert.equal(p[field],beforeParams[field]);calls.push({stage:'manifest-after',timestamp:p.market.candle.timestamp,result:p.order.result===signal});}}};\nconst creator=createStrategyRuntime({strategyName:'SyntheticBridge',defaults:{ENV:'BACKTEST',INTERVAL:'15',MIN_AI_QUALITY:4,MAX_LOSS_VALUE:1,BACKTEST_ENTRY_DELAY_BARS:delay},manifest,createCore:async()=>async()=>{coreCalls++;return coreCalls===1?decision:{kind:'skip',code:'UNIT_SKIP'};}});\nconst connector={universe:'crypto',getPosition:async()=>placed?{qty:1,price:100,direction:'LONG'}:null,placeOrder:async()=>{placed++;return true;},setTakeProfits:async()=>true,setStopLoss:async()=>true,closePosition:async()=>{throw Error('Unexpected close');}};\nconst strategy=await creator({userName:'synthetic',symbol:'BTCUSDT',connector,data,btcData:data,config:{},runtimeConfigSnapshot:{userConfig:{}}});\nconst composition={strategyName:'SyntheticBridge',researchRunId:'synthetic-only',configId:'fixture',symbols:['BTCUSDT'],windowStart:0,windowEnd:1000000000,mode:'capture-pass-all',config:{resolved:cfg,sha256:objectSha256(cfg),minAiQuality:4,nativeMinQuality:4,interval:'15',directionPolicy:'both'},storage:{schema:'tradejs-capture-stream-storage/v1',helperSha256:'d'.repeat(64),reclaimPlain:false},executionObservations:{schema:'tradejs-entry-execution-observations/v1',enabled:true,runtimeVersion:'3.1.29-beta.268',runtimeModule:{relativePath:'dist/chunk-SKY2HNZU.mjs',sha256:'a471d1def1ca8f8ae5956539ae5de6efbe909f5f03d2b012b29c4e819dba003e'},publicModule:{relativePath:'dist/strategies.mjs',sha256:'fe4c6de6260ca322060d3128caa5020792064a123ba879aa21155cb783dfb768'},typesModule:{relativePath:'dist/index.d.ts',sha256:'4cfa0d2af91b3e37d51d7cdf7f7f8d8d9245535adfbec931850b79063385e9d3'},maxPendingInvocations:2,maxPendingBytes:8192,maxIdentityBytes:256,maxResultBytes:1024}};\nconst controller=installEntryGateBridge({manifest,composition,compositionSha256:'a'.repeat(64),observation:{sha256:'b'.repeat(64)},publicAi:{buildAiPayload:s=>({signal:s}),runAiPromptLocal:async()=>{throw Error('No gate search');}},collectFeatures:()=>({}),sink:{append:r=>records.push(r),close(){},abort(){}},executionSink:{append:r=>executions.push(r),close(){},abort(){}}});\nconst first=candle(firstTs);await strategy(first,first);\nif(delay&&!projectVeto){const next=candle(firstTs+900000);await strategy(next,next);}\ncontroller.close();assert.equal(networkAttempts,0);\nif(projectVeto){assert.equal(placed,0);assert.equal(executions.filter(r=>r.stage==='gate-invocation-link').length,0);assert.equal(executions.at(-1).capturedWithoutManifestGate,1);}\nelse if(priorManifestVeto){assert.equal(placed,0);assert.equal(records.filter(r=>r.schema==='tradejs-entry-gate-observation/v1').length,0);assert.equal(executions[0].ownGateCalled,false);assert.equal(executions[0].gateObservationSha256,null);assert.equal(executions[0].gateObservationStatus,'absent-prior-manifest-veto');assert.deepEqual(executions.map(r=>r.observationSequence),[0,1]);}\nelse{assert.equal(placed,1);assert.deepEqual(calls.map(x=>x.stage),['manifest-before','manifest-after']);assert.equal(calls[0].timestamp,firstTs+delay*900000);assert.equal(calls[0].entryTimestamp,firstTs+delay*900000);assert.equal(calls[1].result,true);assert.deepEqual(executions.slice(0,3).map(x=>x.stage),['gate-invocation-link','before-place-order-attempt','after-place-order-executed']);assert.equal(executions[1].executionTimestamp,firstTs+delay*900000);assert.equal(executions[1].timestamp,firstTs);assert.equal(executions.at(-1).unresolved.length,0);const gate=records.find(r=>r.schema==='tradejs-entry-gate-observation/v1');assert.equal(executions[0].gateObservationSha256,objectSha256(gate));assert.deepEqual(executions.map(r=>r.observationSequence),[0,1,2,3]);assert.ok(executions.slice(0,3).every(r=>r.workerObservationSha256==='b'.repeat(64)));}\nconsole.log(JSON.stringify({schema:'tradejs-isolated-public-runtime-fixture/v1',delay,projectVeto,placed,networkAttempts,stages:executions.map(x=>x.stage),publicModuleSha256:composition.executionObservations.publicModule.sha256}));\nprocess.exit(0);\n"
113
+ .replace('FROZEN_NODE_DIST', JSON.stringify(path.join(installedRoot, 'node_modules/@tradejs/node/dist/')))
114
+ .replace(
115
+ 'BRIDGE_URL',
116
+ JSON.stringify(
117
+ new URL('./research-entry-gate-bridge.mjs', import.meta.url).href,
118
+ ),
119
+ )
120
+ .replace(
121
+ 'JOIN_URL',
122
+ JSON.stringify(
123
+ new URL('./decision-capture-join.mjs', import.meta.url).href,
124
+ ),
125
+ ),
126
+ { flag: 'wx' },
127
+ );
128
+ const output = execFileSync(
129
+ process.execPath,
130
+ [
131
+ fixture,
132
+ String(delay),
133
+ projectVeto === 'prior-manifest'
134
+ ? 'prior-veto'
135
+ : projectVeto
136
+ ? 'veto'
137
+ : 'allow',
138
+ ],
139
+ {
140
+ cwd: root,
141
+ env: {
142
+ PATH: path.dirname(process.execPath),
143
+ PROJECT_CWD: root,
144
+ BINANCE_MARKET_CONTEXT_ENABLED: 'false',
145
+ COINMARKETCAP_CONTEXT_ENABLED: 'false',
146
+ DERIVATIVES_CONTEXT_ENABLED: 'false',
147
+ HYPERLIQUID_WHALE_CONTEXT_ENABLED: 'false',
148
+ BACKTEST_LOWER_TIMEFRAME_EXECUTION_ENABLED: 'false',
149
+ NODE_ENV: 'test',
150
+ },
151
+ encoding: 'utf8',
152
+ maxBuffer: 1048576,
153
+ timeout: 10000,
154
+ },
155
+ );
156
+ const result = JSON.parse(output.trim().split('\n').at(-1));
157
+ assert.equal(result.networkAttempts, 0);
158
+ assert.equal(result.placed, projectVeto ? 0 : 1);
159
+ },
160
+ );
@@ -967,36 +967,6 @@ test('default and storage-only capture bytes match independent accepted frozen g
967
967
  assert.equal(canonicalJson(rows), golden);
968
968
  }
969
969
  });
970
- test('installed beta268 module/types SHA binds modeled hook context and public export', () => {
971
- const base =
972
- '/Users/aleksnick/dev/tradejs/tradejs-project/node_modules/@tradejs/';
973
- const options = executionOptions();
974
- for (const [name, pkg] of [
975
- ['runtimeModule', 'node'],
976
- ['publicModule', 'node'],
977
- ['typesModule', 'types'],
978
- ])
979
- assert.equal(
980
- sha256(fs.readFileSync(base + pkg + '/' + options[name].relativePath)),
981
- options[name].sha256,
982
- );
983
- const runtime = fs.readFileSync(
984
- base + 'node/' + options.runtimeModule.relativePath,
985
- 'utf8',
986
- );
987
- const types = fs.readFileSync(
988
- base + 'types/' + options.typesModule.relativePath,
989
- 'utf8',
990
- );
991
- assert.match(runtime, /order:\s*\{\s*result: signal/);
992
- assert.match(runtime, /order:\s*\{\s*result: decision.code/);
993
- assert.match(runtime, /const projectBlock = projectResults.find/);
994
- assert.match(types, /result: Signal \| string/);
995
- assert.ok(
996
- runtime.indexOf('await invokeProjectHooks(stage, params, errorContext)') <
997
- runtime.indexOf('return invokeHook(stage, hook, params, errorContext)'),
998
- );
999
- });
1000
970
  test('module/types version and checksum reject before public runtime import', (t) => {
1001
971
  const root = fs.realpathSync(
1002
972
  fs.mkdtempSync(path.join(os.tmpdir(), 'bridge-module-binding-')),
@@ -1039,84 +1009,3 @@ test('module/types version and checksum reject before public runtime import', (t
1039
1009
  /version/,
1040
1010
  );
1041
1011
  });
1042
- for (const [delay, projectVeto] of [
1043
- [0, false],
1044
- [1, false],
1045
- [0, true],
1046
- [0, 'prior-manifest'],
1047
- ])
1048
- test(
1049
- 'isolated actual public createStrategyRuntime fixture delay=' +
1050
- delay +
1051
- ' ProjectVeto=' +
1052
- projectVeto,
1053
- (t) => {
1054
- const root = fs.realpathSync(
1055
- fs.mkdtempSync(path.join(os.tmpdir(), 'public-runtime-bridge-unit-')),
1056
- );
1057
- t.after(() => fs.rmSync(root, { recursive: true }));
1058
- fs.writeFileSync(
1059
- path.join(root, 'package.json'),
1060
- JSON.stringify({ name: 'synthetic-research-only' }),
1061
- { flag: 'wx' },
1062
- );
1063
- fs.writeFileSync(
1064
- path.join(root, 'tradejs.config.ts'),
1065
- 'export default {strategies:[],indicators:[],connectors:[],hooks:{beforePlaceOrder:async p=>{p.decision.signal.unitProjectBefore=(p.decision.signal.unitProjectBefore||0)+1;},afterPlaceOrder:async p=>{p.decision.signal.unitProjectAfter=(p.decision.signal.unitProjectAfter||0)+1;},' +
1066
- (projectVeto === true
1067
- ? 'beforeEntryGate:async()=>({allow:false,reason:"UNIT_PROJECT_VETO"})'
1068
- : '') +
1069
- '}};',
1070
- { flag: 'wx' },
1071
- );
1072
- const fixture = path.join(root, 'fixture.mjs');
1073
- fs.writeFileSync(
1074
- fixture,
1075
- "// Unit fixture only: public installed export, own synthetic config/connector/data.\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport assert from 'node:assert/strict';\nimport {pathToFileURL} from 'node:url';\nimport {installEntryGateBridge} from BRIDGE_URL;\nimport {objectSha256,sha256} from JOIN_URL;\nconst base='/Users/aleksnick/dev/tradejs/tradejs-project/node_modules/@tradejs/node/dist/';\nassert.equal(sha256(fs.readFileSync(base+'chunk-SKY2HNZU.mjs')),'a471d1def1ca8f8ae5956539ae5de6efbe909f5f03d2b012b29c4e819dba003e');\nassert.equal(sha256(fs.readFileSync(base+'strategies.mjs')),'fe4c6de6260ca322060d3128caa5020792064a123ba879aa21155cb783dfb768');\nlet networkAttempts=0;\n// Test-only denial at OS socket seam, before public package import. No runtime/private module patch.\nnet.Socket.prototype.connect=function(){networkAttempts++;throw Error('UNIT_NETWORK_DENIED');};\nconst {createStrategyRuntime}=await import(pathToFileURL(base+'strategies.mjs'));\nconst delay=Number(process.argv[2]);const projectVeto=process.argv[3]==='veto';const priorManifestVeto=process.argv[3]==='prior-veto';\nconst candle=ts=>({timestamp:ts,dt:new Date(ts).toISOString(),open:100,close:100,high:101,low:99,volume:100,turnover:10000});\nconst firstTs=300*900000;const data=Array.from({length:300},(_,i)=>candle(i*900000));\nconst signal={signalId:'synthetic-public-signal',symbol:'BTCUSDT',direction:'LONG',timestamp:firstTs,interval:'15',strategy:'SyntheticBridge',prices:{currentPrice:100,stopLossPrice:99,takeProfitPrice:102},figures:{},indicators:{},additionalIndicators:{},userName:'synthetic'};\nconst decision={kind:'entry',code:'UNIT_ENTRY',signal,entryContext:{strategy:'SyntheticBridge',direction:'LONG',timestamp:firstTs,prices:signal.prices},orderPlan:{qty:1,stopLossPrice:99,takeProfits:[{price:102,percentage:100}]},runtime:{ai:{enabled:false,minQuality:4},ml:{enabled:false}}};\nconst calls=[],records=[],executions=[];let cfg,gateParams,beforeParams;let placed=0;let coreCalls=0;\nconst manifest={name:'SyntheticBridge',hooks:{onInit:p=>{cfg=p.ctx.strategyConfig;},beforeEntryGate:async p=>{gateParams=p;if(priorManifestVeto)return {allow:false,reason:'UNIT_PRIOR_MANIFEST_VETO'};},beforePlaceOrder:async p=>{assert.equal(p.decision.signal.unitProjectBefore,1);for(const field of ['ctx','decision','policy','ml','ai'])assert.equal(p[field],gateParams[field]);assert.equal(p.entry===gateParams.entry,delay===0);assert.equal(p.market===gateParams.market,delay===0);beforeParams=p;calls.push({stage:'manifest-before',timestamp:p.market.candle.timestamp,signal:p.decision.signal.signalId,entryTimestamp:p.decision.entryContext.timestamp});},afterPlaceOrder:async p=>{assert.equal(p.decision.signal.unitProjectAfter,1);for(const field of ['ctx','decision','entry','policy','ml','ai','market'])assert.equal(p[field],beforeParams[field]);calls.push({stage:'manifest-after',timestamp:p.market.candle.timestamp,result:p.order.result===signal});}}};\nconst creator=createStrategyRuntime({strategyName:'SyntheticBridge',defaults:{ENV:'BACKTEST',INTERVAL:'15',MIN_AI_QUALITY:4,MAX_LOSS_VALUE:1,BACKTEST_ENTRY_DELAY_BARS:delay},manifest,createCore:async()=>async()=>{coreCalls++;return coreCalls===1?decision:{kind:'skip',code:'UNIT_SKIP'};}});\nconst connector={universe:'crypto',getPosition:async()=>placed?{qty:1,price:100,direction:'LONG'}:null,placeOrder:async()=>{placed++;return true;},setTakeProfits:async()=>true,setStopLoss:async()=>true,closePosition:async()=>{throw Error('Unexpected close');}};\nconst strategy=await creator({userName:'synthetic',symbol:'BTCUSDT',connector,data,btcData:data,config:{},runtimeConfigSnapshot:{userConfig:{}}});\nconst composition={strategyName:'SyntheticBridge',researchRunId:'synthetic-only',configId:'fixture',symbols:['BTCUSDT'],windowStart:0,windowEnd:1000000000,mode:'capture-pass-all',config:{resolved:cfg,sha256:objectSha256(cfg),minAiQuality:4,nativeMinQuality:4,interval:'15',directionPolicy:'both'},storage:{schema:'tradejs-capture-stream-storage/v1',helperSha256:'d'.repeat(64),reclaimPlain:false},executionObservations:{schema:'tradejs-entry-execution-observations/v1',enabled:true,runtimeVersion:'3.1.29-beta.268',runtimeModule:{relativePath:'dist/chunk-SKY2HNZU.mjs',sha256:'a471d1def1ca8f8ae5956539ae5de6efbe909f5f03d2b012b29c4e819dba003e'},publicModule:{relativePath:'dist/strategies.mjs',sha256:'fe4c6de6260ca322060d3128caa5020792064a123ba879aa21155cb783dfb768'},typesModule:{relativePath:'dist/index.d.ts',sha256:'4cfa0d2af91b3e37d51d7cdf7f7f8d8d9245535adfbec931850b79063385e9d3'},maxPendingInvocations:2,maxPendingBytes:8192,maxIdentityBytes:256,maxResultBytes:1024}};\nconst controller=installEntryGateBridge({manifest,composition,compositionSha256:'a'.repeat(64),observation:{sha256:'b'.repeat(64)},publicAi:{buildAiPayload:s=>({signal:s}),runAiPromptLocal:async()=>{throw Error('No gate search');}},collectFeatures:()=>({}),sink:{append:r=>records.push(r),close(){},abort(){}},executionSink:{append:r=>executions.push(r),close(){},abort(){}}});\nconst first=candle(firstTs);await strategy(first,first);\nif(delay&&!projectVeto){const next=candle(firstTs+900000);await strategy(next,next);}\ncontroller.close();assert.equal(networkAttempts,0);\nif(projectVeto){assert.equal(placed,0);assert.equal(executions.filter(r=>r.stage==='gate-invocation-link').length,0);assert.equal(executions.at(-1).capturedWithoutManifestGate,1);}\nelse if(priorManifestVeto){assert.equal(placed,0);assert.equal(records.filter(r=>r.schema==='tradejs-entry-gate-observation/v1').length,0);assert.equal(executions[0].ownGateCalled,false);assert.equal(executions[0].gateObservationSha256,null);assert.equal(executions[0].gateObservationStatus,'absent-prior-manifest-veto');assert.deepEqual(executions.map(r=>r.observationSequence),[0,1]);}\nelse{assert.equal(placed,1);assert.deepEqual(calls.map(x=>x.stage),['manifest-before','manifest-after']);assert.equal(calls[0].timestamp,firstTs+delay*900000);assert.equal(calls[0].entryTimestamp,firstTs+delay*900000);assert.equal(calls[1].result,true);assert.deepEqual(executions.slice(0,3).map(x=>x.stage),['gate-invocation-link','before-place-order-attempt','after-place-order-executed']);assert.equal(executions[1].executionTimestamp,firstTs+delay*900000);assert.equal(executions[1].timestamp,firstTs);assert.equal(executions.at(-1).unresolved.length,0);const gate=records.find(r=>r.schema==='tradejs-entry-gate-observation/v1');assert.equal(executions[0].gateObservationSha256,objectSha256(gate));assert.deepEqual(executions.map(r=>r.observationSequence),[0,1,2,3]);assert.ok(executions.slice(0,3).every(r=>r.workerObservationSha256==='b'.repeat(64)));}\nconsole.log(JSON.stringify({schema:'tradejs-isolated-public-runtime-fixture/v1',delay,projectVeto,placed,networkAttempts,stages:executions.map(x=>x.stage),publicModuleSha256:composition.executionObservations.publicModule.sha256}));\nprocess.exit(0);\n"
1076
- .replace(
1077
- 'BRIDGE_URL',
1078
- JSON.stringify(
1079
- new URL('./research-entry-gate-bridge.mjs', import.meta.url).href,
1080
- ),
1081
- )
1082
- .replace(
1083
- 'JOIN_URL',
1084
- JSON.stringify(
1085
- new URL('./decision-capture-join.mjs', import.meta.url).href,
1086
- ),
1087
- ),
1088
- { flag: 'wx' },
1089
- );
1090
- const output = execFileSync(
1091
- process.execPath,
1092
- [
1093
- fixture,
1094
- String(delay),
1095
- projectVeto === 'prior-manifest'
1096
- ? 'prior-veto'
1097
- : projectVeto
1098
- ? 'veto'
1099
- : 'allow',
1100
- ],
1101
- {
1102
- cwd: root,
1103
- env: {
1104
- PATH: path.dirname(process.execPath),
1105
- PROJECT_CWD: root,
1106
- BINANCE_MARKET_CONTEXT_ENABLED: 'false',
1107
- COINMARKETCAP_CONTEXT_ENABLED: 'false',
1108
- DERIVATIVES_CONTEXT_ENABLED: 'false',
1109
- HYPERLIQUID_WHALE_CONTEXT_ENABLED: 'false',
1110
- BACKTEST_LOWER_TIMEFRAME_EXECUTION_ENABLED: 'false',
1111
- NODE_ENV: 'test',
1112
- },
1113
- encoding: 'utf8',
1114
- maxBuffer: 1048576,
1115
- timeout: 10000,
1116
- },
1117
- );
1118
- const result = JSON.parse(output.trim().split('\n').at(-1));
1119
- assert.equal(result.networkAttempts, 0);
1120
- assert.equal(result.placed, projectVeto ? 0 : 1);
1121
- },
1122
- );
@@ -360,6 +360,16 @@ it exactly.
360
360
  `node .codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs`
361
361
  after creating or editing research records.
362
362
 
363
+ ## Completed research storage
364
+
365
+ At the final handoff, follow
366
+ [`references/research-retention.md`](references/research-retention.md).
367
+ Keep compact results and every frozen candidate permanently; remove temporary
368
+ trade data and run-specific caches after all consuming research stages finish.
369
+ When executing one experiment for an ongoing improvement study, hand its
370
+ temporary-file inventory to the orchestrator and preserve its inputs until
371
+ that study's final cleanup.
372
+
363
373
  ## Validation
364
374
 
365
375
  - Run the affected strategy tests after strategy edits, for example `yarn jest packages/strategies/src/<StrategyName> --runInBand`.
@@ -230,6 +230,14 @@ calendar days`. Include zero-activity side cohorts rather than omitting them.
230
230
  - State any metric that cannot be recovered from the structured snapshot under
231
231
  `Limitations and next step` and lower the reproduction status accordingly.
232
232
 
233
+ ## Completed study cleanup
234
+
235
+ Follow [research-retention.md](research-retention.md) after the entire study
236
+ finishes. Keep compact results and all frozen candidates permanently. Trade
237
+ rows, matched-pair payloads, exports and run-specific caches are temporary.
238
+ The permanent note must contain aggregate metrics and exact candidate source
239
+ or retained source patches before those temporary files are removed.
240
+
233
241
  ## Historical migration
234
242
 
235
243
  Historical split records retain their original body under a common v1
@@ -0,0 +1,157 @@
1
+ # Completed research storage
2
+
3
+ Read this when finishing a research lineage or cleaning an older completed
4
+ study. The Project owner keeps compact results and frozen candidates permanently.
5
+ Trade rows, AI feature exports, trace streams, intermediate datasets and
6
+ run-specific caches are temporary. Remove them after the entire study finishes,
7
+ including gate evaluation, comparisons and final charts. A completed backtest
8
+ inside an active study is not permission to remove its inputs.
9
+
10
+ ## Permanent records
11
+
12
+ Use the existing note, candidate manifest and trial ledger. Do not create a
13
+ second best-candidate pointer. Before cleanup, preserve:
14
+
15
+ - Every hypothesis and candidate, including rejected and failed attempts, its
16
+ causal claim, exact resolved config, source commit and any uncommitted patch,
17
+ deterministic gate code/config, context settings, parent IDs and verdict.
18
+ A hash or a deleted worktree path does not preserve candidate source.
19
+ - The common comparison scope: timestamps, ordered symbols, interval, fees,
20
+ slippage, execution assumptions, risk unit, code/tool versions, train/test
21
+ boundaries, exposure history and reconciliation/completion results.
22
+ - Structured metrics for every reported candidate, period and ALL/LONG/SHORT
23
+ cohort, including zero-trade cohorts, statistical checks, limitations and
24
+ candidate-minus-control deltas. Preserve selected and rejected reasons and
25
+ the full trial denominator. Keep compact month/fold/regime summaries and
26
+ cost tests needed to explain the decision.
27
+ - Final reports and charts, the ledger/index and artifact hashes. Freeze any
28
+ chart points needed to render the final chart before removing trade rows.
29
+ Store aggregate metrics in JSON; do not embed trades or matched-pair objects
30
+ in the permanent note merely to retain a large export under another name.
31
+
32
+ Follow [research-notes.md](research-notes.md), and run `yarn notes:check`.
33
+ Review the actual configs, source and metrics, not just the frontmatter label.
34
+ The record must explain which old behavior was tried and why the next study
35
+ should reuse or reject it. Future research reads these records before choosing
36
+ new hypotheses. Compare saved results directly only on matching scopes and
37
+ risk units. Changed periods or assumptions require a new frozen evaluation.
38
+
39
+ ## Cleanup
40
+
41
+ The research owner performs cleanup as the final step of the study, without a
42
+ new approval request. The owner's storage policy authorizes removal of temporary
43
+ research files after their permanent records have been verified. Keep files
44
+ needed by another unfinished study. Never clear a whole shared cache, Redis,
45
+ market history, runtime evidence or unrelated research directory.
46
+
47
+ Create a retention inventory under the study directory. Use the installed
48
+ `yarn strategy-release retention` command with these fields:
49
+
50
+ ```json
51
+ {
52
+ "now": 1792108800000,
53
+ "research": {
54
+ "researchId": "example-study",
55
+ "status": "completed",
56
+ "completedAt": 1792108800000,
57
+ "permanentArtifacts": [
58
+ {"role": "note", "path": "notes/MyStrategy/2026-10-16-example.md", "sha256": "<actual SHA-256>"},
59
+ {"role": "candidates", "path": "data/strategy-release/example/candidates.json", "sha256": "<actual SHA-256>"},
60
+ {"role": "metrics", "path": "data/strategy-release/example/metrics.json", "sha256": "<actual SHA-256>"}
61
+ ]
62
+ },
63
+ "entries": [
64
+ {
65
+ "path": "data/ai/export/example.jsonl",
66
+ "kind": "research_payload",
67
+ "researchId": "example-study",
68
+ "sha256": "<actual SHA-256>",
69
+ "createdAt": 1792022400000,
70
+ "bytes": 1234,
71
+ "verified": true,
72
+ "aggregated": true
73
+ }
74
+ ]
75
+ }
76
+ ```
77
+
78
+ Use actual timestamps, sizes and hashes. `research_cache` identifies disposable
79
+ run-specific cache files. The same note may serve several permanent roles when
80
+ it embeds the complete candidate and metric records; list its exact checksum
81
+ for each role. Add source patches, gate files, manifests, ledgers, indexes and
82
+ charts to `permanentArtifacts` too. Only explicit files inside Project `data/`
83
+ are eligible. Files open in another process, symlinks, notes and patches are
84
+ protected. The command checks all permanent and disposable hashes before
85
+ removing any file, and writes an incremental cleanup receipt.
86
+ On macOS, cached virtual-machine file handles require an additional read-only
87
+ check of the actual processes inside every local Docker container that mounts
88
+ those files. Unreadable or unresolved consumers keep the files protected.
89
+
90
+ ```bash
91
+ yarn strategy-release retention --input <inventory.json>
92
+ yarn strategy-release retention --input <inventory.json> --apply
93
+ ```
94
+
95
+ Check that the plan's `deleteCount` matches the intended inventory before
96
+ applying, then check the completed receipt. An older installed CLI may not
97
+ support research entries and may return zero deletions. In the canonical
98
+ workspace, use the explicitly built framework CLI from the Project directory
99
+ when that happens, and record its source SHA/dirty diff:
100
+
101
+ ```bash
102
+ PROJECT_CWD="$PWD" node "$TRADEJS_FRAMEWORK_REPOSITORY_ROOT/packages/cli/dist/cli.js" \
103
+ strategy-release retention --input <inventory.json> [--apply]
104
+ ```
105
+
106
+ Do not change installed package versions or publish a release just to clean
107
+ research files. If the built source CLI is unavailable, keep the inventory and
108
+ report cleanup as pending rather than claiming the files were removed.
109
+
110
+ Research payloads have no age delay once the study is complete and aggregated.
111
+ The separate runtime retention policy remains unchanged. Keep the inventory and
112
+ receipt and its deletion journal with the permanent records. A future comparison can use the saved
113
+ numbers and reproduce the candidate by rerunning its frozen code/config. New
114
+ trade-level questions and new historical windows require a rerun. Do not claim
115
+ the removed files remain available for checksum verification.
116
+
117
+ ## Older studies
118
+
119
+ Recover available compact results and candidate definitions from existing
120
+ notes, configs, manifests and reports without starting another backtest. If
121
+ the missing evidence cannot be recovered without a rerun, retire the old study
122
+ and delete its temporary payloads. The owner explicitly authorized that policy.
123
+ Keep its original partial/blocked status and record the gaps. Never fabricate
124
+ historical configs, metrics or successful completion.
125
+
126
+ Use `research.status: retired` and set `completedAt` to the retirement decision
127
+ time. Add `retirement: {policy: "discard-unrecoverable-without-rerun", reason:
128
+ "<specific reason>", missingEvidence: ["<recorded gaps>"]}`. Preserve all
129
+ available notes, candidate/source/config files and compact metrics. The tool
130
+ permits partial or blocked notes in this mode and records the retirement in
131
+ the cleanup receipt. `aggregated: false` records genuinely missing aggregates;
132
+ file checksum verification remains mandatory. Active studies are never retired
133
+ merely to reclaim disk space.
134
+
135
+ ## Worktree removal
136
+
137
+ Remove the study's dedicated worktree after freezing permanent candidate and
138
+ result records, including when a selected candidate exists. Retain its
139
+ commit/branch and exact source. For old idle research worktrees, preserve dirty
140
+ and untracked source before removal. Do not delete branches, canonical checkouts,
141
+ locked or managed checkouts belonging to active chats, or ongoing studies.
142
+
143
+ Inspect the owning repository's `git worktree list` and checkout status.
144
+ The helper preserves a Git history bundle, source snapshot and staged/unstaged
145
+ patches, verifies their contents, and refuses worktrees with open files:
146
+
147
+ ```bash
148
+ python3 .codex/skills/strategy-backtest-research/scripts/retire-worktree.py \
149
+ --repository <canonical-repository> --worktree <exact-worktree> \
150
+ --out data/worktree-cleanup/<id>
151
+ ```
152
+
153
+ Review its plan, then repeat with `--apply`. Keep the source archive and
154
+ receipt permanently. Prune stale registrations only after checking that their
155
+ directories are actually absent, and preserve their branch/commit identities
156
+ in the cleanup inventory. For Codex-managed worktrees attached to this chat,
157
+ prefer the app's archive tool, which preserves recoverable state.
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env python3
2
+ """Archive exact source state before removing an explicitly selected worktree."""
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import subprocess
9
+ import tarfile
10
+ import shutil
11
+
12
+
13
+ def git(root, *args):
14
+ return subprocess.check_output(['git', '-C', str(root), *args])
15
+
16
+
17
+ def sha_file(file):
18
+ result = hashlib.sha256()
19
+ with file.open('rb') as stream:
20
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
21
+ result.update(chunk)
22
+ return result.hexdigest()
23
+
24
+
25
+ def retire(repository, worktree, out, apply=False):
26
+ repository, worktree, out = map(lambda p: Path(p).resolve(), (repository, worktree, out))
27
+ records = git(repository, 'worktree', 'list', '--porcelain').decode().strip().split('\n\n')
28
+ paths = [r.splitlines()[0].split(' ', 1)[1] for r in records]
29
+ if str(worktree) not in paths or str(worktree) == paths[0]:
30
+ raise ValueError('Select a registered secondary worktree, never the primary checkout')
31
+ record = records[paths.index(str(worktree))]
32
+ if '\nlocked' in record or not worktree.is_dir():
33
+ raise ValueError('Worktree is locked or missing')
34
+ if git(worktree, 'submodule', 'status').strip():
35
+ raise ValueError('Archive submodules separately before removing this worktree')
36
+ if worktree == out or worktree in out.parents:
37
+ raise ValueError('Archive must be outside the removed worktree')
38
+ head = git(worktree, 'rev-parse', 'HEAD').decode().strip()
39
+ status = git(worktree, 'status', '--porcelain=v1', '-z')
40
+ patch = git(worktree, 'diff', 'HEAD', '--binary')
41
+ staged = git(worktree, 'diff', '--cached', '--binary')
42
+ files = set(git(worktree, 'ls-files', '-z', '--cached', '--others', '--exclude-standard').split(b'\0'))
43
+ files.update(git(worktree, 'ls-files', '-z', '--others', '--ignored', '--exclude-standard').split(b'\0'))
44
+ generated = {'node_modules', 'dist', 'build', '.yarn', '.turbo', '.next', 'coverage', '__pycache__'}
45
+ selected = []
46
+ for raw in sorted(files):
47
+ if not raw:
48
+ continue
49
+ name = os.fsdecode(raw)
50
+ relative = Path(name)
51
+ if relative.is_absolute() or '..' in relative.parts:
52
+ raise ValueError('Invalid source path')
53
+ if any(part in generated for part in relative.parts):
54
+ continue
55
+ if (relative.name == '.env' or relative.name.startswith('.env.') and relative.suffix not in {'.example', '.sample', '.template'}):
56
+ raise ValueError('Preserve local credentials separately before removing this worktree')
57
+ file = worktree / relative
58
+ if file.is_symlink() or file.is_file():
59
+ selected.append((name, None if file.is_symlink() else sha_file(file)))
60
+ plan = {'worktree': str(worktree), 'repository': str(repository), 'head': head,
61
+ 'registration': record, 'sourceFiles': len(selected), 'dirty': bool(status), 'archive': str(out)}
62
+ if not apply:
63
+ return {**plan, 'status': 'planned'}
64
+ # A cwd or any open source file means this checkout is still in use.
65
+ opened = subprocess.run(['lsof', '-F', 'pcn', '+D', str(worktree)], capture_output=True)
66
+ if opened.returncode != 1:
67
+ raise ValueError('Worktree has open files or cannot be inspected: ' + opened.stdout.decode()[:500])
68
+ out.mkdir(parents=True, exist_ok=False)
69
+ git(worktree, 'bundle', 'create', str(out / 'history.bundle'), 'HEAD')
70
+ git(repository, 'bundle', 'verify', str(out / 'history.bundle'))
71
+ (out / 'working-tree.patch').write_bytes(patch)
72
+ (out / 'staged.patch').write_bytes(staged)
73
+ (out / 'status.porcelain').write_bytes(status)
74
+ archive = out / 'source.tar.gz'
75
+ with tarfile.open(archive, 'w:gz', dereference=False) as tar:
76
+ for name, _ in selected:
77
+ tar.add(worktree / name, arcname=name, recursive=False)
78
+ with tarfile.open(archive, 'r:gz') as tar:
79
+ for name, digest in selected:
80
+ member = tar.getmember(name)
81
+ file = worktree / name
82
+ if member.issym():
83
+ assert os.readlink(file) == member.linkname
84
+ else:
85
+ stream = tar.extractfile(member)
86
+ archived = hashlib.file_digest(stream, 'sha256').hexdigest()
87
+ assert archived == digest == sha_file(file), name
88
+ if git(worktree, 'rev-parse', 'HEAD').decode().strip() != head or git(worktree, 'status', '--porcelain=v1', '-z') != status or git(worktree, 'diff', 'HEAD', '--binary') != patch:
89
+ raise ValueError('Worktree changed during archival; leave it in place')
90
+ receipt = {**plan, 'status': 'archived', 'sha256': {p.name: sha_file(p) for p in out.iterdir()}}
91
+ target = out / 'receipt.json'
92
+ target.write_text(json.dumps(receipt, indent=2) + '\n')
93
+ try:
94
+ git(repository, 'worktree', 'remove', *(['--force'] if status else []), str(worktree))
95
+ except subprocess.CalledProcessError:
96
+ # Git can remove the registration but leave an ignored dependency tree
97
+ # behind on macOS. Only finish removal after registration is gone and
98
+ # the exact source snapshot has already passed the checks above.
99
+ remaining = git(repository, 'worktree', 'list', '--porcelain').decode()
100
+ if f'worktree {worktree}\n' in remaining or worktree.is_symlink():
101
+ raise
102
+ if worktree.exists():
103
+ shutil.rmtree(worktree)
104
+ receipt['status'] = 'removed'
105
+ target.write_text(json.dumps(receipt, indent=2) + '\n')
106
+ return receipt
107
+
108
+
109
+ if __name__ == '__main__':
110
+ parser = argparse.ArgumentParser(description=__doc__)
111
+ parser.add_argument('--repository', required=True)
112
+ parser.add_argument('--worktree', required=True)
113
+ parser.add_argument('--out', required=True)
114
+ parser.add_argument('--apply', action='store_true')
115
+ args = parser.parse_args()
116
+ print(json.dumps(retire(args.repository, args.worktree, args.out, args.apply), indent=2))
@@ -27,6 +27,12 @@ it must not change either composition.
27
27
 
28
28
  ## Make the comparison fair
29
29
 
30
+ Use retained compact results and frozen candidate definitions even when a
31
+ completed study's trade data was intentionally removed. Check the permanent
32
+ record and cleanup receipt. Compare saved metrics on identical scopes; a new
33
+ period or unavailable metric needs a frozen bridge evaluation, not an invented
34
+ value or a repeat of the original optimization.
35
+
30
36
  Use the maximum common timestamp range, point-in-time universe, symbols,
31
37
  interval, fees, slippage, entry delay, risk unit, and execution assumptions.
32
38
  Normalize PnL and drawdown per unit of `MAX_LOSS_VALUE` when production and the
@@ -27,6 +27,13 @@ Creating a report or chart under `output/` is allowed.
27
27
 
28
28
  ## Report
29
29
 
30
+ Completed studies may intentionally retain only compact results and candidate
31
+ source/config. Read their permanent notes, manifests, ledgers and cleanup
32
+ receipts before looking for raw exports. Missing intentionally removed trade
33
+ data does not erase a recorded result or rejected hypothesis. Verify retained
34
+ records and label the scope as saved metrics; new trade-level analysis requires
35
+ a rerun. Reuse the saved final chart when raw rows have been removed.
36
+
30
37
  Show:
31
38
 
32
39
  - candidate ID, selection time, research ID, source/package revision, dirty
@@ -34,6 +34,10 @@ source edits does not need a worktree.
34
34
  on the worktree branch and hand off the exact commit SHA; do not retain
35
35
  rejected behavior as source commits.
36
36
 
37
+ After the final evidence handoff, remove the dedicated worktree even when a
38
+ candidate was selected. Keep its commit/branch, source snapshot and any
39
+ uncommitted candidate patches under the shared research-retention contract.
40
+
37
41
  ## Authority boundary
38
42
 
39
43
  You may refresh research artifacts, run cache-backed research, edit strategy
@@ -123,6 +127,15 @@ underpowered below 20 events, diagnostic at 20–49, and selection-grade at 50+.
123
127
 
124
128
  ## Handoff
125
129
 
130
+ Before the final answer, complete
131
+ [`../strategy-backtest-research/references/research-retention.md`](../strategy-backtest-research/references/research-retention.md).
132
+ Preserve compact results, all candidate definitions, source/gate patches,
133
+ selection history and final charts. Then remove the finished study's trade
134
+ exports, trace streams, intermediate datasets and run-specific caches. Do not
135
+ clean up after an individual round or core run while gate/comparison work still
136
+ needs its rows. Read permanent notes and ledgers before inventing new trials;
137
+ the absence of deleted exports is not a reason to repeat an old hypothesis.
138
+
126
139
  Create or update the existing checksum-verified strategy-release/candidate
127
140
  manifest rather than inventing a second pointer format. Freeze candidate ID,
128
141
  source/package SHA, full resolved core config, deterministic gate/context,
@@ -45,3 +45,8 @@ Update the immutable comparison evidence and candidate freshness without
45
45
  rewriting the original selection record. State whether the incumbent remains
46
46
  best under the frozen objective and choose exactly one next skill: report,
47
47
  research, forward-start, forward-status, or risk-scale.
48
+
49
+ Before finishing, follow
50
+ [`../strategy-backtest-research/references/research-retention.md`](../strategy-backtest-research/references/research-retention.md).
51
+ Keep the frozen candidates and compact old/new metric comparison permanently,
52
+ then remove this completed evaluation's trade exports and run-specific caches.
@@ -139,6 +139,15 @@ approval and a separate release decision.
139
139
 
140
140
  Use the default tiering unless the user later changes it:
141
141
 
142
+ Completed research follows
143
+ [`../../strategy-backtest-research/references/research-retention.md`](../../strategy-backtest-research/references/research-retention.md).
144
+ Keep compact outcomes, all candidate definitions, configs, source/gate patches,
145
+ trial ledgers and final charts permanently. Remove research trade payloads and
146
+ run-specific caches immediately after the full study finishes and its compact
147
+ records pass verification. Use `research_payload` or `research_cache` entries
148
+ with an exact completed research binding; never apply this rule to runtime
149
+ evidence. The tiers below apply to runtime data.
150
+
142
151
  - operational Redis evidence: 3 days;
143
152
  - reproducible verbose payloads: 14 days;
144
153
  - verified, aggregated runtime bundles: 90 days;
@@ -0,0 +1,94 @@
1
+ ---
2
+ name: tradejs-docs
3
+ description: Писать и редактировать пользовательскую документацию TradeJS, статьи базы знаний и README пакетов. Выбирать содержание под задачу читателя, убирать лишние внутренние подробности и проверять команды и поведение по исходникам. Применять при просьбах написать инструкцию, упростить статью или убрать AI-слоп из документации TradeJS. Не использовать для исследовательских отчётов, маркетинговых текстов и обычных ответов в чате.
4
+ ---
5
+
6
+ # Документация TradeJS
7
+
8
+ Помоги читателю выполнить конкретную задачу. Простые слова нужны вместе
9
+ с правильным выбором содержания: понятное описание ненужных действий
10
+ всё равно мешает пользоваться инструкцией.
11
+
12
+ ## Читатель и задача
13
+
14
+ По запросу и соседним статьям определи, кто читатель и что он хочет сделать.
15
+ Уточняй только то, что существенно меняет содержание и неясно из контекста.
16
+
17
+ - Пользователь готового приложения подключает клиент, читает данные
18
+ или пользуется функциями. Работающий сервер является исходным условием.
19
+ - Владелец приложения устанавливает и обслуживает TradeJS. Настройка сервера,
20
+ окружения и фоновых процессов относится к его задаче.
21
+ - Разработчик пакета использует публичные команды и API. Внутренние команды
22
+ репозитория допустимы только в явно внутренней документации.
23
+
24
+ Оставляй в статье сведения, которые помогают выполнить задачу, проверить
25
+ результат или понять существенное ограничение. Не добавляй администрирование
26
+ в инструкцию пользователя только потому, что функция зависит от сервера.
27
+ Ссылайся на отдельную инструкцию, если настройка действительно нужна читателю.
28
+ Не создавай дополнительные статьи без необходимости для текущей задачи.
29
+
30
+ Например, в статье о подключении к MCP готового TradeJS нужны адрес сервера,
31
+ команда подключения, авторизация и пример запроса. Требование о совместимости
32
+ пакетов приложения и worker относится к установке сервера. Если статья
33
+ посвящена установке, объясни, какие версии нужны и как проверить совместимость,
34
+ вместо фразы "нужен согласованный выпуск пакетов".
35
+
36
+ ## Проверка содержания
37
+
38
+ Редактируй публичную базу знаний в `tradejs-docs`, README пакета в репозитории
39
+ пакета. Следуй карте репозиториев и местному `AGENTS.md`. Читай исходники
40
+ владельца функции, когда нужно проверить её поведение.
41
+
42
+ Для новых и изменённых технических утверждений проверь названия команд,
43
+ параметры, значения по умолчанию, права и результат. Используй исходники,
44
+ экспорты пакета, справку команды и существующие тесты по необходимости.
45
+ При чисто редакторской правке сохраняй технический смысл; не запускай
46
+ проверку всей системы без повода. Для внешних библиотек и клиентов получай
47
+ актуальную официальную документацию способом, указанным в `AGENTS.md`.
48
+
49
+ Различай текущий исходник, опубликованный пакет и работающий прод.
50
+ Наличие функции в коде не доказывает её доступность пользователю.
51
+ Если нужную деталь подтвердить не удалось, обозначь пробел в сообщении
52
+ пользователю и не выдавай предположение за проверенную инструкцию.
53
+
54
+ ## Написание статьи
55
+
56
+ Начинай с того, что читатель сможет сделать. Условия включай только те,
57
+ которые ему нужно проверить или выполнить. Располагай действия в порядке
58
+ выполнения, рядом указывай ожидаемый результат. Для команд объясняй,
59
+ где их выполнять и какие значения подставить, если это неочевидно.
60
+
61
+ Выбирай структуру по задаче. В инструкции нужен короткий рабочий пример;
62
+ в справочнике уместна таблица параметров; в объяснении нужны причины
63
+ и связи. Не превращай каждую статью в каталог всех возможностей функции.
64
+ Большие перечни полей и протокольных деталей оставляй справочным разделам,
65
+ если без них можно выполнить основной сценарий.
66
+
67
+ Пиши обычными словами, сохраняя точные имена команд, файлов и параметров
68
+ в обратных кавычках. Незнакомый термин объясняй при первом упоминании,
69
+ если он нужен читателю. Убирай повторы, рекламные оценки, абстрактные
70
+ обещания, риторические противопоставления и внутренние названия без объяснения.
71
+ Не подменяй их новыми красивыми, но столь же неясными формулировками.
72
+
73
+ Сохраняй существенные ограничения, смысл предупреждений и поведение при
74
+ ошибках. Не придумывай успешный вывод команды, номера версий, результаты
75
+ проверок или гарантии. Раздел о проблемах должен связывать наблюдаемую
76
+ ошибку с доступным читателю действием, а не перечислять общие советы.
77
+
78
+ ## Редакторская проверка и завершение
79
+
80
+ Прочитай статью как человек, который не знает устройство репозитория.
81
+ Проверь, понятны ли первое действие, значения для подстановки и признак успеха.
82
+ Удали абзацы, которые не помогают заявленной задаче и не объясняют нужное
83
+ ограничение. Сверь изменённые примеры и утверждения с найденными источниками.
84
+
85
+ Сохраняй адрес статьи и по возможности существующие якоря. Если меняешь
86
+ якорь, проверь ведущие к нему ссылки. Обновляй обе локали, когда меняется
87
+ общее содержание; сохраняй одинаковый смысл примеров, прав и ограничений.
88
+ Файлы для ИИ-поиска обновляй, если правка затронула описанные в них сведения.
89
+ Запусти проверки, требуемые репозиторием; для `tradejs-docs` это `yarn checks`.
90
+
91
+ В сообщении о результате кратко укажи изменения и проверку. Различай
92
+ локальную правку, коммит, push, публикацию образа и обновление сайта.
93
+ После запроса на деплой проверь завершение выкладки и содержимое публичной
94
+ страницы. Создание статьи или навыка само по себе не разрешает деплой.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Документация TradeJS"
3
+ short_description: "Понятные инструкции TradeJS с проверкой по коду"
4
+ default_prompt: "Используй $tradejs-docs, чтобы написать или отредактировать статью TradeJS для её читателя и проверить технические детали."
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": "tradejs-skill-bundle/v1",
3
3
  "source": "TradeJS-Dev/TradeJS:.codex/skills",
4
- "bundleSha256": "2106b5dcc9688d50d0e73902d1ee981e0c7b7d15aba3d273af6eb04ef688b532",
4
+ "bundleSha256": "e63d233c0cab62f3924a14db1c665433244f6572cf550812ca30857ae69bfa29",
5
5
  "skills": [
6
6
  "ai-train-local-research",
7
7
  "backtest-config-redis",
@@ -16,6 +16,7 @@
16
16
  "strategy-forward-start",
17
17
  "strategy-forward-status",
18
18
  "tradejs-mcp",
19
+ "tradejs-docs",
19
20
  "strategy-risk-scale",
20
21
  "strategy-release"
21
22
  ],
@@ -34,25 +35,28 @@
34
35
  ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.mjs": "a9f69ec62937344f5a160dce0f66d1f3251c9fcf061229dea65236cfe116c59c",
35
36
  ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.test.mjs": "d7a4f1d8c19a4506bd09cd865b9718f498e4e65a5f54b902fb0309b8eede186c",
36
37
  ".codex/skills/ai-train-local-research/scripts/market-regime-plot.py": "3f1e5d93110c6c8987dd09ba16cd65968c789f548fb374905009bb12705b423d",
38
+ ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.integration.mjs": "fe8fe74d82aae32435640ed3ee2b0062d24f300bc7fc443ec18ac41118ffac74",
37
39
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.mjs": "f8c9cb7f63c7e83dcaedf6d58979a2b2a3b4730bf7159aae10ee19b875530fa7",
38
- ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.test.mjs": "439e844a08631c1af78f2c2b226bb649a2efad79d08c14d67bd2fff297f8a9fe",
40
+ ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.test.mjs": "a9f5a918cda1d36da62dbaaf1ea3aea6bcb40f06ad9f7c4bfc4da18baa5aa01e",
39
41
  ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.mjs": "ad70b73ea49060c0a350d2ca2f85788e6900bdbece46434e9a95865965329d89",
40
42
  ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.test.mjs": "6244c3540f708be6f2f29fa5b871a266e0ecee7a5ba4d588b0e3acb47e1ee445",
41
- ".codex/skills/ai-train-local-research/SKILL.md": "23bd6dbae5d5e8fab46dc94a64de2ac797e47058949d19ca696b9160be67d351",
43
+ ".codex/skills/ai-train-local-research/SKILL.md": "371d98fa7e7de3cb7ccfab6924d7d7bb2638b1c0ed05cf2035c9a074c24ce4fc",
42
44
  ".codex/skills/backtest-config-redis/scripts/get_backtest_config.sh": "833e950d6348c5b7a4bd3f00d25af60f6394190bff744bd5ab64db9e43d826d5",
43
45
  ".codex/skills/backtest-config-redis/SKILL.md": "ac4f9d685c12f748a87b1882df1f731dd3ae9ec8bd7c11cb652221fe0463febc",
44
46
  ".codex/skills/runtime-parity-mismatch-analysis/SKILL.md": "f9cbc571baaba7a185550415c3ef31f0f55a9503107c8ace2314fac88ba025bd",
45
47
  ".codex/skills/save-strategy-config-from-backtest/agents/openai.yaml": "ba163f9449562241ed954ca2e0f12e22562390740cdcf0d09d7f99f0ef791741",
46
48
  ".codex/skills/save-strategy-config-from-backtest/SKILL.md": "a73cddc29fb8fa741fe6226c051e19b0f9a19747babf96d336e7f165fb1fd298",
47
- ".codex/skills/strategy-backtest-research/references/research-notes.md": "e7b85dce73c612ba6821857e511b63754a574cc14d8ba5224466002fe27509aa",
49
+ ".codex/skills/strategy-backtest-research/references/research-notes.md": "85a23e26f2035e98cd8d3a56b4ec14638cd9d42b1dc34b4dc8ca958c3624ecaa",
50
+ ".codex/skills/strategy-backtest-research/references/research-retention.md": "55fb27507d9f83a0123d9c840d4ef3080ff7d77c32ecfc94f33b7aab456e0f3c",
48
51
  ".codex/skills/strategy-backtest-research/scripts/backtest-run-metrics.mjs": "dbcc6bb7cab4e0108ed11df503b8a0a337d1a01b77c5b56554ce1264a00f5d57",
49
52
  ".codex/skills/strategy-backtest-research/scripts/backtest-run-metrics.test.mjs": "a00d0ae5fb0037cc554282dbe22109a9e34cb64b93d26a6feab69005a2ba637f",
50
53
  ".codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.mjs": "61e8604bba829914315fccd604afc4a13f97409b7ebe2f22d255d0eb57f32921",
51
54
  ".codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.test.mjs": "447453e2415004336293297b7f68ffd16ae35053d9725accaa5f42e1bbe28a58",
52
55
  ".codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs": "435aa6560abcf4e8a60fb86230d8d8de2f2dc9e4c52acc7a272ce30287d40325",
53
- ".codex/skills/strategy-backtest-research/SKILL.md": "15cdd5588854f62eeaed5c9dc3b69886163aee0543695be987944c2fc6febced",
54
- ".codex/skills/strategy-candidate-compare/SKILL.md": "62f44b986c879f6247ecce7b98e6286c523e8d690d6f1f9015fddaa56b70a4bf",
55
- ".codex/skills/strategy-candidate-report/SKILL.md": "ec4399494dd545268c74dd5b4d84a3fa6f283801a7f95449ce956a9f22db6713",
56
+ ".codex/skills/strategy-backtest-research/scripts/retire-worktree.py": "5fb920e5d639c58aeef51a104a4dad20824183c566f8f1d049e29394f12a9c68",
57
+ ".codex/skills/strategy-backtest-research/SKILL.md": "7aaccb986c4b6fba4820af683497276d2f517439936011be9d5a2563e8cb8cce",
58
+ ".codex/skills/strategy-candidate-compare/SKILL.md": "0213ffab975f7a19cc204260a9ca587e6f59dbd84f2a4cdac19d84418ebf0792",
59
+ ".codex/skills/strategy-candidate-report/SKILL.md": "2f24b1ac546bd21a0cdcc04cfdce6eeeca25ff89fc42cdd1dc66516b6fe95c11",
56
60
  ".codex/skills/strategy-forward-start/SKILL.md": "a86311aeb4c5b46e43011806ffa0f665c4ec0fddce8d7f8c1232184e4a14bfa7",
57
61
  ".codex/skills/strategy-forward-status/SKILL.md": "7cb021991ff40bb3407eb58e1c9e2bcf597f67b0201059b9e20e4f37fd3320b9",
58
62
  ".codex/skills/strategy-improvement-plan/SKILL.md": "f5f0f390941dd3332890a2f0ffae1248abde4925db2cf49a41c0c0c1b47e7864",
@@ -65,14 +69,14 @@
65
69
  ".codex/skills/strategy-improvement-research/scripts/final-composition-board.test.mjs": "4dae48e797c27a55913639b3c90b66b7c8effe8eb9da3c943d804df301d58aa6",
66
70
  ".codex/skills/strategy-improvement-research/scripts/freeze-gate-variants.mjs": "17b3c868880ddd5b326d309e6e42eaeef1ea22d625a5db947997ac73b221ad6d",
67
71
  ".codex/skills/strategy-improvement-research/scripts/freeze-gate-variants.test.mjs": "963e1c64ab3deef11fd48a96e10f3827af38036dfe2eb28daf7849f19dd414d8",
68
- ".codex/skills/strategy-improvement-research/SKILL.md": "75a0f2420305b269fec0f71f63904b5bf04be00612b015855f0a0f2beface5b7",
69
- ".codex/skills/strategy-period-revalidate/SKILL.md": "f367ba1c632506a7d9bf92662a40b61df55f7a56ad04f3600a475b3c365bbbcb",
72
+ ".codex/skills/strategy-improvement-research/SKILL.md": "841956c4de5f0dbe29c7fe408f27791cb599968f9a86195c962ad18271b464b8",
73
+ ".codex/skills/strategy-period-revalidate/SKILL.md": "b580d09c78c2bf64de26ca25c4394d5e2657e8bc1f8f717391153db894b57ab2",
70
74
  ".codex/skills/strategy-release/agents/openai.yaml": "46ddb09119b08ae3be3b9509121b57492342012e774789b615767b24270dba17",
71
75
  ".codex/skills/strategy-release/references/diagnose-live.md": "dc2effa6eba34e3cfcc1eaf4d2fd1c96d6ccdda971a0edec76c9eed1ec293a3d",
72
76
  ".codex/skills/strategy-release/references/direction-policy.md": "e7635e709dfc7301b94f3dbc1421c6a779c7c39ce4f6066b2eece38e4e600bec",
73
77
  ".codex/skills/strategy-release/references/directional-parameter-split.md": "c303fbd15183b4b8c5662526d5bc762edc0a21a42c45e141d0dc5efdd3b52d8c",
74
78
  ".codex/skills/strategy-release/references/evidence-limitations.md": "523d6541a230b51c2b0b81a6c11c99e3aef69203f22b77e94fda1e3b15321e20",
75
- ".codex/skills/strategy-release/references/evidence-retention.md": "ed39682e5d1cf33b5df0c1fb4896a889e0f53c4dc27ef37efe3d35d2f08a205c",
79
+ ".codex/skills/strategy-release/references/evidence-retention.md": "d0f3c612b0ce13b6b2fd6d4053dc36e0f62c92a2ea2329d22ad7ff85b28c5675",
76
80
  ".codex/skills/strategy-release/references/historical-hypothesis-audit.md": "3c4d579a0c097e974592b855891446060eb70d8bddf8558d765052a92509b516",
77
81
  ".codex/skills/strategy-release/references/professional-research-loop.md": "e440f05dd6b5c803ba20da9f019f745f89477724d46551c53dbb8dab9cffe40f",
78
82
  ".codex/skills/strategy-release/references/release-workflow.md": "a103416334b5605addd856f105462b53602d29ace2816f96162b7e2ecd1a0bb6",
@@ -86,6 +90,8 @@
86
90
  ".codex/skills/strategy-release/scripts/release-progress-checkpoint.test.mjs": "d378b0ab87cd3ee7bbf384ec5f5810565b480b56533ad3c6700edf5938286a38",
87
91
  ".codex/skills/strategy-release/SKILL.md": "590948c2c1ad222c7784b050e0fa0a8fea60efa7b0f23d8d355fd56a3e8a1291",
88
92
  ".codex/skills/strategy-risk-scale/SKILL.md": "2c07846c9da2fd622ea6f5586c42863fc27b35a7d1d00614d5bbe0719da4d39f",
93
+ ".codex/skills/tradejs-docs/agents/openai.yaml": "47e75a2523ba0e4fd3a65d8bd4828dc74b021fa5377b2b04b1aee2130a12d6c3",
94
+ ".codex/skills/tradejs-docs/SKILL.md": "26dec701db7149053afebc086440456601644c904d6f05b180b61aba3e98de89",
89
95
  ".codex/skills/tradejs-mcp/SKILL.md": "a9c5dfde4ccab13e1fa2c3e56f6f3132fb0ed99e492b119a5017588db55b34c4"
90
96
  }
91
97
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tradejs",
3
- "version": "3.1.29-beta.275",
3
+ "version": "3.1.29-beta.277",
4
4
  "description": "Create a ready-to-run TradeJS project with local infrastructure and the Web UI.",
5
5
  "keywords": [
6
6
  "tradejs",