# PORTFOLIO.md — Portfolio Management Protocol 📊

> **Canonical Reference.** This file defines the Portfolio Management layer.
> Portfolio Management controls multi-project orchestration across the workspace.
> Every project in the workspace MUST be registered in this protocol.

<!-- openclaw:portfolio:doctag -->

---

## §0 Purpose

| Layer | File | Scope |
|-------|------|-------|
| Execution Protocol | AGENTS.md | 单任务怎么做 |
| Execution Governance | GOVERNANCE.md | 单项目怎么管 |
| **Portfolio Management** | **PORTFOLIO.md** | **多项目怎么排** |

**Execution Governance 管理单项目。Portfolio Management 管理多项目。**

### Core Objective

最大化：

| Metric | Why |
|--------|-----|
| **Delivery** | 按时交付率 |
| **ROI** | 投入产出比 |
| **Agent Utilization** | 人力不空转 |
| **Learning Reuse** | 知识不重复造 |

最小化：

| Metric | Why |
|--------|-----|
| **Context Waste** | 上下文切换开销 |
| **Idle Agents** | 空转成本 |
| **Duplicate Work** | 两个项目写同一份代码 |
| **Failed Projects** | 及早止损 |

---

## §1 Portfolio Registry

必须维护 `portfolio.md`（项目根目录）。

### §1.1 Schema

```markdown
# Portfolio Registry

<!-- Last Updated: YYYY-MM-DDTHH:mm:ss+08:00 -->
<!-- Canonical Reference: PORTFOLIO.md §1 -->

## Projects

| Project-ID | Name | Status | Priority | Health | Agents | Progress | Last Updated | ROI |
|------------|------|--------|----------|--------|--------|----------|-------------|-----|
| P-001 | Project Alpha | ACTIVE | P1 | 85 | 3 | 65% | YYYY-MM-DD | 2.4 |
| P-002 | Project Beta | PLANNING | P2 | — | 1 | 0% | YYYY-MM-DD | 1.8 |
```

### §1.2 Field Definitions

| Field | Required | Values | Description |
|-------|----------|--------|-------------|
| Project-ID | ✅ | `P-NNN` | 唯一项目标识 |
| Name | ✅ | string | 项目名称 |
| Status | ✅ | §2 Allowed States | 当前项目状态 |
| Priority | ✅ | §3 Priority System | 优先级 |
| Health | ✅ | 0–100, or `—` if PLANNING | 从 Project Health Aggregation (§7) 同步 |
| Agents | ✅ | ≥1 | 分配 Agent 数 |
| Progress | ✅ | 0–100% | 完成进度 |
| Last Updated | ✅ | ISO-8601 | 最后更新 |
| ROI | ✅ | float | ROI 评分 |

### §1.3 Registry Update Rule

| Event | Action |
|-------|--------|
| 新项目创建 | 立即注册，状态 PLANNING |
| 项目状态变更 | 更新 Status + Last Updated |
| Health Score 更新 | 同步 Health 列 |
| Agent 分配变更 | 更新 Agents 列 |
| 每日审计 | 检查所有字段一致性 |

---

## §2 Project States

### §2.1 Allowed States (7)

```
PLANNING
ACTIVE
BLOCKED
RECOVERY
PAUSED
COMPLETED
ARCHIVED
```

禁止自定义状态。

### §2.2 State Transition Diagram

```mermaid
stateDiagram-v2
    [*] --> PLANNING
    PLANNING --> ACTIVE
    PLANNING --> ARCHIVED

    ACTIVE --> BLOCKED
    ACTIVE --> RECOVERY
    ACTIVE --> COMPLETED
    ACTIVE --> PAUSED

    BLOCKED --> ACTIVE
    BLOCKED --> PAUSED
    BLOCKED --> RECOVERY

    RECOVERY --> ACTIVE
    RECOVERY --> PAUSED

    PAUSED --> ACTIVE
    PAUSED --> ARCHIVED

    COMPLETED --> ARCHIVED

    ARCHIVED --> [*]
```

### §2.3 Transition Rules

