@v587d/capital-generation 2.31.7 → 2.32.0
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/CHANGELOG.md +60 -0
- package/README.md +14 -5
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/artifact.d.ts +35 -0
- package/lib/analysis/artifact.js +250 -0
- package/lib/analysis/registry.d.ts +16 -2
- package/lib/analysis/registry.js +133 -23
- package/lib/analysis/runtime.d.ts +46 -19
- package/lib/analysis/runtime.js +485 -116
- package/lib/analysis/schemas.d.ts +46 -0
- package/lib/analysis/schemas.js +260 -7
- package/lib/analysis/snapshot.d.ts +10 -3
- package/lib/analysis/snapshot.js +298 -46
- package/lib/analysis/storage.d.ts +29 -1
- package/lib/analysis/storage.js +39 -6
- package/lib/analysis/tools.js +270 -29
- package/lib/analysis/types.d.ts +257 -3
- package/lib/analysis/types.js +31 -1
- package/lib/analysis/validation.d.ts +37 -1
- package/lib/analysis/validation.js +315 -1
- package/lib/chart/tool.js +1 -0
- package/lib/data-collector/store.d.ts +7 -1
- package/lib/data-collector/store.js +14 -0
- package/lib/python-runtime/child-env.d.ts +4 -2
- package/lib/python-runtime/child-env.js +21 -14
- package/lib/python-runtime/manager.d.ts +8 -0
- package/lib/python-runtime/manager.js +30 -14
- package/lib/sources/tencent-http.js +9 -3
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +2 -1
- package/plugin-page/README.en.md +1 -1
- package/plugin-page/README.zh.md +1 -1
- package/preset/capital-generation/agent.patch.yml +1 -1
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
- package/python/analysis/lib/__init__.py +9 -0
- package/python/analysis/lib/errors.py +12 -0
- package/python/analysis/lib/eventstudy.py +164 -0
- package/python/analysis/lib/frames.py +95 -0
- package/python/analysis/lib/gaps.py +54 -0
- package/python/analysis/lib/jsonio.py +61 -0
- package/python/analysis/lib/metrics.py +147 -0
- package/python/analysis/lib/pit.py +84 -0
- package/python/analysis/lib/prices.py +140 -0
- package/python/analysis/lib/timeaxis.py +142 -0
- package/python/analysis/lib/version.py +3 -0
- package/python/analysis/modules/comps_valuation/module.py +26 -59
- package/python/analysis/modules/earnings_bridge/module.py +20 -77
- package/python/analysis/modules/event_study/LICENSE +21 -0
- package/python/analysis/modules/event_study/module.json +217 -0
- package/python/analysis/modules/event_study/module.py +979 -0
- package/python/analysis/modules/financial_quality/module.py +25 -88
- package/python/analysis/modules/hello/module.py +4 -0
- package/python/analysis/modules/kline_quality/module.py +26 -132
- package/python/analysis/modules/portfolio_stress/module.py +27 -112
- package/python/analysis/modules/returns_risk/module.json +108 -25
- package/python/analysis/modules/returns_risk/module.py +68 -227
- package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
- package/python/analysis/modules/simple_backtest/module.json +244 -36
- package/python/analysis/modules/simple_backtest/module.py +1146 -459
- package/python/analysis/modules/statement_integrity/module.py +35 -87
- package/python/analysis/modules/technical_indicators/module.py +33 -152
- package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
- package/python/worker.py +5 -0
- package/watchlist/package.json +1 -1
package/lib/analysis/snapshot.js
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* AnalysisSnapshot: freeze the references an analysis is allowed to use, once.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* V2 (`snapshot.json`) stores metadata only: refs, per-input hashes/digests and the commit marker.
|
|
5
|
+
* Raw rows exist only in the staged copies under `inputs/`; the model receives an opaque ref plus a
|
|
6
|
+
* coverage summary. V1 files (no `schema_version`) stay readable, but are not runnable while the V2
|
|
7
|
+
* contract is enabled.
|
|
7
8
|
*/
|
|
8
9
|
import { createHash } from 'node:crypto';
|
|
9
10
|
import { dirname } from 'node:path';
|
|
10
11
|
import { MAX_PRESENTATION_ROWS } from '../data-collector/store.js';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { EVIDENCE_ITEM_MAX_BYTES, EVIDENCE_MAX_ITEMS, SNAPSHOT_FILE_V2_SCHEMA, SNAPSHOT_LIMITS, SNAPSHOT_METADATA_HARD_BYTES, SNAPSHOT_TTL_MS, } from './schemas.js';
|
|
13
|
+
import { SNAPSHOT_FILE, analysisContractV2Enabled, analysisDir, inputsDir, inputsRoot, newAnalysisId, readJsonFile, schemaVersionOf, snapshotRef, writeFiles, } from './storage.js';
|
|
14
|
+
import { ANALYSIS_PROTOCOL, AnalysisError, SNAPSHOT_SCHEMA_VERSION, } from './types.js';
|
|
15
|
+
import { validateAgainstSchema } from './validation.js';
|
|
14
16
|
const DATASET_COLUMN_SAMPLE = 200;
|
|
17
|
+
/**
|
|
18
|
+
* Resolved `inputs/` directories for snapshots created in this process. The store seam also exposes
|
|
19
|
+
* a resolver, but test doubles do not; both paths must resolve or a V2 snapshot could be created
|
|
20
|
+
* and never run.
|
|
21
|
+
*/
|
|
22
|
+
const inputsDirs = new Map();
|
|
15
23
|
function sha256(text) {
|
|
16
24
|
return createHash('sha256').update(text, 'utf8').digest('hex');
|
|
17
25
|
}
|
|
@@ -26,6 +34,13 @@ export function stableStringify(value) {
|
|
|
26
34
|
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
27
35
|
return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(',')}}`;
|
|
28
36
|
}
|
|
37
|
+
function canonicalHash(value) {
|
|
38
|
+
const text = stableStringify(value);
|
|
39
|
+
return { digest: sha256(text), byteSize: Buffer.byteLength(text, 'utf8') };
|
|
40
|
+
}
|
|
41
|
+
function schemaDigestOf(...parts) {
|
|
42
|
+
return sha256(stableStringify(parts));
|
|
43
|
+
}
|
|
29
44
|
function inferType(values) {
|
|
30
45
|
let sawNull = false;
|
|
31
46
|
for (const value of values) {
|
|
@@ -78,6 +93,82 @@ function timeAxisOf(ref) {
|
|
|
78
93
|
return null;
|
|
79
94
|
return { column: coverage.column, unit: coverage.format, tz: 'dataset' };
|
|
80
95
|
}
|
|
96
|
+
const DISCLOSURE_COLUMNS = [
|
|
97
|
+
'report_date_ms', 'report_date', 'announce_date_ms', 'announce_date',
|
|
98
|
+
'disclosure_date', 'notice_date', 'publish_date', 'pub_date',
|
|
99
|
+
];
|
|
100
|
+
const PERIOD_COLUMNS = ['period_end_ms', 'period_end', 'period', 'report_period', 'fiscal_year'];
|
|
101
|
+
/** ISO day of a date/timestamp cell; timestamps are read as UTC (the module labels with its zone). */
|
|
102
|
+
function cellDay(value) {
|
|
103
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
104
|
+
const date = new Date(value);
|
|
105
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString().slice(0, 10);
|
|
106
|
+
}
|
|
107
|
+
if (typeof value === 'string') {
|
|
108
|
+
const match = /^(\d{4}-\d{2}-\d{2})/u.exec(value.trim());
|
|
109
|
+
return match === null ? null : match[1];
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
function latestDay(rows, column) {
|
|
114
|
+
let latest;
|
|
115
|
+
for (const row of rows) {
|
|
116
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row))
|
|
117
|
+
continue;
|
|
118
|
+
const day = cellDay(row[column]);
|
|
119
|
+
if (day !== null && (latest === undefined || day > latest))
|
|
120
|
+
latest = day;
|
|
121
|
+
}
|
|
122
|
+
return latest;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Per-input availability facts. Disclosure beats period end (when it was knowable beats what period
|
|
126
|
+
* it covers), and a price time axis makes the bar's close day the availability day.
|
|
127
|
+
*/
|
|
128
|
+
function temporalFactsOf(view) {
|
|
129
|
+
const columns = new Set(view.columns.map((column) => column.name));
|
|
130
|
+
const disclosure = DISCLOSURE_COLUMNS.find((name) => columns.has(name));
|
|
131
|
+
if (disclosure !== undefined) {
|
|
132
|
+
const available = latestDay(view.rows, disclosure);
|
|
133
|
+
return { temporal_basis: 'disclosure', ...(available === undefined ? {} : { available_at: available }) };
|
|
134
|
+
}
|
|
135
|
+
if (view.time_axis !== null) {
|
|
136
|
+
const available = latestDay(view.rows, view.time_axis.column);
|
|
137
|
+
return { temporal_basis: 'exchange_time', ...(available === undefined ? {} : { available_at: available }) };
|
|
138
|
+
}
|
|
139
|
+
if (PERIOD_COLUMNS.some((name) => columns.has(name)))
|
|
140
|
+
return { temporal_basis: 'report_period' };
|
|
141
|
+
return { temporal_basis: 'unknown' };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Metadata-level PIT gate for `as_known_then`: an input whose availability is unknown or later than
|
|
145
|
+
* `as_of` must not enter the snapshot at all. Row-level filtering is the module's job (lib/pit.py).
|
|
146
|
+
*/
|
|
147
|
+
function assertPointInTime(temporalMode, asOf, inputs) {
|
|
148
|
+
if (temporalMode !== 'as_known_then')
|
|
149
|
+
return;
|
|
150
|
+
const boundary = cellDay(asOf);
|
|
151
|
+
if (boundary === null) {
|
|
152
|
+
throw new AnalysisError('analysis_point_in_time_conflict', `as_known_then 快照的 as_of=${JSON.stringify(asOf)} 不是可解析日期`);
|
|
153
|
+
}
|
|
154
|
+
for (const input of inputs) {
|
|
155
|
+
if (input.kind === 'profile')
|
|
156
|
+
continue;
|
|
157
|
+
if (input.temporal_basis === 'unknown' || input.temporal_basis === 'report_period') {
|
|
158
|
+
throw new AnalysisError('analysis_event_time_missing', `${input.source_ref} 没有可得时间(temporal_basis=${input.temporal_basis}):as_known_then 需要时间轴或披露日列`);
|
|
159
|
+
}
|
|
160
|
+
if (input.available_at === undefined) {
|
|
161
|
+
throw new AnalysisError('analysis_event_time_missing', `${input.source_ref} 的可得时间为空:as_known_then 下无法判断何时可知`);
|
|
162
|
+
}
|
|
163
|
+
const available = cellDay(input.available_at);
|
|
164
|
+
if (available === null) {
|
|
165
|
+
throw new AnalysisError('analysis_event_time_missing', `${input.source_ref} 的可得时间 ${input.available_at} 无法解析为日期`);
|
|
166
|
+
}
|
|
167
|
+
if (available > boundary) {
|
|
168
|
+
throw new AnalysisError('analysis_point_in_time_conflict', `${input.source_ref} 的可得时间 ${available} 晚于 as_of ${boundary}:as_known_then 不能包含未来信息`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
81
172
|
function evidenceHash(item) {
|
|
82
173
|
return sha256(stableStringify({ source_id: item.source_id, title: item.title, excerpt: item.excerpt ?? null, url: item.url ?? null }));
|
|
83
174
|
}
|
|
@@ -92,6 +183,22 @@ function validateEvidence(evidence) {
|
|
|
92
183
|
}
|
|
93
184
|
}
|
|
94
185
|
}
|
|
186
|
+
function enforceInputBudgets(limits, inputs) {
|
|
187
|
+
const coreCount = inputs.filter((input) => input.kind !== 'evidence').length;
|
|
188
|
+
if (coreCount > limits.input_max_count) {
|
|
189
|
+
throw new AnalysisError('analysis_snapshot_too_large', `暂存输入 ${coreCount} 份,超过上限 ${limits.input_max_count} 份(dataset + profile)`);
|
|
190
|
+
}
|
|
191
|
+
let total = 0;
|
|
192
|
+
for (const input of inputs) {
|
|
193
|
+
if (input.byte_size > limits.input_file_bytes) {
|
|
194
|
+
throw new AnalysisError('analysis_snapshot_too_large', `输入 ${input.source_ref} 有 ${input.byte_size} 字节,超过单文件上限 ${limits.input_file_bytes}`);
|
|
195
|
+
}
|
|
196
|
+
total += input.byte_size;
|
|
197
|
+
}
|
|
198
|
+
if (total > limits.input_total_bytes) {
|
|
199
|
+
throw new AnalysisError('analysis_snapshot_too_large', `暂存输入合计 ${total} 字节,超过总量上限 ${limits.input_total_bytes}`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
95
202
|
/**
|
|
96
203
|
* Create the snapshot and stage its inputs.
|
|
97
204
|
*
|
|
@@ -101,12 +208,16 @@ function validateEvidence(evidence) {
|
|
|
101
208
|
export async function createSnapshot(options) {
|
|
102
209
|
const { reader, writer, session, input } = options;
|
|
103
210
|
const now = options.now ?? Date.now();
|
|
211
|
+
const limits = { ...SNAPSHOT_LIMITS, ...(options.limits ?? {}) };
|
|
212
|
+
const v2 = analysisContractV2Enabled();
|
|
213
|
+
const temporalMode = input.temporal_mode ?? 'ex_post';
|
|
104
214
|
const analysisId = newAnalysisId();
|
|
105
215
|
const dir = analysisDir(analysisId);
|
|
106
216
|
validateEvidence(input.evidence);
|
|
107
217
|
const datasets = [];
|
|
108
218
|
const datasetFiles = [];
|
|
109
219
|
const retentionCandidates = [];
|
|
220
|
+
const inputs = [];
|
|
110
221
|
for (const ref of input.dataset_refs) {
|
|
111
222
|
const datasetId = typeof ref?.dataset_id === 'string' ? ref.dataset_id.trim() : '';
|
|
112
223
|
if (datasetId === '')
|
|
@@ -138,9 +249,25 @@ export async function createSnapshot(options) {
|
|
|
138
249
|
params_digest: staged.ref.params_digest,
|
|
139
250
|
},
|
|
140
251
|
};
|
|
252
|
+
const content = JSON.stringify(view);
|
|
253
|
+
const { digest, byteSize } = canonicalHash(view);
|
|
141
254
|
datasets.push(view);
|
|
142
255
|
retentionCandidates.push(staged.ref.retention_until);
|
|
143
|
-
datasetFiles.push({ name: `${datasetId}.json`, content
|
|
256
|
+
datasetFiles.push({ name: `${datasetId}.json`, content });
|
|
257
|
+
inputs.push({
|
|
258
|
+
input_id: `in_dataset_${datasetId}`,
|
|
259
|
+
kind: 'dataset',
|
|
260
|
+
source_ref: `dataset:${datasetId}`,
|
|
261
|
+
path: `${inputsDir(analysisId, 'datasets')}/${datasetId}.json`,
|
|
262
|
+
sha256: digest,
|
|
263
|
+
byte_size: byteSize,
|
|
264
|
+
row_count: view.row_count,
|
|
265
|
+
column_count: view.columns.length,
|
|
266
|
+
schema_digest: schemaDigestOf(view.shape, view.columns, view.time_axis),
|
|
267
|
+
...(view.time_axis === null ? {} : { time_axis: view.time_axis }),
|
|
268
|
+
...temporalFactsOf(view),
|
|
269
|
+
retention_until: staged.ref.retention_until,
|
|
270
|
+
});
|
|
144
271
|
}
|
|
145
272
|
const profiles = [];
|
|
146
273
|
const profileFiles = [];
|
|
@@ -155,11 +282,44 @@ export async function createSnapshot(options) {
|
|
|
155
282
|
catch (error) {
|
|
156
283
|
throw new AnalysisError('analysis_input_invalid', `profile ${profileId} 无法作为分析输入:${error instanceof Error ? error.message : String(error)}`);
|
|
157
284
|
}
|
|
285
|
+
const payload = { ref: staged.ref, profile: staged.profile };
|
|
286
|
+
// Hash the profile payload, not the ref: `retention_until` is wall-clock metadata and would
|
|
287
|
+
// make the same staged content fingerprint differently on every call.
|
|
288
|
+
const { digest, byteSize } = canonicalHash(staged.profile);
|
|
158
289
|
profiles.push({ ref: staged.ref });
|
|
159
290
|
retentionCandidates.push(staged.ref.retention_until);
|
|
160
|
-
profileFiles.push({ name: `${profileId}.json`, content: JSON.stringify(
|
|
291
|
+
profileFiles.push({ name: `${profileId}.json`, content: JSON.stringify(payload) });
|
|
292
|
+
inputs.push({
|
|
293
|
+
input_id: `in_profile_${profileId}`,
|
|
294
|
+
kind: 'profile',
|
|
295
|
+
source_ref: `profile:${profileId}`,
|
|
296
|
+
path: `${inputsDir(analysisId, 'profiles')}/${profileId}.json`,
|
|
297
|
+
sha256: digest,
|
|
298
|
+
byte_size: byteSize,
|
|
299
|
+
row_count: staged.profile.row_count,
|
|
300
|
+
column_count: staged.profile.columns.length,
|
|
301
|
+
schema_digest: schemaDigestOf(staged.profile.columns, staged.profile.row_count),
|
|
302
|
+
temporal_basis: 'unknown',
|
|
303
|
+
retention_until: staged.ref.retention_until,
|
|
304
|
+
});
|
|
161
305
|
}
|
|
162
306
|
const evidence = [...input.evidence];
|
|
307
|
+
for (const item of evidence) {
|
|
308
|
+
const { digest, byteSize } = canonicalHash(item);
|
|
309
|
+
inputs.push({
|
|
310
|
+
input_id: `in_evidence_${item.source_id}`,
|
|
311
|
+
kind: 'evidence',
|
|
312
|
+
source_ref: `evidence:${item.source_id}`,
|
|
313
|
+
path: `${inputsDir(analysisId, 'evidence')}/${item.source_id}.json`,
|
|
314
|
+
sha256: digest,
|
|
315
|
+
byte_size: byteSize,
|
|
316
|
+
schema_digest: schemaDigestOf('evidence', item.kind, item.source_id),
|
|
317
|
+
temporal_basis: item.published_at === undefined ? 'unknown' : 'disclosure',
|
|
318
|
+
...(item.published_at === undefined ? {} : { available_at: item.published_at, published_at: item.published_at }),
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
assertPointInTime(temporalMode, input.as_of, inputs);
|
|
322
|
+
enforceInputBudgets(limits, inputs);
|
|
163
323
|
const inputFingerprint = sha256(stableStringify({
|
|
164
324
|
protocol: ANALYSIS_PROTOCOL,
|
|
165
325
|
task_id: input.task_id,
|
|
@@ -170,6 +330,13 @@ export async function createSnapshot(options) {
|
|
|
170
330
|
depth: input.depth,
|
|
171
331
|
as_of: input.as_of,
|
|
172
332
|
data_cutoff: input.data_cutoff ?? null,
|
|
333
|
+
temporal_mode: temporalMode,
|
|
334
|
+
inputs: inputs.map((item) => ({
|
|
335
|
+
source_ref: item.source_ref,
|
|
336
|
+
sha256: item.sha256,
|
|
337
|
+
schema_digest: item.schema_digest,
|
|
338
|
+
temporal_basis: item.temporal_basis,
|
|
339
|
+
})),
|
|
173
340
|
datasets: datasets.map((item) => item.source),
|
|
174
341
|
profiles: profiles.map((item) => ({ profile_id: item.ref.profile_id, created_at: item.ref.created_at })),
|
|
175
342
|
evidence: evidence.map((item) => ({ source_id: item.source_id, hash: evidenceHash(item) })),
|
|
@@ -178,7 +345,36 @@ export async function createSnapshot(options) {
|
|
|
178
345
|
}));
|
|
179
346
|
const earliestRetention = retentionCandidates.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...retentionCandidates);
|
|
180
347
|
const expiresAt = Math.min(now + SNAPSHOT_TTL_MS, earliestRetention);
|
|
181
|
-
|
|
348
|
+
const base = {
|
|
349
|
+
analysis_id: analysisId,
|
|
350
|
+
task_id: input.task_id,
|
|
351
|
+
question: input.question,
|
|
352
|
+
...(input.instrument === undefined ? {} : { instrument: input.instrument }),
|
|
353
|
+
purpose: input.purpose,
|
|
354
|
+
...(input.horizon === undefined ? {} : { horizon: input.horizon }),
|
|
355
|
+
depth: input.depth,
|
|
356
|
+
as_of: input.as_of,
|
|
357
|
+
...(input.data_cutoff === undefined ? {} : { data_cutoff: input.data_cutoff }),
|
|
358
|
+
dataset_refs: datasets.map((item) => item.source),
|
|
359
|
+
profile_refs: profiles.map((item) => ({ profile_id: item.ref.profile_id, created_at: item.ref.created_at })),
|
|
360
|
+
evidence,
|
|
361
|
+
prior_analysis_refs: [...input.prior_analysis_refs],
|
|
362
|
+
constraints: input.constraints,
|
|
363
|
+
input_fingerprint: inputFingerprint,
|
|
364
|
+
created_at: now,
|
|
365
|
+
expires_at: expiresAt,
|
|
366
|
+
limitations: [],
|
|
367
|
+
};
|
|
368
|
+
const snapshotFile = {
|
|
369
|
+
schema_version: SNAPSHOT_SCHEMA_VERSION,
|
|
370
|
+
...base,
|
|
371
|
+
temporal_mode: temporalMode,
|
|
372
|
+
inputs,
|
|
373
|
+
};
|
|
374
|
+
const metadataText = JSON.stringify(snapshotFile);
|
|
375
|
+
if (Buffer.byteLength(metadataText, 'utf8') > limits.metadata_hard_bytes) {
|
|
376
|
+
throw new AnalysisError('analysis_snapshot_too_large', `快照元数据 ${Buffer.byteLength(metadataText, 'utf8')} 字节,超过硬上限 ${limits.metadata_hard_bytes};减少输入或证据条数`);
|
|
377
|
+
}
|
|
182
378
|
const writtenDatasets = datasetFiles.length === 0
|
|
183
379
|
? undefined
|
|
184
380
|
: await writeFiles(writer, session, inputsDir(analysisId, 'datasets'), datasetFiles, {
|
|
@@ -191,63 +387,119 @@ export async function createSnapshot(options) {
|
|
|
191
387
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
192
388
|
what: '暂存 profile 副本失败',
|
|
193
389
|
});
|
|
194
|
-
|
|
195
|
-
|
|
390
|
+
const writtenEvidence = evidence.length === 0
|
|
391
|
+
? undefined
|
|
392
|
+
: await writeFiles(writer, session, inputsDir(analysisId, 'evidence'), evidence.map((item) => ({
|
|
196
393
|
name: `${item.source_id}.json`,
|
|
197
394
|
content: JSON.stringify(item),
|
|
198
395
|
})), {
|
|
199
396
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
200
397
|
what: '暂存证据副本失败',
|
|
201
398
|
});
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
const inputsAbsolute = datasetsAbs !== undefined
|
|
207
|
-
? dirname(datasetsAbs)
|
|
208
|
-
: profilesAbs !== undefined
|
|
209
|
-
? dirname(profilesAbs)
|
|
210
|
-
: undefined;
|
|
399
|
+
// The inputs directory is inputs/<kind>/<file>; resolve the shared parent without string slicing
|
|
400
|
+
// (Windows paths use a backslash separator).
|
|
401
|
+
const firstWritten = writtenDatasets?.[0]?.absolutePath ?? writtenProfiles?.[0]?.absolutePath ?? writtenEvidence?.[0]?.absolutePath;
|
|
402
|
+
const inputsAbsolute = firstWritten === undefined ? `${dir}/inputs` : dirname(dirname(firstWritten));
|
|
211
403
|
const record = {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
purpose: input.purpose,
|
|
217
|
-
...(input.horizon === undefined ? {} : { horizon: input.horizon }),
|
|
218
|
-
depth: input.depth,
|
|
219
|
-
as_of: input.as_of,
|
|
220
|
-
...(input.data_cutoff === undefined ? {} : { data_cutoff: input.data_cutoff }),
|
|
221
|
-
dataset_refs: datasets.map((item) => item.source),
|
|
222
|
-
profile_refs: profiles.map((item) => ({ profile_id: item.ref.profile_id, created_at: item.ref.created_at })),
|
|
223
|
-
evidence,
|
|
224
|
-
prior_analysis_refs: [...input.prior_analysis_refs],
|
|
225
|
-
constraints: input.constraints,
|
|
226
|
-
input_fingerprint: inputFingerprint,
|
|
227
|
-
created_at: now,
|
|
228
|
-
expires_at: expiresAt,
|
|
229
|
-
limitations: [],
|
|
404
|
+
...base,
|
|
405
|
+
...(v2 ? { schema_version: SNAPSHOT_SCHEMA_VERSION } : {}),
|
|
406
|
+
temporal_mode: temporalMode,
|
|
407
|
+
inputs,
|
|
230
408
|
datasets,
|
|
231
409
|
profiles,
|
|
232
|
-
paths: { dir, inputs_dir: inputsAbsolute
|
|
410
|
+
paths: { dir, inputs_dir: inputsAbsolute },
|
|
233
411
|
};
|
|
234
|
-
|
|
412
|
+
inputsDirs.set(analysisId, inputsAbsolute);
|
|
413
|
+
// `snapshot.json` is the commit marker: inputs are on disk first, metadata last. A failed earlier
|
|
414
|
+
// step leaves unreachable staged copies (visible in storage stats), never a loadable half-snapshot.
|
|
415
|
+
const text = v2 ? metadataText : legacySnapshotText(record);
|
|
416
|
+
await writeFiles(writer, session, dir, [{ name: SNAPSHOT_FILE, content: text }], {
|
|
235
417
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
236
418
|
what: '写入 snapshot.json 失败',
|
|
237
419
|
});
|
|
238
420
|
return { record, ref: snapshotRef(analysisId) };
|
|
239
421
|
}
|
|
240
|
-
|
|
422
|
+
function legacySnapshotText(record) {
|
|
423
|
+
const { schema_version: _schemaVersion, temporal_mode: _temporalMode, inputs: _inputs, ...legacy } = record;
|
|
424
|
+
return JSON.stringify(legacy);
|
|
425
|
+
}
|
|
426
|
+
/** Load a snapshot by ref and fail loudly when it is missing, corrupt or expired. */
|
|
241
427
|
export async function loadSnapshot(options) {
|
|
242
|
-
const
|
|
243
|
-
if (
|
|
428
|
+
const raw = await readJsonFile(options.reader, options.session, `${analysisDir(options.analysisId)}/${SNAPSHOT_FILE}`, options.signal);
|
|
429
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
|
|
430
|
+
|| raw.analysis_id !== options.analysisId) {
|
|
244
431
|
throw new AnalysisError('analysis_snapshot_invalid', `找不到分析快照 ${options.analysisId}(ref 可能已失效,或不属于本会话)`);
|
|
245
432
|
}
|
|
246
433
|
const now = options.now ?? Date.now();
|
|
247
|
-
|
|
248
|
-
|
|
434
|
+
const expiresAt = raw.expires_at;
|
|
435
|
+
if (typeof expiresAt === 'number' && expiresAt <= now) {
|
|
436
|
+
throw new AnalysisError('analysis_snapshot_expired', `分析快照 ${options.analysisId} 已于 ${new Date(expiresAt).toISOString()} 过期;重新建快照再跑`);
|
|
437
|
+
}
|
|
438
|
+
if (schemaVersionOf(raw) === SNAPSHOT_SCHEMA_VERSION) {
|
|
439
|
+
return await loadSnapshotV2(options.reader, options.session, options.analysisId, raw, options.signal);
|
|
440
|
+
}
|
|
441
|
+
return legacySnapshot(options.analysisId, raw);
|
|
442
|
+
}
|
|
443
|
+
async function loadSnapshotV2(reader, session, analysisId, raw, signal) {
|
|
444
|
+
const file = raw;
|
|
445
|
+
const issues = validateAgainstSchema(file, SNAPSHOT_FILE_V2_SCHEMA);
|
|
446
|
+
if (issues.length > 0) {
|
|
447
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `快照 ${analysisId} 结构不合法:${issues.slice(0, 4).join(';')}`);
|
|
448
|
+
}
|
|
449
|
+
const metadataBytes = Buffer.byteLength(JSON.stringify(file), 'utf8');
|
|
450
|
+
if (metadataBytes > SNAPSHOT_METADATA_HARD_BYTES) {
|
|
451
|
+
throw new AnalysisError('analysis_snapshot_too_large', `快照 ${analysisId} 元数据 ${metadataBytes} 字节,超过硬上限 ${SNAPSHOT_METADATA_HARD_BYTES}`);
|
|
452
|
+
}
|
|
453
|
+
for (const input of file.inputs) {
|
|
454
|
+
const content = await readJsonFile(reader, session, input.path, signal);
|
|
455
|
+
if (content === undefined) {
|
|
456
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `快照输入 ${input.source_ref} 缺失:${input.path}`);
|
|
457
|
+
}
|
|
458
|
+
const hashed = input.kind === 'profile' && content !== null && typeof content === 'object'
|
|
459
|
+
? content.profile
|
|
460
|
+
: content;
|
|
461
|
+
if (hashed === undefined) {
|
|
462
|
+
throw new AnalysisError('analysis_snapshot_corrupt', `快照输入 ${input.source_ref} 内容缺 profile 字段:${input.path}`);
|
|
463
|
+
}
|
|
464
|
+
const { digest, byteSize } = canonicalHash(hashed);
|
|
465
|
+
if (digest !== input.sha256 || byteSize !== input.byte_size) {
|
|
466
|
+
throw new AnalysisError('analysis_input_hash_mismatch', `输入 ${input.source_ref} 的内容与快照记录不一致(期望 ${input.sha256.slice(0, 12)}…/${input.byte_size} 字节,实际 ${digest.slice(0, 12)}…/${byteSize} 字节);快照或暂存副本被改动过`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
let inputsDir = inputsDirs.get(analysisId);
|
|
470
|
+
if (inputsDir === undefined && typeof reader.resolveWorkspacePath === 'function') {
|
|
471
|
+
try {
|
|
472
|
+
inputsDir = await reader.resolveWorkspacePath({ session, path: inputsRoot(analysisId), ...(signal === undefined ? {} : { signal }) });
|
|
473
|
+
}
|
|
474
|
+
catch {
|
|
475
|
+
inputsDir = undefined;
|
|
476
|
+
}
|
|
249
477
|
}
|
|
250
|
-
|
|
478
|
+
const dir = analysisDir(analysisId);
|
|
479
|
+
return {
|
|
480
|
+
...file,
|
|
481
|
+
input_fingerprint: file.input_fingerprint,
|
|
482
|
+
inputs: file.inputs,
|
|
483
|
+
temporal_mode: file.temporal_mode,
|
|
484
|
+
// Relative fallback matches `createSnapshot`: params-only modules never read `inputs/`, and a
|
|
485
|
+
// host restart must not make their snapshots unrunnable.
|
|
486
|
+
paths: { dir, inputs_dir: inputsDir ?? `${dir}/inputs` },
|
|
487
|
+
legacy: false,
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
function legacySnapshot(analysisId, raw) {
|
|
491
|
+
const file = raw;
|
|
492
|
+
return {
|
|
493
|
+
...file,
|
|
494
|
+
schema_version: 1,
|
|
495
|
+
temporal_mode: 'ex_post',
|
|
496
|
+
inputs: [],
|
|
497
|
+
paths: {
|
|
498
|
+
dir: analysisDir(analysisId),
|
|
499
|
+
...(typeof file.paths?.inputs_dir === 'string' ? { inputs_dir: file.paths.inputs_dir } : {}),
|
|
500
|
+
},
|
|
501
|
+
legacy: true,
|
|
502
|
+
};
|
|
251
503
|
}
|
|
252
504
|
/** Coverage summary returned to the model: counts and ranges only, never rows. */
|
|
253
505
|
export function snapshotCoverage(record) {
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import { type SessionLike } from '../data-collector/store.js';
|
|
2
2
|
import { type AnalysisErrorCode } from './types.js';
|
|
3
|
+
/** Env kill switch for the V2 snapshot contract (support/rollback only; never a settings field). */
|
|
4
|
+
export declare const ANALYSIS_V2_KILL_SWITCH_ENV = "CG_ANALYSIS_V2";
|
|
5
|
+
export declare function analysisContractV2Enabled(env?: NodeJS.ProcessEnv): boolean;
|
|
6
|
+
/** On-disk schema version: V2 files carry `schema_version: 2`, V1 files have no marker. */
|
|
7
|
+
export declare function schemaVersionOf(value: unknown): 1 | 2;
|
|
3
8
|
export declare const ANALYSIS_ROOT = "capital-analysis/runs";
|
|
4
9
|
export declare const SNAPSHOT_FILE = "snapshot.json";
|
|
5
10
|
export declare const RUN_FILE = "run.json";
|
|
6
11
|
export declare const ARTIFACT_FILE = "artifact.json";
|
|
12
|
+
export declare const ARTIFACTS_DIR = "artifacts";
|
|
7
13
|
export declare const REQUEST_FILE = "request.json";
|
|
8
14
|
export declare const RESULT_FILE = "result.json";
|
|
9
15
|
/** Opaque refs: the model never learns a filesystem path, only one of these. */
|
|
@@ -29,17 +35,37 @@ export interface AnalysisFileWriter {
|
|
|
29
35
|
path: string;
|
|
30
36
|
signal?: AbortSignal;
|
|
31
37
|
}): Promise<unknown>;
|
|
38
|
+
/** Absolute workspace path for a relative path; optional because snapshot creation returns one directly. */
|
|
39
|
+
resolveWorkspacePath?(input: {
|
|
40
|
+
session: SessionLike;
|
|
41
|
+
path: string;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
}): Promise<string>;
|
|
32
44
|
}
|
|
33
45
|
export declare function newAnalysisId(): string;
|
|
34
46
|
export declare function newModuleRunId(): string;
|
|
35
47
|
export declare const analysisDir: (analysisId: string) => string;
|
|
48
|
+
export declare const inputsRoot: (analysisId: string) => string;
|
|
36
49
|
export declare const inputsDir: (analysisId: string, kind: "datasets" | "profiles" | "evidence") => string;
|
|
37
50
|
export declare const moduleRunDir: (analysisId: string, moduleRunId: string) => string;
|
|
38
51
|
export declare const snapshotRef: (analysisId: string) => string;
|
|
39
52
|
export declare const runRef: (analysisId: string, moduleRunId: string) => string;
|
|
40
|
-
|
|
53
|
+
/** Latest ref when `revision` is omitted; `@<rev>` pins the immutable `artifacts/rev-<n>.json`. */
|
|
54
|
+
export declare const artifactRef: (analysisId: string, revision?: number) => string;
|
|
55
|
+
export declare const artifactLatestPath: (analysisId: string) => string;
|
|
56
|
+
/** Zero-padded so directory listings sort by revision; the ref itself uses the plain integer. */
|
|
57
|
+
export declare const artifactRevisionPath: (analysisId: string, revision: number) => string;
|
|
58
|
+
export declare const artifactRevisionFile: (revision: number) => string;
|
|
41
59
|
/** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
|
|
42
60
|
export declare function parseSnapshotRef(ref: unknown): string;
|
|
61
|
+
/**
|
|
62
|
+
* Parse `analysis_artifact:<id>` or the pinned `analysis_artifact:<id>@<rev>`. Only the id is needed
|
|
63
|
+
* by callers today; `parseArtifactRefParts` keeps the revision so a pinned ref can be resolved.
|
|
64
|
+
*/
|
|
65
|
+
export declare function parseArtifactRefParts(ref: unknown): {
|
|
66
|
+
analysisId: string;
|
|
67
|
+
revision?: number;
|
|
68
|
+
};
|
|
43
69
|
export declare function parseArtifactRef(ref: unknown): string;
|
|
44
70
|
/**
|
|
45
71
|
* Translate a store failure into an analysis error code. The store already names the object that
|
|
@@ -54,6 +80,8 @@ export declare function writeFiles(writer: AnalysisFileWriter, session: SessionL
|
|
|
54
80
|
signal?: AbortSignal;
|
|
55
81
|
overwrite?: boolean;
|
|
56
82
|
errorCode?: AnalysisErrorCode;
|
|
83
|
+
/** `createIfAbsent` hit an existing file: the caller owns the meaning (e.g. revision conflict). */
|
|
84
|
+
conflictCode?: AnalysisErrorCode;
|
|
57
85
|
what?: string;
|
|
58
86
|
}): Promise<Array<{
|
|
59
87
|
name: string;
|
package/lib/analysis/storage.js
CHANGED
|
@@ -12,10 +12,20 @@
|
|
|
12
12
|
import { randomUUID } from 'node:crypto';
|
|
13
13
|
import { DatasetStoreError } from '../data-collector/store.js';
|
|
14
14
|
import { AnalysisError } from './types.js';
|
|
15
|
+
/** Env kill switch for the V2 snapshot contract (support/rollback only; never a settings field). */
|
|
16
|
+
export const ANALYSIS_V2_KILL_SWITCH_ENV = 'CG_ANALYSIS_V2';
|
|
17
|
+
export function analysisContractV2Enabled(env = process.env) {
|
|
18
|
+
return env[ANALYSIS_V2_KILL_SWITCH_ENV] !== '0';
|
|
19
|
+
}
|
|
20
|
+
/** On-disk schema version: V2 files carry `schema_version: 2`, V1 files have no marker. */
|
|
21
|
+
export function schemaVersionOf(value) {
|
|
22
|
+
return value !== null && typeof value === 'object' && value.schema_version === 2 ? 2 : 1;
|
|
23
|
+
}
|
|
15
24
|
export const ANALYSIS_ROOT = 'capital-analysis/runs';
|
|
16
25
|
export const SNAPSHOT_FILE = 'snapshot.json';
|
|
17
26
|
export const RUN_FILE = 'run.json';
|
|
18
27
|
export const ARTIFACT_FILE = 'artifact.json';
|
|
28
|
+
export const ARTIFACTS_DIR = 'artifacts';
|
|
19
29
|
export const REQUEST_FILE = 'request.json';
|
|
20
30
|
export const RESULT_FILE = 'result.json';
|
|
21
31
|
/** Opaque refs: the model never learns a filesystem path, only one of these. */
|
|
@@ -29,11 +39,17 @@ export function newModuleRunId() {
|
|
|
29
39
|
return `module_run_${idSuffix()}`;
|
|
30
40
|
}
|
|
31
41
|
export const analysisDir = (analysisId) => `${ANALYSIS_ROOT}/${analysisId}`;
|
|
42
|
+
export const inputsRoot = (analysisId) => `${analysisDir(analysisId)}/inputs`;
|
|
32
43
|
export const inputsDir = (analysisId, kind) => `${analysisDir(analysisId)}/inputs/${kind}`;
|
|
33
44
|
export const moduleRunDir = (analysisId, moduleRunId) => `${analysisDir(analysisId)}/modules/${moduleRunId}`;
|
|
34
45
|
export const snapshotRef = (analysisId) => `analysis:${analysisId}`;
|
|
35
46
|
export const runRef = (analysisId, moduleRunId) => `analysis_run:${analysisId}/${moduleRunId}`;
|
|
36
|
-
|
|
47
|
+
/** Latest ref when `revision` is omitted; `@<rev>` pins the immutable `artifacts/rev-<n>.json`. */
|
|
48
|
+
export const artifactRef = (analysisId, revision) => revision === undefined ? `analysis_artifact:${analysisId}` : `analysis_artifact:${analysisId}@${revision}`;
|
|
49
|
+
export const artifactLatestPath = (analysisId) => `${analysisDir(analysisId)}/${ARTIFACT_FILE}`;
|
|
50
|
+
/** Zero-padded so directory listings sort by revision; the ref itself uses the plain integer. */
|
|
51
|
+
export const artifactRevisionPath = (analysisId, revision) => `${analysisDir(analysisId)}/${ARTIFACTS_DIR}/rev-${String(revision).padStart(4, '0')}.json`;
|
|
52
|
+
export const artifactRevisionFile = (revision) => `rev-${String(revision).padStart(4, '0')}.json`;
|
|
37
53
|
/** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
|
|
38
54
|
export function parseSnapshotRef(ref) {
|
|
39
55
|
const text = typeof ref === 'string' ? ref.trim() : '';
|
|
@@ -43,13 +59,26 @@ export function parseSnapshotRef(ref) {
|
|
|
43
59
|
}
|
|
44
60
|
return id;
|
|
45
61
|
}
|
|
46
|
-
|
|
62
|
+
/**
|
|
63
|
+
* Parse `analysis_artifact:<id>` or the pinned `analysis_artifact:<id>@<rev>`. Only the id is needed
|
|
64
|
+
* by callers today; `parseArtifactRefParts` keeps the revision so a pinned ref can be resolved.
|
|
65
|
+
*/
|
|
66
|
+
export function parseArtifactRefParts(ref) {
|
|
47
67
|
const text = typeof ref === 'string' ? ref.trim() : '';
|
|
48
|
-
const
|
|
49
|
-
|
|
68
|
+
const body = text.startsWith('analysis_artifact:') ? text.slice('analysis_artifact:'.length) : '';
|
|
69
|
+
const [id = '', revisionText, ...rest] = body.split('@');
|
|
70
|
+
if (rest.length > 0 || !ANALYSIS_ID.test(id)) {
|
|
50
71
|
throw new AnalysisError('analysis_snapshot_invalid', `分析产物引用无法识别:${JSON.stringify(text).slice(0, 120)}`);
|
|
51
72
|
}
|
|
52
|
-
|
|
73
|
+
if (revisionText === undefined)
|
|
74
|
+
return { analysisId: id };
|
|
75
|
+
if (!/^[1-9]\d{0,5}$/u.test(revisionText)) {
|
|
76
|
+
throw new AnalysisError('analysis_snapshot_invalid', `分析产物 revision 不合法:${JSON.stringify(text).slice(0, 120)}`);
|
|
77
|
+
}
|
|
78
|
+
return { analysisId: id, revision: Number(revisionText) };
|
|
79
|
+
}
|
|
80
|
+
export function parseArtifactRef(ref) {
|
|
81
|
+
return parseArtifactRefParts(ref).analysisId;
|
|
53
82
|
}
|
|
54
83
|
/**
|
|
55
84
|
* Translate a store failure into an analysis error code. The store already names the object that
|
|
@@ -80,7 +109,11 @@ export async function writeFiles(writer, session, dir, files, options = {}) {
|
|
|
80
109
|
});
|
|
81
110
|
}
|
|
82
111
|
catch (error) {
|
|
83
|
-
|
|
112
|
+
const what = options.what ?? `写入 ${dir} 失败`;
|
|
113
|
+
if (options.conflictCode !== undefined && error instanceof DatasetStoreError && error.code === 'workspace_conflict') {
|
|
114
|
+
throw new AnalysisError(options.conflictCode, `${what}:${error.message}`);
|
|
115
|
+
}
|
|
116
|
+
asAnalysisError(error, options.errorCode ?? 'analysis_input_invalid', what);
|
|
84
117
|
}
|
|
85
118
|
}
|
|
86
119
|
/** Read one JSON file; a missing file is `undefined` (callers decide whether that is fatal). */
|