create-tradejs 3.1.29-beta.290 → 3.1.29-beta.292

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 (20) hide show
  1. package/dist/skill-bundle/.codex/skills/ai-train-local-research/SKILL.md +13 -7
  2. package/dist/skill-bundle/.codex/skills/ai-train-local-research/references/gate-ablation.md +68 -0
  3. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs +19 -33
  4. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/equity-stability.mjs +10 -4
  5. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/report-output.mjs +33 -0
  6. package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/report-output.test.mjs +64 -0
  7. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/SKILL.md +3 -2
  8. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-notes.md +25 -6
  9. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-retention.md +46 -1
  10. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs +102 -0
  11. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.test.mjs +69 -0
  12. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs +70 -6
  13. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-notes-check.test.mjs +71 -0
  14. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.py +37 -7
  15. package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py +78 -0
  16. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/SKILL.md +11 -0
  17. package/dist/skill-bundle/.codex/skills/strategy-improvement-research/references/final-composition-board.md +11 -0
  18. package/dist/skill-bundle/.codex/skills/strategy-period-revalidate/SKILL.md +4 -1
  19. package/dist/skill-bundle/.codex/tradejs-skill-bundle.json +19 -13
  20. package/package.json +1 -1
@@ -277,9 +277,10 @@ Mandatory validation sections for gate work:
277
277
  target/benchmark/global, and whether it depends on
278
278
  lookback/window/cache/provider settings.
279
279
  - **Walk-forward validation**: when the export spans enough history, validate
