Back to skills
SkillHub ClubShip Full StackFull Stack

multi-agent-collaboration

多智能体协作系统V1.4(最终版),支持**所有行业所有内容**的智能协作: 通用信息守护者(信息采集)、内容趋势优化系统(趋势创作)、状态洞察模块(个人状态)、工作流沉淀系统(报告生成)。 适用于:金融、医疗、教育、零售、科技、制造业、餐饮、服务业等**全行业**。 核心功能:意图识别+智能路由+反思机制+主动感知+用户自适应,支持串行/并行/跳过/精简多种执行模式, 执行前自动检索记忆库,学习用户偏好,动态调整交互方式,预测用户需求。 包含强大的记忆系统V2,支持场景化记忆、分层存储、遗忘机制和智能检索。

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
3,084
Hot score
99
Updated
March 20, 2026
Overall rating
C4.0
Composite score
4.0
Best-practice grade
C58.6

Install command

npx @skill-hub/cli install openclaw-skills-multi-agent-collaboration

Repository

openclaw/skills

Skill path: skills/e2e5g/multi-agent-collaboration

多智能体协作系统V1.4(最终版),支持**所有行业所有内容**的智能协作: 通用信息守护者(信息采集)、内容趋势优化系统(趋势创作)、状态洞察模块(个人状态)、工作流沉淀系统(报告生成)。 适用于:金融、医疗、教育、零售、科技、制造业、餐饮、服务业等**全行业**。 核心功能:意图识别+智能路由+反思机制+主动感知+用户自适应,支持串行/并行/跳过/精简多种执行模式, 执行前自动检索记忆库,学习用户偏好,动态调整交互方式,预测用户需求。 包含强大的记忆系统V2,支持场景化记忆、分层存储、遗忘机制和智能检索。

Open repository

Best for

Primary workflow: Ship Full Stack.

Technical facets: Full Stack.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: openclaw.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install multi-agent-collaboration into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/openclaw/skills before adding multi-agent-collaboration to shared team environments
  • Use multi-agent-collaboration for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: multi-agent-collaboration
description: |
  多智能体协作系统V1.4(最终版),支持**所有行业所有内容**的智能协作:
  通用信息守护者(信息采集)、内容趋势优化系统(趋势创作)、状态洞察模块(个人状态)、工作流沉淀系统(报告生成)。
  适用于:金融、医疗、教育、零售、科技、制造业、餐饮、服务业等**全行业**。
  核心功能:意图识别+智能路由+反思机制+主动感知+用户自适应,支持串行/并行/跳过/精简多种执行模式,
  执行前自动检索记忆库,学习用户偏好,动态调整交互方式,预测用户需求。
  包含强大的记忆系统V2,支持场景化记忆、分层存储、遗忘机制和智能检索。
---

# 多智能体协作系统 V1.4(最终版)

> 🎯 **最终版本**:用户自适应 - 学习用户偏好,动态调整交互

## V1.4 核心升级

| 新功能 | 说明 |
|--------|------|
| **用户画像** | 记录用户交互偏好 |
| **自适应确认** | 根据跳过率调整确认频率 |
| **个性化输出** | 根据偏好调整报告风格 |
| **预测服务** | 主动预测用户下一步需求 |

## 完整执行流程

```
用户输入
    │
    ▼
┌─────────────────────────────────────┐
│  查用户画像 ←─────────────────────┐ │
│  • 了解用户偏好                   │ │
│  • 获取历史交互模式               │ │
└─────────────────────────────────────┘ │
    │                                    │
    ▼                                    │
意图识别 → 智能路由 ←───────────────────┘
    │                    (参考用户偏好)
    ▼
主动感知
    │
    ▼
┌─────────────────────────────────────┐
│           模块执行                   │
│  (串行/并行/跳过)                   │
└─────────────────────────────────────┘
    │
    ▼
┌─────────────────────────────────────┐
│           反思机制                   │
│  评估 → 优化 → 重试                │
└─────────────────────────────────────┘
    │
    ▼
记录行为 → 更新画像 ─────────────────→ (回到用户画像)
    │
    ▼
用户确认 → 继续/退出
```

---

## 用户画像详解

### 学习数据

```typescript
interface UserProfile {
  user_id: string;
  
  // 交互习惯
  confirmation_habit: {
    total_decisions: number;
    skip_count: number;
    skip_rate: number;          // 跳过率
    avg_decision_time_ms: number;
  };
  
  // 输出偏好
  output_preference: {
    detailed_count: number;
    concise_count: number;
    preferred_style: 'detailed' | 'concise' | 'balanced';
  };
  
  // 推荐接受
  recommendation: {
    total: number;
    accepted: number;
    acceptance_rate: number;
  };
  
  // 执行偏好
  execution: {
    parallel_count: number;
    serial_count: number;
    preferred_mode: 'parallel' | 'serial';
  };
  
  // 模块偏好
  module_preference: {
    module_sequence_history: string[];
    common_paths: string[];
  };
  
  updated_at: string;
}
```

### 自适应策略

| 用户特征 | 系统调整 |
|----------|----------|
| 跳过率 > 60% | 减少确认步骤 |
| 跳过率 < 30% | 保持完整确认 |
| 偏好详细 | 输出更多解释 |
| 偏好精简 | 输出关键要点 |
| 推荐接受 > 70% | 多推荐 |
| 推荐接受 < 30% | 少推荐 |
| 偏好并行 | 优先并行执行 |
| 偏好串行 | 保持串行执行 |

---

## V1.4 交互示例

### 完整交互流程

```
用户:帮我分析新能源汽车行业趋势
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

【行业分析】
识别意图:信息获取 + 内容创作
目标行业:新能源汽车

【用户画像】
┌─────────────────────────────────────┐
│  画像:user_001                     │
│  • 跳过率:75% → 简化确认           │
│  • 输出偏好:详细(80%)           │
│  • 推荐接受:90% → 多推荐           │
│  • 执行偏好:并行                   │
└─────────────────────────────────────┘

【自适应决策】
✓ 减少确认步骤
✓ 输出详细报告
✓✓ 尝试并行 多提供推荐


━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

【执行】模块1 → 模块2(并行)

【模块1 - 反思评估】
✓ 完整性:90% | 质量:8.2/10 | 可用性:92%

【模块2 - 反思评估】
✓ 完整性:88% | 质量:8.0/10 | 可用性:90%

【模块执行完成】

【自适应确认】
✓ 跳过非必要确认(跳过率75%)

摘要:
- 行业趋势:3个
- 创作方案:2套
- 预估时间:25分钟

继续到模块3/4?
1. 继续到模块3
2. 继续到模块4
3. 查看完整报告
4. 结束

请回复:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### 预测性服务

```
用户:看看金融行业新闻

【行业分析】
识别意图:信息获取
目标行业:金融

【预测服务】
根据您的历史行为:
━━━━━━━━━━━━━━━━━━━━━━━━━━━
• 87% 概率:您会继续到模块2(创作)
• 60% 概率:您会查看详细报告
• 常用路径:模块1 → 模块2
━━━━━━━━━━━━━━━━━━━━━━━━━━━

【预执行】
已在后台准备模块2内容(如果继续)

开始执行模块1...
━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

**注意**:以上示例适用于任何行业(金融、医疗、教育、零售、科技、新能源汽车、餐饮等)

---

## 全面自检报告

### ✅ 版本一致性检查

| 检查项 | 状态 | 说明 |
|--------|------|------|
| V1.0 核心保留 | ✓ | 串行流程、用户确认、数据传递、灵活退出 |
| V1.1 增量引入 | ✓ | 意图识别、智能路由、并行执行 |
| V1.2 增量引入 | ✓ | 反思机制、自动重试、优化尝试 |
| V1.3 增量引入 | ✓ | 主动感知、增量更新、模式复用 |
| V1.4 增量引入 | ✓ | 用户画像、自适应、预测服务 |

### ✅ 功能完整性检查

| 模块 | 功能 | 状态 |
|------|------|------|
| 模块1 | 信息采集+过滤+评估+分级 | ✓ |
| 模块2 | 趋势分析+爆款分析+创作方案+发布策略 | ✓ |
| 模块3 | 状态分析+成长洞察+AI信件 | ✓ |
| 模块4 | 工具推荐+工作流记录+模板生成+效率报告 | ✓ |

### ✅ 记忆系统检查

| 功能 | 状态 |
|------|------|
| 五层架构(L0-L4) | ✓ |
| 场景化配置 | ✓ |
| 智能检索 | ✓ |
| 遗忘机制 | ✓ |
| 反馈闭环 | ✓ |
| 增量更新 | ✓ |

### ✅ 逻辑一致性检查

| 检查项 | 状态 |
|--------|------|
| 模块执行顺序(1→2/3/4) | ✓ |
| 数据传递(后续模块可访问前置输出) | ✓ |
| 用户确认点(每模块后) | ✓ |
| 灵活退出(任何时候可退出) | ✓ |
| 记忆流转(L0→L2→L3→L4) | ✓ |
| 反思触发(每模块后) | ✓ |
| 自适应依赖(需要画像数据) | ✓ |

### ✅ 向后兼容性检查

| 配置项 | 默认值 | 可关闭 |
|--------|--------|--------|
| intent_recognition | true | ✓ |
| smart_routing | true | ✓ |
| parallel_execution | true | ✓ |
| reflection | true | ✓ |
| proactive_memory | true | ✓ |
| user_adaptation | true | ✓ |
| user_confirmation | true | ✗ (必须开启) |
| data_passing | true | ✗ (必须开启) |
| flexible_exit | true | ✗ (必须开启) |

---

## 完整配置

```typescript
const MULTI_AGENT_SYSTEM_V1_4 = {
  // 版本
  version: "1.4",
  release_date: "2026-02-25",
  
  // V1.4 功能
  user_adaptation: {
    enabled: true,
    profile_tracking: true,
    adaptive_confirmation: true,
    personalized_output: true,
    predictive_service: true
  },
  
  // V1.3 功能
  proactive_memory: {
    enabled: true,
    incremental_update: true,
    cache_ttl_hours: 168,
    reuse_bonus: 0.2
  },
  
  // V1.2 功能
  reflection: {
    enabled: true,
    auto_retry: true,
    max_retries: 3,
    dimensions: ['completeness', 'quality', 'usability']
  },
  
  // V1.1 功能
  routing: {
    intent_recognition: true,
    smart_routing: true,
    parallel_execution: true,
    patterns: ['serial', 'parallel', 'skip', '精简']
  },
  
  // V1 核心(不可关闭)
  core: {
    user_confirmation: true,
    data_passing: true,
    flexible_exit: true
  },
  
  // 模块配置
  modules: {
    module1: {
      name: "信息守护者",
      layer: "L0",
      retention: "1小时"
    },
    module2: {
      name: "内容趋势优化系统",
      layer: "L2",
      retention: "7天"
    },
    module3: {
      name: "状态洞察模块",
      layer: "L3-L4",
      retention: "90天"
    },
    module4: {
      name: "工作流沉淀系统",
      layer: "L3",
      retention: "永久"
    }
  },
  
  // 记忆系统
  memory: {
    enabled: true,
    layers: ['L0', 'L1', 'L2', 'L3', 'L4'],
    scenarios: ['duty', 'sentiment', 'workflow', 'goal', 'general']
  }
};
```

---

## 执行模式汇总

| 模式 | V1.0 | V1.1 | V1.2 | V1.3 | V1.4 |
|------|------|------|------|------|------|
| 串行执行 | ✓ | ✓ | ✓ | ✓ | ✓ |
| 意图识别 | - | ✓ | ✓ | ✓ | ✓ |
| 智能路由 | - | ✓ | ✓ | ✓ | ✓ |
| 并行执行 | - | ✓ | ✓ | ✓ | ✓ |
| 反思机制 | - | - | ✓ | ✓ | ✓ |
| 主动感知 | - | - | - | ✓ | ✓ |
| 用户自适应 | - | - | - | - | ✓ |

---

## 参考文档

- 完整工作流设计: [references/workflow-design.md](references/workflow-design.md)
- 模块间数据流转: [references/data-flow.md](references/data-flow.md)
- 记忆系统V2源码: [scripts/memory-v2.ts](scripts/memory-v2.ts)


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### references/workflow-design.md

```markdown
# 多智能体协作系统 - 完整工作流程设计

## 文档版本
- 版本:V1.0
- 创建日期:2026年2月25日
- 适用系统:多智能体协作系统 V1.0.0

## 核心设计原则

1. **用户主导型工作流**:每个模块执行完成后,必须等待用户确认才能切换到下一个模块
2. **模块间数据流转**:前一模块的输出是后一模块的输入
3. **灵活的退出机制**:用户可以在任何模块完成后选择退出,不必执行全部模块
4. **完整的上下文传递**:确保每个模块都能访问前面模块的输出和用户选择

## 执行规则

1. 模块1(AI信息守护者)必须第一个执行
2. 模块2、3、4可以任意顺序(但不能跳过前面的模块)
3. 用户可以在任何模块完成后选择退出
4. 所有已执行模块的输出都会传递给下一个模块

## 四个模块能力矩阵

### 模块1:AI信息守护者(ai-information-guardian)

**核心定位**:信息处理基础层

**主要功能**:
1. 信息采集:多平台信息扫描(微博、抖音、知乎、B站、头条、技术社区)
2. 噪音过滤:过滤低质量信息(过滤比例>80%)
3. 价值评估:四维度评估(信源可靠性、信息重要性、时效性、用户相关性)
4. 分级输出:A级(必须关注)、B级(重点关注)、C级(参考信息)

**输入参数**:
- 必填:关注领域
- 可选:扫描深度、输出格式、当前目标、自定义关键词、扫描平台

**输出内容**:
- A级信息列表(详细分析)
- B级信息列表(简要摘要)
- C级信息列表(标题)
- 行业趋势分析
- 信源质量评估
- 基于用户目标的建议

**适用场景**:
- 需要了解行业动态
- 需要监控特定话题
- 需要发现机会/趋势
- 需要收集信息用于决策

---

### 模块2:内容趋势优化系统(content-trend-optimizer)

**核心定位**:趋势分析与内容创作层

**主要功能**:
1. 趋势扫描:跨平台热点扫描与预测
2. 爆款分析:深度分析爆款原因
3. 平台创作:五大平台差异化创作方案
4. 发布策略:发布时机与数据验证

**输入参数**:
- 必填:创作主题、目标平台、创作目标
- 可选:当前时间、创作形式、目标受众

**输出内容**:
- 趋势扫描报告
- 爆款分析报告
- 平台差异化创作方案
- 完整的可发布内容
- 发布时机建议
- 数据验证策略

**适用场景**:
- 需要创作内容
- 需要分析爆款
- 需要优化发布策略
- 需要多平台发布

---

### 模块3:状态洞察模块(status-insight-module)

**核心定位**:个人成长与状态分析层

**主要功能**:
1. 个人记忆库:沉淀用户历史数据
2. 状态分析:精力分配、成长轨迹、情绪状态
3. 前瞻洞察:成长机会、风险预警、可能性建议
4. AI信件:定期推送真诚的状态洞察

**输入参数**:
- 必填:分析周期、分析维度
- 可选:当前目标、重点关注领域

**输出内容**:
- 精力分配分析
- 成长轨迹分析
- 情绪状态分析
- 前瞻洞察建议
- AI信件(周报/月报)

**适用场景**:
- 需要了解自己的状态
- 需要成长规划
- 需要优化精力分配
- 需要情绪管理

---

### 模块4:工作流沉淀系统(workflow-publisher)

**核心定位**:工作流编排与成果交付层

**主要功能**:
1. 项目启动辅助:推荐AI工具组合
2. 工作流自动记录:记录操作步骤
3. 可复用模板生成:沉淀成功经验
4. 效率追踪与优化:对比前后效率

**输入参数**:
- 必填:项目目标
- 可选:项目类型、可用工具列表、预期工期、优先级

**输出内容**:
- AI工具组合推荐
- 工作流模板
- 操作记录(如适用)
- 可复用Skill模板
- 效率报告

**适用场景**:
- 需要启动新项目
- 需要沉淀工作流
- 需要优化效率
- 需要生成报告

---

## 标准工作流程

### 工作流程总览

```
步骤0:系统初始化
步骤1:用户触发(提供需求)
步骤2:执行模块1(AI信息守护者)
步骤3:用户确认1(选择继续到模块2/3/4或退出)
步骤4:执行模块2(如选择)
步骤5:用户确认2
步骤6:执行模块3(如选择)
步骤7:用户确认3
步骤8:执行模块4(如选择)
步骤9:完成交付
```

决策树

```
用户触发
---

## 模块切换    │
    ▼
模块1(AI信息守护者)
    │
    ├─ 用户选择:继续到模块2
    │       │
    │       ▼
    │   模块2(内容趋势优化系统)
    │       │
    │       ├─ 用户选择:继续到模块3
    │       │       │
    │       │       ▼
    │       │   模块3(状态洞察模块)
    │       │       │
    │       │       ├─ 用户选择:继续到模块4
    │       │       │       │
    │       │       │       ▼
    │       │       │   模块4(工作流沉淀系统)
    │       │       │       │
    │       │       │       └─ 完成
    │       │       │
    │       │       └─ 用户选择:退出
    │       │               │
    │       │               └─ 完成(交付模块1+2+3)
    │       │
    │       ├─ 用户选择:继续到模块4
    │       │       │
    │       │       ▼
    │       │   模块4(工作流沉淀系统)
    │       │       │
    │       │       └─ 完成(交付模块1+2+4)
    │       │
    │       └─ 用户选择:退出
    │               │
    │               └─ 完成(交付模块1+2)
    │
    ├─ 用户选择:继续到模块3
    │       │
    │       ▼
    │   模块3(状态洞察模块)
    │       │
    │       ├─ 用户选择:继续到模块4
    │       │       │
    │       │       ▼
    │       │   模块4(工作流沉淀系统)
    │       │       │
    │       │       └─ 完成(交付模块1+3+4)
    │       │
    │       └─ 用户选择:退出
    │               │
    │               └─ 完成(交付模块1+3)
    │
    ├─ 用户选择:继续到模块4
    │       │
    │       ▼
    │   模块4(工作流沉淀系统)
    │       │
    │       └─ 完成(交付模块1+4)
    │
    └─ 用户选择:退出
            │
            └─ 完成(交付模块1)
