@v587d/capital-generation 2.30.1 → 2.31.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 (68) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/automation/package.json +1 -1
  5. package/automation/storage.js +4 -0
  6. package/chart-ui/package.json +1 -1
  7. package/config/client.js +1 -1
  8. package/config/package.json +1 -1
  9. package/lib/agents/messaging-policy.d.ts +1 -1
  10. package/lib/agents/role-tool-policy.d.ts +3 -0
  11. package/lib/agents/role-tool-policy.js +12 -2
  12. package/lib/agents/selected-skills-provider.d.ts +1 -1
  13. package/lib/agents/selected-skills-provider.js +3 -1
  14. package/lib/analysis/registry.d.ts +12 -0
  15. package/lib/analysis/registry.js +76 -0
  16. package/lib/analysis/runtime.d.ts +87 -0
  17. package/lib/analysis/runtime.js +225 -0
  18. package/lib/analysis/schemas.d.ts +52 -0
  19. package/lib/analysis/schemas.js +270 -0
  20. package/lib/analysis/snapshot.d.ts +102 -0
  21. package/lib/analysis/snapshot.js +266 -0
  22. package/lib/analysis/storage.d.ts +64 -0
  23. package/lib/analysis/storage.js +96 -0
  24. package/lib/analysis/tools.d.ts +17 -0
  25. package/lib/analysis/tools.js +352 -0
  26. package/lib/analysis/types.d.ts +201 -0
  27. package/lib/analysis/types.js +44 -0
  28. package/lib/analysis/validation.d.ts +44 -0
  29. package/lib/analysis/validation.js +338 -0
  30. package/lib/analysis-entry.d.ts +10 -0
  31. package/lib/analysis-entry.js +7 -0
  32. package/lib/data-collector/store.d.ts +14 -1
  33. package/lib/data-collector/store.js +44 -0
  34. package/lib/data-contract.d.ts +3 -2
  35. package/lib/data-contract.js +18 -2
  36. package/lib/preset-ids.d.ts +5 -0
  37. package/lib/preset-ids.js +7 -1
  38. package/lib/python-runtime/errors.d.ts +7 -1
  39. package/lib/python-runtime/errors.js +9 -1
  40. package/lib/python-runtime/manager.d.ts +30 -0
  41. package/lib/python-runtime/manager.js +88 -0
  42. package/lib/python-runtime/probe.js +5 -1
  43. package/lib/selected-skills-entry.js +1 -1
  44. package/lib/web-retriever/local-fetch.d.ts +1 -1
  45. package/lib/web-retriever/local-fetch.js +1 -1
  46. package/lib/web-retriever/wind-client.d.ts +1 -1
  47. package/lib/web-retriever/wind-client.js +1 -1
  48. package/package.json +6 -1
  49. package/preset/capital-generation/README.md +5 -6
  50. package/preset/capital-generation/agent.patch.yml +47 -58
  51. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  52. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  53. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +93 -0
  54. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  55. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  56. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  57. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  58. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  59. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +100 -0
  60. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  61. package/python/analysis/modules/financial_quality/module.json +65 -0
  62. package/python/analysis/modules/financial_quality/module.py +535 -0
  63. package/python/analysis/modules/hello/LICENSE +21 -0
  64. package/python/analysis/modules/hello/module.json +46 -0
  65. package/python/analysis/modules/hello/module.py +56 -0
  66. package/python/worker.py +152 -5
  67. package/selected-skills/routing.js +5 -2
  68. package/watchlist/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/config",
3
- "version": "2.30.1",
3
+ "version": "2.31.0",
4
4
  "description": "自动模式的取数凭据与偏好配置行:卡片坐在 @v587d/capital-generation 插件主页的「配置」段,点这一行本身没有表单。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Call-level `send_message` target guard. rc.2 lets any two members of one subagent tree message
3
3
  * each other; Capital keeps the main-agent relay: root -> direct child only, child -> lead only,
4
- * specialist -> none. The target map is explicit so a future data-junior -> data-analyst link is a
4
+ * specialist -> none. The target map is explicit so a future data-junior -> senior-analyst link is a
5
5
  * one-line addition, not a policy rewrite. Non-Capital presets fail open.
6
6
  */
7
7
  import type { GuardedExecution, PolicyContext } from './root-tool-policy.js';