280
- across multiple chronological folds or at least month/quarter buckets. Prefer
281
- pockets that survive changing market regimes over pockets that win only in a
282
- single terminal validation split.
280
+ a recurring refit procedure with the A/B/C protocol in
281
+ [gate-ablation.md](references/gate-ablation.md#compare-refitting-and-ticker-groups).
282
+ Month/quarter buckets of one frozen rule measure stability. Walk-forward
283
+ reselects the rule from earlier mature labels for each evaluation window.
283
284
  - **Acceptance gates**: define minimum validation support, maximum symbol
284
285
  and event concentration, acceptable losing months, max loss streak,
285
286
  PF/drawdown improvement, and cadence/capacity bounds before recommending
@@ -564,7 +565,7 @@ Minimum checks:
564
565
  - classify old pockets as `keep`, `round`, `replace`, `disable`, or
565
566
  `needs-more-data`
566
567
  - include live-env parity and feature provenance tables in the analysis
567
- - run walk-forward or month/quarter stability checks when history allows it
568
+ - apply the validation sections above, including threshold sensitivity
568
569
  - define acceptance gates before treating a pocket as production-ready
569
570
  - use a negative control for unusually strong or highly specific pockets
570
571
  - reject approval rules based on data-count or availability fields such as
@@ -572,7 +573,6 @@ Minimum checks:
572
573
  size; use those only as missing/stale-data guards
573
574
  - reject high-precision pocket thresholds until they have been rounded to a
574
575
  defensible value and replayed again
575
- - run sensitivity checks around each proposed numeric threshold
576
576
  - report train and validation support separately when using `ai-pocket-search`
577
577
  or a custom split, but label any partition used for selection as tuning
578
578
  - group partitions by timestamp and report independent-event support separately
@@ -580,8 +580,8 @@ Minimum checks:
580
580
  - report event clustering and capacity stress for every terminal window
581
581
  - require a target-specific discriminator or portfolio throttle for
582
582
  benchmark/global pockets that can approve many symbols on one timestamp
583
- - include an ablation table: baseline, pocket-only when applicable, and final
584
- gate
583
+ - compare the current gate with the proposed gate. Use the A/B/C protocol
584
+ when the claim concerns the incremental value of ticker groups
585
585
  - require boundary tests and a passive-rollout plan for implemented gate changes
586
586
  - clean up old disabled pockets instead of leaving dead constants or prompt
587
587
  fields behind
@@ -638,6 +638,12 @@ 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
+ When saving a report, use `--output` and read its receipt-bound file instead
642
+ of retaining another JSON copy in a log. New permanent notes use the verified
643
+ v2 snapshot contract in `research-notes.md`; all aggregate fields survive
644
+ lossless encoding. Detailed trade/identity arrays remain temporary until their
645
+ diagnostics and chart consumers finish.
646
+
641
647
  ## Completed study storage
642
648
 
643
649
  Follow
@@ -851,3 +851,71 @@ not gate features or selection predicates. Existing monthly/cohort diagnostics
851
851
  may not supply PF/MaxDD for every common window; report that limitation and use
852
852
  a separately reviewed generic reporting extension if needed. Never derive a
853
853
  new rule from the final cohort tables.
854
+
855
+ ## Report storage
856
+
857
+ With `--output`, the tool writes the complete report once and prints a
858
+ `tradejs-research-report-receipt/v1` JSON receipt with its path, byte count and
859
+ SHA-256. Read that file for downstream metrics. Without `--output`, `--json`
860
+ prints the complete JSON. JSON files use compact serialization without dropping
861
+ metrics, feature audits or the equity needed by ongoing diagnostics.
862
+
863
+ Treat detailed equity/identity arrays as temporary inputs until stability,
864
+ comparisons and final charts finish. For the permanent v2 note, retain all
865
+ aggregate reports and frozen chart points through the verified snapshot encoder
866
+ in `strategy-backtest-research`. Keep shared feature audits once per exact
867
+ export/context fingerprint. Follow the shared retention contract before cleanup.
868
+
869
+ ## Registered features and monthly ticker profiles
870
+
871
+ Read the framework `CONTEXT_FEATURES.md` contract before adding data. New feature
872
+ projections live in strategy/indicator `aiFeatures` definitions and are frozen in
873
+ `AiPayload.featureSnapshot`; native pocket search exposes `registered.<id>`.
874
+ Do not reconstruct untrimmed array reductions from the five-point prompt view.
875
+ Changed definitions require a new decision-time export, not silent replay under
876
+ old lineage. Coverage/provenance/outcome/policy roles are never approval inputs.
877
+ For custom ablation, inspect `payload.featureSnapshot.values` from the frozen
878
+ native payload and preserve its definitions; do not assume a registered discovery
879
+ name is an old baseContext property path. Monthly profiles use explicit
880
+ provider/universe identities, immutable as-of snapshots and unknown coverage.
881
+ They are shared market data and remain outside research-payload cleanup.
882
+
883
+ For backtest exports with profiles, use `--ai` with the profile source. A plain
884
+ `--fast` run without export does not exercise optional profile enrichment. Verify
885
+ `payload.featureSnapshot` in actual rows before claiming feature availability or
886
+ measuring its overhead. Profiles do not manufacture a missing baseContext.
887
+
888
+
889
+ ## Compare refitting and ticker groups
890
+
891
+ Use the same core export and freeze the search budget, eligibility, treatment of
892
+ unknowns and calendar before opening outcomes. A is the current gate. B searches
893
+ with the prior feature list. C repeats B with the declared registered ticker
894
+ groups. Report B–A, C–B and C–A. For a single frozen split, use the existing
895
+ variants report and `--compareTo` for the direct B/C difference.
896
+
897
+ For a recurring refit, use the existing search command from Project:
898
+
899
+ ```sh
900
+ yarn exec tradejs ai-pocket-search --file <export.jsonl> -n 0 \
901
+ --scope all --validationSplit 0 --testSince <outer-test-UTC> --sealTest \
902
+ --objective add-to-gate --walkForwardPlan <plan.json> --output <report.json>
903
+ ```
904
+
905
+ The plan has `folds` with numeric UTC milliseconds `trainStart`, `testStart` and
906
+ `testEnd`, `baselineFeatures` with exact eligible feature paths, `tickerGroups`
907
+ with registered paths such as `registered.ticker.moneyGroup`, and
908
+ `minimumEvents` for timestamp support. Optional `sensitivityFraction` reports
909
+ one-at-a-time changes to nonzero numerical thresholds. This is a diagnostic
910
+ around the selected rule. It does not select a replacement threshold.
911
+
912
+ Test windows are disjoint and entirely inside outer development. Each fold
913
+ uses labels closed strictly before its training cutoff and reports evaluation
914
+ labels closed before the evaluation end. Both searches use the same rows.
915
+ If a search finds no stable pocket, the fold records a fallback to A. If
916
+ support is insufficient, the fold is marked and the aggregate covers only
917
+ evaluated folds. Counts by timestamp measure support, while market-episode
918
+ dependence still needs diagnosis. The report uses decision-time approval-set
919
+ economics. Verify shortlisted frozen rules in native execution where admissions
920
+ change position occupancy. A historical fold previously used to choose rules or
921
+ settings is retrospective evidence.
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import fs from 'node:fs';
4
+ import { writeResearchReport } from './report-output.mjs';
4
5
  import fsp from 'node:fs/promises';
5
6
  import path from 'node:path';
6
7
  import readline from 'node:readline';
@@ -96,7 +97,7 @@ Options:
96
97
  Benchmark/reference row coverage (default: 0.1)
97
98
  --portfolioCapacity <n> Maximum simultaneous approval fan-out (default: 5)
98
99
  --output <path> Write Markdown, or JSON when extension is .json
99
- --json Print JSON instead of Markdown
100
+ --json Print JSON without --output; otherwise print a receipt
100
101
  --list List merged export groups and exit
101
102
  --help Show this help
102
103
  `;
@@ -1595,6 +1596,7 @@ const finalizeFeatureInventory = (inventory) =>
1595
1596
 
1596
1597
  const signalFromRow = (row) => ({
1597
1598
  ...row.payload.signal,
1599
+ aiFeatureReplay: { snapshot: row.payload.featureSnapshot ?? null },
1598
1600
  strategy: row.payload.signal.strategy,
1599
1601
  figures: row.payload.figures ?? {},
1600
1602
  indicators: row.payload.indicators ?? {},
@@ -8038,22 +8040,14 @@ export const main = async () => {
8038
8040
  portfolioCapacity: options.portfolioCapacity,
8039
8041
  });
8040
8042
  const markdown = formatCrossStrategyMarkdown(report);
8041
- const output = options.json
8042
- ? `${JSON.stringify(report, null, 2)}\n`
8043
- : markdown;
8044
- if (options.output) {
8045
- const outputPath = path.resolve(projectRoot, options.output);
8046
- await fsp.mkdir(path.dirname(outputPath), { recursive: true });
8047
- await fsp.writeFile(
8048
- outputPath,
8049
- outputPath.endsWith('.json')
8050
- ? `${JSON.stringify(report, null, 2)}\n`
8051
- : markdown,
8052
- 'utf8',
8053
- );
8054
- console.error(`report: ${path.relative(projectRoot, outputPath)}`);
8055
- }
8056
- process.stdout.write(output);
8043
+ await writeResearchReport({
8044
+ report,
8045
+ markdown,
8046
+ json: options.json,
8047
+ outputPath: options.output
8048
+ ? path.resolve(projectRoot, options.output)
8049
+ : undefined,
8050
+ });
8057
8051
  return;
8058
8052
  }
8059
8053
  let variants = await loadVariants(options.variants, options.spec);
@@ -8181,22 +8175,14 @@ export const main = async () => {
8181
8175
  });
8182
8176
  }
8183
8177
  const markdown = formatMarkdownReport(report);
8184
- const output = options.json
8185
- ? `${JSON.stringify(report, null, 2)}\n`
8186
- : markdown;
8187
- if (options.output) {
8188
- const outputPath = path.resolve(projectRoot, options.output);
8189
- await fsp.mkdir(path.dirname(outputPath), { recursive: true });
8190
- await fsp.writeFile(
8191
- outputPath,
8192
- outputPath.endsWith('.json')
8193
- ? `${JSON.stringify(report, null, 2)}\n`
8194
- : markdown,
8195
- 'utf8',
8196
- );
8197
- console.error(`report: ${path.relative(projectRoot, outputPath)}`);
8198
- }
8199
- process.stdout.write(output);
8178
+ await writeResearchReport({
8179
+ report,
8180
+ markdown,
8181
+ json: options.json,
8182
+ outputPath: options.output
8183
+ ? path.resolve(projectRoot, options.output)
8184
+ : undefined,
8185
+ });
8200
8186
  };
8201
8187
 
8202
8188
  if (isDirectRun()) {
@@ -105,8 +105,14 @@ if (
105
105
  sha256: crypto.createHash('sha256').update(bytes).digest('hex'),
106
106
  },
107
107
  };
108
- fs.writeFileSync(arg('--output'), JSON.stringify(result, null, 2), {
109
- flag: 'wx',
110
- });
111
- console.log(JSON.stringify(result));
108
+ const content = `${JSON.stringify(result)}\n`;
109
+ fs.writeFileSync(arg('--output'), content, { flag: 'wx' });
110
+ console.log(
111
+ JSON.stringify({
112
+ schema: 'tradejs-research-report-receipt/v1',
113
+ path: arg('--output'),
114
+ bytes: Buffer.byteLength(content),
115
+ sha256: crypto.createHash('sha256').update(content).digest('hex'),
116
+ }),
117
+ );
112
118
  }
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+
5
+ // Keep the complete machine-readable result in one place. Explicit stdout-only
6
+ // callers still receive the full report; file-output callers receive a receipt.
7
+ export const writeResearchReport = async ({
8
+ report,
9
+ markdown,
10
+ json = false,
11
+ outputPath,
12
+ stdout = process.stdout,
13
+ }) => {
14
+ if (!outputPath) {
15
+ stdout.write(json ? `${JSON.stringify(report)}\n` : markdown);
16
+ return;
17
+ }
18
+ const resolvedPath = path.resolve(outputPath);
19
+ const content = resolvedPath.endsWith('.json')
20
+ ? `${JSON.stringify(report)}\n`
21
+ : markdown;
22
+ if (typeof content !== 'string') throw new Error('Missing report content');
23
+ await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
24
+ await fs.writeFile(resolvedPath, content, 'utf8');
25
+ const receipt = {
26
+ schema: 'tradejs-research-report-receipt/v1',
27
+ path: resolvedPath,
28
+ bytes: Buffer.byteLength(content),
29
+ sha256: createHash('sha256').update(content).digest('hex'),
30
+ };
31
+ stdout.write(`${JSON.stringify(receipt)}\n`);
32
+ return receipt;
33
+ };
@@ -0,0 +1,64 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { writeResearchReport } from './report-output.mjs';
8
+
9
+ test('file output preserves the full report and logs only a verifiable receipt', async () => {
10
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'report-output-'));
11
+ try {
12
+ const report = {
13
+ candidates: [
14
+ {
15
+ name: 'rejected',
16
+ metrics: { ALL: 0, LONG: null, SHORT: -1 },
17
+ equity: Array.from({ length: 1000 }, (_, i) => [i, i - 5]),
18
+ },
19
+ ],
20
+ };
21
+ for (const extension of ['json', 'md']) {
22
+ const outputPath = path.join(dir, `report.${extension}`);
23
+ let log = '';
24
+ const receipt = await writeResearchReport({
25
+ report,
26
+ markdown: '# Report\n',
27
+ json: true,
28
+ outputPath,
29
+ stdout: {
30
+ write(text) {
31
+ log += text;
32
+ },
33
+ },
34
+ });
35
+ const content = await fs.readFile(outputPath);
36
+ assert.equal(
37
+ receipt.sha256,
38
+ createHash('sha256').update(content).digest('hex'),
39
+ );
40
+ assert.equal(receipt.bytes, content.length);
41
+ assert.deepEqual(JSON.parse(log), receipt);
42
+ assert.ok(log.length < 400);
43
+ if (extension === 'json') assert.deepEqual(JSON.parse(content), report);
44
+ else assert.equal(content.toString(), '# Report\n');
45
+ }
46
+ let log = '';
47
+ await writeResearchReport({
48
+ report,
49
+ json: true,
50
+ stdout: {
51
+ write(text) {
52
+ log += text;
53
+ },
54
+ },
55
+ });
56
+ assert.deepEqual(JSON.parse(log), report);
57
+ await assert.rejects(
58
+ writeResearchReport({ report, outputPath: path.join(dir, 'missing.md') }),
59
+ /Missing report content/,
60
+ );
61
+ } finally {
62
+ await fs.rm(dir, { recursive: true, force: true });
63
+ }
64
+ });
@@ -350,8 +350,9 @@ it exactly.
350
350
  - Put repository-wide work in `notes/Shared/` and genuine multi-strategy
351
351
  comparisons in `notes/CrossStrategy/`; never place files directly in
352
352
  `notes/`.
353
- - Embed the complete secret-free resolved config and the authoritative
354
- structured metrics JSON. Paths to Redis, cached orders, exports, or output
353
+ - Use v2 notes with the verified self-contained compact metric snapshot from
354
+ `references/research-notes.md`. Embed the complete secret-free resolved config
355
+ and preserve every authoritative aggregate metric. Paths to Redis, cached orders, exports, or output
355
356
  reports are not enough because those artifacts may be deleted.
356
357
  - Use `reproduction: complete` only when the note alone preserves every
357
358
  reported aggregate metric and its lineage. Mark missing historical evidence
@@ -49,7 +49,7 @@ Every file starts with:
49
49
 
50
50
  ```yaml
51
51
  ---
52
- schema: tradejs-research/v1
52
+ schema: tradejs-research/v2
53
53
  strategy: '<Strategy|Shared|CrossStrategy>'
54
54
  date: 'YYYY-MM-DD'
55
55
  kind: '<backtest|ai-gate|ml|architecture|runtime-parity>'
@@ -125,10 +125,29 @@ config cannot be recovered, use `reproduction: partial` or `blocked` and write
125
125
 
126
126
  ## Metrics snapshot
127
127
 
128
- Embed the complete structured JSON summary produced by the authoritative tool,
129
- without truncation, in a fenced `json` block. This is the machine-readable
130
- source for the tables and preserves the reported metrics after exports or
131
- caches are deleted.
128
+ For new records use `tradejs-research/v2`. Put every authoritative aggregate
129
+ report in one JSON object, keyed by report ID. Encode it with
130
+ `scripts/metric-snapshot.mjs` and embed the resulting JSON envelope in the
131
+ single fenced `json` block under Metrics snapshot. The envelope contains
132
+ portable gzip/base64 data, its decoded byte count and SHA-256. Decoding recovers
133
+ the complete JSON, including all candidates, periods, ALL/LONG/SHORT cohorts,
134
+ zero/null values, decisions, provenance and frozen chart points. The note remains
135
+ self-contained after exports and other output files are deleted.
136
+
137
+ Run from Project with the installed skill paths:
138
+
139
+ ```bash
140
+ node .codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs encode <aggregates.json> <new-snapshot.json>
141
+ node .codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs decode <note.md> <new-decoded.json>
142
+ ```
143
+
144
+ The decoder also accepts a standalone snapshot JSON file. Keep the readable tables outside the encoded block. The checker verifies the
145
+ snapshot checksum and size and rejects temporary trade/matched-pair payloads.
146
+ An 8 MiB note budget prevents accidental large dumps. Store exact source and
147
+ patches in permanent source archives instead of repeating them in Markdown.
148
+ Never truncate metrics to meet that budget. Existing v1 notes remain immutable
149
+ and continue to validate; do not relabel them as v2 without a new verified
150
+ record.
132
151
 
133
152
  - AI-gate baseline: use the full output of
134
153
  `yarn ai-train --localOnly --json -n 0` for the selected merge group.
@@ -140,7 +159,7 @@ caches are deleted.
140
159
  terminal windows. Add raw sweep/result summaries when the decision depends
141
160
  on them.
142
161
 
143
- The snapshot must contain the numbers needed to rebuild every human-readable
162
+ The decoded snapshot must contain the numbers needed to rebuild every human-readable
144
163
  table in the note. Do not paste the deleted row-level export into Markdown. A
145
164
  complete note preserves reported aggregate metrics and their provenance; it
146
165
  does not claim to recreate arbitrary new row-level analyses after source data
@@ -36,6 +36,45 @@ should reuse or reject it. Future research reads these records before choosing
36
36
  new hypotheses. Compare saved results directly only on matching scopes and
37
37
  risk units. Changed periods or assumptions require a new frozen evaluation.
38
38
 
39
+ ## Compact output for new studies
40
+
41
+ Use the v2 note contract in [research-notes.md](research-notes.md). Write
42
+ machine-readable aggregate JSON without indentation. Keep every candidate,
43
+ period, direction, test result and decision. Lossless snapshot encoding reduces
44
+ repeated field names without dropping scientific evidence.
45
+
46
+ Write a full tool report once. When `--output` is supplied, `ai-train` and the
47
+ ablation tool print a small receipt with the output path, bytes and SHA-256.
48
+ Read the file for metrics. Without `--output`, `--json` still returns the full
49
+ report. Logs should retain the exact command/run identity, progress, exit status,
50
+ warnings and errors. Do not tee the same full JSON into another permanent log.
51
+ Keep repeated diagnostics as counts with bounded examples.
52
+
53
+ `research:core` result schema v2 keeps comparison aggregates and exit-change
54
+ counts. Detailed pairs live only in temporary `matches.csv`; normalized trades
55
+ remain in temporary `trades.jsonl` until every consumer finishes. The permanent
56
+ result and comparison files contain no `matchedPairs` arrays.
57
+
58
+ Keep shared feature-availability summaries once per exact dataset/context
59
+ fingerprint and refer to them from candidate reports. Do not store exhaustive
60
+ `allProjectedLeaves` arrays in permanent notes. Preserve the authoritative
61
+ aggregate JSON, the exact projection generator, input/output hashes and leaf
62
+ counts so the mapping can be regenerated. Verify the regenerated mapping before
63
+ removing an existing temporary mapping. Do not replace aggregate metric values
64
+ with hashes or pointers to disposable files.
65
+
66
+ Generate synthetic test outputs and external-sort runs under disposable output,
67
+ not inside archived report-tool source. Preserve authored fixtures, their
68
+ generators and the complete test verdict. Archive code before tests or exclude
69
+ untracked generated `synthetic-fixtures`, dependencies, builds and caches.
70
+ Tracked source is retained even if its directory has one of those names.
71
+
72
+ Archive Git history in a permanent shared directory. The worktree retirement
73
+ helper reuses one verified full bundle per HEAD and writes `history-reference.json`
74
+ in each source archive. Keep the referenced bundle with every backup/export of
75
+ that archive. Use a common `--history-root` across retirement batches. Different
76
+ HEADs retain distinct bundles; do not infer identical history from file size.
77
+
39
78
  ## Cleanup
40
79
 
41
80
  The research owner performs cleanup as the final step of the study, without a
@@ -141,7 +180,7 @@ and untracked source before removal. Do not delete branches, canonical checkouts
141
180
  locked or managed checkouts belonging to active chats, or ongoing studies.
142
181
 
143
182
  Inspect the owning repository's `git worktree list` and checkout status.
144
- The helper preserves a Git history bundle, source snapshot and staged/unstaged
183
+ The helper preserves a shared Git history reference, source snapshot and staged/unstaged
145
184
  patches, verifies their contents, and refuses worktrees with open files:
146
185
 
147
186
  ```bash
@@ -155,3 +194,9 @@ receipt permanently. Prune stale registrations only after checking that their
155
194
  directories are actually absent, and preserve their branch/commit identities
156
195
  in the cleanup inventory. For Codex-managed worktrees attached to this chat,
157
196
  prefer the app's archive tool, which preserves recoverable state.
197
+
198
+ Shared history bundles must be self-contained: verify and fetch them into an
199
+ empty isolated repository and run object integrity checks before retiring the
200
+ worktree. Verification against the source repository alone accepts incremental
201
+ bundles whose prerequisites happen to exist locally. Reject such a bundle,
202
+ retain the worktree, and do not issue a completed retirement receipt.
@@ -0,0 +1,102 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { gzipSync, gunzipSync } from 'node:zlib';
3
+ import fs from 'node:fs/promises';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ const SCHEMA = 'tradejs-metric-snapshot/v1';
7
+ const MAX_BYTES = 256 * 1024 * 1024;
8
+ const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
+
10
+ export const validatePermanentMetrics = (value) => {
11
+ if (!value || typeof value !== 'object') return;
12
+ for (const [key, child] of Object.entries(value)) {
13
+ if (
14
+ ['matchedPairs', 'tradeRows', 'allProjectedLeaves'].includes(key) &&
15
+ Array.isArray(child) &&
16
+ child.length
17
+ ) {
18
+ throw new Error(`Temporary payload ${key} is not a permanent metric`);
19
+ }
20
+ if (
21
+ key === 'trades' &&
22
+ Array.isArray(child) &&
23
+ child.some(
24
+ (row) =>
25
+ row &&
26
+ typeof row === 'object' &&
27
+ ('signalId' in row || 'entryTimestamp' in row),
28
+ )
29
+ ) {
30
+ throw new Error('Temporary trade records are not permanent metrics');
31
+ }
32
+ validatePermanentMetrics(child);
33
+ }
34
+ };
35
+
36
+ export const encodeMetricSnapshot = (metrics) => {
37
+ validatePermanentMetrics(metrics);
38
+ const bytes = Buffer.from(JSON.stringify(metrics));
39
+ if (bytes.length > MAX_BYTES)
40
+ throw new Error('Metric snapshot exceeds decoded size limit');
41
+ return {
42
+ schema: SCHEMA,
43
+ encoding: 'gzip+base64',
44
+ decodedBytes: bytes.length,
45
+ sha256: sha256(bytes),
46
+ payload: gzipSync(bytes, { level: 9 }).toString('base64'),
47
+ };
48
+ };
49
+
50
+ export const decodeMetricSnapshot = (snapshot) => {
51
+ if (
52
+ snapshot?.schema !== SCHEMA ||
53
+ snapshot.encoding !== 'gzip+base64' ||
54
+ !Number.isSafeInteger(snapshot.decodedBytes) ||
55
+ snapshot.decodedBytes <= 0 ||
56
+ snapshot.decodedBytes > MAX_BYTES ||
57
+ typeof snapshot.payload !== 'string' ||
58
+ !/^[a-f0-9]{64}$/.test(snapshot.sha256)
59
+ ) {
60
+ throw new Error('Invalid metric snapshot envelope');
61
+ }
62
+ const bytes = gunzipSync(Buffer.from(snapshot.payload, 'base64'), {
63
+ maxOutputLength: snapshot.decodedBytes,
64
+ });
65
+ if (
66
+ bytes.length !== snapshot.decodedBytes ||
67
+ sha256(bytes) !== snapshot.sha256
68
+ )
69
+ throw new Error('Metric snapshot checksum or size mismatch');
70
+ const metrics = JSON.parse(bytes.toString('utf8'));
71
+ validatePermanentMetrics(metrics);
72
+ return metrics;
73
+ };
74
+
75
+ if (
76
+ process.argv[1] &&
77
+ import.meta.url === pathToFileURL(process.argv[1]).href
78
+ ) {
79
+ const [mode, input, output] = process.argv.slice(2);
80
+ if (!['encode', 'decode'].includes(mode) || !input || !output)
81
+ throw new Error('Use encode|decode <input.json> <new-output.json>');
82
+ const content = await fs.readFile(input, 'utf8');
83
+ const section =
84
+ mode === 'decode' && input.endsWith('.md')
85
+ ? content
86
+ .split('## Metrics snapshot (machine-readable)')[1]
87
+ ?.split('## Reported metrics')[0]
88
+ : undefined;
89
+ const blocks =
90
+ section == null
91
+ ? []
92
+ : [...section.matchAll(/```json\r?\n([\s\S]*?)\r?\n```/g)];
93
+ if (mode === 'decode' && input.endsWith('.md') && blocks.length !== 1)
94
+ throw new Error('Note needs one compact metric snapshot');
95
+ const value = JSON.parse(blocks[0]?.[1] ?? content);
96
+ const result =
97
+ mode === 'encode'
98
+ ? encodeMetricSnapshot(value)
99
+ : decodeMetricSnapshot(value);
100
+ await fs.writeFile(output, `${JSON.stringify(result)}\n`, { flag: 'wx' });
101
+ console.log(JSON.stringify({ output, schema: result?.schema ?? null }));
102
+ }
@@ -0,0 +1,69 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {
4
+ encodeMetricSnapshot,
5
+ decodeMetricSnapshot,
6
+ } from './metric-snapshot.mjs';
7
+
8
+ test('compact snapshot preserves all candidates, zero/null metrics, config and chart data independently of external files', () => {
9
+ const metrics = {
10
+ config: { enabled: false },
11
+ candidates: Array.from({ length: 1000 }, (_, i) => ({
12
+ id: i,
13
+ verdict: 'rejected',
14
+ periods: {
15
+ full: {
16
+ ALL: { trades: 0, pnl: 0, pf: null },
17
+ LONG: { pnl: -5 },
18
+ SHORT: { pnl: 3 },
19
+ },
20
+ },
21
+ chart: [
22
+ [0, 0],
23
+ [1, -2],
24
+ ],
25
+ })),
26
+ };
27
+ const encoded = encodeMetricSnapshot(metrics);
28
+ assert.deepEqual(
29
+ decodeMetricSnapshot(JSON.parse(JSON.stringify(encoded))),
30
+ metrics,
31
+ );
32
+ assert.ok(
33
+ JSON.stringify(encoded).length < JSON.stringify(metrics).length / 5,
34
+ );
35
+ assert.deepEqual(encodeMetricSnapshot(metrics), encoded);
36
+ assert.throws(
37
+ () => decodeMetricSnapshot({ ...encoded, sha256: '0'.repeat(64) }),
38
+ /checksum/,
39
+ );
40
+ assert.throws(
41
+ () => decodeMetricSnapshot({ ...encoded, decodedBytes: 1024 ** 3 }),
42
+ /Invalid/,
43
+ );
44
+ assert.throws(
45
+ () =>
46
+ decodeMetricSnapshot({
47
+ ...encoded,
48
+ decodedBytes: encoded.decodedBytes + 1,
49
+ }),
50
+ /size mismatch/,
51
+ );
52
+ });
53
+
54
+ test('temporary payloads cannot be hidden in a compressed permanent snapshot', () => {
55
+ for (const key of ['matchedPairs', 'tradeRows', 'allProjectedLeaves']) {
56
+ assert.throws(
57
+ () => encodeMetricSnapshot({ nested: { [key]: [{}] } }),
58
+ /Temporary payload/,
59
+ );
60
+ }
61
+ assert.throws(
62
+ () => encodeMetricSnapshot({ trades: [{ signalId: 's' }] }),
63
+ /Temporary trade/,
64
+ );
65
+ assert.deepEqual(
66
+ decodeMetricSnapshot(encodeMetricSnapshot({ trades: 0, matchedPairs: [] })),
67
+ { trades: 0, matchedPairs: [] },
68
+ );
69
+ });
@@ -2,6 +2,10 @@
2
2
 
3
3
  import fs from 'node:fs/promises';
4
4
  import path from 'node:path';
5
+ import {
6
+ decodeMetricSnapshot,
7
+ validatePermanentMetrics,
8
+ } from './metric-snapshot.mjs';
5
9
 
6
10
  const projectRoot = path.resolve(
7
11
  String(process.env.PROJECT_CWD || process.cwd()),
@@ -41,7 +45,11 @@ const parseFrontmatter = (content) => {
41
45
  const value = entry[2].trim();
42
46
  return [
43
47
  entry[1],
44
- value.startsWith('"') ? JSON.parse(value) : value,
48
+ value.startsWith('"')
49
+ ? JSON.parse(value)
50
+ : value.startsWith("'") && value.endsWith("'")
51
+ ? value.slice(1, -1).replaceAll("''", "'")
52
+ : value,
45
53
  ];
46
54
  }),
47
55
  );
@@ -49,11 +57,18 @@ const parseFrontmatter = (content) => {
49
57
 
50
58
  const errors = [];
51
59
  let records = 0;
52
- const rootEntries = await fs.readdir(notesRoot, { withFileTypes: true });
60
+ const rootEntries = await fs
61
+ .readdir(notesRoot, { withFileTypes: true })
62
+ .catch((error) => {
63
+ if (error.code === 'ENOENT') return [];
64
+ throw error;
65
+ });
53
66
 
54
67
  for (const entry of rootEntries) {
55
68
  if (!entry.isDirectory()) {
56
- errors.push(`notes/${entry.name}: files are not allowed directly in notes/`);
69
+ errors.push(
70
+ `notes/${entry.name}: files are not allowed directly in notes/`,
71
+ );
57
72
  continue;
58
73
  }
59
74
 
@@ -71,7 +86,10 @@ for (const entry of rootEntries) {
71
86
  errors.push(`${relativePath}: expected YYYY-MM-DD-<kebab-slug>.md`);
72
87
  }
73
88
 
74
- const content = await fs.readFile(path.join(directoryPath, noteEntry.name), 'utf8');
89
+ const content = await fs.readFile(
90
+ path.join(directoryPath, noteEntry.name),
91
+ 'utf8',
92
+ );
75
93
  const frontmatter = parseFrontmatter(content);
76
94
  if (!frontmatter) {
77
95
  errors.push(`${relativePath}: missing YAML frontmatter`);
@@ -81,7 +99,11 @@ for (const entry of rootEntries) {
81
99
  for (const key of requiredFrontmatter) {
82
100
  if (!frontmatter[key]) errors.push(`${relativePath}: missing ${key}`);
83
101
  }
84
- if (frontmatter.schema !== 'tradejs-research/v1') {
102
+ if (
103
+ !['tradejs-research/v1', 'tradejs-research/v2'].includes(
104
+ frontmatter.schema,
105
+ )
106
+ ) {
85
107
  errors.push(`${relativePath}: unsupported schema ${frontmatter.schema}`);
86
108
  }
87
109
  if (frontmatter.strategy !== entry.name) {
@@ -93,6 +115,13 @@ for (const entry of rootEntries) {
93
115
  errors.push(`${relativePath}: date must match the filename`);
94
116
  }
95
117
 
118
+ // Preserve the existing Project contract for historical incomplete records.
119
+ if (
120
+ frontmatter.schema === 'tradejs-research/v1' &&
121
+ frontmatter.reproduction !== 'complete'
122
+ )
123
+ continue;
124
+
96
125
  let previousIndex = -1;
97
126
  for (const section of completeSections) {
98
127
  const sectionIndex = content.indexOf(section);
@@ -104,6 +133,25 @@ for (const entry of rootEntries) {
104
133
  previousIndex = Math.max(previousIndex, sectionIndex);
105
134
  }
106
135
 
136
+ if (frontmatter.schema === 'tradejs-research/v2') {
137
+ if (Buffer.byteLength(content) > 8 * 1024 * 1024)
138
+ errors.push(
139
+ `${relativePath}: compact note exceeds 8 MiB; archive source separately, never truncate metrics`,
140
+ );
141
+ for (const block of content.matchAll(/```json\r?\n([\s\S]*?)\r?\n```/g)) {
142
+ try {
143
+ const value = JSON.parse(block[1]);
144
+ if (value?.schema === 'tradejs-metric-snapshot/v1')
145
+ decodeMetricSnapshot(value);
146
+ else validatePermanentMetrics(value);
147
+ } catch (error) {
148
+ errors.push(
149
+ `${relativePath}: invalid compact JSON: ${error.message}`,
150
+ );
151
+ }
152
+ }
153
+ }
154
+
107
155
  if (frontmatter.reproduction === 'complete') {
108
156
  const snapshotStart = content.indexOf(
109
157
  '## Metrics snapshot (machine-readable)',
@@ -111,7 +159,23 @@ for (const entry of rootEntries) {
111
159
  const reportedStart = content.indexOf('## Reported metrics');
112
160
  const snapshot = content.slice(snapshotStart, reportedStart);
113
161
  if (!/```json\n[\s\S]+?\n```/.test(snapshot)) {
114
- errors.push(`${relativePath}: complete record needs a JSON metric snapshot`);
162
+ errors.push(
163
+ `${relativePath}: complete record needs a JSON metric snapshot`,
164
+ );
165
+ }
166
+ if (frontmatter.schema === 'tradejs-research/v2') {
167
+ const blocks = [
168
+ ...snapshot.matchAll(/```json\r?\n([\s\S]*?)\r?\n```/g),
169
+ ];
170
+ try {
171
+ if (blocks.length !== 1)
172
+ throw new Error('use one snapshot containing all reports');
173
+ decodeMetricSnapshot(JSON.parse(blocks[0][1]));
174
+ } catch (error) {
175
+ errors.push(
176
+ `${relativePath}: complete v2 record needs one verified compact metric snapshot: ${error.message}`,
177
+ );
178
+ }
115
179
  }
116
180
  }
117
181
  }
@@ -0,0 +1,71 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { spawnSync } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { encodeMetricSnapshot } from './metric-snapshot.mjs';
9
+
10
+ test('note validation accepts old records and verifies new standalone snapshots', async () => {
11
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'compact-note-'));
12
+ const filename = path.join(dir, 'notes', 'Shared', '2026-11-06-storage.md');
13
+ const sections = [
14
+ 'Research question',
15
+ 'Decision',
16
+ 'Reproduction manifest',
17
+ 'Resolved configuration',
18
+ 'Metrics snapshot (machine-readable)',
19
+ 'Reported metrics',
20
+ 'Findings',
21
+ 'Artifact inventory',
22
+ 'Limitations and next step',
23
+ ];
24
+ const note = (schema, snapshot) =>
25
+ `---\nschema: ${schema}\nstrategy: 'Shared'\ndate: '2026-11-06'\nkind: architecture\nstatus: implemented\nreproduction: complete\n---\n` +
26
+ sections
27
+ .map(
28
+ (s) =>
29
+ `## ${s}\n\n${s === sections[4] ? '```json\n' + JSON.stringify(snapshot) + '\n```\n' : 'Recorded.\n'}`,
30
+ )
31
+ .join('\n');
32
+ const check = () =>
33
+ spawnSync(
34
+ process.execPath,
35
+ [fileURLToPath(new URL('./research-notes-check.mjs', import.meta.url))],
36
+ { env: { ...process.env, PROJECT_CWD: dir }, encoding: 'utf8' },
37
+ );
38
+ try {
39
+ await fs.mkdir(path.dirname(filename), { recursive: true });
40
+ await fs.writeFile(
41
+ filename,
42
+ note('tradejs-research/v1', { matchedPairs: [{}] }),
43
+ );
44
+ assert.equal(check().status, 0);
45
+ await fs.writeFile(
46
+ filename,
47
+ '---\nschema: tradejs-research/v1\nstrategy: Shared\ndate: 2026-11-06\nkind: architecture\nstatus: historical\nreproduction: legacy-partial\n---\nOriginal historical body.\n',
48
+ );
49
+ assert.equal(check().status, 0);
50
+ const snapshot = encodeMetricSnapshot({
51
+ ALL: { trades: 0 },
52
+ LONG: {},
53
+ SHORT: {},
54
+ });
55
+ await fs.writeFile(filename, note('tradejs-research/v2', snapshot));
56
+ assert.equal(check().status, 0);
57
+ await fs.writeFile(
58
+ filename,
59
+ note('tradejs-research/v2', { ...snapshot, sha256: '0'.repeat(64) }),
60
+ );
61
+ assert.match(check().stderr, /checksum/);
62
+ await fs.writeFile(
63
+ filename,
64
+ note('tradejs-research/v2', { matchedPairs: [{}] }),
65
+ );
66
+ assert.match(check().stderr, /Temporary payload/);
67
+ assert.notEqual(check().status, 0);
68
+ } finally {
69
+ await fs.rm(dir, { recursive: true, force: true });
70
+ }
71
+ });
@@ -8,6 +8,7 @@ from pathlib import Path
8
8
  import subprocess