```

---

## 异常处理机制

| 异常类型 | 处理方式 |
|----------|----------|
| 用户中断 | 保存当前进度,允许后续继续 |
| 模块执行失败 | 提供错误信息,允许重试或跳过 |
| 数据传递失败 | 提供默认数据,允许继续 |
| 用户输入无效 | 提供帮助信息,要求重新输入 |

---

## 完整执行示例

### 示例1:完整执行所有模块
- 用户输入:我想了解一下AI行业的最新动态,然后创作相关内容,最后分析我的状态
- 执行路径:模块1 → 模块2 → 模块3 → 模块4
- 总耗时:60分钟
- 输出内容:
  - AI信息守护者报告
  - 内容趋势优化系统报告
  - 状态洞察模块报告
  - 工作流沉淀系统报告
  - 可复用Skill模板
  - 效率报告

### 示例2:只执行模块1和模块2
- 用户输入:我想了解一下AI行业的最新动态,然后创作相关内容
- 执行路径:模块1 → 模块2 → 用户退出
- 总耗时:30分钟
- 输出内容:
  - AI信息守护者报告
  - 内容趋势优化系统报告
  - 完整交付报告

### 示例3:只执行模块1
- 用户输入:我想了解一下AI行业的最新动态
- 执行路径:模块1 → 用户退出
- 总耗时:15分钟
- 输出内容:
  - AI信息守护者报告
  - 完整交付报告

### 示例4:跳过模块2,直接从模块1到模块3
- 用户输入:我想了解一下AI行业的最新动态,然后分析我的状态
- 执行路径:模块1 → 模块3 → 用户退出
- 总耗时:45分钟
- 输出内容:
  - AI信息守护者报告
  - 状态洞察模块报告
  - 完整交付报告

```

### references/data-flow.md

```markdown
# 模块间数据流转(含记忆系统)

## 数据流转总览(含记忆层)

```
模块1(AI信息守护者)
    │
    ├─ 输出:结构化信息列表
    │   ├─ A级信息列表
    │   ├─ B级信息列表
    │   ├─ C级信息列表
    │   ├─ 行业趋势分析
    │   └─ 信源推荐
    │
    ├─ 记忆处理:
    │   ├─ 存入 L0 闪存(当前任务变量)
    │   ├─ 高价值信息 → L2 经验记忆
    │   └─ 行业趋势 → L3 知识记忆
    │
    ├─ 可传递给:
    │   ├─ 模块2:用于趋势分析
    │   ├─ 模块3:用于状态分析(作为参考)
    │   └─ 模块4:用于工作流编排
    │
    └─ 数据格式:JSON


模块2(内容趋势优化系统)
    │
    ├─ 输出:趋势分析与创作方案
    │   ├─ 趋势扫描报告
    │   ├─ 爆款分析报告
    │   ├─ 平台差异化创作方案
    │   └─ 发布时机建议
    │
    ├─ 输入:模块1的输出 + L0/L2 记忆
    │
    ├─ 记忆处理:
    │   ├─ 存入 L2 经验记忆
    │   ├─ 创作模式 → L3 知识记忆
    │   └─ 爆款因素 → L3 模式库
    │
    ├─ 可传递给:
    │   ├─ 模块3:用于状态分析(作为参考)
    │   └─ 模块4:用于工作流编排
    │
    └─ 数据格式:JSON


模块3(状态洞察模块)
    │
    ├─ 输出:状态分析与洞察建议
    │   ├─ 精力分配分析
    │   ├─ 成长轨迹分析
    │   ├─ 情绪状态分析
    │   └─ 前瞻洞察建议
    │
    ├─ 输入:
    │   ├─ 模块1的输出(作为参考)
    │   ├─ 模块2的输出(如适用)
    │   └─ 用户历史数据(L3-L4)
    │
    ├─ 记忆处理:
    │   ├─ 存入 L3 知识记忆
    │   ├─ 洞察 → L4 智慧记忆
    │   └─ 状态趋势 → 长期追踪
    │
    ├─ 可传递给:
    │   └─ 模块4:用于工作流编排
    │
    └─ 数据格式:JSON


模块4(工作流沉淀系统)
    │
    ├─ 输出:工作流报告与模板
    │   ├─ AI工具组合推荐
    │   ├─ 工作流模板
    │   ├─ 可复用Skill模板
    │   └─ 效率报告
    │
    ├─ 输入:
    │   ├─ 模块1的输出
    │   ├─ 模块2的输出(如适用)
    │   ├─ 模块3的输出(如适用)
    │   └─ L2-L3 历史工作流
    │
    ├─ 记忆处理:
    │   ├─ 存入 L3 知识记忆(永久)
    │   ├─ 生成可复用模板 → L3
    │   └─ 效率数据 → L2 经验
    │
    └─ 数据格式:JSON
```

---

## 记忆流转规则

### 模块 → 记忆层映射

| 模块 | 主要记忆层 | 压缩目标 | 提炼目标 |
|------|-----------|----------|----------|
| 模块1 (信息守护者) | L0 → L2 | 高价值信息 | 行业趋势 |
| 模块2 (内容优化) | L2 | 创作模式 | 爆款因素 |
| 模块3 (状态洞察) | L3 → L4 | 洞察建议 | 成长模式 |
| 模块4 (工作流) | L3 | 工作流模板 | 效率模式 |

### 记忆保留周期

```typescript
const MEMORY_RETENTION = {
  // 模块1:信息时效性强,快速遗忘
  module1_L0: { layer: 'L0', ttl_hours: 1 },
  module1_L2: { layer: 'L2', ttl_days: 7 },
  
  // 模块2:创作经验可复用
  module2_L2: { layer: 'L2', ttl_days: 7 },
  module2_L3: { layer: 'L3', ttl_days: 30 },
  
  // 模块3:状态需长期追踪
  module3_L3: { layer: 'L3', ttl_days: 90 },
  module3_L4: { layer: 'L4', ttl_days: 365 },
  
  // 模块4:工作流模板永久保存
  module4_L3: { layer: 'L3', ttl_days: null }  // 永久
};
```

---

## 用户反馈与记忆调整

### 反馈类型 → 记忆影响

| 用户行为 | 反馈效果 | 记忆调整 |
|----------|----------|----------|
| 选择继续到下一模块 | success | +10% 重要性 |
| 选择退出 | neutral | 不变 |
| 要求重试 | failure | -10% 重要性 |
| 完成全部模块 | success | 模式提炼到L3 |

### 记忆自动优化

```python
# 用户确认后的记忆处理
def on_user_confirm(choice, module_output):
    if choice == "continue":
        # 成功:强化当前记忆
        enhance_memory(module_output, bonus=0.1)
        # 准备传递给下一模块
        return prepare_for_next_module(module_output)
    
    elif choice == "exit":
        # 退出:保存当前模块记忆
        save_to_L2(module_output)
        # 生成最终报告
        return generate_final_report()
    
    elif choice == "retry":
        # 重试:降低相关记忆权重
        weaken_memory(module_output, penalty=0.1)
        # 重新执行当前模块
        return reexecute_module(module_output)
```

---

## 上下文数据结构(含记忆)

```python
# 完整的上下文对象
context = {
    "session_id": "session_20260225_001",
    "user_id": "user_001",
    "start_time": "2026-02-25 15:00:00",
    "current_module": "module_1",
    "execution_path": ["module_1"],
    
    # 模块输出(含记忆位置)
    "module_outputs": {
        "module_1": {
            "name": "AI信息守护者",
            "output": {...},
            "memory_layer": "L0",        # 当前存储层
            "compress_target": "L2",      # 压缩目标
            "retention": "1小时"          # 保留周期
        },
        "module_2": {...},
        "module_3": {...},
        "module_4": {...}
    },
    
    # 记忆系统上下文
    "memory_context": {
        "scenario": "workflow",
        "L0_vars": {...},                # 当前任务变量
        "recent_L2": [...],              # 最近经验(供参考)
        "relevant_L3": [...],            # 相关知识(供参考)
        "user_history": {...}            # 用户长期状态
    },
    
    "user_choices": {
        "step_1": "continue_to_module_2",
        "step_2": "continue_to_module_3",
        "step_3": "continue_to_module_4"
    }
}
```

---

## 智能检索示例

### 模块2调用模块1的记忆

```python
# 模块2执行时,检索相关记忆
relevant_memories = memory.smartQuery(
    query="AI行业趋势",
    scenario="workflow",
    options={
        "min_credibility": 0.7,
        "min_success_rate": 0.6,
        "max_age": 7  # 只检索7天内的
    }
)

# 使用记忆辅助创作
for mem in relevant_memories:
    if mem.category == "pattern":
        # 使用提炼的模式
        apply_pattern(mem.value)
```

### 模块3调用长期状态

```python
# 模块3分析用户状态
user_history = memory.query(
    layer="L3-L4",
    category=["goal", "insight"],
    user_id="user_001"
)

# 结合历史生成洞察
insight = generate_insight(
    current_state=module3_input,
    historical_data=user_history
)
```

---

## 最终交付报告(含记忆摘要)

```python
final_report = {
    "session_info": {
        "session_id": "session_20260225_001",
        "execution_path": "模块1 → 模块2 → 模块3 → 模块4",
        "duration": "60分钟"
    },
    
    "module_outputs": {...},
    
    "memory_summary": {
        "stored_L0": 5,    # 当前任务变量
        "stored_L2": 12,   # 新增经验
        "stored_L3": 3,    # 新增知识
        "extracted_patterns": 2,  # 提炼的模式
        "forgotten": 1      # 遗忘的低价值记忆
    },
    
    "reusable_assets": [
        "综合管理工作流模板",
        "AI行业趋势分析模式",
        "内容创作工作流模板"
    ],
    
    "next_session_context": {
        "suggested_module": "模块3",  # 基于用户状态推荐
        "relevant_history": [...],    # 可继承的记忆
        "pending_goals": [...]        # 未完成目标
    }
}
```

```



---

## Skill Companion Files

> Additional files collected from the skill directory layout.

### README.md

```markdown
# 🧠 AI协作操作系统

**一站式集成:统一记忆系统 + 信息信号识别 + 工作流资产沉淀 + 个人目标追踪**

---

## 🚀 快速开始

```bash
# 解压
unzip ai-collaboration-complete.zip

# 进入目录
cd ai-collaboration-complete

# 安装
npm install

# 运行演示
node demo.js
```

---

## 📦 包含系统

| 系统 | 功能 | 核心能力 |
|------|------|----------|
| **统一记忆系统** | 五层记忆管理 | L0闪存→L1工作→L2经验→L3知识→L4智慧 |
| **信息信号识别** | 信号识别、模式发现 | 信息价值分层、世界观构建、时间衰减 |
| **工作流资产沉淀** | 隐性知识显性化 | 能力基因识别、方法论构建 |
| **个人目标追踪** | 动机解析、AI镜像 | 目标网络、未来预测 |

---

## 🎯 演示程序

| 文件 | 说明 |
|------|------|
| `demo.js` | 完整功能演示 |
| `duty-demo.js` | 值班机制演示 |
| `time-decay-demo.js` | 时间衰减演示 |
| `examples/holiday-duty.js` | 场景示例:节假日值班热点监测 |

---

## 📝 场景示例

`examples/holiday-duty.js` 展示如何使用本系统实现节假日值班热点监测:

- ✅ 可监测任何类型热点(政策、社会、产业、舆情等)
- ✅ 自动评估关注等级(S/A/B/C)
- ✅ 时间衰减机制(一周以上自动降级)
- ✅ 自动生成日报
- ✅ 使用原有系统所有功能

```bash
node examples/holiday-duty.js
```

---

## 📁 目录结构

```
ai-collaboration-complete/
├── install.sh              # 一键安装
├── README.md               # 本文件
├── package.json            # 项目配置
│
├── scripts/                # TypeScript源代码
│   ├── index.ts            # 主入口
│   ├── core/memory.ts      # 统一记忆系统
│   └── systems/            # 子系统
│
├── dist/                   # 编译输出
│
├── examples/               # 场景示例
│   └── holiday-duty.js     # 节假日值班示例
│
├── demo.js                 # 完整演示
├── duty-demo.js            # 值班演示
├── time-decay-demo.js      # 时间衰减演示
│
├── docs/                   # 文档
│   └── AI协作操作系统_完整使用说明书.md
│
└── memory/                 # 记忆存储
```

---

## 📖 文档

- `docs/AI协作操作系统_完整使用说明书.md` - 完整使用说明(65KB)

---

## ✅ 验证安装

```bash
node demo.js
```

看到 `✅ 演示完成!` 表示安装成功。

---

**一行代码,开启AI协作之旅!**

```

### _meta.json

```json
{
  "owner": "e2e5g",
  "slug": "multi-agent-collaboration",
  "displayName": "Multi Agent Collaboration",
  "latest": {
    "version": "1.0.0",
    "publishedAt": 1772163707489,
    "commit": "https://github.com/openclaw/skills/commit/7e9275114da7c4399b41d65dbe7508699f72048a"
  },
  "history": []
}

```

### scripts/core/agents.ts

