# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.7.0] - 2026-09-10

### 🐛 Archive Integrity — 归档完整性与变更工作区收口

修复归档时静默损坏主规范、遗漏执行记录的结构性缺陷，建立变更路径的唯一真相源。

#### 修复

- **delta 代码围栏占位符泄漏**（`src/core/archive/delta-merger.ts`）：`mergeDeltaSpec()` 此前只还原主规范侧掩码表，delta 侧 `deltaPlaceholders` 从未还原，导致 delta 需求块含 ``` 围栏（JSON/YAML/示例代码）时归档后主规范出现 `__CODE_FENCE_0__` 字面量
  - `maskCodeFences(content, namespace?)` 新增可选命名空间，主规范与 delta 分别使用 `__CODE_FENCE_base_<n>__` / `__CODE_FENCE_delta_<n>__`，缺省保持旧格式以兼容
  - 冲突提前返回路径与正常返回路径均还原两侧掩码
  - `unmaskCodeFences()` 由 `replace()` 改为 `split()/join()`，全量替换且不解析 `$&`、`$1`、`$$` 替换语义，围栏内容逐字节一致

#### 新增

- **ChangeWorkspace 模块**（`src/core/workspace/`）：变更路径唯一真相源
  - `createChangeWorkspace(projectRoot, changeName, config)` 统一解析 `root` / `sddDir` / `ledgerPath`
  - `artifacts()` 返回有序产物清单，`hasLegacySdd()` 提供遗留 `.specpow/sdd/<change>/` 只读兜底
- **`specpow doctor` 归档健康自检**：扫描主规范中的 `__CODE_FENCE_` 残留（报告文件与行号），检测待迁移的遗留 SDD 工作区，并入输出与退出码
- **归档元数据清单化**：`_ARCHIVE_METADATA.json` 新增 `artifacts` 字段记录本次归档产物

#### 变更

- **`sdd.workspaceDir` 语义变更（破坏性）**：由"变更工作区路径"改为"变更目录内的 SDD 子目录名"，默认值 `.specpow/changes` → `sdd`；SDD 工作区固定为 `<changesDir>/<change>/sdd/`，`.` 表示工件直接位于变更目录根部
- **ArchiveEngine 清单驱动归档**：`archive()` 依据 `ChangeWorkspace.artifacts()` 搬运，归档目录必然包含账本 `progress.md` 与全部 `task-*-brief` / `task-*-report` / `review*`；`rollback()` 整体回收归档目录并保留已并入的统一位置
- **命令层路径收口**：`apply` / `execute` / `status` / workflow gate 移除散落的 `join(config.sdd.workspaceDir, ...)`，统一改用 `ChangeWorkspace`
- **技能文档路径对齐**：`builtin/skills/` 中 `.specpow/sdd/{change}` → `.specpow/changes/{change}/sdd`，并修正 `execution-sdd-orchestrator` 中过时的 `.specpow/openspec/changes/{change}`

#### 迁移

- 新增迁移步骤 `normalize-sdd-workspace`：将遗留 `.specpow/sdd/<change>/` 及散落在变更目录根部的 SDD 工件（`progress.md`、`task-*-brief.md`、`task-*-report.md`、`review*.md`、`review-result.json`、`re-review-result.json`）移动至 `<changesDir>/<change>/sdd/`，并把 `config.sdd.workspaceDir` 改写为 `sdd`；幂等、失败不删除源、支持 `dryRun`

#### 注意

- 若你的脚本或 CI 手工依赖 `sdd.workspaceDir` 旧值（`.specpow/changes`）拼接路径，需改为使用变更目录内的 `sdd/` 子目录；可通过 `specpow doctor` 确认迁移状态

#### 测试

- 新增 `test/delta-merger-enhanced.test.ts`（围栏合并回归：MODIFIED/ADDED 围栏、双侧同名索引互不串扰、`$&`/`$1`/`$$` 保留、冲突路径无残留）
- 新增 `test/change-workspace.test.ts`、`test/doctor-archive-check.test.ts`
- 扩充 `test/archive-engine.test.ts`（归档含 sdd 子目录、遗留 sdd 并入与清理、artifacts 清单、回滚还原）、`test/migration.test.ts`（移动/幂等/原位置清理）

## [0.6.1] - 2026-09-10

### 🔧 mes-prd-to-code Schema 规则修正

统一后端 Excel 导出/导入公共基类约定，修正包路径错误。

#### 变更内容

- **后端公共类引用规则**：导出统一使用 `BaseExcelExportTemplate`、导入统一使用 `BaseAnalysisEventListener`（均为 `com.twsz.mom.ds.util.excel`）
- **后端 Controller 规范**：导出/导入逻辑封装在 ServiceImpl，Controller 只负责调用
- **EasyExcel 白名单**：仅允许 `EasyExcel.read(...)`（作为 `BaseAnalysisEventListener` 的驱动入口）；禁止 `EasyExcel.write(...)`、`doReadSync()`
- **ExcelUtil 废弃**：`com.twsz.mom.web.utils.ExcelUtil` 标注为已废弃，禁止使用
- 修正 `BaseExcelExportTemplate` 包路径（`core.web.excel` → `ds.util.excel`）并补齐 API 说明（`getTotal()`、`getData(start, size)`，start 从 1 开始）
- `templates/tech-design.md` 伪代码由 `uploadExcel(List<T>)` 改为 `export(...)` + `handle(List<T>)`

## [0.5.29] - 2026-08-31

### ✨ Memory Auto Adapter 系统

新增自动从 Claude Code 和 CodeBuddy 读取会话日志并索引的功能，实现跨会话记忆能力。

#### 新增功能

- **SessionAdapter 接口**（`src/core/memory/memory-types.ts`）
  - 定义统一的会话适配器接口
  - 支持 detect/listProjects/listSessions/loadSession 操作

- **Claude Code 适配器**（`src/core/memory/adapters/claude-code-adapter.ts`）
  - 解析 `~/.claude/projects/{project}/{sessionId}.jsonl` 格式
  - 支持 JSONL 消息格式（user/assistant/system）
  - 自动检测项目路径编码（`:` 和 `/` 替换为 `-`）

- **CodeBuddy 适配器**（`src/core/memory/adapters/codebuddy-adapter.ts`）
  - 解析 `%LOCALAPPDATA%/CodeBuddyExtension/Data/{userId}/JetBrains/{userId}/history/{projectHash}/` 格式
  - 支持嵌套 JSON 消息格式（index.json + messages/*.json）
  - 自动计算 projectHash（MD5）

- **适配器注册表**（`src/core/memory/adapters/index.ts`）
  - 统一管理所有会话适配器
  - 支持数据源检测、会话索引、去重机制

- **自动采集调度器**（`src/core/memory/adapters/auto-collector.ts`）
  - 增量索引（基于 sessionId + timestamp 去重）
  - 防抖机制（30 秒内不重复执行）
  - 状态持久化（`.specpow/memory/last-index.json`）

- **记忆注入器**（`src/core/memory/memory-injector.ts`）
  - Token 预算控制（explore:300, propose:500, apply:400, verify:200）
  - 增强关键词提取（支持 kebab-case、camelCase、中文）
  - 上下文感知查询（从变更名称、用户输入、任务描述、涉及文件综合提取）
  - 支持全阶段查询和自定义关键词

- **阶段摘要模板**（`src/core/memory/templates/`）
  - 标准化摘要格式（元信息、关键决策、问题、产出物、建议）
  - 模板渲染器（`renderPhaseSummary()`）

- **配置扩展**（`src/core/config/config-schema.ts`）
  - `memory.adapters` — 适配器配置（claudeCode/codebuddy）
  - `memory.indexing` — 索引配置（autoIndex/debounceSeconds）
  - `memory.injection` — 注入配置（maxEntries/minRelevance/tokenBudgets）
  - `memory.retention` — 保留配置（archiveOnComplete/timeDecayHalflifeDays）

- **CLI 命令扩展**（`src/commands/memory.ts`、`src/cli/index.ts`）
  - `specpow memory auto-index` — 自动索引所有数据源
  - `specpow memory index-summary <file>` — 索引阶段摘要文件
  - `specpow memory sources` — 显示检测到的数据源
  - `specpow memory preview-injection` — 预览记忆注入内容
    - `--all-phases` — 查询所有阶段
    - `--keywords` — 自定义关键词
    - `--user-input` — 用户输入增强
    - `--task-description` — 任务描述增强
    - `--files` — 涉及文件增强

- **初始化流程扩展**（`src/core/init/engine.ts`）
  - Phase 8: Memory 数据源检测
  - 生成 `.specpow/memory/sources.json`

- **归档集成**（`src/commands/archive.ts`）
  - 变更归档时自动归档相关记忆
  - 记忆移入 `.specpow/memory/archives/{year}-{month}.json`

- **SKILL 文件更新**
  - `planning-explore/SKILL.md` — 增加记忆查询和摘要生成步骤
  - `planning-propose/SKILL.md` — 增加历史记忆参考步骤
  - `execution-sdd-orchestrator/SKILL.md` — Brief 模板增加历史上下文段落

#### 使用示例

```bash
# 自动索引所有数据源
specpow memory auto-index