9
9
  import tarfile
10
10
  import shutil
11
+ import tempfile
11
12
 
12
13
 
13
14
  def git(root, *args):
@@ -22,7 +23,7 @@ def sha_file(file):
22
23
  return result.hexdigest()
23
24
 
24
25
 
25
- def retire(repository, worktree, out, apply=False):
26
+ def retire(repository, worktree, out, apply=False, history_root=None):
26
27
  repository, worktree, out = map(lambda p: Path(p).resolve(), (repository, worktree, out))
27
28
  records = git(repository, 'worktree', 'list', '--porcelain').decode().strip().split('\n\n')
28
29
  paths = [r.splitlines()[0].split(' ', 1)[1] for r in records]
@@ -36,12 +37,17 @@ def retire(repository, worktree, out, apply=False):
36
37
  if worktree == out or worktree in out.parents:
37
38
  raise ValueError('Archive must be outside the removed worktree')
38
39
  head = git(worktree, 'rev-parse', 'HEAD').decode().strip()
40
+ history_root = Path(history_root).resolve() if history_root else out.parent / 'shared-history'
41
+ if history_root == worktree or worktree in history_root.parents:
42
+ raise ValueError('Shared history must be outside the removed worktree')
43
+ history = history_root / f'{head}.bundle'
39
44
  status = git(worktree, 'status', '--porcelain=v1', '-z')