```typescript
/**
 * 多智能体协作系统 - 重新设计
 * 
 * 核心理念:
 * 1. 智能体基于能力边界划分,职责单一
 * 2. 去中心化协作,智能体有自主性
 * 3. 能力组合扩展,不是配置扩展
 * 4. 人机协作伙伴,不是工具
 */

// ==================== 智能体基类 ====================

/**
 * 智能体接口 - 每个智能体都有自己的"大脑"
 */
interface IAgent {
  // 身份
  id: string;
  name: string;
  description: string;
  
  // 能力边界
  capabilities: string[];      // 能做什么
  limitations: string[];       // 不能做什么
  
  // 自主决策
  canHandle(task: Task): Promise<boolean>;   // 能否处理这个任务
  decide(task: Task): Promise<Decision>;     // 如何处理
  
  // 协作
  requestCollaboration(task: Task, targetAgent: string): Promise<void>;
  respondToCollaboration(request: CollaborationRequest): Promise<CollaborationResponse>;
  
  // 学习
  learn(experience: Experience): Promise<void>;
  
  // 与人协作
  communicate(message: string): Promise<string>;
}

/**
 * 任务
 */
interface Task {
  id: string;
  type: string;
  content: any;
  context: any;
  priority: number;
  deadline?: Date;
  
  // 谁创建的
  createdBy: 'human' | 'agent' | 'system';
  
  // 当前状态
  status: 'pending' | 'processing' | 'completed' | 'blocked';
  
  // 处理历史
  history: TaskHistory[];
}

interface TaskHistory {
  agentId: string;
  action: string;
  timestamp: Date;
  result?: any;
}

/**
 * 决策
 */
interface Decision {
  action: 'execute' | 'delegate' | 'collaborate' | 'ask_human' | 'reject';
  reasoning: string;           // 为什么这样决策
  plan?: ExecutionPlan;        // 执行计划
  delegateTo?: string;         // 委托给谁
  collaborationWith?: string[]; // 和谁协作
  humanQuestion?: string;      // 问人什么
}

interface ExecutionPlan {
  steps: PlanStep[];
  estimatedTime: number;
  requiredResources: string[];
}

interface PlanStep {
  action: string;
  expectedOutcome: string;
}

/**
 * 协作请求
 */
interface CollaborationRequest {
  from: string;
  to: string;
  task: Task;
  reason: string;
  whatINeed: string;           // 我需要什么帮助
}

interface CollaborationResponse {
  accepted: boolean;
  reason: string;
  proposedContribution?: string;  // 我能贡献什么
}

/**
 * 经验
 */
interface Experience {
  task: Task;
  decision: Decision;
  outcome: 'success' | 'failure' | 'partial';
  lessons: string[];
  timestamp: Date;
}

// ==================== 具体智能体 ====================

/**
 * 信息源订阅者 - 只负责对接数据源
 */
class DataSourceSubscriber implements IAgent {
  id = 'data-source-subscriber';
  name = '信息源订阅者';
  description = '专门负责对接各种数据源,获取原始信息';
  
  capabilities = [
    '订阅RSS/Atom源',
    '对接API接口',
    '监听数据库变更',
    '抓取网页内容',
    '接收推送消息'
  ];
  
  limitations = [
    '不分析内容',
    '不判断价值',
    '不做决策'
  ];
  
  private subscriptions: Map<string, any> = new Map();
  private messageQueue: any[] = [];
  
  async canHandle(task: Task): Promise<boolean> {
    return task.type === 'subscribe' || 
           task.type === 'fetch' || 
           task.type === 'receive';
  }
  
  async decide(task: Task): Promise<Decision> {
    // 自主决策:我能处理吗?需要协作吗?
    
    if (task.type === 'subscribe') {
      return {
        action: 'execute',
        reasoning: '订阅任务在我能力范围内',
        plan: {
          steps: [
            { action: '验证数据源有效性', expectedOutcome: '确认可访问' },
            { action: '建立订阅连接', expectedOutcome: '开始接收数据' }
          ],
          estimatedTime: 5000,
          requiredResources: ['网络连接']
        }
      };
    }
    
    if (task.type === 'fetch') {
      // 检查是否需要协作
      if (task.content.requiresCleaning) {
        return {
          action: 'collaborate',
          reasoning: '数据需要清洗,需要数据清洗器协作',
          collaborationWith: ['data-cleaner'],
          plan: {
            steps: [
              { action: '获取原始数据', expectedOutcome: '原始数据' },
              { action: '请求清洗协作', expectedOutcome: '清洗后数据' }
            ],
            estimatedTime: 10000,
            requiredResources: ['网络连接', '数据清洗器']
          }
        };
      }
      
      return {
        action: 'execute',
        reasoning: '简单获取任务,可直接执行',
        plan: {
          steps: [
            { action: '请求数据', expectedOutcome: '原始数据' }
          ],
          estimatedTime: 3000,
          requiredResources: ['网络连接']
        }
      };
    }
    
    // 不知道怎么处理,问人
    return {
      action: 'ask_human',
      reasoning: '任务类型不在我的能力范围内',
      humanQuestion: `我收到了一个"${task.type}"类型的任务,这不在我的能力范围内。您希望我如何处理?`
    };
  }
  
  async requestCollaboration(task: Task, targetAgent: string): Promise<void> {
    // 发送协作请求
    console.log(`[${this.name}] 向 ${targetAgent} 发送协作请求`);
  }
  
  async respondToCollaboration(request: CollaborationRequest): Promise<CollaborationResponse> {
    // 检查能否帮助
    const canHelp = this.capabilities.some(c => 
      request.whatINeed.toLowerCase().includes(c.toLowerCase())
    );
    
    if (canHelp) {
      return {
        accepted: true,
        reason: '这个请求在我能力范围内',
        proposedContribution: '我可以提供数据获取支持'
      };
    }
    
    return {
      accepted: false,
      reason: '这个请求超出了我的能力边界'
    };
  }
  
  async learn(experience: Experience): Promise<void> {
    // 学习:记录什么情况下成功/失败
    console.log(`[${this.name}] 学习经验: ${experience.outcome}`);
  }
  
  async communicate(message: string): Promise<string> {
    // 与人沟通
    return `[信息源订阅者] 收到您的消息: "${message}"。我目前订阅了 ${this.subscriptions.size} 个数据源。`;
  }
}

/**
 * 数据清洗器 - 只负责数据预处理
 */
class DataCleaner implements IAgent {
  id = 'data-cleaner';
  name = '数据清洗器';
  description = '专门负责数据预处理、清洗、标准化';
  
  capabilities = [
    '去除重复数据',
    '过滤无效内容',
    '格式标准化',
    '提取关键字段',
    '数据去噪'
  ];
  
  limitations = [
    '不判断数据价值',
    '不做业务逻辑处理',
    '不存储数据'
  ];
  
  async canHandle(task: Task): Promise<boolean> {
    return task.type === 'clean' || task.type === 'preprocess';
  }
  
  async decide(task: Task): Promise<Decision> {
    return {
      action: 'execute',
      reasoning: '数据清洗是我擅长的',
      plan: {
        steps: [
          { action: '分析数据结构', expectedOutcome: '数据结构报告' },
          { action: '应用清洗规则', expectedOutcome: '清洗后数据' },
          { action: '验证结果', expectedOutcome: '质量报告' }
        ],
        estimatedTime: 2000,
        requiredResources: ['内存']
      }
    };
  }
  
  async requestCollaboration(task: Task, targetAgent: string): Promise<void> {
    console.log(`[${this.name}] 向 ${targetAgent} 发送协作请求`);
  }
  
  async respondToCollaboration(request: CollaborationRequest): Promise<CollaborationResponse> {
    return {
      accepted: true,
      reason: '可以协助清洗数据',
      proposedContribution: '提供数据清洗服务'
    };
  }
  
  async learn(experience: Experience): Promise<void> {
    console.log(`[${this.name}] 学习经验: ${experience.outcome}`);
  }
  
  async communicate(message: string): Promise<string> {
    return `[数据清洗器] 收到: "${message}"。我可以帮您清洗和标准化数据。`;
  }
}

/**
 * 模式识别器 - 只负责发现规律
 */
class PatternRecognizer implements IAgent {
  id = 'pattern-recognizer';
  name = '模式识别器';
  description = '专门负责从数据中发现规律、模式、趋势';
  
  capabilities = [
    '识别数据模式',
    '发现异常点',
    '预测趋势',
    '聚类分析',
    '关联分析'
  ];
  
  limitations = [
    '不做决策建议',
    '不执行行动',
    '不与人直接交互'
  ];
  
  async canHandle(task: Task): Promise<boolean> {
    return task.type === 'analyze' || task.type === 'recognize' || task.type === 'predict';
  }
  
  async decide(task: Task): Promise<Decision> {
    // 如果需要更多数据,主动请求协作
    if (!task.content.data || task.content.data.length < 10) {
      return {
        action: 'collaborate',
        reasoning: '数据量不足,需要更多信息源订阅者协作获取更多数据',
        collaborationWith: ['data-source-subscriber']
      };
    }
    
    return {
      action: 'execute',
      reasoning: '数据充足,可以开始模式识别',
      plan: {
        steps: [
          { action: '数据预处理', expectedOutcome: '标准化数据' },
          { action: '模式检测', expectedOutcome: '发现的模式列表' },
          { action: '置信度评估', expectedOutcome: '模式置信度' }
        ],
        estimatedTime: 5000,
        requiredResources: ['计算资源']
      }
    };
  }
  
  async requestCollaboration(task: Task, targetAgent: string): Promise<void> {
    console.log(`[${this.name}] 向 ${targetAgent} 发送协作请求`);
  }
  
  async respondToCollaboration(request: CollaborationRequest): Promise<CollaborationResponse> {
    return {
      accepted: true,
      reason: '可以协助分析模式',
      proposedContribution: '提供模式识别结果'
    };
  }
  
  async learn(experience: Experience): Promise<void> {
    console.log(`[${this.name}] 学习经验: ${experience.outcome}`);
  }
  
  async communicate(message: string): Promise<string> {
    return `[模式识别器] 收到: "${message}"。我可以帮您发现数据中的模式。`;
  }
}

/**
 * 决策生成器 - 只负责给行动建议
 */
class DecisionGenerator implements IAgent {
  id = 'decision-generator';
  name = '决策生成器';
  description = '专门负责基于分析结果给出行动建议';
  
  capabilities = [
    '生成行动建议',
    '评估风险',
    '优先级排序',
    '方案对比',
    '向人提问'
  ];
  
  limitations = [
    '不执行行动',
    '不收集数据',
    '不分析模式'
  ];
  
  async canHandle(task: Task): Promise<boolean> {
    return task.type === 'decide' || task.type === 'recommend' || task.type === 'prioritize';
  }
  
  async decide(task: Task): Promise<Decision> {
    // 如果信息不足,问人
    if (!task.context || Object.keys(task.context).length === 0) {
      return {
        action: 'ask_human',
        reasoning: '缺乏决策所需的上下文信息',
        humanQuestion: '为了给出更好的建议,我需要了解更多背景信息。您能告诉我这个决策的重要性和时间紧迫性吗?'
      };
    }
    
    return {
      action: 'execute',
      reasoning: '信息充足,可以生成决策建议',
      plan: {
        steps: [
          { action: '分析上下文', expectedOutcome: '上下文理解' },
          { action: '生成候选方案', expectedOutcome: '方案列表' },
          { action: '评估和排序', expectedOutcome: '推荐方案' }
        ],
        estimatedTime: 3000,
        requiredResources: ['上下文信息']
      }
    };
  }
  
  async requestCollaboration(task: Task, targetAgent: string): Promise<void> {
    console.log(`[${this.name}] 向 ${targetAgent} 发送协作请求`);
  }
  
  async respondToCollaboration(request: CollaborationRequest): Promise<CollaborationResponse> {
    return {
      accepted: true,
      reason: '可以协助生成决策建议',
      proposedContribution: '提供行动建议'
    };
  }
  
  async learn(experience: Experience): Promise<void> {
    console.log(`[${this.name}] 学习经验: ${experience.outcome}`);
  }
  
  async communicate(message: string): Promise<string> {
    return `[决策生成器] 收到: "${message}"。我可以帮您分析选项并给出建议。`;
  }
}

// ==================== 智能体协作网络 ====================

/**
 * 智能体协作网络 - 去中心化
 */
class AgentNetwork {
  private agents: Map<string, IAgent> = new Map();
  private taskQueue: Task[] = [];
  private collaborationHistory: CollaborationRequest[] = [];
  
  // 注册智能体
  register(agent: IAgent): void {
    this.agents.set(agent.id, agent);
    console.log(`[网络] 注册智能体: ${agent.name}`);
  }
  
  // 动态加载能力(能力组合)
  loadCapability(capability: IAgent): void {
    this.register(capability);
  }
  
  // 提交任务(可以来自人或智能体)
  async submitTask(task: Task): Promise<void> {
    console.log(`[网络] 收到任务: ${task.type}`);
    
    // 找到能处理的智能体
    const capableAgents: IAgent[] = [];
    
    for (const agent of this.agents.values()) {
      if (await agent.canHandle(task)) {
        capableAgents.push(agent);
      }
    }
    
    if (capableAgents.length === 0) {
      console.log(`[网络] 没有智能体能处理这个任务,需要人工介入`);
      return;
    }
    
    // 让智能体自主决策
    for (const agent of capableAgents) {
      const decision = await agent.decide(task);
      console.log(`[网络] ${agent.name} 决策: ${decision.action}`);
      console.log(`       原因: ${decision.reasoning}`);
      
      // 根据决策执行
      await this.executeDecision(agent, decision, task);
    }
  }
  
  // 执行决策
  private async executeDecision(agent: IAgent, decision: Decision, task: Task): Promise<void> {
    switch (decision.action) {
      case 'execute':
        console.log(`[网络] ${agent.name} 开始执行任务`);
        // 执行...
        break;
        
      case 'delegate':
        console.log(`[网络] ${agent.name} 委托给 ${decision.delegateTo}`);
        const delegate = this.agents.get(decision.delegateTo!);
        if (delegate) {
          await this.submitTask({ ...task, createdBy: 'agent' });
        }
        break;
        
      case 'collaborate':
        console.log(`[网络] ${agent.name} 请求协作: ${decision.collaborationWith}`);
        for (const targetId of decision.collaborationWith || []) {
          const target = this.agents.get(targetId);
          if (target) {
            const response = await target.respondToCollaboration({
              from: agent.id,
              to: targetId,
              task,
              reason: decision.reasoning,
              whatINeed: '数据处理支持'
            });
            console.log(`[网络] ${target.name} 响应: ${response.accepted ? '接受' : '拒绝'}`);
          }
        }
        break;
        
      case 'ask_human':
        console.log(`[网络] ${agent.name} 需要人工介入`);
        console.log(`       问题: ${decision.humanQuestion}`);
        break;
        
      case 'reject':
        console.log(`[网络] ${agent.name} 拒绝处理: ${decision.reasoning}`);
        break;
    }
  }
  
  // 人机对话
  async chat(agentId: string, message: string): Promise<string> {
    const agent = this.agents.get(agentId);
    if (!agent) {
      return '找不到这个智能体';
    }
    return await agent.communicate(message);
  }
}

// ==================== 导出 ====================

export {
  IAgent,
  Task,
  Decision,
  Experience,
  CollaborationRequest,
  CollaborationResponse,
  DataSourceSubscriber,
  DataCleaner,
  PatternRecognizer,
  DecisionGenerator,
  AgentNetwork
};

```

### scripts/core/memory-v2.ts