| From | To | Condition |
|------|----|-----------|
| PLANNING | ACTIVE | 资源已分配，可以启动 |
| PLANNING | ARCHIVED | 取消启动 |
| ACTIVE | BLOCKED | 遇到阻塞，见 GOVERNANCE.md §3 |
| ACTIVE | RECOVERY | Health < 50 或连续失败 > 3 |
| ACTIVE | COMPLETED | 所有交付物完成，Governance Quality Gate 通过 |
| ACTIVE | PAUSED | 低优先级 / 资源不足 / 依赖阻塞 |
| BLOCKED | ACTIVE | 阻塞解除 |
| BLOCKED | PAUSED | 阻塞短期内无法解决 |
| BLOCKED | RECOVERY | 需要恢复计划 |
| RECOVERY | ACTIVE | Recovery Plan 通过审批 |
| RECOVERY | PAUSED | Recovery 无法推进 |
| PAUSED | ACTIVE | 条件满足，恢复执行 |
| PAUSED | ARCHIVED | 确认不再恢复 |
| COMPLETED | ARCHIVED | 归档 |

### §2.4 Prohibited Transitions

```
PLANNING  → COMPLETED   ❌
ACTIVE    → ARCHIVED    ❌（必须经过 COMPLETED 或 PAUSED）
BLOCKED   → COMPLETED   ❌
RECOVERY  → COMPLETED   ❌
RECOVERY  → ARCHIVED    ❌（必须经过 PAUSED）
PAUSED    → COMPLETED   ❌（必须经过 ACTIVE）
```

---

## §3 Priority System

### §3.1 Priority Levels

| Level | Label | Description | Action |
|-------|-------|-------------|--------|
| P0 | Mission Critical | 生产事故 / 安全漏洞 / 合同违约风险 | 立即暂停其他项目，全资源投入 |
| P1 | High Value | 核心交付 / 里程碑 / 高 ROI | 优先分配 Agent，保留资源 |
| P2 | Normal | 日常任务 / 迭代交付 | 按计划进行 |
| P3 | Low Priority | 探索 / 优化 / 非紧急 | 资源空闲时执行，随时可 PAUSE |

### §3.2 Priority Escalation

| Event | Action |
|-------|--------|
| 新 P0 出现 | 自动暂停所有 < P1 项目 |
| P1 项目连续 3 次 heartbeat 无进展 | 评估是否升级 |
| P3 项目 Health 持续 > 90 | 评估是否升级到 P2 |

### §3.3 Priority Collision Resolution

如果多个 P0 同时出现：

1. 按 ROI 排序
2. 按 Agent 依赖链排序（阻塞其他项目的优先）
3. 如无法抉择 → 通知红尘

---

## §4 Resource Allocation

### §4.1 Agent Inventory

| Metric | Definition |
|--------|------------|
| Total Agents | workspace 可用 Agent 总数 |
| Busy Agents | 当前 ACTIVE 项目占用的 Agent 数 |
| Idle Agents | Total − Busy − Blocked − Recovery |
| Blocked Agents | 在 BLOCKED 项目中的 Agent 数 |
| Recovery Agents | 在 RECOVERY 项目中的 Agent 数 |

### §4.2 Agent Utilization Score

```
Utilization = Busy_Agents / Total_Agents
```

| Range | Rating | Action |
|-------|--------|--------|
| ≥ 90% | **Optimal** | 满负荷运转，监控疲劳风险 |
| ≥ 80% | Good | 正常利用 |
| ≥ 70% | Acceptable | 有轻微空闲，可接受 |
| < 70% | **Waste** | 资源严重浪费，启动新项目或合并 |

### §4.3 Resource Rebalancing

| Condition | Action |
|-----------|--------|
| Utilization < 70% | 启动 backlog 中的 P1/P2 项目 |
| P0 出现且 Utilization > 90% | 暂停 P2/P3 项目释放资源 |
| 某个项目连续 idle > 3 heartbeats | 评估是否应该 PAUSE |
| Blocked Agents > 30% | 优先解除阻塞或 kill 项目 |

---

## §5 Project Health Aggregation

### §5.1 Health Dimensions

Portfolio-level Project Health 综合 GOVERNANCE.md §7 的各维度，并且增加 Portfolio 层的维度：

| Dimension | Weight | Source |
|-----------|--------|--------|
| **Delivery Score** | 25% | GOVERNANCE.md §7 (D1) |
| **Quality Score** | 20% | GOVERNANCE.md §7 (D2) |
| **Learning Score** | 15% | GOVERNANCE.md §7 (D5) |
| **Execution Score** | 25% | 基于 progress.log 的心跳密度和状态迁移频率 |
| **Risk Score** | 15% | Blocker 数量 / 严重度 / Duration 的加权 |

### §5.2 Execution Score (Portfolio-specific)

```
Execution_Score = max(0, 100 - staled_heartbeats_ratio × 50 - stalled_transitions × 20)
```

