@v587d/capital-generation 2.31.8 → 2.32.1

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 (76) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +11 -7
  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/ftshare-rest.js +1 -1
  31. package/lib/sources/tencent-http.js +210 -53
  32. package/lib/web-retriever/local-fetch.d.ts +1 -1
  33. package/lib/web-retriever/local-fetch.js +1 -1
  34. package/lib/web-retriever/wind-client.d.ts +1 -1
  35. package/lib/web-retriever/wind-client.js +1 -1
  36. package/package.json +2 -1
  37. package/plugin-page/README.en.md +1 -1
  38. package/plugin-page/README.zh.md +1 -1
  39. package/preset/capital-generation/agent.patch.yml +1 -1
  40. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
  41. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
  42. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
  43. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  44. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
  45. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  46. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
  47. package/python/analysis/lib/__init__.py +9 -0
  48. package/python/analysis/lib/errors.py +12 -0
  49. package/python/analysis/lib/eventstudy.py +164 -0
  50. package/python/analysis/lib/frames.py +95 -0
  51. package/python/analysis/lib/gaps.py +54 -0
  52. package/python/analysis/lib/jsonio.py +61 -0
  53. package/python/analysis/lib/metrics.py +147 -0
  54. package/python/analysis/lib/pit.py +84 -0
  55. package/python/analysis/lib/prices.py +140 -0
  56. package/python/analysis/lib/timeaxis.py +142 -0
  57. package/python/analysis/lib/version.py +3 -0
  58. package/python/analysis/modules/comps_valuation/module.py +26 -59
  59. package/python/analysis/modules/earnings_bridge/module.py +20 -77
  60. package/python/analysis/modules/event_study/LICENSE +21 -0
  61. package/python/analysis/modules/event_study/module.json +217 -0
  62. package/python/analysis/modules/event_study/module.py +979 -0
  63. package/python/analysis/modules/financial_quality/module.py +25 -88
  64. package/python/analysis/modules/hello/module.py +4 -0
  65. package/python/analysis/modules/kline_quality/module.py +26 -132
  66. package/python/analysis/modules/portfolio_stress/module.py +27 -112
  67. package/python/analysis/modules/returns_risk/module.json +108 -25
  68. package/python/analysis/modules/returns_risk/module.py +68 -227
  69. package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
  70. package/python/analysis/modules/simple_backtest/module.json +244 -36
  71. package/python/analysis/modules/simple_backtest/module.py +1146 -459
  72. package/python/analysis/modules/statement_integrity/module.py +35 -87
  73. package/python/analysis/modules/technical_indicators/module.py +33 -152
  74. package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
  75. package/python/worker.py +5 -0
  76. package/watchlist/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { HEADLINE_MAX_CHARS, MAX_CLAIMS, MAX_PEER_EXCHANGES, MAX_SCENARIOS, STATEMENT_MAX_CHARS, THESIS_MAX_CHARS } from './schemas.js';
1
+ import { GAP_PREFIXES, HEADLINE_MAX_CHARS, MAX_CLAIMS, MAX_PEER_EXCHANGES, MAX_SCENARIOS, STATEMENT_MAX_CHARS, THESIS_MAX_CHARS } from './schemas.js';
2
2
  /** Subset of JSON Schema used by the protocol: types, properties, required, items, enum, bounds. */
3
3
  export function validateAgainstSchema(value, schema, path = '$') {
4
4
  if (schema === undefined || Object.keys(schema).length === 0)
@@ -138,6 +138,18 @@ export function validateModuleResult(value, manifest) {
138
138
  issues.push({ code: 'analysis_output_invalid', severity: 'error', field, detail: `${label}里不能有空串或非字符串` });
139
139
  }
140
140
  }
141
+ // §5.10: data gaps are protocol vocabulary. A free-text gap would be uncountable downstream.
142
+ for (const gap of Array.isArray(result.data_gaps) ? result.data_gaps : []) {
143
+ const ok = typeof gap === 'string' && GAP_PREFIXES.some((prefix) => gap.startsWith(`${prefix}: `));
144
+ if (!ok) {
145
+ issues.push({
146
+ code: 'analysis_output_invalid',
147
+ severity: 'error',
148
+ field: 'data_gaps',
149
+ detail: `数据缺口必须以 ${GAP_PREFIXES.join(' / ')} 之一开头:${String(gap).slice(0, 80)}`,
150
+ });
151
+ }
152
+ }
141
153
  return { ok: issues.every((issue) => issue.severity !== 'error'), issues, result };
142
154
  }
143
155
  const UNIT_CONSTANTS = new Set([1e4, 1e6, 1e8, 1e12]);
@@ -153,6 +165,28 @@ const SECURITY_CODE = /^(?:0|[3-9])\d{5}$/u;
153
165
  const COUNT_CLASSIFIER = /^\s*[个条项期只家次类轮档组段页册笔位名张份套种年]/u;
154
166
  /** Index short-name numbers that must never be read as measured values. */
155
167
  const INDEX_NAME_VALUES = new Set([50, 100, 300, 500, 1000]);