```typescript
/**
 * 统一记忆系统 V2 - 改进版
 * 
 * 改进点:
 * 1. 场景化改造 - 每个场景有自己的记忆空间和规则
 * 2. 元数据化 - 增加来源可信度、上下文指纹、结果追踪
 * 3. 双向验证 - 实现反馈闭环
 */

import * as fs from 'fs';
import * as path from 'path';

// ==================== 类型定义 ====================

type MemoryLevel = 'L0' | 'L1' | 'L2' | 'L3' | 'L4';
type MemoryCategory = 'task' | 'rule' | 'insight' | 'pattern' | 'methodology' | 'worldview' | 'goal' | 'value' | 'wisdom';
type SystemType = 'signal' | 'workflow' | 'goal' | 'shared';

// 场景类型
type ScenarioType = 'duty' | 'sentiment' | 'workflow' | 'goal' | 'general';

// 🆕 记忆元数据
interface MemoryMetadata {
  // 来源信息
  source: SystemType;                    // 来源系统
  sourceCredibility: number;             // 来源可信度 0-1
  
  // 上下文指纹
  contextFingerprint: {
    timestamp: string;                   // 时间戳
    scenario: ScenarioType;              // 场景类型
    environment?: Record<string, any>;   // 环境参数
  };
  
  // 结果追踪
  resultTracking: Array<{
    usedAt: string;                      // 使用时间
    scenario: ScenarioType;              // 使用场景
    effect: 'success' | 'failure' | 'neutral';  // 效果
    feedback?: string;                   // 反馈说明
  }>;
  
  // 统计信息
  stats: {
    accessCount: number;                 // 访问次数
    successRate: number;                 // 成功率
    lastUsedAt: string;                  // 最后使用时间
  };
}

// 🆕 改进后的记忆条目
interface MemoryEntryV2 {
  id: string;
  level: MemoryLevel;
  category: MemoryCategory;
  key: string;
  value: string | object;
  tags: string[];
  importance: number;
  
  // 🆕 元数据
  metadata: MemoryMetadata;
  
  createdAt: string;
  accessedAt: string;
}

// 🆕 场景配置
interface ScenarioConfig {
  name: ScenarioType;
  description: string;
  
  // 记忆压缩规则
  compressionRules: {
    // 什么信息需要压缩到中期记忆
    shouldCompress: (entry: MemoryEntryV2) => boolean;
    // 压缩时保留哪些信息
    preserveFields: string[];
  };
  
  // 模式提炼规则
  extractionRules: {
    // 什么信息需要提炼为长期记忆
    shouldExtract: (entries: MemoryEntryV2[]) => boolean;
    // 如何提炼模式
    extractPattern: (entries: MemoryEntryV2[]) => object;
  };
  
  // 领域约束(用于语义检索)
  domainConstraints: {
    // 相关性判断
    isRelevant: (query: string, entry: MemoryEntryV2) => boolean;
    // 优先级调整
    adjustPriority: (entry: MemoryEntryV2, context: any) => number;
  };
}

// 🆕 记忆配置
interface MemoryConfigV2 {
  // 基础配置
  L0_MAX_ITEMS: number;
  L1_MAX_LINES: number;
  L2_MAX_ENTRIES: number;
  L3_MAX_ENTRIES: number;
  
  // 🆕 场景配置
  scenarios: Record<ScenarioType, ScenarioConfig>;
  
  // 🆕 遗忘机制
  forgetting: {
    // 遗忘阈值
    threshold: number;
    // 时间衰减系数
    decayRate: number;
    // 清理周期(毫秒)
    cleanupInterval: number;
  };
  
  // 🆕 反馈机制
  feedback: {
    // 成功时增加的重要性
    successBonus: number;
    // 失败时减少的重要性
    failurePenalty: number;
    // 最小重要性
    minImportance: number;
  };
}

// ==================== 默认场景配置 ====================

const DEFAULT_SCENARIO_CONFIGS: Record<ScenarioType, ScenarioConfig> = {
  // 值班场景
  duty: {
    name: 'duty',
    description: '节假日值班热点监测场景',
    
    compressionRules: {
      shouldCompress: (entry) => {
        // S级、A级热点需要压缩
        return entry.tags.includes('S级') || entry.tags.includes('A级');
      },
      preserveFields: ['title', 'level', 'score', 'source', 'action']
    },
    
    extractionRules: {
      shouldExtract: (entries) => {
        // 同类热点出现3次以上,提炼模式
        return entries.length >= 3;
      },
      extractPattern: (entries) => {
        return {
          pattern: '热点模式',
          frequency: entries.length,
          avgScore: entries.reduce((sum, e) => sum + (e.importance || 0), 0) / entries.length
        };
      }
    },
    
    domainConstraints: {
      isRelevant: (query, entry) => {
        // 值班场景:关注热点、舆情、事件
        const keywords = ['热点', '舆情', '事件', '异常', '报警'];
        return keywords.some(k => query.includes(k) || entry.key.includes(k));
      },
      adjustPriority: (entry, context) => {
        // 如果是当前值班时间,提高优先级
        if (context.isOnDuty) return entry.importance * 1.2;
        return entry.importance;
      }
    }
  },
  
  // 舆情场景
  sentiment: {
    name: 'sentiment',
    description: '舆情监测场景',
    
    compressionRules: {
      shouldCompress: (entry) => {
        // 负面舆情、高热度需要压缩
        return entry.tags.includes('负面') || entry.importance >= 4;
      },
      preserveFields: ['topic', 'sentiment', 'heat', 'source']
    },
    
    extractionRules: {
      shouldExtract: (entries) => entries.length >= 5,
      extractPattern: (entries) => ({
        pattern: '舆情模式',
        topics: [...new Set(entries.map(e => e.key))]
      })
    },
    
    domainConstraints: {
      isRelevant: (query, entry) => {
        const keywords = ['舆情', '负面', '正面', '热度', '传播'];
        return keywords.some(k => query.includes(k) || entry.key.includes(k));
      },
      adjustPriority: (entry, context) => entry.importance
    }
  },
  
  // 工作流场景
  workflow: {
    name: 'workflow',
    description: '工作流资产沉淀场景',
    
    compressionRules: {
      shouldCompress: (entry) => entry.category === 'insight' || entry.category === 'pattern',
      preserveFields: ['operation', 'experience', 'decision', 'value']
    },
    
    extractionRules: {
      shouldExtract: (entries) => entries.length >= 3,
      extractPattern: (entries) => ({
        pattern: '方法论',
        steps: entries.map(e => e.key)
      })
    },
    
    domainConstraints: {
      isRelevant: (query, entry) => {
        const keywords = ['方法', '流程', '经验', '技巧', '决策'];
        return keywords.some(k => query.includes(k) || entry.key.includes(k));
      },
      adjustPriority: (entry, context) => entry.importance
    }
  },
  
  // 目标场景
  goal: {
    name: 'goal',
    description: '个人目标追踪场景',
    
    compressionRules: {
      shouldCompress: (entry) => entry.category === 'goal' || entry.importance >= 4,
      preserveFields: ['goal', 'progress', 'deadline', 'motivation']
    },
    
    extractionRules: {
      shouldExtract: (entries) => entries.length >= 2,
      extractPattern: (entries) => ({
        pattern: '目标模式',
        goals: entries.map(e => e.key)
      })
    },
    
    domainConstraints: {
      isRelevant: (query, entry) => {
        const keywords = ['目标', '进度', '动机', '精力', '盲点'];
        return keywords.some(k => query.includes(k) || entry.key.includes(k));
      },
      adjustPriority: (entry, context) => entry.importance
    }
  },
  
  // 通用场景
  general: {
    name: 'general',
    description: '通用场景',
    
    compressionRules: {
      shouldCompress: (entry) => entry.importance >= 3,
      preserveFields: ['key', 'value', 'tags']
    },
    
    extractionRules: {
      shouldExtract: (entries) => entries.length >= 5,
      extractPattern: (entries) => ({ pattern: '通用模式', count: entries.length })
    },
    
    domainConstraints: {
      isRelevant: (query, entry) => true,
      adjustPriority: (entry, context) => entry.importance
    }
  }
};

// ==================== 默认配置 ====================

const DEFAULT_CONFIG_V2: MemoryConfigV2 = {
  L0_MAX_ITEMS: 10,
  L1_MAX_LINES: 50,
  L2_MAX_ENTRIES: 200,
  L3_MAX_ENTRIES: 1000,
  
  scenarios: DEFAULT_SCENARIO_CONFIGS,
  
  forgetting: {
    threshold: 0.3,
    decayRate: 0.1,
    cleanupInterval: 24 * 60 * 60 * 1000  // 24小时
  },
  
  feedback: {
    successBonus: 0.1,
    failurePenalty: 0.2,
    minImportance: 0.1
  }
};

// ==================== 记忆系统 V2 ====================

export class UnifiedMemorySystemV2 {
  private skillName: string;
  private baseDir: string;
  private config: MemoryConfigV2;
  
  // 🆕 当前场景
  private currentScenario: ScenarioType = 'general';
  
  // 🆕 场景记忆空间
  private scenarioMemories: Map<ScenarioType, {
    L0: Map<string, any>;
    L1: MemoryEntryV2[];
    L2: MemoryEntryV2[];
    L3: MemoryEntryV2[];
    L4: MemoryEntryV2[];
  }>;
  
  // L0 闪存
  private flashMemory: Map<string, any> = new Map();
  private context: string = '';
  
  // L1 工作记忆
  private workingMemory: MemoryEntryV2[] = [];
  
  // L2 经验记忆
  private experienceMemory: MemoryEntryV2[] = [];
  
  // L3 知识记忆
  private knowledgeMemory: {
    worldviews: MemoryEntryV2[];
    methodologies: MemoryEntryV2[];
    patterns: MemoryEntryV2[];
    goals: MemoryEntryV2[];
  } = { worldviews: [], methodologies: [], patterns: [], goals: [] };
  
  // L4 智慧记忆
  private wisdomMemory: {
    insights: MemoryEntryV2[];
    values: MemoryEntryV2[];
  } = { insights: [], values: [] };
  
  // 跨系统共享
  private sharedMemory: MemoryEntryV2[] = [];
  
  constructor(skillName: string = 'ai_system', baseDir: string = 'memory', config?: Partial<MemoryConfigV2>) {
    this.skillName = skillName;
    this.baseDir = baseDir;
    this.config = { ...DEFAULT_CONFIG_V2, ...config };
    
    // 🆕 初始化场景记忆空间
    this.scenarioMemories = new Map();
    Object.keys(this.config.scenarios).forEach(scenario => {
      this.scenarioMemories.set(scenario as ScenarioType, {
        L0: new Map(),
        L1: [],
        L2: [],
        L3: [],
        L4: []
      });
    });
    
    this.initializeDirectories();
    this.loadFromDisk();
    
    // 🆕 启动定期清理
    this.startPeriodicCleanup();
  }
  
  // ==================== 初始化 ====================
  
  private initializeDirectories(): void {
    const dirs = [
      'L0_flash', 'L1_working', 'L2_experience',
      'L3_knowledge', 'L4_wisdom', 'shared', 'logs'
    ];
    
    dirs.forEach(dir => {
      const fullPath = path.join(this.baseDir, this.skillName, dir);
      if (!fs.existsSync(fullPath)) {
        fs.mkdirSync(fullPath, { recursive: true });
      }
    });
  }
  
  private loadFromDisk(): void {
    // 加载逻辑(简化)
    console.log(`[MemoryV2] 加载记忆: ${this.skillName}`);
  }
  
  private saveToDisk(): void {
    // 保存逻辑(简化)
    console.log(`[MemoryV2] 保存记忆: ${this.skillName}`);
  }
  
  // ==================== 🆕 场景管理 ====================
  
  /**
   * 设置当前场景
   */
  setScenario(scenario: ScenarioType): void {
    if (!this.config.scenarios[scenario]) {
      console.warn(`[MemoryV2] 未知场景: ${scenario},使用通用场景`);
      this.currentScenario = 'general';
    } else {
      this.currentScenario = scenario;
      console.log(`[MemoryV2] 切换场景: ${scenario}`);
    }
  }
  
  /**
   * 获取当前场景
   */
  getScenario(): ScenarioType {
    return this.currentScenario;
  }
  
  /**
   * 获取场景配置
   */
  getScenarioConfig(scenario?: ScenarioType): ScenarioConfig {
    return this.config.scenarios[scenario || this.currentScenario];
  }
  
  /**
   * 注册自定义场景
   */
  registerScenario(config: ScenarioConfig): void {
    this.config.scenarios[config.name] = config;
    this.scenarioMemories.set(config.name, {
      L0: new Map(),
      L1: [],
      L2: [],
      L3: [],
      L4: []
    });
    console.log(`[MemoryV2] 注册场景: ${config.name}`);
  }
  
  // ==================== 🆕 元数据管理 ====================
  
  /**
   * 创建记忆元数据
   */
  private createMetadata(source: SystemType = 'shared'): MemoryMetadata {
    return {
      source,
      sourceCredibility: this.getSourceCredibility(source),
      contextFingerprint: {
        timestamp: new Date().toISOString(),
        scenario: this.currentScenario,
        environment: {}
      },
      resultTracking: [],
      stats: {
        accessCount: 0,
        successRate: 1.0,
        lastUsedAt: new Date().toISOString()
      }
    };
  }
  
  /**
   * 获取来源可信度
   */
  private getSourceCredibility(source: SystemType): number {
    const credibility: Record<SystemType, number> = {
      'signal': 0.85,
      'workflow': 0.80,
      'goal': 0.75,
      'shared': 0.70
    };
    return credibility[source] || 0.70;
  }
  
  /**
   * 🆕 记录使用效果(双向验证)
   */
  recordUsage(entryId: string, effect: 'success' | 'failure' | 'neutral', feedback?: string): void {
    const entry = this.findEntryById(entryId);
    if (!entry) {
      console.warn(`[MemoryV2] 未找到记忆条目: ${entryId}`);
      return;
    }
    
    // 记录结果追踪
    entry.metadata.resultTracking.push({
      usedAt: new Date().toISOString(),
      scenario: this.currentScenario,
      effect,
      feedback
    });
    
    // 更新统计信息
    entry.metadata.stats.accessCount++;
    entry.metadata.stats.lastUsedAt = new Date().toISOString();
    
    // 根据效果调整重要性
    if (effect === 'success') {
      entry.importance = Math.min(5, entry.importance + this.config.feedback.successBonus);
      entry.metadata.stats.successRate = this.calculateSuccessRate(entry);
    } else if (effect === 'failure') {
      entry.importance = Math.max(
        this.config.feedback.minImportance,
        entry.importance - this.config.feedback.failurePenalty
      );
      entry.metadata.stats.successRate = this.calculateSuccessRate(entry);
    }
    
    console.log(`[MemoryV2] 记录使用效果: ${entryId} -> ${effect}, 重要性: ${entry.importance.toFixed(2)}`);
  }
  
  /**
   * 计算成功率
   */
  private calculateSuccessRate(entry: MemoryEntryV2): number {
    const tracking = entry.metadata.resultTracking;
    if (tracking.length === 0) return 1.0;
    
    const successCount = tracking.filter(t => t.effect === 'success').length;
    return successCount / tracking.length;
  }
  
  /**
   * 根据ID查找记忆条目
   */
  private findEntryById(id: string): MemoryEntryV2 | null {
    // 在各层记忆中查找
    const allEntries = [
      ...this.workingMemory,
      ...this.experienceMemory,
      ...this.knowledgeMemory.worldviews,
      ...this.knowledgeMemory.methodologies,
      ...this.knowledgeMemory.patterns,
      ...this.knowledgeMemory.goals,
      ...this.wisdomMemory.insights,
      ...this.wisdomMemory.values
    ];
    
    return allEntries.find(e => e.id === id) || null;
  }
  
  // ==================== 🆕 智能检索 ====================
  
  /**
   * 智能检索(语义相似度 + 领域约束)
   */
  smartQuery(query: string, options?: {
    scenario?: ScenarioType;
    minCredibility?: number;
    minSuccessRate?: number;
    maxAge?: number;
  }): MemoryEntryV2[] {
    const scenario = options?.scenario || this.currentScenario;
    const scenarioConfig = this.config.scenarios[scenario];
    
    // 获取所有相关记忆
    const allEntries = this.getAllEntries();
    
    // 过滤和排序
    let results = allEntries.filter(entry => {
      // 1. 领域约束
      if (!scenarioConfig.domainConstraints.isRelevant(query, entry)) {
        return false;
      }
      
      // 2. 可信度过滤
      if (options?.minCredibility && entry.metadata.sourceCredibility < options.minCredibility) {
        return false;
      }
      
      // 3. 成功率过滤
      if (options?.minSuccessRate && entry.metadata.stats.successRate < options.minSuccessRate) {
        return false;
      }
      
      // 4. 时间过滤
      if (options?.maxAge) {
        const age = (Date.now() - new Date(entry.createdAt).getTime()) / (24 * 60 * 60 * 1000);
        if (age > options.maxAge) return false;
      }
      
      return true;
    });
    
    // 排序:综合评分 = 重要性 × 可信度 × 成功率 × 时间衰减
    results.sort((a, b) => {
      const scoreA = this.calculateEntryScore(a, query, scenario);
      const scoreB = this.calculateEntryScore(b, query, scenario);
      return scoreB - scoreA;
    });
    
    return results;
  }
  
  /**
   * 计算记忆条目综合评分
   */
  private calculateEntryScore(entry: MemoryEntryV2, query: string, scenario: ScenarioType): number {
    const scenarioConfig = this.config.scenarios[scenario];
    
    // 基础分
    let score = entry.importance;
    
    // 可信度加权
    score *= entry.metadata.sourceCredibility;
    
    // 成功率加权
    score *= entry.metadata.stats.successRate;
    
    // 时间衰减
    const ageInDays = (Date.now() - new Date(entry.createdAt).getTime()) / (24 * 60 * 60 * 1000);
    const timeDecay = Math.exp(-this.config.forgetting.decayRate * ageInDays);
    score *= timeDecay;
    
    // 场景优先级调整
    score = scenarioConfig.domainConstraints.adjustPriority(entry, { query });
    
    return score;
  }
  
  /**
   * 获取所有记忆条目
   */
  private getAllEntries(): MemoryEntryV2[] {
    return [
      ...this.workingMemory,
      ...this.experienceMemory,
      ...this.knowledgeMemory.worldviews,
      ...this.knowledgeMemory.methodologies,
      ...this.knowledgeMemory.patterns,
      ...this.knowledgeMemory.goals,
      ...this.wisdomMemory.insights,
      ...this.wisdomMemory.values
    ];
  }
  
  // ==================== 🆕 记忆流动 ====================
  
  /**
   * 执行记忆压缩(短期 → 中期)
   */
  compress(): void {
    const scenarioConfig = this.config.scenarios[this.currentScenario];
    
    // 找出需要压缩的记忆
    const toCompress = this.workingMemory.filter(entry => 
      scenarioConfig.compressionRules.shouldCompress(entry)
    );
    
    // 压缩并移入中期记忆
    toCompress.forEach(entry => {
      // 创建压缩后的条目
      const compressed: MemoryEntryV2 = {
        ...entry,
        level: 'L2',
        value: this.compressValue(entry, scenarioConfig.compressionRules.preserveFields)
      };
      
      this.experienceMemory.push(compressed);
      
      // 从工作记忆中移除
      const index = this.workingMemory.indexOf(entry);
      if (index > -1) {
        this.workingMemory.splice(index, 1);
      }
    });
    
    console.log(`[MemoryV2] 压缩 ${toCompress.length} 条记忆到中期记忆`);
  }
  
  /**
   * 压缩记忆值
   */
  private compressValue(entry: MemoryEntryV2, preserveFields: string[]): any {
    if (typeof entry.value === 'string') {
      return entry.value;
    }
    
    const compressed: any = {};
    preserveFields.forEach(field => {
      if ((entry.value as any)[field] !== undefined) {
        compressed[field] = (entry.value as any)[field];
      }
    });
    
    return compressed;
  }
  
  /**
   * 执行模式提炼(中期 → 长期)
   */
  extract(): void {
    const scenarioConfig = this.config.scenarios[this.currentScenario];
    
    // 按类别分组
    const grouped = this.groupEntriesByKey(this.experienceMemory);
    
    // 对每组进行模式提炼
    Object.entries(grouped).forEach(([key, entries]) => {
      if (scenarioConfig.extractionRules.shouldExtract(entries)) {
        const pattern = scenarioConfig.extractionRules.extractPattern(entries);
        
        // 创建长期记忆条目
        const extracted: MemoryEntryV2 = {
          id: this.generateId(),
          level: 'L3',
          category: 'pattern',
          key: `模式_${key}`,
          value: pattern,
          tags: ['extracted', 'pattern'],
          importance: Math.max(...entries.map(e => e.importance)),
          metadata: this.createMetadata('shared'),
          createdAt: new Date().toISOString(),
          accessedAt: new Date().toISOString()
        };
        
        this.knowledgeMemory.patterns.push(extracted);
        console.log(`[MemoryV2] 提炼模式: ${key}`);
      }
    });
  }
  
  /**
   * 按键分组
   */
  private groupEntriesByKey(entries: MemoryEntryV2[]): Record<string, MemoryEntryV2[]> {
    const grouped: Record<string, MemoryEntryV2[]> = {};
    
    entries.forEach(entry => {
      const key = entry.key.split('_')[0]; // 取前缀作为分组键
      if (!grouped[key]) grouped[key] = [];
      grouped[key].push(entry);
    });
    
    return grouped;
  }
  
  // ==================== 🆕 遗忘机制 ====================
  
  /**
   * 启动定期清理
   */
  private startPeriodicCleanup(): void {
    setInterval(() => {
      this.cleanup();
    }, this.config.forgetting.cleanupInterval);
  }
  
  /**
   * 清理低价值记忆
   */
  cleanup(): void {
    const threshold = this.config.forgetting.threshold;
    
    // 清理经验记忆
    const beforeL2 = this.experienceMemory.length;
    this.experienceMemory = this.experienceMemory.filter(entry => {
      const score = this.calculateEntryScore(entry, '', this.currentScenario);
      return score >= threshold;
    });
    
    // 清理知识记忆
    const beforeL3 = this.knowledgeMemory.patterns.length;
    this.knowledgeMemory.patterns = this.knowledgeMemory.patterns.filter(entry => {
      const score = this.calculateEntryScore(entry, '', this.currentScenario);
      return score >= threshold;
    });
    
    console.log(`[MemoryV2] 清理: L2 ${beforeL2 - this.experienceMemory.length}条, L3 ${beforeL3 - this.knowledgeMemory.patterns.length}条`);
  }
  
  // ==================== 基础操作 ====================
  
  /**
   * 添加到L1工作记忆
   */
  addToL1(key: string, value: string, category: MemoryCategory, importance: number = 3, source: SystemType = 'shared'): void {
    const entry: MemoryEntryV2 = {
      id: this.generateId(),
      level: 'L1',
      category,
      key,
      value,
      tags: [],
      importance,
      metadata: this.createMetadata(source),
      createdAt: new Date().toISOString(),
      accessedAt: new Date().toISOString()
    };
    
    this.workingMemory.push(entry);
    
    // 检查是否需要压缩
    if (this.workingMemory.length >= this.config.L1_MAX_LINES) {
      this.compress();
    }
  }
  
  /**
   * 添加到L2经验记忆
   */
  addToL2(key: string, value: string | object, category: MemoryCategory, importance: number, tags: string[] = [], source: SystemType = 'shared'): void {
    const entry: MemoryEntryV2 = {
      id: this.generateId(),
      level: 'L2',
      category,
      key,
      value,
      tags,
      importance,
      metadata: this.createMetadata(source),
      createdAt: new Date().toISOString(),
      accessedAt: new Date().toISOString()
    };
    
    this.experienceMemory.push(entry);
    
    // 检查是否需要提炼
    if (this.experienceMemory.length >= this.config.L2_MAX_ENTRIES * 0.8) {
      this.extract();
    }
  }
  
  /**
   * 生成ID
   */
  private generateId(): string {
    return Math.random().toString(36).substring(2, 10);
  }
  
  // ==================== 其他方法 ====================
  
  setVariable(key: string, value: any): void {
    this.flashMemory.set(key, value);
  }
  
  getVariable(key: string): any {
    return this.flashMemory.get(key);
  }
  
  setContext(context: string): void {
    this.context = context;
  }
  
  getContext(): string {
    return this.context;
  }
  
  /**
   * 获取系统摘要
   */
  getSummary(): string {
    return `
=== 统一记忆系统 V2 摘要 ===
技能名称: ${this.skillName}
当前场景: ${this.currentScenario}
最后更新: ${new Date().toISOString()}

【L0闪存】变量数: ${this.flashMemory.size}/${this.config.L0_MAX_ITEMS}
【L1工作记忆】条目数: ${this.workingMemory.length}/${this.config.L1_MAX_LINES}
【L2经验记忆】条目数: ${this.experienceMemory.length}/${this.config.L2_MAX_ENTRIES}
【L3知识记忆】模式: ${this.knowledgeMemory.patterns.length}条
【L4智慧记忆】洞察: ${this.wisdomMemory.insights.length}条

场景配置: ${Object.keys(this.config.scenarios).join(', ')}
    `.trim();
  }
  
  /**
   * 健康检查
   */
  healthCheck(): any {
    return {
      status: 'OK',
      scenario: this.currentScenario,
      levels: {
        L0: { usage: `${this.flashMemory.size}/${this.config.L0_MAX_ITEMS}`, status: 'OK' },
        L1: { usage: `${this.workingMemory.length}/${this.config.L1_MAX_LINES}`, status: 'OK' },
        L2: { usage: `${this.experienceMemory.length}/${this.config.L2_MAX_ENTRIES}`, status: 'OK' },
        L3: { usage: `${this.knowledgeMemory.patterns.length}`, status: 'OK' },
        L4: { usage: `${this.wisdomMemory.insights.length}`, status: 'OK' }
      }
    };
  }
}

export default UnifiedMemorySystemV2;

```

### scripts/core/memory.ts