# 查看检测到的数据源
specpow memory sources

# 预览记忆注入（基础）
specpow memory preview-injection --change my-change --phase apply

# 预览记忆注入（增强）
specpow memory preview-injection --phase apply \
  --all-phases \
  --keywords "适配器,会话,索引" \
  --user-input "实现功能" \
  --task-description "任务描述" \
  --files "src/file.ts"
```

## [0.5.1] - 2026-08-23

### ✨ Delta Spec 名称一致性优化

- **主规范名称清单注入**（`src/core/templates/index.ts`）
  - 问题: 主规范超过 2000 字符时截断，AI 看不到截断点后的需求名称
  - 修复: 截断前提取所有需求名称清单，始终注入到 AI prompt

- **路由失败警告**（`src/core/archive/engine.ts`）
  - 问题: MODIFIED/REMOVED 名称不匹配时操作被静默丢弃
  - 修复: `routeDeltaOperations()` 收集未路由操作，生成 `名称未匹配` 警告

- **新增 `validate-specs` 命令**（`src/commands/validate-specs.ts`）
  - 提前验证 delta spec 中 MODIFIED/REMOVED/RENAMED 名称与主规范匹配
  - 基于编辑距离提供近似名称建议（阈值 ≤ 3）
  - 支持 `--change` 和 `--json` 选项

- **apply 预验证**（`src/commands/apply.ts`）
  - 执行前自动检测 delta spec 名称不匹配并警告

- **SKILL.md 名称校验规则**（`.specpow/skills/planning-write-specs/SKILL.md`）
  - 新增"名称校验（铁律）"段落，指导 AI 精确匹配需求名称

- **RENAMED 模板格式修正**（`.specpow/schemas/spec-driven/templates/spec.md`）
  - 从表格格式改为箭头格式: `### <旧名称> → <新名称>`

