@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.
Files changed (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +14 -5
  3. package/automation/package.json +1 -1
  4. package/chart-ui/package.json +1 -1
  5. package/config/package.json +1 -1
  6. package/lib/analysis/artifact.d.ts +35 -0
  7. package/lib/analysis/artifact.js +250 -0
  8. package/lib/analysis/registry.d.ts +16 -2
  9. package/lib/analysis/registry.js +133 -23
  10. package/lib/analysis/runtime.d.ts +46 -19
  11. package/lib/analysis/runtime.js +485 -116
  12. package/lib/analysis/schemas.d.ts +46 -0
  13. package/lib/analysis/schemas.js +260 -7
  14. package/lib/analysis/snapshot.d.ts +10 -3
  15. package/lib/analysis/snapshot.js +298 -46
  16. package/lib/analysis/storage.d.ts +29 -1
  17. package/lib/analysis/storage.js +39 -6
  18. package/lib/analysis/tools.js +270 -29
  19. package/lib/analysis/types.d.ts +257 -3
  20. package/lib/analysis/types.js +31 -1
  21. package/lib/analysis/validation.d.ts +37 -1
  22. package/lib/analysis/validation.js +315 -1
  23. package/lib/chart/tool.js +1 -0
  24. package/lib/data-collector/store.d.ts +7 -1
  25. package/lib/data-collector/store.js +14 -0
  26. package/lib/python-runtime/child-env.d.ts +4 -2
  27. package/lib/python-runtime/child-env.js +21 -14
  28. package/lib/python-runtime/manager.d.ts +8 -0
  29. package/lib/python-runtime/manager.js +30 -14
  30. package/lib/sources/tencent-http.js +9 -3
  31. package/lib/web-retriever/local-fetch.d.ts +1 -1
  32. package/lib/web-retriever/local-fetch.js +1 -1
  33. package/lib/web-retriever/wind-client.d.ts +1 -1
  34. package/lib/web-retriever/wind-client.js +1 -1
  35. package/package.json +2 -1
  36. package/plugin-page/README.en.md +1 -1
  37. package/plugin-page/README.zh.md +1 -1
  38. package/preset/capital-generation/agent.patch.yml +1 -1
  39. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
  40. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
  41. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
  42. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  43. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
  44. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  45. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
  46. package/python/analysis/lib/__init__.py +9 -0
  47. package/python/analysis/lib/errors.py +12 -0
  48. package/python/analysis/lib/eventstudy.py +164 -0
  49. package/python/analysis/lib/frames.py +95 -0
  50. package/python/analysis/lib/gaps.py +54 -0
  51. package/python/analysis/lib/jsonio.py +61 -0
  52. package/python/analysis/lib/metrics.py +147 -0
  53. package/python/analysis/lib/pit.py +84 -0
  54. package/python/analysis/lib/prices.py +140 -0
  55. package/python/analysis/lib/timeaxis.py +142 -0
  56. package/python/analysis/lib/version.py +3 -0
  57. package/python/analysis/modules/comps_valuation/module.py +26 -59
  58. package/python/analysis/modules/earnings_bridge/module.py +20 -77
  59. package/python/analysis/modules/event_study/LICENSE +21 -0
  60. package/python/analysis/modules/event_study/module.json +217 -0
  61. package/python/analysis/modules/event_study/module.py +979 -0
  62. package/python/analysis/modules/financial_quality/module.py +25 -88
  63. package/python/analysis/modules/hello/module.py +4 -0
  64. package/python/analysis/modules/kline_quality/module.py +26 -132
  65. package/python/analysis/modules/portfolio_stress/module.py +27 -112
  66. package/python/analysis/modules/returns_risk/module.json +108 -25
  67. package/python/analysis/modules/returns_risk/module.py +68 -227
  68. package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
  69. package/python/analysis/modules/simple_backtest/module.json +244 -36
  70. package/python/analysis/modules/simple_backtest/module.py +1146 -459
  71. package/python/analysis/modules/statement_integrity/module.py +35 -87
  72. package/python/analysis/modules/technical_indicators/module.py +33 -152
  73. package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
  74. package/python/worker.py +5 -0
  75. package/watchlist/package.json +1 -1
@@ -1,41 +1,125 @@
1
1
  /**
2
- * Static analysis-module registry: the whitelist and the version facts, nothing else.
2
+ * Static analysis-module registry: the whitelist, the version facts and the code hash, nothing else.
3
3
  *
4
4
  * Modules are never discovered by scanning a directory — a directory scan would turn "drop a file in
5
5
  * the package" into "run arbitrary code under the private interpreter". `module.json` is the single
6
6
  * manifest source; the entry only adds the resolved directory the worker gets.
7
+ *
8
+ * The code hash is what makes reuse honest: edit a module (or the shared primitives it imports)
9
+ * without bumping its version and the next run's fingerprint changes, so the old result is not reused.
7
10
  */
8
- import { readFileSync } from 'node:fs';
9
- import { join } from 'node:path';
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
13
+ import { join, relative } from 'node:path';
10
14
  import { fileURLToPath } from 'node:url';
11
15
  import { MODULE_DEFAULT_LIMITS } from './schemas.js';
16
+ import { stableStringify } from './snapshot.js';
12
17
  const MODULE_ROOT = fileURLToPath(new URL('../../python/analysis/modules/', import.meta.url));
18
+ const MODULE_LIB_ROOT = fileURLToPath(new URL('../../python/analysis/lib/', import.meta.url));
13
19
  /** Registered ids, in listing order. Adding a module means adding its id here. */
14
20
  const REGISTERED_MODULE_IDS = [
15
21
  'hello', 'financial_quality', 'returns_risk', 'scenario_sensitivity',
16
22
  'statement_integrity', 'kline_quality', 'valuation_sensitivity',
17
23
  'comps_valuation', 'earnings_bridge',
18
- 'technical_indicators', 'simple_backtest', 'portfolio_stress',
24
+ 'technical_indicators', 'simple_backtest', 'portfolio_stress', 'event_study',
19
25
  ];
20
- const cache = new Map();
21
- function readManifest(moduleId) {
22
- const cached = cache.get(moduleId);
26
+ const manifestCache = new Map();
27
+ const codeCache = new Map();
28
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
29
+ function walkFiles(root, current = root) {
30
+ let entries;
31
+ try {
32
+ entries = readdirSync(current, { withFileTypes: true });
33
+ }
34
+ catch {
35
+ return [];
36
+ }
37
+ const files = [];
38
+ for (const entry of entries) {
39
+ const path = join(current, entry.name);
40
+ if (entry.isDirectory())
41
+ files.push(...walkFiles(root, path));
42
+ else if (entry.isFile() && statSync(path).isFile())
43
+ files.push(relative(root, path).split('\\').join('/'));
44
+ }
45
+ return files.sort();
46
+ }
47
+ /** Deterministic digest of the shared-primitive tree; `null` when the package is absent. */
48
+ function libTreeDigest() {
49
+ try {
50
+ if (!statSync(MODULE_LIB_ROOT).isDirectory())
51
+ return null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ const files = walkFiles(MODULE_LIB_ROOT);
57
+ if (files.length === 0)
58
+ return null;
59
+ return sha256(stableStringify(files.map((file) => [file, sha256(readFileSync(join(MODULE_LIB_ROOT, file), 'utf8'))])));
60
+ }
61
+ /**
62
+ * Hash the module bytes for the run fingerprint. Cached per directory: module code is fixed for the
63
+ * life of the process; `resetAnalysisModuleCache` clears it for fixture rewrites.
64
+ */
65
+ export function moduleCodeFacts(entry) {
66
+ const cached = codeCache.get(entry.dir);
23
67
  if (cached !== undefined)
24
68
  return cached;
25
- const dir = join(MODULE_ROOT, moduleId);
26
- let parsed;
27
- try {
28
- parsed = JSON.parse(readFileSync(join(dir, 'module.json'), 'utf8'));
69
+ const entrypoint = readFileSync(join(entry.dir, entry.entrypoint), 'utf8');
70
+ const manifestFile = join(entry.dir, 'module.json');
71
+ const manifestDigest = existsSync(manifestFile)
72
+ ? sha256(readFileSync(manifestFile, 'utf8'))
73
+ // A test fixture may hand a manifest without a file on disk; the normalized object is the contract.
74
+ : sha256(stableStringify(entry.manifest));
75
+ const libDigest = libTreeDigest();
76
+ const facts = {
77
+ module_code_hash: sha256(stableStringify({
78
+ entrypoint: sha256(entrypoint),
79
+ manifest: manifestDigest,
80
+ lib: libDigest,
81
+ })),
82
+ entrypoint_sha256: sha256(entrypoint),
83
+ manifest_sha256: manifestDigest,
84
+ lib_digest: libDigest,
85
+ };
86
+ codeCache.set(entry.dir, facts);
87
+ return facts;
88
+ }
89
+ /** `required_fields` entries are request paths, so a manifest cannot ask for an unknown field. */
90
+ const REQUIRED_FIELD = /^(?:task_id|as_of|inputs\.(?:datasets|profiles|evidence)|params\.[A-Za-z0-9_]{1,64})$/u;
91
+ function normalizeLimits(value, moduleId) {
92
+ const declared = value !== null && typeof value === 'object' && !Array.isArray(value)
93
+ ? value
94
+ : {};
95
+ const limits = { ...MODULE_DEFAULT_LIMITS };
96
+ for (const [key, raw] of Object.entries(declared)) {
97
+ if (!(key in MODULE_DEFAULT_LIMITS)) {
98
+ throw new Error(`分析模块 ${moduleId} 的 manifest 声明了未知 limits.${key}(只认 ${Object.keys(MODULE_DEFAULT_LIMITS).join(' / ')})`);
99
+ }
100
+ if (!Number.isSafeInteger(raw) || raw <= 0) {
101
+ throw new Error(`分析模块 ${moduleId} 的 limits.${key} 必须是正整数`);
102
+ }
103
+ const ceiling = MODULE_DEFAULT_LIMITS[key];
104
+ if (raw > ceiling) {
105
+ throw new Error(`分析模块 ${moduleId} 的 limits.${key}=${String(raw)} 放宽了默认上限 ${ceiling};limits 只能收紧`);
106
+ }
107
+ limits[key] = raw;
29
108
  }
30
- catch (error) {
31
- throw new Error(`分析模块 ${moduleId} 的 module.json 读不到(${error instanceof Error ? error.message : String(error)})`);
109
+ return limits;
110
+ }
111
+ function normalizeReuse(value, moduleId) {
112
+ const raw = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
113
+ for (const key of Object.keys(raw)) {
114
+ if (key !== 'allow_partial' && key !== 'allow_blocked') {
115
+ throw new Error(`分析模块 ${moduleId} 的 manifest 声明了未知 reuse.${key}(只认 allow_partial / allow_blocked)`);
116
+ }
117
+ if (typeof raw[key] !== 'boolean')
118
+ throw new Error(`分析模块 ${moduleId} 的 reuse.${key} 必须是布尔值`);
32
119
  }
33
- const manifest = normalizeManifest(parsed, moduleId);
34
- const entry = { manifest, dir, entrypoint: manifest.entrypoint };
35
- cache.set(moduleId, entry);
36
- return entry;
120
+ return { allow_partial: raw.allow_partial === true, allow_blocked: raw.allow_blocked === true };
37
121
  }
38
- function normalizeManifest(value, moduleId) {
122
+ export function normalizeManifest(value, moduleId) {
39
123
  const raw = value;
40
124
  if (typeof raw !== 'object' || raw === null || raw.id !== moduleId) {
41
125
  throw new Error(`分析模块 ${moduleId} 的 manifest 缺失或 id 不符`);
@@ -48,7 +132,12 @@ function normalizeManifest(value, moduleId) {
48
132
  }
49
133
  if (!Array.isArray(raw.capabilities))
50
134
  throw new Error(`分析模块 ${moduleId} 的 manifest 缺少 capabilities`);
51
- const limits = { ...MODULE_DEFAULT_LIMITS, ...(raw.limits ?? {}) };
135
+ const requiredFields = [...(raw.required_fields ?? [])];
136
+ for (const field of requiredFields) {
137
+ if (typeof field !== 'string' || !REQUIRED_FIELD.test(field)) {
138
+ throw new Error(`分析模块 ${moduleId} 的 required_fields 含非法字段 ${JSON.stringify(field)}(只认 task_id / as_of / inputs.* / params.<key>)`);
139
+ }
140
+ }
52
141
  return {
53
142
  id: moduleId,
54
143
  version: raw.version,
@@ -57,15 +146,35 @@ function normalizeManifest(value, moduleId) {
57
146
  description: raw.description,
58
147
  roles: [...raw.roles],
59
148
  capabilities: [...raw.capabilities],
60
- required_fields: [...(raw.required_fields ?? [])],
149
+ required_fields: requiredFields,
61
150
  input_schema: raw.input_schema ?? {},
62
151
  output_schema: raw.output_schema ?? {},
63
152
  assumptions: [...(raw.assumptions ?? [])],
64
153
  applicability: [...(raw.applicability ?? [])],
65
- limits,
154
+ limits: normalizeLimits(raw.limits, moduleId),
155
+ temporal_aware: raw.temporal_aware === true,
156
+ ...(typeof raw.display_name === 'string' && raw.display_name !== '' ? { display_name: raw.display_name } : {}),
157
+ reuse: normalizeReuse(raw.reuse, moduleId),
66
158
  provenance: raw.provenance ?? { source_type: 'original', license: 'MIT' },
67
159
  };
68
160
  }
161
+ function readManifest(moduleId) {
162
+ const cached = manifestCache.get(moduleId);
163
+ if (cached !== undefined)
164
+ return cached;
165
+ const dir = join(MODULE_ROOT, moduleId);
166
+ let parsed;
167
+ try {
168
+ parsed = JSON.parse(readFileSync(join(dir, 'module.json'), 'utf8'));
169
+ }
170
+ catch (error) {
171
+ throw new Error(`分析模块 ${moduleId} 的 module.json 读不到(${error instanceof Error ? error.message : String(error)})`);
172
+ }
173
+ const manifest = normalizeManifest(parsed, moduleId);
174
+ const entry = { manifest, dir, entrypoint: manifest.entrypoint };
175
+ manifestCache.set(moduleId, entry);
176
+ return entry;
177
+ }
69
178
  /** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
70
179
  export function listAnalysisModules() {
71
180
  return REGISTERED_MODULE_IDS.map((moduleId) => readManifest(moduleId));
@@ -75,7 +184,8 @@ export function analysisModuleById(moduleId) {
75
184
  return undefined;
76
185
  return readManifest(moduleId);
77
186
  }
78
- /** Test-only: drop the manifest cache so a fixture rewrite is visible. */
187
+ /** Test-only: drop the manifest and code-hash caches so a fixture rewrite is visible. */
79
188
  export function resetAnalysisModuleCache() {
80
- cache.clear();
189
+ manifestCache.clear();
190
+ codeCache.clear();
81
191
  }
@@ -2,17 +2,23 @@
2
2
  * Analysis execution: build the module request, run it under the private interpreter, validate the
3
3
  * result and persist it.
4
4
  *
5
- * Two gates are enforced here rather than in the worker, because they are the host's facts:
6
- * - concurrency: at most two analysis processes globally, and one module run at a time per snapshot
7
- * (two runs on one snapshot would race the run index);
8
- * - result contract: the worker's output must satisfy the manifest schema and be lossless JSON.
5
+ * Three gates are enforced here rather than in the worker, because they are the host's facts:
6
+ * - concurrency: at most two analysis processes globally, one module run at a time per snapshot;
7
+ * - queueing: a run that waits longer than `ANALYSIS_QUEUE_WAIT_MS` fails as `analysis_queue_timeout`
8
+ * and an already-aborted call never starts a process;
9
+ * - lifecycle: every run has a terminal row in `run.json` written *before* the error is thrown, so a
10
+ * timeout or cancellation can be audited afterwards instead of vanishing.
9
11
  */
10
12
  import type { Context } from '@deepseek-ai/cordis';
11
13
  import type { SessionLike } from '../data-collector/store.js';
12
- import type { AnalysisModuleEntry } from './registry.js';
13
- import type { SnapshotRecord } from './snapshot.js';
14
+ import { type AnalysisModuleEntry } from './registry.js';
14
15
  import { type AnalysisFileWriter } from './storage.js';
15
- import { type ModuleResult } from './types.js';
16
+ import { type DatasetRefLike, type EvidenceItem, type ModuleResult, type ModuleRunRecordV2, type ProfileRefLike, type TemporalMode } from './types.js';
17
+ /** Runtime facts that identify the interpreter; part of `run_fingerprint`. */
18
+ export interface AnalysisRuntimeIdentity {
19
+ readonly python_version: string;
20
+ readonly packs?: Readonly<Record<string, string>>;
21
+ }
16
22
  /** The slice of `pythonRuntime` the analysis family uses. Resolved per call, never memoized. */
17
23
  export interface AnalysisRuntimeLike {
18
24
  runAnalysisModule(options: {
@@ -33,6 +39,8 @@ export interface AnalysisRuntimeLike {
33
39
  pythonVersion: string;
34
40
  durationMs: number;
35
41
  }>;
42
+ /** Optional: test doubles omit it, and their fingerprints then use the `unknown` runtime. */
43
+ analysisRuntimeIdentity?(): Promise<AnalysisRuntimeIdentity>;
36
44
  }
37
45
  /**
38
46
  * Resolve the runtime service at call time: the row is opt-in and the pack may be missing, so a
@@ -42,41 +50,58 @@ export interface AnalysisRuntimeLike {
42
50
  export declare function analysisRuntimeFrom(ctx: Context): AnalysisRuntimeLike;
43
51
  /** Test-only: reset the concurrency counters between cases. */
44
52
  export declare function resetAnalysisRuntimeState(): void;
45
- export interface AnalysisRunRecord {
46
- readonly module_run_id: string;
47
- readonly module_id: string;
48
- readonly module_version: string;
49
- readonly params_digest: string;
50
- readonly run_fingerprint: string;
51
- readonly status: ModuleResult['status'];
52
- readonly created_at: number;
53
- readonly reused_from?: string;
54
- }
53
+ /** One row per `module_run_id` in `run.json`; the row moves queued/running → terminal, never deleted. */
55
54
  export interface AnalysisRunIndex {
55
+ readonly schema_version?: 2;
56
56
  readonly analysis_id: string;
57
57
  readonly input_fingerprint: string;
58
- readonly runs: readonly AnalysisRunRecord[];
58
+ readonly runs: readonly ModuleRunRecordV2[];
59
+ }
60
+ /** The slice of a snapshot a run needs; both a freshly created record and a loaded V2 snapshot fit. */
61
+ export interface RunnableSnapshot {
62
+ readonly analysis_id: string;
63
+ readonly task_id: string;
64
+ readonly as_of: string;
65
+ readonly dataset_refs: readonly DatasetRefLike[];
66
+ readonly profile_refs: readonly ProfileRefLike[];
67
+ readonly evidence: readonly EvidenceItem[];
68
+ readonly input_fingerprint: string;
69
+ readonly temporal_mode?: TemporalMode;
70
+ readonly data_cutoff?: string;
71
+ readonly paths: {
72
+ readonly inputs_dir?: string;
73
+ };
74
+ readonly legacy?: boolean;
59
75
  }
60
76
  export interface RunModuleOptions {
61
77
  writer: AnalysisFileWriter;
62
78
  runtime: AnalysisRuntimeLike;
63
79
  session: SessionLike;
64
- snapshot: SnapshotRecord;
80
+ snapshot: RunnableSnapshot;
65
81
  module: AnalysisModuleEntry;
66
82
  params: Readonly<Record<string, unknown>>;
67
83
  signal?: AbortSignal;
68
84
  now?: number;
85
+ /** Injectable clock and queue budget: tests need deterministic timestamps without sleeping 120s. */
86
+ clock?: () => number;
87
+ queueWaitMs?: number;
69
88
  }
70
89
  export interface RunModuleOutcome {
71
90
  readonly analysis_run_ref: string;
72
91
  readonly module_id: string;
73
92
  readonly module_version: string;
93
+ readonly module_code_hash: string;
74
94
  readonly status: ModuleResult['status'];
75
95
  readonly summary: string;
76
96
  readonly metrics: Record<string, unknown>;
77
97
  readonly assumptions: readonly string[];
98
+ readonly methodology: readonly string[];
78
99
  readonly limitations: readonly string[];
79
100
  readonly data_gaps: readonly string[];
101
+ readonly output_refs: readonly string[];
102
+ readonly sensitivity: Readonly<Record<string, unknown>>;
103
+ readonly simulation?: ModuleResult['simulation'];
104
+ readonly event_study?: ModuleResult['event_study'];
80
105
  readonly validation: {
81
106
  readonly status: 'pass' | 'warning';
82
107
  readonly issues: readonly unknown[];
@@ -85,3 +110,5 @@ export interface RunModuleOutcome {
85
110
  }
86
111
  /** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
87
112
  export declare function runModuleOnSnapshot(options: RunModuleOptions): Promise<RunModuleOutcome>;
113
+ export declare function readRunIndex(writer: AnalysisFileWriter, session: SessionLike, analysisId: string, signal?: AbortSignal): Promise<AnalysisRunIndex>;
114
+ export declare function writeRunIndex(writer: AnalysisFileWriter, session: SessionLike, analysisId: string, index: AnalysisRunIndex, signal?: AbortSignal): Promise<void>;