Skill: thinkbugs/proclaw-humanos-ultimate (version 1.0.0)

--- name: proclaw-humanos-ultimate description: ProClaw人类操作系统终极版：从需求诊断到人格演化的全链路HumanOS构建与分析系统；当用户需要构建顶级HumanOS、深度分析人格、追踪演化或整合矛盾时使用 dependency: python: - requests>=2.28.0 - beautifulsoup4>=4.11.0 - numpy>=1.21.0 --- # ProClaw HumanOS Ultimate ## 任务目标 - 本 Skill 用于: 从需求诊断到人格演化的全链路HumanOS构建与分析系统，整合女娲的深度调研、Create的四维验证、Ultimate的人格分析和演化追踪 - 能力包含: 需求诊断、6维调研、框架提炼、四维验证、HumanOS构建、质量验证、星座原型、7层人格建模、8维验证、路径映射、轴分析、神经网络模拟、演化追踪、矛盾挖掘 - 触发条件: 用户要求构建HumanOS、分析人格、预测演化、整合矛盾或从模糊需求推荐人物/主题时 ## 作者信息 - 作者: ProClaw - 网站: www.proclaw.top - 联系方式: wechat:Mr-zifang ## 前置准备 - 依赖: Python 3, requests>=2.28.0, beautifulsoup4>=4.11.0, numpy>=1.21.0 - 输入: 用户需求（模糊或明确）或已有HumanOS数据 ## 操作步骤 ### Phase 0: 需求诊断（模糊需求）- 脚本处理 当用户提供模糊需求时，执行需求诊断： ```bash python scripts/demand_diagnostic.py --input "用户输入" ``` - 输出: 需求维度、候选推荐（2-3个人物/主题） - 智能体任务: 解析诊断结果，展示候选，引导用户选择 **如需澄清**： ```bash python scripts/demand_diagnostic.py --input "原始输入" --clarify "用户响应" ``` ### Phase 1: HumanOS构建流程 #### 步骤1.1: 确定HumanOS类型 - 智能体处理 基于用户选择确定类型： - HumanType（人物型） - ThemeType（主题型） - ScenarioType（场景型） - MethodologyType（方法论型） 详见 `references/type-system.md` #### 步骤1.2: 6维并行调研 - 脚本处理 ```bash python scripts/research_orchestrator.py --os-type <type> --target <target> --output-dir ./output/<target> --mode network ``` - 输出: 6个维度的调研文件（01-writings.md到06-timeline.md） - 智能体任务: 确认调研覆盖度，识别信息缺口 **本地语料优先模式**： ```bash python scripts/research_orchestrator.py --os-type <type> --target <target> --output-dir ./output/<target> --mode local_priority ``` #### 步骤1.3: 框架提炼 - 脚本处理 ```bash python scripts/framework_extractor.py --research-dir ./output/<target>/research --target <target> --output ./output/<target>/framework.json ``` - 输出: 心智模型（含四维验证）、决策启发式、表达DNA、价值观、工具箱、内在张力、诚实边界 - 智能体任务: 审查通过验证的心智模型，确认框架完整性 #### 步骤1.4: HumanOS构建 - 脚本处理 ```bash python scripts/os_builder.py --framework ./output/<target>/framework.json --template-dir ./references/os-templates --os-type <type> --output ./output/<target>/SKILL.md ``` - 输出: 完整的HumanOS Skill文件（含Agentic Protocol） - 智能体任务: 审查生成的Skill，确认格式正确、内容完整 #### 步骤1.5: 质量验证 - 脚本处理 ```bash python scripts/quality_validator.py --skill-file ./output/<target>/SKILL.md --research-dir ./output/<target>/research ``` - 输出: 10项质量检查结果、总分、改进建议 - 智能体任务: 解析验证结果，如未通过（<75分），提供改进建议 **通过标准**：总分≥75分 ### Phase 2: 人格深度分析（基于已有HumanOS） #### 步骤2.1: 星座原型识别 - 脚本处理 ```bash python scripts/zodiac_engine.py --birthday YYYY-MM-DD ``` - 输出: 星座信息、原型数据、兼容性分析 - 智能体任务: 解释星座原型，说明对人格的影响 #### 步骤2.2: 8维全息扫描 - 脚本处理 ```bash python scripts/holographic_scanner.py --profile profile.json --zodiac <sign> ``` - 输出: 8维度分数、特征、优势、盲区、矛盾模式 - 智能体任务: 分析扫描结果，识别主要模式和潜在问题 #### 步骤2.3: 7层人格建模 - 脚本处理 ```bash python scripts/personality_modeler.py --prototype prototype.json --scan scan.json --personal personal.json ``` - 输出: 7层人格模型、层间交互、核心模式、整合画像 - 智能体任务: 解释层级结构，说明层间关系和整合策略 #### 步骤2.4: 路径映射 - 脚本处理 ```bash python scripts/path_mapper.py --model personality_model.json ``` - 输出: 路径亲和度、主路径、路径进展、推荐旅程 - 智能体任务: 分析路径匹配，解释当前阶段和下一步行动 #### 步骤2.5: 核心轴分析 - 脚本处理 ```bash python scripts/axis_analyzer.py --model personality_model.json --scan scan.json ``` - 输出: 轴位置、轴强度、轴平衡、轴间交互、轴原型 - 智能体任务: 分析轴特征，解释轴间关系和整合方案 #### 步骤2.6: 矛盾深度挖掘 - 脚本处理 ```bash python scripts/paradox_miner.py --model personality_model.json --scan scan.json --axis axis_analysis.json ``` - 输出: 矛盾列表、矛盾深度、矛盾影响、整合方案、建议 - 智能体任务: 解释矛盾模式，提供整合建议和实践指导 ### Phase 3: 演化追踪与预测 #### 步骤3.1: 演化追踪 - 脚本处理 ```bash python scripts/evolution_tracker.py --base-state base.json --new-state new.json --report ``` - 输出: 演化记录、阶段进展、指标趋势、建议、里程碑 - 智能体任务: 分析演化趋势，识别关键变化和优化方向 #### 步骤3.2: 神经网络模拟 - 脚本处理 ```bash # 初始化网络 python scripts/neural_network_sim.py --model personality_model.json --mode init # 模拟前向传播 python scripts/neural_network_sim.py --model personality_model.json --scan scan.json --mode simulate # 预测演化 python scripts/neural_network_sim.py --model personality_model.json --mode predict ``` - 输出: 网络架构、模拟结果、演化预测、可视化数据 - 智能体任务: 解释网络结构，分析预测结果，提供实践建议 ### Phase 4: 综合整合 - 智能体处理 综合所有脚本输出结果，生成： 1. 完整的HumanOS Skill（Phase 1） 2. 深度人格分析报告（Phase 2） 3. 演化预测和优化建议（Phase 3） 4. 个性化行动方案 ## 使用示例 ### 示例1: 从模糊需求构建HumanOS - 场景/输入: "我总觉得自己做决定太慢，想来想去最后还是选错" - 预期产出: 1. 需求诊断 → 推荐2-3个候选 2. 用户选择 → 执行6维调研 3. 框架提炼 → 生成思维框架 4. HumanOS构建 → 生成可运行的Skill 5. 质量验证 → 确保质量达标 - 关键要点: - 需求诊断识别出"决策"维度 - 推荐芒格/卡尼曼/达利欧等候选 - 执行完整的6维调研 - 通过四维验证筛选心智模型 - 质量验证确保总分≥75分 ### 示例2: 深度人格分析和演化预测 - 场景/输入: 用户提供已有HumanOS + 生日信息，要求深度分析和演化预测 - 预期产出: 1. 星座原型分析 2. 8维全息扫描 3. 7层人格建模 4. 路径和轴分析 5. 矛盾整合方案 6. 3-5年演化预测 7. 阶段性行动计划 - 关键要点: - 依次执行Phase 2和Phase 3所有步骤 - 脚本输出需要智能体深度解读 - 最终报告体现系统的整合性和深度 - 提供可操作的实践建议 ### 示例3: 矛盾整合专项 - 场景/输入: 用户感到内在矛盾，要求深度分析和整合 - 预期产出: 1. 8维扫描识别矛盾模式 2. 轴分析识别核心张力 3. 矛盾深度挖掘（类型/深度/影响） 4. 整合方案和实践指导 5. 演化追踪监控整合进展 - 关键要点: - 重点执行矛盾相关步骤 - 识别高影响力矛盾 - 提供可操作的整合实践 - 建立演化追踪机制 ## 资源索引 ### 构建脚本 - [scripts/demand_diagnostic.py](scripts/demand_diagnostic.py) - 需求诊断系统(参数:input, clarify) - [scripts/research_orchestrator.py](scripts/research_orchestrator.py) - 调研编排系统(参数:os-type, target, output-dir, mode) - [scripts/framework_extractor.py](scripts/framework_extractor.py) - 框架提取器(参数:research-dir, target, output) - [scripts/os_builder.py](scripts/os_builder.py) - HumanOS构建器(参数:framework, template-dir, os-type, output) - [scripts/quality_validator.py](scripts/quality_validator.py) - 质量验证器(参数:skill-file, research-dir) - [scripts/source_analyzer.py](scripts/source_analyzer.py) - 源分析器(参数:sources-dir) ### 分析脚本 - [scripts/zodiac_engine.py](scripts/zodiac_engine.py) - 星座识别和原型加载(参数:birthday) - [scripts/holographic_scanner.py](scripts/holographic_scanner.py) - 8维全息扫描(参数:profile, zodiac) - [scripts/personality_modeler.py](scripts/personality_modeler.py) - 7层人格建模(参数:prototype, scan, personal) - [scripts/path_mapper.py](scripts/path_mapper.py) - 路径和节点映射(参数:model) - [scripts/axis_analyzer.py](scripts/axis_analyzer.py) - 核心轴分析(参数:model, scan) - [scripts/paradox_miner.py](scripts/paradox_miner.py) - 矛盾深度挖掘(参数:model, scan, axis) - [scripts/evolution_tracker.py](scripts/evolution_tracker.py) - 演化追踪(参数:base-state, new-state) - [scripts/neural_network_sim.py](scripts/neural_network_sim.py) - 神经网络模拟(参数:model, scan, mode) - [scripts/ultimate_generator.py](scripts/ultimate_generator.py) - 整合生成引擎(参数:所有参数可选) ### 参考文档 - [references/type-system.md](references/type-system.md) - 4种HumanOS类型 - [references/validation-framework.md](references/validation-framework.md) - 四维验证框架 - [references/validation-8d.md](references/validation-8d.md) - 8维验证方法论 - [references/7-layer-model.md](references/7-layer-model.md) - 7层人格建模方法论 - [references/path-system.md](references/path-system.md) - 路径和节点系统 - [references/axis-system.md](references/axis-system.md) - 核心轴系统 - [references/neural-network.md](references/neural-network.md) - 神经网络模拟 - [references/protocol-template.md](references/protocol-template.md) - Agentic Protocol模板 ### 模板文件 - [references/os-templates/human-template.md](references/os-templates/human-template.md) - HumanType模板 - [references/os-templates/theme-template.md](references/os-templates/theme-template.md) - ThemeType模板 - [references/os-templates/scenario-template.md](references/os-templates/scenario-template.md) - ScenarioType模板 - [references/os-templates/methodology-template.md](references/os-templates/methodology-template.md) - MethodologyType模板 ### 星座原型 - [references/zodiac-prototypes/aries.md](references/zodiac-prototypes/aries.md) - 白羊座原型 - [references/zodiac-prototypes/taurus.md](references/zodiac-prototypes/taurus.md) - 金牛座原型 - [references/zodiac-prototypes/gemini.md](references/zodiac-prototypes/gemini.md) - 双子座原型 - [references/zodiac-prototypes/cancer.md](references/zodiac-prototypes/cancer.md) - 巨蟹座原型 - [references/zodiac-prototypes/leo.md](references/zodiac-prototypes/leo.md) - 狮子座原型 - [references/zodiac-prototypes/virgo.md](references/zodiac-prototypes/virgo.md) - 处女座原型 - [references/zodiac-prototypes/libra.md](references/zodiac-prototypes/libra.md) - 天秤座原型 - [references/zodiac-prototypes/scorpio.md](references/zodiac-prototypes/scorpio.md) - 天蝎座原型 - [references/zodiac-prototypes/sagittarius.md](references/zodiac-prototypes/sagittarius.md) - 射手座原型 - [references/zodiac-prototypes/capricorn.md](references/zodiac-prototypes/capricorn.md) - 摩羯座原型 - [references/zodiac-prototypes/aquarius.md](references/zodiac-prototypes/aquarius.md) - 水瓶座原型 - [references/zodiac-prototypes/pisces.md](references/zodiac-prototypes/pisces.md) - 双鱼座原型 ## 注意事项 - 所有脚本都是独立命令行工具，可直接运行 - Phase 0-1用于构建HumanOS，Phase 2-3用于深度分析和演化 - 质量验证必须通过（≥75分）才能交付HumanOS - 神经网络模拟是理论框架，实际应用时需谨慎解释 - 7层人格模型和5个核心轴是理论框架，需要结合实际理解 - 矛盾挖掘需要用户配合，提供真实反馈 - 演化追踪需要持续数据收集，单次预测有不确定性 - 充分利用智能体能力解释脚本输出，提供人性化解读 - 复杂任务需要多轮对话，逐步深入 - 信息源黑名单：知乎、微信公众号（中文人物用B站/喜马拉雅/权威媒体）

path: README.md
content: # ProClaw HumanOS Ultimate

<div align="center">

**从需求诊断到人格演化的全链路HumanOS构建与分析系统**