## [0.5.0] - 2026-08-20

### 🔄 归档引擎名称匹配路由（Breaking Fix）

- **findSpecMutations 从路径匹配改为名称匹配**
  - File: `src/core/archive/engine.ts`
  - 问题: propose 生成的 delta 文件路径 (`specs/<capability>/spec.md`) 永远无法匹配主规范路径
  - 修复: 新增 `buildSpecNameIndex()` 扫描主规范提取需求名称索引
  - 修复: 新增 `routeDeltaOperations()` 按需求名称路由操作到目标文件
  - 修复: 新增 `buildSubDeltaContent()` 为每个目标文件构建子 delta
  - 修复: RENAMED 处理后自动将新名称加入索引，支持后续 MODIFIED/REMOVED 按新名称查找

- **精确退休判断**
  - File: `src/core/archive/engine.ts`
  - 问题: 旧逻辑 "delta 文件只含 REMOVED → 整个文件 retire" 会错误退休未被移除的需求
  - 修复: 增加 `fileReqCount` 索引，只有当 REMOVED 覆盖目标文件全部需求时才 retire
  - 部分退休: 仅标记被移除的需求为 `[RETIRED]`，其他需求保留

## [0.4.9] - 2026-08-20

### 🐛 归档引擎 Delta 检测正则修复

- **BUG-5 findSpecMutations 检测正则强制冒号**
  - File: `src/core/archive/engine.ts`
  - Fix: `/##\s+REMOVED:/i` → `/##\s+REMOVED[:\s]/i`（冒号可选），与 delta-parser 一致
  - Fix: 新增 `hasRenamed` 检测，支持纯 RENAMED 操作触发合并

## [0.4.8] - 2026-08-20

### 🐛 Delta Spec 系统修复 — 4 个 Bug + 1 个架构修复

- **GAP-6 propose 阶段 AI 无法看到已有主规范**
  - Files: `src/commands/propose.ts`, `src/core/templates/index.ts`
  - Fix: propose 扫描 `.specpow/openspec/specs/` 注入到 specs 工件上下文

- **BUG-1 Scenario 截断 Requirement 块**
  - Files: `src/core/archive/delta-parser.ts`, `src/core/archive/delta-merger.ts`
  - Fix: 添加 `(?!Scenario:\s*)` 负向前瞻，防止 `### Scenario:` 终止 `## Requirement:` 块提取

- **BUG-2 --force 无法覆盖已存在的 ADDED 块**
  - File: `src/core/archive/delta-merger.ts`
  - Fix: 修正 ADDED 阶段逻辑：identical→跳过 / force→替换 / 否则→冲突

- **BUG-2b 幂等性比较失效（body vs fullBlock）**
  - File: `src/core/archive/delta-merger.ts`
  - Fix: 新增 `extractBlockBody()` 辅助函数，MODIFIED 和 ADDED 阶段用 body 比较

- **BUG-3 [RETIRED] 重复叠加 + 无法查找已退休块**
  - Files: `src/core/archive/delta-parser.ts`, `src/core/archive/delta-merger.ts`
  - Fix: 所有 header 匹配正则支持 `[RETIRED]` 前缀（兼容新旧格式），REMOVED 阶段添加幂等检查

- **ISSUE-4 formatBlock 固定 ## 级别**
  - File: `src/core/archive/delta-merger.ts`
  - Fix: formatBlock 接受 headerLevel 参数，MODIFIED 从现有块检测级别，ADDED 默认 ##

## [0.3.1] - 2026-08-18

### 🐛 Comprehensive Bug Fix Release — 21 Issues Resolved

This patch release addresses 21 verified issues discovered during a comprehensive review of functional runnability and usability. Every fix was verified against actual code before implementation. Build passes, all 849 tests pass.

### 🔴 IMPORTANT Fixes (4 items)

- **#1 `init --force` 选项缺失**
  - File: `src/cli/index.ts`
  - Fix: 添加 `--force` Commander.js 选项定义，配合 `TemplateHashManager.reset()` 实现强制覆盖

- **#2 `review --diff-file` 未实际解析 diff 文件**
  - File: `src/commands/review.ts`
  - Fix: 添加 diff 文件读取与正则解析（`+++ b/` 前缀匹配），提取变更文件路径列表

- **#3 `review --model` 选项无效但无警告**
  - File: `src/commands/review.ts`
  - Fix: 当传入 `--model` 时输出黄色警告：审查为静态分析，不涉及 AI 模型调用