40
45
  patch = git(worktree, 'diff', 'HEAD', '--binary')
41
46
  staged = git(worktree, 'diff', '--cached', '--binary')
47
+ tracked = set(git(worktree, 'ls-files', '-z', '--cached').split(b'\0'))
42
48
  files = set(git(worktree, 'ls-files', '-z', '--cached', '--others', '--exclude-standard').split(b'\0'))
43
49
  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__'}
50
+ generated = {'node_modules', 'dist', 'build', '.yarn', '.turbo', '.next', 'coverage', '__pycache__', 'synthetic-fixtures'}
45
51
  selected = []
46
52
  for raw in sorted(files):
47
53
  if not raw:
@@ -50,7 +56,7 @@ def retire(repository, worktree, out, apply=False):
50
56
  relative = Path(name)
51
57
  if relative.is_absolute() or '..' in relative.parts:
52
58
  raise ValueError('Invalid source path')
53
- if any(part in generated for part in relative.parts):
59
+ if raw not in tracked and any(part in generated for part in relative.parts):
54
60
  continue
55
61
  if (relative.name == '.env' or relative.name.startswith('.env.') and relative.suffix not in {'.example', '.sample', '.template'}):
56
62
  raise ValueError('Preserve local credentials separately before removing this worktree')
@@ -58,7 +64,8 @@ def retire(repository, worktree, out, apply=False):
58
64
  if file.is_symlink() or file.is_file():
