create-tradejs 3.1.29-beta.290 → 3.1.29-beta.291
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/skill-bundle/.codex/skills/ai-train-local-research/SKILL.md +6 -0
- package/dist/skill-bundle/.codex/skills/ai-train-local-research/references/gate-ablation.md +33 -0
- package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs +19 -33
- package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/equity-stability.mjs +10 -4
- package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/report-output.mjs +33 -0
- package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/report-output.test.mjs +64 -0
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/SKILL.md +3 -2
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-notes.md +25 -6
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-retention.md +40 -1
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs +102 -0
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.test.mjs +69 -0
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs +70 -6
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-notes-check.test.mjs +71 -0
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.py +32 -7
- package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py +53 -0
- package/dist/skill-bundle/.codex/tradejs-skill-bundle.json +16 -10
- package/package.json +1 -1
|
@@ -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,36 @@ 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.
|
package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/ai-gate-ablation.mjs
CHANGED
|
@@ -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
|
|
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
|
-
|
|
8042
|
-
|
|
8043
|
-
|
|
8044
|
-
|
|
8045
|
-
|
|
8046
|
-
|
|
8047
|
-
|
|
8048
|
-
|
|
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
|
-
|
|
8185
|
-
|
|
8186
|
-
|
|
8187
|
-
|
|
8188
|
-
|
|
8189
|
-
|
|
8190
|
-
|
|
8191
|
-
|
|
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()) {
|
package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/equity-stability.mjs
CHANGED
|
@@ -105,8 +105,14 @@ if (
|
|
|
105
105
|
sha256: crypto.createHash('sha256').update(bytes).digest('hex'),
|
|
106
106
|
},
|
|
107
107
|
};
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
+
};
|
package/dist/skill-bundle/.codex/skills/ai-train-local-research/scripts/report-output.test.mjs
ADDED
|
@@ -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
|
-
-
|
|
354
|
-
|
|
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
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-notes.md
CHANGED
|
@@ -49,7 +49,7 @@ Every file starts with:
|
|
|
49
49
|
|
|
50
50
|
```yaml
|
|
51
51
|
---
|
|
52
|
-
schema: tradejs-research/
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/references/research-retention.md
CHANGED
|
@@ -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
|
|
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
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.mjs
ADDED
|
@@ -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
|
+
}
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/metric-snapshot.test.mjs
ADDED
|
@@ -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
|
+
});
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/research-notes-check.mjs
CHANGED
|
@@ -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('"')
|
|
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
|
|
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(
|
|
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(
|
|
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 (
|
|
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(
|
|
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
|
+
});
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.py
CHANGED
|
@@ -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,25 @@ 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
|
-
|
|
70
|
-
|
|
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
|
+
git(repository, 'bundle', 'verify', str(history))
|
|
91
|
+
if git(repository, 'bundle', 'list-heads', str(history), 'HEAD').decode().strip() != f'{head} HEAD':
|
|
92
|
+
raise ValueError('Shared history HEAD does not match archived worktree')
|
|
93
|
+
history_reference = {'path': os.path.relpath(history, out), 'sha256': sha_file(history), 'head': head}
|
|
94
|
+
(out / 'history-reference.json').write_text(json.dumps(history_reference) + '\n')
|
|
71
95
|
(out / 'working-tree.patch').write_bytes(patch)
|
|
72
96
|
(out / 'staged.patch').write_bytes(staged)
|
|
73
97
|
(out / 'status.porcelain').write_bytes(status)
|
|
@@ -112,5 +136,6 @@ if __name__ == '__main__':
|
|
|
112
136
|
parser.add_argument('--worktree', required=True)
|
|
113
137
|
parser.add_argument('--out', required=True)
|
|
114
138
|
parser.add_argument('--apply', action='store_true')
|
|
139
|
+
parser.add_argument('--history-root', help='Permanent shared Git-bundle directory; defaults to <out-parent>/shared-history')
|
|
115
140
|
args = parser.parse_args()
|
|
116
|
-
print(json.dumps(retire(args.repository, args.worktree, args.out, args.apply), indent=2))
|
|
141
|
+
print(json.dumps(retire(args.repository, args.worktree, args.out, args.apply, args.history_root), indent=2))
|
package/dist/skill-bundle/.codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
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_shared_history_and_source_recovery(self):
|
|
16
|
+
with tempfile.TemporaryDirectory(prefix='research-archive-') as temporary:
|
|
17
|
+
root = Path(temporary).resolve()
|
|
18
|
+
repo = root / 'repo'
|
|
19
|
+
repo.mkdir()
|
|
20
|
+
module.git(repo, 'init', '-q')
|
|
21
|
+
(repo / '.gitignore').write_text('synthetic-fixtures/\n')
|
|
22
|
+
(repo / 'synthetic-fixtures').mkdir()
|
|
23
|
+
(repo / 'synthetic-fixtures/authored.json').write_text('{"source":true}')
|
|
24
|
+
module.git(repo, 'add', '.gitignore')
|
|
25
|
+
module.git(repo, 'add', '-f', 'synthetic-fixtures/authored.json')
|
|
26
|
+
module.git(repo, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture')
|
|
27
|
+
receipts = []
|
|
28
|
+
for number in range(2):
|
|
29
|
+
worktree = root / f'worktree-{number}'
|
|
30
|
+
module.git(repo, 'worktree', 'add', '--detach', str(worktree), 'HEAD')
|
|
31
|
+
(worktree / 'synthetic-fixtures/generated.json').write_text('[]')
|
|
32
|
+
(worktree / 'candidate.py').write_text('exact_untracked_source = True\n')
|
|
33
|
+
out = root / 'archives' / str(number)
|
|
34
|
+
receipt = module.retire(repo, worktree, out, apply=True)
|
|
35
|
+
self.assertEqual(receipt['status'], 'removed')
|
|
36
|
+
self.assertFalse(worktree.exists())
|
|
37
|
+
with tarfile.open(out / 'source.tar.gz') as archive:
|
|
38
|
+
self.assertIn('synthetic-fixtures/authored.json', archive.getnames())
|
|
39
|
+
self.assertNotIn('synthetic-fixtures/generated.json', archive.getnames())
|
|
40
|
+
self.assertEqual(archive.extractfile('candidate.py').read(), b'exact_untracked_source = True\n')
|
|
41
|
+
reference = json.loads((out / 'history-reference.json').read_text())
|
|
42
|
+
history = (out / reference['path']).resolve()
|
|
43
|
+
self.assertEqual(module.sha_file(history), reference['sha256'])
|
|
44
|
+
receipts.append(history)
|
|
45
|
+
self.assertEqual(receipts[0], receipts[1])
|
|
46
|
+
self.assertEqual(len(list((root / 'archives/shared-history').glob('*.bundle'))), 1)
|
|
47
|
+
restored = root / 'restored'
|
|
48
|
+
subprocess.run(['git', 'clone', '-q', str(receipts[0]), str(restored)], check=True)
|
|
49
|
+
self.assertEqual((restored / 'synthetic-fixtures/authored.json').read_text(), '{"source":true}')
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == '__main__':
|
|
53
|
+
unittest.main()
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": "tradejs-skill-bundle/v1",
|
|
3
3
|
"source": "TradeJS-Dev/TradeJS:.codex/skills",
|
|
4
|
-
"bundleSha256": "
|
|
4
|
+
"bundleSha256": "d72cedcf85ed6ae8ac3198758b9713c3b3faa464e8008864d9b802ed604b53ee",
|
|
5
5
|
"skills": [
|
|
6
6
|
"ai-train-local-research",
|
|
7
7
|
"backtest-config-redis",
|
|
@@ -22,40 +22,46 @@
|
|
|
22
22
|
"strategy-release"
|
|
23
23
|
],
|
|
24
24
|
"files": {
|
|
25
|
-
".codex/skills/ai-train-local-research/references/gate-ablation.md": "
|
|
25
|
+
".codex/skills/ai-train-local-research/references/gate-ablation.md": "4565ba0712b21f810029eb8ed20587a4a52dcce3486a6c46ff98cbfdd0e36db3",
|
|
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": "
|
|
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": "
|
|
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": "
|
|
46
|
+
".codex/skills/ai-train-local-research/SKILL.md": "c19c1e7048a5f970725ae52f2fa6d18430fe7ffb79d18b50ee692d8768091b14",
|
|
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": "
|
|
51
|
-
".codex/skills/strategy-backtest-research/references/research-retention.md": "
|
|
52
|
+
".codex/skills/strategy-backtest-research/references/research-notes.md": "d9ccda0ac667079edc97078d1cb96cb461569e1d74b66934e9392a687e507d6f",
|
|
53
|
+
".codex/skills/strategy-backtest-research/references/research-retention.md": "cf7508901b83e95a9dd18c53d2c46fe70f38fab1c259f86d8ee6161a5a0ce427",
|
|
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/
|
|
57
|
-
".codex/skills/strategy-backtest-research/scripts/
|
|
58
|
-
".codex/skills/strategy-backtest-research/
|
|
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": "454246e6c38a886a6811e198d464a452948d5ee12cefc8f473fffe4f20f463fc",
|
|
63
|
+
".codex/skills/strategy-backtest-research/scripts/retire-worktree.test.py": "84fa52df7e2ffc8020214dda570c827f0cc3cfe69cac8f911d34d5589a1ec18a",
|
|
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",
|