- **#4 Hook 失败被静默吞掉**
  - File: `src/core/hooks/hook-registry.ts`
  - Fix: `mergeResults` 中捕获失败 hook 的 error 信息作为 warning 输出

### 🟡 MODERATE Fixes (8 items)

- **#5 `formatForPlatform` 忽略 platform 参数**
  - File: `src/core/hooks/hook-registry.ts`
  - Fix: 根据 platform 参数返回对应格式（claude/cursor/generic），而非始终返回 claude 格式
  - Breaking: `PlatformOutput` 接口字段改为 optional，支持平台特定返回

- **#6 `migrate` 失败时静默退出码 0**
  - File: `src/cli/index.ts`
  - Fix: 迁移失败时输出失败步骤详情并调用 `process.exit(1)`

- **#7 `debug` 提示不存在的 `--report` 选项**
  - File: `src/commands/debug.ts`
  - Fix: 移除 `console.log` 中关于 `debug --report` 的误导性提示

- **#8 `channel send` 无消息类型验证**
  - File: `src/commands/channel.ts`
  - Fix: 添加 MessageType 白名单校验，无效类型输出有效值列表并退出

- **#9 `status` 任务正则仅匹配小写 `[x]`**
  - File: `src/commands/status.ts`
  - Fix: 正则添加 `gi` 标志，支持 `[X]` 大写完成标记

- **#10 `verify` 无变更时直接报错退出**
  - File: `src/commands/verify.ts`
  - Fix: 自动检测唯一活跃变更（单变更免 `--change`），多变更时列出选项

- **#11/#12 `init` 内置 Schema/Skill 目录不存在时静默返回**
  - File: `src/commands/init.ts`
  - Fix: 添加 `console.warn` 警告输出，提示包安装可能不完整

### 🟢 MINOR Fixes (9 items)

- **#13/#14 `channel` 提示错误子命令名**
  - File: `src/commands/channel.ts`
  - Fix: `workers add` → `add-worker`，`tasks create` → `create-task`

- **#15 session-start 技能列表仅 22/34**
  - File: `src/core/hooks/session-start-hook.ts`
  - Fix: 补全全部 34 个技能，新增 Meta 分类（using-specpow、meta-using-skills 等）

- **#16 `apply` host-driven 写文件失败返回码 0**
  - File: `src/commands/apply.ts`
  - Fix: `return` → `process.exit(1)`，确保 task-manifest.json 写入失败时进程异常退出

- **#17 `parseProposal` 缺少 risks 解析**
  - File: `src/core/parsers/index.ts`
  - Fix: 添加 Markdown 表格解析逻辑，支持 `| 风险 | 影响 | 概率 | 应对 |` 格式

- **#18 `runTests()` 同步阻塞事件循环**
  - File: `src/core/sdd-engine/controller.ts`
  - Fix: `execFileSync` → 异步 `execFile` + Promise，避免最多 14 分钟的事件循环阻塞

- **#19 `detectActiveChanges` 重复调用**
  - File: `src/core/hooks/session-start-hook.ts`
  - Fix: `detectWorkflowStage` 接收已计算的 `activeChanges` 参数，避免重复文件系统扫描

- **#20 PostToolCall 每次工具调用注入无用上下文**
  - File: `src/core/hooks/post-tool-call-hook.ts`
  - Fix: 仅在有阶段转换信号时注入 `additionalContext`，普通工具调用不再消耗 token

- **#21 `initialize()` 同步函数误用 `await`**
  - File: `src/commands/init.ts`
  - Fix: 移除误导性 `await`，`engine.initialize()` 为同步方法

### 🧪 Testing

- 849 tests pass across 37 test files
- 3 tests updated to match new PostToolCallHook behavior (no context injection without transition signal)
- Added `readFileSync` import to `test/hook-system.test.ts`

### 📝 Documentation

- CHANGELOG.md: 新增 v0.3.1 版本记录
- README.md: 版本历史新增 v0.3.1 修复摘要
- docs/guide.md: CLI 命令参考更新（init --force、review、verify、channel、migrate）

---

## [0.3.0] - 2026-08-15

### 🚀 Superpowers Pattern Transformation — Host-Driven Mode

This release introduces **dual-mode execution**: the existing TypeScript SDD Engine (Mode A) now coexists with a new **Host-Driven mode** (Mode B), where the host AI agent orchestrates the SDD workflow using its native subagent tools.

### ✨ New Features

- **Host-Driven Mode (`--host-driven`)**: New execution mode for `specpow apply` that generates a `task-manifest.json` and delegates orchestration to the host AI agent via SKILL.md instructions. No TypeScript AI-caller subprocess needed.
- **Bootstrap Meta-Skill (`using-specpow`)**: New skill injected via `SessionStart` hook that teaches the host agent the full SDD workflow, trigger discipline, and iron rules.
- **SDD Orchestrator Skill (`execution-sdd-orchestrator`)**: Skill file encoding the implement→review→fix loop logic, replacing `controller.ts` orchestration in Host-Driven mode. Includes parallel execution guidance.
- **Subagent Dispatch Skill (`execution-subagent-dispatch`)**: Skill file encoding implementer/reviewer/re-reviewer prompt templates, replacing `ai-caller.ts` prompt construction in Host-Driven mode.
- **`init` Copies Builtin Skills**: `specpow init` now uses `copyBuiltinSkillsWithHash` to incrementally copy all 34 builtin skill files to target projects, with template-hash protection for user modifications.