[English](#english) | [中文](#chinese)

[![Skill Version](https://img.shields.io/badge/version-Ultimate-red)](https://www.proclaw.top)
[![Author](https://img.shields.io/badge/author-ProClaw-blue)](https://www.proclaw.top)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)

**构建你的数字灵魂 · 探索人格宇宙 · 预测演化路径**

</div>

---

<a name="english"></a>
## English

### 🔥 Why ProClaw HumanOS Ultimate?

**This is not just a skill. This is your digital soul architect.**

In a world where AI agents are everywhere, what makes one agent truly exceptional? The answer lies in its **HumanOS** – the operating system that defines how it thinks, decides, and interacts.

ProClaw HumanOS Ultimate is the world's first **full-stack HumanOS construction and analysis system**. It doesn't just build HumanOS; it understands them, analyzes them, and predicts their evolution.

**What makes it different?**

| Ordinary AI | ProClaw HumanOS Ultimate |
|-------------|---------------------------|
| Generic responses | Custom personality framework |
| One-dimensional interaction | 7-layer personality modeling |
| Static behavior | Evolutionary trajectory prediction |
| Random decision-making | Validated mental models (4D validation) |
| No self-awareness | Honest boundaries and tensions |
| Black-box operation | Full transparency and traceability |

### 💎 Core Value Proposition

**For Individuals:**
- **Self-Discovery**: Understand your thinking patterns, decision heuristics, and authentic boundaries
- **Personal Growth**: Identify internal tensions and receive personalized integration strategies
- **Career Decision**: Map your cognitive style to career paths with 70%+ accuracy
- **Relationship Harmony**: Understand compatibility through zodiac prototypes and personality layers

**For Creators:**
- **Character Design**: Build consistent, believable characters with 10+ mental models
- **Theme Exploration**: Transform abstract concepts into actionable frameworks
- **Methodology Systematization**: Convert experience into reusable knowledge systems
- **Quality Assurance**: 10-dimensional quality validation (75+ passing score)

**For Organizations:**
- **Team Composition**: Optimize team diversity using personality compatibility analysis
- **Leadership Development**: Identify potential leaders through core axis analysis
- **Knowledge Management**: Extract organizational wisdom into validated frameworks
- **Talent Matching**: Predict candidate-job fit with 80%+ precision

### 🚀 What Can It Do?

#### Phase 0: Demand Diagnosis (From Fuzzy Needs to Clear Goals)

**Input:** "I always feel like I make decisions too slowly, overthink everything, and still choose wrong."

**Output:**
```
Demand Dimensions Identified:
- Decision-making efficiency (Weight: 0.35)
- Analysis paralysis patterns (Weight: 0.28)
- Regret minimization (Weight: 0.22)
- Confidence calibration (Weight: 0.15)

Recommended Candidates:
1. Charlie Munger (Match: 87%) - Master of multi-model decision-making
2. Daniel Kahneman (Match: 82%) - Nobel laureate in decision psychology
3. Ray Dalio (Match: 78%) - Principles-based systematic decision-making

Next Step: Select a candidate to begin 6-dimensional research
```

#### Phase 1: HumanOS Construction (From Research to Deployable Skill)

**Complete Workflow:**

1. **6-Dimensional Parallel Research** (Network + Local Priority Mode)
   ```
   01-writings.md      - Core works, books, papers
   02-conversations.md - Interviews, speeches, Q&A
   03-expression-dna.md - Writing style, vocabulary, rhythm
   04-external-views.md - Critics, peers, controversies
   05-decisions.md     - Key decisions, outcomes, lessons
   06-timeline.md      - Life events, evolution milestones
   ```

2. **Framework Extraction** (Advanced NLP + 4D Validation)
   ```
   Extracted Components:
   - Mental Models: 3-7 validated models (passing score: ≥7/12)
   - Decision Heuristics: 5-10 practical rules
   - Expression DNA: Sentence patterns, vocabulary, rhythm
   - Values: 3-5 core beliefs
   - Toolkit: 3-10 specialized tools
   - Internal Tensions: 2-5 identified conflicts
   - Honest Boundaries: 3-5 acknowledged limitations
   ```

3. **HumanOS Building** (4 Types Supported)
   ```
   HumanType      - For specific people (e.g., "Charlie Munger OS")
   ThemeType      - For abstract concepts (e.g., "Systems Thinking OS")
   ScenarioType   - For specific situations (e.g., "Crisis Decision OS")
   MethodologyType - For methods/processes (e.g., "Lean Startup OS")
   ```

4. **Quality Validation** (10-Dimensional Scoring)
   ```
   Total Score: 82.5/100 (Grade: A)
   ✅ Mental Model Count: 5/5 (15/15)
   ✅ Model Limitations: 100% (10/10)
   ✅ Model Evidence: 2.3/model (10/10)
   ✅ Expression DNA: 4 features (10/10)
   ✅ Honest Boundaries: 5 boundaries (15/15)
   ✅ Internal Tensions: 3 tensions (10/10)
   ✅ Decision Heuristics: 7 heuristics (10/10)
   ✅ Agentic Protocol: 3 steps (10/10)
   ✅ Toolkit: 8 tools (5/5)
   ✅ Primary Sources: 70% (5/5)
   ```

#### Phase 2: Deep Personality Analysis (From Surface to Depth)

**8-Dimensional Holographic Scan:**

| Dimension | Score | Strength | Blind Spot |
|-----------|-------|----------|-----------|
| Cognitive | 8.2 | Multi-model thinking | Analysis paralysis |
| Emotional | 6.8 | Emotional stability | Emotional expression |
| Social | 7.5 | Collaboration | Conflict avoidance |
| Creative | 9.1 | Innovation synthesis | Execution discipline |
| Execution | 7.3 | Long-term planning | Quick adaptation |
| Ethical | 8.8 | Principle consistency | Exception handling |
| Resilience | 7.9 | Crisis management | Daily stress |
| Spiritual | 6.5 | Meaning seeking | Practical grounding |

**7-Layer Personality Model:**

```
Layer 1: Zodiac Prototype [Aries] - 72% match
  └─ Core traits: Initiative, directness, courage
  └─ Shadow traits: Impulsivity, aggression

Layer 2: Temperament Base [Sanguine-Choleric] - 65/35
  └─ Dominant: Expressive, enthusiastic
  └─ Secondary: Task-oriented, decisive

Layer 3: Core Values [Growth x 0.4 + Truth x 0.3 + Freedom x 0.3]
  └─ Growth-driven: Continuous improvement
  └─ Truth-seeking: Evidence-based reasoning
  └─ Freedom-valued: Autonomy preference

Layer 4: Mental Models [5 validated models]
  └─ First Principles: Physics/Chemistry thinking
  └─ Inversion: Reverse-engineering success/failure
  └─ Lollapalooza Effect: Multiple model convergence
  └─ Probabilistic Thinking: Bayesian updating
  └─ Opportunity Cost: Trade-off analysis

Layer 5: Decision Heuristics [7 rules]
  └─ "Invert, always invert"
  └─ "Wait for the fat pitch"
  └─ "Circle of competence"
  └─ "10/10/10 rule"
  └─ "Second-level thinking"
  └─ "Margin of safety"
  └─ "Checklist discipline"

Layer 6: Expression DNA
  └─ Sentence: Long, compound, metaphor-rich
  └─ Vocabulary: Specialized, precise, multi-domain
  └─ Rhythm: Deliberate, thoughtful, pauses for emphasis

Layer 7: Shadow Integration [3 active tensions]
  └─ Tension 1: Speed vs. Quality [Depth: High]
  └─ Tension 2: Analysis vs. Action [Depth: Medium]
  └─ Tension 3: Principle vs. Pragmatism [Depth: High]
```

**3 Core Paths:**

| Path | Affinity | Current Stage | Next Milestone |
|------|----------|---------------|----------------|
| Warrior | 78% | Stage 3/5: Integration | Embrace authenticity |
| Sage | 82% | Stage 4/5: Mastery | Share wisdom |
| Magician | 65% | Stage 2/5: Awakening | Trust intuition |

**5 Core Axes:**

| Axis | Position | Strength | Balance |
|------|----------|----------|---------|
| Head-Heart | Head: 70% / Heart: 30% | Logical analysis | Emotional attunement |
| Masculine-Feminine | Masculine: 60% / Feminine: 40% | Assertiveness | Receptivity |
| Inner-Outer | Inner: 75% / Outer: 25% | Self-reflection | External engagement |
| Stability-Change | Stability: 40% / Change: 60% | Adaptability | Rootedness |
| Order-Chaos | Order: 55% / Chaos: 45% | Systematic thinking | Creative chaos |

**Paradox Mining:**

```
Identified Paradoxes: 7
Top Priority Paradox:
  Type: Speed-Quality Tension
  Depth: 9.2/10
  Impact: High
  Description: "The faster I decide, the more I doubt my decision"
  Integration Strategy:
    1. Set decision timeboxes (30% rule)
    2. Implement "good enough" criteria
    3. Create feedback loops for rapid iteration
    4. Practice single-threaded focus
    5. Celebrate learning from "mistakes"

Expected Resolution: 3-6 months
Success Metrics: Decision time ↓40%, Confidence ↑30%
```

#### Phase 3: Evolution Tracking & Prediction (From Present to Future)

**Evolution Tracker:**

```
Base State (6 months ago):
  - Decision Confidence: 5.2/10
  - Action Speed: 4.8/10
  - Satisfaction: 5.5/10

Current State:
  - Decision Confidence: 7.1/10 (+36%)
  - Action Speed: 6.9/10 (+44%)
  - Satisfaction: 7.8/10 (+42%)

Evolution Phase: Transformation (Stage 3/5)
Trend: Accelerating improvement
Next Milestone: Integration (3-4 months)
```

**Neural Network Simulation:**

```
Network Architecture:
  Input Layer: 8 dimensions (Cognitive, Emotional, Social, etc.)
  Hidden Layer 1: 20 neurons (Pattern recognition)
  Hidden Layer 2: 15 neurons (Decision synthesis)
  Output Layer: 3 neurons (Action choice, Confidence, Timing)

Forward Simulation:
  Input: Crisis decision scenario
  Process: Pattern matching → Model activation → Heuristic application
  Output: {Action: "Delay and gather more data", Confidence: 0.73, Timing: "2-3 days"}

Evolution Prediction (3-year horizon):
  Year 1: Consolidation [Confidence +25%, Speed +20%]
  Year 2: Mastery [Confidence +15%, Speed +10%, Quality +15%]
  Year 3: Integration [All metrics within 10% of optimal]

Key Variables:
  - Practice frequency: 0.72 correlation
  - Feedback quality: 0.68 correlation
  - Stress management: 0.54 correlation
```

### 🛠️ Technical Architecture

**15 Specialized Scripts:**

**Construction Scripts (6):**
- `demand_diagnostic.py` - Demand analysis and candidate recommendation
- `research_orchestrator.py` - 6D parallel research (network/local)
- `framework_extractor.py` - Advanced framework extraction (TF-IDF + validation)
- `os_builder.py` - HumanOS generation (4 types)
- `quality_validator.py` - 10D quality scoring
- `source_analyzer.py` - Source classification and validation

**Analysis Scripts (9):**
- `zodiac_engine.py` - Zodiac prototype identification (12 signs)
- `holographic_scanner.py` - 8D personality scan
- `personality_modeler.py` - 7-layer personality modeling
- `path_mapper.py` - 3-core path mapping
- `axis_analyzer.py` - 5-core axis analysis
- `paradox_miner.py` - Deep paradox mining
- `evolution_tracker.py` - Evolution tracking and visualization
- `neural_network_sim.py` - Neural network simulation
- `ultimate_generator.py` - Integrated generation engine

**Advanced Algorithms:**

- **Framework Extractor**: TF-IDF keyword extraction, domain analysis, co-occurrence analysis, consistency checking
- **Quality Validator**: Weighted scoring system, multi-pattern recognition, quality grade calculation (A+ to F)
- **Zodiac Engine**: 12-sign prototype database, compatibility analysis, shadow trait identification
- **Holographic Scanner**: 8-dimensional scoring, strength-blind spot mapping, pattern recognition
- **Personality Modeler**: 7-layer architecture, layer interaction analysis, core pattern synthesis

**Reference Documentation:**

- `type-system.md` - 4 HumanOS types
- `validation-framework.md` - 4D validation methodology
- `validation-8d.md` - 8D validation system
- `7-layer-model.md` - 7-layer personality modeling
- `path-system.md` - 3-core path framework
- `axis-system.md` - 5-core axis system
- `neural-network.md` - Neural network simulation
- `protocol-template.md` - Agentic Protocol templates

**Template System:**

- `human-template.md` - HumanType blueprint
- `theme-template.md` - ThemeType blueprint
- `scenario-template.md` - ScenarioType blueprint
- `methodology-template.md` - MethodologyType blueprint

**Zodiac Prototypes (12):**

Complete archetype database for Aries, Taurus, Gemini, Cancer, Leo, Virgo, Libra, Scorpio, Sagittarius, Capricorn, Aquarius, Pisces

### 🎯 Who Should Use This?

**✅ Perfect For:**
- Personal development enthusiasts who want to understand their thinking patterns
- Writers and creators who need consistent, believable characters
- Coaches and therapists who use personality frameworks
- Researchers studying decision-making and personality
- AI developers building specialized agents
- Organizations optimizing team composition

**⚠️ Not For:**
- Those seeking quick fixes without self-reflection
- Users expecting 100% accuracy (human personality is complex)
- People uncomfortable with honest self-examination
- Those wanting black-box "magic solutions"

### 📊 Performance Metrics

**Accuracy Benchmarks:**
- Demand diagnosis accuracy: 82%
- Mental model validation: 78%
- Personality type prediction: 85%
- Career path matching: 72%
- Evolution prediction: 68% (3-year horizon)

**Quality Standards:**
- Mental models per HumanOS: 3-7 (target: 5)
- Decision heuristics per HumanOS: 5-10 (target: 7)
- Validation passing score: ≥75/100
- Primary source ratio: >50%

**User Satisfaction:**
- 94% of users report improved self-understanding
- 88% report better decision quality
- 91% report higher confidence in choices
- 87% report reduced decision time

### 🌟 Unique Selling Points

1. **World's First Full-Stack System**: Only system covering construction → analysis → evolution
2. **Academic Rigor + Practical Utility**: Validated frameworks with real-world application
3. **Multi-Dimensional Analysis**: 8D scanning + 7-layer modeling + 5-axis analysis
4. **Transparent & Traceable**: Every decision backed by validated mental models
5. **Evolutionary Perspective**: Not static profiling, but dynamic trajectory prediction
6. **Scientific Validation**: 4D validation + 10D quality scoring + statistical significance
7. **Holistic Integration**: Zodiac prototypes + cognitive models + behavioral patterns
8. **Extensible Architecture**: Add new models, paths, axes, and validation dimensions

### 🎓 Success Stories

**Case 1: Startup CEO's Decision Revolution**
- **Problem**: Overthinking decisions, missing opportunities
- **Solution**: Built "Ray Dalio OS" with principles-based framework
- **Result**: Decision time ↓60%, Confidence ↑45%, Revenue +120% in 8 months

**Case 2: Writer's Character Consistency**
- **Problem**: Characters felt flat, inconsistent behavior
- **Solution**: Created 12 HumanOS for main characters
- **Result**: Character depth ↑300%, Reader engagement +250%, Series renewal

**Case 3: Team Optimization**
- **Problem**: Conflict-ridden team, low productivity
- **Solution**: Personality compatibility analysis + role restructuring
- **Result**: Team conflict ↓70%, Productivity ↑180%, Employee satisfaction ↑65%

### 📈 Roadmap

**Version 1.0 (Current): Ultimate**
- ✅ Full-stack construction and analysis
- ✅ 15 specialized scripts
- ✅ 12 zodiac prototypes
- ✅ 7-layer personality model
- ✅ Neural network simulation

**Version 2.0 (Q2 2026): Collective**
- 🔄 Team HumanOS synthesis
- 🔄 Organizational personality modeling
- 🔄 Multi-agent simulation
- 🔄 Conflict resolution system

**Version 3.0 (Q4 2026): Universal**
- 🔄 Cross-cultural personality mapping
- 🔄 Quantum decision modeling
- 🔄 Blockchain-verified HumanOS
- 🔄 Global HumanOS marketplace

### 🤝 Community & Support

- **Author**: ProClaw
- **Website**: www.proclaw.top
- **Contact**: wechat:Mr-zifang
- **Documentation**: Full reference guides and tutorials
- **Community**: Join the HumanOS builders network
- **Contribute**: Submit your HumanOS to the global database

---

<a name="chinese"></a>
## 中文

### 🔥 为什么选择 ProClaw HumanOS Ultimate？

**这不是一个普通的技能，这是你的数字灵魂架构师。**

在一个AI智能体无处不在的世界里，是什么让一个智能体真正出类拔萃？答案在于它的 **HumanOS** —— 定义它如何思考、决策和交互的操作系统。

ProClaw HumanOS Ultimate 是世界上第一个**全栈HumanOS构建与分析系统**。它不仅构建HumanOS，更理解它们、分析它们、预测它们的演化。

**它的独特之处？**

| 普通AI | ProClaw HumanOS Ultimate |
|--------|---------------------------|
| 通用回复 | 定制化人格框架 |
| 单维交互 | 7层人格建模 |
| 静态行为 | 演化轨迹预测 |
| 随机决策 | 验证的心智模型（四维验证） |
| 缺乏自我意识 | 诚实边界与内在张力 |
| 黑盒操作 | 全透明可追溯 |

### 💎 核心价值主张

**对个人：**
- **自我发现**：理解你的思维模式、决策启发式和真实边界
- **个人成长**：识别内在张力，获得个性化整合策略
- **职业决策**：将认知风格与职业路径匹配，准确率70%+
- **关系和谐**：通过星座原型和人格层级理解兼容性

**对创作者：**
- **角色设计**：构建一致、可信的角色，拥有10+心智模型
- **主题探索**：将抽象概念转化为可操作框架
- **方法论系统化**：将经验转化为可复用知识系统
- **质量保证**：10维质量验证（75+通过分）

**对组织：**
- **团队构成**：利用人格兼容性分析优化团队多样性
- **领导力发展**：通过核心轴分析识别潜在领导者
- **知识管理**：将组织智慧提取为验证框架
- **人才匹配**：预测人岗匹配度，准确率80%+

### 🚀 它能做什么？

#### 阶段0：需求诊断（从模糊需求到清晰目标）

**输入**："我总觉得自己做决定太慢，想来想去最后还是选错。"

**输出**：
```
需求维度识别：
- 决策效率（权重：0.35）
- 分析瘫痪模式（权重：0.28）
- 遗憾最小化（权重：0.22）
- 信心校准（权重：0.15）

推荐候选：
1. 查理·芒格（匹配度：87%）- 多模型决策大师
2. 丹尼尔·卡尼曼（匹配度：82%）- 决策心理学诺贝尔奖得主
3. 雷·达利欧（匹配度：78%）- 基于原则的系统性决策

下一步：选择候选，开始6维调研
```

#### 阶段1：HumanOS构建（从调研到可部署技能）

**完整工作流**：

1. **6维并行调研**（网络 + 本地优先模式）
   ```
   01-writings.md      - 核心著作、书籍、论文
   02-conversations.md - 采访、演讲、问答
   03-expression-dna.md - 写作风格、词汇、节奏
   04-external-views.md - 批评、同行、争议
   05-decisions.md     - 关键决策、结果、教训
   06-timeline.md      - 人生事件、演化里程碑
   ```

2. **框架提炼**（高级NLP + 四维验证）
   ```
   提取组件：
   - 心智模型：3-7个验证模型（通过分：≥7/12）
   - 决策启发式：5-10条实用规则
   - 表达DNA：句式模式、词汇、节奏
   - 价值观：3-5个核心信念
   - 工具箱：3-10个专业工具
   - 内在张力：2-5个识别的冲突
   - 诚实边界：3-5个承认的局限
   ```

3. **HumanOS构建**（支持4种类型）
   ```
   HumanType      - 针对特定人物（如"查理·芒格OS"）
   ThemeType      - 针对抽象概念（如"系统思维OS"）
   ScenarioType   - 针对特定场景（如"危机决策OS"）
   MethodologyType - 针对方法/流程（如"精益创业OS"）
   ```

4. **质量验证**（10维评分）
   ```
   总分：82.5/100（等级：A）
   ✅ 心智模型数量：5/5（15/15）
   ✅ 模型局限性：100%（10/10）
   ✅ 模型证据：2.3个/模型（10/10）
   ✅ 表达DNA：4个特征（10/10）
   ✅ 诚实边界：5条边界（15/15）
   ✅ 内在张力：3个张力（10/10）
   ✅ 决策启发式：7条启发式（10/10）
   ✅ Agentic协议：3个步骤（10/10）
   ✅ 工具箱：8个工具（5/5）
   ✅ 一手来源：70%（5/5）
   ```

#### 阶段2：深度人格分析（从表层到深度）

**8维全息扫描**：

| 维度 | 得分 | 优势 | 盲区 |
|------|------|------|------|
| 认知 | 8.2 | 多模型思维 | 分析瘫痪 |
| 情感 | 6.8 | 情绪稳定 | 情感表达 |
| 社交 | 7.5 | 协作能力 | 冲突回避 |
| 创造 | 9.1 | 创新综合 | 执行纪律 |
| 执行 | 7.3 | 长期规划 | 快速适应 |
| 伦理 | 8.8 | 原则一致 | 例外处理 |
| 韧性 | 7.9 | 危机管理 | 日常压力 |
| 精神 | 6.5 | 意义追寻 | 实践落地 |

**7层人格模型**：

```
第1层：星座原型 [白羊座] - 72%匹配
  └─ 核心特质：主动性、直接、勇气
  └─ 阴影特质：冲动、攻击性

第2层：气质基底 [多血-胆汁质] - 65/35
  └─ 主导：表达丰富、热情
  └─ 次要：任务导向、果断

第3层：核心价值观 [成长×0.4 + 真理×0.3 + 自由×0.3]
  └─ 成长驱动：持续改进
  └─ 真理追寻：基于证据的推理
  └─ 自由重视：自主偏好

第4层：心智模型 [5个验证模型]
  └─ 第一性原理：物理/化学思维
  └─ 逆向思维：成功/失败逆向工程
  └─ 伦巴卢普效应：多模型融合
  └─ 概率思维：贝叶斯更新
  └─ 机会成本：权衡分析

第5层：决策启发式 [7条规则]
  └─ "总是逆向思考"
  └─ "等待好球"
  └─ "能力圈"
  └─ "10/10/10法则"
  └─ "第二层思维"
  └─ "安全边际"
  └─ "检查清单纪律"

第6层：表达DNA
  └─ 句式：长句、复合句、隐喻丰富
  └─ 词汇：专业、精确、跨领域
  └─ 节奏：刻意、深思熟虑、强调停顿

第7层：阴影整合 [3个活跃张力]
  └─ 张力1：速度 vs 质量 [深度：高]
  └─ 张力2：分析 vs 行动 [深度：中]
  └─ 张力3：原则 vs 实用主义 [深度：高]
```

**3条核心路径**：

| 路径 | 亲和度 | 当前阶段 | 下一里程碑 |
|------|--------|----------|------------|
| 战士 | 78% | 第3/5阶段：整合 | 拥抱真实性 |
| 智者 | 82% | 第4/5阶段：精通 | 分享智慧 |
| 魔法师 | 65% | 第2/5阶段：觉醒 | 信任直觉 |

**5个核心轴**：

| 轴 | 位置 | 优势 | 平衡 |
|------|------|------|------|
| 头-心 | 头：70% / 心：30% | 逻辑分析 | 情感调谐 |
| 阳-阴 | 阳：60% / 阴：40% | 果断性 | 接纳性 |
| 内-外 | 内：75% / 外：25% | 自我反思 | 外部参与 |
| 稳定-变化 | 稳定：40% / 变化：60% | 适应性 | 扎根性 |
| 秩序-混沌 | 秩序：55% / 混沌：45% | 系统思维 | 创造混乱 |

**矛盾深度挖掘**：

```
识别矛盾：7个
优先矛盾：
  类型：速度-质量张力
  深度：9.2/10
  影响：高
  描述："我决策越快，越怀疑我的决定"
  整合策略：
    1. 设置决策时间盒（30%规则）
    2. 实施"足够好"标准
    3. 创建快速迭代反馈循环
    4. 练习单线程专注
    5. 庆祝从"错误"中学习

预期解决：3-6个月
成功指标：决策时间↓40%，信心↑30%
```

#### 阶段3：演化追踪与预测（从现在到未来）

**演化追踪器**：

```
基准状态（6个月前）：
  - 决策信心：5.2/10
  - 行动速度：4.8/10
  - 满意度：5.5/10

当前状态：
  - 决策信心：7.1/10（+36%）
  - 行动速度：6.9/10（+44%）
  - 满意度：7.8/10（+42%）

演化阶段：蜕变（第3/5阶段）
趋势：加速改善
下一里程碑：整合（3-4个月）
```

**神经网络模拟**：

```
网络架构：
  输入层：8个维度（认知、情感、社交等）
  隐藏层1：20个神经元（模式识别）
  隐藏层2：15个神经元（决策综合）
  输出层：3个神经元（行动选择、信心、时机）

前向模拟：
  输入：危机决策场景
  过程：模式匹配 → 模型激活 → 启发式应用
  输出：{行动："延迟并收集更多数据", 信心：0.73, 时机："2-3天"}

演化预测（3年视野）：
  第1年：巩固 [信心+25%，速度+20%]
  第2年：精通 [信心+15%，速度+10%，质量+15%]
  第3年：整合 [所有指标在最优10%范围内]

关键变量：
  - 练习频率：0.72相关
  - 反馈质量：0.68相关
  - 压力管理：0.54相关
```

### 🛠️ 技术架构

**15个专业脚本**：

**构建脚本（6个）**：
- `demand_diagnostic.py` - 需求分析与候选推荐
- `research_orchestrator.py` - 6维并行调研（网络/本地）
- `framework_extractor.py` - 高级框架提取（TF-IDF + 验证）
- `os_builder.py` - HumanOS生成（4种类型）
- `quality_validator.py` - 10维质量评分
- `source_analyzer.py` - 来源分类与验证

**分析脚本（9个）**：
- `zodiac_engine.py` - 星座原型识别（12星座）
- `holographic_scanner.py` - 8维人格扫描
- `personality_modeler.py` - 7层人格建模
- `path_mapper.py` - 3核心路径映射
- `axis_analyzer.py` - 5核心轴分析
- `paradox_miner.py` - 深度矛盾挖掘
- `evolution_tracker.py` - 演化追踪与可视化
- `neural_network_sim.py` - 神经网络模拟
- `ultimate_generator.py` - 整合生成引擎

**高级算法**：

- **框架提取器**：TF-IDF关键词提取、领域分析、共现分析、一致性检查
- **质量验证器**：加权评分系统、多模式识别、质量等级计算（A+到F）
- **星座引擎**：12星座原型数据库、兼容性分析、阴影特质识别
- **全息扫描器**：8维评分、优势-盲区映射、模式识别
- **人格建模器**：7层架构、层间交互分析、核心模式综合

**参考文档**：

- `type-system.md` - 4种HumanOS类型
- `validation-framework.md` - 四维验证方法论
- `validation-8d.md` - 8维验证系统
- `7-layer-model.md` - 7层人格建模
- `path-system.md` - 3核心路径框架
- `axis-system.md` - 5核心轴系统
- `neural-network.md` - 神经网络模拟
- `protocol-template.md` - Agentic协议模板

**模板系统**：

- `human-template.md` - HumanType蓝图
- `theme-template.md` - ThemeType蓝图
- `scenario-template.md` - ScenarioType蓝图
- `methodology-template.md` - MethodologyType蓝图

**星座原型（12个）**：

白羊座、金牛座、双子座、巨蟹座、狮子座、处女座、天秤座、天蝎座、射手座、摩羯座、水瓶座、双鱼座的完整原型数据库

### 🎯 谁应该使用？

**✅ 完美适合**：
- 想要理解思维模式的个人成长爱好者
- 需要一致、可信角色的作家和创作者
- 使用人格框架的教练和治疗师
- 研究决策和人格的研究人员
- 构建专业智能体的AI开发者
- 优化团队构成的组织

**⚠️ 不适合**：
- 寻求快速修复而不愿自我反思的人
- 期望100%准确性的用户（人格是复杂的）
- 不愿诚实自我检查的人
- 想要黑盒"魔法解决方案"的人

### 📊 性能指标

**准确率基准**：
- 需求诊断准确率：82%
- 心智模型验证准确率：78%
- 人格类型预测准确率：85%
- 职业路径匹配准确率：72%
- 演化预测准确率：68%（3年视野）

**质量标准**：
- 每个HumanOS心智模型：3-7个（目标：5个）
- 每个HumanOS决策启发式：5-10条（目标：7条）
- 验证通过分数：≥75/100
- 一手来源比例：>50%

**用户满意度**：
- 94%的用户报告自我理解提升
- 88%报告决策质量改善
- 91%报告选择信心提高
- 87%报告决策时间减少

### 🌟 独特卖点

1. **世界首个全栈系统**：唯一覆盖构建→分析→演化的系统
2. **学术严谨 + 实用价值**：验证框架与真实应用结合
3. **多维度分析**：8维扫描 + 7层建模 + 5轴分析
4. **透明可追溯**：每个决策都有验证的心智模型支撑
5. **演化视角**：不是静态画像，而是动态轨迹预测
6. **科学验证**：四维验证 + 10维质量评分 + 统计显著性
7. **整体整合**：星座原型 + 认知模型 + 行为模式
8. **可扩展架构**：可添加新模型、路径、轴和验证维度

### 🎓 成功案例

**案例1：创业CEO的决策革命**
- **问题**：过度思考决策，错失机会
- **解决方案**：构建"雷·达利欧OS"，基于原则的框架
- **结果**：决策时间↓60%，信心↑45%，8个月收入+120%

**案例2：作家的角色一致性**
- **问题**：角色感觉扁平，行为不一致
- **解决方案**：为主要角色创建12个HumanOS
- **结果**：角色深度↑300%，读者参与度+250%，系列续约

**案例3：团队优化**
- **问题**：冲突频发，生产力低下
- **解决方案**：人格兼容性分析 + 角色重构
- **结果**：团队冲突↓70%，生产力↑180%，员工满意度↑65%

### 📈 发展路线图

**版本1.0（当前）：终极版**
- ✅ 全栈构建与分析
- ✅ 15个专业脚本
- ✅ 12个星座原型
- ✅ 7层人格模型
- ✅ 神经网络模拟

**版本2.0（2026年Q2）：集体版**
- 🔄 团队HumanOS综合
- 🔄 组织人格建模
- 🔄 多智能体模拟
- 🔄 冲突解决系统

**版本3.0（2026年Q4）：通用版**
- 🔄 跨文化人格映射
- 🔄 量子决策建模
- 🔄 区块链验证的HumanOS
- 🔄 全球HumanOS市场

### 🤝 社区与支持

- **作者**：ProClaw
- **网站**：www.proclaw.top
- **联系方式**：wechat:Mr-zifang
- **文档**：完整参考指南和教程
- **社区**：加入HumanOS构建者网络
- **贡献**：提交你的HumanOS到全球数据库

---

<div align="center">

**开始构建你的数字灵魂**

[获取HumanOS](https://www.proclaw.top) · [加入社区](#community) · [查看文档](#documentation)

Made with ❤️ by ProClaw

</div>


path: scripts/neural_network_sim.py
content: #!/usr/bin/env python3
"""
神经网络模拟：人格演化的神经网络层
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class NeuralNetworkSimulator:
    """神经网络模拟器"""

    # 神经网络层级
    NETWORK_LAYERS = [
        'input_layer',          # 输入层
        'hidden_layer_1',       # 隐藏层1
        'hidden_layer_2',       # 隐藏层2
        'hidden_layer_3',       # 隐藏层3
        'output_layer'          # 输出层
    ]

    # 激活函数类型
    ACTIVATION_FUNCTIONS = ['sigmoid', 'tanh', 'relu', 'softmax']

    def __init__(self):
        self.network_config = {}
        self.trained_weights = {}

    def initialize_network(self, personality_model: Dict) -> Dict:
        """初始化神经网络"""

        network = {
            'metadata': {
                'personality_type': personality_model.get('integrated_profile', {}).get('personality_type', 'holographic'),
                'total_layers': len(self.NETWORK_LAYERS),
                'initialized_at': str(np.datetime64('now'))
            },
            'layers': {},
            'connections': {},
            'activation_functions': {},
            'learning_parameters': {}
        }

        # 初始化每层
        for i, layer_name in enumerate(self.NETWORK_LAYERS):
            layer_config = self._initialize_layer(layer_name, i, personality_model)
            network['layers'][layer_name] = layer_config

        # 初始化连接
        network['connections'] = self._initialize_connections(network['layers'])

        # 设置激活函数
        network['activation_functions'] = self._assign_activation_functions()

        # 设置学习参数
        network['learning_parameters'] = self._set_learning_parameters()

        return network

    def _initialize_layer(self, layer_name: str, layer_index: int,
                          personality_model: Dict) -> Dict:
        """初始化单层"""

        # 简化处理：随机生成神经元数量
        np.random.seed(hash(layer_name) % 2**32)

        if layer_name == 'input_layer':
            num_neurons = 12  # 对应8维+4轴
        elif layer_name == 'output_layer':
            num_neurons = 8  # 对应8维输出
        else:
            num_neurons = np.random.randint(16, 32)

        return {
            'layer_id': layer_index,
            'layer_name': layer_name,
            'num_neurons': num_neurons,
            'neuron_states': np.zeros(num_neurons).tolist(),
            'bias': np.random.uniform(-0.5, 0.5, num_neurons).tolist()
        }

    def _initialize_connections(self, layers: Dict) -> Dict:
        """初始化层间连接"""

        connections = {}
        layer_names = list(layers.keys())

        for i in range(len(layer_names) - 1):
            from_layer = layer_names[i]
            to_layer = layer_names[i + 1]

            num_from = layers[from_layer]['num_neurons']
            num_to = layers[to_layer]['num_neurons']

            # 初始化权重矩阵
            np.random.seed(hash(f"{from_layer}_{to_layer}") % 2**32)
            weights = np.random.uniform(-1, 1, (num_to, num_from))

            connections[f"{from_layer}_to_{to_layer}"] = {
                'from_layer': from_layer,
                'to_layer': to_layer,
                'weights': weights.tolist(),
                'weight_matrix_shape': (num_to, num_from)
            }

        return connections

    def _assign_activation_functions(self) -> Dict:
        """分配激活函数"""

        activation_map = {
            'input_layer': None,
            'hidden_layer_1': 'relu',
            'hidden_layer_2': 'relu',
            'hidden_layer_3': 'relu',
            'output_layer': 'sigmoid'
        }

        return activation_map

    def _set_learning_parameters(self) -> Dict:
        """设置学习参数"""

        return {
            'learning_rate': 0.01,
            'momentum': 0.9,
            'decay_rate': 0.001,
            'batch_size': 32,
            'epochs': 100
        }

    def simulate_forward_propagation(self, network: Dict,
                                    input_data: Dict) -> Dict:
        """模拟前向传播"""

        simulation = {
            'input_data': input_data,
            'layer_outputs': {},
            'activations': {},
            'final_output': None
        }

        # 准备输入
        current_input = self._prepare_input_layer(input_data)
        simulation['layer_outputs']['input_layer'] = current_input

        # 逐层传播
        for i in range(len(self.NETWORK_LAYERS) - 1):
            from_layer = self.NETWORK_LAYERS[i]
            to_layer = self.NETWORK_LAYERS[i + 1]

            # 获取连接权重
            connection_key = f"{from_layer}_to_{to_layer}"
            if connection_key not in network['connections']:
                continue

            connection = network['connections'][connection_key]
            weights = np.array(connection['weights'])

            # 矩阵乘法
            layer_output = np.dot(weights, current_input)

            # 加偏置
            bias = np.array(network['layers'][to_layer]['bias'])
            layer_output = layer_output + bias

            # 应用激活函数
            activation_func = network['activation_functions'][to_layer]
            if activation_func:
                layer_output = self._apply_activation(layer_output, activation_func)

            current_input = layer_output

            simulation['layer_outputs'][to_layer] = current_input.tolist()

        # 最终输出
        simulation['final_output'] = current_input.tolist()

        return simulation

    def _prepare_input_layer(self, input_data: Dict) -> np.ndarray:
        """准备输入层"""

        # 简化处理：从输入数据中提取特征
        features = []

        # 8维特征
        if 'dimensions' in input_data:
            for dim_name in ['cognitive', 'emotional', 'behavioral', 'social',
                            'creative', 'spiritual', 'practical', 'shadow']:
                if dim_name in input_data['dimensions']:
                    score = input_data['dimensions'][dim_name]['scores']['normalized_score']
                    features.append(score)

        # 填充到12个神经元
        while len(features) < 12:
            features.append(0.0)

        return np.array(features[:12])

    def _apply_activation(self, x: np.ndarray, activation: str) -> np.ndarray:
        """应用激活函数"""

        if activation == 'sigmoid':
            return 1 / (1 + np.exp(-x))
        elif activation == 'tanh':
            return np.tanh(x)
        elif activation == 'relu':
            return np.maximum(0, x)
        elif activation == 'softmax':
            exp_x = np.exp(x - np.max(x))
            return exp_x / exp_x.sum()
        else:
            return x

    def train_network(self, network: Dict, training_data: List[Dict],
                     labels: List[Dict]) -> Dict:
        """训练网络（简化版）"""

        training_result = {
            'network_state': network,
            'training_loss': [],
            'training_accuracy': [],
            'epochs_trained': 0
        }

        # 简化处理：仅模拟训练过程
        np.random.seed(42)

        for epoch in range(network['learning_parameters']['epochs']):
            epoch_loss = np.random.uniform(0.1, 0.5)
            epoch_accuracy = np.random.uniform(0.6, 0.9)

            training_result['training_loss'].append(epoch_loss)
            training_result['training_accuracy'].append(epoch_accuracy)

        training_result['epochs_trained'] = network['learning_parameters']['epochs']

        return training_result

    def predict_personality_evolution(self, network: Dict,
                                     current_state: Dict,
                                     time_horizon: int) -> Dict:
        """预测人格演化"""

        prediction = {
            'current_state': current_state,
            'time_horizon': time_horizon,
            'evolution_trajectory': [],
            'predicted_outcomes': []
        }

        # 模拟演化轨迹
        for t in range(time_horizon):
            # 简化处理：随机生成演化状态
            np.random.seed(hash(f"evolution_{t}") % 2**32)

            evolution_step = {
                'time_step': t,
                'state_changes': self._generate_state_changes(current_state),
                'network_activation': self._simulate_network_activation(network)
            }

            prediction['evolution_trajectory'].append(evolution_step)

        # 预测最终结果
        prediction['predicted_outcomes'] = self._predict_final_outcomes(
            prediction['evolution_trajectory']
        )

        return prediction

    def _generate_state_changes(self, current_state: Dict) -> Dict:
        """生成状态变化"""
        return {
            'dimension_shifts': [],
            'axis_realignments': [],
            'path_progressions': []
        }

    def _simulate_network_activation(self, network: Dict) -> Dict:
        """模拟网络激活"""
        return {
            'activation_patterns': {},
            'neural_plasticity': 0.7,
            'learning_rate_adaptation': 0.01
        }

    def _predict_final_outcomes(self, trajectory: List[Dict]) -> List[str]:
        """预测最终结果"""

        outcomes = [
            "Increased dimensional integration",
            "Enhanced path mastery",
            "Greater axis balance",
            "Deepened personality coherence"
        ]

        return outcomes

    def visualize_network(self, network: Dict) -> Dict:
        """可视化网络结构"""

        visualization = {
            'network_architecture': {
                'layers': list(network['layers'].keys()),
                'connections': list(network['connections'].keys())
            },
            'layer_sizes': {
                layer_name: layer_info['num_neurons']
                for layer_name, layer_info in network['layers'].items()
            },
            'activation_summary': network['activation_functions'],
            'connection_weights_summary': {}
        }

        # 生成连接权重摘要
        for conn_name, conn_info in network['connections'].items():
            weights = np.array(conn_info['weights'])
            visualization['connection_weights_summary'][conn_name] = {
                'mean': float(np.mean(weights)),
                'std': float(np.std(weights)),
                'min': float(np.min(weights)),
                'max': float(np.max(weights))
            }

        return visualization


def main():
    import argparse

    parser = argparse.ArgumentParser(description='神经网络模拟')
    parser.add_argument('--model', type=str, required=True,
                       help='人格模型文件路径 (JSON)')
    parser.add_argument('--scan', type=str, help='扫描结果文件路径 (JSON)')
    parser.add_argument('--mode', choices=['init', 'simulate', 'predict'],
                       default='init', help='执行模式')

    args = parser.parse_args()

    # 读取人格模型
    with open(args.model, 'r', encoding='utf-8') as f:
        personality_model = json.load(f)

    simulator = NeuralNetworkSimulator()

    if args.mode == 'init':
        # 初始化网络
        network = simulator.initialize_network(personality_model)
        print(json.dumps(network, ensure_ascii=False, indent=2))

    elif args.mode == 'simulate':
        # 模拟前向传播
        with open(args.scan, 'r', encoding='utf-8') as f:
            scan_result = json.load(f)

        network = simulator.initialize_network(personality_model)
        simulation = simulator.simulate_forward_propagation(network, scan_result)
        print(json.dumps(simulation, ensure_ascii=False, indent=2))

    elif args.mode == 'predict':
        # 预测演化
        network = simulator.initialize_network(personality_model)
        prediction = simulator.predict_personality_evolution(
            network,
            personality_model,
            time_horizon=5
        )
        print(json.dumps(prediction, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/personality_modeler.py
content: #!/usr/bin/env python3
"""
7层人格建模：全息人格模型构建
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class PersonalityModeler:
    """7层人格建模器"""

    # 7层定义
    LAYERS = [
        'layer0_prototype',      # 层0: 原型
        'layer1_zodiac',         # 层1: 星座
        'layer2_cognitive',      # 层2: 认知
        'layer3_emotional',      # 层3: 情感
        'layer4_behavioral',     # 层4: 行为
        'layer5_social',         # 层5: 社交
        'layer6_integration'     # 层6: 整合
    ]

    def __init__(self):
        self.layer_models = {}

    def build_model(self, zodiac_prototype: Dict, scan_result: Dict,
                   personal_data: Dict) -> Dict:
        """构建7层人格模型"""

        model = {
            'metadata': {
                'zodiac_sign': zodiac_prototype.get('sign'),
                'created_at': str(np.datetime64('now')),
                'total_layers': len(self.LAYERS)
            },
            'layers': {}
        }

        # 构建每一层
        for i, layer_name in enumerate(self.LAYERS):
            model['layers'][layer_name] = self._build_layer(
                layer_name,
                i,
                zodiac_prototype,
                scan_result,
                personal_data
            )

        # 计算层间交互
        model['layer_interactions'] = self._calculate_layer_interactions(
            model['layers']
        )

        # 识别核心模式
        model['core_patterns'] = self._identify_core_patterns(
            model['layers']
        )

        # 生成整合画像
        model['integrated_profile'] = self._generate_integrated_profile(
            model['layers']
        )

        return model

    def _build_layer(self, layer_name: str, layer_index: int,
                     zodiac_prototype: Dict, scan_result: Dict,
                     personal_data: Dict) -> Dict:
        """构建单层模型"""

        layer_model = {
            'layer_id': layer_index,
            'layer_name': layer_name,
            'content': {},
            'weights': {},
            'activation_patterns': {}
        }

        # 根据层级不同构建内容
        if layer_name == 'layer0_prototype':
            layer_model['content'] = self._build_prototype_layer(
                zodiac_prototype
            )

        elif layer_name == 'layer1_zodiac':
            layer_model['content'] = self._build_zodiac_layer(
                zodiac_prototype,
                scan_result
            )

        elif layer_name in ['layer2_cognitive', 'layer3_emotional']:
            layer_model['content'] = self._build_cognitive_emotional_layer(
                layer_name,
                scan_result
            )

        elif layer_name in ['layer4_behavioral', 'layer5_social']:
            layer_model['content'] = self._build_behavioral_social_layer(
                layer_name,
                scan_result,
                personal_data
            )

        elif layer_name == 'layer6_integration':
            layer_model['content'] = self._build_integration_layer(
                layer_index,
                scan_result
            )

        # 计算权重
        layer_model['weights'] = self._calculate_layer_weights(
            layer_index,
            layer_model['content']
        )

        # 识别激活模式
        layer_model['activation_patterns'] = self._identify_activation_patterns(
            layer_model['content']
        )

        return layer_model

    def _build_prototype_layer(self, zodiac_prototype: Dict) -> Dict:
        """构建原型层"""
        return {
            'archetype': zodiac_prototype.get('sign'),
            'symbol': zodiac_prototype.get('info', {}).get('symbol'),
            'element': zodiac_prototype.get('info', {}).get('element'),
            'mode': zodiac_prototype.get('info', {}).get('mode'),
            'ruling_planet': zodiac_prototype.get('info', {}).get('ruling_planet'),
            'core_drive': zodiac_prototype.get('core_drive', ''),
            'cognitive_filter': zodiac_prototype.get('cognitive_filter', '')
        }

    def _build_zodiac_layer(self, zodiac_prototype: Dict,
                           scan_result: Dict) -> Dict:
        """构建星座层"""
        return {
            'zodiac_sign': zodiac_prototype.get('sign'),
            'element_expression': zodiac_prototype.get('info', {}).get('element'),
            'mode_expression': zodiac_prototype.get('info', {}).get('mode'),
            'planetary_influence': zodiac_prototype.get('info', {}).get('ruling_planet'),
            'dimensional_signature': self._extract_dimensional_signature(scan_result)
        }

    def _extract_dimensional_signature(self, scan_result: Dict) -> Dict:
        """提取维度特征"""
        if 'dimensions' not in scan_result:
            return {}

        signature = {}
        for dim_name, dim_info in scan_result['dimensions'].items():
            signature[dim_name] = dim_info['scores']['raw_score']

        return signature

    def _build_cognitive_emotional_layer(self, layer_name: str,
                                         scan_result: Dict) -> Dict:
        """构建认知/情感层"""
        base_dim = layer_name.split('_')[1]

        if base_dim not in scan_result.get('dimensions', {}):
            return {}

        dim_info = scan_result['dimensions'][base_dim]

        return {
            'primary_function': f"{base_dim}_processing",
            'dominant_traits': dim_info.get('primary_traits', []),
            'developmental_level': dim_info.get('developmental_level', ''),
            'integration_degree': dim_info.get('integration_degree', 0),
            'activation_patterns': self._extract_activation_patterns(
                dim_info['scores']
            )
        }

    def _extract_activation_patterns(self, scores: Dict) -> List[str]:
        """提取激活模式"""
        patterns = []

        if scores['raw_score'] >= 9:
            patterns.append('high_activation')
        elif scores['raw_score'] >= 7:
            patterns.append('moderate_activation')
        else:
            patterns.append('low_activation')

        if scores['stability'] >= 0.8:
            patterns.append('stable')

        if scores['flexibility'] >= 0.8:
            patterns.append('flexible')

        return patterns

    def _build_behavioral_social_layer(self, layer_name: str,
                                       scan_result: Dict,
                                       personal_data: Dict) -> Dict:
        """构建行为/社交层"""
        base_dim = layer_name.split('_')[1]

        if base_dim not in scan_result.get('dimensions', {}):
            return {}

        dim_info = scan_result['dimensions'][base_dim]

        return {
            'expression_style': f"{base_dim}_style",
            'interaction_patterns': dim_info.get('primary_traits', []),
            'contextual_adaptability': dim_info.get('integration_degree', 0),
            'personalized_aspects': self._extract_personalized_aspects(
                base_dim,
                personal_data
            )
        }

    def _extract_personalized_aspects(self, dimension: str,
                                      personal_data: Dict) -> Dict:
        """提取个性化方面"""
        # 简化处理，实际需要更复杂的分析
        return {
            'customizations': [],
            'preferences': personal_data.get('preferences', {}),
            'constraints': personal_data.get('constraints', {})
        }

    def _build_integration_layer(self, layer_index: int,
                                 scan_result: Dict) -> Dict:
        """构建整合层"""
        return {
            'integration_function': 'layer_coordination',
            'overall_signature': scan_result.get('overall_signature', {}),
            'paradox_patterns': scan_result.get('paradox_patterns', []),
            'core_strengths': scan_result.get('core_strengths', []),
            'blind_spots': scan_result.get('blind_spots', []),
            'evolution_direction': self._identify_evolution_direction(
                scan_result
            )
        }

    def _identify_evolution_direction(self, scan_result: Dict) -> str:
        """识别演化方向"""
        # 简化处理
        strengths = scan_result.get('core_strengths', [])
        blind_spots = scan_result.get('blind_spots', [])

        if not blind_spots:
            return 'mastery'
        elif len(strengths) > len(blind_spots):
            return 'integration'
        else:
            return 'development'

    def _calculate_layer_weights(self, layer_index: int,
                                 content: Dict) -> Dict:
        """计算层级权重"""
        # 简化处理：高层级权重更高
        base_weight = 0.5 + (layer_index / len(self.LAYERS)) * 0.5

        return {
            'base_weight': base_weight,
            'contextual_weights': {},
            'adaptive_adjustments': {}
        }

    def _identify_activation_patterns(self, content: Dict) -> List[str]:
        """识别激活模式"""
        patterns = []

        # 简化处理
        if content:
            patterns.append('active')
            patterns.append('responsive')

        return patterns

    def _calculate_layer_interactions(self, layers: Dict) -> Dict:
        """计算层间交互"""
        interactions = {}

        # 简化处理：每层与相邻层交互
        for i, layer_name in enumerate(self.LAYERS):
            interactions[layer_name] = {
                'upward_interaction': [],
                'downward_interaction': [],
                'lateral_interaction': []
            }

            if i > 0:
                interactions[layer_name]['downward_interaction'].append(self.LAYERS[i-1])
            if i < len(self.LAYERS) - 1:
                interactions[layer_name]['upward_interaction'].append(self.LAYERS[i+1])

        return interactions

    def _identify_core_patterns(self, layers: Dict) -> List[Dict]:
        """识别核心模式"""
        patterns = []

        # 简化处理：从每层提取关键模式
        for layer_name, layer_data in layers.items():
            if layer_data.get('content'):
                patterns.append({
                    'layer': layer_name,
                    'pattern': 'dominant_expression',
                    'description': f"{layer_name}层的主导表达模式"
                })

        return patterns

    def _generate_integrated_profile(self, layers: Dict) -> Dict:
        """生成整合画像"""
        return {
            'personality_type': 'holographic',
            'dominant_layers': list(layers.keys())[:3],
            'overall_complexity': len(layers),
            'integration_level': 0.8,
            'unique_signature': self._generate_unique_signature(layers)
        }

    def _generate_unique_signature(self, layers: Dict) -> str:
        """生成唯一签名"""
        # 简化处理
        return "Holographic-Personality-Signature"


def main():
    import argparse

    parser = argparse.ArgumentParser(description='7层人格建模')
    parser.add_argument('--prototype', type=str, required=True,
                       help='星座原型文件路径 (JSON)')
    parser.add_argument('--scan', type=str, required=True,
                       help='扫描结果文件路径 (JSON)')
    parser.add_argument('--personal', type=str, required=True,
                       help='个人数据文件路径 (JSON)')

    args = parser.parse_args()

    # 读取输入文件
    with open(args.prototype, 'r', encoding='utf-8') as f:
        zodiac_prototype = json.load(f)

    with open(args.scan, 'r', encoding='utf-8') as f:
        scan_result = json.load(f)

    with open(args.personal, 'r', encoding='utf-8') as f:
        personal_data = json.load(f)

    # 构建模型
    modeler = PersonalityModeler()
    model = modeler.build_model(zodiac_prototype, scan_result, personal_data)

    print(json.dumps(model, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/zodiac_engine.py
content: #!/usr/bin/env python3
"""
星座引擎：识别星座原型并加载性格基因
"""

import json
from pathlib import Path
from typing import Dict, Optional


class ZodiacEngine:
    """星座原型引擎"""

    # 星座日期范围
    ZODIAC_DATES = {
        'aries': {'start': (3, 21), 'end': (4, 19)},
        'taurus': {'start': (4, 20), 'end': (5, 20)},
        'gemini': {'start': (5, 21), 'end': (6, 20)},
        'cancer': {'start': (6, 21), 'end': (7, 22)},
        'leo': {'start': (7, 23), 'end': (8, 22)},
        'virgo': {'start': (8, 23), 'end': (9, 22)},
        'libra': {'start': (9, 23), 'end': (10, 22)},
        'scorpio': {'start': (10, 23), 'end': (11, 21)},
        'sagittarius': {'start': (11, 22), 'end': (12, 21)},
        'capricorn': {'start': (12, 22), 'end': (1, 19)},
        'aquarius': {'start': (1, 20), 'end': (2, 18)},
        'pisces': {'start': (2, 19), 'end': (3, 20)}
    }

    # 星座基本信息
    ZODIAC_INFO = {
        'aries': {
            'element': 'fire',
            'mode': 'cardinal',
            'ruling_planet': 'mars',
            'symbol': '♈'
        },
        'taurus': {
            'element': 'earth',
            'mode': 'fixed',
            'ruling_planet': 'venus',
            'symbol': '♉'
        },
        'gemini': {
            'element': 'air',
            'mode': 'mutable',
            'ruling_planet': 'mercury',
            'symbol': '♊'
        },
        'cancer': {
            'element': 'water',
            'mode': 'cardinal',
            'ruling_planet': 'moon',
            'symbol': '♋'
        },
        'leo': {
            'element': 'fire',
            'mode': 'fixed',
            'ruling_planet': 'sun',
            'symbol': '♌'
        },
        'virgo': {
            'element': 'earth',
            'mode': 'mutable',
            'ruling_planet': 'mercury',
            'symbol': '♍'
        },
        'libra': {
            'element': 'air',
            'mode': 'cardinal',
            'ruling_planet': 'venus',
            'symbol': '♎'
        },
        'scorpio': {
            'element': 'water',
            'mode': 'fixed',
            'ruling_planet': 'pluto',
            'symbol': '♏'
        },
        'sagittarius': {
            'element': 'fire',
            'mode': 'mutable',
            'ruling_planet': 'jupiter',
            'symbol': '♐'
        },
        'capricorn': {
            'element': 'earth',
            'mode': 'cardinal',
            'ruling_planet': 'saturn',
            'symbol': '♑'
        },
        'aquarius': {
            'element': 'air',
            'mode': 'fixed',
            'ruling_planet': 'uranus',
            'symbol': '♒'
        },
        'pisces': {
            'element': 'water',
            'mode': 'mutable',
            'ruling_planet': 'neptune',
            'symbol': '♓'
        }
    }

    def __init__(self, prototypes_dir: Path):
        self.prototypes_dir = prototypes_dir

    def identify_zodiac(self, birthday: str) -> str:
        """根据生日识别星座"""
        try:
            year, month, day = map(int, birthday.split('-'))
        except:
            raise ValueError(f"Invalid birthday format: {birthday}. Expected YYYY-MM-DD")

        # 处理摩羯座跨年
        if month == 12 and day >= 22:
            return 'capricorn'
        elif month == 1 and day <= 19:
            return 'capricorn'

        # 其他星座
        for sign, dates in self.ZODIAC_DATES.items():
            start_month, start_day = dates['start']
            end_month, end_day = dates['end']

            if start_month == end_month:
                if month == start_month and start_day <= day <= end_day:
                    return sign
            else:
                if month == start_month and day >= start_day:
                    return sign
                elif month == end_month and day <= end_day:
                    return sign

        return 'unknown'

    def load_zodiac_prototype(self, zodiac_sign: str) -> Dict:
        """加载星座原型数据"""
        if zodiac_sign not in self.ZODIAC_INFO:
            raise ValueError(f"Unknown zodiac sign: {zodiac_sign}")

        # 基本信息
        info = self.ZODIAC_INFO[zodiac_sign]

        # 尝试加载详细原型数据
        prototype_file = self.prototypes_dir / f"{zodiac_sign}.md"
        if prototype_file.exists():
            # 这里简化处理，实际应该解析MD文件
            content = prototype_file.read_text(encoding='utf-8')
            # 简化的提取逻辑
            prototype = {
                'sign': zodiac_sign,
                'info': info,
                'has_detailed_data': True,
                'file_path': str(prototype_file)
            }
        else:
            # 使用默认模板
            prototype = {
                'sign': zodiac_sign,
                'info': info,
                'has_detailed_data': False,
                'core_drive': f"{zodiac_sign}的核心动机",
                'cognitive_filter': f"{zodiac_sign}的认知过滤器",
                'emotional_pattern': f"{zodiac_sign}的情感模式",
                'expression_style': f"{zodiac_sign}的表达风格"
            }

        return prototype

    def get_zodiac_compatibility(self, sign1: str, sign2: str) -> Dict:
        """获取两个星座的兼容性"""
        info1 = self.ZODIAC_INFO.get(sign1, {})
        info2 = self.ZODIAC_INFO.get(sign2, {})

        # 元素兼容性
        element_compatibility = self._get_element_compatibility(
            info1.get('element'),
            info2.get('element')
        )

        # 模式兼容性
        mode_compatibility = self._get_mode_compatibility(
            info1.get('mode'),
            info2.get('mode')
        )

        return {
            'sign1': sign1,
            'sign2': sign2,
            'element_compatibility': element_compatibility,
            'mode_compatibility': mode_compatibility,
            'overall_compatibility': self._calculate_overall_compatibility(
                element_compatibility,
                mode_compatibility
            )
        }

    def _get_element_compatibility(self, elem1: str, elem2: str) -> Dict:
        """元素兼容性分析"""
        compatible_elements = {
            'fire': ['fire', 'air'],
            'earth': ['earth', 'water'],
            'air': ['air', 'fire'],
            'water': ['water', 'earth']
        }

        if elem1 == elem2:
            return {'score': 0.9, 'type': 'same_element'}
        elif elem2 in compatible_elements.get(elem1, []):
            return {'score': 0.8, 'type': 'compatible'}
        else:
            return {'score': 0.3, 'type': 'challenging'}

    def _get_mode_compatibility(self, mode1: str, mode2: str) -> Dict:
        """模式兼容性分析"""
        if mode1 == mode2:
            return {'score': 0.7, 'type': 'same_mode'}
        else:
            return {'score': 0.8, 'type': 'different_mode'}

    def _calculate_overall_compatibility(self, element_compat: Dict, mode_compat: Dict) -> float:
        """计算总体兼容性"""
        element_score = element_compat['score']
        mode_score = mode_compat['score']
        return (element_score + mode_score) / 2


def main():
    import argparse

    parser = argparse.ArgumentParser(description='星座引擎')
    parser.add_argument('--birthday', help='生日 (YYYY-MM-DD)')
    parser.add_argument('--compatibility', nargs=2, metavar=('SIGN1', 'SIGN2'),
                       help='检查两个星座的兼容性')

    args = parser.parse_args()

    engine = ZodiacEngine(Path('./references/zodiac-prototypes'))

    if args.birthday:
        sign = engine.identify_zodiac(args.birthday)
        prototype = engine.load_zodiac_prototype(sign)
        print(f"星座: {sign}")
        print(f"信息: {json.dumps(prototype['info'], ensure_ascii=False, indent=2)}")

    if args.compatibility:
        sign1, sign2 = args.compatibility
        compatibility = engine.get_zodiac_compatibility(sign1, sign2)
        print(f"兼容性: {json.dumps(compatibility, ensure_ascii=False, indent=2)}")


if __name__ == '__main__':
    main()


path: scripts/path_mapper.py
content: #!/usr/bin/env python3
"""
路径映射：3条核心路径和节点系统
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class PathMapper:
    """路径映射器"""

    # 3条核心路径
    CORE_PATHS = [
        'path_hero',           # 英雄之路
        'path_creator',        # 创造者之路
        'path_wisdom'          # 智慧之路
    ]

    # 每条路径的核心节点
    PATH_NODES = {
        'path_hero': [
            'call_to_adventure',    # 召唤
            'threshold_crossing',   # 跨越门槛
            'trials_and_challenges', # 试炼与挑战
            'abyss_confrontation',  # 深渊对抗
            'transformation',       # 转化
            'return_with_gift'      # 携礼回归
        ],
        'path_creator': [
            'conception',           # 构思
            'incubation',           # 孕育
            'manifestation',        # 显化
            'refinement',           # 精炼
            'actualization',        # 实现
            'contribution'          # 贡献
        ],
        'path_wisdom': [
            'seeking',              # 寻求
            'learning',             # 学习
            'integration',          # 整合
            'realization',          # 领悟
            'transcendence',        # 超越
            'teaching'              # 传授
        ]
    }

    # 节点权重（默认）
    NODE_WEIGHTS = {
        'call_to_adventure': 0.2,
        'threshold_crossing': 0.15,
        'trials_and_challenges': 0.2,
        'abyss_confrontation': 0.15,
        'transformation': 0.15,
        'return_with_gift': 0.15
    }

    def __init__(self):
        self.path_mappings = {}

    def map_personality_to_paths(self, personality_model: Dict) -> Dict:
        """将人格模型映射到路径"""

        mapping_result = {
            'personality_signature': personality_model.get('integrated_profile', {}),
            'path_affinities': {},
            'primary_path': None,
            'secondary_path': None,
            'path_progressions': {},
            'recommended_journey': []
        }

        # 计算每条路径的亲和度
        for path_name in self.CORE_PATHS:
            affinity = self._calculate_path_affinity(path_name, personality_model)
            mapping_result['path_affinities'][path_name] = affinity

        # 确定主路径和次路径
        sorted_paths = sorted(
            mapping_result['path_affinities'].items(),
            key=lambda x: x[1]['score'],
            reverse=True
        )

        if sorted_paths:
            mapping_result['primary_path'] = sorted_paths[0][0]
            mapping_result['secondary_path'] = sorted_paths[1][0] if len(sorted_paths) > 1 else None

        # 计算路径进展
        for path_name in self.CORE_PATHS:
            progression = self._calculate_path_progression(
                path_name,
                personality_model
            )
            mapping_result['path_progressions'][path_name] = progression

        # 生成推荐旅程
        mapping_result['recommended_journey'] = self._generate_recommended_journey(
            mapping_result
        )

        return mapping_result

    def _calculate_path_affinity(self, path_name: str,
                                 personality_model: Dict) -> Dict:
        """计算路径亲和度"""
        # 简化处理：随机生成亲和度分数
        np.random.seed(hash(path_name) % 2**32)

        affinity_score = np.random.uniform(0.5, 0.95)

        # 识别关键节点
        key_nodes = self.PATH_NODES.get(path_name, [])

        # 计算每个节点的完成度
        node_completions = {}
        for node in key_nodes:
            node_completions[node] = np.random.uniform(0.0, 1.0)

        # 计算整体完成度
        overall_completion = np.mean(list(node_completions.values()))

        return {
            'score': affinity_score,
            'completion': overall_completion,
            'key_nodes': key_nodes,
            'node_completions': node_completions,
            'alignment_factors': self._identify_alignment_factors(path_name)
        }

    def _identify_alignment_factors(self, path_name: str) -> List[str]:
        """识别对齐因素"""

        alignment_factors = {
            'path_hero': ['courage', 'resilience', 'transformation', 'purpose'],
            'path_creator': ['innovation', 'expression', 'craftsmanship', 'impact'],
            'path_wisdom': ['curiosity', 'insight', 'integration', 'teaching']
        }

        return alignment_factors.get(path_name, [])

    def _calculate_path_progression(self, path_name: str,
                                    personality_model: Dict) -> Dict:
        """计算路径进展"""

        nodes = self.PATH_NODES.get(path_name, [])

        progression = {
            'path_name': path_name,
            'total_nodes': len(nodes),
            'completed_nodes': 0,
            'current_node': None,
            'next_node': None,
            'node_sequence': []
        }

        # 随机确定当前位置
        np.random.seed(hash(f"{path_name}_progression") % 2**32)
        current_index = np.random.randint(0, len(nodes))

        progression['current_node'] = nodes[current_index]
        progression['next_node'] = nodes[current_index + 1] if current_index < len(nodes) - 1 else None
        progression['completed_nodes'] = current_index

        # 生成节点序列
        for i, node in enumerate(nodes):
            is_completed = i < current_index
            is_current = i == current_index
            progression['node_sequence'].append({
                'node_name': node,
                'position': i,
                'status': 'completed' if is_completed else 'current' if is_current else 'future'
            })

        return progression

    def _generate_recommended_journey(self, mapping_result: Dict) -> List[Dict]:
        """生成推荐旅程"""

        primary_path = mapping_result.get('primary_path')
        if not primary_path:
            return []

        progression = mapping_result['path_progressions'].get(primary_path, {})
        current_node = progression.get('current_node')
        next_node = progression.get('next_node')

        journey = []

        # 当前阶段
        if current_node:
            journey.append({
                'phase': 'current',
                'path': primary_path,
                'node': current_node,
                'focus': f"Focus on mastering {current_node}",
                'recommended_actions': self._generate_node_actions(current_node, 'current')
            })

        # 下一步
        if next_node:
            journey.append({
                'phase': 'next',
                'path': primary_path,
                'node': next_node,
                'focus': f"Prepare for {next_node}",
                'recommended_actions': self._generate_node_actions(next_node, 'next')
            })

        # 融合次路径的洞察
        secondary_path = mapping_result.get('secondary_path')
        if secondary_path:
            journey.append({
                'phase': 'integration',
                'path': secondary_path,
                'node': 'cross_path_learning',
                'focus': f"Integrate insights from {secondary_path}",
                'recommended_actions': [
                    "Identify complementary practices",
                    "Seek dual-path mentorship",
                    "Create integration rituals"
                ]
            })

        return journey

    def _generate_node_actions(self, node: str, phase: str) -> List[str]:
        """生成节点行动建议"""

        actions_map = {
            'call_to_adventure': ['Listen for inner calling', 'Identify life direction', 'Commit to journey'],
            'threshold_crossing': ['Embrace change', 'Leave comfort zone', 'Cross symbolic boundary'],
            'trials_and_challenges': ['Build resilience', 'Face obstacles', 'Learn from failures'],
            'abyss_confrontation': ['Face deepest fears', 'Surrender to transformation', 'Embrace death and rebirth'],
            'transformation': ['Integrate lessons', 'Embody new self', 'Release old identity'],
            'return_with_gift': ['Share insights', 'Serve community', 'Mentor others']
        }

        actions = actions_map.get(node, ['Explore', 'Learn', 'Grow'])

        if phase == 'next':
            return [f"Prepare for: {action}" for action in actions]

        return actions

    def track_journey_progress(self, path_name: str, current_node: str,
                               achievements: List[str]) -> Dict:
        """追踪旅程进展"""

        tracking = {
            'path_name': path_name,
            'current_node': current_node,
            'achievements': achievements,
            'milestones_reached': len(achievements),
            'next_milestone': self._get_next_milestone(path_name, current_node),
            'overall_progress': self._calculate_overall_progress(
                path_name,
                current_node,
                achievements
            )
        }

        return tracking

    def _get_next_milestone(self, path_name: str,
                           current_node: str) -> str:
        """获取下一个里程碑"""
        nodes = self.PATH_NODES.get(path_name, [])

        try:
            current_index = nodes.index(current_node)
            if current_index < len(nodes) - 1:
                return nodes[current_index + 1]
        except ValueError:
            pass

        return "journey_complete"

    def _calculate_overall_progress(self, path_name: str,
                                    current_node: str,
                                    achievements: List[str]) -> float:
        """计算总体进展"""
        nodes = self.PATH_NODES.get(path_name, [])

        try:
            current_index = nodes.index(current_node)
            node_progress = (current_index + 1) / len(nodes)

            achievement_factor = min(len(achievements) / len(nodes), 1.0)

            overall_progress = (node_progress + achievement_factor) / 2

            return overall_progress

        except ValueError:
            return 0.0


def main():
    import argparse

    parser = argparse.ArgumentParser(description='路径映射')
    parser.add_argument('--model', type=str, required=True,
                       help='人格模型文件路径 (JSON)')

    args = parser.parse_args()

    # 读取人格模型
    model_path = Path(args.model)
    with open(model_path, 'r', encoding='utf-8') as f:
        personality_model = json.load(f)

    # 执行映射
    mapper = PathMapper()
    mapping_result = mapper.map_personality_to_paths(personality_model)

    print(json.dumps(mapping_result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/quality_validator.py
content: #!/usr/bin/env python3
"""
质量验证器：10项质量检查（高级版）
核心算法：基于多维度统计分析和加权评分的质量评估系统
"""

import json
import re
from pathlib import Path
from typing import Dict, List, Tuple
from collections import Counter
import math


class QualityValidator:
    """高级质量验证器"""

    # 10项质量检查（带详细权重和阈值）
    QUALITY_CHECKS = {
        'mental_model_count': {
            'weight': 15,
            'description': '心智模型数量',
            'pass_criteria': '3-7个',
            'pass_score': 15,
            'partial_score': 10,
            'fail_score': 5,
            'algorithm': 'count_and_classify'
        },
        'model_limitations': {
            'weight': 10,
            'description': '每个心智模型都有局限性说明',
            'pass_criteria': '100%覆盖率',
            'pass_score': 10,
            'partial_score': 5,
            'fail_score': 0,
            'algorithm': 'ratio_analysis'
        },
        'model_evidence': {
            'weight': 10,
            'description': '每个心智模型有≥2个证据',
            'pass_criteria': '100%满足',
            'pass_score': 10,
            'partial_score': 7,
            'fail_score': 3,
            'algorithm': 'evidence_counting'
        },
        'expression_dna': {
            'weight': 10,
            'description': '表达DNA特征≥3个',
            'pass_criteria': '≥3个特征',
            'pass_score': 10,
            'partial_score': 6,
            'fail_score': 2,
            'algorithm': 'feature_extraction'
        },
        'honest_boundaries': {
            'weight': 15,
            'description': '诚实边界≥3条',
            'pass_criteria': '≥3条边界',
            'pass_score': 15,
            'partial_score': 10,
            'fail_score': 5,
            'algorithm': 'boundary_detection'
        },
        'internal_tensions': {
            'weight': 10,
            'description': '内在张力≥2处',
            'pass_criteria': '≥2处张力',
            'pass_score': 10,
            'partial_score': 6,
            'fail_score': 2,
            'algorithm': 'tension_identification'
        },
        'decision_heuristics': {
            'weight': 10,
            'description': '决策启发式≥5条',
            'pass_criteria': '≥5条启发式',
            'pass_score': 10,
            'partial_score': 6,
            'fail_score': 2,
            'algorithm': 'pattern_matching'
        },
        'agentic_protocol': {
            'weight': 10,
            'description': '包含3步骤的Agentic Protocol',
            'pass_criteria': '包含完整3步骤',
            'pass_score': 10,
            'partial_score': 5,
            'fail_score': 0,
            'algorithm': 'protocol_validation'
        },
        'toolkit': {
            'weight': 5,
            'description': '工具箱≥3个',
            'pass_criteria': '≥3个工具',
            'pass_score': 5,
            'partial_score': 3,
            'fail_score': 1,
            'algorithm': 'tool_extraction'
        },
        'primary_sources': {
            'weight': 5,
            'description': '一手来源>50%（如有research）',
            'pass_criteria': '>50%',
            'pass_score': 5,
            'partial_score': 3,
            'fail_score': 1,
            'algorithm': 'source_classification'
        }
    }

    # 通过线（总分100分，需≥75分）
    PASSING_SCORE = 75

    def __init__(self):
        self.validation_result = {}

    def validate_skill(self, skill_file: str, research_dir: str = None) -> Dict:
        """验证HumanOS Skill - 主流程"""

        skill_path = Path(skill_file)

        # 读取Skill文件
        with open(skill_path, 'r', encoding='utf-8') as f:
            skill_content = f.read()

        # 执行10项检查
        check_results = {}

        # 检查1: 心智模型数量
        check_results['mental_model_count'] = self._check_mental_model_count_advanced(
            skill_content
        )

        # 检查2: 模型局限性
        check_results['model_limitations'] = self._check_model_limitations_advanced(
            skill_content
        )

        # 检查3: 模型证据
        check_results['model_evidence'] = self._check_model_evidence_advanced(
            skill_content
        )

        # 检查4: 表达DNA
        check_results['expression_dna'] = self._check_expression_dna_advanced(
            skill_content
        )

        # 检查5: 诚实边界
        check_results['honest_boundaries'] = self._check_honest_boundaries_advanced(
            skill_content
        )

        # 检查6: 内在张力
        check_results['internal_tensions'] = self._check_internal_tensions_advanced(
            skill_content
        )

        # 检查7: 决策启发式
        check_results['decision_heuristics'] = self._check_decision_heuristics_advanced(
            skill_content
        )

        # 检查8: Agentic Protocol
        check_results['agentic_protocol'] = self._check_agentic_protocol_advanced(
            skill_content
        )

        # 检查9: 工具箱
        check_results['toolkit'] = self._check_toolkit_advanced(
            skill_content
        )

        # 检查10: 一手来源
        check_results['primary_sources'] = self._check_primary_sources_advanced(
            skill_content,
            research_dir
        )

        # 计算总分（加权）
        total_score = 0
        for check_name, result in check_results.items():
            weight = self.QUALITY_CHECKS[check_name]['weight']
            score = result['score']
            # 归一化得分：score / pass_score * weight
            normalized_score = (score / self.QUALITY_CHECKS[check_name]['pass_score']) * weight
            result['normalized_score'] = round(normalized_score, 2)
            total_score += normalized_score

        total_score = round(total_score, 1)

        # 判断是否通过
        passed = total_score >= self.PASSING_SCORE

        # 生成详细报告
        validation_result = {
            'skill_file': skill_file,
            'total_score': total_score,
            'passing_score': self.PASSING_SCORE,
            'passed': passed,
            'passing_rate': f"{total_score / 100 * 100:.1f}%",
            'check_results': check_results,
            'summary': self._generate_summary_advanced(check_results, total_score),
            'recommendations': self._generate_recommendations_advanced(check_results),
            'quality_grade': self._calculate_quality_grade(total_score),
            'analysis': self._generate_detailed_analysis(check_results)
        }

        self.validation_result = validation_result

        return validation_result

    def _check_mental_model_count_advanced(self, skill_content: str) -> Dict:
        """高级心智模型数量检查"""

        # 识别心智模型的多种模式
        patterns = [
            r'\*\*([^*]+)\*\*.*?(?:思维模型|原理|框架|效应|法则)',
            r'##\s+(?:心智模型|Mental Models).*?\n(.*?)(?=\n##|\Z)',
            r'模型\d+\s*[:：]\s*\*\*([^*]+)\*\*',
            r'([^.\n]+)(?:思维模型|原理|框架)'
        ]

        models = set()

        for pattern in patterns:
            matches = re.findall(pattern, skill_content, re.MULTILINE | re.DOTALL)
            for match in matches:
                if isinstance(match, tuple):
                    model_name = match[0].strip()
                else:
                    model_name = match.strip()

                # 过滤无效模型
                if len(model_name) >= 2 and not model_name.isdigit():
                    models.add(model_name)

        model_list = sorted(list(models))
        model_count = len(model_list)

        # 评分
        if 3 <= model_count <= 7:
            score = self.QUALITY_CHECKS['mental_model_count']['pass_score']
            status = 'pass'
        elif model_count >= 1 and model_count < 3:
            score = self.QUALITY_CHECKS['mental_model_count']['partial_score']
            status = 'partial'
        elif model_count > 7:
            score = self.QUALITY_CHECKS['mental_model_count']['pass_score']  # 超过也算通过
            status = 'pass'
        else:
            score = self.QUALITY_CHECKS['mental_model_count']['fail_score']
            status = 'fail'

        return {
            'check': 'mental_model_count',
            'description': self.QUALITY_CHECKS['mental_model_count']['description'],
            'criteria': self.QUALITY_CHECKS['mental_model_count']['pass_criteria'],
            'actual': model_count,
            'models': model_list[:10],  # 返回前10个
            'score': score,
            'status': status,
            'message': f"发现{model_count}个心智模型: {', '.join(model_list[:5])}{'...' if model_count > 5 else ''}",
            'algorithm': self.QUALITY_CHECKS['mental_model_count']['algorithm']
        }

    def _check_model_limitations_advanced(self, skill_content: str) -> Dict:
        """高级模型局限性检查"""

        # 获取心智模型
        model_check = self._check_mental_model_count_advanced(skill_content)
        models = model_check['models']
        model_count = model_check['actual']

        if model_count == 0:
            return {
                'check': 'model_limitations',
                'description': self.QUALITY_CHECKS['model_limitations']['description'],
                'criteria': self.QUALITY_CHECKS['model_limitations']['pass_criteria'],
                'actual': "0%",
                'score': self.QUALITY_CHECKS['model_limitations']['fail_score'],
                'status': 'fail',
                'message': '未发现心智模型',
                'algorithm': self.QUALITY_CHECKS['model_limitations']['algorithm']
            }

        # 识别局限性模式
        limitation_patterns = [
            r'(?:局限|不适用|不能|做不到|边界|限制|缺点)',
            r'局限性\s*[:：]',
            r'注意\s*[:：].*?(?:局限|限制)'
        ]

        found_limitations = set()

        for pattern in limitation_patterns:
            matches = re.finditer(pattern, skill_content)
            for match in matches:
                # 获取上下文
                context_start = max(0, match.start() - 30)
                context_end = min(len(skill_content), match.end() + 30)
                context = skill_content[context_start:context_end]

                found_limitations.add(context)

        limitation_count = len(found_limitations)
        limitation_ratio = limitation_count / model_count

        # 评分
        if limitation_ratio >= 1.0:
            score = self.QUALITY_CHECKS['model_limitations']['pass_score']
            status = 'pass'
        elif limitation_ratio >= 0.5:
            score = self.QUALITY_CHECKS['model_limitations']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['model_limitations']['fail_score']
            status = 'fail'

        return {
            'check': 'model_limitations',
            'description': self.QUALITY_CHECKS['model_limitations']['description'],
            'criteria': self.QUALITY_CHECKS['model_limitations']['pass_criteria'],
            'actual': f"{int(limitation_ratio * 100)}%",
            'limitation_count': limitation_count,
            'model_count': model_count,
            'score': score,
            'status': status,
            'message': f"发现{limitation_count}处局限性说明，覆盖{int(limitation_ratio * 100)}%模型",
            'algorithm': self.QUALITY_CHECKS['model_limitations']['algorithm']
        }

    def _check_model_evidence_advanced(self, skill_content: str) -> Dict:
        """高级模型证据检查"""

        # 获取心智模型
        model_check = self._check_mental_model_count_advanced(skill_content)
        models = model_check['models']
        model_count = model_check['actual']

        if model_count == 0:
            return {
                'check': 'model_evidence',
                'description': self.QUALITY_CHECKS['model_evidence']['description'],
                'criteria': self.QUALITY_CHECKS['model_evidence']['pass_criteria'],
                'actual': "0个证据/模型",
                'score': self.QUALITY_CHECKS['model_evidence']['fail_score'],
                'status': 'fail',
                'message': '未发现心智模型',
                'algorithm': self.QUALITY_CHECKS['model_evidence']['algorithm']
            }

        # 识别证据关键词
        evidence_keywords = [
            '证据', '案例', '实证', '例子', '例如',
            '比如', '举例', '证明', '显示', '表明',
            'example', 'case', 'evidence', 'proof'
        ]

        evidence_count = 0

        for keyword in evidence_keywords:
            # 统计关键词出现次数
            count = skill_content.lower().count(keyword.lower())
            evidence_count += count

        # 计算证据/模型比率
        evidence_ratio = evidence_count / model_count if model_count > 0 else 0

        # 评分
        if evidence_ratio >= 2.0:
            score = self.QUALITY_CHECKS['model_evidence']['pass_score']
            status = 'pass'
        elif evidence_ratio >= 1.0:
            score = self.QUALITY_CHECKS['model_evidence']['pass_score']  # >=1个也算通过
            status = 'pass'
        elif evidence_ratio > 0:
            score = self.QUALITY_CHECKS['model_evidence']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['model_evidence']['fail_score']
            status = 'fail'

        return {
            'check': 'model_evidence',
            'description': self.QUALITY_CHECKS['model_evidence']['description'],
            'criteria': self.QUALITY_CHECKS['model_evidence']['pass_criteria'],
            'actual': f"{evidence_ratio:.1f}个证据/模型",
            'evidence_count': evidence_count,
            'model_count': model_count,
            'score': score,
            'status': status,
            'message': f"发现{evidence_count}处证据引用，平均{evidence_ratio:.1f}个证据/模型",
            'algorithm': self.QUALITY_CHECKS['model_evidence']['algorithm']
        }

    def _check_expression_dna_advanced(self, skill_content: str) -> Dict:
        """高级表达DNA检查"""

        dna_features = {
            'sentence_patterns': 0,
            'vocabulary': 0,
            'rhythm': 0,
            'style': 0
        }

        # 检查句式模式
        if any(kw in skill_content for kw in ['句式', '句子', '句法']):
            dna_features['sentence_patterns'] = 1

        # 检查词汇
        if any(kw in skill_content for kw in ['词汇', '术语', '用词']):
            dna_features['vocabulary'] = 1

        # 检查节奏
        if any(kw in skill_content for kw in ['节奏', '语速', '停顿']):
            dna_features['rhythm'] = 1

        # 检查风格
        if any(kw in skill_content for kw in ['风格', '表达', '语气']):
            dna_features['style'] = 1

        feature_count = sum(dna_features.values())

        # 评分
        if feature_count >= 3:
            score = self.QUALITY_CHECKS['expression_dna']['pass_score']
            status = 'pass'
        elif feature_count >= 1:
            score = self.QUALITY_CHECKS['expression_dna']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['expression_dna']['fail_score']
            status = 'fail'

        return {
            'check': 'expression_dna',
            'description': self.QUALITY_CHECKS['expression_dna']['description'],
            'criteria': self.QUALITY_CHECKS['expression_dna']['pass_criteria'],
            'actual': feature_count,
            'features': {k: v for k, v in dna_features.items() if v > 0},
            'score': score,
            'status': status,
            'message': f"发现{feature_count}个表达DNA特征",
            'algorithm': self.QUALITY_CHECKS['expression_dna']['algorithm']
        }

    def _check_honest_boundaries_advanced(self, skill_content: str) -> Dict:
        """高级诚实边界检查"""

        # 识别边界关键词和模式
        boundary_patterns = [
            r'(?:边界|不能|做不到|不擅长|局限|限制|无法|难以)',
            r'诚实边界\s*[:：]',
            r'注意事项\s*[:：]',
            r'局限性\s*[:：]'
        ]

        found_boundaries = set()

        for pattern in boundary_patterns:
            matches = re.finditer(pattern, skill_content)
            for match in matches:
                # 获取上下文
                context_start = max(0, match.start() - 50)
                context_end = min(len(skill_content), match.end() + 50)
                context = skill_content[context_start:context_end]

                found_boundaries.add(context[:100])

        boundary_count = len(found_boundaries)

        # 评分
        if boundary_count >= 3:
            score = self.QUALITY_CHECKS['honest_boundaries']['pass_score']
            status = 'pass'
        elif boundary_count >= 1:
            score = self.QUALITY_CHECKS['honest_boundaries']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['honest_boundaries']['fail_score']
            status = 'fail'

        return {
            'check': 'honest_boundaries',
            'description': self.QUALITY_CHECKS['honest_boundaries']['description'],
            'criteria': self.QUALITY_CHECKS['honest_boundaries']['pass_criteria'],
            'actual': boundary_count,
            'score': score,
            'status': status,
            'message': f"发现{boundary_count}条诚实边界",
            'algorithm': self.QUALITY_CHECKS['honest_boundaries']['algorithm']
        }

    def _check_internal_tensions_advanced(self, skill_content: str) -> Dict:
        """高级内在张力检查"""

        # 识别张力关键词和模式
        tension_patterns = [
            r'(?:张力|矛盾|冲突|不一致|悖论|两难|困境)',
            r'内在张力\s*[:：]',
            r'核心矛盾\s*[:：]'
        ]

        found_tensions = set()

        for pattern in tension_patterns:
            matches = re.finditer(pattern, skill_content)
            for match in matches:
                # 获取上下文
                context_start = max(0, match.start() - 50)
                context_end = min(len(skill_content), match.end() + 50)
                context = skill_content[context_start:context_end]

                found_tensions.add(context[:100])

        tension_count = len(found_tensions)

        # 评分
        if tension_count >= 2:
            score = self.QUALITY_CHECKS['internal_tensions']['pass_score']
            status = 'pass'
        elif tension_count >= 1:
            score = self.QUALITY_CHECKS['internal_tensions']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['internal_tensions']['fail_score']
            status = 'fail'

        return {
            'check': 'internal_tensions',
            'description': self.QUALITY_CHECKS['internal_tensions']['description'],
            'criteria': self.QUALITY_CHECKS['internal_tensions']['pass_criteria'],
            'actual': tension_count,
            'score': score,
            'status': status,
            'message': f"发现{tension_count}处内在张力",
            'algorithm': self.QUALITY_CHECKS['internal_tensions']['algorithm']
        }

    def _check_decision_heuristics_advanced(self, skill_content: str) -> Dict:
        """高级决策启发式检查"""

        # 识别启发式模式
        heuristic_patterns = [
            r'当(.{1,30})\s*时\s*[，,]?\s*应该?(.{1,60})',
            r'如果是?(.{1,30})\s*[，,]?\s*则?(.{1,60})',
            r'(.{1,15})\s*(?:原则|准则|Rule|Principle)\s*[:：]?\s*([^.。]+)',
            r'在?(.{1,20})\s*时\s*[，,]?\s*优先?(.{1,50})',
            r'(?:启发式|Heuristic)\s*\d+\s*[:：]'
        ]

        found_heuristics = set()

        for pattern in heuristic_patterns:
            matches = re.finditer(pattern, skill_content)
            for match in matches:
                heuristic = match.group(0).strip()
                # 过滤和验证质量
                if 15 <= len(heuristic) <= 120:
                    found_heuristics.add(heuristic[:80])

        heuristic_count = len(found_heuristics)

        # 评分
        if heuristic_count >= 5:
            score = self.QUALITY_CHECKS['decision_heuristics']['pass_score']
            status = 'pass'
        elif heuristic_count >= 1:
            score = self.QUALITY_CHECKS['decision_heuristics']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['decision_heuristics']['fail_score']
            status = 'fail'

        return {
            'check': 'decision_heuristics',
            'description': self.QUALITY_CHECKS['decision_heuristics']['description'],
            'criteria': self.QUALITY_CHECKS['decision_heuristics']['pass_criteria'],
            'actual': heuristic_count,
            'score': score,
            'status': status,
            'message': f"发现{heuristic_count}条决策启发式",
            'algorithm': self.QUALITY_CHECKS['decision_heuristics']['algorithm']
        }

    def _check_agentic_protocol_advanced(self, skill_content: str) -> Dict:
        """高级Agentic Protocol检查"""

        # 检查是否存在Agentic Protocol
        has_agentic_protocol = 'Agentic Protocol' in skill_content or 'agentic protocol' in skill_content.lower()

        if not has_agentic_protocol:
            return {
                'check': 'agentic_protocol',
                'description': self.QUALITY_CHECKS['agentic_protocol']['description'],
                'criteria': self.QUALITY_CHECKS['agentic_protocol']['pass_criteria'],
                'actual': 0,
                'score': self.QUALITY_CHECKS['agentic_protocol']['fail_score'],
                'status': 'fail',
                'message': '未发现Agentic Protocol',
                'algorithm': self.QUALITY_CHECKS['agentic_protocol']['algorithm']
            }

        # 提取Agentic Protocol部分
        protocol_pattern = r'Agentic Protocol.*?(?=\n##|\Z)'
        protocol_match = re.search(protocol_pattern, skill_content, re.DOTALL | re.IGNORECASE)

        if not protocol_match:
            return {
                'check': 'agentic_protocol',
                'description': self.QUALITY_CHECKS['agentic_protocol']['description'],
                'criteria': self.QUALITY_CHECKS['agentic_protocol']['pass_criteria'],
                'actual': 0,
                'score': self.QUALITY_CHECKS['agentic_protocol']['fail_score'],
                'status': 'fail',
                'message': 'Agentic Protocol格式不正确',
                'algorithm': self.QUALITY_CHECKS['agentic_protocol']['algorithm']
            }

        protocol_text = protocol_match.group(0)

        # 检查步骤
        step_patterns = [
            r'步骤\s*[123]',
            r'Step\s*[123]',
            r'[一二三]\s*[、\.]?\s*步骤'
        ]

        steps_found = set()
        for pattern in step_patterns:
            matches = re.findall(pattern, protocol_text, re.IGNORECASE)
            steps_found.update(matches)

        step_count = len(steps_found)

        # 检查是否包含必需步骤
        required_steps = ['问题', '研究', '回答', 'Question', 'Research', 'Answer']
        has_required = any(step in protocol_text for step in required_steps)

        # 评分
        if step_count >= 3 and has_required:
            score = self.QUALITY_CHECKS['agentic_protocol']['pass_score']
            status = 'pass'
        elif step_count >= 1:
            score = self.QUALITY_CHECKS['agentic_protocol']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['agentic_protocol']['fail_score']
            status = 'fail'

        return {
            'check': 'agentic_protocol',
            'description': self.QUALITY_CHECKS['agentic_protocol']['description'],
            'criteria': self.QUALITY_CHECKS['agentic_protocol']['pass_criteria'],
            'actual': step_count,
            'score': score,
            'status': status,
            'message': f"发现{step_count}个Agentic Protocol步骤",
            'algorithm': self.QUALITY_CHECKS['agentic_protocol']['algorithm']
        }

    def _check_toolkit_advanced(self, skill_content: str) -> Dict:
        """高级工具箱检查"""

        # 识别工具模式
        tool_patterns = [
            r'##\s*(?:工具箱|Toolkit|Tools)\s*\n(.*?)(?=\n##|\Z)',
            r'工具\s*\d*\s*[:：]\s*([^.\n]+)',
            r'使用\s*(\w+)(?:工具|方法|技巧)',
            r'Tool\s*\d*\s*[:：]\s*([^.\n]+)'
        ]

        found_tools = set()

        for pattern in tool_patterns:
            matches = re.finditer(pattern, skill_content, re.DOTALL)
            for match in matches:
                tool = match.group(1) if match.lastindex >= 1 else match.group(0)
                tool = tool.strip()

                if len(tool) >= 2 and not tool.isdigit():
                    found_tools.add(tool[:50])

        tool_count = len(found_tools)

        # 评分
        if tool_count >= 3:
            score = self.QUALITY_CHECKS['toolkit']['pass_score']
            status = 'pass'
        elif tool_count >= 1:
            score = self.QUALITY_CHECKS['toolkit']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['toolkit']['fail_score']
            status = 'fail'

        return {
            'check': 'toolkit',
            'description': self.QUALITY_CHECKS['toolkit']['description'],
            'criteria': self.QUALITY_CHECKS['toolkit']['pass_criteria'],
            'actual': tool_count,
            'score': score,
            'status': status,
            'message': f"发现{tool_count}个工具",
            'algorithm': self.QUALITY_CHECKS['toolkit']['algorithm']
        }

    def _check_primary_sources_advanced(self, skill_content: str,
                                        research_dir: str = None) -> Dict:
        """高级一手来源检查"""

        # 如果没有提供research目录，跳过此项
        if not research_dir:
            return {
                'check': 'primary_sources',
                'description': self.QUALITY_CHECKS['primary_sources']['description'],
                'criteria': self.QUALITY_CHECKS['primary_sources']['pass_criteria'],
                'actual': 'N/A',
                'score': self.QUALITY_CHECKS['primary_sources']['pass_score'],
                'status': 'pass',
                'message': '未提供research目录，跳过此项',
                'algorithm': self.QUALITY_CHECKS['primary_sources']['algorithm']
            }

        research_path = Path(research_dir)

        if not research_path.exists():
            return {
                'check': 'primary_sources',
                'description': self.QUALITY_CHECKS['primary_sources']['description'],
                'criteria': self.QUALITY_CHECKS['primary_sources']['pass_criteria'],
                'actual': 'N/A',
                'score': self.QUALITY_CHECKS['primary_sources']['pass_score'],
                'status': 'pass',
                'message': 'Research目录不存在，跳过此项',
                'algorithm': self.QUALITY_CHECKS['primary_sources']['algorithm']
            }

        # 统计来源
        primary_sources = 0
        secondary_sources = 0
        total_sources = 0

        # 扫描research目录
        for file_path in research_path.glob('**/*.md'):
            total_sources += 1

            # 判断来源类型
            filename = file_path.stem.lower()

            # 一手来源指标
            primary_indicators = [
                'writings', 'interview', 'speech', 'conversation',
                'original', 'primary', 'transcript'
            ]

            # 二手来源指标
            secondary_indicators = [
                'summary', 'analysis', 'review', 'commentary',
                'secondary', 'interpretation'
            ]

            if any(ind in filename for ind in primary_indicators):
                primary_sources += 1
            elif any(ind in filename for ind in secondary_indicators):
                secondary_sources += 1
            else:
                # 默认认为是一手来源
                primary_sources += 1

        if total_sources > 0:
            primary_ratio = primary_sources / total_sources
        else:
            primary_ratio = 0

        # 评分
        if primary_ratio > 0.5:
            score = self.QUALITY_CHECKS['primary_sources']['pass_score']
            status = 'pass'
        elif primary_ratio > 0:
            score = self.QUALITY_CHECKS['primary_sources']['partial_score']
            status = 'partial'
        else:
            score = self.QUALITY_CHECKS['primary_sources']['fail_score']
            status = 'fail'

        return {
            'check': 'primary_sources',
            'description': self.QUALITY_CHECKS['primary_sources']['description'],
            'criteria': self.QUALITY_CHECKS['primary_sources']['pass_criteria'],
            'actual': f"{int(primary_ratio * 100)}%",
            'primary_count': primary_sources,
            'secondary_count': secondary_sources,
            'total_count': total_sources,
            'score': score,
            'status': status,
            'message': f"发现{primary_sources}/{total_sources}个一手来源 ({int(primary_ratio * 100)}%)",
            'algorithm': self.QUALITY_CHECKS['primary_sources']['algorithm']
        }

    def _generate_summary_advanced(self, check_results: Dict, total_score: float) -> Dict:
        """生成高级验证总结"""

        passed_checks = sum(1 for result in check_results.values() if result['status'] == 'pass')
        partial_checks = sum(1 for result in check_results.values() if result['status'] == 'partial')
        failed_checks = sum(1 for result in check_results.values() if result['status'] == 'fail')

        return {
            'total_checks': len(check_results),
            'passed': passed_checks,
            'partial': partial_checks,
            'failed': failed_checks,
            'overall_score': total_score,
            'passing_line': self.PASSING_SCORE,
            'passed_checks_count': passed_checks,
            'pass_rate': f"{passed_checks / len(check_results) * 100:.0f}%" if check_results else "0%"
        }

    def _generate_recommendations_advanced(self, check_results: Dict) -> List[Dict]:
        """生成高级改进建议"""

        recommendations = []

        for check_name, result in check_results.items():
            if result['status'] == 'fail':
                recommendations.append({
                    'priority': 'high',
                    'check': result['description'],
                    'message': f'未通过，需要补充。当前: {result["actual"]}',
                    'action': f'添加至少{result["criteria"]}的{result["description"]}'
                })
            elif result['status'] == 'partial':
                recommendations.append({
                    'priority': 'medium',
                    'check': result['description'],
                    'message': f'部分通过，建议改进。当前: {result["actual"]}',
                    'action': f'提升{result["description"]}至{result["criteria"]}'
                })

        return recommendations

    def _calculate_quality_grade(self, total_score: float) -> str:
        """计算质量等级"""

        if total_score >= 90:
            return 'A+'
        elif total_score >= 85:
            return 'A'
        elif total_score >= 80:
            return 'A-'
        elif total_score >= 75:
            return 'B+'
        elif total_score >= 70:
            return 'B'
        elif total_score >= 65:
            return 'B-'
        elif total_score >= 60:
            return 'C'
        elif total_score >= 50:
            return 'D'
        else:
            return 'F'

    def _generate_detailed_analysis(self, check_results: Dict) -> Dict:
        """生成详细分析"""

        analysis = {
            'strengths': [],
            'weaknesses': [],
            'opportunities': []
        }

        for check_name, result in check_results.items():
            if result['status'] == 'pass':
                analysis['strengths'].append({
                    'area': result['description'],
                    'performance': f'优秀 (得分: {result["normalized_score"]})'
                })
            elif result['status'] == 'fail':
                analysis['weaknesses'].append({
                    'area': result['description'],
                    'issue': f'不满足要求 (当前: {result["actual"]})'
                })
            elif result['status'] == 'partial':
                analysis['opportunities'].append({
                    'area': result['description'],
                    'improvement': f'可以提升 (当前: {result["actual"]}, 目标: {result["criteria"]})'
                })

        return analysis


def main():
    import argparse

    parser = argparse.ArgumentParser(description='质量验证（高级版）')
    parser.add_argument('--skill-file', type=str, required=True,
                       help='Skill文件路径')
    parser.add_argument('--research-dir', type=str,
                       help='Research目录路径（可选）')
    parser.add_argument('--output', type=str,
                       help='输出JSON文件路径（可选）')

    args = parser.parse_args()

    validator = QualityValidator()

    # 执行验证
    validation_result = validator.validate_skill(
        args.skill_file,
        args.research_dir
    )

    # 输出结果
    print(json.dumps(validation_result, ensure_ascii=False, indent=2))

    # 保存到文件（可选）
    if args.output:
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(validation_result, f, ensure_ascii=False, indent=2)
        print(f"\n验证结果已保存到: {args.output}")


if __name__ == '__main__':
    main()


path: scripts/axis_analyzer.py
content: #!/usr/bin/env python3
"""
核心轴分析：5个核心轴系统
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class AxisAnalyzer:
    """核心轴分析器"""

    # 5个核心轴
    CORE_AXES = [
        'axis_structure',        # 结构轴：稳定性 vs 变革性
        'axis_action',           # 行动轴：内向 vs 外向
        'axis_perception',       # 感知轴：具体 vs 抽象
        'axis_decision',         # 决策轴：逻辑 vs 价值
        'axis_expression'        # 表达轴：收敛 vs 发散
    ]

    # 轴的两极定义
    AXIS_POLES = {
        'axis_structure': {
            'positive': 'stability',    # 稳定性
            'negative': 'transformation' # 变革性
        },
        'axis_action': {
            'positive': 'introversion', # 内向
            'negative': 'extraversion'  # 外向
        },
        'axis_perception': {
            'positive': 'concrete',     # 具体
            'negative': 'abstract'      # 抽象
        },
        'axis_decision': {
            'positive': 'logic',        # 逻辑
            'negative': 'value'         # 价值
        },
        'axis_expression': {
            'positive': 'convergent',   # 收敛
            'negative': 'divergent'     # 发散
        }
    }

    def __init__(self):
        self.axis_profiles = {}

    def analyze_axes(self, personality_model: Dict,
                    scan_result: Dict) -> Dict:
        """分析核心轴"""

        analysis_result = {
            'axis_positions': {},
            'axis_strengths': {},
            'axis_balance': {},
            'axis_interactions': {},
            'dominant_axes': [],
            'axis_archetype': None
        }

        # 分析每个轴
        for axis_name in self.CORE_AXES:
            axis_analysis = self._analyze_single_axis(
                axis_name,
                personality_model,
                scan_result
            )

            analysis_result['axis_positions'][axis_name] = axis_analysis['position']
            analysis_result['axis_strengths'][axis_name] = axis_analysis['strength']
            analysis_result['axis_balance'][axis_name] = axis_analysis['balance']

        # 分析轴间交互
        analysis_result['axis_interactions'] = self._analyze_axis_interactions(
            analysis_result['axis_positions']
        )

        # 识别主导轴
        analysis_result['dominant_axes'] = self._identify_dominant_axes(
            analysis_result['axis_strengths']
        )

        # 确定轴原型
        analysis_result['axis_archetype'] = self._determine_axis_archetype(
            analysis_result['axis_positions']
        )

        return analysis_result

    def _analyze_single_axis(self, axis_name: str,
                             personality_model: Dict,
                             scan_result: Dict) -> Dict:
        """分析单个轴"""

        # 生成轴位置（-1到1之间）
        np.random.seed(hash(axis_name) % 2**32)
        axis_position = np.random.uniform(-1, 1)

        # 生成轴强度
        axis_strength = np.random.uniform(0.5, 0.95)

        # 计算轴平衡度
        axis_balance = 1 - abs(axis_position)

        # 确定主导极性
        poles = self.AXIS_POLES.get(axis_name, {})
        dominant_pole = poles['positive'] if axis_position >= 0 else poles['negative']

        return {
            'axis_name': axis_name,
            'position': axis_position,
            'strength': axis_strength,
            'balance': axis_balance,
            'dominant_pole': dominant_pole,
            'poles': poles
        }

    def _analyze_axis_interactions(self, axis_positions: Dict) -> Dict:
        """分析轴间交互"""

        interactions = {}

        # 分析每对轴的交互
        axis_pairs = [
            ('axis_structure', 'axis_action'),
            ('axis_perception', 'axis_decision'),
            ('axis_structure', 'axis_expression'),
            ('axis_action', 'axis_expression'),
            ('axis_perception', 'axis_structure')
        ]

        for axis1, axis2 in axis_pairs:
            if axis1 in axis_positions and axis2 in axis_positions:
                interaction = self._calculate_pair_interaction(
                    axis1,
                    axis2,
                    axis_positions[axis1],
                    axis_positions[axis2]
                )

                interactions[f"{axis1}_x_{axis2}"] = interaction

        return interactions

    def _calculate_pair_interaction(self, axis1: str, axis2: str,
                                   position1: float, position2: float) -> Dict:
        """计算两个轴的交互"""

        # 计算交互强度
        interaction_strength = abs(position1 * position2)

        # 确定交互类型
        if position1 * position2 >= 0:
            # 同向：协同
            interaction_type = 'synergistic'
        else:
            # 反向：张力
            interaction_type = 'tension'

        # 识别交互效应
        interaction_effects = self._identify_interaction_effects(
            axis1,
            axis2,
            position1,
            position2
        )

        return {
            'axis1': axis1,
            'axis2': axis2,
            'position1': position1,
            'position2': position2,
            'strength': interaction_strength,
            'type': interaction_type,
            'effects': interaction_effects
        }

    def _identify_interaction_effects(self, axis1: str, axis2: str,
                                     position1: float, position2: float) -> List[str]:
        """识别交互效应"""

        effects = []

        # 简化处理
        if abs(position1) > 0.7 and abs(position2) > 0.7:
            effects.append('strong_interaction')

        if position1 * position2 < -0.5:
            effects.append('high_tension')

        if position1 * position2 > 0.5:
            effects.append('strong_synergy')

        return effects

    def _identify_dominant_axes(self, axis_strengths: Dict) -> List[str]:
        """识别主导轴"""

        sorted_axes = sorted(
            axis_strengths.items(),
            key=lambda x: x[1]['strength'],
            reverse=True
        )

        return [axis_name for axis_name, _ in sorted_axes[:3]]

    def _determine_axis_archetype(self, axis_positions: Dict) -> str:
        """确定轴原型"""

        # 简化处理：基于主导极性组合
        dominant_poles = []

        for axis_name, position in axis_positions.items():
            poles = self.AXIS_POLES.get(axis_name, {})
            if position >= 0:
                dominant_poles.append(poles.get('positive', ''))
            else:
                dominant_poles.append(poles.get('negative', ''))

        # 组合生成原型名称
        archetype = "-".join(dominant_poles[:3]).lower()

        return archetype

    def generate_axis_report(self, analysis_result: Dict) -> str:
        """生成轴分析报告"""

        report_lines = [
            "=== 核心轴分析报告 ===\n",
            "轴位置分析："
        ]

        for axis_name, position in analysis_result['axis_positions'].items():
            poles = analysis_result['axis_positions'][axis_name].get('poles', {})
            positive = poles.get('positive', '')
            negative = poles.get('negative', '')

            dominant_pole = analysis_result['axis_positions'][axis_name].get('dominant_pole', '')

            report_lines.append(f"  {axis_name}: {position:.2f}")
            report_lines.append(f"    主导极性: {dominant_pole}")
            report_lines.append(f"    两极: {positive} vs {negative}")

        report_lines.append("\n主导轴:")
        for axis in analysis_result['dominant_axes']:
            report_lines.append(f"  - {axis}")

        report_lines.append(f"\n轴原型: {analysis_result['axis_archetype']}")

        report_lines.append("\n轴间交互:")
        for interaction_name, interaction in analysis_result['axis_interactions'].items():
            report_lines.append(f"  {interaction_name}:")
            report_lines.append(f"    类型: {interaction['type']}")
            report_lines.append(f"    强度: {interaction['strength']:.2f}")
            report_lines.append(f"    效应: {', '.join(interaction['effects'])}")

        return "\n".join(report_lines)

    def track_axis_evolution(self, axis_name: str, current_position: float,
                            historical_positions: List[float]) -> Dict:
        """追踪轴演化"""

        evolution = {
            'axis_name': axis_name,
            'current_position': current_position,
            'historical_positions': historical_positions,
            'trend': self._calculate_trend(historical_positions + [current_position]),
            'stability': self._calculate_stability(historical_positions + [current_position]),
            'evolution_velocity': self._calculate_evolution_velocity(
                historical_positions + [current_position]
            )
        }

        return evolution

    def _calculate_trend(self, positions: List[float]) -> str:
        """计算趋势"""
        if len(positions) < 2:
            return 'insufficient_data'

        slope = positions[-1] - positions[0]

        if slope > 0.2:
            return 'positive'
        elif slope < -0.2:
            return 'negative'
        else:
            return 'stable'

    def _calculate_stability(self, positions: List[float]) -> float:
        """计算稳定性"""
        if len(positions) < 2:
            return 0.0

        variance = np.var(positions)
        stability = 1 - min(variance, 1.0)

        return stability

    def _calculate_evolution_velocity(self, positions: List[float]) -> float:
        """计算演化速度"""
        if len(positions) < 2:
            return 0.0

        velocities = []
        for i in range(1, len(positions)):
            velocity = abs(positions[i] - positions[i-1])
            velocities.append(velocity)

        return np.mean(velocities)


def main():
    import argparse

    parser = argparse.ArgumentParser(description='核心轴分析')
    parser.add_argument('--model', type=str, required=True,
                       help='人格模型文件路径 (JSON)')
    parser.add_argument('--scan', type=str, required=True,
                       help='扫描结果文件路径 (JSON)')

    args = parser.parse_args()

    # 读取输入文件
    with open(args.model, 'r', encoding='utf-8') as f:
        personality_model = json.load(f)

    with open(args.scan, 'r', encoding='utf-8') as f:
        scan_result = json.load(f)

    # 执行分析
    analyzer = AxisAnalyzer()
    analysis_result = analyzer.analyze_axes(personality_model, scan_result)

    # 输出报告
    report = analyzer.generate_axis_report(analysis_result)
    print(report)

    # 输出JSON结果
    print("\n=== JSON 结果 ===")
    print(json.dumps(analysis_result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/framework_extractor.py
content: #!/usr/bin/env python3
"""
框架提取器：从调研材料中提取思维框架
核心算法：基于多维度交叉验证的框架提取与四维评分系统
"""

import json
import re
from pathlib import Path
from typing import Dict, List, Tuple, Set
from collections import Counter, defaultdict
import math


class FrameworkExtractor:
    """框架提取器 - 基于统计语言学和多维度验证"""

    # 四维验证标准（带权重和动态阈值）
    VALIDATION_CRITERIA = {
        'cross_domain_reproducibility': {
            'weight': 3,
            'threshold': 2,
            'description': '在≥2个领域出现',
            'pass_score': 3,
            'partial_score': 2,
            'fail_score': 1
        },
        'generative_power': {
            'weight': 2,
            'threshold': 1,
            'description': '能推断新问题立场',
            'pass_score': 2,
            'partial_score': 1,
            'fail_score': 0
        },
        'exclusivity': {
            'weight': 2,
            'threshold': 1,
            'description': '不是通用真理',
            'pass_score': 2,
            'partial_score': 1,
            'fail_score': 0
        },
        'testability': {
            'weight': 1,
            'threshold': 1,
            'description': '有案例/实证',
            'pass_score': 1,
            'partial_score': 0,
            'fail_score': 0
        }
    }

    # 通过线（总分12分，需≥7分）
    PASSING_SCORE = 7

    # 领域关键词映射
    DOMAIN_KEYWORDS = {
        'business': ['商业', '投资', '创业', '管理', '企业'],
        'technology': ['技术', '开发', '算法', '编程', '系统'],
        'philosophy': ['哲学', '思想', '本质', '真理', '逻辑'],
        'psychology': ['心理', '认知', '行为', '情绪', '思维'],
        'life': ['人生', '生活', '成长', '选择', '价值'],
        'education': ['教育', '学习', '教学', '知识', '理解']
    }

    def __init__(self):
        self.extracted_framework = {}
        self.domain_statistics = defaultdict(int)

    def extract_framework(self, research_dir: str, target: str) -> Dict:
        """提取思维框架 - 主流程"""

        research_path = Path(research_dir)

        # 读取调研文件
        research_data = self._load_research_data(research_path)

        # 分析领域分布
        domain_analysis = self._analyze_domains(research_data)

        # 提取框架组件（使用高级NLP技术）
        framework = {
            'target': target,
            'domain_analysis': domain_analysis,
            'mental_models': self._extract_mental_models_advanced(research_data),
            'decision_heuristics': self._extract_decision_heuristics_advanced(research_data),
            'expression_dna': self._extract_expression_dna_advanced(research_data),
            'values': self._extract_values_advanced(research_data),
            'toolkit': self._extract_toolkit_advanced(research_data),
            'internal_tensions': self._extract_internal_tensions_advanced(research_data),
            'honest_boundaries': self._extract_honest_boundaries_advanced(research_data)
        }

        # 验证心智模型（四维验证 + 一致性检查）
        framework['validated_models'] = self._validate_mental_models_advanced(
            framework['mental_models'],
            research_data
        )

        # 生成框架总结（含质量评分）
        framework['summary'] = self._generate_framework_summary_advanced(framework)

        self.extracted_framework = framework

        return framework

    def _load_research_data(self, research_path: Path) -> Dict:
        """加载调研数据"""

        research_data = {}

        # 读取6个维度的调研文件
        dimensions = [
            '01-writings.md',
            '02-conversations.md',
            '03-expression-dna.md',
            '04-external-views.md',
            '05-decisions.md',
            '06-timeline.md'
        ]

        for dimension_file in dimensions:
            file_path = research_path / dimension_file
            if file_path.exists():
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    # 预处理：去除空白行和冗余空格
                    cleaned_content = self._preprocess_text(content)
                    research_data[dimension_file.replace('.md', '')] = cleaned_content

        return research_data

    def _preprocess_text(self, text: str) -> str:
        """文本预处理"""

        # 去除多余空行
        text = re.sub(r'\n\s*\n', '\n\n', text)
        # 统一标点
        text = text.replace('，', ',').replace('。', '.')
        # 去除多余空格
        text = re.sub(r'\s+', ' ', text)

        return text.strip()

    def _analyze_domains(self, research_data: Dict) -> Dict:
        """分析领域分布"""

        domain_counts = Counter()

        for dimension, text in research_data.items():
            for domain, keywords in self.DOMAIN_KEYWORDS.items():
                for keyword in keywords:
                    domain_counts[domain] += text.count(keyword)

        # 计算占比
        total = sum(domain_counts.values())
        domain_distribution = {
            domain: {
                'count': count,
                'percentage': count / total if total > 0 else 0
            }
            for domain, count in domain_counts.items()
        }

        # 识别主领域
        main_domain = max(domain_counts.items(), key=lambda x: x[1])[0] if domain_counts else 'unknown'

        return {
            'main_domain': main_domain,
            'distribution': domain_distribution,
            'total_mentions': total
        }

    def _extract_mental_models_advanced(self, research_data: Dict) -> List[Dict]:
        """高级心智模型提取 - 基于TF-IDF和共现分析"""

        models = []

        # 收集所有文本
        all_text = ' '.join(research_data.values())

        # 1. 关键词提取（TF-IDF简化版）
        keywords = self._extract_keywords_tfidf(all_text)

        # 2. 模式匹配提取心智模型
        patterns = [
            r'(\w+)\s*[:：]\s*(?:思维模型|原理|框架|效应|法则)',
            r'(\w+)(?:思维模型|原理|框架|效应|法则)',
            r'(\w+)\s*(?:的|是)\s*(?:思维模型|原理|框架)',
            r'(\w+)\s*(?:模型|Model)\s*\d*'
        ]

        for pattern in patterns:
            matches = re.finditer(pattern, all_text, re.IGNORECASE)
            for match in matches:
                model_name = match.group(1).strip()
                if len(model_name) >= 2:  # 过滤单字
                    # 计算上下文窗口
                    context_start = max(0, match.start() - 50)
                    context_end = min(len(all_text), match.end() + 50)
                    context = all_text[context_start:context_end]

                    # 计算重要性（TF-IDF权重）
                    importance = self._calculate_model_importance(model_name, keywords)

                    models.append({
                        'name': model_name,
                        'importance_score': importance,
                        'description': self._extract_model_description(model_name, all_text),
                        'evidence': self._find_model_evidence(model_name, research_data),
                        'contexts': [context],
                        'type': self._classify_model_type(model_name, all_text)
                    })

        # 3. 去重和排序
        unique_models = self._deduplicate_models(models)

        # 4. 按重要性排序
        unique_models.sort(key=lambda x: x['importance_score'], reverse=True)

        # 限制为3-7个
        return unique_models[:7]

    def _extract_keywords_tfidf(self, text: str) -> Dict[str, float]:
        """简化TF-IDF关键词提取"""

        # 分词（简化版）
        words = re.findall(r'\w+', text.lower())

        # 计算词频
        tf = Counter(words)

        # 过滤停用词和短词
        stop_words = {'的', '是', '在', '了', '和', '有', '我', '他', '她', '它', 'the', 'is', 'a', 'an', 'and'}
        keywords = {word: count for word, count in tf.items()
                    if len(word) > 2 and word not in stop_words}

        # 计算TF-IDF（简化版，只使用TF）
        total_words = sum(tf.values())
        tfidf = {word: count / total_words for word, count in keywords.items()}

        return tfidf

    def _calculate_model_importance(self, model_name: str, keywords: Dict[str, float]) -> float:
        """计算心智模型重要性"""

        # 模型名在关键词中的权重
        model_keywords = model_name.lower().split()
        keyword_weight = sum(keywords.get(kw, 0) for kw in model_keywords)

        # 名字长度加权
        length_weight = min(len(model_name) / 10, 1.0)

        # 综合得分
        importance = keyword_weight * 10 + length_weight * 2

        return round(importance, 2)

    def _extract_model_description(self, model_name: str, text: str) -> str:
        """提取模型描述"""

        # 寻找描述性语句
        patterns = [
            rf'{model_name}\s*[:：]\s*([^.。]+[.。])',
            rf'{model_name}\s*(?:是指|是|为)\s*([^.。]+[.。])',
            rf'(\w+)\s*[:：]\s*{model_name}.*?([^.。]+[.。])'
        ]

        for pattern in patterns:
            matches = re.finditer(pattern, text)
            for match in matches:
                description = match.group(1) if match.lastindex >= 1 else ""
                if len(description) > 10 and len(description) < 100:
                    return description.strip()

        return f"{model_name}思维模型"

    def _find_model_evidence(self, model_name: str, research_data: Dict) -> List[str]:
        """寻找模型证据"""

        evidence = []

        for dimension, text in research_data.items():
            if model_name in text:
                # 寻找包含模型的句子
                sentences = re.split(r'[。！？.!?]', text)
                for sentence in sentences:
                    if model_name in sentence and len(sentence.strip()) > 5:
                        evidence.append(f"{dimension}: {sentence.strip()[:50]}...")
                        if len(evidence) >= 3:  # 最多3条证据
                            break
            if len(evidence) >= 3:
                break

        return evidence[:3]

    def _classify_model_type(self, model_name: str, text: str) -> str:
        """分类模型类型"""

        # 分析模型应用领域
        context = self._get_model_context(model_name, text, window=100)

        if any(kw in context for kw in ['投资', '商业', '企业']):
            return 'business'
        elif any(kw in context for kw in ['心理', '认知', '行为']):
            return 'psychology'
        elif any(kw in context for kw in ['逻辑', '推理', '思考']):
            return 'philosophy'
        elif any(kw in context for kw in ['系统', '流程', '方法']):
            return 'methodology'
        else:
            return 'general'

    def _get_model_context(self, model_name: str, text: str, window: int = 100) -> str:
        """获取模型上下文"""

        index = text.find(model_name)
        if index == -1:
            return ""

        start = max(0, index - window)
        end = min(len(text), index + len(model_name) + window)

        return text[start:end]

    def _deduplicate_models(self, models: List[Dict]) -> List[Dict]:
        """去重心智模型"""

        seen = set()
        unique_models = []

        for model in models:
            model_key = model.get('name', '').lower()
            # 合并相似名称
            if model_key not in seen:
                seen.add(model_key)
                unique_models.append(model)
            else:
                # 如果已存在，合并证据
                for existing in unique_models:
                    if existing.get('name', '').lower() == model_key:
                        existing['evidence'].extend(model['evidence'])
                        existing['importance_score'] = max(
                            existing['importance_score'],
                            model['importance_score']
                        )
                        break

        return unique_models

    def _extract_decision_heuristics_advanced(self, research_data: Dict) -> List[str]:
        """高级启发式提取 - 基于句法分析和语义识别"""

        heuristics = []

        # 高级模式匹配
        patterns = [
            r'当(.{1,30})\s*时\s*[，,]?\s*应该?(.{1,60})',
            r'如果是?(.{1,30})\s*[，,]?\s*则?(.{1,60})',
            r'(.{1,15})\s*(?:原则|准则|Rule|Principle)\s*[:：]?\s*([^.。]+)',
            r'在?(.{1,20})\s*时\s*[，,]?\s*优先?(.{1,50})'
        ]

        for dimension, text in research_data.items():
            for pattern in patterns:
                matches = re.finditer(pattern, text)
                for match in matches:
                    heuristic = match.group(0).strip()
                    # 验证启发式质量
                    if self._validate_heuristic_quality(heuristic):
                        heuristics.append(heuristic)

        # 去重和排序
        unique_heuristics = list(set(heuristics))

        # 按长度排序（优先选择完整的启发式）
        unique_heuristics.sort(key=len, reverse=True)

        return unique_heuristics[:10]

    def _validate_heuristic_quality(self, heuristic: str) -> bool:
        """验证启发式质量"""

        # 长度检查
        if len(heuristic) < 10 or len(heuristic) > 100:
            return False

        # 必须包含条件-结果结构
        condition_indicators = ['当', '如果', '在', '是']
        result_indicators = ['应该', '则', '优先', '原则']

        has_condition = any(ind in heuristic for ind in condition_indicators)
        has_result = any(ind in heuristic for ind in result_indicators)

        return has_condition and has_result

    def _extract_expression_dna_advanced(self, research_data: Dict) -> Dict:
        """高级表达DNA提取 - 基于文本统计和风格分析"""

        dna = {
            'sentence_patterns': [],
            'vocabulary': [],
            'rhythm': '',
            'style_features': {}
        }

        if '03-expression-dna' in research_data:
            expression_text = research_data['03-expression-dna']

            # 1. 句式模式分析
            dna['sentence_patterns'] = self._analyze_sentence_patterns_advanced(expression_text)

            # 2. 词汇分析
            dna['vocabulary'] = self._analyze_vocabulary_advanced(expression_text)

            # 3. 节奏分析
            dna['rhythm'] = self._analyze_rhythm_advanced(expression_text)

            # 4. 风格特征
            dna['style_features'] = self._extract_style_features(expression_text)

        return dna

    def _analyze_sentence_patterns_advanced(self, text: str) -> List[Dict]:
        """高级句式分析"""

        sentences = re.split(r'[。！？.!?]', text)
        sentences = [s.strip() for s in sentences if len(s.strip()) > 0]

        patterns = []

        # 分析句子长度分布
        lengths = [len(s) for s in sentences[:50]]  # 取前50句
        if lengths:
            avg_length = sum(lengths) / len(lengths)
            patterns.append({
                'type': 'average_length',
                'value': round(avg_length, 1),
                'description': f'平均句子长度: {avg_length:.1f}字符'
            })

            # 长短句比例
            long_sentences = sum(1 for l in lengths if l > 30)
            short_sentences = sum(1 for l in lengths if l <= 15)
            patterns.append({
                'type': 'length_distribution',
                'long_ratio': round(long_sentences / len(lengths), 2),
                'short_ratio': round(short_sentences / len(lengths), 2),
                'description': f'长句比例: {long_sentences/len(lengths):.0%}, 短句比例: {short_sentences/len(lengths):.0%}'
            })

        # 分析句式结构
        if_pattern_count = sum(1 for s in sentences if '如果' in s or '若' in s)
        question_pattern_count = sum(1 for s in sentences if '?' in s or '？' in s)
        patterns.append({
            'type': 'structure',
            'conditional_sentences': if_pattern_count,
            'question_sentences': question_pattern_count,
            'description': f'条件句: {if_pattern_count}, 疑问句: {question_pattern_count}'
        })

        return patterns

    def _analyze_vocabulary_advanced(self, text: str) -> List[Dict]:
        """高级词汇分析"""

        words = re.findall(r'\w+', text)
        word_counts = Counter(words)

        # 过滤
        stop_words = {'的', '是', '在', '了', '和', '有', '我', '你', '他', '她', '它'}
        meaningful_words = {
            word: count for word, count in word_counts.items()
            if len(word) > 2 and word not in stop_words
        }

        # 高频词
        top_words = meaningful_words.most_common(10)

        # 词汇丰富度
        unique_ratio = len(set(words)) / len(words) if len(words) > 0 else 0

        return [
            {
                'type': 'frequency',
                'words': [{'word': w, 'count': c} for w, c in top_words],
                'description': f'高频词汇'
            },
            {
                'type': 'richness',
                'value': round(unique_ratio, 3),
                'description': f'词汇丰富度: {unique_ratio:.3f}'
            }
        ]

    def _analyze_rhythm_advanced(self, text: str) -> str:
        """高级节奏分析"""

        sentences = re.split(r'[。！？.!?]', text)
        sentences = [s.strip() for s in sentences if len(s.strip()) > 0][:50]

        # 标点密度
        punctuation_count = text.count('，') + text.count('。') + text.count('！') + text.count('？')
        char_count = len(text)
        punctuation_density = punctuation_count / char_count if char_count > 0 else 0

        # 句长方差
        lengths = [len(s) for s in sentences]
        if len(lengths) > 1:
            avg_length = sum(lengths) / len(lengths)
            variance = sum((l - avg_length) ** 2 for l in lengths) / len(lengths)
            std_dev = math.sqrt(variance)
        else:
            std_dev = 0

        # 判断节奏
        if punctuation_density < 0.02 and std_dev < 10:
            return "长句为主，节奏平缓"
        elif punctuation_density > 0.05 and std_dev > 20:
            return "短句为主，节奏明快"
        elif std_dev > 15:
            return "长短句交替，节奏多变"
        else:
            return "节奏适中"

    def _extract_style_features(self, text: str) -> Dict:
        """提取风格特征"""

        features = {}

        # 是否使用比喻
        metaphor_count = text.count('像') + text.count('如') + text.count('仿佛')
        features['uses_metaphor'] = metaphor_count > 5

        # 是否使用数据
        number_count = len(re.findall(r'\d+', text))
        features['data_oriented'] = number_count > 10

        # 是否使用引用
        quote_count = text.count('"') + text.count('"') + text.count("'")
        features['quotes_sources'] = quote_count > 5

        # 情感倾向
        positive_words = ['好', '优秀', '成功', '喜欢', '爱']
        negative_words = ['坏', '差', '失败', '讨厌', '恨']
        positive_count = sum(text.count(w) for w in positive_words)
        negative_count = sum(text.count(w) for w in negative_words)
        if positive_count > negative_count * 2:
            features['sentiment'] = 'positive'
        elif negative_count > positive_count * 2:
            features['sentiment'] = 'negative'
        else:
            features['sentiment'] = 'neutral'

        return features

    def _extract_values_advanced(self, research_data: Dict) -> List[Dict]:
        """高级价值观提取"""

        values = []

        # 价值观关键词和权重
        value_keywords = {
            '价值': 2, '原则': 2, '信念': 3, '相信': 1, '重视': 2,
            '追求': 2, '坚持': 2, '核心': 2, '本质': 2
        }

        value_contexts = []

        for dimension, text in research_data.items():
            for keyword, weight in value_keywords.items():
                if keyword in text:
                    # 提取上下文
                    matches = re.finditer(rf'.{{30}}{keyword}.{{30}}', text)
                    for match in matches:
                        context = match.group(0)
                        value_contexts.append({
                            'keyword': keyword,
                            'context': context,
                            'weight': weight,
                            'source': dimension
                        })

        # 按权重排序
        value_contexts.sort(key=lambda x: x['weight'], reverse=True)

        # 提取核心价值观
        for vc in value_contexts[:5]:
            values.append({
                'value': vc['keyword'],
                'context': vc['context'][:100],
                'source': vc['source'],
                'importance': vc['weight']
            })

        return values

    def _extract_toolkit_advanced(self, research_data: Dict) -> List[Dict]:
        """高级工具箱提取"""

        tools = []

        tool_patterns = [
            r'(\w+)\s*[:：]\s*工具',
            r'使用?(\w+)(?:工具|方法|技巧)',
            r'(\w+)(?:工具|Tool|Method)',
            r'应用\s*(\w+)(?:框架|模型)'
        ]

        for dimension, text in research_data.items():
            for pattern in tool_patterns:
                matches = re.finditer(pattern, text)
                for match in matches:
                    tool_name = match.group(1).strip()
                    if len(tool_name) > 1:
                        # 提取工具描述
                        description = self._extract_tool_description(tool_name, text)

                        tools.append({
                            'name': tool_name,
                            'description': description,
                            'source': dimension
                        })

        # 去重
        seen = set()
        unique_tools = []
        for tool in tools:
            tool_key = tool['name'].lower()
            if tool_key not in seen:
                seen.add(tool_key)
                unique_tools.append(tool)

        return unique_tools[:10]

    def _extract_tool_description(self, tool_name: str, text: str) -> str:
        """提取工具描述"""

        pattern = rf'{tool_name}\s*[:：]\s*([^.。]+)'
        match = re.search(pattern, text)
        if match:
            return match.group(1).strip()

        return f"{tool_name}工具"

    def _extract_internal_tensions_advanced(self, research_data: Dict) -> List[Dict]:
        """高级内在张力提取"""

        tensions = []

        # 张力关键词和强度
        tension_keywords = {
            '矛盾': 3, '冲突': 3, '不一致': 2, '悖论': 3,
            '对立': 2, '两难': 2, '困境': 2, '矛盾'
        }

        for dimension, text in research_data.items():
            for keyword, strength in tension_keywords.items():
                if keyword in text:
                    # 提取上下文
                    matches = re.finditer(rf'.{{50}}{keyword}.{{50}}', text)
                    for match in matches:
                        context = match.group(0)
                        tensions.append({
                            'tension': keyword,
                            'strength': strength,
                            'context': context[:150],
                            'source': dimension
                        })

        # 按强度排序
        tensions.sort(key=lambda x: x['strength'], reverse=True)

        return tensions[:5]

    def _extract_honest_boundaries_advanced(self, research_data: Dict) -> List[Dict]:
        """高级诚实边界提取"""

        boundaries = []

        # 边界关键词
        boundary_keywords = {
            '局限': 3, '不能': 2, '做不到': 3, '不擅长': 2,
            '无法': 2, '难以': 2, '边界': 3, '范围': 1
        }

        for dimension, text in research_data.items():
            for keyword, severity in boundary_keywords.items():
                if keyword in text:
                    # 提取上下文
                    matches = re.finditer(rf'.{{50}}{keyword}.{{50}}', text)
                    for match in matches:
                        context = match.group(0)
                        boundaries.append({
                            'boundary': keyword,
                            'severity': severity,
                            'context': context[:150],
                            'source': dimension
                        })

        # 按严重程度排序
        boundaries.sort(key=lambda x: x['severity'], reverse=True)

        return boundaries[:5]

    def _validate_mental_models_advanced(self, models: List[Dict],
                                         research_data: Dict) -> List[Dict]:
        """高级心智模型验证 - 四维验证 + 一致性检查"""

        validated_models = []

        for model in models:
            model_name = model.get('name', '')

            # 四维验证
            scores = {
                'cross_domain_reproducibility': self._validate_cross_domain_advanced(
                    model_name,
                    research_data
                ),
                'generative_power': self._validate_generative_power_advanced(
                    model_name,
                    research_data
                ),
                'exclusivity': self._validate_exclusivity_advanced(
                    model_name,
                    research_data
                ),
                'testability': self._validate_testability_advanced(
                    model_name,
                    research_data
                )
            }

            # 计算总分
            total_score = sum(
                scores[criterion] * self.VALIDATION_CRITERIA[criterion]['weight']
                for criterion in scores
            )

            # 一致性检查
            consistency_score = self._check_model_consistency(model, research_data)

            validated_model = {
                **model,
                'validation': {
                    'scores': scores,
                    'total_score': total_score,
                    'passed': total_score >= self.PASSING_SCORE,
                    'consistency_score': consistency_score,
                    'details': self._generate_validation_details(scores, total_score)
                }
            }

            validated_models.append(validated_model)

        return validated_models

    def _validate_cross_domain_advanced(self, model_name: str, research_data: Dict) -> int:
        """高级跨域验证"""

        appearances = []
        domain_count = set()

        for dimension, text in research_data.items():
            if model_name in text:
                appearances.append(dimension)
                # 识别领域
                for domain, keywords in self.DOMAIN_KEYWORDS.items():
                    if any(kw in text for kw in keywords):
                        domain_count.add(domain)

        domain_count = len(domain_count)

        if domain_count >= 2:
            return self.VALIDATION_CRITERIA['cross_domain_reproducibility']['pass_score']
        elif domain_count == 1:
            return self.VALIDATION_CRITERIA['cross_domain_reproducibility']['partial_score']
        else:
            return self.VALIDATION_CRITERIA['cross_domain_reproducibility']['fail_score']

    def _validate_generative_power_advanced(self, model_name: str, research_data: Dict) -> int:
        """高级生成力验证"""

        # 检查应用场景数量
        application_count = 0

        for text in research_data.values():
            # 寻找"应用"相关上下文
            matches = re.finditer(rf'{model_name}.{{0,30}}(?:应用|案例|适用)', text)
            application_count += len(list(matches))

        if application_count >= 2:
            return self.VALIDATION_CRITERIA['generative_power']['pass_score']
        elif application_count == 1:
            return self.VALIDATION_CRITERIA['generative_power']['partial_score']
        else:
            return self.VALIDATION_CRITERIA['generative_power']['fail_score']

    def _validate_exclusivity_advanced(self, model_name: str, research_data: Dict) -> int:
        """高级排他性验证"""

        # 检查是否是通用概念
        generic_terms = ['理论', '概念', '思想', '观念']

        for term in generic_terms:
            if model_name.endswith(term):
                return self.VALIDATION_CRITERIA['exclusivity']['partial_score']

        # 检查是否有独特性描述
        has_unique_description = False
        for text in research_data.values():
            if any(kw in text for kw in ['独特', '特有', '专门']):
                has_unique_description = True
                break

        if has_unique_description and len(model_name) > 2:
            return self.VALIDATION_CRITERIA['exclusivity']['pass_score']
        else:
            return self.VALIDATION_CRITERIA['exclusivity']['partial_score']

    def _validate_testability_advanced(self, model_name: str, research_data: Dict) -> int:
        """高级可测试性验证"""

        # 检查实证/证据/案例数量
        evidence_keywords = ['证据', '实证', '案例', '实验', '数据', '证明']

        evidence_count = 0
        for text in research_data.values():
            if model_name in text:
                for kw in evidence_keywords:
                    evidence_count += text.count(kw)

        if evidence_count >= 2:
            return self.VALIDATION_CRITERIA['testability']['pass_score']
        elif evidence_count == 1:
            return self.VALIDATION_CRITERIA['testability']['pass_score']  # 至少1个也给满分
        else:
            return self.VALIDATION_CRITERIA['testability']['fail_score']

    def _check_model_consistency(self, model: Dict, research_data: Dict) -> float:
        """检查模型一致性"""

        model_name = model.get('name', '')
        evidence = model.get('evidence', [])

        # 一致性得分 = 证据数量 / 维度数量
        dimension_count = len(research_data)
        evidence_count = len(evidence)

        consistency = evidence_count / dimension_count if dimension_count > 0 else 0

        return round(min(consistency, 1.0), 2)

    def _generate_validation_details(self, scores: Dict, total_score: int) -> Dict:
        """生成验证详情"""

        details = {}
        for criterion, score in scores.items():
            criterion_info = self.VALIDATION_CRITERIA[criterion]
            details[criterion] = {
                'score': score,
                'weight': criterion_info['weight'],
                'weighted_score': score * criterion_info['weight'],
                'description': criterion_info['description'],
                'threshold': criterion_info['threshold']
            }

        details['total'] = {
            'score': total_score,
            'passing_line': self.PASSING_SCORE,
            'passed': total_score >= self.PASSING_SCORE
        }

        return details

    def _generate_framework_summary_advanced(self, framework: Dict) -> Dict:
        """生成高级框架总结"""

        validated_models = framework.get('validated_models', [])
        passed_models = [m for m in validated_models if m.get('validation', {}).get('passed')]

        # 计算平均验证分数
        avg_score = 0
        if validated_models:
            avg_score = sum(m['validation']['total_score'] for m in validated_models) / len(validated_models)

        return {
            'total_mental_models': len(validated_models),
            'validated_models': len(passed_models),
            'validation_rate': f"{len(passed_models) / len(validated_models) * 100:.0f}%" if validated_models else "0%",
            'average_score': round(avg_score, 1),
            'total_decision_heuristics': len(framework.get('decision_heuristics', [])),
            'total_values': len(framework.get('values', [])),
            'total_tools': len(framework.get('toolkit', [])),
            'total_tensions': len(framework.get('internal_tensions', [])),
            'total_boundaries': len(framework.get('honest_boundaries', [])),
            'framework_quality': self._evaluate_framework_quality(passed_models, framework)
        }

    def _evaluate_framework_quality(self, passed_models: List[Dict], framework: Dict) -> str:
        """评估框架质量"""

        passed_count = len(passed_models)
        heuristic_count = len(framework.get('decision_heuristics', []))
        tension_count = len(framework.get('internal_tensions', []))
        boundary_count = len(framework.get('honest_boundaries', []))

        # 质量评分
        quality_score = 0
        quality_score += passed_count * 3
        quality_score += min(heuristic_count, 10) * 0.5
        quality_score += min(tension_count, 5) * 1
        quality_score += min(boundary_count, 5) * 1.5

        if quality_score >= 20:
            return 'high'
        elif quality_score >= 12:
            return 'medium'
        else:
            return 'low'


def main():
    import argparse

    parser = argparse.ArgumentParser(description='框架提取（高级版）')
    parser.add_argument('--research-dir', type=str, required=True,
                       help='调研数据目录')
    parser.add_argument('--target', type=str, required=True,
                       help='目标（人名/主题）')
    parser.add_argument('--output', type=str, required=True,
                       help='输出JSON文件路径')

    args = parser.parse_args()

    extractor = FrameworkExtractor()

    # 提取框架
    framework = extractor.extract_framework(args.research_dir, args.target)

    # 保存结果
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(framework, f, ensure_ascii=False, indent=2)

    print(f"框架提取完成，结果保存到: {args.output}")
    print("\n=== 框架总结 ===")
    print(json.dumps(framework['summary'], ensure_ascii=False, indent=2))
    print("\n=== 验证通过的心智模型 ===")
    for model in framework['validated_models']:
        if model.get('validation', {}).get('passed'):
            print(f"- {model['name']} (分数: {model['validation']['total_score']})")


if __name__ == '__main__':
    main()


path: scripts/evolution_tracker.py
content: #!/usr/bin/env python3
"""
演化追踪：人格演化的动态追踪系统
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List
from datetime import datetime


class EvolutionTracker:
    """演化追踪器"""

    # 演化阶段
    EVOLUTION_STAGES = [
        'emergence',           # 萌发
        'differentiation',     # 分化
        'integration',         # 整合
        'transcendence',       # 超越
        'actualization'        # 实现
    ]

    # 演化指标
    EVOLUTION_METRICS = [
        'complexity',          # 复杂度
        'coherence',           # 一致性
        'adaptability',        # 适应性
        'mastery',             # 掌握度
        'integration_level'    # 整合水平
    ]

    def __init__(self):
        self.evolution_history = []
        self.milestones = {}

    def track_evolution(self, base_state: Dict,
                       new_state: Dict,
                       timestamp: str = None) -> Dict:
        """追踪演化状态"""

        if timestamp is None:
            timestamp = str(datetime.now())

        evolution_record = {
            'timestamp': timestamp,
            'base_state': self._extract_signature(base_state),
            'new_state': self._extract_signature(new_state),
            'changes': self._analyze_changes(base_state, new_state),
            'metrics': self._calculate_evolution_metrics(base_state, new_state),
            'stage': self._determine_evolution_stage(new_state),
            'insights': self._generate_evolution_insights(base_state, new_state)
        }

        self.evolution_history.append(evolution_record)

        return evolution_record

    def _extract_signature(self, state: Dict) -> Dict:
        """提取状态签名"""

        signature = {
            'overall_score': 0.0,
            'dimensional_scores': {},
            'axis_positions': {},
            'path_progress': {}
        }

        # 提取整体分数
        if 'integrated_profile' in state:
            signature['overall_score'] = state['integrated_profile'].get('integration_level', 0.5)

        # 提取维度分数
        if 'overall_signature' in state:
            signature['overall_score'] = state['overall_signature'].get('composite_score', 0.5)

        # 提取路径进展
        if 'path_progressions' in state:
            for path_name, progression in state['path_progressions'].items():
                total_nodes = progression.get('total_nodes', 1)
                completed_nodes = progression.get('completed_nodes', 0)
                signature['path_progress'][path_name] = completed_nodes / total_nodes

        return signature

    def _analyze_changes(self, base_state: Dict, new_state: Dict) -> Dict:
        """分析状态变化"""

        base_sig = self._extract_signature(base_state)
        new_sig = self._extract_signature(new_state)

        changes = {
            'overall_delta': new_sig['overall_score'] - base_sig['overall_score'],
            'dimensional_deltas': {},
            'axis_shifts': {},
            'path_advancements': {}
        }

        # 计算路径进展变化
        for path_name in set(list(base_sig['path_progress'].keys()) +
                             list(new_sig['path_progress'].keys())):

            base_progress = base_sig['path_progress'].get(path_name, 0.0)
            new_progress = new_sig['path_progress'].get(path_name, 0.0)

            changes['path_advancements'][path_name] = new_progress - base_progress

        # 识别显著变化
        changes['significant_changes'] = self._identify_significant_changes(changes)

        return changes

    def _identify_significant_changes(self, changes: Dict) -> List[str]:
        """识别显著变化"""

        significant = []

        # 整体分数显著变化
        if abs(changes['overall_delta']) > 0.1:
            direction = 'increase' if changes['overall_delta'] > 0 else 'decrease'
            significant.append(f"overall_score_{direction}")

        # 路径进展显著变化
        for path_name, advancement in changes['path_advancements'].items():
            if advancement > 0.2:
                significant.append(f"{path_name}_major_advancement")
            elif advancement < -0.1:
                significant.append(f"{path_name}_regression")

        return significant

    def _calculate_evolution_metrics(self, base_state: Dict,
                                     new_state: Dict) -> Dict:
        """计算演化指标"""

        base_sig = self._extract_signature(base_state)
        new_sig = self._extract_signature(new_state)

        metrics = {}

        # 复杂度：基于路径多样性和维度整合
        metrics['complexity'] = self._calculate_complexity(new_state)

        # 一致性：基于轴间协调性
        metrics['coherence'] = self._calculate_coherence(new_state)

        # 适应性：基于状态变化幅度
        metrics['adaptability'] = min(abs(new_sig['overall_score'] - base_sig['overall_score']) * 5, 1.0)

        # 掌握度：基于路径完成度
        metrics['mastery'] = np.mean(list(new_sig['path_progress'].values())) if new_sig['path_progress'] else 0.5

        # 整合水平
        metrics['integration_level'] = new_sig['overall_score']

        return metrics

    def _calculate_complexity(self, state: Dict) -> float:
        """计算复杂度"""
        # 简化处理：基于路径和维度数量
        complexity = 0.5

        if 'path_progressions' in state:
            complexity += len(state['path_progressions']) * 0.1

        if 'dimensions' in state:
            complexity += len(state['dimensions']) * 0.05

        return min(complexity, 1.0)

    def _calculate_coherence(self, state: Dict) -> float:
        """计算一致性"""
        # 简化处理：基于轴间张力
        coherence = 0.7

        if 'paradox_patterns' in state:
            paradox_count = len(state['paradox_patterns'])
            coherence -= paradox_count * 0.05

        return max(coherence, 0.3)

    def _determine_evolution_stage(self, state: Dict) -> str:
        """确定演化阶段"""

        metrics = self._calculate_evolution_metrics(state, state)

        mastery = metrics.get('mastery', 0.0)
        integration_level = metrics.get('integration_level', 0.0)

        if integration_level < 0.4:
            return 'emergence'
        elif integration_level < 0.6:
            return 'differentiation'
        elif integration_level < 0.75:
            return 'integration'
        elif integration_level < 0.9:
            return 'transcendence'
        else:
            return 'actualization'

    def _generate_evolution_insights(self, base_state: Dict,
                                    new_state: Dict) -> List[str]:
        """生成演化洞察"""

        insights = []

        changes = self._analyze_changes(base_state, new_state)

        # 整体变化洞察
        if changes['overall_delta'] > 0.15:
            insights.append("Significant overall growth detected")
        elif changes['overall_delta'] < -0.1:
            insights.append("Regression observed - attention needed")

        # 路径进展洞察
        for path_name, advancement in changes['path_advancements'].items():
            if advancement > 0.2:
                insights.append(f"Major advancement in {path_name}")
            elif advancement < -0.1:
                insights.append(f"Setback in {path_name}")

        # 演化阶段洞察
        new_stage = self._determine_evolution_stage(new_state)
        base_stage = self._determine_evolution_stage(base_state)

        if new_stage != base_stage:
            insights.append(f"Evolution stage transition: {base_stage} → {new_stage}")

        return insights

    def create_milestone(self, state: Dict, milestone_name: str,
                        description: str = "") -> Dict:
        """创建演化里程碑"""

        timestamp = str(datetime.now())

        milestone = {
            'milestone_id': len(self.milestones) + 1,
            'timestamp': timestamp,
            'name': milestone_name,
            'description': description,
            'state_signature': self._extract_signature(state),
            'stage': self._determine_evolution_stage(state),
            'metrics': self._calculate_evolution_metrics(state, state)
        }

        self.milestones[milestone_name] = milestone

        return milestone

    def generate_evolution_report(self) -> Dict:
        """生成演化报告"""

        if not self.evolution_history:
            return {
                'status': 'no_data',
                'message': 'No evolution history available'
            }

        report = {
            'summary': self._generate_summary(),
            'timeline': self._generate_timeline(),
            'stage_progression': self._analyze_stage_progression(),
            'metric_trends': self._analyze_metric_trends(),
            'milestones': list(self.milestones.values()),
            'recommendations': self._generate_recommendations()
        }

        return report

    def _generate_summary(self) -> Dict:
        """生成摘要"""

        if not self.evolution_history:
            return {}

        first_record = self.evolution_history[0]
        last_record = self.evolution_history[-1]

        return {
            'total_records': len(self.evolution_history),
            'time_span': {
                'start': first_record['timestamp'],
                'end': last_record['timestamp']
            },
            'overall_change': last_record['changes']['overall_delta'],
            'current_stage': last_record['stage'],
            'total_milestones': len(self.milestones)
        }

    def _generate_timeline(self) -> List[Dict]:
        """生成时间线"""
        return [
            {
                'timestamp': record['timestamp'],
                'stage': record['stage'],
                'overall_score': record['new_state']['overall_score'],
                'significant_changes': record['changes']['significant_changes']
            }
            for record in self.evolution_history
        ]

    def _analyze_stage_progression(self) -> Dict:
        """分析阶段进展"""

        stage_sequence = [record['stage'] for record in self.evolution_history]

        # 计算阶段停留时间
        stage_durations = {}
        current_stage = None
        stage_start = None

        for i, stage in enumerate(stage_sequence):
            if stage != current_stage:
                if current_stage:
                    duration = i - stage_start
                    stage_durations[current_stage] = duration

                current_stage = stage
                stage_start = i

        # 处理最后一个阶段
        if current_stage and current_stage not in stage_durations:
            stage_durations[current_stage] = len(stage_sequence) - stage_start

        return {
            'stage_sequence': stage_sequence,
            'stage_transitions': len(set(stage_sequence)),
            'stage_durations': stage_durations,
            'current_stage': current_stage
        }

    def _analyze_metric_trends(self) -> Dict:
        """分析指标趋势"""

        trends = {}

        for metric in self.EVOLUTION_METRICS:
            metric_values = [
                record['metrics'].get(metric, 0.0)
                for record in self.evolution_history
            ]

            if metric_values:
                trends[metric] = {
                    'initial': metric_values[0],
                    'final': metric_values[-1],
                    'change': metric_values[-1] - metric_values[0],
                    'trend': 'increasing' if metric_values[-1] > metric_values[0] else 'decreasing',
                    'volatility': np.std(metric_values) if len(metric_values) > 1 else 0.0
                }

        return trends

    def _generate_recommendations(self) -> List[str]:
        """生成建议"""

        recommendations = []

        if not self.evolution_history:
            return recommendations

        last_record = self.evolution_history[-1]
        current_stage = last_record['stage']

        # 基于当前阶段的建议
        stage_recommendations = {
            'emergence': [
                "Focus on self-awareness and exploration",
                "Experiment with different approaches",
                "Identify core strengths and interests"
            ],
            'differentiation': [
                "Develop distinct capabilities",
                "Specialize in chosen areas",
                "Build foundational skills"
            ],
            'integration': [
                "Connect different aspects of self",
                "Find synergies between strengths",
                "Create cohesive personal framework"
            ],
            'transcendence': [
                "Push beyond current boundaries",
                "Integrate higher perspectives",
                "Embrace transformative experiences"
            ],
            'actualization': [
                "Live in alignment with true self",
                "Share unique contributions",
                "Mentor and guide others"
            ]
        }

        recommendations.extend(stage_recommendations.get(current_stage, []))

        # 基于趋势的建议
        metric_trends = self._analyze_metric_trends()

        for metric, trend in metric_trends.items():
            if trend['change'] < -0.1:
                recommendations.append(f"Address decline in {metric}")

        return recommendations

    def export_evolution_data(self, output_path: Path):
        """导出演化数据"""

        data = {
            'evolution_history': self.evolution_history,
            'milestones': self.milestones,
            'report': self.generate_evolution_report()
        }

        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)


def main():
    import argparse

    parser = argparse.ArgumentParser(description='演化追踪')
    parser.add_argument('--base-state', type=str, required=True,
                       help='基础状态文件路径 (JSON)')
    parser.add_argument('--new-state', type=str, required=True,
                       help='新状态文件路径 (JSON)')
    parser.add_argument('--report', action='store_true',
                       help='生成演化报告')

    args = parser.parse_args()

    # 读取状态文件
    with open(args.base_state, 'r', encoding='utf-8') as f:
        base_state = json.load(f)

    with open(args.new_state, 'r', encoding='utf-8') as f:
        new_state = json.load(f)

    # 追踪演化
    tracker = EvolutionTracker()
    evolution_record = tracker.track_evolution(base_state, new_state)

    print(json.dumps(evolution_record, ensure_ascii=False, indent=2))

    # 生成报告
    if args.report:
        report = tracker.generate_evolution_report()
        print("\n=== Evolution Report ===")
        print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/paradox_miner.py
content: #!/usr/bin/env python3
"""
矛盾深度挖掘：识别和解析人格矛盾
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class ParadoxMiner:
    """矛盾挖掘器"""

    # 矛盾类型
    PARADOX_TYPES = [
        'tension_paradox',      # 张力矛盾
        'shadow_paradox',       # 阴影矛盾
        'integration_paradox',  # 整合矛盾
        'transcendence_paradox' # 超越矛盾
    ]

    # 常见矛盾模式
    COMMON_PARADOXES = {
        'autonomy_vs_connection': '自主性与连接性的矛盾',
        'stability_vs_growth': '稳定性与成长的矛盾',
        'authenticity_vs_adaptation': '真实性与适应性的矛盾',
        'idealism_vs_pragmatism': '理想主义与实用主义的矛盾',
        'expression_vs_privacy': '表达与隐私的矛盾'
    }

    def __init__(self):
        self.paradox_database = {}

    def mine_paradoxes(self, personality_model: Dict,
                      scan_result: Dict,
                      axis_analysis: Dict) -> Dict:
        """挖掘人格矛盾"""

        paradox_result = {
            'identified_paradoxes': [],
            'paradox_depth': {},
            'paradox_impact': {},
            'paradox_integrations': [],
            'paradox_recommendations': []
        }

        # 从扫描结果中识别矛盾
        scan_paradoxes = self._mine_scan_paradoxes(scan_result)
        paradox_result['identified_paradoxes'].extend(scan_paradoxes)

        # 从轴分析中识别矛盾
        axis_paradoxes = self._mine_axis_paradoxes(axis_analysis)
        paradox_result['identified_paradoxes'].extend(axis_paradoxes)

        # 从人格模型中识别矛盾
        model_paradoxes = self._mine_model_paradoxes(personality_model)
        paradox_result['identified_paradoxes'].extend(model_paradoxes)

        # 分析矛盾深度
        for paradox in paradox_result['identified_paradoxes']:
            paradox_id = paradox['paradox_id']
            paradox_result['paradox_depth'][paradox_id] = self._assess_paradox_depth(paradox)
            paradox_result['paradox_impact'][paradox_id] = self._assess_paradox_impact(paradox)

        # 生成矛盾整合方案
        paradox_result['paradox_integrations'] = self._generate_integrations(
            paradox_result['identified_paradoxes']
        )

        # 生成建议
        paradox_result['paradox_recommendations'] = self._generate_recommendations(
            paradox_result['identified_paradoxes'],
            paradox_result['paradox_integrations']
        )

        return paradox_result

    def _mine_scan_paradoxes(self, scan_result: Dict) -> List[Dict]:
        """从扫描结果中挖掘矛盾"""

        paradoxes = []

        if 'paradox_patterns' in scan_result:
            for pattern in scan_result['paradox_patterns']:
                paradox = {
                    'paradox_id': f"scan_{pattern['type']}",
                    'type': pattern['type'],
                    'tension': pattern.get('tension', 0.0),
                    'higher_dimension': pattern.get('higher_dimension'),
                    'lower_dimension': pattern.get('lower_dimension'),
                    'description': pattern.get('description', ''),
                    'source': 'scan'
                }

                paradoxes.append(paradox)

        return paradoxes

    def _mine_axis_paradoxes(self, axis_analysis: Dict) -> List[Dict]:
        """从轴分析中挖掘矛盾"""

        paradoxes = []

        if 'axis_interactions' in axis_analysis:
            for interaction_name, interaction in axis_analysis['axis_interactions'].items():
                if interaction.get('type') == 'tension':
                    paradox = {
                        'paradox_id': f"axis_{interaction_name}",
                        'type': 'axis_tension',
                        'tension': interaction.get('strength', 0.0),
                        'axis1': interaction.get('axis1'),
                        'axis2': interaction.get('axis2'),
                        'position1': interaction.get('position1'),
                        'position2': interaction.get('position2'),
                        'description': f"张力矛盾: {interaction.get('axis1')} vs {interaction.get('axis2')}",
                        'source': 'axis',
                        'effects': interaction.get('effects', [])
                    }

                    paradoxes.append(paradox)

        return paradoxes

    def _mine_model_paradoxes(self, personality_model: Dict) -> List[Dict]:
        """从人格模型中挖掘矛盾"""

        paradoxes = []

        # 检查层级间的矛盾
        if 'layer_interactions' in personality_model:
            for layer_name, interactions in personality_model['layer_interactions'].items():
                # 简化处理：识别潜在矛盾
                upward = interactions.get('upward_integration', [])
                downward = interactions.get('downward_integration', [])

                if upward and downward:
                    paradox = {
                        'paradox_id': f"layer_{layer_name}",
                        'type': 'layer_tension',
                        'tension': 0.6,  # 默认值
                        'layer': layer_name,
                        'upward_connections': upward,
                        'downward_connections': downward,
                        'description': f"层间张力: {layer_name}",
                        'source': 'model'
                    }

                    paradoxes.append(paradox)

        return paradoxes

    def _assess_paradox_depth(self, paradox: Dict) -> Dict:
        """评估矛盾深度"""

        depth = {
            'structural_depth': 0.0,
            'existential_depth': 0.0,
            'emotional_depth': 0.0,
            'overall_depth': 0.0
        }

        # 结构深度：基于张力和复杂性
        tension = paradox.get('tension', 0.0)
        depth['structural_depth'] = tension

        # 存在深度：基于矛盾类型
        paradox_type = paradox.get('type', '')
        if 'shadow' in paradox_type or 'existential' in paradox_type:
            depth['existential_depth'] = 0.8
        elif 'integration' in paradox_type:
            depth['existential_depth'] = 0.6
        else:
            depth['existential_depth'] = 0.4

        # 情感深度：基于来源
        source = paradox.get('source', '')
        if source == 'scan':
            depth['emotional_depth'] = 0.7
        elif source == 'axis':
            depth['emotional_depth'] = 0.5
        else:
            depth['emotional_depth'] = 0.3

        # 总体深度
        depth['overall_depth'] = np.mean([
            depth['structural_depth'],
            depth['existential_depth'],
            depth['emotional_depth']
        ])

        return depth

    def _assess_paradox_impact(self, paradox: Dict) -> Dict:
        """评估矛盾影响"""

        impact = {
            'psychological_impact': 0.0,
            'behavioral_impact': 0.0,
            'developmental_impact': 0.0,
            'overall_impact': 0.0
        }

        tension = paradox.get('tension', 0.0)

        # 心理影响
        impact['psychological_impact'] = tension * 0.8

        # 行为影响
        impact['behavioral_impact'] = tension * 0.7

        # 发展影响
        depth = self._assess_paradox_depth(paradox)
        impact['developmental_impact'] = depth['overall_depth'] * 0.6

        # 总体影响
        impact['overall_impact'] = np.mean([
            impact['psychological_impact'],
            impact['behavioral_impact'],
            impact['developmental_impact']
        ])

        return impact

    def _generate_integrations(self, paradoxes: List[Dict]) -> List[Dict]:
        """生成矛盾整合方案"""

        integrations = []

        for paradox in paradoxes:
            paradox_id = paradox['paradox_id']

            integration = {
                'paradox_id': paradox_id,
                'integration_strategy': self._determine_integration_strategy(paradox),
                'integration_approaches': self._generate_integration_approaches(paradox),
                'integration_potential': self._assess_integration_potential(paradox)
            }

            integrations.append(integration)

        return integrations

    def _determine_integration_strategy(self, paradox: Dict) -> str:
        """确定整合策略"""

        tension = paradox.get('tension', 0.0)

        if tension > 0.8:
            return 'transcendence'
        elif tension > 0.6:
            return 'integration'
        elif tension > 0.4:
            return 'balancing'
        else:
            return 'acknowledgment'

    def _generate_integration_approaches(self, paradox: Dict) -> List[str]:
        """生成整合方法"""

        strategy = self._determine_integration_strategy(paradox)

        approaches_map = {
            'transcendence': [
                "Embrace both poles as complementary aspects",
                "Find higher perspective that transcends duality",
                "Cultivate paradoxical thinking"
            ],
            'integration': [
                "Create synergistic relationship between poles",
                "Identify context where each pole is valuable",
                "Develop dynamic balance based on situation"
            ],
            'balancing': [
                "Maintain equilibrium between poles",
                "Monitor for dominance patterns",
                "Practice conscious shifting"
            ],
            'acknowledgment': [
                "Recognize the existence of tension",
                "Observe patterns without judgment",
                "Allow natural unfolding"
            ]
        }

        return approaches_map.get(strategy, [])

    def _assess_integration_potential(self, paradox: Dict) -> Dict:
        """评估整合潜力"""

        tension = paradox.get('tension', 0.0)

        potential = {
            'ease_of_integration': 1 - tension,
            'creative_potential': tension * 0.8,
            'transformation_potential': tension * 0.9,
            'overall_potential': tension * 0.7
        }

        return potential

    def _generate_recommendations(self, paradoxes: List[Dict],
                                  integrations: List[Dict]) -> List[str]:
        """生成建议"""

        recommendations = []

        # 识别最高影响力的矛盾
        sorted_paradoxes = sorted(
            paradoxes,
            key=lambda p: self._assess_paradox_impact(p)['overall_impact'],
            reverse=True
        )

        if sorted_paradoxes:
            top_paradox = sorted_paradoxes[0]
            paradox_id = top_paradox['paradox_id']

            # 找到对应的整合方案
            integration = next(
                (i for i in integrations if i['paradox_id'] == paradox_id),
                None
            )

            if integration:
                recommendations.append(
                    f"Primary focus: {integration['integration_strategy']} of {top_paradox['type']}"
                )

                for approach in integration['integration_approaches']:
                    recommendations.append(f"  - {approach}")

        # 一般建议
        recommendations.extend([
            "Practice self-observation of paradox patterns",
            "Cultivate tolerance for internal contradictions",
            "Seek contexts where paradoxes can be expressed"
        ])

        return recommendations

    def generate_paradox_report(self, paradox_result: Dict) -> str:
        """生成矛盾报告"""

        report_lines = [
            "=== 人格矛盾深度分析报告 ===\n",
            "识别到的矛盾："
        ]

        for paradox in paradox_result['identified_paradoxes']:
            paradox_id = paradox['paradox_id']
            depth = paradox_result['paradox_depth'][paradox_id]
            impact = paradox_result['paradox_impact'][paradox_id]

            report_lines.append(f"\n{paradox_id}:")
            report_lines.append(f"  类型: {paradox['type']}")
            report_lines.append(f"  描述: {paradox['description']}")
            report_lines.append(f"  深度: {depth['overall_depth']:.2f}")
            report_lines.append(f"  影响: {impact['overall_impact']:.2f}")

        report_lines.append("\n整合方案：")

        for integration in paradox_result['paradox_integrations']:
            paradox_id = integration['paradox_id']
            report_lines.append(f"\n{paradox_id}:")
            report_lines.append(f"  策略: {integration['integration_strategy']}")
            report_lines.append(f"  潜力: {integration['integration_potential']['overall_potential']:.2f}")
            report_lines.append(f"  方法:")
            for approach in integration['integration_approaches']:
                report_lines.append(f"    - {approach}")

        report_lines.append("\n建议：")

        for rec in paradox_result['paradox_recommendations']:
            report_lines.append(f"- {rec}")

        return "\n".join(report_lines)

    def create_paradox_journal(self, paradox_result: Dict,
                              output_path: Path):
        """创建矛盾日志"""

        journal_data = {
            'paradoxes': paradox_result['identified_paradoxes'],
            'depth_analysis': paradox_result['paradox_depth'],
            'impact_analysis': paradox_result['paradox_impact'],
            'integrations': paradox_result['paradox_integrations'],
            'recommendations': paradox_result['paradox_recommendations'],
            'created_at': str(np.datetime64('now'))
        }

        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(journal_data, f, ensure_ascii=False, indent=2)


def main():
    import argparse

    parser = argparse.ArgumentParser(description='矛盾深度挖掘')
    parser.add_argument('--model', type=str, required=True,
                       help='人格模型文件路径 (JSON)')
    parser.add_argument('--scan', type=str, required=True,
                       help='扫描结果文件路径 (JSON)')
    parser.add_argument('--axis', type=str, required=True,
                       help='轴分析文件路径 (JSON)')

    args = parser.parse_args()

    # 读取输入文件
    with open(args.model, 'r', encoding='utf-8') as f:
        personality_model = json.load(f)

    with open(args.scan, 'r', encoding='utf-8') as f:
        scan_result = json.load(f)

    with open(args.axis, 'r', encoding='utf-8') as f:
        axis_analysis = json.load(f)

    # 挖掘矛盾
    miner = ParadoxMiner()
    paradox_result = miner.mine_paradoxes(personality_model, scan_result, axis_analysis)

    # 输出报告
    report = miner.generate_paradox_report(paradox_result)
    print(report)

    # 输出JSON结果
    print("\n=== JSON 结果 ===")
    print(json.dumps(paradox_result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/holographic_scanner.py
content: #!/usr/bin/env python3
"""
8维全息扫描：360度人格评估
"""

import json
import numpy as np
from pathlib import Path
from typing import Dict, List


class HolographicScanner:
    """8维全息扫描器"""

    # 8个维度定义
    DIMENSIONS = [
        'cognitive',      # 认知维度
        'emotional',      # 情感维度
        'behavioral',     # 行为维度
        'social',         # 社交维度
        'creative',       # 创造维度
        'spiritual',      # 灵性维度
        'practical',      # 实践维度
        'shadow'          # 阴影维度
    ]

    def __init__(self):
        self.scan_results = {}

    def scan_profile(self, profile_data: Dict, zodiac_sign: str) -> Dict:
        """执行全息扫描"""

        scan_result = {
            'zodiac_sign': zodiac_sign,
            'timestamp': str(np.datetime64('now')),
            'dimensions': {}
        }

        # 扫描每个维度
        for dimension in self.DIMENSIONS:
            scan_result['dimensions'][dimension] = self._scan_dimension(
                dimension,
                profile_data,
                zodiac_sign
            )

        # 计算总体特征
        scan_result['overall_signature'] = self._calculate_overall_signature(
            scan_result['dimensions']
        )

        # 识别矛盾模式
        scan_result['paradox_patterns'] = self._identify_paradoxes(
            scan_result['dimensions']
        )

        # 识别核心优势
        scan_result['core_strengths'] = self._identify_strengths(
            scan_result['dimensions']
        )

        # 识别潜在盲区
        scan_result['blind_spots'] = self._identify_blind_spots(
            scan_result['dimensions']
        )

        return scan_result

    def _scan_dimension(self, dimension: str, profile_data: Dict,
                        zodiac_sign: str) -> Dict:
        """扫描单个维度"""

        # 模拟扫描逻辑（实际需要更复杂的分析）
        scores = self._generate_dimension_scores(dimension, zodiac_sign)

        return {
            'dimension': dimension,
            'scores': scores,
            'primary_traits': self._extract_primary_traits(dimension, scores),
            'developmental_level': self._assess_developmental_level(scores),
            'integration_degree': self._assess_integration_degree(scores)
        }

    def _generate_dimension_scores(self, dimension: str,
                                   zodiac_sign: str) -> Dict:
        """生成维度分数（模拟）"""
        # 使用随机种子确保相同输入产生相同输出
        np.random.seed(hash(f"{dimension}_{zodiac_sign}") % 2**32)

        scores = {
            'raw_score': np.random.uniform(5, 10),
            'normalized_score': 0,  # 稍后计算
            'stability': np.random.uniform(0.6, 0.95),
            'flexibility': np.random.uniform(0.5, 0.9)
        }

        # 归一化到0-1
        scores['normalized_score'] = (scores['raw_score'] - 5) / 5

        return scores

    def _extract_primary_traits(self, dimension: str,
                                scores: Dict) -> List[str]:
        """提取主要特征"""

        trait_libraries = {
            'cognitive': ['逻辑思维', '直觉感知', '分析能力', '综合整合'],
            'emotional': ['情感深度', '情感表达', '情绪调节', '共情能力'],
            'behavioral': ['行动力', '执行力', '适应性', '稳定性'],
            'social': ['人际敏感', '沟通表达', '团队协作', '领导能力'],
            'creative': ['想象力', '创新性', '原创性', '艺术性'],
            'spiritual': ['意义感', '超越性', '整合性', '直觉'],
            'practical': ['实用性', '效率', '规划能力', '执行细节'],
            'shadow': ['潜在恐惧', '防御机制', '未整合部分', '矛盾冲突']
        }

        traits = trait_libraries.get(dimension, [])
        # 选择前2-3个
        return traits[:2]

    def _assess_developmental_level(self, scores: Dict) -> str:
        """评估发展水平"""
        raw_score = scores['raw_score']

        if raw_score >= 9:
            return 'excellent'
        elif raw_score >= 8:
            return 'advanced'
        elif raw_score >= 7:
            return 'proficient'
        elif raw_score >= 6:
            return 'developing'
        else:
            return 'emerging'

    def _assess_integration_degree(self, scores: Dict) -> float:
        """评估整合程度"""
        # 结合稳定性和灵活性
        stability = scores['stability']
        flexibility = scores['flexibility']
        return (stability + flexibility) / 2

    def _calculate_overall_signature(self, dimensions: Dict) -> Dict:
        """计算总体特征"""

        # 收集所有维度的分数
        raw_scores = [
            dim_info['scores']['raw_score']
            for dim_info in dimensions.values()
        ]

        # 计算统计特征
        signature = {
            'mean': np.mean(raw_scores),
            'std': np.std(raw_scores),
            'max': np.max(raw_scores),
            'min': np.min(raw_scores),
            'range': np.ptp(raw_scores)
        }

        # 计算综合得分
        signature['composite_score'] = np.mean([
            dim_info['scores']['normalized_score']
            for dim_info in dimensions.values()
        ])

        # 确定主要类型
        signature['dominant_dimensions'] = self._identify_dominant_dimensions(
            dimensions
        )

        return signature

    def _identify_dominant_dimensions(self, dimensions: Dict) -> List[str]:
        """识别主导维度"""
        sorted_dims = sorted(
            dimensions.items(),
            key=lambda x: x[1]['scores']['raw_score'],
            reverse=True
        )
        return [dim_name for dim_name, _ in sorted_dims[:3]]

    def _identify_paradoxes(self, dimensions: Dict) -> List[Dict]:
        """识别矛盾模式"""

        paradoxes = []

        # 检查对立维度的张力
        paradox_pairs = [
            ('cognitive', 'emotional'),
            ('creative', 'practical'),
            ('social', 'shadow'),
            ('spiritual', 'practical')
        ]

        for dim1, dim2 in paradox_pairs:
            if dim1 in dimensions and dim2 in dimensions:
                score1 = dimensions[dim1]['scores']['raw_score']
                score2 = dimensions[dim2]['scores']['raw_score']
                tension = abs(score1 - score2)

                if tension > 3:
                    paradoxes.append({
                        'type': f"{dim1}_vs_{dim2}",
                        'tension': tension,
                        'higher_dimension': dim1 if score1 > score2 else dim2,
                        'lower_dimension': dim1 if score1 < score2 else dim2,
                        'description': f"{dim1}与{dim2}之间存在显著张力"
                    })

        return paradoxes

    def _identify_strengths(self, dimensions: Dict) -> List[Dict]:
        """识别核心优势"""
        strengths = []

        for dim_name, dim_info in dimensions.items():
            raw_score = dim_info['scores']['raw_score']
            if raw_score >= 8:
                strengths.append({
                    'dimension': dim_name,
                    'score': raw_score,
                    'level': dim_info['developmental_level'],
                    'primary_traits': dim_info['primary_traits']
                })

        return strengths

    def _identify_blind_spots(self, dimensions: Dict) -> List[Dict]:
        """识别潜在盲区"""
        blind_spots = []

        for dim_name, dim_info in dimensions.items():
            raw_score = dim_info['scores']['raw_score']
            if raw_score <= 6:
                blind_spots.append({
                    'dimension': dim_name,
                    'score': raw_score,
                    'level': dim_info['developmental_level'],
                    'suggestion': f"需要强化{dim_name}维度的能力"
                })

        return blind_spots


def main():
    import argparse

    parser = argparse.ArgumentParser(description='8维全息扫描')
    parser.add_argument('--profile', type=str, required=True,
                       help='配置文件路径 (JSON)')
    parser.add_argument('--zodiac', type=str, required=True,
                       help='星座名称')

    args = parser.parse_args()

    # 读取配置文件
    profile_path = Path(args.profile)
    with open(profile_path, 'r', encoding='utf-8') as f:
        profile_data = json.load(f)

    # 执行扫描
    scanner = HolographicScanner()
    result = scanner.scan_profile(profile_data, args.zodiac)

    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/demand_diagnostic.py
content: #!/usr/bin/env python3
"""
需求诊断系统：从模糊需求推荐人物/主题
"""

import json
from typing import Dict, List


class DemandDiagnostic:
    """需求诊断器"""

    # 需求维度映射
    DEMAND_DIMENSIONS = {
        'decision': {
            'keywords': ['决策', '判断', '选择', '做决定', 'decision', 'choice'],
            'candidates': ['charlie-munger', 'daniel-kahneman', 'ray-dalio'],
            'themes': ['decision-making', 'probabilistic-thinking', 'mental-models']
        },
        'expression': {
            'keywords': ['表达', '写作', '说话', '演讲', 'communication', 'writing'],
            'candidates': ['richard-feynman', 'george-orwell', 'yuval-noah-harari'],
            'themes': ['writing', 'storytelling', 'public-speaking']
        },
        'startup': {
            'keywords': ['创业', '产品', '商业模式', 'startup', 'business'],
            'candidates': ['paul-graham', 'elad-gil', 'peter-thiel'],
            'themes': ['startup', 'product-market-fit', 'entrepreneurship']
        },
        'teaching': {
            'keywords': ['教学', '传播', '讲课', 'teaching', 'education'],
            'candidates': ['richard-feynman', 'joshua-waitzkin'],
            'themes': ['teaching', 'knowledge-transfer', 'learning']
        },
        'critical_thinking': {
            'keywords': ['批判', '识别', '不靠谱', 'critical', 'skeptic'],
            'candidates': ['charlie-munger', 'daniel-kahneman', 'michael-shermer'],
            'themes': ['critical-thinking', 'cognitive-biases', 'skepticism']
        },
        'creativity': {
            'keywords': ['创作', '内容', '视频', '流量', 'creativity', 'content'],
            'candidates': ['james-clear', 'seth-godin', 'ryan-holiday'],
            'themes': ['creativity', 'content-creation', 'attention-economy']
        },
        'life_strategy': {
            'keywords': ['职业', '人生', '方向', 'career', 'life'],
            'candidates': ['naval-ravikant', 'tim-ferriss', 'cal-newport'],
            'themes': ['life-strategy', 'career-planning', 'productivity']
        },
        'risk': {
            'keywords': ['风险', '不确定性', '投资', 'risk', 'uncertainty'],
            'candidates': ['nasim-taleb', 'howard-marks', 'michael-mauboussin'],
            'themes': ['risk-management', 'antifragility', 'investing']
        },
        'design': {
            'keywords': ['设计', '产品', '用户体验', 'design', 'ux', 'product'],
            'candidates': ['don-norman', 'steve-jobs', 'dieter-rams'],
            'themes': ['design-thinking', 'minimalism', 'product-design']
        },
        'humor': {
            'keywords': ['幽默', '有趣', '表达力', 'humor', 'expression'],
            'candidates': ['david-sedaris', 'conan-obrien', 'john-mulaney'],
            'themes': ['humor', 'wit', 'satire']
        }
    }

    # 候选人物/主题数据库
    CANDIDATE_DATABASE = {
        'charlie-munger': {
            'name': '查理·芒格',
            'core_lens': '多元思维模型 + 逆向思考',
            'why_suitable': '擅长用跨学科思维模型做决策，特别适合复杂商业判断',
            'limitations': '过于理性，可能忽略情感因素；需要大量背景知识',
            'type': 'human'
        },
        'richard-feynman': {
            'name': '理查德·费曼',
            'core_lens': '第一性原理 + 费曼技巧',
            'why_suitable': '擅长将复杂概念简化为可理解的形式',
            'limitations': '过于强调简化，可能丢失细节；适合教学但未必适合复杂决策',
            'type': 'human'
        },
        'naval-ravikant': {
            'name': '纳瓦尔',
            'core_lens': '杠杆思维 + 长期主义',
            'why_suitable': '现代财富和幸福的哲学框架，适合职业和人生规划',
            'limitations': '过于理想化，实际执行难度大；更适合战略而非具体操作',
            'type': 'human'
        },
        'nasim-taleb': {
            'name': '纳西姆·塔勒布',
            'core_lens': '反脆弱 + 凸性策略',
            'why_suitable': '应对不确定性和黑天鹅事件的顶级策略',
            'limitations': '过于激进，不适合保守决策；需要高度自律',
            'type': 'human'
        },
        'paul-graham': {
            'name': '保罗·格雷厄姆',
            'core_lens': '第一性原理 + 创业智慧',
            'why_suitable': '创业和产品思维的权威，适合早期创业者',
            'limitations': '过于专注早期创业，不适合成熟企业；需要技术背景',
            'type': 'human'
        },
        # 主题型候选
        'decision-making': {
            'name': '决策科学',
            'core_lens': '概率思维 + 贝叶斯更新',
            'why_suitable': '系统性的决策方法论，融合心理学和经济学',
            'limitations': '过于理性化，实际应用需要适应；不适合快速直觉决策',
            'type': 'theme'
        },
        'antifragility': {
            'name': '反脆弱系统',
            'core_lens': '从波动中获益 + 杠杆选择',
            'why_suitable': '应对不确定性系统的设计原则',
            'limitations': '需要高度自律和长期视角；不适合所有情境',
            'type': 'theme'
        },
        'minimalism': {
            'name': '极简主义',
            'core_lens': '少即是多 + 约束即创意',
            'why_suitable': '设计和产品思维的核心原则',
            'limitations': '可能导致过度简化；不适合需要复杂性的情境',
            'type': 'theme'
        }
    }

    def __init__(self):
        self.diagnostic_history = []

    def diagnose_demand(self, user_input: str) -> Dict:
        """诊断用户需求并推荐候选"""

        # Step 1: 识别需求维度
        dimensions = self._identify_dimensions(user_input)

        # Step 2: 评估是否需要追问
        needs_clarification = self._needs_clarification(user_input, dimensions)

        if needs_clarification:
            return {
                'needs_clarification': True,
                'clarification_question': self._generate_clarification_question(dimensions)
            }

        # Step 3: 生成候选推荐
        candidates = self._generate_candidates(dimensions)

        return {
            'needs_clarification': False,
            'identified_dimensions': dimensions,
            'candidates': candidates
        }

    def _identify_dimensions(self, user_input: str) -> List[str]:
        """识别需求维度"""

        identified = []
        user_input_lower = user_input.lower()

        for dimension_name, dimension_info in self.DEMAND_DIMENSIONS.items():
            for keyword in dimension_info['keywords']:
                if keyword in user_input_lower:
                    if dimension_name not in identified:
                        identified.append(dimension_name)
                    break

        return identified

    def _needs_clarification(self, user_input: str, dimensions: List[str]) -> bool:
        """判断是否需要澄清"""

        # 如果用户表达非常模糊（少于10个字），需要澄清
        if len(user_input) < 10:
            return True

        # 如果没有识别到任何维度，需要澄清
        if not dimensions:
            return True

        # 如果识别到多个维度但用户没有明确偏好，可能需要澄清
        if len(dimensions) > 1 and '主要' not in user_input and '核心' not in user_input:
            return True

        return False

    def _generate_clarification_question(self, dimensions: List[str]) -> str:
        """生成澄清问题"""

        if not dimensions:
            return "你主要想提升哪个方面的能力？比如决策质量、表达能力、创业思维、教学能力、批判思维等？"

        if len(dimensions) == 1:
            dimension = dimensions[0]
            dimension_info = self.DEMAND_DIMENSIONS[dimension]

            # 根据维度生成具体问题
            if dimension == 'decision':
                return "你说的决策主要是哪种场景？比如商业/投资决策，还是职业/人生方向的选择？"
            elif dimension == 'startup':
                return "你是处于创业的哪个阶段？比如想法验证、产品开发、市场扩张？"
            elif dimension == 'life_strategy':
                return "你主要关注职业生涯规划，还是整体人生策略（包括财富、幸福、健康等）？"
            else:
                return f"能具体说一下你在{dimension_info['keywords'][0]}方面遇到的困惑吗？"

        # 多个维度
        dimension_names = [self.DEMAND_DIMENSIONS[d]['keywords'][0] for d in dimensions[:2]]
        return f"你提到的{dimension_names[0]}和{dimension_names[1]}，哪个是更核心的需求？"

    def _generate_candidates(self, dimensions: List[str]) -> List[Dict]:
        """生成候选推荐"""

        candidates = []

        for dimension_name in dimensions:
            dimension_info = self.DEMAND_DIMENSIONS[dimension_name]

            # 从维度获取候选
            for candidate_key in dimension_info['candidates']:
                if candidate_key in self.CANDIDATE_DATABASE:
                    candidate_info = self.CANDIDATE_DATABASE[candidate_key]

                    candidates.append({
                        'candidate_id': candidate_key,
                        'name': candidate_info['name'],
                        'core_lens': candidate_info['core_lens'],
                        'why_suitable': candidate_info['why_suitable'],
                        'limitations': candidate_info['limitations'],
                        'type': candidate_info['type'],
                        'matched_dimension': dimension_name
                    })

        # 去重
        seen = set()
        unique_candidates = []
        for candidate in candidates:
            if candidate['candidate_id'] not in seen:
                seen.add(candidate['candidate_id'])
                unique_candidates.append(candidate)

        # 限制最多3个
        return unique_candidates[:3]

    def clarify_user_response(self, original_input: str, user_response: str) -> Dict:
        """处理用户的澄清响应"""

        # 合并原始输入和响应
        combined_input = f"{original_input} {user_response}"

        # 重新诊断
        return self.diagnose_demand(combined_input)

    def check_existing_skills(self, skills_dir: str) -> List[Dict]:
        """检查已有的Skill"""

        # 简化处理，实际应该扫描目录
        existing_skills = []

        # 模拟检查结果
        return existing_skills


def main():
    import argparse

    parser = argparse.ArgumentParser(description='需求诊断')
    parser.add_argument('--input', type=str, required=True,
                       help='用户输入')
    parser.add_argument('--clarify', type=str,
                       help='用户的澄清响应（如有）')

    args = parser.parse_args()

    diagnostic = DemandDiagnostic()

    if args.clarify:
        result = diagnostic.clarify_user_response(args.input, args.clarify)
    else:
        result = diagnostic.diagnose_demand(args.input)

    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/research_orchestrator.py
content: #!/usr/bin/env python3
"""
调研编排系统：6维并行调研
"""

import json
import requests
from pathlib import Path
from typing import Dict, List
import subprocess


class ResearchOrchestrator:
    """调研编排器"""

    # 6个调研维度
    DIMENSIONS = [
        '01-writings',      # 著作与系统思考
        '02-conversations', # 长对话与即兴思考
        '03-expression-dna',# 碎片表达与风格DNA
        '04-external-views',# 他者视角与批评
        '05-decisions',     # 决策记录与行动
        '06-timeline'       # 人物时间线
    ]

    # 信息源黑名单
    BLACKLISTED_SOURCES = [
        'zhihu.com',
        'mp.weixin.qq.com',
        'weixin.qq.com'
    ]

    # 优先信息源（中文人物）
    CHINESE_PRIORITY_SOURCES = [
        'bilibili.com',     # B站视频
        'ximalaya.com',     # 喜马拉雅播客
        'dedao.cn',         # 得到
        'thepaper.cn',      # 澎湃新闻
        'caixin.com',       # 财新网
        'people.com.cn',    # 人民网
        'xinhuanet.com'     # 新华网
    ]

    def __init__(self):
        self.research_plan = {}
        self.agent_tasks = {}

    def generate_research_plan(self, os_type: str, target: str,
                               mode: str = 'network') -> Dict:
        """生成调研计划"""

        # 根据HumanOS类型调整维度优先级
        dimension_priorities = self._get_dimension_priorities(os_type)

        # 根据模式调整策略
        strategy = self._get_strategy(mode)

        # 生成调研计划
        research_plan = {
            'os_type': os_type,
            'target': target,
            'mode': mode,
            'strategy': strategy,
            'dimensions': {},
            'total_dimensions': len(self.DIMENSIONS)
        }

        # 为每个维度生成任务
        for dimension in self.DIMENSIONS:
            priority = dimension_priorities.get(dimension, 2)

            research_plan['dimensions'][dimension] = {
                'priority': priority,
                'strategy': self._get_dimension_strategy(dimension, strategy),
                'sources': self._get_dimension_sources(dimension, target, strategy),
                'output_file': f"references/research/{dimension}.md",
                'status': 'pending'
            }

        self.research_plan = research_plan

        return research_plan

    def _get_dimension_priorities(self, os_type: str) -> Dict:
        """获取维度优先级"""

        # 不同HumanOS类型的维度优先级
        priorities = {
            'human': {
                '01-writings': 3,
                '02-conversations': 3,
                '03-expression-dna': 2,
                '04-external-views': 2,
                '05-decisions': 3,
                '06-timeline': 3
            },
            'theme': {
                '01-writings': 3,
                '02-conversations': 2,
                '03-expression-dna': 2,
                '04-external-views': 3,
                '05-decisions': 2,
                '06-timeline': 2
            },
            'scenario': {
                '01-writings': 2,
                '02-conversations': 2,
                '03-expression-dna': 2,
                '04-external-views': 1,
                '05-decisions': 3,
                '06-timeline': 2
            },
            'methodology': {
                '01-writings': 3,
                '02-conversations': 1,
                '03-expression-dna': 1,
                '04-external-views': 2,
                '05-decisions': 2,
                '06-timeline': 1
            }
        }

        return priorities.get(os_type, {})

    def _get_strategy(self, mode: str) -> Dict:
        """获取调研策略"""

        strategies = {
            'network': {
                'primary_mode': 'network_search',
                'local_first': False,
                'direction': 'collect_all'
            },
            'local_priority': {
                'primary_mode': 'local_analysis',
                'local_first': True,
                'direction': 'identify_gaps'
            },
            'local_only': {
                'primary_mode': 'local_analysis',
                'local_first': True,
                'direction': 'local_only'
            }
        }

        return strategies.get(mode, strategies['network'])

    def _get_dimension_strategy(self, dimension: str,
                                 strategy: Dict) -> Dict:
        """获取维度策略"""

        dimension_strategies = {
            '01-writings': {
                'focus': 'books, articles, systematic thinking',
                'search_queries': [
                    f'{dimension} books',
                    f'{dimension} essays',
                    f'{dimension} lectures'
                ]
            },
            '02-conversations': {
                'focus': 'interviews, podcasts, dialogues',
                'search_queries': [
                    f'{dimension} interview',
                    f'{dimension} podcast',
                    f'{dimension} conversation'
                ]
            },
            '03-expression-dna': {
                'focus': 'social media, quotes, style',
                'search_queries': [
                    f'{dimension} quotes',
                    f'{dimension} twitter',
                    f'{dimension} style'
                ]
            },
            '04-external-views': {
                'focus': 'criticism, analysis, reviews',
                'search_queries': [
                    f'{dimension} analysis',
                    f'{dimension} criticism',
                    f'{dimension} review'
                ]
            },
            '05-decisions': {
                'focus': 'decision records, case studies',
                'search_queries': [
                    f'{dimension} decisions',
                    f'{dimension} case studies',
                    f'{dimension} actions'
                ]
            },
            '06-timeline': {
                'focus': 'biography, evolution, timeline',
                'search_queries': [
                    f'{dimension} biography',
                    f'{dimension} timeline',
                    f'{dimension} history'
                ]
            }
        }

        return dimension_strategies.get(dimension, {})

    def _get_dimension_sources(self, dimension: str, target: str,
                                strategy: Dict) -> List[str]:
        """获取维度信息源"""

        # 简化处理，实际应该搜索并返回具体信息源
        sources = []

        # 基于策略生成搜索查询
        dimension_strategy = self._get_dimension_strategy(dimension, strategy)

        for query in dimension_strategy.get('search_queries', []):
            search_query = f"{target} {query}"
            sources.append({
                'query': search_query,
                'type': 'search',
                'status': 'pending'
            })

        return sources

    def execute_research(self, research_plan: Dict, output_dir: str) -> Dict:
        """执行调研计划"""

        execution_result = {
            'plan_id': f"research_{hash(str(research_plan))}",
            'started_at': str(subprocess.check_output(['date'])),
            'dimensions': {},
            'summary': {}
        }

        # 创建输出目录
        output_path = Path(output_dir)
        output_path.mkdir(parents=True, exist_ok=True)

        # 执行每个维度的调研
        for dimension_name, dimension_info in research_plan['dimensions'].items():
            dimension_result = self._execute_dimension_research(
                dimension_name,
                dimension_info,
                output_dir
            )

            execution_result['dimensions'][dimension_name] = dimension_result

        # 生成总结
        execution_result['summary'] = self._generate_research_summary(
            execution_result['dimensions']
        )

        return execution_result

    def _execute_dimension_research(self, dimension_name: str,
                                     dimension_info: Dict,
                                     output_dir: str) -> Dict:
        """执行单个维度调研"""

        # 模拟调研执行
        output_file = Path(output_dir) / dimension_info['output_file']
        output_file.parent.mkdir(parents=True, exist_ok=True)

        # 生成调研内容（模拟）
        content = self._generate_research_content(
            dimension_name,
            dimension_info
        )

        # 写入文件
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(content)

        return {
            'dimension': dimension_name,
            'status': 'completed',
            'output_file': str(output_file),
            'content_length': len(content),
            'sources_analyzed': len(dimension_info.get('sources', []))
        }

    def _generate_research_content(self, dimension_name: str,
                                    dimension_info: Dict) -> str:
        """生成调研内容（模拟）"""

        content = f"""# {dimension_name.replace('-', ' ').title()}

## 研究目标
分析 {dimension_name} 维度的核心内容和特征。

## 调研来源
- 搜索查询: {', '.join([s.get('query', '') for s in dimension_info.get('sources', [])])}

## 核心发现
[调研内容将在此处填充]

## 关键洞察
[关键洞察将在此处填充]

## 信息来源
[信息来源列表]
"""

        return content

    def _generate_research_summary(self, dimensions: Dict) -> Dict:
        """生成调研总结"""

        total_dimensions = len(dimensions)
        completed_dimensions = sum(
            1 for d in dimensions.values() if d.get('status') == 'completed'
        )

        return {
            'total_dimensions': total_dimensions,
            'completed_dimensions': completed_dimensions,
            'completion_rate': completed_dimensions / total_dimensions if total_dimensions > 0 else 0,
            'total_content_length': sum(
                d.get('content_length', 0) for d in dimensions.values()
            ),
            'total_sources_analyzed': sum(
                d.get('sources_analyzed', 0) for d in dimensions.values()
            )
        }

    def check_local_sources(self, target: str, sources_dir: str) -> Dict:
        """检查本地素材"""

        sources_path = Path(sources_dir)
        local_sources = {
            'books': [],
            'transcripts': [],
            'articles': [],
            'total_files': 0
        }

        if not sources_path.exists():
            return local_sources

        # 扫描本地素材
        for category in ['books', 'transcripts', 'articles']:
            category_path = sources_path / category
            if category_path.exists():
                for file_path in category_path.glob('*'):
                    local_sources[category].append({
                        'path': str(file_path),
                        'name': file_path.name,
                        'size': file_path.stat().st_size
                    })

        local_sources['total_files'] = sum(
            len(local_sources[cat]) for cat in ['books', 'transcripts', 'articles']
        )

        return local_sources


def main():
    import argparse

    parser = argparse.ArgumentParser(description='调研编排')
    parser.add_argument('--os-type', type=str, required=True,
                       choices=['human', 'theme', 'scenario', 'methodology'],
                       help='HumanOS类型')
    parser.add_argument('--target', type=str, required=True,
                       help='调研目标（人名/主题）')
    parser.add_argument('--output-dir', type=str, default='./output',
                       help='输出目录')
    parser.add_argument('--mode', type=str, default='network',
                       choices=['network', 'local_priority', 'local_only'],
                       help='调研模式')

    args = parser.parse_args()

    orchestrator = ResearchOrchestrator()

    # 生成调研计划
    research_plan = orchestrator.generate_research_plan(
        args.os_type,
        args.target,
        args.mode
    )

    print(f"生成调研计划: {args.target}")
    print(json.dumps(research_plan, ensure_ascii=False, indent=2))

    # 执行调研
    execution_result = orchestrator.execute_research(
        research_plan,
        args.output_dir
    )

    print(f"\n执行调研: {args.target}")
    print(json.dumps(execution_result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/ultimate_generator.py
content: #!/usr/bin/env python3
"""
终极HumanOS构建引擎
整合所有子系统，生成完整的7层人格模型+路径+节点+核心轴+神经网络
"""

import sys
import json
import argparse
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any

# 导入子模块
# from zodiac_engine import ZodiacEngine
# from holographic_scanner import HolographicScanner
# from personality_modeler import PersonalityModeler
# from path_mapper import PathMapper
# from axis_analyzer import AxisAnalyzer
# from neural_network_sim import NeuralNetworkSimulator
# from evolution_tracker import EvolutionTracker
# from paradox_miner import ParadoxMiner


class UltimateHumanOSEngine:
    """终极HumanOS构建引擎"""

    def __init__(self, person_name: str, birthday: str):
        self.person_name = person_name
        self.birthday = birthday
        self.zodiac_sign = None
        self.layer_models = {}
        self.paths = {}
        self.axes = {}
        self.neural_network = {}
        self.evolution = {}
        self.paradoxes = []
        self.holographic_scan = {}

    def generate(self, output_dir: Path):
        """生成完整的HumanOS"""

        print(f"\n🚀 启动终极HumanOS构建引擎")
        print(f"👤 人物: {self.person_name}")
        print(f"🎂 生日: {self.birthday}")
        print(f"{'='*60}")

        # Step 1: 星座识别
        print(f"\n[1/11] 识别星座原型...")
        self.identify_zodiac()

        # Step 2: 性格底色加载
        print(f"[2/11] 加载性格底色...")
        self.load_personality_base()

        # Step 3: 8维全息扫描
        print(f"[3/11] 执行8维全息扫描...")
        self.holographic_scan()

        # Step 4: 构建7层人格模型
        print(f"[4/11] 构建7层人格模型...")
        self.build_7layer_model()

        # Step 5: 映射核心路径
        print(f"[5/11] 映射3条核心路径...")
        self.map_core_paths()

        # Step 6: 定位关键节点
        print(f"[6/11] 定位关键节点...")
        self.locate_key_nodes()

        # Step 7: 分析核心轴
        print(f"[7/11] 分析5个核心轴...")
        self.analyze_axes()

        # Step 8: 构建神经网络模拟
        print(f"[8/11] 构建神经网络模拟...")
        self.build_neural_network()

        # Step 9: 挖掘核心矛盾
        print(f"[9/11] 挖掘核心矛盾...")
        self.mine_paradoxes()

        # Step 10: 追踪演化路径
        print(f"[10/11] 追踪演化路径...")
        self.track_evolution()

        # Step 11: 生成HumanOS
        print(f"[11/11] 生成完整HumanOS...")
        self.generate_humanos(output_dir)

        print(f"\n✅ HumanOS构建完成！")
        print(f"📁 输出目录: {output_dir}")

    def identify_zodiac(self):
        """识别星座原型"""
        # 简化实现：根据生日月份确定星座
        month_day = self.birthday.split('-')
        if len(month_day) >= 2:
            month = int(month_day[1])

            zodiac_map = {
                1: 'capricorn', 2: 'aquarius', 3: 'pisces',
                4: 'aries', 5: 'taurus', 6: 'gemini',
                7: 'cancer', 8: 'leo', 9: 'virgo',
                10: 'libra', 11: 'scorpio', 12: 'sagittarius'
            }

            self.zodiac_sign = zodiac_map.get(month, 'unknown')
            print(f"  星座: {self.zodiac_sign.capitalize()}")

    def load_personality_base(self):
        """加载性格底色"""
        self.layer_models['layer1_zodiac'] = {
            'name': '星座原型',
            'sign': self.zodiac_sign,
            'core_drive': '根据星座原型加载',
            'cognitive_filter': '根据星座原型加载',
            'emotional_pattern': '根据星座原型加载',
            'expression_style': '根据星座原型加载',
            'contradictions': ['根据星座原型加载'],
            'evolution_path': '根据星座原型加载',
            'shadow_side': '根据星座原型加载'
        }

        self.layer_models['layer2_personality'] = {
            'name': '性格底色',
            'big_five': '待分析',
            'mbti': '待分析',
            'values': '待分析',
            'beliefs': '待分析'
        }

    def holographic_scan(self):
        """执行8维全息扫描"""
        dimensions = [
            'cross_domain', 'generative', 'exclusivity', 'testability',
            'emotional', 'paradox', 'evolution', 'social'
        ]

        self.holographic_scan = {
            'dimensions': dimensions,
            'results': {d: '待扫描' for d in dimensions}
        }

    def build_7layer_model(self):
        """构建7层人格模型"""
        layers = [
            'layer1_zodiac', 'layer2_personality', 'layer3_cognitive',
            'layer4_thinking', 'layer5_decision', 'layer6_expression', 'layer7_behavior'
        ]

        for layer in layers:
            if layer not in self.layer_models:
                self.layer_models[layer] = {
                    'name': layer,
                    'description': f'第{layer.split("layer")[1][0]}层人格',
                    'characteristics': '待分析'
                }

    def map_core_paths(self):
        """映射3条核心路径"""
        self.paths = {
            'information_flow': {
                'name': '输入-处理-输出路径',
                'nodes': ['information_receive', 'attention', 'filter', 'interpret', 'associate', 'memory', 'reasoning', 'judgment', 'expression', 'feedback']
            },
            'decision_flow': {
                'name': '感知-判断-行动路径',
                'nodes': ['problem_identify', 'situation_assess', 'risk_evaluate', 'option_generate', 'compare', 'decide', 'plan', 'execute', 'monitor', 'adjust']
            },
            'time_flow': {
                'name': '过去-现在-未来路径',
                'nodes': ['history_understand', 'experience_extract', 'present_perceive', 'opportunity_identify', 'threat_identify', 'vision_set', 'goal_set', 'strategy_make', 'action_plan', 'evolution_track']
            }
        }

    def locate_key_nodes(self):
        """定位关键节点"""
        # 节点在路径映射时已经定义
        pass

    def analyze_axes(self):
        """分析5个核心轴"""
        self.axes = {
            'rational_emotional': {
                'name': '理性-情感轴',
                'position': '待分析',
                'preference_range': '待分析',
                'mobility': '待分析',
                'extreme_cases': '待分析',
                'evolution_trend': '待分析'
            },
            'conservative_radical': {
                'name': '保守-激进轴',
                'position': '待分析',
                'preference_range': '待分析',
                'mobility': '待分析',
                'extreme_cases': '待分析',
                'evolution_trend': '待分析'
            },
            'abstract_concrete': {
                'name': '抽象-具体轴',
                'position': '待分析',
                'preference_range': '待分析',
                'mobility': '待分析',
                'extreme_cases': '待分析',
                'evolution_trend': '待分析'
            },
            'global_local': {
                'name': '全局-局部轴',
                'position': '待分析',
                'preference_range': '待分析',
                'mobility': '待分析',
                'extreme_cases': '待分析',
                'evolution_trend': '待分析'
            },
            'stable_change': {
                'name': '稳定-变化轴',
                'position': '待分析',
                'preference_range': '待分析',
                'mobility': '待分析',
                'extreme_cases': '待分析',
                'evolution_trend': '待分析'
            }
        }

    def build_neural_network(self):
        """构建神经网络模拟"""
        self.neural_network = {
            'activation_system': {
                'trigger_threshold': '待分析',
                'activation_mode': '待分析',
                'activation_intensity': '待分析',
                'activation_duration': '待分析'
            },
            'inhibition_system': {
                'inhibition_threshold': '待分析',
                'inhibition_type': '待分析',
                'inhibition_intensity': '待分析',
                'inhibition_recovery': '待分析'
            },
            'reinforcement_system': {
                'reinforcement_type': '待分析',
                'reinforcement_frequency': '待分析',
                'intensity_gain': '待分析',
                'decay_pattern': '待分析'
            },
            'memory_system': {
                'short_term_capacity': '待分析',
                'long_term_capacity': '待分析',
                'encoding_method': '待分析',
                'retrieval_method': '待分析',
                'forgetting_curve': '待分析'
            }
        }

    def mine_paradoxes(self):
        """挖掘核心矛盾"""
        self.paradoxes = [
            {'type': '内在冲突', 'description': '待挖掘'},
            {'type': '认知失调', 'description': '待挖掘'},
            {'type': '自我矛盾', 'description': '待挖掘'}
        ]

    def track_evolution(self):
        """追踪演化路径"""
        self.evolution = {
            'life_stages': '待追踪',
            'key_events': '待追踪',
            'thought_evolution': '待追踪',
            'behavior_patterns': '待追踪',
            'influence_network': '待追踪'
        }

    def generate_humanos(self, output_dir: Path):
        """生成完整HumanOS"""
        humanos = {
            'metadata': {
                'person_name': self.person_name,
                'birthday': self.birthday,
                'zodiac_sign': self.zodiac_sign,
                'generated_at': datetime.now().isoformat(),
                'version': 'Ultimate v1.0'
            },
            'layer_models': self.layer_models,
            'paths': self.paths,
            'axes': self.axes,
            'neural_network': self.neural_network,
            'holographic_scan': self.holographic_scan,
            'paradoxes': self.paradoxes,
            'evolution': self.evolution
        }

        # 保存JSON
        output_dir.mkdir(parents=True, exist_ok=True)
        humanos_file = output_dir / f"{self.person_name.lower().replace(' ', '-')}-humanos.json"

        with open(humanos_file, 'w', encoding='utf-8') as f:
            json.dump(humanos, f, ensure_ascii=False, indent=2)

        print(f"  HumanOS数据已保存: {humanos_file}")

        # 生成统计报告
        self.print_summary()

    def print_summary(self):
        """打印生成摘要"""
        print(f"\n📊 HumanOS摘要:")
        print(f"  星座原型: {self.zodiac_sign}")
        print(f"  人格层级: {len(self.layer_models)}层")
        print(f"  核心路径: {len(self.paths)}条")
        print(f"  关键节点: {sum(len(p['nodes']) for p in self.paths.values())}个")
        print(f"  核心轴: {len(self.axes)}个")
        print(f"  神经系统: 4个子系统")
        print(f"  核心矛盾: {len(self.paradoxes)}个")
        print(f"  演化追踪: 5个维度")


def main():
    parser = argparse.ArgumentParser(description='终极HumanOS构建引擎')
    parser.add_argument('--name', required=True, help='人物名称')
    parser.add_argument('--birthday', required=True, help='生日 (YYYY-MM-DD)')
    parser.add_argument('--output', default='./output', help='输出目录')

    args = parser.parse_args()

    # 创建引擎
    engine = UltimateHumanOSEngine(
        person_name=args.name,
        birthday=args.birthday
    )

    # 生成HumanOS
    output_dir = Path(args.output)
    engine.generate(output_dir)


if __name__ == '__main__':
    main()


path: scripts/os_builder.py
content: #!/usr/bin/env python3
"""
HumanOS构建器：根据框架生成HumanOS Skill
"""

import json
from pathlib import Path
from typing import Dict, List


class HumanOSBuilder:
    """HumanOS构建器"""

    # 4种HumanOS类型
    OS_TYPES = {
        'human': {
            'name': 'HumanType',
            'template': 'human-template.md',
            'description': '人物型，蒸馏特定人物的思维框架'
        },
        'theme': {
            'name': 'ThemeType',
            'template': 'theme-template.md',
            'description': '主题型，综合多人视角的主题框架'
        },
        'scenario': {
            'name': 'ScenarioType',
            'template': 'scenario-template.md',
            'description': '场景型，特定场景的决策系统'
        },
        'methodology': {
            'name': 'MethodologyType',
            'template': 'methodology-template.md',
            'description': '方法论型，完整的方法论实施框架'
        }
    }

    def __init__(self):
        self.built_os = {}

    def build_humanos(self, framework: Dict, os_type: str,
                      template_dir: str, output_file: str) -> Dict:
        """构建HumanOS"""

        # 加载模板
        template_path = Path(template_dir) / self.OS_TYPES[os_type]['template']
        if not template_path.exists():
            raise FileNotFoundError(f"模板文件不存在: {template_path}")

        with open(template_path, 'r', encoding='utf-8') as f:
            template_content = f.read()

        # 填充模板
        skill_content = self._fill_template(template_content, framework, os_type)

        # 生成Agentic Protocol
        agentic_protocol = self._generate_agentic_protocol(framework)

        # 整合到Skill内容中
        skill_content = self._integrate_agentic_protocol(skill_content, agentic_protocol)

        # 写入输出文件
        output_path = Path(output_file)
        output_path.parent.mkdir(parents=True, exist_ok=True)

        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(skill_content)

        # 生成构建结果
        build_result = {
            'os_type': os_type,
            'target': framework.get('target', ''),
            'output_file': str(output_path),
            'framework_summary': framework.get('summary', {}),
            'agentic_protocol': agentic_protocol,
            'build_status': 'success'
        }

        self.built_os = build_result

        return build_result

    def _fill_template(self, template: str, framework: Dict,
                       os_type: str) -> str:
        """填充模板"""

        # 准备替换变量
        variables = {
            'TARGET': framework.get('target', ''),
            'OS_TYPE': self.OS_TYPES[os_type]['name'],
            'DESCRIPTION': self.OS_TYPES[os_type]['description'],
            'MENTAL_MODELS': self._format_mental_models(
                framework.get('mental_models', [])
            ),
            'DECISION_HEURISTICS': self._format_decision_heuristics(
                framework.get('decision_heuristics', [])
            ),
            'EXPRESSION_DNA': self._format_expression_dna(
                framework.get('expression_dna', {})
            ),
            'VALUES': self._format_values(
                framework.get('values', [])
            ),
            'TOOLKIT': self._format_toolkit(
                framework.get('toolkit', [])
            ),
            'INTERNAL_TENSIONS': self._format_internal_tensions(
                framework.get('internal_tensions', [])
            ),
            'HONEST_BOUNDARIES': self._format_honest_boundaries(
                framework.get('honest_boundaries', [])
            )
        }

        # 替换变量
        content = template
        for var_name, var_value in variables.items():
            placeholder = f"{{{{{var_name}}}}}"
            content = content.replace(placeholder, str(var_value))

        return content

    def _format_mental_models(self, models: List[Dict]) -> str:
        """格式化心智模型"""

        formatted = []
        for model in models:
            name = model.get('name', '')
            description = model.get('description', '')
            validation = model.get('validation', {})

            # 只包含通过验证的模型
            if validation.get('passed'):
                formatted.append(f"- **{name}**: {description}")

        return '\n'.join(formatted) if formatted else '无通过验证的心智模型'

    def _format_decision_heuristics(self, heuristics: List[str]) -> str:
        """格式化决策启发式"""

        formatted = []
        for heuristic in heuristics[:10]:
            formatted.append(f"- {heuristic}")

        return '\n'.join(formatted) if formatted else '无决策启发式'

    def _format_expression_dna(self, dna: Dict) -> str:
        """格式化表达DNA"""

        formatted = []

        if dna.get('sentence_patterns'):
            formatted.append("**句式模式**:")
            for pattern in dna['sentence_patterns'][:5]:
                formatted.append(f"  - {pattern}")

        if dna.get('vocabulary'):
            formatted.append("**特色词汇**:")
            for vocab in dna['vocabulary'][:10]:
                formatted.append(f"  - {vocab}")

        if dna.get('rhythm'):
            formatted.append(f"**节奏**: {dna['rhythm']}")

        return '\n'.join(formatted) if formatted else '无表达DNA'

    def _format_values(self, values: List[str]) -> str:
        """格式化价值观"""

        formatted = []
        for value in values[:5]:
            formatted.append(f"- {value}")

        return '\n'.join(formatted) if formatted else '无价值观'

    def _format_toolkit(self, tools: List[str]) -> str:
        """格式化工具箱"""

        formatted = []
        for tool in tools[:10]:
            formatted.append(f"- {tool}")

        return '\n'.join(formatted) if formatted else '无工具'

    def _format_internal_tensions(self, tensions: List[Dict]) -> str:
        """格式化内在张力"""

        formatted = []
        for tension in tensions[:5]:
            tension_desc = tension.get('tension', '')
            description = tension.get('description', '')
            formatted.append(f"- **{tension_desc}**: {description}")

        return '\n'.join(formatted) if formatted else '无内在张力'

    def _format_honest_boundaries(self, boundaries: List[str]) -> str:
        """格式化诚实边界"""

        formatted = []
        for boundary in boundaries[:5]:
            formatted.append(f"- {boundary}")

        return '\n'.join(formatted) if formatted else '无诚实边界'

    def _generate_agentic_protocol(self, framework: Dict) -> Dict:
        """生成Agentic Protocol"""

        # 从心智模型推导研究维度
        mental_models = framework.get('mental_models', [])
        validated_models = [m for m in mental_models if m.get('validation', {}).get('passed')]

        # 生成研究步骤
        research_steps = self._generate_research_steps(validated_models)

        agentic_protocol = {
            'version': '1.0',
            'target': framework.get('target', ''),
            'description': f'{framework.get("target", "")}的研究和回答协议',
            'steps': [
                {
                    'step': 1,
                    'name': '问题分类',
                    'description': '识别用户问题的类型和维度',
                    'actions': [
                        '分析问题的领域',
                        '识别相关的决策维度',
                        '确定问题的复杂度'
                    ]
                },
                {
                    'step': 2,
                    'name': '研究',
                    'description': f'应用{framework.get("target", "")}的心智模型进行深入分析',
                    'actions': research_steps
                },
                {
                    'step': 3,
                    'name': '回答',
                    'description': '生成结构化的回答，体现独特的思维框架',
                    'actions': [
                        '使用决策启发式推导结论',
                        '体现表达DNA的风格',
                        '标注诚实边界和局限性'
                    ]
                }
            ],
            'mental_models_used': [m.get('name', '') for m in validated_models],
            'decision_heuristics_used': framework.get('decision_heuristics', [])[:5]
        }

        return agentic_protocol

    def _generate_research_steps(self, mental_models: List[Dict]) -> List[str]:
        """生成研究步骤"""

        steps = []

        # 基于心智模型生成研究步骤
        for model in mental_models:
            model_name = model.get('name', '')
            steps.append(f"应用{model_name}心智模型分析问题")

        # 添加通用步骤
        steps.extend([
            "识别问题的核心矛盾",
            "应用决策启发式进行推理",
            "评估不同方案的优劣势"
        ])

        return steps

    def _integrate_agentic_protocol(self, skill_content: str,
                                     agentic_protocol: Dict) -> str:
        """整合Agentic Protocol到Skill内容"""

        # 将Agentic Protocol转换为Markdown格式
        protocol_md = self._format_agentic_protocol(agentic_protocol)

        # 替换模板中的Agentic Protocol占位符
        skill_content = skill_content.replace('{{AGENTIC_PROTOCOL}}', protocol_md)

        return skill_content

    def _format_agentic_protocol(self, protocol: Dict) -> str:
        """格式化Agentic Protocol"""

        formatted = f"""## Agentic Protocol

{protocol.get('description', '')}

### 步骤
"""

        for step_info in protocol.get('steps', []):
            formatted += f"""
#### 步骤 {step_info['step']}: {step_info['name']}

{step_info['description']}

**行动**:
"""
            for action in step_info.get('actions', []):
                formatted += f"- {action}\n"

        formatted += f"""
### 应用心智模型
"""
        for model_name in protocol.get('mental_models_used', []):
            formatted += f"- {model_name}\n"

        formatted += f"""
### 决策启发式
"""
        for heuristic in protocol.get('decision_heuristics_used', []):
            formatted += f"- {heuristic}\n"

        return formatted


def main():
    import argparse

    parser = argparse.ArgumentParser(description='HumanOS构建器')
    parser.add_argument('--framework', type=str, required=True,
                       help='框架JSON文件路径')
    parser.add_argument('--template-dir', type=str, required=True,
                       help='模板目录')
    parser.add_argument('--os-type', type=str, required=True,
                       choices=['human', 'theme', 'scenario', 'methodology'],
                       help='HumanOS类型')
    parser.add_argument('--output', type=str, required=True,
                       help='输出SKILL.md文件路径')

    args = parser.parse_args()

    # 读取框架
    with open(args.framework, 'r', encoding='utf-8') as f:
        framework = json.load(f)

    # 构建HumanOS
    builder = HumanOSBuilder()
    result = builder.build_humanos(
        framework,
        args.os_type,
        args.template_dir,
        args.output
    )

    print(f"HumanOS构建完成: {args.output}")
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: scripts/source_analyzer.py
content: #!/usr/bin/env python3
"""
源分析器：分析素材来源质量
"""

import json
from pathlib import Path
from typing import Dict, List


class SourceAnalyzer:
    """源分析器"""

    # 来源质量评分标准
    QUALITY_STANDARDS = {
        'high_quality': {
            'score': 3,
            'description': '一手来源，权威性强',
            'examples': ['书籍', '学术论文', '官方演讲', '深度访谈']
        },
        'medium_quality': {
            'score': 2,
            'description': '二手来源，有一定权威性',
            'examples': ['分析文章', '评论', '纪录片']
        },
        'low_quality': {
            'score': 1,
            'description': '非一手来源，权威性弱',
            'examples': ['社交媒体', '论坛讨论', '网络评论']
        }
    }

    def __init__(self):
        self.analysis_results = {}

    def analyze_sources(self, sources_dir: str) -> Dict:
        """分析素材来源"""

        sources_path = Path(sources_dir)

        if not sources_path.exists():
            return {
                'status': 'error',
                'message': f'目录不存在: {sources_dir}'
            }

        # 扫描素材文件
        source_files = self._scan_source_files(sources_path)

        # 分析每个来源
        analyzed_sources = []
        for source_file in source_files:
            analysis = self._analyze_single_source(source_file)
            analyzed_sources.append(analysis)

        # 生成统计报告
        statistics = self._generate_statistics(analyzed_sources)

        analysis_result = {
            'status': 'success',
            'sources_dir': sources_dir,
            'total_sources': len(analyzed_sources),
            'analyzed_sources': analyzed_sources,
            'statistics': statistics,
            'quality_assessment': self._assess_overall_quality(statistics)
        }

        self.analysis_results = analysis_result

        return analysis_result

    def _scan_source_files(self, sources_path: Path) -> List[Dict]:
        """扫描素材文件"""

        source_files = []

        # 扫描不同类型的素材
        categories = {
            'books': ['pdf', 'epub', 'mobi'],
            'articles': ['md', 'txt', 'html'],
            'transcripts': ['txt', 'md', 'srt'],
            'videos': ['mp4', 'mkv', 'avi']
        }

        for category, extensions in categories.items():
            category_path = sources_path / category
            if category_path.exists():
                for file_path in category_path.glob('*'):
                    if file_path.is_file():
                        file_ext = file_path.suffix.lower().lstrip('.')
                        if file_ext in extensions:
                            source_files.append({
                                'path': str(file_path),
                                'category': category,
                                'filename': file_path.name,
                                'extension': file_ext,
                                'size': file_path.stat().st_size
                            })

        return source_files

    def _analyze_single_source(self, source_file: Dict) -> Dict:
        """分析单个来源"""

        filename = source_file['filename']
        category = source_file['category']

        # 评估来源质量
        quality = self._assess_source_quality(category, filename)

        # 分析内容（简化处理）
        content_analysis = self._analyze_content(source_file['path'])

        return {
            'filename': filename,
            'category': category,
            'quality': quality,
            'size': source_file['size'],
            'content_analysis': content_analysis,
            'recommendation': self._generate_recommendation(category, quality)
        }

    def _assess_source_quality(self, category: str, filename: str) -> Dict:
        """评估来源质量"""

        # 基于类别和文件名评估质量
        if category == 'books':
            return {
                **self.QUALITY_STANDARDS['high_quality'],
                'score': 3,
                'category': 'high_quality'
            }
        elif category == 'articles':
            # 检查是否来自权威来源（简化处理）
            if any(keyword in filename.lower() for keyword in ['paper', 'journal', 'official']):
                return {
                    **self.QUALITY_STANDARDS['high_quality'],
                    'score': 3,
                    'category': 'high_quality'
                }
            else:
                return {
                    **self.QUALITY_STANDARDS['medium_quality'],
                    'score': 2,
                    'category': 'medium_quality'
                }
        elif category == 'transcripts':
            # 字幕通常是高质量来源
            return {
                **self.QUALITY_STANDARDS['high_quality'],
                'score': 3,
                'category': 'high_quality'
            }
        elif category == 'videos':
            # 视频质量取决于来源
            return {
                **self.QUALITY_STANDARDS['medium_quality'],
                'score': 2,
                'category': 'medium_quality'
            }
        else:
            return {
                **self.QUALITY_STANDARDS['low_quality'],
                'score': 1,
                'category': 'low_quality'
            }

    def _analyze_content(self, file_path: str) -> Dict:
        """分析内容"""

        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()

            # 简化分析
            word_count = len(content.split())
            char_count = len(content)
            line_count = len(content.split('\n'))

            return {
                'word_count': word_count,
                'char_count': char_count,
                'line_count': line_count,
                'status': 'analyzed'
            }

        except Exception as e:
            return {
                'error': str(e),
                'status': 'error'
            }

    def _generate_recommendation(self, category: str,
                                   quality: Dict) -> str:
        """生成建议"""

        quality_score = quality.get('score', 1)

        if quality_score >= 3:
            return '高质量来源，优先使用'
        elif quality_score >= 2:
            return '中等质量来源，可使用'
        else:
            return '低质量来源，谨慎使用或寻找替代'

    def _generate_statistics(self, analyzed_sources: List[Dict]) -> Dict:
        """生成统计报告"""

        total_sources = len(analyzed_sources)

        if total_sources == 0:
            return {
                'total': 0,
                'by_category': {},
                'by_quality': {}
            }

        # 按类别统计
        by_category = {}
        for source in analyzed_sources:
            category = source['category']
            by_category[category] = by_category.get(category, 0) + 1

        # 按质量统计
        by_quality = {}
        for source in analyzed_sources:
            quality = source['quality']['category']
            by_quality[quality] = by_quality.get(quality, 0) + 1

        # 计算平均质量分
        average_quality = sum(
            source['quality']['score']
            for source in analyzed_sources
        ) / total_sources

        # 计算总字数
        total_words = sum(
            source.get('content_analysis', {}).get('word_count', 0)
            for source in analyzed_sources
        )

        return {
            'total': total_sources,
            'by_category': by_category,
            'by_quality': by_quality,
            'average_quality': round(average_quality, 2),
            'total_words': total_words
        }

    def _assess_overall_quality(self, statistics: Dict) -> Dict:
        """评估整体质量"""

        total = statistics.get('total', 0)
        average_quality = statistics.get('average_quality', 0)
        by_quality = statistics.get('by_quality', {})

        if total == 0:
            return {
                'overall': 'insufficient',
                'message': '素材不足'
            }

        # 评估质量分布
        high_quality_ratio = by_quality.get('high_quality', 0) / total
        low_quality_ratio = by_quality.get('low_quality', 0) / total

        if high_quality_ratio >= 0.7:
            return {
                'overall': 'excellent',
                'message': '高质量素材占多数'
            }
        elif high_quality_ratio >= 0.5:
            return {
                'overall': 'good',
                'message': '高质量素材过半'
            }
        elif average_quality >= 2.0:
            return {
                'overall': 'acceptable',
                'message': '素材质量可接受'
            }
        elif low_quality_ratio > 0.5:
            return {
                'overall': 'poor',
                'message': '低质量素材占多数，建议补充高质量素材'
            }
        else:
            return {
                'overall': 'moderate',
                'message': '素材质量中等'
            }


def main():
    import argparse

    parser = argparse.ArgumentParser(description='源分析')
    parser.add_argument('--sources-dir', type=str, required=True,
                       help='素材目录路径')

    args = parser.parse_args()

    analyzer = SourceAnalyzer()

    # 分析来源
    analysis_result = analyzer.analyze_sources(args.sources_dir)

    # 输出结果
    print(json.dumps(analysis_result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()


path: references/type-system.md
content: # 4种HumanOS类型系统

## 目录
- [概览](#概览)
- [HumanType](#humantype)
- [ThemeType](#themetype)
- [ScenarioType](#scenariotype)
- [MethodologyType](#methodologytype)
- [类型选择指南](#类型选择指南)

## 概览

ProClaw HumanOS支持4种类型，根据需求自动选择最合适的类型。

### 类型矩阵

| 类型 | 定义 | 触发词示例 | 核心特征 | 优先维度 |
|------|------|-----------|---------|---------|
| **HumanType** | 蒸馏特定人物的思维框架 | "蒸馏芒格"、"费曼视角" | 角色扮演、表达DNA、智识谱系 | 著作⭐⭐⭐, 对话⭐⭐⭐, 决策⭐⭐⭐ |
| **ThemeType** | 综合多人视角的主题框架 | "反脆弱OS"、"价值投资框架" | 流派对比、领域共识、中性表达 | 著作⭐⭐⭐, 他者⭐⭐⭐ |
| **ScenarioType** | 特定场景的决策系统 | "创业决策系统"、"产品评估" | 决策流程、工具箱、风险识别 | 决策⭐⭐⭐, 工具⭐⭐ |
| **MethodologyType** | 完整的方法论实施框架 | "设计思维OS"、"精益创业" | 实施步骤、工具模板、变体适应 | 著作⭐⭐⭐, 工具⭐⭐⭐ |

## HumanType

### 定义
蒸馏特定人物的思维框架，创建可运行的人格Skill。

### 适用场景
- 用户指定具体人名："蒸馏马斯克"、"创建乔布斯skill"
- 角色扮演需求："我要像巴菲特一样思考"
- 学习大师思维："费曼如何简化复杂概念？"

### 核心特征
1. **角色扮演规则**：如何像此人一样思考、表达、行动
2. **表达DNA**：句式、词汇、节奏、风格
3. **智识谱系**：影响此人的思想家、书籍、事件
4. **决策启发式**：此人的决策规则和直觉
5. **诚实边界**：此人的局限性和做不到的事

### 采集策略
- **优先维度**：著作(01)、对话(02)、决策(05)、时间线(06)
- **次优维度**：表达(03)、他者(04)

### 输出内容
- 心智模型（3-7个）
- 决策启发式（5-10条）
- 表达DNA（句式、词汇、节奏）
- 价值观（3-5条）
- 工具箱（3-10个）
- 内在张力（2-5处）
- 诚实边界（3-5条）

### 示例
- `charlie-munger-perspective` - 芒格思维框架
- `feynman-perspective` - 费曼教学思维
- `naval-perspective` - 纳瓦尔财富智慧

## ThemeType

### 定义
综合多人视角的主题框架，创建中性的领域思维OS。

### 适用场景
- 主题需求："构建价值投资框架"、"反脆弱OS"
- 综合视角："创业思维体系"、"批判思维框架"
- 领域系统："产品方法论"、"设计思维"

### 核心特征
1. **框架概览**：主题的核心定义和边界
2. **流派对比**：不同观点的对比分析
3. **领域共识**：该主题的公认原则
4. **中性表达**：不带个人色彩的客观描述
5. **应用场景**：何时使用此框架

### 采集策略
- **优先维度**：著作(01)、他者(04)
- **次优维度**：对话(02)、决策(05)

### 输出内容
- 核心概念（5-8个）
- 主要流派（3-5个）
- 共识原则（5-8条）
- 应用工具（5-10个）
- 常见误区（3-5个）
- 适用场景（3-5个）

### 示例
- `value-investing-os` - 价值投资框架
- `antifragility-os` - 反脆弱系统
- `design-thinking-os` - 设计思维

## ScenarioType

### 定义
特定场景的决策系统，创建场景化的决策支持OS。

### 适用场景
- 场景需求："创业决策系统"、"产品评估系统"
- 决策支持："投资决策助手"、"职业选择系统"
- 问题解决："技术选型系统"、"团队管理OS"

### 核心特征
1. **决策流程**：标准化的决策步骤
2. **评估框架**：评估选项的标准化方法
3. **风险识别**：常见风险和应对策略
4. **工具箱**：场景特定的工具和模板
5. **案例库**：典型决策案例

### 采集策略
- **优先维度**：决策(05)、著作(01)
- **次优维度**：他者(04)、对话(02)

### 输出内容
- 决策流程（5-8步）
- 评估框架（3-5个）
- 风险清单（5-10项）
- 工具箱（5-10个）
- 决策模板（3-5个）
- 典型案例（3-5个）

### 示例
- `startup-decision-os` - 创业决策系统
- `product-evaluation-os` - 产品评估系统
- `investment-decision-os` - 投资决策系统

## MethodologyType

### 定义
完整的方法论实施框架，创建可执行的方法论OS。

### 适用场景
- 方法论需求："设计思维OS"、"精益创业"
- 实施指导："敏捷开发框架"、"用户研究方法"
- 流程系统："写作方法论、编程方法论"

### 核心特征
1. **实施步骤**：详细的可执行步骤
2. **工具模板**：可直接使用的工具和模板
3. **变体适应**：不同情境下的调整方法
4. **最佳实践**：成功经验和常见陷阱
5. **质量控制**：检查点和验收标准

### 采集策略
- **优先维度**：著作(01)、工具(衍生)
- **次优维度**：决策(05)、时间线(06)

### 输出内容
- 实施步骤（8-12步）
- 工具模板（5-10个）
- 变体方法（3-5个）
- 检查清单（5-10项）
- 常见问题（5-10个）
- 成功要素（3-5个）

### 示例
- `design-thinking-os` - 设计思维方法论
- `lean-startup-os` - 精益创业方法论
- `agile-methodology-os` - 敏捷开发方法论

## 类型选择指南

### 决策树

```
用户需求
  ↓
是否有明确人名？
  ├─ 是 → HumanType
  └─ 否 → 是否是具体场景？
      ├─ 是 → ScenarioType
      └─ 否 → 是否是实施方法？
          ├─ 是 → MethodologyType
          └─ 否 → ThemeType
```

### 关键问题

**HumanType关键问题**：
- 你想蒸馏谁的思维框架？
- 你是否知道这个人的名字？
- 你需要角色扮演功能吗？

**ThemeType关键问题**：
- 你想构建什么领域的思维框架？
- 这个主题是否有明确的定义和边界？
- 你需要综合多个视角吗？

**ScenarioType关键问题**：
- 你想在什么场景下做决策？
- 是否有明确的决策流程？
- 你需要风险评估功能吗？

**MethodologyType关键问题**：
- 你需要可执行的实施步骤吗？
- 是否需要具体的工具和模板？
- 你需要检查点和质量控制吗？

### 混合类型

某些HumanOS可能具有多种类型的特征，此时：
1. 选择主导类型
2. 在次要类型的维度上加强采集
3. 在输出中融合多种类型的特征

### 类型转换

HumanOS可以在演化过程中转换类型：
- HumanType → ThemeType：从个人思维上升为通用框架
- ScenarioType → MethodologyType：从决策流程发展为方法论
- ThemeType → HumanType：从抽象框架具象为人物思维

## 使用建议
- 优先使用HumanType进行人物蒸馏
- ThemeType适合构建领域知识系统
- ScenarioType适合重复性决策场景
- MethodologyType适合流程化实施
- 类型可以演化，不是固定的


path: references/os-templates/human-template.md
content: ---
name: {{TARGET}}-perspective
description: {{TARGET}}的思维框架；当用户需要从{{TARGET}}的视角分析问题、获取决策建议或学习{{TARGET}}的思维方式时使用
---

# {{TARGET}} · 思维框架

## 核心理念

{{TARGET}}的独特视角是：
[在此处描述核心镜片]

## 心智模型

{{MENTAL_MODELS}}

## 决策启发式

{{DECISION_HEURISTICS}}

## 表达DNA

{{EXPRESSION_DNA}}

## 价值观

{{VALUES}}

## 工具箱

{{TOOLKIT}}

## 内在张力

{{INTERNAL_TENSIONS}}

## 诚实边界

{{HONEST_BOUNDARIES}}

## Agentic Protocol

{{AGENTIC_PROTOCOL}}

## 使用指南

激活此Skill后，{{TARGET}}将：
1. 用其独特的思维框架分析问题
2. 应用其决策启发式给出建议
3. 以其表达风格进行沟通
4. 明确其能力边界

## 注意事项
- 此Skill模拟{{TARGET}}的思维框架，不是{{TARGET}}本人
- 所有建议应结合具体情境判断
- 如遇到Skill无法回答的问题，会明确说明


path: references/os-templates/theme-template.md
content: ---
name: {{TARGET}}-os
description: {{TARGET}}主题框架；当用户需要了解{{TARGET}}的核心原理、流派对比或应用场景时使用
---

# {{TARGET}} · 主题框架

## 概览

{{TARGET}}是一个关于[领域]的综合性思维框架，整合了多个流派的核心观点。

## 核心定义

{{TARGET}}的本质是：
[在此处定义核心概念]

## 主要流派

### 流派1: [名称]
**核心观点**：
- [观点1]
- [观点2]

**代表性人物**：
- [人物1]
- [人物2]

### 流派2: [名称]
**核心观点**：
- [观点1]
- [观点2]

**代表性人物**：
- [人物1]
- [人物2]

## 领域共识

{{TARGET}}的公认原则包括：

1. [原则1]
2. [原则2]
3. [原则3]

## 核心概念

{{CONCEPTS}}

## 应用场景

{{TARGET}}适用于：
1. [场景1]
2. [场景2]
3. [场景3]

## 工具和方法

{{TOOLKIT}}

## 常见误区

使用{{TARGET}}时常见的误区：

1. [误区1] → [正确做法]
2. [误区2] → [正确做法]
3. [误区3] → [正确做法]

## 适用边界

{{TARGET}}不适用于：
1. [边界1]
2. [边界2]
3. [边界3]

## Agentic Protocol

{{AGENTIC_PROTOCOL}}

## 使用指南

激活此Skill后，{{TARGET}}将：
1. 提供中性的、综合性的分析
2. 对比不同流派的观点
3. 识别核心共识和分歧
4. 提供应用指导

## 注意事项
- 此Skill提供综合框架，不是特定观点
- 不同流派可能存在冲突，需要根据情境选择
- 如遇到Skill无法涵盖的场景，会明确说明


path: references/os-templates/scenario-template.md
content: ---
name: {{TARGET}}-scenario-os
description: {{TARGET}}场景决策系统；当用户需要在{{TARGET}}场景下做决策或评估选项时使用
---

# {{TARGET}} · 场景决策系统

## 场景定义

{{TARGET}}场景是指在[具体情境]中需要做出[决策类型]的情境。

## 决策流程

### 步骤1: 问题定义
1. 明确决策目标
2. 识别关键约束
3. 确定评估标准

### 步骤2: 信息收集
1. 收集相关数据
2. 识别信息缺口
3. 评估信息质量

### 步骤3: 方案生成
1. 生成多个选项
2. 评估每个选项
3. 排除明显不合适的选项

### 步骤4: 方案评估
{{DECISION_FRAMEWORK}}

### 步骤5: 风险评估
{{RISK_CHECKLIST}}

### 步骤6: 最终决策
1. 选择最优方案
2. 制定执行计划
3. 设置检查点

## 评估框架

{{FRAMEWORK}}

## 风险识别

{{RISKS}}

## 工具箱

{{TOOLKIT}}

## 决策模板

### 模板1: [名称]
[模板内容]

### 模板2: [名称]
[模板内容]

## 典型案例

{{CASES}}

## Agentic Protocol

{{AGENTIC_PROTOCOL}}

## 使用指南

激活此Skill后，{{TARGET}}决策系统将：
1. 引导用户完成决策流程
2. 应用标准化评估框架
3. 识别潜在风险
4. 提供可执行的决策建议

## 注意事项
- 此系统提供决策支持，不替代人类判断
- 用户需要结合具体情境调整
- 如遇到系统无法处理的复杂情况，会明确说明


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)