59
65
  selected.append((name, None if file.is_symlink() else sha_file(file)))
60
66
  plan = {'worktree': str(worktree), 'repository': str(repository), 'head': head,
61
- 'registration': record, 'sourceFiles': len(selected), 'dirty': bool(status), 'archive': str(out)}
67
+ 'registration': record, 'sourceFiles': len(selected), 'dirty': bool(status), 'archive': str(out),
68
+ 'sharedHistoryBundle': str(history), 'reuseHistoryBundle': history.exists()}
62
69
  if not apply:
63
70
  return {**plan, 'status': 'planned'}
64
71
  # A cwd or any open source file means this checkout is still in use.
@@ -66,8 +73,30 @@ def retire(repository, worktree, out, apply=False):
66
73
  if opened.returncode != 1:
67
74
  raise ValueError('Worktree has open files or cannot be inspected: ' + opened.stdout.decode()[:500])
68
75
  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'))
76
+ history_root.mkdir(parents=True, exist_ok=True)
77
+ if history.is_symlink():
78
+ raise ValueError('Shared history must be a regular file')
79
+ if not history.exists():
80
+ handle, temporary = tempfile.mkstemp(prefix='history-', suffix='.bundle', dir=history_root)
81
+ os.close(handle)
82
+ try:
83
+ git(worktree, 'bundle', 'create', temporary, 'HEAD')
84
+ try:
85
+ os.link(temporary, history)
86
+ except FileExistsError:
87
+ pass
88
+ finally:
89
+ os.unlink(temporary)
90
+ # Verify without objects from the source repository: incremental bundles are not backups.
91
+ with tempfile.TemporaryDirectory(prefix='verify-history-') as verification:
92
+ git(verification, 'init', '--bare', '-q')
93
+ git(verification, 'bundle', 'verify', str(history))
94
+ git(verification, 'fetch', '--quiet', str(history), 'HEAD')
95
+ git(verification, 'fsck', '--full', '--strict')
96
+ if git(repository, 'bundle', 'list-heads', str(history), 'HEAD').decode().strip() != f'{head} HEAD':
97
+ raise ValueError('Shared history HEAD does not match archived worktree')
98
+ history_reference = {'path': os.path.relpath(history, out), 'sha256': sha_file(history), 'head': head}
99
+ (out / 'history-reference.json').write_text(json.dumps(history_reference) + '\n')
71
100
  (out / 'working-tree.patch').write_bytes(patch)