- `staled_heartbeats_ratio`: 过期心跳占总心跳比例
- `stalled_transitions`: 同一状态停留超过 2 倍 stale 阈值的次数

### §5.3 Risk Score (Portfolio-specific)

```
Risk_Score = max(0, 100 - active_blockers × 15 - critical_blockers × 30 - avg_blocker_age_hours × 2)
```

### §5.4 Final Project Health

```
Project_Health = Delivery × 0.25 + Quality × 0.20 + Learning × 0.15 + Execution × 0.25 + Risk × 0.15
```

---

## §6 Portfolio Health Score

### §6.1 Calculation

```
Portfolio_Health = Σ(Project_Health_i × Agent_Count_i) / Σ(Agent_Count_i)
```

按 Agent 数加权的项目健康度平均值。大项目权重高。

### §6.2 Rating

| Range | Rating | Meaning |
|-------|--------|---------|
| 90–100 | **EXCELLENT** | 所有项目健康运转 |
| 80–89 | GOOD | 整体良好，个别关注 |
| 70–79 | ACCEPTABLE | 有风险项目需关注 |
| 60–69 | AT RISK | 多个项目有问题 |
| < 60 | **CRITICAL** | 整条 Portfolio 出问题 |

---

## §7 Learning Reuse Detector

### §7.1 Detection

检查 workspace 中是否多个项目在解决同一问题。

| Signal | Detection Method |
|--------|-----------------|
| 重复模块 | 跨项目文件结构对比 |
| 重复技术选型问题 | Memory Search / ctx_search |
| 重复错误模式 | Reflection 中的 Pattern Class 比较 |
| 重复工具配置 | Shell 配置 / CI config 对比 |

### §7.2 Duplicate Work Criteria

如果满足 **任意两条**：

1. 两个项目的文件清单有 > 30% 重叠
2. 两个项目的 Reflection 中有相同 Pattern Class
3. 两个项目引用了相同的外部依赖且版本相同
4. 两个项目处理了相同的业务域（如 "Auth Module" × 2）

→ 判定 **DUPLICATE WORK**

### §7.3 Required Action

检测到 DUPLICATE WORK 后：

1. **Stop** — 暂停重复部分的开发
2. **Extract** — 抽象为 Shared Package / Shared Service
3. **Refactor** — 两个项目都依赖共享包
4. **Audit** — 记录在 portfolio-audit.md 中
5. **Promote** — 如果 Shared Package 质量过关，纳入 workspace 固化工具集

### §7.4 Prevention

- 新项目启动前，先搜索 workspace 中是否有可复用模块
- 使用 `ctx_search` 或 `memory_search` 检查已有 Pattern
- 设计阶段标注 "可能复用" 候选

---

## §8 Portfolio Audit

### §8.1 Daily Generation

每日生成 `portfolio-audit.md`。

**文件位置:** `<workspace>/portfolio-audit.md`（覆盖式写入）

### §8.2 Audit Schema

See `protocol-reference/templates.md` §portfolio-audit for full schema.

---

## §9 Project Kill Rule

### §9.1 Kill Conditions

满足**任意一条**：

| # | Condition | Threshold |
|---|-----------|-----------|
| K1 | Project Health | < 50 |
| K2 | Continuous Recovery Failure | > 3 次 |
| K3 | ROI Score | < threshold（由项目类型决定） |
| K4 | Scope Explosion × Low Priority | SCOPE EXPLOSION + P3 |

### §9.2 Kill Procedure

1. 标记为 KILL CANDIDATE
2. 生成 Kill Report（包含 Kill Condition、累计投入、已产出）
3. 通知用户审批
4. 审批通过 → 归档项目（PLANNING → ARCHIVED 跳过 ACTIVE）
5. 审计记录 kill 原因和 lessons learned

### §9.3 Graceful Shutdown

即使 kill，也要完成：

- 代码提交（如果写了任何有价值的东西）
- Reflection（记录为什么失败）
- 文档归档（Knowledge 不浪费）

---

## §10 Project Pause Rule

### §10.1 Pause Conditions

满足**任意一条**：

| # | Condition | Threshold |
|---|-----------|-----------|
| P1 | Priority | P3 |
| P2 | Resource Scarcity | Utilization > 90% + 有 P0/P1 等待 |
| P3 | Dependency Blocked | 依赖链阻塞，预计 > 48h 无法解除 |

### §10.2 Pause Procedure