168
+ /**
169
+ * Plan §4 invariant 8 / Q-01 / §M6-4: a historical simulation may not be described as live validation,
170
+ * a proven executable strategy or a guaranteed return, and an event study may not turn a statistical
171
+ * association into causal language. Negated sentences ("不是实盘验证") are allowed — the point is the
172
+ * claim, not the word.
173
+ */
174
+ const SIMULATION_OVERCLAIM = /实盘验证|已证明可执行|保证收益|稳赚不赔|无风险套利|必赚|稳赚/gu;
175
+ /** `公告/事件 … 导致/造成 … 股价/上涨/收益` and `证明/证实 … 因果` are the banned event-study moves. */
176
+ const EVENT_OVERCLAIM = /因果(?:关系)?(?:成立|确立|已证明)|(?:证明|证实|确认)[^。;\n]{0,12}(?:公告|事件)[^。;\n]{0,12}(?:因果|导致|造成|引起)|(?:公告|事件)[^。;\n]{0,10}(?:导致|造成|引起)[^。;\n]{0,8}(?:股价|上涨|下跌|超额|收益)/gu;
177
+ const NEGATION = /不|非|未|无|没有|不是|不算|并非|禁止|无法/u;
178
+ const OVERCLAIM_RULES = [
179
+ {
180
+ code: 'simulation_overclaim',
181
+ pattern: SIMULATION_OVERCLAIM,
182
+ detail: (match) => `含过度表述「${match}」:历史模拟不得写成实盘验证、已证明可执行或保证收益`,
183
+ },
184
+ {
185
+ code: 'event_overclaim',
186
+ pattern: EVENT_OVERCLAIM,
187
+ detail: (match) => `含过度表述「${match}」:事件研究不得把统计关联写成因果关系或确定性影响`,
188
+ },
189
+ ];
156
190
  /** Numeric tokens with just enough context to honour the exemption set. */
157
191
  export function numberTokens(text) {
158
192
  const tokens = [];
@@ -260,6 +294,24 @@ function unmatchedNumbers(text, anchors, calculations) {
260
294
  }
261
295
  return misses;
262
296
  }