72
101
  (out / 'staged.patch').write_bytes(staged)
73
102
  (out / 'status.porcelain').write_bytes(status)
@@ -112,5 +141,6 @@ if __name__ == '__main__':
112
141
  parser.add_argument('--worktree', required=True)
113
142
  parser.add_argument('--out', required=True)
114
143
  parser.add_argument('--apply', action='store_true')
144
+ parser.add_argument('--history-root', help='Permanent shared Git-bundle directory; defaults to <out-parent>/shared-history')
115
145
  args = parser.parse_args()
116
- print(json.dumps(retire(args.repository, args.worktree, args.out, args.apply), indent=2))
146
+ print(json.dumps(retire(args.repository, args.worktree, args.out, args.apply, args.history_root), indent=2))
@@ -0,0 +1,78 @@
1
+ import importlib.util
2
+ from pathlib import Path
3
+ import subprocess
4
+ import tarfile
5
+ import tempfile
6
+ import json
7
+ import unittest
8
+
9
+ spec = importlib.util.spec_from_file_location('retire_worktree', Path(__file__).with_name('retire-worktree.py'))
10
+ module = importlib.util.module_from_spec(spec)
11
+ spec.loader.exec_module(module)
12
+
13
+
14
+ class ArchiveTest(unittest.TestCase):
15
+ def test_incremental_bundle_cannot_authorize_removal(self):
16
+ with tempfile.TemporaryDirectory(prefix='research-incremental-') as temporary:
17
+ root = Path(temporary).resolve()
18
+ repo = root / 'repo'
19
+ repo.mkdir()
20
+ module.git(repo, 'init', '-q')
21
+ (repo / 'source').write_text('first')
22
+ module.git(repo, 'add', '.')
23
+ module.git(repo, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'first')
24
+ (repo / 'source').write_text('second')
25
+ module.git(repo, 'add', '.')
26
+ module.git(repo, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'second')
27
+ head = module.git(repo, 'rev-parse', 'HEAD').decode().strip()
28
+ history = root / 'history'
29
+ history.mkdir()
30
+ module.git(repo, 'bundle', 'create', str(history / f'{head}.bundle'), 'HEAD^..HEAD')
31
+ # This succeeds in the source repo, which already has the prerequisite.
32
+ module.git(repo, 'bundle', 'verify', str(history / f'{head}.bundle'))
33
+ worktree = root / 'worktree'
34
+ module.git(repo, 'worktree', 'add', '--detach', str(worktree), 'HEAD')
35
+ with self.assertRaises(subprocess.CalledProcessError):
36
+ module.retire(repo, worktree, root / 'archive', apply=True, history_root=history)
37
+ self.assertTrue(worktree.exists())
38
+ self.assertFalse((root / 'archive/receipt.json').exists())
39
+
40
+ def test_shared_history_and_source_recovery(self):
41
+ with tempfile.TemporaryDirectory(prefix='research-archive-') as temporary:
42
+ root = Path(temporary).resolve()
43
+ repo = root / 'repo'
44
+ repo.mkdir()
45
+ module.git(repo, 'init', '-q')
46
+ (repo / '.gitignore').write_text('synthetic-fixtures/\n')
47
+ (repo / 'synthetic-fixtures').mkdir()
48
+ (repo / 'synthetic-fixtures/authored.json').write_text('{"source":true}')
49
+ module.git(repo, 'add', '.gitignore')
50
+ module.git(repo, 'add', '-f', 'synthetic-fixtures/authored.json')
51
+ module.git(repo, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture')
52
+ receipts = []
53
+ for number in range(2):
54
+ worktree = root / f'worktree-{number}'
55
+ module.git(repo, 'worktree', 'add', '--detach', str(worktree), 'HEAD')
56
+ (worktree / 'synthetic-fixtures/generated.json').write_text('[]')
57
+ (worktree / 'candidate.py').write_text('exact_untracked_source = True\n')
58
+ out = root / 'archives' / str(number)
59
+ receipt = module.retire(repo, worktree, out, apply=True)
60
+ self.assertEqual(receipt['status'], 'removed')
61
+ self.assertFalse(worktree.exists())
62
+ with tarfile.open(out / 'source.tar.gz') as archive:
63
+ self.assertIn('synthetic-fixtures/authored.json', archive.getnames())
64
+ self.assertNotIn('synthetic-fixtures/generated.json', archive.getnames())
65
+ self.assertEqual(archive.extractfile('candidate.py').read(), b'exact_untracked_source = True\n')
66
+ reference = json.loads((out / 'history-reference.json').read_text())
67
+ history = (out / reference['path']).resolve()
68
+ self.assertEqual(module.sha_file(history), reference['sha256'])
69
+ receipts.append(history)
70
+ self.assertEqual(receipts[0], receipts[1])
71
+ self.assertEqual(len(list((root / 'archives/shared-history').glob('*.bundle'))), 1)
72
+ restored = root / 'restored'
73
+ subprocess.run(['git', 'clone', '-q', str(receipts[0]), str(restored)], check=True)
74
+ self.assertEqual((restored / 'synthetic-fixtures/authored.json').read_text(), '{"source":true}')
75
+
76
+
77
+ if __name__ == '__main__':
78
+ unittest.main()
@@ -63,6 +63,17 @@ Before preregistration, read
63
63
  It defines candidate-specific gate isolation, common partitions, the final
64
64
  composition ledger, and the mandatory visual artifacts.
65
65
 
66
+ ## Support before outcomes
67
+
68
+ Before evaluating PnL, record the mechanism, event identity, minimum useful
69
+ effect and available support by calendar block, symbol and market episode.
70
+ Compare two rules on the same setup when possible. For different events,
71
+ declare causal comparability fields and inspect overlap before seeing outcomes.
72
+ Exact ticker/week pairing is optional when it leaves too little support.
73
+ For existing outcome-blind traces, use the optional `research:core prepare`
74
+ support check in `CORE_RESEARCH.md`. Distinguish missing evidence, insufficient
75
+ support, mechanism failure and economic rejection.
76
+
66
77
  ## Required contour
67
78
 
68
79
  1. Start a new immutable research lineage. Freeze data bounds, point-in-time
@@ -176,6 +176,17 @@ ranking or charting. Use the same half-open comparison window and terminal
176
176
  zero-trade windows. A gate without sufficient untouched support remains visible
177
177
  as `research-only` or `blocked`; the chart is not evidence of readiness.
178
178
 
179
+ ## Portfolio contribution
180
+
181
+ For a finalist intended for a shared portfolio, compare the incumbent portfolio
182
+ with the same ordered composition replacing one strategy. Use identical
183
+ cached inputs, risk and policies. Run both as one shared replay batch and pass
184
+ the incumbent portfolio JSON to the candidate replay with
185
+ `--portfolioCompareTo`. Compare realized PnL, drawdown, recovery and contributions
186
+ from unchanged strategies. Read marked drawdown and confirmed displacement
187
+ from the shared replay diagnostics. A change in trade count alone is not
188
+ evidence of capacity displacement.
189
+
179
190
  ## Mandatory visual artifacts
180
191
 
181
192
  Create the board from authoritative structured reports with:
@@ -26,7 +26,10 @@ cannot be reproduced.
26
26
  ## Run
27
27
 
28
28
  1. Freeze the new common end time, maximum common start, point-in-time universe,
29
- costs, execution assumptions, and candidate identities before evaluation.
29
+ costs, execution assumptions, candidate identities and acceptance rules before
30
+ evaluation. Record previously inspected calendar windows and mark them
31
+ retrospective. For later observation, bind runtime scorecards and execution
32
+ calibration to the exact frozen composition and candidate lineage.
30
33
  2. Use existing cached history first. If the requested new tail is absent,
31
34
  fetch only that missing tail through the supported TradeJS data path, then
32
35
  fingerprint the resulting coverage; never silently rewrite old history.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": "tradejs-skill-bundle/v1",
3
3
  "source": "TradeJS-Dev/TradeJS:.codex/skills",
4
- "bundleSha256": "862253ef7dd16a4bf699a93c7d86b279c33223e071f81f79a48d221268712c80",
4
+ "bundleSha256": "2134821363848dd2ad0ac24a892c8a45a77250eaecdf275b9dca49f56ea0b192",
5
5
  "skills": [
6
6
  "ai-train-local-research",
7
7
  "backtest-config-redis",
@@ -22,46 +22,52 @@
22
22
  "strategy-release"
23
23
  ],
24
24
  "files": {
25
- ".codex/skills/ai-train-local-research/references/gate-ablation.md": "0de5ad8476df2659e5c0d5a0cb9c053d3d7f424b229253bde683a7c562a2e78f",
25
+ ".codex/skills/ai-train-local-research/references/gate-ablation.md": "546fee090bf1e326c20a6477c8b775cc3acf71c15c9f32ebb235fc56b24a1193",
26
26
  ".codex/skills/ai-train-local-research/references/pocket-feature-exclusion.md": "c7af65fcfcd404d5324f0222678126d5e166fb77c4c27afea96369ef427f4bb0",
27
27
  ".codex/skills/ai-train-local-research/references/reporting.md": "ae0faaab3b3dd0f4bd27142fa2c9aa889c5e7572a10e9fe1ee79ff57ebbd8653",
28
- ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs": "73d7592eb3c5f52e9739e160348b1419d642ef34044694822c5a6b6e2e26b32e",
28
+ ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs": "83b8791122a391f9cefa2f4331af23a0f30a83638178b2f282de9d5db802467f",
29
29
  ".codex/skills/ai-train-local-research/scripts/ai-gate-ablation.test.mjs": "3d37e2ab217991aa083a60e77369a9f1c9afe8c5d0f99b3ea964f59be2c143f3",
30
30
  ".codex/skills/ai-train-local-research/scripts/decision-capture-join.mjs": "be10d5bec64bf102d16aa8097eb8e32701e46cbe4328a99093ab7fb256b4f815",
31
31
  ".codex/skills/ai-train-local-research/scripts/decision-capture-join.test.mjs": "017511e3d1530ab85f1c43677cddd146c7a68aab49cfce201cae0a187038e625",
32
32
  ".codex/skills/ai-train-local-research/scripts/decision-capture-storage.mjs": "a72b30351c79bd040ec6543c42a43ecc145fc056ea4108da4ac26d1641c0112c",
33
33
  ".codex/skills/ai-train-local-research/scripts/decision-capture-storage.test.mjs": "10af1fabaa880023215239e27b7d17cdf66e6e09a4a1329a226f2a8a2606d18e",
34
- ".codex/skills/ai-train-local-research/scripts/equity-stability.mjs": "3f60d079f881437f275d50ca78e063ef76451b166e031ec3e8f7a29b3b5e8a8a",
34
+ ".codex/skills/ai-train-local-research/scripts/equity-stability.mjs": "d105ad8c4f8033dce8847649628426bc79f52d051a7d9307faf661a1315cb962",
35
35
  ".codex/skills/ai-train-local-research/scripts/equity-stability.test.mjs": "48e544ec259d3bbb6b8f7c3112bcf003807b5c84ecff65f43254627ea4dd3de0",
36
36
  ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.mjs": "a9f69ec62937344f5a160dce0f66d1f3251c9fcf061229dea65236cfe116c59c",
37
37
  ".codex/skills/ai-train-local-research/scripts/market-regime-diagnostics.test.mjs": "d7a4f1d8c19a4506bd09cd865b9718f498e4e65a5f54b902fb0309b8eede186c",
38
38
  ".codex/skills/ai-train-local-research/scripts/market-regime-plot.py": "3f1e5d93110c6c8987dd09ba16cd65968c789f548fb374905009bb12705b423d",
39
+ ".codex/skills/ai-train-local-research/scripts/report-output.mjs": "a5f42441a002d6c77dc5ce61055a9462bd3bf3097a2c297fc3d297b108675c06",
40
+ ".codex/skills/ai-train-local-research/scripts/report-output.test.mjs": "f693447bde99959be03d9acccb8529e249d4bfab0d76a547ad0b3a0becd5ca3b",
39
41
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.integration.mjs": "fe8fe74d82aae32435640ed3ee2b0062d24f300bc7fc443ec18ac41118ffac74",
40
42
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.mjs": "f8c9cb7f63c7e83dcaedf6d58979a2b2a3b4730bf7159aae10ee19b875530fa7",
41
43
  ".codex/skills/ai-train-local-research/scripts/research-entry-gate-bridge.test.mjs": "a9f5a918cda1d36da62dbaaf1ea3aea6bcb40f06ad9f7c4bfc4da18baa5aa01e",
42
44
  ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.mjs": "ad70b73ea49060c0a350d2ca2f85788e6900bdbece46434e9a95865965329d89",
43
45
  ".codex/skills/ai-train-local-research/scripts/symbol-mix-diagnostics.test.mjs": "6244c3540f708be6f2f29fa5b871a266e0ecee7a5ba4d588b0e3acb47e1ee445",
44
- ".codex/skills/ai-train-local-research/SKILL.md": "371d98fa7e7de3cb7ccfab6924d7d7bb2638b1c0ed05cf2035c9a074c24ce4fc",
46
+ ".codex/skills/ai-train-local-research/SKILL.md": "d570134151e29ea1f010e48d16ae09687e7b8e53dc5e595251e44b0e61a1dc96",
45
47
  ".codex/skills/backtest-config-redis/scripts/get_backtest_config.sh": "833e950d6348c5b7a4bd3f00d25af60f6394190bff744bd5ab64db9e43d826d5",
46
48
  ".codex/skills/backtest-config-redis/SKILL.md": "ac4f9d685c12f748a87b1882df1f731dd3ae9ec8bd7c11cb652221fe0463febc",
47
49
  ".codex/skills/runtime-parity-mismatch-analysis/SKILL.md": "f9cbc571baaba7a185550415c3ef31f0f55a9503107c8ace2314fac88ba025bd",
48
50
  ".codex/skills/save-strategy-config-from-backtest/agents/openai.yaml": "ba163f9449562241ed954ca2e0f12e22562390740cdcf0d09d7f99f0ef791741",
49
51
  ".codex/skills/save-strategy-config-from-backtest/SKILL.md": "a73cddc29fb8fa741fe6226c051e19b0f9a19747babf96d336e7f165fb1fd298",
50
- ".codex/skills/strategy-backtest-research/references/research-notes.md": "85a23e26f2035e98cd8d3a56b4ec14638cd9d42b1dc34b4dc8ca958c3624ecaa",
51
- ".codex/skills/strategy-backtest-research/references/research-retention.md": "55fb27507d9f83a0123d9c840d4ef3080ff7d77c32ecfc94f33b7aab456e0f3c",
52
+ ".codex/skills/strategy-backtest-research/references/research-notes.md": "d9ccda0ac667079edc97078d1cb96cb461569e1d74b66934e9392a687e507d6f",
53
+ ".codex/skills/strategy-backtest-research/references/research-retention.md": "df4c236d1986b52854a313ba6e179f5be5e09c69c57647f8f9a8ba0fa8f7f796",
52
54
  ".codex/skills/strategy-backtest-research/scripts/backtest-run-metrics.mjs": "dbcc6bb7cab4e0108ed11df503b8a0a337d1a01b77c5b56554ce1264a00f5d57",
53
55
  ".codex/skills/strategy-backtest-research/scripts/backtest-run-metrics.test.mjs": "a00d0ae5fb0037cc554282dbe22109a9e34cb64b93d26a6feab69005a2ba637f",
54
56
  ".codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.mjs": "61e8604bba829914315fccd604afc4a13f97409b7ebe2f22d255d0eb57f32921",
55
57
  ".codex/skills/strategy-backtest-research/scripts/fast-ai-export-metrics.test.mjs": "447453e2415004336293297b7f68ffd16ae35053d9725accaa5f42e1bbe28a58",
56
- ".codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs": "435aa6560abcf4e8a60fb86230d8d8de2f2dc9e4c52acc7a272ce30287d40325",
57
- ".codex/skills/strategy-backtest-research/scripts/retire-worktree.py": "5fb920e5d639c58aeef51a104a4dad20824183c566f8f1d049e29394f12a9c68",
58
- ".codex/skills/strategy-backtest-research/SKILL.md": "7aaccb986c4b6fba4820af683497276d2f517439936011be9d5a2563e8cb8cce",
58
+ ".codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs": "b96ece871772c82074a188c105520f773362980fa09677456bc5dff895855ade",
59
+ ".codex/skills/strategy-backtest-research/scripts/metric-snapshot.test.mjs": "77ef641d1f8590063db13aa9fe12d1db30b28c622f44c774be502d0a9fa487dc",
60
+ ".codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs": "196f420845f0cc841bdbb1651063a485c90a1140f767e88f4dbf3543adb881de",
61
+ ".codex/skills/strategy-backtest-research/scripts/research-notes-check.test.mjs": "256618c16d797374078198e6e61c50b518cef5bbbc85c3ceffa891035ae58318",
62
+ ".codex/skills/strategy-backtest-research/scripts/retire-worktree.py": "6870d1c537e32c9626c27c1e0dfd5911e4e2fe917b82de28a15f82193f1e6384",
63
+ ".codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py": "648071b5c6326f5129c3d1893da763212d2bdd92d4ea66226e3823e7189848ef",
64
+ ".codex/skills/strategy-backtest-research/SKILL.md": "c033ab2e4b552e2a19e69e797413b5dee9ed66987a52d3b201e7bdaa60cfe06c",
59
65
  ".codex/skills/strategy-candidate-compare/SKILL.md": "0213ffab975f7a19cc204260a9ca587e6f59dbd84f2a4cdac19d84418ebf0792",
60
66
  ".codex/skills/strategy-candidate-report/SKILL.md": "2f24b1ac546bd21a0cdcc04cfdce6eeeca25ff89fc42cdd1dc66516b6fe95c11",
61
67
  ".codex/skills/strategy-forward-start/SKILL.md": "a86311aeb4c5b46e43011806ffa0f665c4ec0fddce8d7f8c1232184e4a14bfa7",
62
68
  ".codex/skills/strategy-forward-status/SKILL.md": "7cb021991ff40bb3407eb58e1c9e2bcf597f67b0201059b9e20e4f37fd3320b9",
63
69
  ".codex/skills/strategy-improvement-plan/SKILL.md": "f5f0f390941dd3332890a2f0ffae1248abde4925db2cf49a41c0c0c1b47e7864",
64
- ".codex/skills/strategy-improvement-research/references/final-composition-board.md": "9be39311ab1feb8abbbdd7ee7575ca4b91ff45be13cb7df1e241d7cb1435eacc",
70
+ ".codex/skills/strategy-improvement-research/references/final-composition-board.md": "9c5b9d7ae75a46fbc3bd81109b203590f32faa6f8202cc55926c0f085724e207",
65
71
  ".codex/skills/strategy-improvement-research/scripts/build-final-composition-spec.mjs": "f336bb3b7e0d0040cabeda9f2d0d015301b017ea6e825f3bcdcafeed187ee93b",
66
72
  ".codex/skills/strategy-improvement-research/scripts/build-final-composition-spec.test.mjs": "1985664ce89c00269c5e5b8748aceaaa7377759c84e28dfca7bb3618bfcfbe44",
67
73
  ".codex/skills/strategy-improvement-research/scripts/executed-composition-report.mjs": "0dcae8ceef53974e689ea9c96ef8ab0f44150f98f4b3adc44661207e827b5aa5",
@@ -70,8 +76,8 @@
70
76
  ".codex/skills/strategy-improvement-research/scripts/final-composition-board.test.mjs": "4dae48e797c27a55913639b3c90b66b7c8effe8eb9da3c943d804df301d58aa6",
71
77
  ".codex/skills/strategy-improvement-research/scripts/freeze-gate-variants.mjs": "17b3c868880ddd5b326d309e6e42eaeef1ea22d625a5db947997ac73b221ad6d",
72
78
  ".codex/skills/strategy-improvement-research/scripts/freeze-gate-variants.test.mjs": "963e1c64ab3deef11fd48a96e10f3827af38036dfe2eb28daf7849f19dd414d8",
73
- ".codex/skills/strategy-improvement-research/SKILL.md": "841956c4de5f0dbe29c7fe408f27791cb599968f9a86195c962ad18271b464b8",
74
- ".codex/skills/strategy-period-revalidate/SKILL.md": "b580d09c78c2bf64de26ca25c4394d5e2657e8bc1f8f717391153db894b57ab2",
79
+ ".codex/skills/strategy-improvement-research/SKILL.md": "49dc75ae27d9c57c9109be680bf8cfbdc273addca6625cdc0336a4ba45ffd67c",
80
+ ".codex/skills/strategy-period-revalidate/SKILL.md": "424389c13c238b51247dcdbed3172d3209f47f33cee54cbcdfc0548780b35f5f",
75
81
  ".codex/skills/strategy-release/agents/openai.yaml": "46ddb09119b08ae3be3b9509121b57492342012e774789b615767b24270dba17",
76
82
  ".codex/skills/strategy-release/references/diagnose-live.md": "dc2effa6eba34e3cfcc1eaf4d2fd1c96d6ccdda971a0edec76c9eed1ec293a3d",
77
83
  ".codex/skills/strategy-release/references/direction-policy.md": "e7635e709dfc7301b94f3dbc1421c6a779c7c39ce4f6066b2eece38e4e600bec",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tradejs",
3
- "version": "3.1.29-beta.290",
3
+ "version": "3.1.29-beta.292",
4
4
  "description": "Create a ready-to-run TradeJS project with local infrastructure and the Web UI.",
5
5
  "keywords": [
6
6
  "tradejs",