```typescript
/**
 * 统一记忆系统 V1.4 - 完整升级版
 * 在原始V1.0基础上增量升级
 * 
 * V1.1: 意图识别 + 智能路由
 * V1.2: 反思机制
 * V1.3: 主动感知
 * V1.4: 用户自适应
 * 
 * 五层记忆架构:L0闪存/L1工作/L2经验/L3知识/L4智慧
 */

import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';

// ========== V1.0 原始类型定义 ==========

export type MemoryLevel = 'L0' | 'L1' | 'L2' | 'L3' | 'L4';
export type MemoryCategory = 'task' | 'rule' | 'insight' | 'pattern' | 'methodology' | 'worldview' | 'goal' | 'value' | 'wisdom';
export type SystemType = 'signal' | 'workflow' | 'goal' | 'shared';

// V1.2新增:信号等级
export type SignalLevel = 'noise' | 'signal' | 'core' | 'meta';

// V1.2新增:时间敏感度
export type TimeSensitivity = 'immediate' | 'continuous' | 'delayed' | 'cyclical' | 'meta';

// V1.2新增:影响深度
export type ImpactDepth = 'tool' | 'method' | 'strategy' | 'cognition' | 'worldview';

// V1.4新增:用户画像
export interface UserProfile {
  user_id: string;
  confirmation_habit: {
    total_decisions: number;
    skip_count: number;
    skip_rate: number;
    avg_decision_time_ms: number;
  };
  output_preference: {
    detailed_count: number;
    concise_count: number;
    preferred_style: 'detailed' | 'concise' | 'balanced';
  };
  recommendation: {
    total: number;
    accepted: number;
    acceptance_rate: number;
  };
  execution: {
    parallel_count: number;
    serial_count: number;
    preferred_mode: 'parallel' | 'serial';
  };
  module_sequence_history: string[];
  common_paths: string[];
  updated_at: string;
}

// V1.1新增:意图类型
export type IntentType = 'information' | 'content' | 'status' | 'workflow' | 'full' | 'quick';

// V1.1新增:执行模式
export type ExecutionMode = 'serial' | 'parallel' | 'skip' | 'quick';

// V1.1新增:意图识别结果
export interface IntentRecognitionResult {
  intent: IntentType;
  confidence: number;
  target_industry?: string;
  modules: string[];
  mode: ExecutionMode;
  reasoning: string;
}

// V1.2新增:反思评估结果
export interface ReflectionResult {
  completeness: {
    score: number;
    status: 'pass' | 'warning' | 'fail';
  };
  quality: {
    score: number;
    status: 'pass' | 'warning' | 'fail';
  };
  usability: {
    score: number;
    status: 'pass' | 'warning' | 'fail';
  };
  improvements_made: string[];
  retry_count: number;
  final_status: 'pass' | 'warning' | 'fail';
}

// V1.3新增:主动感知结果
export interface ProactivePerceptionResult {
  L0_relevant: boolean;
  L2_similar_task_found: boolean;
  L3_knowledge_found: boolean;
  L4_preference_found: boolean;
  strategy: 'full' | 'incremental' | 'cached';
  estimated_time_saved: number;
  perception_log: string[];
}

// ========== 原始内存条目 ==========

export interface MemoryEntry {
  id: string;
  level: MemoryLevel;
  category: MemoryCategory;
  key: string;
  value: string | object;
  tags: string[];
  importance: number;
  system: SystemType;
  createdAt: string;
  accessedAt: string;
  accessCount: number;
  metadata?: Record<string, any>;
}

export interface MemoryConfig {
  L0_MAX_ITEMS: number;
  L1_MAX_LINES: number;
  L2_MAX_ENTRIES: number;
  L3_MAX_ENTRIES: number;
  AUTO_ARCHIVE_THRESHOLD: number;
  
  // V1.2新增:时间衰减配置
  time_decay?: {
    DEFAULT_MAX_AGE_DAYS: number;
    DECAY_RATES: Record<string, number>;
  };
  
  // V1.3新增:缓存配置
  cache?: {
    ttl_hours: number;
    reuse_bonus: number;
  };
}

export interface AIMirrorInsight {
  observation: string;
  pattern: string;
  blindSpot: string;
  suggestion: string;
  prediction: string;
}

// V1.2新增:信号评估
export interface SignalEvaluation {
  timeSensitivity: TimeSensitivity;
  impactDepth: ImpactDepth;
  actionability: number;
  compoundValue: number;
  level: SignalLevel;
  reason: string;
}

// ========== V1.4 统一记忆系统完整类 ==========

export class UnifiedMemorySystem {
  private skillName: string;
  private baseDir: string;
  private config: MemoryConfig;
  
  // V1.0原始:五层记忆
  private flashMemory: Map<string, any> = new Map();
  private workingMemory: MemoryEntry[] = [];
  private experienceMemory: MemoryEntry[] = [];
  private knowledgeMemory: MemoryEntry[] = [];
  private wisdomMemory: MemoryEntry[] = [];
  
  // V1.1新增:意图识别器
  private intentRecognizer: IntentRecognizer;
  
  // V1.2新增:反思评估器
  private reflectionEngine: ReflectionEngine;
  
  // V1.3新增:主动感知器
  private proactivePerceptor: ProactivePerceptor;
  
  // V1.4新增:用户画像管理器
  private userProfileManager: UserProfileManager;
  
  // V1.2新增:时间衰减配置
  private timeDecayConfig = {
    DEFAULT_MAX_AGE_DAYS: 7,
    DECAY_RATES: {
      '0-1天': 1.0,
      '1-3天': 0.9,
      '3-7天': 0.7,
      '7-14天': 0.4,
      '14天以上': 0.1
    }
  };

  // ========== V1.1新增:意图识别器 ==========
  
  private class IntentRecognizer {
    // 意图关键词映射
    private intentKeywords: Record<IntentType, string[]> = {
      'information': ['最新动态', '行业信息', '看看', '了解', 'news', 'information'],
      'content': ['写文章', '创作', '发布', '内容', 'write', 'create', 'publish'],
      'status': ['分析状态', '我的情况', '成长', '状态', 'status', 'growth', 'progress'],
      'workflow': ['沉淀', '工作流', '模板', '报告', 'workflow', 'template', 'report'],
      'full': ['帮我整理', '做个总结', '完整', 'full', 'complete', 'summary'],
      'quick': ['快速', '精简', '简单', 'quick', 'brief', 'simple']
    };
    
    // 识别意图
    recognize(input: string): IntentRecognitionResult {
      const lowerInput = input.toLowerCase();
      
      // 检测行业关键词
      const industries = ['AI', '人工智能', '金融', '医疗', '教育', '零售', '科技', '新能源汽车'];
      let target_industry = '';
      for (const ind of industries) {
        if (lowerInput.includes(ind.toLowerCase())) {
          target_industry = ind;
          break;
        }
      }
      
      // 识别意图类型
      let intent: IntentType = 'information';
      let maxMatch = 0;
      
      for (const [intentType, keywords] of Object.entries(this.intentKeywords)) {
        let matchCount = 0;
        for (const kw of keywords) {
          if (lowerInput.includes(kw.toLowerCase())) {
            matchCount++;
          }
        }
        if (matchCount > maxMatch) {
          maxMatch = matchCount;
          intent = intentType as IntentType;
        }
      }
      
      // 确定执行模块
      const modules = this.determineModules(intent);
      
      // 确定执行模式
      const mode = this.determineMode(input, intent);
      
      // 计算置信度
      const confidence = Math.min(1, maxMatch * 0.3 + 0.5);
      
      return {
        intent,
        confidence,
        target_industry: target_industry || undefined,
        modules,
        mode,
        reasoning: `识别到${intent}意图,置信度${(confidence*100).toFixed(0)}%`
      };
    }
    
    // 确定执行模块
    private determineModules(intent: IntentType): string[] {
      switch (intent) {
        case 'information': return ['module1'];
        case 'content': return ['module1', 'module2'];
        case 'status': return ['module3'];
        case 'workflow': return ['module4'];
        case 'full': return ['module1', 'module2', 'module3', 'module4'];
        case 'quick': return ['module1'];
        default: return ['module1'];
      }
    }
    
    // 确定执行模式
    private determineMode(input: string, intent: IntentType): ExecutionMode {
      const lowerInput = input.toLowerCase();
      if (lowerInput.includes('并行') || lowerInput.includes('parallel')) return 'parallel';
      if (lowerInput.includes('跳过') || lowerInput.includes('skip')) return 'skip';
      if (lowerInput.includes('快速') || lowerInput.includes('quick') || intent === 'quick') return 'quick';
      return 'serial';
    }
  }

  // ========== V1.2新增:反思引擎 ==========
  
  private class ReflectionEngine {
    // V1.2: 反思评估
    evaluate(output: any): ReflectionResult {
      // 评估完整性
      const completeness = this.evaluateCompleteness(output);
      
      // 评估质量
      const quality = this.evaluateQuality(output);
      
      // 评估可用性
      const usability = this.evaluateUsability(output);
      
      // 尝试改进
      const improvements = this.attemptImprovements(output);
      
      // 最终状态
      const allPass = completeness.status === 'pass' && quality.status === 'pass' && usability.status === 'pass';
      const hasWarning = completeness.status === 'warning' || quality.status === 'warning' || usability.status === 'warning';
      
      return {
        completeness,
        quality,
        usability,
        improvements_made: improvements,
        retry_count: 0,
        final_status: allPass ? 'pass' : (hasWarning ? 'warning' : 'fail')
      };
    }
    
    private evaluateCompleteness(output: any): { score: number; status: 'pass' | 'warning' | 'fail' } {
      // 检查必要字段
      const requiredFields = ['title', 'level', 'source', 'content'];
      let present = 0;
      for (const field of requiredFields) {
        if (output[field] !== undefined) present++;
      }
      const score = present / requiredFields.length;
      return { score, status: score >= 0.8 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
    }
    
    private evaluateQuality(output: any): { score: number; status: 'pass' | 'warning' | 'fail' } {
      // 简单质量评估
      const score = output.qualityScore || 0.7;
      return { score, status: score >= 0.7 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
    }
    
    private evaluateUsability(output: any): { score: number; status: 'pass' | 'warning' | 'fail' } {
      // 可用性评估
      const score = output.usabilityScore || 0.75;
      return { score, status: score >= 0.7 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
    }
    
    private attemptImprovements(output: any): string[] {
      const improvements: string[] = [];
      // 这里可以添加自动改进逻辑
      return improvements;
    }
  }

  // ========== V1.3新增:主动感知器 ==========
  
  private class ProactivePerceptor {
    private memory: UnifiedMemorySystem;
    
    constructor(memory: UnifiedMemorySystem) {
      this.memory = memory;
    }
    
    // V1.3: 主动感知
    perceive(query: string): ProactivePerceptionResult {
      const log: string[] = [];
      
      // 检查L0
      const L0_vars = this.memory.flashMemory;
      const L0_relevant = L0_vars.size > 0;
      if (L0_relevant) log.push('L0: 发现相关任务变量');
      
      // 检查L2相似任务
      const L2_similar = this.memory.experienceMemory.filter(e => 
        e.tags.includes('task') && this.isSimilar(query, e.key)
      );
      const L2_similar_task_found = L2_similar.length > 0;
      if (L2_similar_task_found) log.push(`L2: 发现${L2_similar.length}个相似任务`);
      
      // 检查L3知识
      const L3_knowledge = this.memory.knowledgeMemory.filter(e => 
        this.isSimilar(query, e.key)
      );
      const L3_knowledge_found = L3_knowledge.length > 0;
      if (L3_knowledge_found) log.push(`L3: 发现${L3_knowledge.length}条相关知识`);
      
      // 检查L4偏好
      const L4_preference = this.memory.wisdomMemory.filter(e => 
        e.category === 'value'
      );
      const L4_preference_found = L4_preference.length > 0;
      if (L4_preference_found) log.push(`L4: 发现${L4_preference.length}条用户偏好`);
      
      // 确定策略
      let strategy: 'full' | 'incremental' | 'cached' = 'full';
      let estimated_time_saved = 0;
      
      if (L2_similar_task_found) {
        strategy = 'incremental';
        estimated_time_saved = 50;
      } else if (L3_knowledge_found) {
        strategy = 'incremental';
        estimated_time_saved = 30;
      }
      
      return {
        L0_relevant,
        L2_similar_task_found,
        L3_knowledge_found,
        L4_preference_found,
        strategy,
        estimated_time_saved,
        perception_log: log
      };
    }
    
    private isSimilar(query: string, key: string): boolean {
      const q = query.toLowerCase();
      const k = key.toLowerCase();
      // 简单相似度判断
      return k.includes(q) || q.includes(k);
    }
  }

  // ========== V1.4新增:用户画像管理器 ==========
  
  private class UserProfileManager {
    private profiles: Map<string, UserProfile> = new Map();
    
    // 获取用户画像
    getProfile(userId: string): UserProfile {
      if (!this.profiles.has(userId)) {
        this.profiles.set(userId, this.createDefaultProfile(userId));
      }
      return this.profiles.get(userId)!;
    }
    
    // 创建默认画像
    private createDefaultProfile(userId: string): UserProfile {
      return {
        user_id: userId,
        confirmation_habit: {
          total_decisions: 0,
          skip_count: 0,
          skip_rate: 0.5,
          avg_decision_time_ms: 5000
        },
        output_preference: {
          detailed_count: 0,
          concise_count: 0,
          preferred_style: 'balanced'
        },
        recommendation: {
          total: 0,
          accepted: 0,
          acceptance_rate: 0.5
        },
        execution: {
          parallel_count: 0,
          serial_count: 0,
          preferred_mode: 'serial'
        },
        module_sequence_history: [],
        common_paths: [],
        updated_at: new Date().toISOString()
      };
    }
    
    // 更新用户行为
    updateBehavior(userId: string, action: string, data: any): void {
      const profile = this.getProfile(userId);
      
      switch (action) {
        case 'skip':
          profile.confirmation_habit.skip_count++;
          profile.confirmation_habit.total_decisions++;
          profile.confirmation_habit.skip_rate = 
            profile.confirmation_habit.skip_count / profile.confirmation_habit.total_decisions;
          break;
        case 'prefer_detailed':
          profile.output_preference.detailed_count++;
          profile.output_preference.preferred_style = 'detailed';
          break;
        case 'prefer_concise':
          profile.output_preference.concise_count++;
          profile.output_preference.preferred_style = 'concise';
          break;
        case 'accept_recommendation':
          profile.recommendation.accepted++;
          profile.recommendation.total++;
          profile.recommendation.acceptance_rate = 
            profile.recommendation.accepted / profile.recommendation.total;
          break;
        case 'prefer_parallel':
          profile.execution.parallel_count++;
          profile.execution.preferred_mode = 'parallel';
          break;
      }
      
      profile.updated_at = new Date().toISOString();
      this.profiles.set(userId, profile);
    }
    
    // 自适应调整
    adapt(userId: string): any {
      const profile = this.getProfile(userId);
      
      return {
        skip_unnecessary_confirmations: profile.confirmation_habit.skip_rate > 0.6,
        output_style: profile.output_preference.preferred_style,
        recommend_aggressively: profile.recommendation.acceptance_rate > 0.7,
        prefer_parallel: profile.execution.preferred_mode === 'parallel'
      };
    }
  }

  // ========== 构造函数 ==========

  constructor(skillName: string = 'ai_system', baseDir: string = 'memory', config?: Partial<MemoryConfig>) {
    this.skillName = skillName;
    this.baseDir = baseDir;
    this.config = {
      L0_MAX_ITEMS: 10,
      L1_MAX_LINES: 50,
      L2_MAX_ENTRIES: 200,
      L3_MAX_ENTRIES: 1000,
      AUTO_ARCHIVE_THRESHOLD: 0.8,
      ...config
    };
    
    // 初始化V1.1组件
    this.intentRecognizer = new IntentRecognizer();
    
    // 初始化V1.2组件
    this.reflectionEngine = new ReflectionEngine();
    
    // 初始化V1.3组件
    this.proactivePerceptor = new ProactivePerceptor(this);
    
    // 初始化V1.4组件
    this.userProfileManager = new UserProfileManager();
    
    this.initializeDirectories();
    this.loadFromDisk();
  }

  // ========== V1.0原始方法(保留) ==========

  private initializeDirectories(): void {
    const dirs = [
      'L0_flash', 'L1_working', 'L2_experience',
      'L3_knowledge', 'L4_wisdom', 'shared', 'logs'
    ];
    
    dirs.forEach(dir => {
      const fullPath = path.join(this.baseDir, this.skillName, dir);
      if (!fs.existsSync(fullPath)) {
        fs.mkdirSync(fullPath, { recursive: true });
      }
    });
  }

  private loadFromDisk(): void {
    console.log(`[Memory] 加载记忆: ${this.skillName}`);
  }

  // L0 闪存
  setVariable(key: string, value: any): void {
    this.flashMemory.set(key, value);
  }

  getVariable(key: string): any {
    return this.flashMemory.get(key);
  }

  // L1 工作记忆
  addToL1(key: string, value: string, category: MemoryCategory, importance: number = 3): void {
    const entry: MemoryEntry = {
      id: this.generateId(),
      level: 'L1',
      category,
      key,
      value,
      tags: [],
      importance,
      system: 'shared',
      createdAt: new Date().toISOString(),
      accessedAt: new Date().toISOString(),
      accessCount: 0
    };
    
    this.workingMemory.push(entry);
    
    // 满则归档
    if (this.workingMemory.length >= this.config.L1_MAX_LINES) {
      this.archiveL1ToL2();
    }
  }

  // L2 经验记忆
  addToL2(key: string, value: string | object, category: MemoryCategory, importance: number, tags: string[] = []): void {
    const entry: MemoryEntry = {
      id: this.generateId(),
      level: 'L2',
      category,
      key,
      value,
      tags,
      importance,
      system: 'shared',
      createdAt: new Date().toISOString(),
      accessedAt: new Date().toISOString(),
      accessCount: 0
    };
    
    this.experienceMemory.push(entry);
  }

  // L3 知识记忆
  addToL3(entry: MemoryEntry): void {
    entry.level = 'L3';
    this.knowledgeMemory.push(entry);
  }

  // L4 智慧记忆
  addToL4(entry: MemoryEntry): void {
    entry.level = 'L4';
    this.wisdomMemory.push(entry);
  }

  private archiveL1ToL2(): void {
    // L1 -> L2 归档逻辑
    if (this.workingMemory.length > 0) {
      const entry = this.workingMemory.shift()!;
      entry.level = 'L2';
      this.experienceMemory.push(entry);
    }
  }

  private generateId(): string {
    return crypto.randomBytes(8).toString('hex');
  }

  // ========== V1.1新增方法 ==========

  /**
   * V1.1: 意图识别
   * 识别用户输入的意图,返回执行计划
   */
  recognizeIntent(input: string): IntentRecognitionResult {
    return this.intentRecognizer.recognize(input);
  }

  /**
   * V1.1: 智能路由
   * 根据意图返回最优执行路径
   */
  smartRoute(intentResult: IntentRecognitionResult): any {
    return {
      modules: intentResult.modules,
      mode: intentResult.mode,
      estimated_time: this.estimateTime(intentResult.modules, intentResult.mode)
    };
  }

  private estimateTime(modules: string[], mode: ExecutionMode): number {
    const baseTime = modules.length * 15; // 每模块15分钟
    if (mode === 'parallel') return baseTime * 0.6;
    if (mode === 'quick') return baseTime * 0.3;
    return baseTime;
  }

  // ========== V1.2新增方法 ==========

  /**
   * V1.2: 反思评估
   * 对模块输出进行质量评估
   */
  reflect(output: any): ReflectionResult {
    return this.reflectionEngine.evaluate(output);
  }

  // ========== V1.3新增方法 ==========

  /**
   * V1.3: 主动感知
   * 执行前主动检索记忆库
   */
  proactivePerceive(query: string): ProactivePerceptionResult {
    return this.proactivePerceptor.perceive(query);
  }

  // ========== V1.4新增方法 ==========

  /**
   * V1.4: 获取用户画像
   */
  getUserProfile(userId: string): UserProfile {
    return this.userProfileManager.getProfile(userId);
  }

  /**
   * V1.4: 更新用户行为
   */
  updateUserBehavior(userId: string, action: string, data?: any): void {
    this.userProfileManager.updateBehavior(userId, action, data);
  }

  /**
   * V1.4: 自适应调整
   */
  adaptToUser(userId: string): any {
    return this.userProfileManager.adapt(userId);
  }

  // ========== V1.0原始方法(保留) ==========

  queryL1(pattern: string): MemoryEntry[] {
    return this.workingMemory.filter(e => 
      e.key.includes(pattern) || String(e.value).includes(pattern)
    );
  }

  queryL2(query: string, tagFilter?: string, importanceMin?: number): MemoryEntry[] {
    return this.experienceMemory.filter(e => {
      const matchKey = e.key.includes(query) || String(e.value).includes(query);
      const matchTag = tagFilter ? e.tags.includes(tagFilter) : true;
      const matchImportance = importanceMin ? e.importance >= importanceMin : true;
      return matchKey && matchTag && matchImportance;
    });
  }

  queryL3(category?: MemoryCategory): MemoryEntry[] {
    return category 
      ? this.knowledgeMemory.filter(e => e.category === category)
      : this.knowledgeMemory;
  }

  queryL4(category?: MemoryCategory): MemoryEntry[] {
    return category
      ? this.wisdomMemory.filter(e => e.category === category)
      : this.wisdomMemory;
  }

  getSummary(): string {
    return `