297
+ function overclaimIssues(texts) {
298
+ const issues = [];
299
+ for (const { field, text } of texts) {
300
+ for (const sentence of text.split(/[。;;!!??\n]/u)) {
301
+ if (NEGATION.test(sentence))
302
+ continue;
303
+ for (const rule of OVERCLAIM_RULES) {
304
+ const match = rule.pattern.exec(sentence);
305
+ rule.pattern.lastIndex = 0;
306
+ if (match === null)
307
+ continue;
308
+ issues.push({ code: rule.code, severity: 'error', field, detail: rule.detail(match[0]) });
309
+ break;
310
+ }
311
+ }
312
+ }
313
+ return issues;
314
+ }
263
315
  function claimIssues(claim, path, tier1, tier2) {
264
316
  if (typeof claim?.statement === 'string' && claim.statement.length > STATEMENT_MAX_CHARS) {
265
317
  tier1.push({ code: 'analysis_result_too_large', severity: 'error', field: `${path}.statement`, detail: `单条 statement 超过 ${STATEMENT_MAX_CHARS} 字符` });
@@ -267,6 +319,33 @@ function claimIssues(claim, path, tier1, tier2) {
267
319
  if (typeof claim?.confidence_basis !== 'string' || claim.confidence_basis.trim() === '') {
268
320
  tier2.push({ code: 'confidence_basis_missing', severity: 'warning', field: `${path}.confidence_basis`, detail: 'confidence 必须带一句依据' });
269
321
  }
322
+ // G4 (plan §5.7): causal strength is a claim about what the evidence supports, so it has to agree
323
+ // with the claim type and, for the strongest level, come with a stated falsifier.
324
+ const strength = claim?.causal_strength;
325
+ if (strength === 'causal_with_assumptions' && (typeof claim.falsifier !== 'string' || claim.falsifier.trim() === '')) {
326
+ tier1.push({
327
+ code: 'causal_falsifier_missing',
328
+ severity: 'error',
329
+ field: `${path}.falsifier`,
330
+ detail: '因果强度写 causal_with_assumptions 时必须给出能推翻该判断的观察(falsifier)',
331
+ });
332
+ }
333
+ if ((claim.type === 'fact' || claim.type === 'scenario') && strength !== undefined && strength !== 'descriptive') {
334
+ tier1.push({
335
+ code: 'claim_type_conflict',
336
+ severity: 'error',
337
+ field: `${path}.causal_strength`,
338
+ detail: `${claim.type} 型论据只陈述事实或情景,只能写 descriptive(实际 ${strength})`,
339
+ });
340
+ }
341
+ if (claim.type === 'assumption' && (strength === 'associational' || strength === 'causal_with_assumptions')) {
342
+ tier1.push({
343
+ code: 'claim_type_conflict',
344
+ severity: 'error',
345
+ field: `${path}.causal_strength`,
346
+ detail: `assumption 型论据不是证据,不能声称 ${strength}`,
347
+ });
348
+ }
270
349
  }
271
350
  /**
272
351
  * Artifact validation in the three tiers of the design (Tier 1 rejects, Tier 2 downgrades to
@@ -320,6 +399,16 @@ export function validateArtifact(artifact, snapshot) {
320
399
  if (Array.isArray(artifact.limitations) && artifact.limitations.length === 0) {
321
400
  tier2.push({ code: 'limitations_empty', severity: 'warning', field: 'limitations', detail: 'limitations 为空:至少写明一条口径或数据限制' });
322
401
  }
402
+ // Invariant 7 / R-04: a conclusion that still carries unresolved data gaps is at most `partial`;
403
+ // claiming `completed` while listing gaps is the exact overclaim the contract forbids.
404
+ if (artifact.status === 'completed' && (artifact.unresolved_gaps?.length ?? 0) > 0) {
405
+ tier2.push({
406
+ code: 'completed_with_gaps',
407
+ severity: 'warning',
408
+ field: 'unresolved_gaps',
409
+ detail: `还有 ${artifact.unresolved_gaps.length} 条未解决的数据缺口,status 最多 partial`,
410
+ });
411
+ }
323
412
  // Refs must exist inside this snapshot.
324
413
  const datasetIds = new Set(snapshot.dataset_refs.map((item) => item.dataset_id));
325
414
  const profileIds = new Set(snapshot.profile_refs.map((item) => item.profile_id));
@@ -359,6 +448,10 @@ export function validateArtifact(artifact, snapshot) {
359
448
  }
360
449
  }
361
450
  for (const [index, calculation] of (artifact.calculations ?? []).entries()) {
451
+ // A run-bound calculation was read from `result.json` by the host; that is a stronger proof than
452
+ // an anchor, so it does not need a second one (only legacy/hand-written values still do).
453
+ if (typeof calculation.analysis_run_ref === 'string' && calculation.analysis_run_ref !== '')
454
+ continue;
362
455
  const known = anchors.some((anchor) => Math.abs(anchor.value - calculation.value) <= tolerance(anchor.precision));
363
456
  if (!known) {
364
457
  tier2.push({ code: 'calculation_without_anchor', severity: 'warning', field: `calculations[${index}]`, detail: `计算结果 ${calculation.metric}=${calculation.value} 没有对应锚点` });
@@ -387,5 +480,226 @@ export function validateArtifact(artifact, snapshot) {
387
480
  if ((artifact.alternative_explanations ?? []).length === 0) {
388
481
  tier3.push({ code: 'no_alternative_explanation', severity: 'notice', field: 'alternative_explanations', detail: '没有替代解释:审阅者会问"还可能是别的什么"' });
389
482
  }
483
+ // G5 (plan §5.7): simulation validity downgrades, it never silently passes. A grade typed by the
484
+ // model cannot appear here — the host copies the block from the cited run.
485
+ const simulation = artifact.simulation;
486
+ const citesBacktest = (artifact.calculations ?? []).some((item) => item.module_id === 'simple_backtest')
487
+ || (artifact.methods_used ?? []).some((item) => item.module_id === 'simple_backtest');
488
+ if (citesBacktest && simulation === undefined) {
489
+ tier2.push({
490
+ code: 'simulation_missing',
491
+ severity: 'warning',
492
+ field: 'simulation_run_ref',
493
+ detail: '引用了 simple_backtest 但没有用 simulation_run_ref 引用该 run:模拟等级与审计缺失,最多 partial',
494
+ });
495
+ }
496
+ if (simulation !== undefined) {
497
+ if (simulation.grade === 'insufficient_data') {
498
+ tier2.push({ code: 'simulation_insufficient_data', severity: 'warning', field: 'simulation', detail: '模拟等级是 insufficient_data:结论最多 partial' });
499
+ }
500
+ if (simulation.audit?.status === 'FAIL') {
501
+ tier2.push({ code: 'simulation_audit_failed', severity: 'warning', field: 'simulation.audit', detail: '模拟审计 FAIL:结论最多 partial,不能写成可执行结果' });
502
+ }
503
+ if (simulation.audit?.status === 'WARN' && (simulation.audit.uncovered_risks?.length ?? 0) === 0) {
504
+ tier2.push({ code: 'simulation_risks_undisclosed', severity: 'warning', field: 'simulation.audit', detail: '审计 WARN 但没有列出未覆盖风险' });
505
+ }
506
+ }
507
+ // G6 (plan §M6-4/§M6-5): the event study is the only evidence for a claim about an announcement's
508
+ // effect, so its facts downgrade the artifact instead of silently passing. A single event (or no
509
+ // valid sample) supports descriptive statistics only — a causal claim on top of it is hard-rejected.
510
+ const eventStudy = artifact.event_study;
511
+ const citesEventStudy = (artifact.calculations ?? []).some((item) => item.module_id === 'event_study')
512
+ || (artifact.methods_used ?? []).some((item) => item.module_id === 'event_study');
513
+ if (citesEventStudy && eventStudy === undefined) {
514
+ tier2.push({
515
+ code: 'event_study_missing',
516
+ severity: 'warning',
517
+ field: 'event_study_run_ref',
518
+ detail: '引用了 event_study 但没有用 event_study_run_ref 引用该 run:事件窗、有效样本与因果强度缺失,最多 partial',
519
+ });
520
+ }
521
+ if (eventStudy !== undefined) {
522
+ if (eventStudy.sample_size <= 0) {
523
+ tier2.push({ code: 'event_study_insufficient_data', severity: 'warning', field: 'event_study', detail: '有效事件样本为 0:结论最多 partial,不得输出事件窗结论' });
524
+ }
525
+ if (eventStudy.audit?.status === 'FAIL') {
526
+ tier2.push({ code: 'event_study_audit_failed', severity: 'warning', field: 'event_study.audit', detail: '事件研究审计 FAIL:结论最多 partial' });
527
+ }
528
+ if ((artifact.alternative_explanations ?? []).length === 0) {
529
+ tier2.push({ code: 'event_study_risks_undisclosed', severity: 'warning', field: 'alternative_explanations', detail: '引用事件研究但没有列出替代解释:同期市场、其他事件与预期都可能解释价格变化' });
530
+ }
531
+ if (eventStudy.causal_strength === 'descriptive') {
532
+ const causal = claims.find((claim) => claim?.causal_strength === 'causal_with_assumptions');
533
+ if (causal !== undefined) {
534
+ tier1.push({
535
+ code: 'event_overclaim',
536
+ severity: 'error',
537
+ field: causal.claim_id,
538
+ detail: `事件研究的有效样本 ${eventStudy.sample_size} 个、因果强度为 descriptive:claim ${causal.claim_id} 不能标成 causal_with_assumptions`,
539
+ });
540
+ }
541
+ }
542
+ }
543
+ // Overclaim scan covers the conclusion layer; module limitations are not model text.
544
+ tier1.push(...overclaimIssues([
545
+ { field: 'headline', text: artifact.headline ?? '' },
546
+ { field: 'thesis', text: artifact.thesis ?? '' },
547
+ ...claims.map((claim, index) => ({ field: `claims[${index}].statement`, text: claim.statement ?? '' })),
548
+ ]));
390
549
  return { tier1, tier2, tier3 };
391
550
  }
551
+ const RUN_REF = /^analysis_run:([a-z0-9_]+)\/([a-z0-9_]+)$/u;
552
+ /** Parse `analysis_run:<analysis_id>/<module_run_id>`; the binding code is the only parser. */
553
+ export function parseRunRef(ref) {
554
+ const parsed = RUN_REF.exec(ref);
555
+ return parsed === null ? undefined : { analysisId: parsed[1], moduleRunId: parsed[2] };
556
+ }
557
+ /** A run that did not produce a result is not a source of numbers, whatever its failure mode was. */
558
+ const CITABLE_STATUSES = new Set(['completed', 'partial', 'blocked']);
559
+ function inputRefsOf(request) {
560
+ const ids = [];
561
+ for (const item of request?.inputs?.datasets ?? []) {
562
+ if (typeof item?.dataset_id === 'string' && item.dataset_id !== '')
563
+ ids.push(item.dataset_id);
564
+ }
565
+ for (const item of request?.inputs?.profiles ?? []) {
566
+ if (typeof item?.profile_id === 'string' && item.profile_id !== '')
567
+ ids.push(item.profile_id);
568
+ }
569
+ return ids;
570
+ }
571
+ export async function bindCalculations(raw, context, methodsUsed) {
572
+ const issues = [];
573
+ const calculations = [];
574
+ const seenIds = new Set();
575
+ for (const calculation of raw) {
576
+ if (seenIds.has(calculation.calculation_id)) {
577
+ issues.push({ code: 'analysis_metric_binding_invalid', detail: `calculation_id ${calculation.calculation_id} 重复` });
578
+ continue;
579
+ }
580
+ seenIds.add(calculation.calculation_id);
581
+ const parsed = RUN_REF.exec(calculation.analysis_run_ref);
582
+ if (parsed === null || parsed[1] !== context.analysis_id) {
583
+ issues.push({
584
+ code: 'analysis_run_binding_mismatch',
585
+ detail: `${calculation.calculation_id} 的 analysis_run_ref 不属于本快照:${calculation.analysis_run_ref.slice(0, 120)}`,
586
+ });
587
+ continue;
588
+ }
589
+ const runId = parsed[2];
590
+ const record = context.runs.find((item) => item.module_run_id === runId);
591
+ if (record === undefined) {
592
+ issues.push({
593
+ code: 'analysis_run_not_found',
594
+ detail: `${calculation.calculation_id} 引用的 run ${runId} 不在 run.json 索引里(先 run_analysis 再引用回执里的 ref)`,
595
+ });
596
+ continue;
597
+ }
598
+ if (!CITABLE_STATUSES.has(record.status)) {
599
+ issues.push({
600
+ code: 'analysis_run_binding_mismatch',
601
+ detail: `${calculation.calculation_id} 引用的 run 状态是 ${record.status},没有可复核结果`,
602
+ });
603
+ continue;
604
+ }
605
+ const result = await context.readResult(record);
606
+ if (result === undefined) {
607
+ issues.push({
608
+ code: 'analysis_run_binding_mismatch',
609
+ detail: `${calculation.calculation_id} 引用的 run ${runId} 缺少 result.json,无法复核数值`,
610
+ });
611
+ continue;
612
+ }
613
+ const metric = (result.metrics ?? {})[calculation.metric_key];
614
+ if (metric === undefined || metric === null) {
615
+ issues.push({
616
+ code: 'analysis_metric_undefined',
617
+ detail: `run ${runId} 的 result.metrics 没有 ${calculation.metric_key};可引用的指标见 run_analysis 回执的 metrics`,
618
+ });
619
+ continue;
620
+ }
621
+ if (typeof metric !== 'number' || !Number.isFinite(metric)) {
622
+ issues.push({
623
+ code: 'analysis_metric_binding_invalid',
624
+ detail: `${calculation.calculation_id} 的指标 ${calculation.metric_key} 不是有限数值(${String(metric)}),不能作为计算值`,
625
+ });
626
+ continue;
627
+ }
628
+ const unit = calculation.unit.trim();
629
+ if (unit === '' || unit.length > 32) {
630
+ issues.push({ code: 'analysis_metric_binding_invalid', detail: `${calculation.calculation_id} 的 unit 必须是 1–32 字符` });
631
+ continue;
632
+ }
633
+ // `methods_used` must admit the run it is built on: that is what makes the artifact auditable.
634
+ const method = methodsUsed.find((item) => item.module_id === record.module_id);
635
+ if (method === undefined) {
636
+ issues.push({
637
+ code: 'analysis_run_binding_mismatch',
638
+ detail: `${calculation.calculation_id} 引用的 run 用了 ${record.module_id},但 methods_used 没有列它`,
639
+ });
640
+ continue;
641
+ }
642
+ if (method.module_version !== record.module_version) {
643
+ issues.push({
644
+ code: 'analysis_method_version_mismatch',
645
+ detail: `${record.module_id} 的 methods_used 版本是 ${method.module_version},本次 run 是 ${record.module_version}`,
646
+ });
647
+ continue;
648
+ }
649
+ const request = await context.readRequest(record);
650
+ const requestPeriod = typeof request?.params?.period === 'string' ? request.params.period : undefined;
651
+ let period = calculation.period;
652
+ if (period !== undefined && requestPeriod !== undefined && period !== requestPeriod) {
653
+ issues.push({
654
+ code: 'analysis_metric_binding_invalid',
655
+ detail: `${calculation.calculation_id} 的 period=${period} 与 run 的参数摘要 period=${requestPeriod} 不一致`,
656
+ });
657
+ continue;
658
+ }
659
+ if (period === undefined)
660
+ period = requestPeriod;
661
+ calculations.push({
662
+ calculation_id: calculation.calculation_id,
663
+ module_id: record.module_id,
664
+ module_version: record.module_version,
665
+ metric: calculation.metric_key,
666
+ metric_key: calculation.metric_key,
667
+ value: metric,
668
+ unit,
669
+ ...(period === undefined ? {} : { period }),
670
+ ...(calculation.display === undefined ? {} : { display: calculation.display }),
671
+ ...(calculation.assumption_source === undefined ? {} : { assumption_source: calculation.assumption_source }),
672
+ params_digest: record.params_digest,
673
+ analysis_run_ref: calculation.analysis_run_ref,
674
+ methodology_version: `${record.module_id}@${record.module_version}`,
675
+ ...(inputRefsOf(request).length === 0 ? {} : { input_refs: inputRefsOf(request) }),
676
+ });
677
+ }
678
+ // Every claimed method must be backed by a real run: a version written from memory is fabrication.
679
+ for (const method of methodsUsed) {
680
+ if (method.module_run_ids !== undefined && method.module_run_ids.length > 0) {
681
+ for (const runId of method.module_run_ids) {
682
+ const record = context.runs.find((item) => item.module_run_id === runId);
683
+ if (record === undefined) {
684
+ issues.push({ code: 'analysis_run_not_found', detail: `methods_used 引用的 run ${runId} 不在 run.json 索引里` });
685
+ continue;
686
+ }
687
+ if (record.module_id !== method.module_id || record.module_version !== method.module_version) {
688
+ issues.push({
689
+ code: 'analysis_method_version_mismatch',
690
+ detail: `methods_used 的 ${method.module_id}@${method.module_version} 与 run ${runId}(${record.module_id}@${record.module_version})不符`,
691
+ });
692
+ }
693
+ }
694
+ continue;
695
+ }
696
+ const backed = context.runs.some((record) => record.module_id === method.module_id && record.module_version === method.module_version);
697
+ if (!backed) {
698
+ issues.push({
699
+ code: 'analysis_method_version_mismatch',
700
+ detail: `methods_used 声称用了 ${method.module_id}@${method.module_version},但本次没有任何该版本的 run`,
701
+ });
702
+ }
703
+ }
704
+ return { calculations, issues };
705
+ }
package/lib/chart/tool.js CHANGED
@@ -90,6 +90,7 @@ function normalizeStoreError(error) {
90
90
  return new ChartError('chart_source_invalid', detail, { cause: error.code });
91
91
  case 'workspace_not_writable':
92
92
  case 'dataset_write_failed':
93
+ case 'workspace_conflict':
93
94
  return new ChartError('chart_write_failed', detail, { cause: error.code });
94
95
  case 'filesystem_unavailable':
95
96
  case 'sandbox_policy_unavailable':
@@ -188,7 +188,7 @@ export interface ProfilePayload {
188
188
  validation?: ProfileValidation;
189
189
  warnings: string[];
190
190
  }
191
- export type DatasetStoreErrorCode = 'workspace_not_writable' | 'session_unavailable' | 'session_cwd_unavailable' | 'sandbox_policy_unavailable' | 'filesystem_unavailable' | 'dataset_write_failed' | 'dataset_id_invalid' | 'dataset_not_found' | 'dataset_expired' | 'dataset_session_mismatch' | 'dataset_manifest_invalid' | 'dataset_format_unsupported' | 'dataset_not_row_readable' | 'dataset_too_large' | 'profile_invalid' | 'profile_not_found' | 'profile_expired' | 'profile_too_large' | 'profile_dataset_mismatch' | 'workspace_path_invalid' | 'workspace_file_invalid';
191
+ export type DatasetStoreErrorCode = 'workspace_not_writable' | 'session_unavailable' | 'session_cwd_unavailable' | 'sandbox_policy_unavailable' | 'filesystem_unavailable' | 'dataset_write_failed' | 'dataset_id_invalid' | 'dataset_not_found' | 'dataset_expired' | 'dataset_session_mismatch' | 'dataset_manifest_invalid' | 'dataset_format_unsupported' | 'dataset_not_row_readable' | 'dataset_too_large' | 'profile_invalid' | 'profile_not_found' | 'profile_expired' | 'profile_too_large' | 'profile_dataset_mismatch' | 'workspace_path_invalid' | 'workspace_file_invalid' | 'workspace_conflict';
192
192
  export declare class DatasetStoreError extends Error {
193
193
  readonly code: DatasetStoreErrorCode;
194
194
  constructor(code: DatasetStoreErrorCode, detail: string);
@@ -394,6 +394,12 @@ export declare class WorkspaceDatasetStore {
394
394
  signal?: AbortSignal;
395
395
  maxBytes?: number;
396
396
  }): Promise<string>;
397
+ /** Absolute workspace path for a relative path; analysis snapshots resolve `inputs/` through this. */
398
+ resolveWorkspacePath(input: {
399
+ session: SessionLike;
400
+ path: string;
401
+ signal?: AbortSignal;
402
+ }): Promise<string>;
397
403
  /**
398
404
  * Host-internal raw-byte read (local PDF/images). maxBytes is mandatory and fails loudly; never
399
405
  * fall back to readText, which would corrupt binary data.
@@ -478,6 +478,15 @@ export class WorkspaceDatasetStore {
478
478
  }
479
479
  return text;
480
480
  }
481
+ /** Absolute workspace path for a relative path; analysis snapshots resolve `inputs/` through this. */
482
+ async resolveWorkspacePath(input) {
483
+ const root = this.readRoot(input.session);
484
+ if (!root || !this.fs)
485
+ throw new DatasetStoreError('filesystem_unavailable', 'workspace filesystem is unavailable');
486
+ const relative = normalizeWorkspaceRelativePath(input.path);
487
+ const target = await this.resolveContained(relative, root, input.signal);
488
+ return target.displayPath;
489
+ }
481
490
  /**
482
491
  * Host-internal raw-byte read (local PDF/images). maxBytes is mandatory and fails loudly; never
483
492
  * fall back to readText, which would corrupt binary data.
@@ -676,6 +685,11 @@ export class WorkspaceDatasetStore {
676
685
  if (code === 'FS_SANDBOX_DENIED' || code === 'FS_PERMISSION_DENIED') {
677
686
  throw new DatasetStoreError('workspace_not_writable', `${action} denied by the DSH file sandbox (${code})`);
678
687
  }
688
+ // createIfAbsent collisions are a different fact from a failed write: callers that need
689
+ // revision semantics (artifact revisions) decide whether it is a retry or a conflict.
690
+ if (code === 'FS_NOT_OBSERVED') {
691
+ throw new DatasetStoreError('workspace_conflict', `${action} failed: the target already exists (${code})`);
692
+ }
679
693
  throw new DatasetStoreError('dataset_write_failed', `${action} failed${code ? ` (${code})` : ''}`);
680
694
  }
681
695
  }
@@ -3,9 +3,11 @@ export interface PythonEnvOptions {
3
3
  homeDir: string;
4
4
  tempDir: string;
5
5
  baseEnv?: Record<string, string | undefined>;
6
+ /** Data scripts may fetch from the network behind a proxy; analysis/probe must not inherit it. */
7
+ allowProxyEnv?: boolean;
6
8
  }
7
9
  /**
8
- * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; this
9
- * also removes native-loader variables and keeps the child from reading the user's home/config.
10
+ * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; the
11
+ * allow-list also keeps the child from reading the user's home, credentials or loader overrides.
10
12
  */
11
13
  export declare function pythonChildEnv(options: PythonEnvOptions): Record<string, string>;
@@ -1,17 +1,25 @@
1
1
  import { delimiter } from 'node:path';
2
2
  import { minimalSystemPath } from './platform.js';
3
- const REMOVE = [
4
- 'PYTHONPATH',
5
- 'PYTHONHOME',
6
- 'PYTHONSTARTUP',
7
- 'PYTHONEXECUTABLE',
8
- 'PYTHONUSERBASE',
9
- 'NODE_OPTIONS',
3
+ /**
4
+ * Allow-list for the child interpreter. The analysis modules never need network or credentials, so
5
+ * inheriting the host environment would leak API keys and proxy variables into reviewed code.
6
+ */
7
+ const ALWAYS_KEEP = new Set([
8
+ // Windows loader/system dirs (Python and its DLLs need these to start).
9
+ 'SystemRoot', 'SYSTEMROOT', 'windir', 'WINDIR', 'SystemDrive', 'SYSTEMDRIVE',
10
+ 'COMSPEC', 'PATHEXT',
11
+ // Locale/time facts that change results (PYTHONUTF8 still wins over LANG).
12
+ 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ',
13
+ ]);
14
+ /** Proxy settings only for the data-script path, which may legitimately need network access. */
15
+ const PROXY_KEYS = [
16
+ 'HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'ALL_PROXY',
17
+ 'http_proxy', 'https_proxy', 'no_proxy', 'all_proxy',
18
+ 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'SSL_CERT_FILE', 'SSL_CERT_DIR',
10
19
  ];
11
- const REMOVE_PREFIX = ['PIP_', 'LD_', 'DYLD_'];
12
20
  /**
13
- * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; this
14
- * also removes native-loader variables and keeps the child from reading the user's home/config.
21
+ * Minimal environment for the private interpreter. `-I` already ignores PYTHON* variables; the
22
+ * allow-list also keeps the child from reading the user's home, credentials or loader overrides.
15
23
  */
16
24
  export function pythonChildEnv(options) {
17
25
  const base = options.baseEnv ?? process.env;
@@ -19,13 +27,12 @@ export function pythonChildEnv(options) {
19
27
  for (const [key, value] of Object.entries(base)) {
20
28
  if (value === undefined)
21
29
  continue;
22
- if (REMOVE.includes(key) || REMOVE_PREFIX.some((prefix) => key.startsWith(prefix)))
23
- continue;
24
30
  if (key === 'PATH' || key === 'Path')
25
31
  continue;
26
- env[key] = value;
32
+ if (ALWAYS_KEEP.has(key) || (options.allowProxyEnv === true && PROXY_KEYS.includes(key)))
33
+ env[key] = value;
27
34
  }
28
- env.PATH = [options.pythonDir, minimalSystemPath(base)].join(delimiter);
35
+ env.PATH = [options.pythonDir, minimalSystemPath(base)].filter((item) => item !== '').join(delimiter);
29
36
  env.HOME = options.homeDir;
30
37
  env.USERPROFILE = options.homeDir;
31
38
  env.TMPDIR = options.tempDir;
@@ -93,6 +93,14 @@ export declare class PythonRuntimeManager {
93
93
  verify(packs?: unknown): Promise<ProbeReport>;
94
94
  /** Base pack must be installed and intact; a missing runtime is a call-time failure, never a boot gate. */
95
95
  private resolveDataRuntime;
96
+ /**
97
+ * Interpreter identity for the analysis run fingerprint. Resolving here is deliberate: a run that
98
+ * reused a result computed under another pack would otherwise hide the pack change.
99
+ */
100
+ analysisRuntimeIdentity(): Promise<{
101
+ python_version: string;
102
+ packs: Record<string, string>;
103
+ }>;
96
104
  /** Quote a JSON value for a script's `input.json`: no `undefined`, no non-finite numbers. */
97
105
  private static serializeParams;
98
106
  /**
@@ -500,6 +500,14 @@ export class PythonRuntimeManager {
500
500
  throw error;
501
501
  }
502
502
  }
503
+ /**
504
+ * Interpreter identity for the analysis run fingerprint. Resolving here is deliberate: a run that
505
+ * reused a result computed under another pack would otherwise hide the pack change.
506
+ */
507
+ async analysisRuntimeIdentity() {
508
+ const handle = await this.resolveDataRuntime();
509
+ return { python_version: handle.pythonVersion, packs: { ...handle.packs } };
510
+ }
503
511
  /** Quote a JSON value for a script's `input.json`: no `undefined`, no non-finite numbers. */
504
512
  static serializeParams(params) {
505
513
  return JSON.stringify(params ?? {});
@@ -546,7 +554,7 @@ export class PythonRuntimeManager {
546
554
  const sitePackages = [...handle.sitePackages];
547
555
  if (await exists(PYTHON_VENDOR_DIR))
548
556
  sitePackages.push(PYTHON_VENDOR_DIR);
549
- const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env });
557
+ const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env, allowProxyEnv: true });
550
558
  const args = [
551
559
  ...pythonFlags,
552
560
  this.workerPath,
@@ -620,11 +628,11 @@ export class PythonRuntimeManager {
620
628
  if (await exists(PYTHON_VENDOR_DIR))
621
629
  sitePackages.push(PYTHON_VENDOR_DIR);
622
630
  // The cache root can be mounted read-only for the running process; the child only needs a
623
- // writable HOME/TMPDIR, and the run directory itself already lives in the workspace.
624
- const homeDir = join(tmpdir(), 'cg-analysis-home');
625
- const tempDir = join(tmpdir(), 'cg-analysis-tmp');
626
- await mkdir(homeDir, { recursive: true, mode: 0o700 });
627
- await mkdir(tempDir, { recursive: true, mode: 0o700 });
631
+ // writable HOME/TMPDIR, and the run directory itself already lives in the workspace. One
632
+ // sandbox per run: a shared HOME would let one module read another run's temp files.
633
+ const sandboxDir = join(tmpdir(), `cg-analysis-run-${randomUUID()}`);
634
+ const homeDir = join(sandboxDir, 'home');
635
+ const tempDir = join(sandboxDir, 'tmp');
628
636
  const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env });
629
637
  const args = [
630
638
  ...pythonFlags,
@@ -648,14 +656,22 @@ export class PythonRuntimeManager {
648
656
  max_log_bytes: options.limits.max_log_bytes,
649
657
  }),
650
658
  ];
651
- const worker = await this.runWorker({
652
- python: handle.python,
653
- args,
654
- cwd: options.runDir,
655
- env,
656
- timeoutMs,
657
- ...(signal === undefined ? {} : { signal }),
658
- });
659
+ let worker;
660
+ try {
661
+ await mkdir(homeDir, { recursive: true, mode: 0o700 });
662
+ await mkdir(tempDir, { recursive: true, mode: 0o700 });
663
+ worker = await this.runWorker({
664
+ python: handle.python,
665
+ args,
666
+ cwd: options.runDir,
667
+ env,
668
+ timeoutMs,
669
+ ...(signal === undefined ? {} : { signal }),
670
+ });
671
+ }
672
+ finally {
673
+ await rm(sandboxDir, { recursive: true, force: true });
674
+ }
659
675
  if (worker.spawnError !== undefined) {
660
676
  throw new PythonRuntimeError('script-failed', `启动 Python 失败:${worker.spawnError}`, diagnosticTail(worker.stderr));
661
677
  }
@@ -2019,7 +2019,7 @@ function createRateSeriesSource(options) {
2019
2019
  }
2020
2020
  const SHIBOR_DESCRIPTION = '按日期区间获取 **SHIBOR(上海银行间同业拆放利率)** 日度值,一行一个交易日、八个期限一次给全(`on_rate_pct` 隔夜,`w1` / `w2` 一至两周,`m1` / `m3` / `m6` / `m9` 一至九个月,`y1_pct` 一年)。补的是货币市场基准:此前本仓没有任何拆借利率,要利率只能走 Wind EDB(按次计费)。⛔ 单位是**百分数原值**(实测 2026-10-15 隔夜 1.266 读作 1.266%)——依据只有量级(隔夜拆借不会是 1.266 个基点、也不会是 126.6%),**上游文档没有写这一列的单位**。历史起点实测在 **2006-10-08**(2006 全年给 63 行、首行就是它;2006-01-01..06-30 与 07-01..09-30、1999 / 2004 全年都是 0 行),早于起点是合法空,不要换年份重试。⛔ **周末、节假日与未发布日没有行**,上游也不插值、不补算、不前值填充——序列天然不连续,做时序前先声明对齐规则。列按可空声明:上游文档说某期限可能"源数据未发布",而实测 2020-01-02 起 1000 行里一个 null 都没有;⛔ 真要出现缺失,本层也**不补 0**。`start_date` / `end_date` 必填(实测缺参数 400、倒转 400、带横杠 400),`page_size` 上限 1000(1001 是响亮 400)。防改版:逐行核返回日期落在请求区间内。';
2021
2021
  const HIBOR_DESCRIPTION = '按日期区间获取 **HIBOR(香港银行间同业拆放利率)** 日度值,一行一个交易日,十五个期限档(隔夜、一至两周、一至十二个月)。补的是港币资金面:此前本仓没有任何港币利率。⛔ 单位是**百分数原值**(实测 2026-10-08 隔夜 2.16821 读作 2.16821%)。⛔ **十五档里有七档实测整列为 null**:`m4` / `m5` / `m7` / `m8` / `m9` / `m10` / `m11` 在 2026-10-01..15 的 6 行里 6 / 6 全为 null,只有隔夜、一至两周、一至三月、六月、十二月有值——那是 HIBOR 实际公布的档位就这些,⛔ 不是缺数据,别补值也别把 null 读成 0。历史深度实测至少到 2010 年(2010 全年 249 行、首行 2010-01-04;2000-01-01..2001-12-31 两年 0 行),起点是滚动还是固定未核出。香港假日与未发布日没有行(上游声明不插值、不补算、不前值填充)。`start_date` / `end_date` 必填,`page_size` 上限 1000(实测 1001 → 响亮 400)。防改版:逐行核返回日期落在请求区间内。';
2022
- const FINANCIAL_CALENDAR_DESCRIPTION = '按**最多 3 天的窗口**获取全球财经日历(华尔街见闻口径),一行一个事件。这块本仓**整块零覆盖**:此前既没有宏观数据发布时刻表,也没有"今天几点出 CPI"。⛔ **窗口上限是硬约束**:实测 `end_date` 比 `start_date` **晚四天及以上**才 400「时间范围不能超过3天」(2026-10-15..10-19 与 ..10-20 被拒,..10-18 那四天含首尾正常回 114 行),本层在参数层先拦;要更长区间请分段请求,本层**不替你循环取**——那会把一次取数变成 N 次出网却假装是一份 Dataset。⛔ **覆盖是滚动窗口**:实测 2026-08-03 / 09-01 / 09-15 / 10-05 / 10-12 / 10-19 / 10-26 各日都有事件(40 / 59 / 45 / 37 / 21 / 25 / 10 行),而 **2026-11-02 / 11-16 / 12-01 与 2026-01-05 都是 `records` 空数组 + `total=0`**,2020 / 2023 / 2024 / 2025 里的整天更是直接回 `data:null`——大约"过去 2.5 个月到未来 2 周",边界随日期前移;两种空都是合法空、不是失败,不要换日期重试。列口径:`event_time_ms` 与 `event_time_beijing` 是同一时刻的两种写法(上游 `event_time` 是**秒级** Unix **字符串**,实测 1791993600 → 北京 2026-10-15 00:00;⛔ 直接当毫秒会差三个数量级),`tab_type` 实测只有 `general` 与 `earnings` 两值,`region` 是中文地区名(实测单次 113 行里 14 个:中国 / 美国 / 欧元区 / 日本 / 香港 …;跨多次请求累计见过 28 个),`importance` 上游给**字符串数字** "1".."4",另有空字符串(实测 113 行里 2 行)——本层把空归一成 null,⛔ 不是 0。⛔ `actual_value` / `forecast_value` / `previous_value` **保持文本原样**:这些读数的单位随事件本身而变(指数、百分比、套…上游不给列级单位),本层不转数值、也不换算;缺失只有一种写法——**空字符串**(实测 19 份成功响应、1517 行里这三列加 `link` / `importance` 的空值全是 `""`,`null` 型字段 0 个),本层把它归一成 null。⛔ 财报类事件常给 `actual_value = "0"` 与 `forecast_value = "0"` 的占位(实测首行 赣锋锂业 earnings),那个 0 **不是"实际值为零"**。`link` 是原文链接(实测 113 行里 39 行为空)。`page_size` 真实上限实测 **500**(文档写 200;传 1000 → 回显 pageSize=500),实测最密的三天窗(2026-09-28..09-30)132 个事件、一页就给完;⛔ `page_size=0` 静默只回 1 行(实测),本层要求 ≥1。防改版:逐行核 `stat_date` 落在请求窗口内。';
2022
+ const FINANCIAL_CALENDAR_DESCRIPTION = '按**最多 3 天的窗口**获取全球财经日历(华尔街见闻口径),一行一个事件。这块本仓**整块零覆盖**:此前既没有宏观数据发布时刻表,也没有"今天几点出 CPI"。⛔ **窗口上限是硬约束**:实测 `end_date` 比 `start_date` **晚四天及以上**才 400「时间范围不能超过3天」(2026-10-15..10-19 与 ..10-20 被拒,..10-18 那四天含首尾正常回 114 行),本层在参数层先拦;要更长区间请分段请求,本层**不替你循环取**——那会把一次取数变成 N 次出网却假装是一份 Dataset。⛔ **覆盖是滚动窗口**:实测 2026-08-03 / 09-01 / 09-15 / 10-05 / 10-12 / 10-19 / 10-26 各日都有事件(40 / 59 / 45 / 37 / 21 / 25 / 10 行),而 **2026-11-02 / 11-16 / 12-01 与 2026-01-05 当时都是 `records` 空数组 + `total=0`**(2026-11-29 复测:11-02 / 11-16 已分别回填 30 / 43 行——覆盖随日期滚动回填,别把某天当永久空表),2020 / 2023 / 2024 / 2025 里的整天更是直接回 `data:null`——大约"过去 2.5 个月到未来 2 周",边界随日期前移;两种空都是合法空、不是失败,不要换日期重试。列口径:`event_time_ms` 与 `event_time_beijing` 是同一时刻的两种写法(上游 `event_time` 是**秒级** Unix **字符串**,实测 1791993600 → 北京 2026-10-15 00:00;⛔ 直接当毫秒会差三个数量级),`tab_type` 实测只有 `general` 与 `earnings` 两值,`region` 是中文地区名(实测单次 113 行里 14 个:中国 / 美国 / 欧元区 / 日本 / 香港 …;跨多次请求累计见过 28 个),`importance` 上游给**字符串数字**:实测 2026-11-01..11-28 的 816 行是 `"1"` 277 / `"2"` 337 / `"3"` 95 / `"4"` 54 / **`"0"` 2** / 空字符串 51——**`"0"` 是见闻没评级的条目**(上游 v3.10.5 #66 实测两条都是公司事件:小鹏 Q3 财报会、华为新品发布),本层原样返回 0,⛔ 不重映射成 null、也不按等级过滤(本能力没有 `min_importance` 参数);空字符串归一成 null,⛔ 不是 0。⛔ `actual_value` / `forecast_value` / `previous_value` **保持文本原样**:这些读数的单位随事件本身而变(指数、百分比、套…上游不给列级单位),本层不转数值、也不换算;缺失只有一种写法——**空字符串**(实测 19 份成功响应、1517 行里这三列加 `link` / `importance` 的空值全是 `""`,`null` 型字段 0 个),本层把它归一成 null。⛔ 财报类事件常给 `actual_value = "0"` 与 `forecast_value = "0"` 的占位(实测首行 赣锋锂业 earnings),那个 0 **不是"实际值为零"**。`link` 是原文链接(实测 113 行里 39 行为空)。`page_size` 真实上限实测 **500**(文档写 200;传 1000 → 回显 pageSize=500),实测最密的三天窗(2026-09-28..09-30)132 个事件、一页就给完;⛔ `page_size=0` 静默只回 1 行(实测),本层要求 ≥1。防改版:逐行核 `stat_date` 落在请求窗口内。';
2023
2023
  const financialCalendarRow = {
2024
2024
  type: 'object',
2025
2025
  properties: {