### 🏗️ Architecture Changes

- **Dual-Mode Execution Layer**: Architecture diagram updated to show Mode A (SDD Engine) and Mode B (Host-Driven) side-by-side. Both modes share Ledger, Git ops, and review-loop infrastructure.
- **Skills Count**: 31 → 34 (added `using-specpow`, `execution-sdd-orchestrator`, `execution-subagent-dispatch`)

### 📦 Deprecation Markers

- `src/core/sdd-engine/controller.ts` — marked `@deprecated`, only used by SDD Engine mode
- `src/core/sdd-engine/ai-caller.ts` — marked `@deprecated`, only used by SDD Engine mode
- `src/core/sdd-engine/model-selector.ts` — marked `@deprecated`, model selection guidance now in SKILL.md

### 🔧 Bug Fixes

- **CLI `--host-driven` flag registration**: Flag was implemented in `apply.ts` but not registered in Commander.js — fixed.
- **`copyBuiltinSkillsWithHash` missing definition**: Function was called but never defined in `init.ts` — implemented with same pattern as `copyBuiltinSchemasWithHash`.

### 📝 Documentation

- README.md architecture diagram updated for dual-mode execution layer
- README.md skills table updated from 31 to 34
- README.md quick-start section documents `--host-driven` flag

## [0.2.2] - 2026-08-15

### 🐛 Bug Fix: AI Tool Detection

- **修复 `specpow init` 检测到 0 个 AI 工具的问题**
  - File: `src/core/init/engine.ts`
  - Root cause: `SUPPORTED_TOOLS` 中 Claude Code 的检测路径为 `.claude-plugin/plugin.json`，该文件在实际 Claude Code 项目中不存在
  - Fix: 更新所有工具的 `detectionPaths` 为真实存在的标记文件：
    - Claude Code: `.claude/settings.json`, `.claude/commands`, `.claude/CLAUDE.md`, `CLAUDE.md`
    - Cursor: `.cursor/rules`, `.cursor/mcp.json`
    - GitHub Copilot: `.github/copilot-instructions.md`
    - Gemini CLI: `.gemini/settings.json`, `gemini-extension.json`
    - Codex App: `.codex/instructions.md`
    - OpenCode: `opencode.json`
    - Kimi Code: `.kimi/instructions.md`
    - Pi: `.pi/extensions`
  - Impact: `specpow init` 现在能正确检测到已安装的 AI 工具

---

## [0.2.1] - 2026-08-15

### 🐛 Bug Fixes & Code Cleanup (9 items from comprehensive review)

This patch release addresses issues discovered during a comprehensive code review of the v0.2.0 codebase. All fixes have been verified with the existing test suite (854 tests, 37 files).

#### P0: Critical Fixes (1 item)

- **#19 Controller 未传递 commit SHA 给 ai-caller**
  - File: `src/core/sdd-engine/controller.ts`
  - Fix: `callImplementer()` now passes `headCommit` and `baseCommit` to `aiCaller.call()`, ensuring implementer agents receive correct git context
  - Impact: Without commit SHAs, implementer agents could not accurately diff changes during review loops

#### P1: High-Value Fixes (2 items)

- **#20 Ledger fix-round 数据丢失**
  - File: `src/core/sdd-engine/ledger.ts`
  - Fix: `recordFixRound()` now appends fix-round entries instead of overwriting previous rounds
  - Impact: Multi-round fix history was lost, making it impossible to track iterative improvements

- **#21 design.md 未传递给 SDD 引擎**
  - File: `src/commands/apply.ts`
  - Fix: `design.md` content is now included in `specConstraints` alongside specs content
  - Impact: Implementer agents were missing design context, leading to implementations that deviated from design

#### P2: Medium-Priority Fixes (4 items)

- **#22 模型配置死代码清理**
  - Files: `src/core/sdd-engine/controller.ts`, `src/core/sdd-engine/types.ts`
  - Fix: Removed unused `modelTier` field and dead code paths that referenced hardcoded model values
  - Impact: Config `sdd.modelTier` was documented but never actually read; cleanup removes confusion

- **#23 串行 apply --json 输出实现**
  - File: `src/commands/apply.ts`
  - Fix: Serial (non-parallel) mode now supports `--json` flag, outputting `ApplyData` in Agent Contract format
  - Impact: `specpow apply --json` previously only worked in `--parallel` mode; now consistent across both modes

- **#24 projectContext 传递原始路径而非项目名**
  - Files: `src/commands/apply.ts`, `src/commands/execute.ts`
  - Fix: Changed from passing `projectRoot` (absolute path) to `basename(projectRoot)` (project name) as `projectContext`
  - Impact: SDD engine was receiving `/home/user/my-project` instead of `my-project`, causing context pollution in prompts