1. 状态 → PAUSED
2. 释放 Agent 资源
3. 在 portfolio.md 中记录 pause reason
4. 设置自动唤醒条件（如：dependency resolved / P0 cleared）

### §10.3 Resume Decision

PAUSED 项目在满足以下条件时评估是否恢复：

- 阻塞原因已解除
- 有可用 Agent 资源（Utilization < 80%）
- Priority 未被降级

---

## §11 Project Promotion Rule

### §11.1 Fast Track Criteria

满足**全部**条件：

| # | Condition | Threshold |
|---|-----------|-----------|
| F1 | Project Health | > 90 |
| F2 | Progress | > 80% |
| F3 | Risk Score | < 20（无高严重度 blocker） |

### §11.2 Fast Track Benefits

- 优先分配 Agent（可抢占 P2/P3 资源）
- 加速 Review 周期
- 更多 Learning Reuse 资源（协助提取 Shared Package）

### §11.3 Demotion

如果 Fast Track 项目连续 2 个心跳不满足 F1/F2/F3 → 自动降级回正常轨道。

---

## §12 Executive Dashboard

### §12.1 Dashboard Generation

生成 `dashboard.md`。

**文件位置:** `<workspace>/dashboard.md`（覆盖式写入，每日更新）

### §12.2 Dashboard Schema

See `protocol-reference/templates.md` §dashboard for full schema.

---

## §13 Portfolio Quality Gate

### §13.1 Pre-Output Checklist

See `protocol-reference/quality-gates.md` §PORTFOLIO for full checklist.

### §13.2 Gate Failure

若任意一项未通过：

```
❌ PORTFOLIO GOVERNANCE FAILED — Portfolio 治理失败。
```

必须修复后才能继续 Portfolio 管理。

---

## §14 Integration Summary

```text
AGENTS.md (Execution)        GOVERNANCE.md (Governance)      PORTFOLIO.md (Portfolio)
│                           │                               │
├─ §0 Classify              ├─ §0 Purpose                   ├─ §0 Purpose
├─ §1 Task Tree             ├─ §1 State Machine             ├─ §1 Portfolio Registry
├─ §2 PLAN                  ├─ §2 Heartbeat                 ├─ §2 Project States
├─ §3 Pre-flight            ├─ §3 Blocker                   ├─ §3 Priority System
├─ §4 Failure Replanning    ├─ §4 Replanning                ├─ §4 Resource Allocation
├─ §5 Verification          ├─ §5 Scope Explosion           ├─ §5 Project Health Aggregation
│                           ├─ §6 Execution Audit           ├─ §6 Portfolio Health Score
│                           ├─ §7 Health Score              ├─ §7 Learning Reuse Detector
│                           ├─ §8 Auto-Stop                 ├─ §8 Portfolio Audit
│                           ├─ §9 Quality Gate              ├─ §9 Project Kill Rule
│                           ├─ §10 State Initialization     ├─ §10 Project Pause Rule
│                           └─ §11 Integration              ├─ §11 Project Promotion Rule
│                                                           ├─ §12 Executive Dashboard
│                                                           ├─ §13 Portfolio Quality Gate
│                                                           └─ §14 Integration Summary
```

### §14.1 Data Flow

```
AGENTS.md §5 Verification
    → Governance Quality Gate (GOVERNANCE.md §9)
        → Project Health (GOVERNANCE.md §7)
            → Portfolio Registry (PORTFOLIO.md §1)
                → Portfolio Health (PORTFOLIO.md §6)
                    → Portfolio Audit (PORTFOLIO.md §8)
                        → Dashboard (PORTFOLIO.md §12)
```

### §14.2 Lifecycle

```
Project Start
    → PORTFOLIO.md §1: Register project
    → GOVERNANCE.md §10: Init governance state
    → AGENTS.md §0: Start execution

Project Active
    → AGENTS.md §1–5: Execute
    → GOVERNANCE.md: Heartbeat / Blocker / Audit
    → PORTFOLIO.md §8: Portfolio Audit

Project End
    → GOVERNANCE.md §9: Governance Quality Gate
    → PORTFOLIO.md §2: Mark COMPLETED
    → PORTFOLIO.md §1: Update Registry
    → PORTFOLIO.md §8: Final Audit
    → PORTFOLIO.md §12: Update Dashboard
```

---

> **Integrity Check:** This document completes the three-layer architecture.
> PORTFOLIO.md, GOVERNANCE.md, and AGENTS.md form a coherent stack.
> Any amendment to one layer must check consistency with the other two.