@@ -9,6 +9,9 @@ export { ROLE_PRESET_IDS, ROLE_PRESET_ID_LIST, type RolePresetId } from '../pres
9
9
  /** Registered together with `send_message` by `tool-subagent-control`; no host switch, so leaf roles deny these by name.
10
10
  * 0.2.2 moved `list_agents` into the same main entry, so the welded set grew from one to two names. */
11
11
  export declare const SIBLING_DENIED_TOOLS: readonly ["interrupt_agent", "list_agents"];
12
+ /** Welded in by the same row, but only the analyst denies it: it is a leaf with nothing to wait on,
13
+ * while data-junior's chart barrier needs `wait_agent` (design §5.5 — do not widen this to the shared set). */
14
+ export declare const ANALYST_DENIED_TOOLS: readonly ["wait_agent"];
12
15
  /** Full intended surface; only names that resolve as host-global are enforced by the allow-list.
13
16
  * Scoped family-row tools stay visible regardless; they must remain in this list for review. */
14
17
  export declare const COLLECTOR_ROLE_TOOLS: readonly ["send_message", "skill", "get_local_datetime", "resolve_data_time_range", "request_data", "list_capabilities", "describe_capability", "dc_status"];
@@ -10,6 +10,9 @@ export { ROLE_PRESET_IDS, ROLE_PRESET_ID_LIST } from '../preset-ids.js';
10
10
  /** Registered together with `send_message` by `tool-subagent-control`; no host switch, so leaf roles deny these by name.
11
11
  * 0.2.2 moved `list_agents` into the same main entry, so the welded set grew from one to two names. */
12
12
  export const SIBLING_DENIED_TOOLS = ['interrupt_agent', 'list_agents'];
13
+ /** Welded in by the same row, but only the analyst denies it: it is a leaf with nothing to wait on,
14
+ * while data-junior's chart barrier needs `wait_agent` (design §5.5 — do not widen this to the shared set). */
15
+ export const ANALYST_DENIED_TOOLS = ['wait_agent'];
13
16
  /** Shared leaf capabilities that are host-global in rc.2, not preset-scoped. */
14
17
  const ROLE_MESSAGING_TOOLS = ['send_message', 'skill'];
15
18
  const ROLE_TIME_TOOLS = ['get_local_datetime', 'resolve_data_time_range'];