- **#25 ParallelDispatcher 忽略模型配置**
  - File: `src/core/sdd-engine/parallel-dispatcher.ts`
  - Fix: Added `ModelSelector` initialization from `config.modelConfig` and passed selected model to `dispatchImplementer`
  - Impact: Parallel mode always used default model regardless of `config.json` settings

#### P3: Low-Priority Cleanup (2 items)

- **#26 execute.ts 冗余 initialize() 调用清理**
  - File: `src/commands/execute.ts`
  - Fix: Removed redundant `await controller.initialize()` calls (constructor already handles initialization)
  - Impact: Minor performance improvement and code clarity

- **#27 store 选项死代码清理**
  - Files: `src/commands/apply.ts`, `src/commands/propose.ts`, `src/commands/status.ts`, `src/cli/index.ts`
  - Fix: Removed `--store <store-id>` option from propose/status/apply commands (option was defined but never used)
  - Impact: CLI surface reduced; removed confusing option that had no effect

### 🧪 Testing

- All 854 tests pass across 37 test files
- No new test failures introduced
- Infrastructure layer verified: hook-system (77), memory-manager (69), memory-adapters (17), channel-runtime (77), migration (19) — 259 tests

### 📚 Documentation

- **CHANGELOG.md**: Added v0.2.1 section documenting all 9 fixes
- **docs/guide.md**: Updated CLI command reference to reflect removed `--store` option

---

## [0.2.0] - 2026-08-14

### 🎉 Major Release: 26 Optimization Items from OpenSpec/Superpowers/Trellis

This release represents a comprehensive optimization of SpecPow, incorporating best practices from OpenSpec (spec-driven planning), Superpowers (SDD execution engine), and Trellis (workflow automation).

**Key Highlights:**
- **860 tests** (up from 422, +104% coverage)
- **22 AI tool adapters** (up from 6, +267% support)
- **31 skills** (added meta-create-skill)
- **11 second-round optimizations** (performance, defense, extensibility)

### ✨ Added

#### P0: Core Fixes (4 items)