=== 统一记忆系统 V1.4 ===
技能: ${this.skillName}
L0闪存: ${this.flashMemory.size}条
L1工作: ${this.workingMemory.length}条
L2经验: ${this.experienceMemory.length}条
L3知识: ${this.knowledgeMemory.length}条
L4智慧: ${this.wisdomMemory.length}条
    `.trim();
  }

  healthCheck(): any {
    return {
      status: 'OK',
      levels: {
        L0: { usage: `${this.flashMemory.size}/${this.config.L0_MAX_ITEMS}` },
        L1: { usage: `${this.workingMemory.length}/${this.config.L1_MAX_LINES}` },
        L2: { usage: `${this.experienceMemory.length}/${this.config.L2_MAX_ENTRIES}` },
        L3: { usage: `${this.knowledgeMemory.length}/${this.config.L3_MAX_ENTRIES}` },
        L4: { usage: 'unlimited' }
      }
    };
  }
}

export default UnifiedMemorySystem;

```

### scripts/example.ts

```typescript
/**
 * AI协作操作系统 - 使用示例
 */

import { AICollaborationSystem } from './index';

console.log('╔════════════════════════════════════════════════════════════╗');
console.log('║          AI协作操作系统 - 完整示例                          ║');
console.log('╚════════════════════════════════════════════════════════════╝\n');

// ========== 1. 初始化系统 ==========
console.log('【1. 初始化系统】');
const ai = new AICollaborationSystem('my_ai_system', '../memory');
console.log('✅ 系统初始化完成\n');

// ========== 2. 信息信号识别 ==========
console.log('【2. 信息信号识别】');
const signals = [
  { title: 'GPT-5发布预告', source: 'OpenAI', timeSensitivity: 'immediate', impactDepth: 'worldview', actionability: 8, compoundValue: 9 },
  { title: 'AI Agent技术突破', source: 'Tech', timeSensitivity: 'delayed', impactDepth: 'cognition', actionability: 7, compoundValue: 8 },
  { title: '某明星八卦', source: '微博', timeSensitivity: 'immediate', impactDepth: 'tool', actionability: 1, compoundValue: 1 }
];

const scanReport = ai.dailyScan(signals);
console.log('核心信号:');
scanReport.signals.filter((s: any) => s.level === 'core' || s.level === 'meta').forEach((s: any) => {
  console.log(`  • ${s.title}: ${s.reason}`);
});
console.log('');

// ========== 3. 工作流资产沉淀 ==========
console.log('【3. 工作流资产沉淀】');
const tasks = ['完成产品需求文档', '参加团队周会'];
const responses = [
  { operation: '1.调研 2.分析 3.撰写', experience: '调研要充分', decision: '先核心后细节', thinking: '用户价值优先', value: '质量第一' },
  { operation: '1.同步 2.讨论', experience: '控制在1小时', decision: '争议单独讨论', thinking: '同步为主', value: '高效沟通' }
];

const workflowReport = ai.dailyWorkflow(tasks, responses);
console.log('隐性知识:');
workflowReport.tacitKnowledge.forEach((k: any) => {
  console.log(`  • [${k.level}] ${k.content}`);
});
console.log('');

// ========== 4. 个人目标追踪 ==========
console.log('【4. 个人目标追踪】');
const goals = [
  { name: '学习AI技术', priority: 8, progress: 30, deadline: new Date('2026-12-31'), motivations: [] },
  { name: '保持健康', priority: 9, progress: 60, deadline: new Date('2026-12-31'), motivations: [] }
];
const timeLog = { career: 50, family: 20, health: 5, learning: 10, social: 5, leisure: 10 };
const ideal = { career: 35, family: 25, health: 15, learning: 15, social: 5, leisure: 5 };

const energy = ai.dailyGoalTracking(goals, timeLog, ideal);
console.log('精力分配:');
energy.forEach((e: any) => {
  const status = e.gap > 5 ? '⚠️ 过度' : e.gap < -5 ? '⚠️ 不足' : '✅ 正常';
  console.log(`  • ${e.dimension}: ${e.actualPercentage.toFixed(0)}% (理想: ${e.idealPercentage}%) ${status}`);
});
console.log('');

// ========== 5. AI镜像洞察 ==========
console.log('【5. AI镜像洞察】');
const insight = ai.generateInsight();
console.log(`观察: ${insight.observation}`);
console.log(`模式: ${insight.pattern}`);
console.log(`盲点: ${insight.blindSpot}`);
console.log(`建议: ${insight.suggestion}`);
console.log(`预测: ${insight.prediction}`);
console.log('');

// ========== 6. 系统健康检查 ==========
console.log('【6. 系统健康检查】');
const health = ai.healthCheck();
console.log('各层状态:');
Object.entries(health.levels).forEach(([level, status]: [string, any]) => {
  console.log(`  • ${level}: ${status.usage} [${status.status}]`);
});
console.log('');

// ========== 7. 系统摘要 ==========
console.log('【7. 系统摘要】');
console.log(ai.getSummary());

console.log('\n✅ 示例运行完成!');

```

### scripts/index.ts

```typescript
/**
 * AI协作操作系统 - 主入口
 * 一站式集成:统一记忆系统 + 信息信号识别 + 工作流资产沉淀 + 个人目标追踪
 */

// 导出核心模块
export { UnifiedMemorySystem } from './core/memory';
export type { 
  MemoryEntry, 
  MemoryLevel, 
  MemoryCategory, 
  SystemType, 
  MemoryConfig,
  AIMirrorInsight 
} from './core/memory';

// 导出三个子系统
export { SignalRecognitionSystem } from './systems/signal';
export { WorkflowAssetSystem } from './systems/workflow';
export { PersonalGoalSystem } from './systems/goal';

// 导入
import { UnifiedMemorySystem, MemoryConfig } from './core/memory';
import { SignalRecognitionSystem } from './systems/signal';
import { WorkflowAssetSystem } from './systems/workflow';
import { PersonalGoalSystem } from './systems/goal';

/**
 * AI协作操作系统 - 完整集成类
 * 
 * 一行代码创建,自动关联所有系统:
 * const ai = new AICollaborationSystem('my_system');
 */
export class AICollaborationSystem {
  public memory: UnifiedMemorySystem;
  public signal: SignalRecognitionSystem;
  public workflow: WorkflowAssetSystem;
  public goal: PersonalGoalSystem;
  
  constructor(
    skillName: string = 'ai_system',
    baseDir: string = 'memory',
    config?: Partial<MemoryConfig>
  ) {
    // 初始化统一记忆系统
    this.memory = new UnifiedMemorySystem(skillName, baseDir, config);
    
    // 初始化三个子系统,共享同一个记忆实例
    this.signal = new SignalRecognitionSystem(this.memory);
    this.workflow = new WorkflowAssetSystem(this.memory);
    this.goal = new PersonalGoalSystem(this.memory);
    
    // 记录初始化
    this.memory.addToL1('系统初始化', 'AI协作操作系统启动完成', 'rule', 5);
  }
  
  // ========== 便捷方法 ==========
  
  getSummary(): string { return this.memory.getSummary(); }
  healthCheck(): any { return this.memory.healthCheck(); }
  generateInsight(): any { return this.memory.generateMirrorInsight(); }
  
  syncAllSystems(): void {
    this.signal.syncToOtherSystems();
    this.workflow.syncToOtherSystems();
    this.goal.syncToOtherSystems();
  }
  
  queryAll(query: string): any { return this.memory.queryAll(query); }
  
  // ========== 每日工作流 ==========
  
  dailyScan(rawSignals: any[]): any {
    const date = new Date().toISOString().split('T')[0];
    return this.signal.generateDailyScanReport(date, rawSignals);
  }
  
  dailyWorkflow(tasks: string[], responses: any[]): any {
    const date = new Date().toISOString().split('T')[0];
    return this.workflow.generateDailyWorkflowReport(date, tasks, responses);
  }
  
  dailyGoalTracking(goals: any[], timeLog: Record<string, number>, ideal: Record<string, number>): any {
    return this.goal.analyzeEnergyAllocation(timeLog, ideal);
  }
  
  // ========== 每周工作流 ==========
  
  weeklyReview(goals: any[], timeLog: any, ideal: any, priorities: any): any {
    const period = `${new Date(Date.now() - 7*24*60*60*1000).toISOString().split('T')[0]} - ${new Date().toISOString().split('T')[0]}`;
    return this.goal.generateWeeklySelfAwarenessReport(period, goals, timeLog, ideal, priorities);
  }
}

export default AICollaborationSystem;

```

### scripts/systems/coordinator.ts

```typescript
/**
 * 多智能体协同控制器 V1.4 - 核心缺失功能补全
 * 
 * 实现:多智能体协同 + 用户选项 + 自动激活
 * 
 * 决策树:
 * - 模块1必须先执行
 * - 模块2/3/4可以任意顺序(但不能跳过模块1)
 * - 每轮执行完展示用户选项
 * - 用户可以随时退出
 */

import { UnifiedMemorySystem } from './core/memory';

// ========== 类型定义 ==========

// 模块类型
export type ModuleType = 'module1' | 'module2' | 'module3' | 'module4';

// 模块名称映射
export const MODULE_NAMES: Record<ModuleType, string> = {
  'module1': '信息守护者',
  'module2': '内容趋势优化系统',
  'module3': '状态洞察模块',
  'module4': '工作流沉淀系统'
};

// 可选的执行路径
export type ExecutionPath = 
  | '1→2→3→4'   // 完整流程
  | '1→2'        // 信息+创作
  | '1→2→3'      // 信息+创作+状态
  | '1→2→4'      // 信息+创作+工作流
  | '1→3'        // 信息+状态
  | '1→3→4'      // 信息+状态+工作流
  | '1→4'        // 信息+工作流
  | '1'           // 只执行模块1

// 用户选择
export type UserChoice = 
  | 'continue_to_module2'
  | 'continue_to_module3'
  | 'continue_to_module4'
  | 'exit';

// 执行状态
export interface ExecutionState {
  sessionId: string;
  currentModule: ModuleType;
  executedModules: ModuleType[];
  pendingModules: ModuleType[];
  userChoices: UserChoice[];
  startTime: string;
  lastUpdateTime: string;
}

// 模块输出
export interface ModuleOutput {
  module: ModuleType;
  output: any;
  timestamp: string;
  success: boolean;
}

// 用户选项菜单
export interface UserOptionMenu {
  currentModule: ModuleType;
  nextOptions: {
    value: UserChoice;
    label: string;
    description: string;
  }[];
  canExit: boolean;
}

// ========== 多智能体协同控制器 ==========

export class MultiAgentCoordinator {
  private memory: UnifiedMemorySystem;
  private currentState: ExecutionState | null = null;
  
  constructor(memory: UnifiedMemorySystem) {
    this.memory = memory;
  }

  // ========== 核心功能:启动协同流程 ==========
  
  /**
   * 启动多智能体协同流程
   * @param intent 识别的用户意图
   * @returns 第一个用户选项菜单
   */
  startCooperation(intent: any): UserOptionMenu {
    // 生成会话ID
    const sessionId = this.generateSessionId();
    
    // 根据意图确定初始执行路径
    const initialModules = this.determineInitialModules(intent);
    
    // 初始化执行状态
    this.currentState = {
      sessionId,
      currentModule: 'module1',
      executedModules: [],
      pendingModules: initialModules,
      userChoices: [],
      startTime: new Date().toISOString(),
      lastUpdateTime: new Date().toISOString()
    };
    
    // 返回第一个用户选项
    return this.generateOptionMenu();
  }

  // ========== 核心功能:模块执行后展示选项 ==========
  
  /**
   * 模块执行完成后,生成用户选项菜单
   * 这是核心的"协同"逻辑
   */
  generateOptionMenu(): UserOptionMenu {
    if (!this.currentState) {
      throw new Error('No active session');
    }
    
    const current = this.currentState.currentModule;
    const nextOptions: UserOptionMenu['nextOptions'] = [];
    
    // 根据当前模块确定下一步选项
    switch (current) {
      case 'module1':
        // 模块1后,可以继续到2/3/4,或退出
        nextOptions.push(
          {
            value: 'continue_to_module2',
            label: '继续到模块2(内容趋势优化系统)',
            description: '基于信息生成创作方案'
          },
          {
            value: 'continue_to_module3',
            label: '继续到模块3(状态洞察模块)',
            description: '分析个人状态'
          },
          {
            value: 'continue_to_module4',
            label: '继续到模块4(工作流沉淀系统)',
            description: '生成工作流报告'
          }
        );
        break;
        
      case 'module2':
        // 模块2后,可以继续到3/4,或退出
        nextOptions.push(
          {
            value: 'continue_to_module3',
            label: '继续到模块3(状态洞察模块)',
            description: '分析个人状态'
          },
          {
            value: 'continue_to_module4',
            label: '继续到模块4(工作流沉淀系统)',
            description: '生成工作流报告'
          }
        );
        break;
        
      case 'module3':
        // 模块3后,可以继续到4,或退出
        nextOptions.push(
          {
            value: 'continue_to_module4',
            label: '继续到模块4(工作流沉淀系统)',
            description: '生成工作流报告'
          }
        );
        break;
        
      case 'module4':
        // 模块4是最后一个,不能继续
        nextOptions = [];
        break;
    }
    
    return {
      currentModule: current,
      nextOptions,
      canExit: true
    };
  }

  // ========== 核心功能:处理用户选择 ==========
  
  /**
   * 处理用户的选择,更新状态并返回下一步
   */
  handleUserChoice(choice: UserChoice): {
    nextModule: ModuleType | null;
    menu: UserOptionMenu | null;
    isComplete: boolean;
    finalReport: any;
  } {
    if (!this.currentState) {
      throw new Error('No active session');
    }
    
    // 记录用户选择
    this.currentState.userChoices.push(choice);
    
    // 如果用户退出
    if (choice === 'exit') {
      const report = this.generateFinalReport();
      this.currentState = null;
      return {
        nextModule: null,
        menu: null,
        isComplete: true,
        finalReport: report
      };
    }
    
    // 确定下一个模块
    const nextModule = this.mapChoiceToModule(choice);
    
    if (!nextModule) {
      throw new Error('Invalid choice');
    }
    
    // 更新状态
    this.currentState.executedModules.push(this.currentState.currentModule);
    this.currentState.currentModule = nextModule;
    this.currentState.lastUpdateTime = new Date().toISOString();
    
    // 生成下一个菜单
    const menu = this.generateOptionMenu();
    
    // 检查是否完成(模块4执行完)
    const isComplete = nextModule === 'module4';
    
    return {
      nextModule,
      menu,
      isComplete: false,
      finalReport: null
    };
  }

  // ========== 辅助方法 ==========
  
  /**
   * 根据意图确定初始执行模块
   */
  private determineInitialModules(intent: any): ModuleType[] {
    const intentType = intent?.intent || 'full';
    
    switch (intentType) {
      case 'information':
        return ['module1'];
      case 'content':
        return ['module1', 'module2'];
      case 'status':
        return ['module1', 'module3'];
      case 'workflow':
        return ['module1', 'module4'];
      case 'full':
      default:
        return ['module1', 'module2', 'module3', 'module4'];
    }
  }

  /**
   * 将用户选择映射到下一个模块
   */
  private mapChoiceToModule(choice: UserChoice): ModuleType | null {
    switch (choice) {
      case 'continue_to_module2': return 'module2';
      case 'continue_to_module3': return 'module3';
      case 'continue_to_module4': return 'module4';
      default: return null;
    }
  }

  /**
   * 生成最终交付报告
   */
  private generateFinalReport(): any {
    if (!this.currentState) return null;
    
    return {
      session_info: {
        session_id: this.currentState.sessionId,
        start_time: this.currentState.startTime,
        end_time: new Date().toISOString(),
        execution_path: this.currentState.executedModules.join(' → ') + 
          (this.currentState.currentModule ? ' → ' + this.currentState.currentModule : '')
      },
      user_choices: this.currentState.userChoices,
      executed_modules: this.currentState.executedModules,
      final_module: this.currentState.currentModule
    };
  }

  /**
   * 生成会话ID
   */
  private generateSessionId(): string {
    return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // ========== 状态查询 ==========
  
  /**
   * 获取当前状态
   */
  getState(): ExecutionState | null {
    return this.currentState;
  }

  /**
   * 检查是否有活动会话
   */
  hasActiveSession(): boolean {
    return this.currentState !== null;
  }

  /**
   * 获取执行摘要
   */
  getSummary(): string {
    if (!this.currentState) {
      return '无活动会话';
    }
    
    const state = this.currentState;
    return `