@@ -36,7 +39,7 @@ export const ROLE_TOOL_SURFACES = {
36
39
  [ROLE_PRESET_IDS.junior]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
37
40
  [ROLE_PRESET_IDS.retriever]: { allowTools: RETRIEVER_ROLE_TOOLS, denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
38
41
  [ROLE_PRESET_IDS.specialist]: { allowTools: SPECIALIST_ROLE_TOOLS, ...DENY_TEAM },
39
- [ROLE_PRESET_IDS.analyst]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
42
+ [ROLE_PRESET_IDS.analyst]: { denySiblings: [...SIBLING_DENIED_TOOLS, ...ANALYST_DENIED_TOOLS], ...DENY_TEAM },
40
43
  };
41
44
  /** Role preset id only, undefined for root and other presets; failure means "do not converge". */
42
45
  export function rolePresetIdOf(ctx, agent) {
@@ -125,13 +128,20 @@ export function restrictRoleAgentTools(agent, surface) {
125
128
  export function roleSiblingGuardReasonFor(ctx) {
126
129
  return (exec) => {
127
130
  const name = exec?.name;
128
- if (typeof name !== 'string' || !SIBLING_DENIED_TOOLS.includes(name))
131
+ if (typeof name !== 'string')
129
132
  return undefined;
130
133
  const claim = readPresetClaim(ctx, exec?.agent);
131
134
  if (claim.registryMissing || claim.failed || claim.claim === undefined)
132
135
  return undefined;
133
136
  if (!ROLE_PRESET_ID_LIST.includes(claim.claim))
134
137
  return undefined;
138
+ const denied = [...SIBLING_DENIED_TOOLS, ...(claim.claim === ROLE_PRESET_IDS.analyst ? ANALYST_DENIED_TOOLS : [])];
139
+ if (!denied.includes(name))
140
+ return undefined;
141
+ if (name === 'wait_agent') {
142
+ return `${name} 不对人设 ${claim.claim} 开放:叶子角色没有子 Agent 可等,结果直接回传主 Agent;`
143
+ + '等待归主 Agent 的 wait_for_agents 负责。';
144
+ }
135
145
  if (name === 'list_agents') {
136
146
  return `${name} 不对人设 ${claim.claim} 开放:叶子角色只回传自己的结果,子 Agent 名单与调度归主 Agent。`
137
147
  + '需要别的 Agent 配合,用 send_message 回告主 Agent;不要自己换工具硬做。';
@@ -16,7 +16,7 @@ export type SelectedSkillCatalogEntry = {
16
16
  };
17
17
  export declare const SELECTED_SKILL_CATALOG: readonly SelectedSkillCatalogEntry[];
18
18
  /** Roles a preset row may declare. data_collector / visualization have no method set. */
19
- export declare const SELECTED_SKILL_ENTRY_ROLES: readonly ["main", "data_junior", "web_retriever", "data_analyst", "data_collector", "visualization_specialist"];
19
+ export declare const SELECTED_SKILL_ENTRY_ROLES: readonly ["main", "data_junior", "web_retriever", "senior_analyst", "data_analyst", "data_collector", "visualization_specialist"];
20
20
  export type SelectedSkillRole = typeof SELECTED_SKILL_ENTRY_ROLES[number];
21
21
  export type SelectedSkillSelection = Partial<Record<string, boolean>>;
22
22
  export type SelectedSkillSelectionSource = SelectedSkillSelection | (() => SelectedSkillSelection);
@@ -13,7 +13,7 @@ import { SELECTED_SKILL_ROLES, SELECTED_SKILL_ROUTING as ROUTING, selectedSkillN
13
13
  export const SELECTED_SKILL_CATALOG = CATALOG;
14
14
  /** Roles a preset row may declare. data_collector / visualization have no method set. */
15
15
  export const SELECTED_SKILL_ENTRY_ROLES = [
16
- 'main', 'data_junior', 'web_retriever', 'data_analyst', 'data_collector', 'visualization_specialist',
16
+ 'main', 'data_junior', 'web_retriever', 'senior_analyst', 'data_analyst', 'data_collector', 'visualization_specialist',
17
17
  ];
18
18
  const ROUTING_BY_NAME = ROUTING;
19
19
  const PROVIDER_NAME = 'capital-selected-skills';
@@ -27,6 +27,8 @@ const ROLE_PRESET = {
27
27
  main: ROOT_PRESET_ID,
28
28
  data_junior: ROLE_PRESET_IDS.junior,
29
29
  web_retriever: ROLE_PRESET_IDS.retriever,
30
+ senior_analyst: ROLE_PRESET_IDS.analyst,
31
+ /** Legacy key: presets written before 2026-11-24 name the same role. */
30
32
  data_analyst: ROLE_PRESET_IDS.analyst,
31
33
  data_collector: ROLE_PRESET_IDS.collector,
32
34
  visualization_specialist: ROLE_PRESET_IDS.specialist,
@@ -0,0 +1,12 @@
1
+ import type { ModuleManifest } from './types.js';
2
+ export interface AnalysisModuleEntry {
3
+ readonly manifest: ModuleManifest;
4
+ /** Absolute directory handed to the worker; always inside the package. */
5
+ readonly dir: string;
6
+ readonly entrypoint: string;
7
+ }
8
+ /** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
9
+ export declare function listAnalysisModules(): readonly AnalysisModuleEntry[];
10
+ export declare function analysisModuleById(moduleId: string): AnalysisModuleEntry | undefined;
11
+ /** Test-only: drop the manifest cache so a fixture rewrite is visible. */
12
+ export declare function resetAnalysisModuleCache(): void;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Static analysis-module registry: the whitelist and the version facts, nothing else.
3
+ *
4
+ * Modules are never discovered by scanning a directory — a directory scan would turn "drop a file in
5
+ * the package" into "run arbitrary code under the private interpreter". `module.json` is the single
6
+ * manifest source; the entry only adds the resolved directory the worker gets.
7
+ */
8
+ import { readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { MODULE_DEFAULT_LIMITS } from './schemas.js';
12
+ const MODULE_ROOT = fileURLToPath(new URL('../../python/analysis/modules/', import.meta.url));
13
+ /** Registered ids, in listing order. Adding a module means adding its id here. */
14
+ const REGISTERED_MODULE_IDS = ['hello', 'financial_quality'];
15
+ const cache = new Map();
16
+ function readManifest(moduleId) {
17
+ const cached = cache.get(moduleId);
18
+ if (cached !== undefined)
19
+ return cached;
20
+ const dir = join(MODULE_ROOT, moduleId);
21
+ let parsed;
22
+ try {
23
+ parsed = JSON.parse(readFileSync(join(dir, 'module.json'), 'utf8'));
24
+ }
25
+ catch (error) {
26
+ throw new Error(`分析模块 ${moduleId} 的 module.json 读不到(${error instanceof Error ? error.message : String(error)})`);
27
+ }
28
+ const manifest = normalizeManifest(parsed, moduleId);
29
+ const entry = { manifest, dir, entrypoint: manifest.entrypoint };
30
+ cache.set(moduleId, entry);
31
+ return entry;
32
+ }
33
+ function normalizeManifest(value, moduleId) {
34
+ const raw = value;
35
+ if (typeof raw !== 'object' || raw === null || raw.id !== moduleId) {
36
+ throw new Error(`分析模块 ${moduleId} 的 manifest 缺失或 id 不符`);
37
+ }
38
+ if (typeof raw.version !== 'string' || typeof raw.description !== 'string' || typeof raw.entrypoint !== 'string') {
39
+ throw new Error(`分析模块 ${moduleId} 的 manifest 缺少 version / description / entrypoint`);
40
+ }
41
+ if (!Array.isArray(raw.roles) || raw.roles.length === 0) {
42
+ throw new Error(`分析模块 ${moduleId} 的 manifest 必须声明 roles(语义键,如 senior_analyst)`);
43
+ }
44
+ if (!Array.isArray(raw.capabilities))
45
+ throw new Error(`分析模块 ${moduleId} 的 manifest 缺少 capabilities`);
46
+ const limits = { ...MODULE_DEFAULT_LIMITS, ...(raw.limits ?? {}) };
47
+ return {
48
+ id: moduleId,
49
+ version: raw.version,
50
+ entrypoint: raw.entrypoint,
51
+ runtime: 'python',
52
+ description: raw.description,
53
+ roles: [...raw.roles],
54
+ capabilities: [...raw.capabilities],
55
+ required_fields: [...(raw.required_fields ?? [])],
56
+ input_schema: raw.input_schema ?? {},
57
+ output_schema: raw.output_schema ?? {},
58
+ assumptions: [...(raw.assumptions ?? [])],
59
+ applicability: [...(raw.applicability ?? [])],
60
+ limits,
61
+ provenance: raw.provenance ?? { source_type: 'original', license: 'MIT' },
62
+ };
63
+ }
64
+ /** Registered modules, manifest-normalized. Throws when a registered module cannot be read. */
65
+ export function listAnalysisModules() {
66
+ return REGISTERED_MODULE_IDS.map((moduleId) => readManifest(moduleId));
67
+ }
68
+ export function analysisModuleById(moduleId) {
69
+ if (!REGISTERED_MODULE_IDS.includes(moduleId))
70
+ return undefined;
71
+ return readManifest(moduleId);
72
+ }
73
+ /** Test-only: drop the manifest cache so a fixture rewrite is visible. */
74
+ export function resetAnalysisModuleCache() {
75
+ cache.clear();
76
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Analysis execution: build the module request, run it under the private interpreter, validate the
3
+ * result and persist it.
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.
9
+ */
10
+ import type { Context } from '@deepseek-ai/cordis';
11
+ 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 AnalysisFileWriter } from './storage.js';
15
+ import { type ModuleResult } from './types.js';
16
+ /** The slice of `pythonRuntime` the analysis family uses. Resolved per call, never memoized. */
17
+ export interface AnalysisRuntimeLike {
18
+ runAnalysisModule(options: {
19
+ moduleDir: string;
20
+ entrypoint: string;
21
+ runDir: string;
22
+ inputsDir: string;
23
+ capabilities: readonly string[];
24
+ limits: {
25
+ max_input_rows: number;
26
+ max_output_bytes: number;
27
+ max_log_bytes: number;
28
+ };
29
+ timeoutMs: number;
30
+ signal?: AbortSignal;
31
+ }): Promise<{
32
+ result: unknown;
33
+ pythonVersion: string;
34
+ durationMs: number;
35
+ }>;
36
+ }
37
+ /**
38
+ * Resolve the runtime service at call time: the row is opt-in and the pack may be missing, so a
39
+ * boot-time lookup would either hide the tools or fail the plugin. Missing runtime is reported with
40
+ * the same install hint as the data capabilities.
41
+ */
42
+ export declare function analysisRuntimeFrom(ctx: Context): AnalysisRuntimeLike;
43
+ /** Test-only: reset the concurrency counters between cases. */
44
+ 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
+ }
55
+ export interface AnalysisRunIndex {
56
+ readonly analysis_id: string;
57
+ readonly input_fingerprint: string;
58
+ readonly runs: readonly AnalysisRunRecord[];
59
+ }
60
+ export interface RunModuleOptions {
61
+ writer: AnalysisFileWriter;
62
+ runtime: AnalysisRuntimeLike;
63
+ session: SessionLike;
64
+ snapshot: SnapshotRecord;
65
+ module: AnalysisModuleEntry;
66
+ params: Readonly<Record<string, unknown>>;
67
+ signal?: AbortSignal;
68
+ now?: number;
69
+ }
70
+ export interface RunModuleOutcome {
71
+ readonly analysis_run_ref: string;
72
+ readonly module_id: string;
73
+ readonly module_version: string;
74
+ readonly status: ModuleResult['status'];
75
+ readonly summary: string;
76
+ readonly metrics: Record<string, unknown>;
77
+ readonly assumptions: readonly string[];
78
+ readonly limitations: readonly string[];
79
+ readonly data_gaps: readonly string[];
80
+ readonly validation: {
81
+ readonly status: 'pass' | 'warning';
82
+ readonly issues: readonly unknown[];
83
+ };
84
+ readonly reused: boolean;
85
+ }
86
+ /** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
87
+ export declare function runModuleOnSnapshot(options: RunModuleOptions): Promise<RunModuleOutcome>;
@@ -0,0 +1,225 @@
1
+ import { MODULE_DEFAULT_LIMITS } from './schemas.js';
2
+ import { REQUEST_FILE, RESULT_FILE, RUN_FILE, analysisDir, moduleRunDir, newModuleRunId, readJsonFile, runRef, writeFiles, } from './storage.js';
3
+ import { ANALYSIS_ERROR_CODES, ANALYSIS_PROTOCOL, AnalysisError } from './types.js';
4
+ import { validateAgainstSchema, validateModuleResult } from './validation.js';
5
+ import { createHash } from 'node:crypto';
6
+ import { dirname } from 'node:path';
7
+ import { stableStringify } from './snapshot.js';
8
+ /**
9
+ * Resolve the runtime service at call time: the row is opt-in and the pack may be missing, so a
10
+ * boot-time lookup would either hide the tools or fail the plugin. Missing runtime is reported with
11
+ * the same install hint as the data capabilities.
12
+ */
13
+ export function analysisRuntimeFrom(ctx) {
14
+ return {
15
+ async runAnalysisModule(options) {
16
+ const manager = ctx.get('pythonRuntime');
17
+ if (manager === undefined || typeof manager.runAnalysisModule !== 'function') {
18
+ throw new AnalysisError('analysis_runtime_not_ready', '私有 Python 运行时未加载(python-runtime 行未启用或尚未装配);请在插件设置 → 分析环境里安装 base pack');
19
+ }
20
+ return await manager.runAnalysisModule(options);
21
+ },
22
+ };
23
+ }
24
+ /** Global cap: the private interpreter is heavy and the machine is shared with the DSH host. */
25
+ const MAX_CONCURRENT_ANALYSES = 2;
26
+ let activeAnalyses = 0;
27
+ const waiting = [];
28
+ async function withAnalysisSlot(run) {
29
+ if (activeAnalyses >= MAX_CONCURRENT_ANALYSES) {
30
+ await new Promise((resolve) => waiting.push(resolve));
31
+ }
32
+ activeAnalyses += 1;
33
+ try {
34
+ return await run();
35
+ }
36
+ finally {
37
+ activeAnalyses -= 1;
38
+ waiting.shift()?.();
39
+ }
40
+ }
41
+ /** One run per snapshot at a time; the tail is kept so later runs queue instead of interleaving. */
42
+ const snapshotTails = new Map();
43
+ async function serializeBySnapshot(analysisId, run) {
44
+ const previous = snapshotTails.get(analysisId) ?? Promise.resolve();
45
+ const next = previous.catch(() => undefined).then(run);
46
+ snapshotTails.set(analysisId, next);
47
+ try {
48
+ return await next;
49
+ }
50
+ finally {
51
+ if (snapshotTails.get(analysisId) === next)
52
+ snapshotTails.delete(analysisId);
53
+ }
54
+ }
55
+ /** Test-only: reset the concurrency counters between cases. */
56
+ export function resetAnalysisRuntimeState() {
57
+ activeAnalyses = 0;
58
+ waiting.length = 0;
59
+ snapshotTails.clear();
60
+ }
61
+ function digest(value) {
62
+ return createHash('sha256').update(stableStringify(value), 'utf8').digest('hex');
63
+ }
64
+ function requireString(value, field) {
65
+ if (typeof value !== 'string' || value.trim() === '') {
66
+ throw new AnalysisError('analysis_snapshot_invalid', `快照缺少 ${field}(快照文件被改动过?)`);
67
+ }
68
+ return value;
69
+ }
70
+ /** Run one registered module against a loaded snapshot, with reuse keyed by `run_fingerprint`. */
71
+ export async function runModuleOnSnapshot(options) {
72
+ const { writer, runtime, session, snapshot, module } = options;
73
+ const now = options.now ?? Date.now();
74
+ const manifest = module.manifest;
75
+ if (!manifest.roles.includes('senior_analyst')) {
76
+ throw new AnalysisError('analysis_module_not_applicable', `模块 ${manifest.id} 未声明 senior_analyst 角色`);
77
+ }
78
+ const params = options.params ?? {};
79
+ const paramIssues = validateAgainstSchema(params, manifest.input_schema, 'params');
80
+ if (paramIssues.length > 0) {
81
+ throw new AnalysisError('analysis_input_invalid', `参数不符合 ${manifest.id} 的输入契约:${paramIssues.slice(0, 4).join(';')}`);
82
+ }
83
+ const analysisId = requireString(snapshot.analysis_id, 'analysis_id');
84
+ const paramsDigest = digest(params);
85
+ const runFingerprint = digest({
86
+ input_fingerprint: snapshot.input_fingerprint,
87
+ module_id: manifest.id,
88
+ module_version: manifest.version,
89
+ params_digest: paramsDigest,
90
+ });
91
+ return await serializeBySnapshot(analysisId, async () => {
92
+ const index = await readRunIndex(writer, session, analysisId, options.signal);
93
+ const reusable = index.runs.find((record) => record.run_fingerprint === runFingerprint && record.status !== 'failed');
94
+ if (reusable !== undefined) {
95
+ const stored = await readJsonFile(writer, session, `${moduleRunDir(analysisId, reusable.module_run_id)}/${RESULT_FILE}`, options.signal);
96
+ if (stored?.result !== undefined)
97
+ return toOutcome(analysisId, reusable.module_run_id, manifest.id, manifest.version, stored.result, true);
98
+ }
99
+ const moduleRunId = newModuleRunId();
100
+ const dir = moduleRunDir(analysisId, moduleRunId);
101
+ const request = {
102
+ protocol: ANALYSIS_PROTOCOL,
103
+ task_id: requireString(snapshot.task_id, 'task_id'),
104
+ analysis_id: analysisId,
105
+ module_run_id: moduleRunId,
106
+ snapshot_id: analysisId,
107
+ as_of: requireString(snapshot.as_of, 'as_of'),
108
+ inputs: {
109
+ datasets: snapshot.dataset_refs.map((item) => ({ dataset_id: item.dataset_id })),
110
+ profiles: snapshot.profile_refs.map((item) => ({ profile_id: item.profile_id })),
111
+ evidence: snapshot.evidence,
112
+ },
113
+ params,
114
+ };
115
+ const [requestFile] = await writeFiles(writer, session, dir, [{ name: REQUEST_FILE, content: JSON.stringify(request) }], {
116
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
117
+ what: '写入模块请求失败',
118
+ });
119
+ const runDirAbsolute = dirname(requestFile.absolutePath);
120
+ const limits = { ...MODULE_DEFAULT_LIMITS, ...manifest.limits };
121
+ let executed;
122
+ try {
123
+ executed = await withAnalysisSlot(() => runtime.runAnalysisModule({
124
+ moduleDir: module.dir,
125
+ entrypoint: module.entrypoint,
126
+ runDir: runDirAbsolute,
127
+ inputsDir: snapshot.paths.inputs_dir,
128
+ capabilities: manifest.capabilities,
129
+ limits: {
130
+ max_input_rows: limits.max_input_rows,
131
+ max_output_bytes: limits.max_output_bytes,
132
+ max_log_bytes: limits.max_log_bytes,
133
+ },
134
+ timeoutMs: limits.timeout_ms,
135
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
136
+ }));
137
+ }
138
+ catch (error) {
139
+ throw asRuntimeError(error, manifest.id);
140
+ }
141
+ const validated = validateModuleResult(executed.result, manifest);
142
+ const result = validated.result;
143
+ if (result === undefined || !validated.ok) {
144
+ await writeFiles(writer, session, dir, [{
145
+ name: RESULT_FILE,
146
+ content: JSON.stringify({ ok: false, issues: validated.issues, raw: executed.result ?? null }),
147
+ }], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入失败结果失败' });
148
+ throw new AnalysisError('analysis_output_invalid', `模块 ${manifest.id} 的结果不满足契约:${validated.issues.slice(0, 4).map((issue) => issue.detail).join(';')}`);
149
+ }
150
+ const moduleResult = result;
151
+ await writeFiles(writer, session, dir, [{
152
+ name: RESULT_FILE,
153
+ content: JSON.stringify({
154
+ ok: true,
155
+ python: executed.pythonVersion,
156
+ duration_ms: executed.durationMs,
157
+ result: moduleResult,
158
+ }),
159
+ }], { ...(options.signal === undefined ? {} : { signal: options.signal }), overwrite: true, what: '写入模块结果失败' });
160
+ const record = {
161
+ module_run_id: moduleRunId,
162
+ module_id: manifest.id,
163
+ module_version: manifest.version,
164
+ params_digest: paramsDigest,
165
+ run_fingerprint: runFingerprint,
166
+ status: moduleResult.status,
167
+ created_at: now,
168
+ };
169
+ const nextIndex = {
170
+ analysis_id: analysisId,
171
+ input_fingerprint: snapshot.input_fingerprint,
172
+ runs: [...index.runs, record],
173
+ };
174
+ await writeFiles(writer, session, analysisDir(analysisId), [{ name: RUN_FILE, content: JSON.stringify(nextIndex) }], {
175
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
176
+ overwrite: true,
177
+ what: '写入 run.json 失败',
178
+ });
179
+ return toOutcome(analysisId, moduleRunId, manifest.id, manifest.version, moduleResult, false);
180
+ });
181
+ }
182
+ function toOutcome(analysisId, moduleRunId, moduleId, moduleVersion, result, reused) {
183
+ const issues = result.status === 'failed' ? [{ code: 'analysis_module_failed', detail: result.summary }] : [];
184
+ return {
185
+ analysis_run_ref: runRef(analysisId, moduleRunId),
186
+ module_id: moduleId,
187
+ module_version: moduleVersion,
188
+ status: result.status,
189
+ summary: typeof result.summary === 'string' ? result.summary : '',
190
+ metrics: (result.metrics ?? {}),
191
+ assumptions: result.assumptions ?? [],
192
+ limitations: result.limitations ?? [],
193
+ data_gaps: result.data_gaps ?? [],
194
+ validation: { status: issues.length === 0 ? 'pass' : 'warning', issues },
195
+ reused,
196
+ };
197
+ }
198
+ function asRuntimeError(error, moduleId) {
199
+ if (error instanceof AnalysisError)
200
+ return error;
201
+ const code = error?.code;
202
+ const message = error instanceof Error ? error.message : String(error);
203
+ // A module-declared code (`AnalysisInputError`) becomes the protocol code; only known codes pass,
204
+ // so a module cannot invent one or impersonate a host-side failure.
205
+ const declared = error?.analysisCode;
206
+ if (typeof declared === 'string' && ANALYSIS_ERROR_CODES.includes(declared)) {
207
+ return new AnalysisError(declared, `模块 ${moduleId} 拒绝本次输入:${message}`);
208
+ }
209
+ if (code === 'timeout')
210
+ return new AnalysisError('analysis_timeout', `模块 ${moduleId} 超时:${message}`);
211
+ if (code === 'cancelled')
212
+ return new AnalysisError('analysis_cancelled', `模块 ${moduleId} 被取消`);
213
+ // `resolveDataRuntime` reports a missing base pack as `data-runtime-not-ready`; without this the
214
+ // documented `analysis_runtime_not_ready` degraded into `analysis_output_invalid` (2026-11-24 实测).
215
+ if (code === 'runtime-not-ready' || code === 'data-runtime-not-ready') {
216
+ return new AnalysisError('analysis_runtime_not_ready', message);
217
+ }
218
+ return new AnalysisError('analysis_output_invalid', `模块 ${moduleId} 执行失败:${message}`);
219
+ }
220
+ async function readRunIndex(writer, session, analysisId, signal) {
221
+ const stored = await readJsonFile(writer, session, `${analysisDir(analysisId)}/${RUN_FILE}`, signal);
222
+ if (stored === undefined)
223
+ return { analysis_id: analysisId, input_fingerprint: '', runs: [] };
224
+ return { analysis_id: analysisId, input_fingerprint: stored.input_fingerprint ?? '', runs: Array.isArray(stored.runs) ? stored.runs : [] };
225
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * JSON Schemas for the analysis family and the module protocol. One carrier per shape: tools,
3
+ * host validation and the worker all read these, so a hand-written second copy would drift.
4
+ *
5
+ * `additionalProperties: false` everywhere is deliberate — an undeclared field is a protocol
6
+ * change, and silently accepting it would make the artifact contract a suggestion.
7
+ */
8
+ /** Submit-time budgets; exceeding one names the offending section (`analysis_result_too_large`). */
9
+ export declare const ARTIFACT_MAX_CHARS = 20000;
10
+ export declare const HEADLINE_MAX_CHARS = 300;
11
+ export declare const THESIS_MAX_CHARS = 1200;
12
+ export declare const STATEMENT_MAX_CHARS = 600;
13
+ export declare const MAX_CLAIMS = 20;
14
+ export declare const MAX_SCENARIOS = 8;
15
+ /** Bounded evidence intake: single item bytes and total count. */
16
+ export declare const EVIDENCE_ITEM_MAX_BYTES = 2048;
17
+ export declare const EVIDENCE_MAX_ITEMS = 20;
18
+ /** `expires_at = min(created_at + 7d, earliest input retention)`. */
19
+ export declare const SNAPSHOT_TTL_MS: number;
20
+ /** Module limits when a manifest omits one; the manifest may only tighten them. */
21
+ export declare const MODULE_DEFAULT_LIMITS: {
22
+ readonly timeout_ms: 30000;
23
+ readonly max_input_rows: 200000;
24
+ readonly max_output_bytes: 1048576;
25
+ readonly max_log_bytes: 65536;
26
+ };
27
+ export declare const EVIDENCE_SCHEMA: Record<string, unknown>;
28
+ export declare const NUMBER_ANCHOR_SCHEMA: Record<string, unknown>;
29
+ export declare const CLAIM_SCHEMA: Record<string, unknown>;
30
+ export declare const CALCULATION_SCHEMA: Record<string, unknown>;
31
+ export declare const PEER_EXCHANGE_SCHEMA: Record<string, unknown>;
32
+ export declare const SCENARIO_SCHEMA: Record<string, unknown>;
33
+ /** `submit_analysis` parameters: the final artifact, minus the host-written `validation`. */
34
+ export declare const ANALYSIS_ARTIFACT_SCHEMA: Record<string, unknown>;
35
+ export declare const MODULE_MANIFEST_SCHEMA: Record<string, unknown>;
36
+ export declare const MODULE_REQUEST_SCHEMA: Record<string, unknown>;
37
+ /** Worker result. `outputs` carry refs only; large payloads live under `modules/<id>/outputs/`. */
38
+ export declare const MODULE_RESULT_SCHEMA: Record<string, unknown>;
39
+ /** `context.read_dataset` shape handed to a module; `rows` never crosses the tool boundary. */
40
+ export declare const DATASET_VIEW_SCHEMA: Record<string, unknown>;
41
+ export declare const CREATE_SNAPSHOT_PARAMETERS: Record<string, unknown>;
42
+ export declare const CREATE_SNAPSHOT_OUTPUT: Record<string, unknown>;
43
+ export declare const READ_PROFILE_PARAMETERS: Record<string, unknown>;
44
+ /** Bounded profile facts; `hint` is present when the payload was cut by the shared size gate. */
45
+ export declare const READ_PROFILE_OUTPUT: Record<string, unknown>;
46
+ export declare const LIST_MODULES_OUTPUT: Record<string, unknown>;
47
+ export declare const DESCRIBE_MODULE_OUTPUT: Record<string, unknown>;
48
+ export declare const LIST_MODULES_PARAMETERS: Record<string, unknown>;
49
+ export declare const DESCRIBE_MODULE_PARAMETERS: Record<string, unknown>;
50
+ export declare const RUN_ANALYSIS_PARAMETERS: Record<string, unknown>;
51
+ export declare const RUN_ANALYSIS_OUTPUT: Record<string, unknown>;
52
+ export declare const SUBMIT_ANALYSIS_OUTPUT: Record<string, unknown>;