- **Model Configuration** (#1): Model selection now reads from `config.json` instead of hardcoded values
  - Modified: `src/commands/apply.ts`, `src/core/sdd-engine/controller.ts`
  - Config field: `sdd.modelTier`

- **Parallel Dispatcher Integration** (#2): Exposed `ParallelDispatcher` to CLI with `--parallel` flag
  - Modified: `src/commands/apply.ts`
  - Usage: `specpow apply --parallel`

- **Test Framework Auto-Detection** (#3): Extended `runTests()` to support any test framework
  - Modified: `src/core/sdd-engine/controller.ts`
  - Auto-detects test script from `package.json`

- **Three-Layer Schema Resolution** (#4): Added user-level schema layer
  - Modified: `src/core/artifact-graph/resolver.ts`
  - Resolution order: project → user (`~/.specpow/schemas/`) → package

#### P1: High-Value Features (6 items)

- **Delta Spec Structured Merge** (#5): OpenSpec-style merge algorithm
  - New: `src/core/archive/delta-parser.ts`, `src/core/archive/delta-merger.ts`
  - Modified: `src/core/archive/engine.ts`
  - Supports: ADDED/MODIFIED/REMOVED/RENAMED operations
  - Features: Conflict detection, idempotency, merge order enforcement

- **Agent Contract** (#6): JSON output support for all CLI commands
  - Modified: All `src/commands/*.ts` files
  - Usage: `specpow status --json`, `specpow schemas --json`
  - Format: `{ status, data, diagnostics, nextSteps }`

- **Context & Rules Injection** (#7): Project-level context and rules configuration
  - Modified: `src/core/config/config-schema.ts`, `src/core/artifact-graph/instruction-loader.ts`
  - New fields in `.specpow/config.yaml`: `context`, `rules`
  - Template placeholders: `{{context}}`, `{{rules}}`

- **Interactive Explore Mode** (#8): Socratic requirement exploration
  - Modified: `src/commands/explore.ts`, `skills/planning-explore/SKILL.md`
  - Features: Curiosity-driven, visual (ASCII diagrams), adaptive, non-committal

- **Extended AI Tool Adapters** (#9): **22 AI tool adapters** (was 6)
  - Modified: `src/core/command-generation/`
  - New adapters: Amazon Q, Cline, Continue, Kiro, Trae, Qwen, Kimi, GitHub Copilot Workspace, Roo Code, Auggie, Bob, Crush, Devin, Junie, Qoder
  - Features: Unified `AdapterRegistry`, invocation styles (namespaced/flat/prefix)

- **Template Hash Incremental Update** (#10): Protect user modifications during `specpow init`
  - New: `src/core/init/template-hash.ts`
  - Modified: `src/commands/init.ts`
  - Storage: `.specpow/.template-hashes.json`
  - Logic: Skip unchanged, create `.new` for user-modified, overwrite for framework-updated

#### P2: Innovative Features (5 items)

- **Hook Auto-Context Injection** (#11): 4-hook pipeline for automatic context injection
  - New: `src/core/hooks/` module
  - Hooks: `SessionStart`, `UserPromptSubmit`, `PreToolCall`, `PostToolCall`
  - Configuration: `.specpow/hooks/hooks.json`

- **Cross-Session Memory System** (#12): Event-sourced memory with keyword extraction
  - New: `src/core/memory/` module
  - Features: Keyword extraction, phase detection, relevance scoring, inverted index
  - **Adapters**: SQLite (WAL mode, prepared statements), Sharded JSON (incremental updates, atomic writes)
  - API: `createMemoryManager()`, `indexSession()`, `search()`, `getRecent()`

- **Channel Multi-Agent Collaboration** (#13): Event-sourced multi-agent runtime
  - New: `src/core/channel/` module
  - Features: Supervisor pattern, worker lifecycle management, task assignment strategies
  - Strategies: round_robin, least_busy, priority
  - API: `createChannelRuntime()`, `Supervisor`, `registerWorker()`, `assignTask()`

- **Workflow State Tags** (#14): Trellis-style `[workflow-state:xxx]` tags
  - New: `src/core/workflow-state.ts`
  - Features: Tag generation, parsing, stage inference, transition hooks
  - API: `stageToTag()`, `parseWorkflowStateTag()`, `inferStageFromPath()`, `onStageTransition()`

- **Core SDK Subpath Exports** (#15): Modular imports via package.json exports
  - Modified: `package.json` (added `exports` field)
  - New: `src/core/archive/index.ts`, `src/core/config/index.ts`
  - 10 subpath exports: `/sdd`, `/artifact-graph`, `/archive`, `/hooks`, `/memory`, `/channel`, `/workflow-state`, `/config`, `/command-generation`

#### Second-Round Optimizations (11 items)

- **Four-Module Test Coverage** (#16): Comprehensive tests for Memory, Channel, Hook, WorkflowState
  - New: `test/memory-manager.test.ts`, `test/channel-runtime.test.ts`, `test/hook-system.test.ts`, `test/workflow-state.test.ts`
  - Tests: ~300 new test cases

- **Delta Spec Four Enhancements** (#17): Advanced OpenSpec features
  - Modified: `src/core/archive/engine.ts`, `src/core/archive/delta-merger.ts`
  - Features: Scenario-loss guard, capability retirement, unaccounted content detection, code fence masking
  - Tests: ~150 new test cases

- **Rationalization Defense System** (#18): Extended defense tables + red flags + pressure testing
  - Modified: `skills/execution-tdd/SKILL.md`, `skills/execution-systematic-debugging/SKILL.md`, `skills/execution-verification-before-completion/SKILL.md`
  - Added: 11+ row defense tables, 13 red flags, pressure testing checklists
  - Fixed: Duplicate YAML frontmatter bugs

- **AI Adapter Extension to 22** (#19): 8 new adapters
  - Modified: `src/core/command-generation/index.ts`
  - New: GitHub Copilot Workspace, Roo Code, Auggie, Bob, Crush, Devin, Junie, Qoder
  - Tests: ~50 new test cases

- **Hook System Completion** (#20): PreToolCall + PostToolCall implementation
  - New: `src/core/hooks/pre-tool-call-hook.ts`, `src/core/hooks/post-tool-call-hook.ts`
  - Modified: `src/core/hooks/hook-registry.ts`, `src/core/hooks/index.ts`
  - Features: Tool call interception, workflow context injection, result logging

- **Hook + WorkflowState Deep Integration** (#21): Stage transition hooks + state recovery
  - Modified: `src/core/hooks/workflow-state-hook.ts`, `src/core/workflow-state.ts`
  - Features: Auto-inject stage tags, detect stage transitions, recover last workflow state on session start
  - Tests: ~80 new test cases

- **Meta-Create-Skill** (#22): Skill for creating new skills
  - New: `skills/meta-create-skill/SKILL.md`
  - Features: Guided skill creation, auto-generate SKILL.md skeleton, auto-register to skill directory
  - Tests: 12 test cases

- **Version Migration System** (#23): Safe version upgrades with automatic backup
  - New: `src/core/migration/`, `src/commands/migrate.ts`
  - Features: Migration manifests, dry-run preview, automatic backup
  - Tests: ~60 test cases

- **Memory Platform Adapter Extension** (#24): SQLite + Sharded JSON adapters
  - New: `src/core/memory/adapters/sqlite-adapter.ts`, `src/core/memory/adapters/json-adapter.ts`
  - SQLite: WAL mode, prepared statements, transaction support
  - JSON: Multi-file sharding, incremental updates, atomic writes
  - Tests: 17 test cases

- **Memory Adapter Performance Optimization** (#25): Prepared statement caching + incremental updates
  - Modified: `src/core/memory/adapters/sqlite-adapter.ts`, `src/core/memory/adapters/json-adapter.ts`
  - SQLite: 11 cached prepared statements, explicit timeline sorting
  - JSON: Incremental shard updates (compare old vs new), atomic writes (temp + rename)
  - Performance: ~30% faster save/load operations

- **Pre-existing Defect Fixes** (#26): Fixed 714 → 860 test cases
  - Fixed: 4 pre-existing test failures
  - Added: 146 new test cases across all modules

### 🔧 Fixed

- **Memory Module Bug**: Fixed `calculateRelevance()` crash when `keywords` parameter is undefined
  - File: `src/core/memory/memory-indexer.ts`
  - Fix: Added null-safe handling with `?? []`

- **Command Generation Bug**: Added missing `AdapterRegistry.getAll()` method
  - File: `src/core/command-generation/index.ts`
  - Fix: Implemented static method to return all adapter instances

- **TypeScript Compilation Errors**: Fixed 6 type errors in channel module
  - Files: `channel-types.ts`, `channel-supervisor.ts`, `channel-event-log.ts`
  - Fixes: Added missing event types, removed unused imports, fixed async return types

- **Pre-existing Test Failures**: Fixed 4 failing tests
  - Fixed: Memory adapter edge cases
  - Fixed: Hook registration race conditions
  - Fixed: WorkflowState tag parsing
  - Result: 714 → 860 passing tests

### 📚 Documentation

- **README.md**: Comprehensive update with all v0.2.0 features
  - Added: SDK subpath exports guide
  - Added: Context & Rules injection examples
  - Added: Hook system documentation (4-hook pipeline)
  - Added: Memory system API guide (SQLite + JSON adapters)
  - Added: Channel multi-agent examples
  - Added: Workflow state tag usage (with transition hooks)
  - Added: Delta spec merge format (with 4 enhancements)
  - Added: Template hash update logic
  - Added: Migration system documentation
  - Added: Meta-create-skill documentation
  - Updated: Architecture diagram with new "Intelligence Layer"
  - Updated: AI tool support table (6 → 22 tools)
  - Updated: Project structure with new modules
  - Updated: Test count (422 → 860)

- **CHANGELOG.md**: Comprehensive v0.2.0 changelog
  - Documented all 26 optimization items
  - Added migration guide
  - Added statistics and performance improvements

### 🧪 Testing

- **Integration Testing**: All 10 subpath exports verified
  - Main entry: 12 exports ✅
  - SDD engine: 17 exports ✅
  - Artifact Graph: 5 exports ✅
  - Archive: Delta parsing ✅
  - Hooks: 8 exports ✅
  - Memory: Keyword extraction, phase detection, relevance scoring ✅
  - Channel: Multi-agent runtime ✅
  - Workflow State: Tag generation/parsing ✅
  - Config: 14 exports ✅
  - Command Generation: 14 adapters ✅

### 📦 Package

- Version bump: 0.1.0 → 0.2.0
- Added `exports` field to `package.json` for subpath imports
- All modules compiled successfully with TypeScript strict mode

### 🎯 Migration Guide

#### From v0.1.0 to v0.2.0

1. **Update dependencies**:
   ```bash
   pnpm install
   pnpm build
   ```

2. **Re-initialize project** (optional, to get new templates):
   ```bash
   specpow init
   ```
   Note: User modifications will be preserved (template hash feature)

3. **Use new SDK imports** (optional):
   ```typescript
   // Old way (still works)
   import { SDDController } from '@specpow/framework';
   
   // New way (recommended for tree-shaking)
   import { SDDController } from '@specpow/framework/sdd';
   ```

4. **Configure context/rules** (optional):
   ```yaml
   # .specpow/config.yaml
   context: |
     Project description...
   rules:
     proposal:
       - Rule 1
       - Rule 2
   ```

5. **Set up hooks** (optional):
   ```json
   // .specpow/hooks/hooks.json
   {
     "hooks": {
       "SessionStart": [{ "matcher": "", "command": "node hooks/session-start.js" }]
     }
   }
   ```

### 📊 Statistics

- **Files Modified**: 35+
- **New Files**: 25+
- **New Features**: 26 (15 first-round + 11 second-round)
- **Bug Fixes**: 7 (3 first-round + 4 pre-existing)
- **Test Coverage**: 860 tests across 37 files (+104%)
- **AI Tool Support**: 6 → 22 adapters (+267%)
- **Skills**: 30 → 31 skills (added meta-create-skill)
- **Breaking Changes**: None (fully backward compatible)

### 🙏 Acknowledgments

This release incorporates best practices from:
- **OpenSpec**: Spec-driven planning, Delta Spec format, Agent Contract
- **Superpowers**: SDD execution engine, TDD enforcement, review cycles
- **Trellis**: Hook system, cross-session memory, channel collaboration, workflow state tags

---

## [0.1.0] - Initial Release

### ✨ Added

- OpenSpec artifact graph engine
- Superpowers SDD execution engine
- 30 skills (planning, execution, quality, business)
- 8 agents (PRD, DB design, codegen, testing, review, deployment)
- 6 AI tool adapters (Claude, Cursor, Copilot, CodeBuddy, Codex, Gemini)
- 3 workflow schemas (spec-driven, crud-module, bug-fix)
- 19 CLI commands
- TDD enforcement (RED-GREEN-REFACTOR)
- 5-round review cycle with circuit breaker
- Progress ledger with resume support
- Template engine with AI instruction generation
- Configuration management with Zod validation
- Git worktree support for parallel execution

[0.3.1]: https://github.com/specpow/framework/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/specpow/framework/compare/v0.2.2...v0.3.0
[0.2.2]: https://github.com/specpow/framework/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/specpow/framework/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/specpow/framework/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/specpow/framework/releases/tag/v0.1.0