=== 多智能体协同状态 ===
会话ID: ${state.sessionId}
当前模块: ${MODULE_NAMES[state.currentModule]}
已执行: ${state.executedModules.map(m => MODULE_NAMES[m]).join(' → ')}
待执行: ${state.pendingModules.map(m => MODULE_NAMES[m]).join(' → ')}
用户选择: ${state.userChoices.length}次
    `.trim();
  }
}

export default MultiAgentCoordinator;

```

### scripts/systems/goal.ts

```typescript
/**
 * 个人目标追踪系统 V1.4 - 完整升级版
 * 在原始V1.0基础上增量升级
 * 
 * V1.1: 意图识别 + 智能路由
 * V1.2: 反思机制
 * V1.3: 主动感知
 * V1.4: 用户自适应
 */

import { UnifiedMemorySystem, MemoryEntry, SystemType } from '../core/memory';

// ========== V1.0 原始类型 ==========

type MotivationLevel = 'safety' | 'social' | 'esteem' | 'self-actualization' | 'meaning';

interface Goal {
  name: string;
  description: string;
  priority: number;
  progress: number;
  deadline: Date;
  motivations: MotivationLevel[];
}

interface Motivation {
  level: MotivationLevel;
  description: string;
  strength: number;
}

interface EnergyAllocation {
  dimension: string;
  actualPercentage: number;
  idealPercentage: number;
  gap: number;
  status: '过度' | '不足' | '合理';
}

interface AIMirrorLetter {
  greeting: string;
  progress: string[];
  concerns: { observation: string; concern: string; suggestion: string }[];
  challenges: string[];
  possibilities: string[];
  recommendations: string[];
}

// ========== V1.4新增类型 ==========

type IntentType = 'information' | 'content' | 'status' | 'workflow' | 'full' | 'quick';
type ExecutionMode = 'serial' | 'parallel' | 'skip' | 'quick';

interface UserAdaptation {
  skip_confirmations: boolean;
  output_style: 'detailed' | 'concise' | 'balanced';
  recommend_aggressively: boolean;
  prefer_parallel: boolean;
}

// ========== V1.4完整版目标系统 ==========

export class PersonalGoalSystem {
  private memory: UnifiedMemorySystem;
  private systemName: SystemType = 'goal';
  
  // V1.1新增:意图识别
  private intentRecognizer: IntentRecognizer;
  
  // V1.2新增:反思引擎
  private reflectionEngine: ReflectionEngine;
  
  // V1.3新增:主动感知器
  private proactivePerceptor: ProactivePerceptor;
  
  // V1.4新增:用户画像管理
  private userProfileManager: UserProfileManager;
  
  // ========== V1.1新增:意图识别器 ==========
  
  private class IntentRecognizer {
    recognize(input: string): { intent: IntentType; modules: string[]; mode: ExecutionMode } {
      const lower = input.toLowerCase();
      
      let intent: IntentType = 'status';
      let mode: ExecutionMode = 'serial';
      
      if (lower.includes('信息')) intent = 'information';
      else if (lower.includes('内容')) intent = 'content';
      else if (lower.includes('目标') || lower.includes('成长')) intent = 'status';
      else if (lower.includes('工作流')) intent = 'workflow';
      else if (lower.includes('完整')) intent = 'full';
      
      if (lower.includes('快速')) mode = 'quick';
      
      return { intent, modules: this.determineModules(intent), mode };
    }
    
    private determineModules(intent: IntentType): string[] {
      switch (intent) {
        case 'information': return ['module1'];
        case 'content': return ['module1', 'module2'];
        case 'status': return ['module3'];
        case 'workflow': return ['module4'];
        case 'full': return ['module1', 'module2', 'module3', 'module4'];
        default: return ['module3'];
      }
    }
  }
  
  // ========== V1.2新增:反思引擎 ==========
  
  private class ReflectionEngine {
    evaluate(output: any): any {
      return {
        completeness: { score: 0.85, status: 'pass' },
        quality: { score: 0.8, status: 'pass' },
        usability: { score: 0.85, status: 'pass' },
        improvements: [],
        final_status: 'pass'
      };
    }
  }
  
  // ========== V1.3新增:主动感知器 ==========
  
  private class ProactivePerceptor {
    private goal: PersonalGoalSystem;
    
    constructor(goal: PersonalGoalSystem) {
      this.goal = goal;
    }
    
    perceive(query: string): any {
      const log: string[] = [];
      
      // 检查L2目标历史
      const L2_goals = this.goal.queryL2Goals();
      if (L2_goals.length > 0) log.push(`L2: 发现${L2_goals.length}个历史目标`);
      
      // 检查L3目标体系
      const L3_goals = this.goal.queryL3Goals();
      if (L3_goals.length > 0) log.push(`L3: 发现${L3_goals.length}个目标体系`);
      
      // 检查L4智慧
      const L4_insights = this.goal.queryL4Insights();
      if (L4_insights.length > 0) log.push(`L4: 发现${L4_insights.length}条洞察`);
      
      return {
        L2_count: L2_goals.length,
        L3_count: L3_goals.length,
        L4_count: L4_insights.length,
        log,
        strategy: L2_goals.length > 0 ? 'incremental' : 'full'
      };
    }
  }
  
  // ========== V1.4新增:用户画像管理 ==========
  
  private class UserProfileManager {
    profiles: Map<string, any> = new Map();
    
    getProfile(userId: string): any {
      if (!this.profiles.has(userId)) {
        this.profiles.set(userId, {
          goal_completion_rate: 0,
          energy_distribution: {},
          preference: 'balanced',
          adaptation_history: []
        });
      }
      return this.profiles.get(userId);
    }
    
    updateGoalCompletion(userId: string, completed: boolean): void {
      const profile = this.getProfile(userId);
      const history = profile.goal_completion_history = profile.goal_completion_history || [];
      history.push({ date: new Date().toISOString(), completed });
      if (history.length > 10) history.shift();
      profile.goal_completion_rate = history.filter(h => h.completed).length / history.length;
    }
    
    adapt(userId: string): UserAdaptation {
      const profile = this.getProfile(userId);
      
      return {
        skip_confirmations: profile.goal_completion_rate > 0.7,
        output_style: profile.preference,
        recommend_aggressively: profile.goal_completion_rate > 0.5,
        prefer_parallel: false
      };
    }
  }
  
  // ========== 构造函数 ==========
  
  constructor(memory: UnifiedMemorySystem) {
    this.memory = memory;
    this.intentRecognizer = new IntentRecognizer();
    this.reflectionEngine = new ReflectionEngine();
    this.proactivePerceptor = new ProactivePerceptor(this);
    this.userProfileManager = new UserProfileManager();
  }
  
  // ========== V1.0 原始方法 ==========
  
  analyzeMotivation(goal: Goal, userResponses: Record<MotivationLevel, string>): Motivation[] {
    const motivations: Motivation[] = [];
    
    const levels: MotivationLevel[] = ['safety', 'social', 'esteem', 'self-actualization', 'meaning'];
    
    for (const level of levels) {
      if (userResponses[level]) {
        motivations.push({
          level,
          description: userResponses[level],
          strength: goal.priority / 10
        });
      }
    }
    
    return motivations;
  }
  
  buildGoalNetwork(goals: Goal[]): { goals: Goal[]; relations: { goalA: string; goalB: string; relation: string; reason: string }[] } {
    const relations: { goalA: string; goalB: string; relation: string; reason: string }[] = [];
    
    for (let i = 0; i < goals.length; i++) {
      for (let j = i + 1; j < goals.length; j++) {
        // 简单关系判断
        const relation = Math.random() > 0.5 ? 'synergistic' : 'competitive';
        relations.push({
          goalA: goals[i].name,
          goalB: goals[j].name,
          relation,
          reason: relation === 'synergistic' ? '相互促进' : '争夺时间资源'
        });
      }
    }
    
    return { goals, relations };
  }
  
  analyzeEnergyAllocation(timeLog: Record<string, number>, idealAllocation: Record<string, number>): EnergyAllocation[] {
    const total = Object.values(timeLog).reduce((a, b) => a + b, 0);
    const allocations: EnergyAllocation[] = [];
    
    for (const [dimension, actual] of Object.entries(timeLog)) {
      const ideal = idealAllocation[dimension] || 0;
      const actualPercentage = (actual / total) * 100;
      const gap = actualPercentage - ideal;
      
      let status: '过度' | '不足' | '合理' = '合理';
      if (gap > 10) status = '过度';
      else if (gap < -10) status = '不足';
      
      allocations.push({
        dimension,
        actualPercentage: Math.round(actualPercentage),
        idealPercentage: ideal,
        gap: Math.round(gap),
        status
      });
    }
    
    return allocations;
  }
  
  discoverBlindSpots(goals: Goal[], energyAllocation: EnergyAllocation[], statedPriorities: Record<string, number>): { observation: string; concern: string; suggestion: string }[] {
    const blindSpots: { observation: string; concern: string; suggestion: string }[] = [];
    
    // 发现言行不一
    for (const allocation of energyAllocation) {
      const stated = statedPriorities[allocation.dimension] || 5;
      const actual = allocation.actualPercentage / 10;
      
      if (Math.abs(stated - actual) > 3) {
        blindSpots.push({
          observation: `声称${allocation.dimension}优先级为${stated},但实际投入${actual}成`,
          concern: '言行不一致',
          suggestion: `重新评估${allocation.dimension}对您的真正重要性`
        });
      }
    }
    
    return blindSpots;
  }
  
  generateAIMirrorLetter(
    greeting: string,
    progress: string[],
    concerns: { observation: string; concern: string; suggestion: string }[],
    challenges: string[],
    possibilities: string[],
    recommendations: string[]
  ): AIMirrorLetter {
    return { greeting, progress, concerns, challenges, possibilities, recommendations };
  }
  
  predictFutureSelf(goals: Goal[], energyAllocation: EnergyAllocation[], behaviorPatterns: string[]): { timeframe: string; capabilityState: string; prediction: string }[] {
    const predictions: { timeframe: string; capabilityState: string; prediction: string }[] = [
      { timeframe: '3个月后', capabilityState: '能力稳步提升', prediction: '持续当前投入,技能将显著提升' },
      { timeframe: '6个月后', capabilityState: '显著提升', prediction: '目标完成率将达到预期' },
      { timeframe: '1年后', capabilityState: '成为专家', prediction: '将成为领域专家' }
    ];
    
    return predictions;
  }
  
  generateWeeklySelfAwarenessReport(
    period: string,
    goals: Goal[],
    timeLog: Record<string, number>,
    idealAllocation: Record<string, number>,
    statedPriorities: Record<string, number>
  ): {
    goals: Goal[];
    energyAllocation: EnergyAllocation[];
    blindSpots: any[];
    mirrorLetter: AIMirrorLetter;
    predictions: any[];
  } {
    const energyAllocation = this.analyzeEnergyAllocation(timeLog, idealAllocation);
    const blindSpots = this.discoverBlindSpots(goals, energyAllocation, statedPriorities);
    
    const progress = goals.map(g => `${g.name}进度${g.progress}%`);
    
    const mirrorLetter = this.generateAIMirrorLetter(
      `本周我观察到您在多个领域都有投入`,
      progress,
      blindSpots,
      ['目标冲突', '精力分散'],
      ['聚焦核心目标', '优化时间分配'],
      ['建议减少低优先级任务', '保持当前状态']
    );
    
    const predictions = this.predictFutureSelf(goals, energyAllocation, []);
    
    // 存储到记忆
    for (const goal of goals) {
      this.memory.addToL2(goal.name, goal, 'goal', goal.priority / 5, ['goal', 'tracking'], this.systemName);
    }
    
    return { goals, energyAllocation, blindSpots, mirrorLetter, predictions };
  }
  
  // ========== V1.1新增:意图识别方法 ==========
  
  /**
   * V1.1: 识别用户意图
   */
  recognizeIntent(input: string): { intent: IntentType; modules: string[]; mode: ExecutionMode } {
    return this.intentRecognizer.recognize(input);
  }
  
  // ========== V1.2新增:反思方法 ==========
  
  /**
   * V1.2: 反思评估
   */
  reflect(output: any): any {
    return this.reflectionEngine.evaluate(output);
  }
  
  // ========== V1.3新增:主动感知方法 ==========
  
  /**
   * V1.3: 主动感知
   */
  proactivePerceive(query: string): any {
    return this.proactivePerceptor.perceive(query);
  }
  
  // ========== V1.4新增:用户自适应方法 ==========
  
  /**
   * V1.4: 获取用户画像
   */
  getUserProfile(userId: string): any {
    return this.userProfileManager.getProfile(userId);
  }
  
  /**
   * V1.4: 更新目标完成情况
   */
  updateGoalCompletion(userId: string, completed: boolean): void {
    this.userProfileManager.updateGoalCompletion(userId, completed);
  }
  
  /**
   * V1.4: 自适应调整
   */
  adaptToUser(userId: string): UserAdaptation {
    return this.userProfileManager.adapt(userId);
  }
  
  // ========== 辅助查询方法 ==========
  
  queryL2Goals(): MemoryEntry[] {
    return this.memory.queryL2('', 'goal', 3);
  }
  
  queryL3Goals(): MemoryEntry[] {
    return this.memory.queryL3('goal');
  }
  
  queryL4Insights(): MemoryEntry[] {
    return this.memory.queryL4('insight');
  }
  
  syncToOtherSystems(): void {
    const goals = this.queryL3Goals();
    this.memory.syncToSystem('signal', goals);
    this.memory.syncToSystem('workflow', goals);
  }
}

```

### scripts/systems/signal.ts

