# Software Factory Core Layer

> **PR-36**：Software Factory Core — SF-01 ~ SF-15 全部 Factory 的统一入口。

---

## 目录

1. [架构定位](#架构定位)
2. [模块架构](#模块架构)
3. [Factory Contract](#factory-contract)
4. [Factory Registry](#factory-registry)
5. [Product Model](#product-model)
6. [Workflow Engine](#workflow-engine)
7. [Artifact Graph](#artifact-graph)
8. [Factory Reporting](#factory-reporting)
9. [使用示例](#使用示例)
10. [扩展性设计](#扩展性设计)

---

## 架构定位

```
┌──────────────────────────────────────────────────────────────┐
│               AI Software Company Layer (SF-01~SF-15)        │
│    SF-01 Strategy · SF-02 Requirement · SF-03 Design · ...   │
└────────────────────────────┬─────────────────────────────────┘
                             │ 注册并运行于
┌────────────────────────────▼─────────────────────────────────┐
│              Software Factory Core Layer (PR-36)              │
│                                                              │
│  Factory Contract  →  统一接口规范                             │
│  Factory Registry  →  SF-01~SF-15 元数据管理                   │
│  Product Model     →  统一产品模型                             │
│  Workflow Engine   →  Factory 编排引擎                        │
│  Artifact Graph    →  产物图谱与追踪                           │
│  Factory Reporting →  跨 Factory 报告体系                      │
└────────────────────────────┬─────────────────────────────────┘
                             │ 构建于
┌────────────────────────────▼─────────────────────────────────┐
│               Agent Runtime Layer (PR-35)                    │
│  Task · Pipeline · State Machine · Adapters · Reporting       │
└────────────────────────────┬─────────────────────────────────┘
                             │ 调用
┌────────────────────────────▼─────────────────────────────────┐
│          Quality Foundation (PR-01 ~ PR-34)                  │
│  Checklist · Baseline · Gate · Precompute · Memory · ...      │
└──────────────────────────────────────────────────────────────┘
```

### 层次关系

| 层次 | PR 编号 | 职责 |
|------|---------|------|
| Quality Foundation | PR-01 ~ PR-34 | 质量门禁、基线比较、发布检查、记忆系统 |
| Runtime Layer | PR-35 | 统一任务执行引擎、状态机、适配器 |
| **Factory Core Layer** | **PR-36** | **Factory 注册、编排、产品模型、产物追踪、报告** |
| AI Software Company | SF-01 ~ SF-15 | 具体 Factory 实现（产品战略到公司运营） |

---

## 模块架构

```
src/software-factory-core/
├── index.mjs                 # Barrel export（唯一入口）
├── factory-contract.mjs      # Part B：统一 Factory 接口
│   ├── FactoryInput          # 进入 Factory 的输入
│   ├── FactoryOutput         # Factory 产出
│   ├── FactoryArtifact       # 产物（10 种类型）
│   ├── FactoryMetric         # 度量指标（8 种类型）
│   ├── FactoryReport         # 报告（5 种类型）
│   └── FactoryDependency     # Factory 间依赖（4 种类型）
├── factory-registry.mjs      # Part A：Factory 注册中心
│   ├── SF-01 ~ SF-15 元数据定义
│   ├── 按领域/依赖/状态查询
│   ├── 拓扑排序 + 并行批次
│   └── 实现注册与执行
├── product-model.mjs         # Part C：统一产品模型
│   ├── 15 种产品组件类型
│   ├── 生命周期管理（8 阶段）
│   └── 默认技术栈推荐
├── workflow-engine.mjs       # Part D：Factory 编排引擎
│   ├── 4 种执行模式
│   ├── 4 种失败策略
│   ├── 标准 Factory 流程
│   └── 条件执行支持
├── artifact-graph.mjs        # Part E：产物图谱
│   ├── 节点 + 边模型
│   ├── 图遍历（祖先/后代/依赖链）
│   ├── 完整性校验
│   └── 按多维度检索
└── factory-reporting.mjs     # Part F：报告体系
    ├── Factory Report
    ├── Project Report
    ├── Product Report
    ├── Release Report
    └── Business Report
```

---

## Factory Contract

所有 SF-01 ~ SF-15 必须遵守的统一接口：

| 类型 | 作用 | 必填字段 |
|------|------|----------|
| `FactoryInput` | Factory 入参 | `factoryId` |
| `FactoryOutput` | Factory 出参 | `factoryId`, `status` |
| `FactoryArtifact` | Factory 产物 | `kind`, `name`, `factoryId` |
| `FactoryMetric` | 度量指标 | `factoryId`, `name`, `value` |
| `FactoryReport` | 标准化报告 | `type`, `title` |
| `FactoryDependency` | Factory 间依赖 | `from`, `to` |

### Artifact 种类（10 种）

```
requirement → prototype → design → architecture → code
→ test → release → report → operations → marketing
```

### 依赖种类（4 种）

| Kind | 含义 | 行为 |
|------|------|------|
| `hard` | 硬依赖 | 上游失败 → 下游阻断 |
| `soft` | 软依赖 | 上游失败 → 下游可继续 |
| `data` | 数据依赖 | 上游产物作为下游输入 |
| `trigger` | 触发依赖 | 上游完成触发下游启动 |

---

## Factory Registry

注册 SF-01 ~ SF-15 共 15 个 Factory：

| ID | 名称 | 领域 | 核心 input → output |
|----|------|------|---------------------|
| SF-01 | 产品战略工厂 | product-strategy | other → requirement, report |
| SF-02 | 需求工程工厂 | requirement-engineering | requirement → requirement, prototype |
| SF-03 | 产品设计工厂 | product-design | requirement → design, prototype |
| SF-04 | 视觉设计工厂 | visual-design | design → design |
| SF-05 | 技术架构工厂 | architecture | requirement, design → architecture, code |
| SF-06 | 平台规划工厂 | platform-planning | architecture → architecture, report |
| SF-07 | 全栈开发工厂 | full-stack-development | architecture, design, requirement → code, test |
| SF-08 | Agent 协作工厂 | agent-collaboration | requirement, code → code, report |
| SF-09 | 质量治理工厂 | quality-governance | code, test, architecture → report |
| SF-10 | 测试工厂 | testing | code, architecture → test, report |
| SF-11 | 发布工厂 | release | code, test, report → release, report |
| SF-12 | 运维工厂 | operations | release, report → operations, report |
| SF-13 | 演进工厂 | evolution | operations, report → requirement, report |
| SF-14 | 增长工厂 | growth | operations, report → report, marketing |
| SF-15 | 软件公司工厂 | software-company | report → report |

### Registry API

```javascript
const registry = createFactoryRegistry();

registry.get("SF-07");                    // → Factory 元数据
registry.list({ domain: "testing" });      // → 按领域过滤
registry.getDependencies("SF-07");         // → 上游依赖
registry.getDependents("SF-05");          // → 下游依赖者
registry.getTopologicalOrder();           // → 拓扑排序
registry.getParallelBatches();            // → 并行批次

// 注入实现
registry.registerImplementation("SF-07", myFullStackFactory);
registry.execute("SF-07", input);         // → FactoryOutput
```

---

## Product Model

### 产品组件类型（15 种）

```
Desktop App / Web App / Official Website / Admin System
Backend Service / Database / Android App / iOS App
Mini Program / API Platform / Payment System
Account System / License System / Download Center
Update Service
```

### 生命周期（8 阶段）

```
concept → planning → development → testing
→ staging → production → maintenance → sunset
```

---

## Workflow Engine

### 执行模式（4 种）

| 模式 | 行为 |
|------|------|
| `sequential` | 按 stages 顺序逐个执行 |
| `parallel` | 并行执行所有阶段（忽略依赖） |
| `dependency` | 按依赖图自动排序，批量并行执行 |
| `conditional` | 按条件逐个执行 |

### 标准流程（13 阶段）

```
SF-01 Strategy
  ↓
SF-02 Requirement
  ↓
SF-03 Design ──→ SF-05 Architecture
  ↓                    ↓
SF-04 UI          SF-06 Platform Planning
  ↓                    ↓
  └──────→ SF-07 Development ←──────┘
               ↓
       SF-09 Quality ──→ SF-10 Testing
               ↓               ↓
       └──────→ SF-11 Release ←──────┘
                    ↓
               SF-12 Operations
                    ↓
       SF-14 Growth ──→ SF-13 Evolution
```

### 失败策略（4 种）

| 策略 | 行为 |
|------|------|
| `stop` | 遇失败立即停止工作流 |
| `continue` | 记录失败，继续执行 |
| `retry` | 自动重试（最多 maxRetries 次） |
| `fallback` | 执行备选路径 |

---

## Artifact Graph

### 图结构

- **节点 (ArtifactNode)**: 产物（代码/文档/测试/报告/…）
- **边 (ArtifactEdge)**: 关系（依赖/产出/派生/包含/…）

### 关系类型（8 种）

```
depends_on / produces / parent_of / derived_from
references / contains / input_to / related_to
```

### 图操作

```javascript
const graph = createArtifactGraph();
graph.addNode(node);
graph.addEdge(edge);

graph.getAncestors(nodeId);        // 追溯依赖祖先
graph.getDescendants(nodeId);      // 追溯下游依赖者
graph.getDependencyChain(nodeId);  // 拓扑排序依赖链
graph.getDirectDependencies(nodeId);
graph.getDirectDependents(nodeId);
graph.validateAll();               // 完整性校验
```

---

## Factory Reporting

| 报告类型 | 内容 |
|----------|------|
| Factory Report | 单 Factory 执行摘要、产物、风险、决策 |
| Project Report | 多 Factory 聚合、风险总结、建议 |
| Product Report | 产品状态、组件、生命周期、质量评估 |
| Release Report | 发布决策、认证、测试结果、制品 |
| Business Report | 产品组合、Factory 舰队、关键指标 |

---

## 使用示例

### 注册并执行 Factory

```javascript
import { createFactoryRegistry, createFactoryInput, createFactoryOutput,
         createFactoryArtifact, createFactoryMetric } from './src/software-factory-core/index.mjs';

const registry = createFactoryRegistry();

// 注入 SF-07 实现
registry.registerImplementation("SF-07", (input) => {
  return createFactoryOutput({
    factoryId: "SF-07",
    status: "passed",
    artifacts: [
      createFactoryArtifact({ kind: "code", name: "auth.ts", factoryId: "SF-07" }),
    ],
    metrics: [
      createFactoryMetric({ factoryId: "SF-07", name: "loc", value: 350, kind: "count", unit: "lines" }),
    ],
    nextActions: ["Run tests"],
  });
});

// 执行
const input = createFactoryInput({ factoryId: "SF-07" });
const output = registry.execute("SF-07", input);
console.log(output.status); // "passed"
```

### 编排 Workflow

```javascript
import { createStandardFactoryWorkflow, executeWorkflow } from './src/software-factory-core/index.mjs';

const wf = createStandardFactoryWorkflow();
const result = await executeWorkflow(wf, registry, { product });
console.log(result.status); // "completed"
```

### 产物追踪

```javascript
import { createArtifactGraph, createArtifactNode, createArtifactEdge } from './src/software-factory-core/index.mjs';

const graph = createArtifactGraph();
const prd = createArtifactNode({ kind: "requirement", name: "PRD v1", factoryId: "SF-02" });
const design = createArtifactNode({ kind: "design", name: "Wireframe", factoryId: "SF-03" });

graph.addNode(prd);
graph.addNode(design);
graph.addEdge(createArtifactEdge({ from: design.id, to: prd.id, relation: "depends_on" }));

const chain = graph.getDependencyChain(design.id);
// → [prd, design] (topological order)
```

---

## 扩展性设计

### 原则

1. **禁止硬编码 Factory 实现** — Registry 只管理元数据，实现通过 `registerImplementation()` 外部注入
2. **保持兼容** — 不修改 `src/agent-runtime/` 任何文件，不修改现有测试
3. **保持可扩展** — `metadata` 字段支持 vendor extensions，自定义 Factory 可在 SF-15 之后添加
4. **纯函数优先** — 数据模型为不可变创建模式，引擎为纯函数

### 未来扩展点

- 在 SF-01~SF-15 之外注册 `SF-16+`
- 实现持久化 Artifact Graph（替换内存 Map）
- 添加 Workflow 可视化（Mermaid/DAG 输出）
- 集成 CI/CD（自动化 Workflow 触发）

---

*PR-36 — Software Factory Core Layer。SF-01 ~ SF-15 的根基。*
