@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
@@ -2,12 +2,13 @@ import { SAFE_RESULT_CHARS } from '../data-collector/describe.js';
2
2
  import { ANALYSIS_PRESET_IDS } from '../preset-ids.js';
3
3
  import { authorizedSession } from '../tool-exec.js';
4
4
  import { analysisModuleById, listAnalysisModules } from './registry.js';
5
- import { ANALYSIS_ARTIFACT_SCHEMA, ARTIFACT_MAX_CHARS, CREATE_SNAPSHOT_OUTPUT, CREATE_SNAPSHOT_PARAMETERS, DESCRIBE_MODULE_OUTPUT, DESCRIBE_MODULE_PARAMETERS, HEADLINE_MAX_CHARS, LIST_MODULES_OUTPUT, LIST_MODULES_PARAMETERS, MAX_CLAIMS, MAX_SCENARIOS, READ_PROFILE_OUTPUT, READ_PROFILE_PARAMETERS, RUN_ANALYSIS_OUTPUT, RUN_ANALYSIS_PARAMETERS, STATEMENT_MAX_CHARS, SUBMIT_ANALYSIS_OUTPUT, THESIS_MAX_CHARS, } from './schemas.js';
6
- import { analysisRuntimeFrom, runModuleOnSnapshot } from './runtime.js';
5
+ import { artifactCredential, buildArtifactRecord, diffArtifacts, loadArtifact } from './artifact.js';
6
+ import { ANALYSIS_ARTIFACT_SCHEMA, ARTIFACT_MAX_CHARS, ARTIFACT_V2_SCHEMA, CREATE_SNAPSHOT_OUTPUT, EVENT_STUDY_FACTS_SCHEMA, SIMULATION_FACTS_SCHEMA, CREATE_SNAPSHOT_PARAMETERS, DESCRIBE_MODULE_OUTPUT, DESCRIBE_MODULE_PARAMETERS, HEADLINE_MAX_CHARS, LIST_MODULES_OUTPUT, LIST_MODULES_PARAMETERS, MAX_CLAIMS, MAX_SCENARIOS, READ_PROFILE_OUTPUT, READ_PROFILE_PARAMETERS, RUN_ANALYSIS_OUTPUT, RUN_ANALYSIS_PARAMETERS, STATEMENT_MAX_CHARS, SUBMIT_ANALYSIS_OUTPUT, THESIS_MAX_CHARS, } from './schemas.js';
7
+ import { analysisRuntimeFrom, readRunIndex, runModuleOnSnapshot } from './runtime.js';
7
8
  import { createSnapshot, loadSnapshot, snapshotCoverage } from './snapshot.js';
8
- import { ARTIFACT_FILE, analysisDir, artifactRef, parseSnapshotRef, parseArtifactRef, writeFiles, } from './storage.js';
9
+ import { ARTIFACT_FILE, ARTIFACTS_DIR, REQUEST_FILE, RESULT_FILE, analysisContractV2Enabled, analysisDir, artifactRef, artifactRevisionFile, moduleRunDir, parseSnapshotRef, parseArtifactRef, readJsonFile, writeFiles, } from './storage.js';
9
10
  import { ANALYSIS_TOOL_NAMES, AnalysisError, } from './types.js';
10
- import { validateAgainstSchema, validateArtifact } from './validation.js';
11
+ import { bindCalculations, parseRunRef, validateAgainstSchema, validateArtifact } from './validation.js';
11
12
  function render(_args, value) {
12
13
  return [{ type: 'text', text: JSON.stringify(value) }];
13
14
  }
@@ -43,6 +44,49 @@ function oneOf(value, allowed, field) {
43
44
  }
44
45
  return value;
45
46
  }