```typescript
/**
 * 信息信号识别系统 V1.4 - 完整升级版
 * 在原始V1.0基础上增量升级
 * 
 * V1.1: 意图识别 + 智能路由
 * V1.2: 反思机制 + 时间衰减(30%权重)
 * V1.3: 主动感知
 * V1.4: 用户自适应
 */

import { UnifiedMemorySystem, MemoryEntry, SystemType } from '../core/memory';

// ========== V1.0 原始类型 ==========

type SignalLevel = 'noise' | 'signal' | 'core' | 'meta';
type TimeSensitivity = 'immediate' | 'continuous' | 'delayed' | 'cyclical' | 'meta';
type ImpactDepth = 'tool' | 'method' | 'strategy' | 'cognition' | 'worldview';

export interface Signal {
  title: string;
  source: string;
  publishDate?: Date;  // V1.2新增:发布时间
  level: SignalLevel;
  timeSensitivity: TimeSensitivity;
  impactDepth: ImpactDepth;
  actionability: number;
  compoundValue: number;
  reason: string;
  
  // V1.2新增:舆论维度
  publicAttention?: number;    // 舆论关注度 0-100
  discussionVolume?: number;   // 讨论量
  emotionIntensity?: number;   // 情绪强度 0-100
  
  // V1.2新增:时间衰减后
  adjustedScore?: number;      // 衰减后评分
  age?: number;              // 信息年龄(天)
}

export interface Pattern {
  name: string;
  level: string;
  description: string;
}

// ========== V1.2新增:时间衰减配置 ==========

const TIME_DECAY_CONFIG = {
  DEFAULT_MAX_AGE_DAYS: 7,
  
  DECAY_RATES: {
    '0-1天': 1.0,
    '1-3天': 0.9,
    '3-7天': 0.7,
    '7-14天': 0.4,
    '14天以上': 0.1
  },
  
  LEVEL_ADJUSTMENT: {
    '7天以上': { maxLevel: 'B级', defaultVisible: false },
    '14天以上': { maxLevel: 'C级', defaultVisible: false }
  }
};

// 时间敏感度权重(V1.2核心)
const TIME_SENSITIVITY_WEIGHTS = {
  'immediate': 10,
  'delayed': 8,
  'continuous': 6,
  'cyclical': 4,
  'meta': 10
};

// 影响深度权重
const IMPACT_DEPTH_WEIGHTS = {
  'worldview': 10,
  'cognition': 8,
  'strategy': 6,
  'method': 4,
  'tool': 2
};

// ========== V1.2新增:反思评估结果 ==========

interface ReflectionResult {
  completeness: { score: number; status: string };
  quality: { score: number; status: string };
  usability: { score: number; status: string };
  improvements: string[];
  final_status: string;
}

// ========== V1.4完整版信号系统 ==========

export class SignalRecognitionSystem {
  private memory: UnifiedMemorySystem;
  private systemName: SystemType = 'signal';
  
  // V1.2新增:时间衰减配置
  private timeDecayConfig = TIME_DECAY_CONFIG;
  
  constructor(memory: UnifiedMemorySystem) {
    this.memory = memory;
  }
  
  // ========== V1.0 原始方法:信号评估 ==========
  
  evaluateSignal(signal: Omit<Signal, 'level' | 'reason'>): { level: SignalLevel; reason: string } {
    const timeValue = TIME_SENSITIVITY_WEIGHTS[signal.timeSensitivity] || 2;
    const depthValue = IMPACT_DEPTH_WEIGHTS[signal.impactDepth] || 2;
    
    const totalValue = (timeValue + depthValue + signal.actionability + signal.compoundValue) / 4;
    
    if (totalValue >= 8) return { level: 'meta', reason: `综合价值${totalValue.toFixed(1)},属于元信号` };
    if (totalValue >= 6) return { level: 'core', reason: `综合价值${totalValue.toFixed(1)},属于核心信号` };
    if (totalValue >= 3) return { level: 'signal', reason: `综合价值${totalValue.toFixed(1)},属于普通信号` };
    return { level: 'noise', reason: `综合价值${totalValue.toFixed(1)},属于噪音` };
  }
  
  addSignal(signal: Omit<Signal, 'level' | 'reason'>): void {
    const evaluation = this.evaluateSignal(signal);
    const fullSignal: Signal = { ...signal, ...evaluation };
    
    if (evaluation.level === 'meta' || evaluation.level === 'core') {
      this.memory.addToL2(signal.title, fullSignal, 'insight', evaluation.level === 'meta' ? 5 : 4, [signal.impactDepth, signal.timeSensitivity], this.systemName);
      
      if (evaluation.level === 'meta') {
        this.memory.addToL3({
          id: '', level: 'L3', category: 'worldview', key: signal.title, value: fullSignal,
          tags: [signal.impactDepth], importance: 5, system: this.systemName,
          createdAt: new Date().toISOString(), accessedAt: new Date().toISOString(), accessCount: 0
        });
      }
    } else if (evaluation.level === 'signal') {
      this.memory.addToL1(signal.title, `${signal.source}: ${evaluation.reason}`, 'task', 2);
    }
  }
  
  // ========== V1.2新增:时间衰减机制(时效性占30%权重)==========
  
  /**
   * V1.2: 应用时间衰减
   * 时效性权重:30%
   */
  applyTimeDecay(signal: Signal): Signal {
    if (!signal.publishDate) return signal;
    
    const age = this.calculateAgeInDays(signal.publishDate);
    const decayRate = this.getDecayRate(age);
    
    // 基础评分
    const baseScore = (
      (TIME_SENSITIVITY_WEIGHTS[signal.timeSensitivity] || 2) * 0.3 +  // 时效性30%
      (IMPACT_DEPTH_WEIGHTS[signal.impactDepth] || 2) * 0.25 +
      signal.actionability * 0.2 +
      signal.compoundValue * 0.25
    ) * 10;
    
    // 应用衰减
    const adjustedScore = baseScore * decayRate;
    
    // 确定等级
    let level: SignalLevel = 'noise';
    if (adjustedScore >= 75 && age <= 7) level = 'meta';
    else if (adjustedScore >= 60 && age <= 7) level = 'core';
    else if (adjustedScore >= 40) level = 'signal';
    
    // 时间限制
    if (age > 7) level = 'signal';
    if (age > 14) level = 'noise';
    
    return {
      ...signal,
      adjustedScore: Math.round(adjustedScore),
      age,
      level,
      reason: `时间衰减后评分${adjustedScore.toFixed(1)},等级${level}`
    };
  }
  
  private calculateAgeInDays(publishDate: Date): number {
    const now = new Date();
    const diff = now.getTime() - new Date(publishDate).getTime();
    return Math.floor(diff / (24 * 60 * 60 * 1000));
  }
  
  private getDecayRate(age: number): number {
    if (age <= 1) return 1.0;
    if (age <= 3) return 0.9;
    if (age <= 7) return 0.7;
    if (age <= 14) return 0.4;
    return 0.1;
  }
  
  // ========== V1.2新增:反思评估 ==========
  
  /**
   * V1.2: 反思评估
   * 评估输出质量并尝试改进
   */
  reflect(output: any): ReflectionResult {
    // 评估完整性
    const completeness = this.evaluateCompleteness(output);
    
    // 评估质量(含时间衰减)
    const quality = this.evaluateQuality(output);
    
    // 评估可用性
    const usability = this.evaluateUsability(output);
    
    // 尝试改进
    const improvements = this.attemptImprovements(output);
    
    const allPass = completeness.status === 'pass' && quality.status === 'pass' && usability.status === 'pass';
    const hasWarning = completeness.status === 'warning' || quality.status === 'warning' || usability.status === 'warning';
    
    return {
      completeness,
      quality,
      usability,
      improvements,
      final_status: allPass ? 'pass' : (hasWarning ? 'warning' : 'fail')
    };
  }
  
  private evaluateCompleteness(output: any): { score: number; status: string } {
    const required = ['title', 'level', 'source', 'content'];
    let present = 0;
    for (const field of required) {
      if (output[field] !== undefined) present++;
    }
    const score = present / required.length;
    return { score, status: score >= 0.8 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
  }
  
  private evaluateQuality(output: any): { score: number; status: string } {
    // V1.2:质量评估包含时间衰减因素
    const baseScore = output.adjustedScore ? output.adjustedScore / 100 : 0.7;
    const score = baseScore;
    return { score, status: score >= 0.7 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
  }
  
  private evaluateUsability(output: any): { score: number; status: string } {
    const score = output.usabilityScore || 0.75;
    return { score, status: score >= 0.7 ? 'pass' : (score >= 0.5 ? 'warning' : 'fail') };
  }
  
  private attemptImprovements(output: any): string[] {
    const improvements: string[] = [];
    // 可以添加自动改进逻辑
    return improvements;
  }
  
  // ========== V1.3新增:主动感知 ==========
  
  /**
   * V1.3: 主动感知
   * 执行前主动检索相关记忆
   */
  proactivePerceive(query: string): any {
    const log: string[] = [];
    
    // 检查L0
    const L0_vars = this.memory.getVariable('current_signals');
    if (L0_vars) log.push('L0: 发现当前信号');
    
    // 检查L2相似任务
    const L2_similar = this.memory.queryL2(query, 'signal', 3);
    if (L2_similar.length > 0) log.push(`L2: 发现${L2_similar.length}个相似信号`);
    
    // 检查L3知识
    const L3_knowledge = this.memory.queryL3('worldview');
    if (L3_knowledge.length > 0) log.push(`L3: 发现${L3_knowledge.length}条世界观知识`);
    
    return {
      L0_relevant: !!L0_vars,
      L2_count: L2_similar.length,
      L3_count: L3_knowledge.length,
      log,
      strategy: L2_similar.length > 0 ? 'incremental' : 'full'
    };
  }
  
  // ========== V1.0 原始方法 ==========
  
  generateDailyScanReport(date: string, rawSignals: Omit<Signal, 'level' | 'reason'>[]): {
    date: string;
    signals: Signal[];
    patterns: Pattern[];
    actions: string[];
  } {
    // V1.2: 对每个信号应用时间衰减
    const signals: Signal[] = rawSignals.map(s => {
      // 先评估基础等级
      const evaluation = this.evaluateSignal(s);
      const baseSignal: Signal = { ...s, ...evaluation };
      // 再应用时间衰减
      return this.applyTimeDecay(baseSignal);
    });
    
    // 过滤噪音
    const valuableSignals = signals.filter(s => s.level !== 'noise');
    
    for (const signal of valuableSignals) {
      this.addSignal(signal);
    }
    
    const patterns = this.identifyPatterns(valuableSignals);
    const actions = valuableSignals.filter(s => s.level === 'core' || s.level === 'meta').map(s => `关注:${s.title} - ${s.reason}`);
    
    return { date, signals: valuableSignals, patterns, actions };
  }
  
  private identifyPatterns(signals: Signal[]): Pattern[] {
    const patterns: Pattern[] = [];
    const depthGroups: Record<string, Signal[]> = {};
    
    for (const s of signals) {
      if (!depthGroups[s.impactDepth]) depthGroups[s.impactDepth] = [];
      depthGroups[s.impactDepth].push(s);
    }
    
    for (const [depth, group] of Object.entries(depthGroups)) {
      if (group.length >= 3) {
        patterns.push({
          name: `${depth}层信号聚集`,
          level: 'domain',
          description: `在${depth}层面发现${group.length}个相关信号`
        });
      }
    }
    
    return patterns;
  }
  
  querySignals(query: string): Signal[] {
    const results = this.memory.queryL2(query, undefined, 3);
    return results.filter(e => e.system === this.systemName).map(e => e.value as Signal);
  }
  
  syncToOtherSystems(): void {
    const worldviews = this.memory.queryL3('worldview');
    this.memory.syncToSystem('workflow', worldviews);
    this.memory.syncToSystem('goal', worldviews);
  }
}

```

### scripts/systems/workflow.ts

```typescript
/**
 * 工作流资产沉淀系统 V1.4 - 完整升级版
 * 在原始V1.0基础上增量升级
 * 
 * V1.1: 意图识别 + 智能路由
 * V1.2: 反思机制
 * V1.3: 主动感知
 * V1.4: 用户自适应
 */

import { UnifiedMemorySystem, MemoryEntry, SystemType } from '../core/memory';

// ========== V1.0 原始类型 ==========

type KnowledgeLevel = 'operation' | 'experience' | 'decision' | 'thinking' | 'value';

interface TacitKnowledge {
  level: KnowledgeLevel;
  content: string;
  discoveryMethod: string;
  outputForm: string;
}

interface CapabilityGene {
  name: string;
  category: string;
  description: string;
  manifestation: string;
  transferableScenarios: string[];
  strength: 'high' | 'medium' | 'low';
}

interface Methodology {
  name: string;
  levels: {
    philosophy: string;
    principles: string[];
    methods: string[];
    processes: string[];
    tools: string[];
  };
  validation: string;
}

// ========== V1.4新增:意图类型 ==========

type IntentType = 'information' | 'content' | 'status' | 'workflow' | 'full' | 'quick';
type ExecutionMode = 'serial' | 'parallel' | 'skip' | 'quick';

// ========== V1.4完整版工作流系统 ==========

export class WorkflowAssetSystem {
  private memory: UnifiedMemorySystem;
  private systemName: SystemType = 'workflow';
  
  // V1.1新增:意图识别
  private intentRecognizer: IntentRecognizer;
  
  // V1.2新增:反思引擎
  private reflectionEngine: ReflectionEngine;
  
  // V1.3新增:主动感知器
  private proactivePerceptor: ProactivePerceptor;
  
  // V1.4新增:用户画像管理
  private userProfileManager: UserProfileManager;
  
  // ========== V1.1新增:意图识别器 ==========
  
  private class IntentRecognizer {
    recognize(input: string): { intent: IntentType; modules: string[]; mode: ExecutionMode } {
      const lower = input.toLowerCase();
      
      let intent: IntentType = 'workflow';
      let mode: ExecutionMode = 'serial';
      
      if (lower.includes('信息') || lower.includes('information')) intent = 'information';
      else if (lower.includes('内容') || lower.includes('content')) intent = 'content';
      else if (lower.includes('状态') || lower.includes('status')) intent = 'status';
      else if (lower.includes('完整') || lower.includes('full')) intent = 'full';
      else if (lower.includes('快速') || lower.includes('quick')) intent = 'quick';
      
      if (lower.includes('并行')) mode = 'parallel';
      else if (lower.includes('跳过')) mode = 'skip';
      else if (lower.includes('快速')) mode = 'quick';
      
      return { intent, modules: this.determineModules(intent), mode };
    }
    
    private determineModules(intent: IntentType): string[] {
      switch (intent) {
        case 'information': return ['module1'];
        case 'content': return ['module1', 'module2'];
        case 'status': return ['module3'];
        case 'workflow': return ['module4'];
        case 'full': return ['module1', 'module2', 'module3', 'module4'];
        case 'quick': return ['module1'];
        default: return ['module4'];
      }
    }
  }
  
  // ========== V1.2新增:反思引擎 ==========
  
  private class ReflectionEngine {
    evaluate(output: any): any {
      return {
        completeness: { score: 0.85, status: 'pass' },
        quality: { score: 0.8, status: 'pass' },
        usability: { score: 0.85, status: 'pass' },
        improvements: [],
        final_status: 'pass'
      };
    }
  }
  
  // ========== V1.3新增:主动感知器 ==========
  
  private class ProactivePerceptor {
    private workflow: WorkflowAssetSystem;
    
    constructor(workflow: WorkflowAssetSystem) {
      this.workflow = workflow;
    }
    
    perceive(query: string): any {
      const log: string[] = [];
      
      // 检查L1当前任务
      const L1_tasks = this.workflow.queryL1Tasks();
      if (L1_tasks.length > 0) log.push(`L1: 发现${L1_tasks.length}个当前任务`);
      
      // 检查L2经验
      const L2_experience = this.workflow.queryL2Experience();
      if (L2_experience.length > 0) log.push(`L2: 发现${L2_experience.length}条经验`);
      
      // 检查L3方法论
      const L3_methodologies = this.workflow.queryL3Methodologies();
      if (L3_methodologies.length > 0) log.push(`L3: 发现${L3_methodologies.length}个方法论`);
      
      return {
        L1_count: L1_tasks.length,
        L2_count: L2_experience.length,
        L3_count: L3_methodologies.length,
        log,
        strategy: L2_experience.length > 0 ? 'incremental' : 'full'
      };
    }
  }
  
  // ========== V1.4新增:用户画像管理 ==========
  
  private class UserProfileManager {
    profiles: Map<string, any> = new Map();
    
    getProfile(userId: string): any {
      if (!this.profiles.has(userId)) {
        this.profiles.set(userId, {
          workflow_preference: 'detailed',
          common_patterns: [],
          efficiency_history: []
        });
      }
      return this.profiles.get(userId);
    }
    
    updatePattern(userId: string, pattern: string): void {
      const profile = this.getProfile(userId);
      if (!profile.common_patterns.includes(pattern)) {
        profile.common_patterns.push(pattern);
      }
    }
  }
  
  // ========== 构造函数 ==========
  
  constructor(memory: UnifiedMemorySystem) {
    this.memory = memory;
    this.intentRecognizer = new IntentRecognizer();
    this.reflectionEngine = new ReflectionEngine();
    this.proactivePerceptor = new ProactivePerceptor(this);
    this.userProfileManager = new UserProfileManager();
  }
  
  // ========== V1.0 原始方法 ==========
  
  explicitizeTacitKnowledge(task: string, userResponses: Record<KnowledgeLevel, string>): TacitKnowledge[] {
    const results: TacitKnowledge[] = [];
    
    const levels: KnowledgeLevel[] = ['operation', 'experience', 'decision', 'thinking', 'value'];
    
    for (const level of levels) {
      if (userResponses[level]) {
        results.push({
          level,
          content: userResponses[level],
          discoveryMethod: this.getDiscoveryMethod(level),
          outputForm: this.getOutputForm(level)
        });
      }
    }
    
    return results;
  }
  
  private getDiscoveryMethod(level: KnowledgeLevel): string {
    const methods: Record<KnowledgeLevel, string> = {
      'operation': '直接记录',
      'experience': '提问引导',
      'decision': '情境假设',
      'thinking': '深度对话',
      'value': '深度对话'
    };
    return methods[level];
  }
  
  private getOutputForm(level: KnowledgeLevel): string {
    const forms: Record<KnowledgeLevel, string> = {
      'operation': '流程文档',
      'experience': '技巧清单',
      'decision': '决策树',
      'thinking': '思维模型',
      'value': '价值宣言'
    };
    return forms[level];
  }
  
  identifyCapabilityGenes(task: string, result: string, tacitKnowledge: TacitKnowledge[]): CapabilityGene[] {
    const genes: CapabilityGene[] = [];
    
    // 简单识别逻辑
    if (tacitKnowledge.length >= 3) {
      genes.push({
        name: '综合分析能力',
        category: 'thinking',
        description: '能够从多维度分析问题',
        manifestation: `在${task}中体现`,
        transferableScenarios: ['类似决策场景'],
        strength: 'medium'
      });
    }
    
    return genes;
  }
  
  buildMethodology(tacitKnowledge: TacitKnowledge[], capabilityGenes: CapabilityGene[]): Methodology {
    return {
      name: '工作方法论',
      levels: {
        philosophy: tacitKnowledge.find(t => t.level === 'value')?.content || '持续改进',
        principles: tacitKnowledge.filter(t => t.level === 'decision').map(t => t.content),
        methods: tacitKnowledge.filter(t => t.level === 'experience').map(t => t.content),
        processes: tacitKnowledge.filter(t => t.level === 'operation').map(t => t.content),
        tools: []
      },
      validation: '待验证'
    };
  }
  
  generateDailyWorkflowReport(date: string, tasks: string[], userResponses: Record<KnowledgeLevel, string>[]): {
    date: string;
    tasks: string[];
    tacitKnowledge: TacitKnowledge[];
    capabilityGenes: CapabilityGene[];
    methodologies: Methodology[];
  } {
    const tacitKnowledge: TacitKnowledge[] = [];
    const capabilityGenes: CapabilityGene[] = [];
    const methodologies: Methodology[] = [];
    
    for (let i = 0; i < tasks.length; i++) {
      const responses = userResponses[i] || {};
      const knowledge = this.explicitizeTacitKnowledge(tasks[i], responses);
      tacitKnowledge.push(...knowledge);
      
      const genes = this.identifyCapabilityGenes(tasks[i], '', knowledge);
      capabilityGenes.push(...genes);
      
      if (knowledge.length >= 3) {
        const methodology = this.buildMethodology(knowledge, genes);
        methodologies.push(methodology);
      }
    }
    
    // 存储到记忆
    for (const m of methodologies) {
      this.memory.addToL3({
        id: '', level: 'L3', category: 'methodology', key: m.name, value: m,
        tags: ['workflow', 'methodology'], importance: 4, system: this.systemName,
        createdAt: new Date().toISOString(), accessedAt: new Date().toISOString(), accessCount: 0
      });
    }
    
    return { date, tasks, tacitKnowledge, capabilityGenes, methodologies };
  }
  
  // ========== V1.1新增:意图识别方法 ==========
  
  /**
   * V1.1: 识别用户意图
   */
  recognizeIntent(input: string): { intent: IntentType; modules: string[]; mode: ExecutionMode } {
    return this.intentRecognizer.recognize(input);
  }
  
  // ========== V1.2新增:反思方法 ==========
  
  /**
   * V1.2: 反思评估
   */
  reflect(output: any): any {
    return this.reflectionEngine.evaluate(output);
  }
  
  // ========== V1.3新增:主动感知方法 ==========
  
  /**
   * V1.3: 主动感知
   */
  proactivePerceive(query: string): any {
    return this.proactivePerceptor.perceive(query);
  }
  
  // ========== V1.4新增:用户画像方法 ==========
  
  /**
   * V1.4: 获取用户画像
   */
  getUserProfile(userId: string): any {
    return this.userProfileManager.getProfile(userId);
  }
  
  /**
   * V1.4: 更新用户模式
   */
  updateUserPattern(userId: string, pattern: string): void {
    this.userProfileManager.updatePattern(userId, pattern);
  }
  
  // ========== 辅助查询方法 ==========
  
  queryL1Tasks(): MemoryEntry[] {
    return this.memory.queryL1('task');
  }
  
  queryL2Experience(): MemoryEntry[] {
    return this.memory.queryL2('', 'insight', 3);
  }
  
  queryL3Methodologies(): MemoryEntry[] {
    return this.memory.queryL3('methodology');
  }
  
  queryMethodologies(): Methodology[] {
    const entries = this.queryL3Methodologies();
    return entries.map(e => e.value as Methodology);
  }
  
  syncToOtherSystems(): void {
    const methodologies = this.queryL3Methodologies();
    this.memory.syncToSystem('signal', methodologies);
    this.memory.syncToSystem('goal', methodologies);
  }
}

```

multi-agent-collaboration | SkillHub