47
+ /** A params object is passed through untouched; an array or string is a bad request, not `{}`. */
48
+ function paramsOf(value) {
49
+ if (value === undefined || value === null)
50
+ return {};
51
+ if (typeof value !== 'object' || Array.isArray(value)) {
52
+ throw new AnalysisError('analysis_input_invalid', 'params 必须是 JSON 对象(不能是数组或字符串)');
53
+ }
54
+ return value;
55
+ }
56
+ function calculationRequestsOf(value) {
57
+ if (value === undefined || value === null)
58
+ return [];
59
+ if (!Array.isArray(value))
60
+ throw new AnalysisError('analysis_input_invalid', 'calculations 必须是数组');
61
+ return value.map((item, index) => {
62
+ const record = recordOf(item);
63
+ return {
64
+ calculation_id: text(record.calculation_id, `calculations[${index}].calculation_id`, 120),
65
+ analysis_run_ref: text(record.analysis_run_ref, `calculations[${index}].analysis_run_ref`, 200),
66
+ metric_key: text(record.metric_key, `calculations[${index}].metric_key`, 120),
67
+ unit: text(record.unit, `calculations[${index}].unit`, 32),
68
+ ...(optionalText(record.period, `calculations[${index}].period`, 64) === undefined ? {} : { period: String(record.period) }),
69
+ ...(optionalText(record.display, `calculations[${index}].display`, 64) === undefined ? {} : { display: String(record.display) }),
70
+ ...(record.assumption_source === undefined
71
+ ? {}
72
+ : { assumption_source: oneOf(record.assumption_source, ['user', 'dataset', 'evidence', 'model_assumption', 'default'], `calculations[${index}].assumption_source`) }),
73
+ };
74
+ });
75
+ }
76
+ function methodsUsedOf(value) {
77
+ if (value === undefined || value === null)
78
+ return [];
79
+ if (!Array.isArray(value))
80
+ throw new AnalysisError('analysis_input_invalid', 'methods_used 必须是数组');
81
+ return value.map((item, index) => {
82
+ const record = recordOf(item);
83
+ return {
84
+ module_id: text(record.module_id, `methods_used[${index}].module_id`, 64),
85
+ module_version: text(record.module_version, `methods_used[${index}].module_version`, 32),
86
+ ...(record.module_run_ids === undefined ? {} : { module_run_ids: stringArray(record.module_run_ids, `methods_used[${index}].module_run_ids`) }),
87
+ };
88
+ });
89
+ }
46
90
  /** Dataset/profile refs arrive as objects or bare ids; only the id is used. */
47
91
  function refId(value, field) {
48
92
  const raw = typeof value === 'string' ? value : recordOf(value)[field];
@@ -89,6 +133,9 @@ function createSnapshotInput(args) {
89
133
  evidence: evidenceOf(args.evidence),
90
134
  prior_analysis_refs: stringArray(args.prior_analysis_refs, 'prior_analysis_refs'),
91
135
  constraints: recordOf(args.constraints),
136
+ ...(optionalText(args.temporal_mode, 'temporal_mode', 32) === undefined
137
+ ? {}
138
+ : { temporal_mode: oneOf(args.temporal_mode, ['as_known_then', 'ex_post'], 'temporal_mode') }),
92
139
  };
93
140
  }
94
141
  function profileIdOf(ref) {
@@ -126,7 +173,7 @@ function oversizedSection(artifact) {
126
173
  return sized[0]?.[0] ?? 'artifact';
127
174
  }
128
175
  function artifactOf(args) {
129
- const artifact = {
176
+ return {
130
177
  analysis_id: text(args.analysis_id, 'analysis_id', 120),
131
178
  task_id: text(args.task_id, 'task_id', 120),
132
179
  snapshot_id: text(args.snapshot_id, 'snapshot_id', 120),
@@ -138,15 +185,156 @@ function artifactOf(args) {
138
185
  counter_claims: Array.isArray(args.counter_claims) ? args.counter_claims : [],
139
186
  alternative_explanations: stringArray(args.alternative_explanations, 'alternative_explanations'),
140
187
  contradictions: stringArray(args.contradictions, 'contradictions'),
141
- calculations: Array.isArray(args.calculations) ? args.calculations : [],
188
+ calculations: calculationRequestsOf(args.calculations),
142
189
  scenarios: Array.isArray(args.scenarios) ? args.scenarios : [],
143
190
  invalidation_conditions: stringArray(args.invalidation_conditions, 'invalidation_conditions'),
144
191
  unresolved_gaps: stringArray(args.unresolved_gaps, 'unresolved_gaps'),
145
192
  limitations: stringArray(args.limitations, 'limitations'),
146
- methods_used: Array.isArray(args.methods_used) ? args.methods_used : [],
193
+ methods_used: methodsUsedOf(args.methods_used),
147
194
  peer_exchanges: Array.isArray(args.peer_exchanges) ? args.peer_exchanges : [],
195
+ ...(optionalText(args.simulation_run_ref, 'simulation_run_ref', 200) === undefined
196
+ ? {}
197
+ : { simulation_run_ref: String(args.simulation_run_ref) }),
198
+ ...(optionalText(args.event_study_run_ref, 'event_study_run_ref', 200) === undefined
199
+ ? {}
200
+ : { event_study_run_ref: String(args.event_study_run_ref) }),
148
201
  };
149
- return artifact;
202
+ }
203
+ /**
204
+ * Resolve a module-authored facts block from the cited run. The module owns the facts (simulation grade
205
+ * or event-study sample size), so the host copies them instead of accepting values the model typed. A
206
+ * run without the block cannot back the corresponding claim.
207
+ */
208
+ async function factsFromRun(input) {
209
+ if (input.ref === undefined)
210
+ return undefined;
211
+ const parsed = parseRunRef(input.ref);
212
+ if (parsed === undefined || parsed.analysisId !== input.analysisId) {
213
+ throw new AnalysisError('analysis_run_binding_mismatch', `${input.label}_run_ref 不属于本快照:${input.ref.slice(0, 160)}`);
214
+ }
215
+ const record = input.runs.find((item) => item.module_run_id === parsed.moduleRunId);
216
+ if (record === undefined) {
217
+ throw new AnalysisError('analysis_run_not_found', `${input.label}_run_ref 引用的 run ${parsed.moduleRunId} 不在 run.json 索引里`);
218
+ }
219
+ if (!['completed', 'partial', 'blocked'].includes(record.status)) {
220
+ throw new AnalysisError('analysis_run_binding_mismatch', `${input.label}_run_ref 引用的 run 状态是 ${record.status},没有可复核的结果`);
221
+ }
222
+ const result = await input.readResult(record);
223
+ const facts = result === undefined ? undefined : input.pick(result);
224
+ if (facts === undefined) {
225
+ throw new AnalysisError('analysis_run_binding_mismatch', `run ${parsed.moduleRunId} 的结果里没有 ${input.label} 块:引用它不能给结论提供对应事实`);
226
+ }
227
+ const issues = validateAgainstSchema(facts, input.schema);
228
+ if (issues.length > 0) {
229
+ throw new AnalysisError('analysis_output_invalid', `run 的 ${input.label} 块不符合契约(${issues.length} 条):${issues.slice(0, 4).join(';')}`);
230
+ }
231
+ return { ...facts, analysis_run_ref: input.ref };
232
+ }
233
+ function resolveSimulationFacts(input) {
234
+ return factsFromRun({
235
+ ...input,
236
+ label: 'simulation',
237
+ schema: SIMULATION_FACTS_SCHEMA,
238
+ pick: (result) => result.simulation,
239
+ });
240
+ }
241
+ function resolveEventStudyFacts(input) {
242
+ return factsFromRun({
243
+ ...input,
244
+ label: 'event_study',
245
+ schema: EVENT_STUDY_FACTS_SCHEMA,
246
+ pick: (result) => result.event_study,
247
+ });
248
+ }
249
+ /**
250
+ * The read side of the run index for `submit_analysis`: results and request params are loaded once per
251
+ * cited run, and only through the store seam (no absolute paths, no module code).
252
+ */
253
+ function runBindingContext(store, session, analysisId, index, signal) {
254
+ const results = new Map();
255
+ const requests = new Map();
256
+ const resultPath = (record) => record.result_ref === undefined
257
+ ? `${moduleRunDir(analysisId, record.module_run_id)}/${RESULT_FILE}`
258
+ : `${analysisDir(analysisId)}/${record.result_ref}`;
259
+ return {
260
+ analysis_id: analysisId,
261
+ runs: index.runs,
262
+ readResult(record) {
263
+ const key = record.module_run_id;
264
+ const pending = results.get(key);
265
+ if (pending !== undefined)
266
+ return pending;
267
+ const loaded = (async () => {
268
+ const stored = await readJsonFile(store, session, resultPath(record), signal);
269
+ return stored?.result;
270
+ })();
271
+ results.set(key, loaded);
272
+ return loaded;
273
+ },
274
+ readRequest(record) {
275
+ const key = record.module_run_id;
276
+ const pending = requests.get(key);
277
+ if (pending !== undefined)
278
+ return pending;
279
+ const loaded = (async () => {
280
+ const stored = await readJsonFile(store, session, `${moduleRunDir(analysisId, record.module_run_id)}/${REQUEST_FILE}`, signal);
281
+ return stored;
282
+ })();
283
+ requests.set(key, loaded);
284
+ return loaded;
285
+ },
286
+ };
287
+ }
288
+ // ── revision append ───────────────────────────────────────────────────────────────────────────
289
+ /**
290
+ * Append one accepted artifact: write the immutable revision first, then refresh `artifact.json`.
291
+ * A `createIfAbsent` collision means another writer took this revision; reload once and retry, and
292
+ * if the latest pointer still points at the same revision the conflict is reported, never overwritten.
293
+ */
294
+ async function appendArtifactRevision(input) {
295
+ const { store, session, analysisId, artifact } = input;
296
+ for (let attempt = 0; attempt < 2; attempt += 1) {
297
+ const previous = await loadArtifact(store, session, analysisId, input.signal);
298
+ const continues = previous !== undefined && !previous.legacy;
299
+ const revision = continues ? previous.revision + 1 : 1;
300
+ const record = buildArtifactRecord({
301
+ analysisId,
302
+ revision,
303
+ ...(continues ? { supersedes: artifactRef(analysisId, previous.revision) } : {}),
304
+ artifact,
305
+ changes: continues ? diffArtifacts(previous.artifact, artifact) : [],
306
+ createdAt: input.now,
307
+ });
308
+ const schemaIssues = validateAgainstSchema(record, ARTIFACT_V2_SCHEMA);
309
+ if (schemaIssues.length > 0) {
310
+ throw new AnalysisError('analysis_output_invalid', `产物不符合 Artifact V2 落盘契约:${schemaIssues.slice(0, 4).join(';')}`);
311
+ }
312
+ try {
313
+ await writeFiles(store, session, `${analysisDir(analysisId)}/${ARTIFACTS_DIR}`, [{
314
+ name: artifactRevisionFile(revision),
315
+ content: JSON.stringify(record),
316
+ }], {
317
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
318
+ conflictCode: 'analysis_artifact_revision_conflict',
319
+ what: `写入 artifacts/rev-${revision}.json 失败`,
320
+ });
321
+ await writeFiles(store, session, analysisDir(analysisId), [{
322
+ name: ARTIFACT_FILE,
323
+ content: JSON.stringify(record),
324
+ }], {
325
+ ...(input.signal === undefined ? {} : { signal: input.signal }),
326
+ overwrite: true,
327
+ what: '刷新 artifact.json 失败',
328
+ });
329
+ return { record, ref: artifactRef(analysisId, revision) };
330
+ }
331
+ catch (error) {
332
+ if (attempt === 0 && error instanceof AnalysisError && error.code === 'analysis_artifact_revision_conflict')
333
+ continue;
334
+ throw error;
335
+ }
336
+ }
337
+ throw new AnalysisError('analysis_artifact_revision_conflict', '产物 revision 写入冲突:同一 analysis 的并发提交占用了该 revision,请重试');
150
338
  }
151
339
  export function registerAnalysisTools(deps) {
152
340
  const { ctx, store } = deps;
@@ -159,7 +347,8 @@ export function registerAnalysisTools(deps) {
159
347
  {
160
348
  name: 'create_analysis_snapshot',
161
349
  description: '冻结本次分析的输入版本:把 Dataset / profile / 证据引用连同研究问题、口径与时间点打包成不可变快照,'
162
- + '返回 snapshot 引用与到期时间。分析前必须先建快照;快照只存引用与摘要,不包含原始数据行。',
350
+ + '返回 snapshot 引用与到期时间。分析前必须先建快照;快照只存引用与摘要,不包含原始数据行。'
351
+ + '事件研究或历史回测用 temporal_mode=as_known_then 显式声明“只用当时可知的信息”(缺省 ex_post)。',
163
352
  parameters: CREATE_SNAPSHOT_PARAMETERS,
164
353
  output: { schema: CREATE_SNAPSHOT_OUTPUT, render },
165
354
  async execute(args, exec) {
@@ -248,13 +437,15 @@ export function registerAnalysisTools(deps) {
248
437
  required_fields: entry.manifest.required_fields,
249
438
  assumptions: entry.manifest.assumptions,
250
439
  capabilities: entry.manifest.capabilities,
440
+ temporal_aware: entry.manifest.temporal_aware,
251
441
  limits: entry.manifest.limits,
252
442
  };
253
443
  },
254
444
  },
255
445
  {
256
446
  name: 'run_analysis',
257
- description: '在快照上运行一个分析模块,返回指标、假设、数据缺口与校验结论。同一快照内输入与参数不变时会复用已有结果;'
447
+ description: '在快照上运行一个分析模块,返回 analysis_run_ref、指标、方法日志、输出引用与校验结论;提交产物时用它绑定计算。'
448
+ + '同一快照内输入、参数、模块代码与运行时都不变时才复用(复用也会写一条 reused_from 记录);'
258
449
  + '模块未声明的能力(如读数据集)会在运行前被拒绝。',
259
450
  parameters: RUN_ANALYSIS_PARAMETERS,
260
451
  output: { schema: RUN_ANALYSIS_OUTPUT, render },
@@ -279,7 +470,7 @@ export function registerAnalysisTools(deps) {
279
470
  session,
280
471
  snapshot,
281
472
  module,
282
- params: recordOf(args.params),
473
+ params: paramsOf(args.params),
283
474
  ...(exec.signal === undefined ? {} : { signal: exec.signal }),
284
475
  now: now(),
285
476
  });
@@ -288,25 +479,29 @@ export function registerAnalysisTools(deps) {
288
479
  },
289
480
  {
290
481
  name: 'submit_analysis',
291
- description: '提交最终分析产物:结论、正反论据、替代解释、失效条件与数字锚点。宿主会校验结论里的每个数字能否追到锚点;'
292
- + '缺失效条件、引用不存在或数字无来源会被拒绝,警告级问题会让产物降级为 partial。',
482
+ description: '提交最终分析产物:结论、正反论据、替代解释、失效条件与数字锚点。calculations 只填 analysis_run_ref、'
483
+ + 'metric_key 与 unit,数值由宿主从该 run 的结果里取;结论里的每个数字必须能追到锚点或 run 指标。'
484
+ + '缺失效条件、引用不存在、run 绑定不成立、claim 类型/因果强度不成立或数字无来源会被拒绝,警告级问题会让'
485
+ + '引用事件研究时再用 event_study_run_ref 指向同一 run,宿主复制事件窗、有效样本、因果强度与审计事实;'
486
+ + '单事件或零样本却写强因果/过度断言会被拒绝。每次接受生成一个不可变 revision,回执的 analysis_ref 带 @版本并附'
487
+ + ' credential(revision、artifact_hash、状态、方法、PIT 模式、缺口数、模拟等级、事件样本数),把它原样转述给主 Agent。',
293
488
  parameters: ANALYSIS_ARTIFACT_SCHEMA,
294
489
  output: { schema: SUBMIT_ANALYSIS_OUTPUT, render },
295
490
  async execute(args, exec) {
296
491
  const session = authorize(exec, 'submit_analysis');
297
- const artifact = artifactOf(args);
298
- const serialized = JSON.stringify(artifact);
492
+ const submitted = artifactOf(args);
493
+ const serialized = JSON.stringify(submitted);
299
494
  if (serialized.length > ARTIFACT_MAX_CHARS) {
300
- throw new AnalysisError('analysis_result_too_large', `产物 ${serialized.length} 字符,超过 ${ARTIFACT_MAX_CHARS} 上限;先压缩 ${oversizedSection(artifact)} 再重发(上限:headline ${HEADLINE_MAX_CHARS} / thesis ${THESIS_MAX_CHARS} / 单条 statement ${STATEMENT_MAX_CHARS} / claims ${MAX_CLAIMS} / scenarios ${MAX_SCENARIOS})`);
495
+ throw new AnalysisError('analysis_result_too_large', `产物 ${serialized.length} 字符,超过 ${ARTIFACT_MAX_CHARS} 上限;先压缩 ${oversizedSection(submitted)} 再重发(上限:headline ${HEADLINE_MAX_CHARS} / thesis ${THESIS_MAX_CHARS} / 单条 statement ${STATEMENT_MAX_CHARS} / claims ${MAX_CLAIMS} / scenarios ${MAX_SCENARIOS})`);
301
496
  }
302
497
  // §11.4 Tier 1 covers "schema mismatch" too: the artifact schema is the contract the model
303
498
  // reads, so an undeclared field or an over-long claim list must be rejected here, not ignored.
304
- const schemaIssues = validateAgainstSchema(artifact, ANALYSIS_ARTIFACT_SCHEMA);
499
+ const schemaIssues = validateAgainstSchema(submitted, ANALYSIS_ARTIFACT_SCHEMA);
305
500
  if (schemaIssues.length > 0) {
306
501
  throw new AnalysisError('analysis_validation_failed', `产物不符合 artifact schema(${schemaIssues.length} 条):${schemaIssues.slice(0, 6).join(';')}`);
307
502
  }
308
- const analysisId = parseArtifactRef(`analysis_artifact:${artifact.analysis_id}`);
309
- if (artifact.snapshot_id !== artifact.analysis_id) {
503
+ const analysisId = parseArtifactRef(`analysis_artifact:${submitted.analysis_id}`);
504
+ if (submitted.snapshot_id !== submitted.analysis_id) {
310
505
  throw new AnalysisError('analysis_snapshot_invalid', 'snapshot_id 必须等于建快照时返回的 analysis_id');
311
506
  }
312
507
  const snapshot = await loadSnapshot({
@@ -316,13 +511,51 @@ export function registerAnalysisTools(deps) {
316
511
  ...(exec.signal === undefined ? {} : { signal: exec.signal }),
317
512
  now: now(),
318
513
  });
514
+ if (snapshot.legacy && analysisContractV2Enabled()) {
515
+ throw new AnalysisError('analysis_snapshot_legacy', '这是 V1 快照:只读兼容,不能提交新产物;请重建 V2 快照后重跑');
516
+ }
517
+ // Calculation V2: the value comes from the cited run, never from the submitted text.
518
+ const runs = await readRunIndex(store, session, analysisId, exec.signal);
519
+ const runContext = runBindingContext(store, session, analysisId, runs, exec.signal);
520
+ const binding = await bindCalculations(submitted.calculations, runContext, submitted.methods_used);
521
+ if (binding.issues.length > 0) {
522
+ const first = binding.issues[0];
523
+ throw new AnalysisError(first.code, `Calculation 与 run 绑定未通过(${binding.issues.length} 条):${binding.issues.slice(0, 4).map((issue) => issue.detail).join(';')}`);
524
+ }
525
+ // M5 G5: the simulation credential is copied from the cited run, never typed by the model.
526
+ // M5 G5 / M6 G6: simulation and event-study facts are copied from the cited runs, never typed
527
+ // by the model.
528
+ const simulation = await resolveSimulationFacts({
529
+ analysisId,
530
+ runs: runs.runs,
531
+ ref: submitted.simulation_run_ref,
532
+ readResult: runContext.readResult,
533
+ });
534
+ const eventStudy = await resolveEventStudyFacts({
535
+ analysisId,
536
+ runs: runs.runs,
537
+ ref: submitted.event_study_run_ref,
538
+ readResult: runContext.readResult,
539
+ });
540
+ const artifact = {
541
+ ...submitted,
542
+ calculations: binding.calculations,
543
+ ...(simulation === undefined ? {} : { simulation }),
544
+ ...(eventStudy === undefined ? {} : { event_study: eventStudy }),
545
+ };
319
546
  const validation = validateArtifact(artifact, snapshot);
320
547
  if (validation.tier1.length > 0) {
321
- // The reserved code exists for exactly this budget (§5.6-2); a generic validation error
322
- // would hide that the peer loop is the problem.
548
+ // The reserved codes exist for exactly these gates; a generic validation error would hide
549
+ // which hard rule failed (peer budget §5.6-2, simulation overclaim §4-8).
323
550
  const budget = validation.tier1.find((issue) => issue.code === 'peer_budget_exhausted');
324
551
  if (budget !== undefined)
325
552
  throw new AnalysisError('analysis_peer_budget_exhausted', budget.detail);
553
+ const overclaim = validation.tier1.find((issue) => issue.code === 'simulation_overclaim');
554
+ if (overclaim !== undefined)
555
+ throw new AnalysisError('analysis_simulation_overclaim', overclaim.detail);
556
+ const eventOverclaim = validation.tier1.find((issue) => issue.code === 'event_overclaim');
557
+ if (eventOverclaim !== undefined)
558
+ throw new AnalysisError('analysis_event_overclaim', eventOverclaim.detail);
326
559
  throw new AnalysisError('analysis_validation_failed', `产物未通过硬校验(${validation.tier1.length} 条):${validation.tier1.slice(0, 6).map((issue) => `${issue.code} ${issue.detail}`).join(';')}`);
327
560
  }
328
561
  const downgraded = validation.tier2.length > 0 && artifact.status === 'completed' ? 'partial' : artifact.status;
@@ -334,18 +567,26 @@ export function registerAnalysisTools(deps) {
334
567
  issues: [...validation.tier1, ...validation.tier2, ...validation.tier3],
335
568
  },
336
569
  };
337
- await writeFiles(store, session, analysisDir(analysisId), [{
338
- name: ARTIFACT_FILE,
339
- content: JSON.stringify(persisted),
340
- }], {
570
+ const { record, ref } = await appendArtifactRevision({
571
+ store,
572
+ session,
573
+ analysisId,
574
+ artifact: persisted,
341
575
  ...(exec.signal === undefined ? {} : { signal: exec.signal }),
342
- overwrite: true,
343
- what: '写入 artifact.json 失败',
576
+ now: now(),
344
577
  });
578
+ // Plan §3.3/R-07: the host guarantees the credential fields; whether the final answer repeats
579
+ // them is model discipline, not something a host check can see.
345
580
  return {
346
- analysis_ref: artifactRef(analysisId),
581
+ analysis_ref: ref,
347
582
  status: 'accepted',
348
- validation: persisted.validation,
583
+ validation: record.validation,
584
+ credential: artifactCredential({
585
+ artifactRef: ref,
586
+ record,
587
+ temporalMode: snapshot.temporal_mode,
588
+ ...(snapshot.data_cutoff === undefined ? {} : { dataCutoff: snapshot.data_cutoff }),
589
+ }),
349
590
  };
350
591
  },
351
592
  },