feat(pi-hermes-memory): 导入上游 v0.9.10 源码快照

从官方 Git 仓库导入 chandra447/pi-hermes-memory 在 tag v0.9.10
(df624056a2e8c68bc89ba0a81e1c120856ec9665,2026-10-02)的源码快照。
本次仅导入源码,尚未接入组合包:package.json、加载顺序、依赖与权限策略
均未改动。

- 原样导入 src/、tests/、docs/、scripts/、README、CHANGELOG、PLAN、
  AGENTS 与 LICENSE;该快照共 156 个上游文件。
- 剔除嵌套 .git、上游 .github 工作流、.ralph/、.claude/、node_modules、
  覆盖率与构建产物。
- 新增中文 UPSTREAM.md,记录来源,以及启用前必须完成的待决事项:
  在 pi-compaction 之前注册加载顺序、better-sqlite3 版本与根 allowScripts
  对齐、strip-ansi 解析确认。
- 说明选择 tag 而非 main 的原因:导入时上游 main 已领先至
  24fcd8ad26fc27badb8d7dbaf8034645de07b893(2026-10-11),选 tag 是为
  对应一个已发布、可复现的版本。

尚未接线。启用前还需反转 tests/extension-load.test.ts 中"不得加载
Hermes"的断言,并同步 pi-tool-search 分组、权限策略与文档。

验证:快照 156 个上游文件全部导入,目录内仅多出 UPSTREAM.md 一份;
已确认与上游 main 内容存在差异,证明取的是 tag 而非 main。
This commit is contained in:
云服务部-叶林立
2026-10-13 23:19:35 -07:00
parent 879fc5d37f
commit 312bb2ba5a
157 changed files with 52287 additions and 0 deletions
+290
View File
@@ -0,0 +1,290 @@
# v0.2.0 Implementation Plan — Skills + Smart Curation
> **Goal**: Close the two biggest Hermes gaps — procedural memory (skills) and intelligent memory management (auto-consolidation, correction detection, tool-call-aware nudges).
## Implementation Order
```
Epic 2 (Auto-Consolidation) → standalone, modifies MemoryStore.add()
Epic 3 (Correction Detection) → standalone, new handler
Epic 4 (Tool-Call Nudge) → modifies background-review.ts
Epic 1 (Skill Tool) → largest: new store + tool + handlers
Epic 5 (Docs + Release) → depends on all above
```
Epics 2, 3, 4 are independent but done sequentially to avoid merge conflicts in shared files (`types.ts`, `config.ts`, `constants.ts`, `index.ts`).
---
## Epic 2: Auto-Consolidation
**Problem**: When `add()` exceeds char limit, we return an error. Hermes auto-consolidates.
### New Files
**`src/handlers/auto-consolidate.ts`** (~120 lines)
```typescript
export async function triggerConsolidation(
pi: ExtensionAPI,
store: MemoryStore,
target: "memory" | "user",
signal?: AbortSignal,
): Promise<ConsolidationResult>
```
- Builds prompt from `CONSOLIDATION_PROMPT` + current entries for the target
- Calls `pi.exec("pi", ["-p", "--no-session", prompt], { signal, timeout: 60000 })`
- Returns `{ consolidated: true }` on success, `{ consolidated: false, error }` on failure
**`src/handlers/consolidate-command.ts`** (~30 lines)
- Registers `/memory-consolidate` via `pi.registerCommand()`
- Runs consolidation for both targets, reports via `ctx.ui.notify()`
**`tests/handlers/auto-consolidate.test.ts`** (~120 lines)
### Modified Files
**`src/constants.ts`** — Add `CONSOLIDATION_PROMPT`
**`src/types.ts`** — Add `autoConsolidate: boolean` to `MemoryConfig`; add `ConsolidationResult` interface
**`src/config.ts`** — Add `autoConsolidate: true` default + parsing
**`src/store/memory-store.ts`** — Key changes:
- `add()` becomes **async** (returns `Promise<MemoryResult>`)
- Add `setConsolidator()` method for dependency injection (avoids circular import)
- When over limit + consolidator set: call consolidator, **reload from disk** (`await this.loadFromDisk()`), then retry once
- **Critical**: The `pi.exec()` child process modifies files on disk. The parent's in-memory arrays become stale after consolidation. We MUST reload before retrying `add()` or the retry will overwrite consolidated entries with stale data.
**`src/tools/memory-tool.ts`** — `await store.add(target, content)` (line ~58)
**`src/index.ts`** — Wire consolidator + register command
**Test migration**: Making `add()` async means all existing tests calling `store.add()` must use `await`. Without `await`, tests get a Promise object instead of `MemoryResult`, causing assertion failures. Update all `store.add()` calls in `tests/store/memory-store.test.ts` to `await store.add()`.
### Key Decision: Consolidator Injection via Setter
MemoryStore cannot import from handlers (circular). Instead, `index.ts` injects a consolidator function via `store.setConsolidator()` after both `store` and `pi` are available.
### Key Decision: No memoryDirPath Getter
SkillStore receives its directory path directly from config (`config.memoryDir + "/skills/"`) in `index.ts`. No need to expose MemoryStore internals.
---
## Epic 3: Correction Detection + Immediate Save
**Problem**: User says "no, don't do that" — we only save it 8 turns later at the next nudge. Hermes detects immediately.
### New Files
**`src/handlers/correction-detector.ts`** (~100 lines)
```typescript
export function setupCorrectionDetector(
pi: ExtensionAPI,
store: MemoryStore,
config: MemoryConfig,
): void
```
**Design**:
1. On `message_end` (role=user): check text against `CORRECTION_PATTERNS`, set `pendingCorrection = true`
2. On `turn_end`: if `pendingCorrection`, trigger `pi.exec()` with `CORRECTION_SAVE_PROMPT` + recent messages + current memory
3. Rate limit: `turnsSinceLastCorrection >= 3` and `!correctionInProgress`
**Why turn_end, not message_end**: We need the full context (user correction + what agent said wrong) for the save prompt.
**`tests/handlers/correction-detector.test.ts`** (~150 lines)
### Modified Files
**`src/constants.ts`** — Add `CORRECTION_SAVE_PROMPT` and `CORRECTION_PATTERNS` (regex array)
**`src/types.ts`** — Add `correctionDetection: boolean` to `MemoryConfig`
**`src/config.ts`** — Add `correctionDetection: true` default + parsing
**`src/index.ts`** — Wire `setupCorrectionDetector()`
### Correction Patterns (Two-Pass Filter)
Patterns are split into **strong** (high confidence, trigger immediately) and **weak** (need a directive clause to confirm).
**Strong patterns** (always trigger):
```typescript
/don'?t do that/i, /not like that/i,
/^I said\b/i, /^I told you\b/i, /we already discussed/i,
/^please don'?t/i, /^that'?s not what I/i
```
**Weak patterns** (only trigger if followed by a directive — verb or "the/that/this"):
```typescript
/^no[,.\s!]/i, /^wrong[,.\s!]/i, /^actually[,.\s]/i, /^stop[,.\s!]/i
```
**Negative patterns** (suppress trigger even if a positive pattern matches):
```typescript
/^no worries/i, /^no problem/i, /^no thanks/i, /^no need/i,
/^actually.{0,10}(looks? great|perfect|good|correct|right)/i,
/^stop.{0,5}(there|here|for now)/i
```
This eliminates false positives like "no worries, I'll handle it" and "actually, that looks great" while still catching "no, don't use npm" and "actually, use yarn instead".
---
## Epic 4: Tool-Call-Aware Nudge
**Problem**: Nudge is purely turn-count based. Complex tasks with many tool calls generate more valuable memories.
### Modified Files
**`src/types.ts`** — Add `nudgeToolCalls: number` to `MemoryConfig`
**`src/config.ts`** — Add `nudgeToolCalls: 15` default + parsing
**`src/handlers/background-review.ts`** — Key changes:
- Count tool-use entries from `ctx.sessionManager.getBranch()` at `turn_end` time (robust — no unknown event names)
- Change trigger to OR logic: `turnsSinceReview >= nudgeInterval || toolCallsSinceReview >= nudgeToolCalls`
- Reset both counters on review
**`tests/handlers/background-review.test.ts`** — Add tool-call trigger tests
### Key Decision: Count from Branch, Not Events
Rather than depending on unknown Pi event names like `tool_end`, count tool-use entries from `ctx.sessionManager.getBranch()` at `turn_end` time. More robust and testable.
---
## Epic 1: Skill Tool + Procedural Memory
**Problem**: `COMBINED_REVIEW_PROMPT` asks about skills but there's no skill tool. This is the single highest-leverage change.
### New Files
**`src/store/skill-store.ts`** (~250 lines)
```typescript
export class SkillStore {
constructor(private skillsDir: string) {}
async loadIndex(): Promise<SkillIndex[]>
async loadSkill(fileName: string): Promise<SkillDocument | null>
async create(name: string, description: string, body: string): Promise<SkillResult>
async patch(fileName: string, section: string, newContent: string): Promise<SkillResult>
async edit(fileName: string, description: string, body: string): Promise<SkillResult>
async delete(fileName: string): Promise<SkillResult>
formatIndexForSystemPrompt(): string
}
```
**Storage**: `~/.pi/agent/memory/skills/` (isolated from user skills at `~/.pi/agent/skills/`)
**SKILL.md format**:
```markdown
---
name: debug-typescript-errors
description: Step-by-step approach to debugging TS errors in monorepos
version: 1
created: 2026-04-27
updated: 2026-04-27
---
## When to Use
## Procedure
## Pitfalls
## Verification
```
**Frontmatter parsing**: Simple regex (no yaml dependency). Split on `---`, parse key-value pairs.
**File naming**: `slugify(name) + ".md"` — lowercase, replace non-alphanum with `-`, collapse dashes.
**`src/tools/skill-tool.ts`** (~180 lines)
- Registered via `pi.registerTool()` with actions: `create`, `view`, `patch`, `edit`, `delete`
- Content scanning on all writes via `scanContent()`
**`src/handlers/skill-auto-trigger.ts`** (~80 lines)
- Track tool calls per turn
- When turn completes with **8+ tool calls** (not 5 — a typical read→bash→edit→bash→read is already 5), trigger skill extraction via `pi.exec()`
- Additionally require at least **2 distinct tool types** in the turn (e.g., read + bash, not just 8 reads) to filter trivial multi-call turns
- Rate limit: max 1 auto-trigger per session
**`src/handlers/skills-command.ts`** (~50 lines)
- `/memory-skills` command listing all skills
**Test files**: `tests/store/skill-store.test.ts`, `tests/tools/skill-tool.test.ts`, `tests/handlers/skill-auto-trigger.test.ts`
### Modified Files
**`src/constants.ts`** — Add `SKILL_TOOL_DESCRIPTION`, `DEFAULT_SKILL_TRIGGER_TOOL_CALLS` (= 8); update `COMBINED_REVIEW_PROMPT`:
```typescript
export const COMBINED_REVIEW_PROMPT = `Review the conversation above and consider two things:
**Memory**: Has the user revealed things about themselves — their persona, desires, preferences, or personal details? Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate? If so, save using memory_add.
**Skills**: Was a complex, non-trivial approach used to complete a task — one that required trial and error, multiple tool calls, or changing course? If so, save a reusable procedure using the skill tool with action 'create'. Include: when to use it, step-by-step procedure, pitfalls to avoid, and how to verify success.
Only act if there's something genuinely worth saving. If nothing stands out, just say 'Nothing to save.' and stop.`;
```
**Note on pi.exec() child tools**: The child `pi` process loads the same installed extension, so it has access to the memory write tools and `skill_manage`. This is the same mechanism that makes the existing memory tools work in background review.
**`src/index.ts`** — Wire SkillStore, registerSkillTool, setupSkillAutoTrigger, registerSkillsCommand; inject skill index into system prompt at `before_agent_start`. Pass `config.memoryDir + "/skills/"` directly to SkillStore constructor (no memoryDirPath getter needed).
### Progressive Disclosure
- **System prompt**: Skill index only (name + description per skill, ~3K tokens max)
- **On demand**: Agent calls `skill` tool with action `view` to load full content
- **Frozen snapshot**: Index captured at `session_start`, same as memory snapshot
### Key Decision: Frozen Snapshot for Skills
Skill index is captured at `session_start` and injected at `before_agent_start`. New skills created mid-session appear in the index on next session. This preserves Pi's prompt cache.
---
## Epic 5: Documentation & Release
- Update `README.md` with new features, config options, commands
- Update `docs/ROADMAP.md` — mark v0.2 complete
- Bump `package.json` version to `0.2.0`
- `npm run check` passes, all tests pass
- Tag `v0.2.0`
---
## File Change Summary
### New Files (12)
| File | Lines | Epic |
|---|---|---|
| `src/handlers/auto-consolidate.ts` | ~120 | 2 |
| `src/handlers/consolidate-command.ts` | ~30 | 2 |
| `src/handlers/correction-detector.ts` | ~100 | 3 |
| `src/store/skill-store.ts` | ~250 | 1 |
| `src/tools/skill-tool.ts` | ~180 | 1 |
| `src/handlers/skill-auto-trigger.ts` | ~80 | 1 |
| `src/handlers/skills-command.ts` | ~50 | 1 |
| `tests/handlers/auto-consolidate.test.ts` | ~120 | 2 |
| `tests/handlers/correction-detector.test.ts` | ~150 | 3 |
| `tests/store/skill-store.test.ts` | ~200 | 1 |
| `tests/tools/skill-tool.test.ts` | ~100 | 1 |
| `tests/handlers/skill-auto-trigger.test.ts` | ~80 | 1 |
### Modified Files (8)
| File | Epic(s) |
|---|---|
| `src/types.ts` | 2, 3, 4 |
| `src/constants.ts` | 1, 2, 3, 4 |
| `src/config.ts` | 2, 3, 4 |
| `src/store/memory-store.ts` | 1, 2 |
| `src/tools/memory-tool.ts` | 2 |
| `src/handlers/background-review.ts` | 4 |
| `src/index.ts` | 1, 2, 3, 4 |
| `tests/handlers/background-review.test.ts` | 4 |
---
## Verification
After each epic:
1. `npm run check` — zero type errors
2. `npm test` — all tests pass
3. Manual test: `pi -e ./src/index.ts` — verify the feature works in a live session
Final:
4. Full regression: all 119 existing tests + new tests pass
5. Tag v0.2.0
+134
View File
@@ -0,0 +1,134 @@
# Tasks — v0.2.0: Skills + Smart Curation
> **Workflow**: When you start a task, change `[ ]` to `[~]`. When done, change to `[x]` and note the commit hash.
>
> **Implementation order**: Epic 2 → Epic 3 → Epic 4 → Epic 1 → Epic 5 (quick wins first, then the largest piece)
>
> **Plan**: See `docs/0.2/PLAN.md` for full implementation details and architectural decisions.
---
## Epic 2: Auto-Consolidation
_Done when: memory full no longer returns an error — it triggers automatic consolidation and retries the add._
### Shared Config (Epics 2-4 touch these files — do once, extend per epic)
- [x] `src/types.ts` — add `autoConsolidate: boolean` to `MemoryConfig`; add `ConsolidationResult` interface (`c6317dd`)
- [x] `src/config.ts` — add `autoConsolidate: true` default + parsing (`c6317dd`)
- [x] `src/constants.ts` — add `CONSOLIDATION_PROMPT` (`c6317dd`)
### Implementation
- [x] `src/store/memory-store.ts` — make `add()` async, add `setConsolidator()` injection method; after consolidation: `await this.loadFromDisk()` before retry (`c6317dd`)
- [x] `src/tools/memory-tool.ts` — `await store.add(target, content)` (`c6317dd`)
- [x] `src/handlers/auto-consolidate.ts` — `triggerConsolidation()` using `pi.exec()` pattern (`c6317dd`)
- [x] `src/handlers/consolidate-command.ts` — `/memory-consolidate` command (`c6317dd` — combined into `auto-consolidate.ts`)
- [x] `src/index.ts` — wire consolidator via `store.setConsolidator()` + register command (`c6317dd`)
### Tests
- [x] `tests/handlers/auto-consolidate.test.ts` — consolidation trigger, pi.exec call, success/failure paths (`83e7c46`)
- [x] `tests/store/memory-store.test.ts` — migrate all `store.add()` calls to `await store.add()`; consolidator tests (`83e7c46`)
---
## Epic 3: Correction Detection + Immediate Save
_Done when: user corrections are detected in real-time and trigger an immediate memory save._
### Config
- [x] `src/types.ts` — add `correctionDetection: boolean` to `MemoryConfig` (`c6317dd`)
- [x] `src/config.ts` — add `correctionDetection: true` default + parsing (`c6317dd`)
- [x] `src/constants.ts` — add `CORRECTION_SAVE_PROMPT`, strong/weak/negative pattern arrays (`c6317dd`)
### Implementation
- [x] `src/handlers/correction-detector.ts` — two-pass filter: strong/weak/negative patterns (`c6317dd`)
- [x] Rate limiting — `turnsSinceLastCorrection >= 3` and `!correctionInProgress` guard (`c6317dd`)
- [x] `src/index.ts` — wire `setupCorrectionDetector()` (`c6317dd`)
### Tests
- [x] `tests/handlers/correction-detector.test.ts` — 35 tests: strong/weak/negative patterns, rate limiting, false positives (`83e7c46`)
---
## Epic 4: Tool-Call-Aware Nudge
_Done when: background review triggers based on EITHER turn count OR tool call count._
### Config
- [x] `src/types.ts` — add `nudgeToolCalls: number` to `MemoryConfig` (`c6317dd`)
- [x] `src/config.ts` — add `nudgeToolCalls: 15` default + parsing (`c6317dd`)
### Implementation
- [x] `src/handlers/background-review.ts` — count toolCall entries from branch; OR trigger logic; reset both counters (`c6317dd`)
### Tests
- [x] `tests/handlers/background-review.test.ts` — 6 new tests: tool-call trigger, combined trigger, counter reset, text-only, crash recovery (`83e7c46`)
---
## Epic 1: Skill Tool + Procedural Memory
_Done when: the agent can create/update/delete skill documents, skills appear in a progressive index in the system prompt, and skills are auto-created after complex tasks._
### Research & Design
- [x] Read Pi's skill discovery API — Pi uses `~/.pi/agent/skills/` with SKILL.md frontmatter format (`c6317dd`)
- [x] Decide: write to `~/.pi/agent/memory/skills/` — isolated from user skills (`c6317dd`)
- [x] Read Hermes `skill_manage` tool source for reference patterns (`c6317dd`)
### Store
- [x] `src/store/skill-store.ts` — `SkillStore` class with full CRUD + `formatIndexForSystemPrompt()` (`c6317dd`)
- [x] SKILL.md format — frontmatter (name, description, version, created, updated) + markdown body (`c6317dd`)
- [x] File naming — `slugify(name) + ".md"` (`c6317dd`)
- [x] Frontmatter parsing — regex-based, no yaml dependency (`c6317dd`)
- [x] Content scanning — all writes go through `scanContent()` (`c6317dd`)
- [x] Atomic writes — temp+rename pattern (`c6317dd`)
### Tool
- [x] `src/tools/skill-tool.ts` — `registerSkillTool()` with actions: `create`, `view`, `patch`, `edit`, `delete` (`c6317dd`)
- [x] `src/constants.ts` — add `SKILL_TOOL_DESCRIPTION` and `DEFAULT_SKILL_TRIGGER_TOOL_CALLS` (= 8) (`c6317dd`)
- [x] Rewrite `COMBINED_REVIEW_PROMPT` — references skill tool with create/patch actions (`c6317dd`)
### Progressive Disclosure
- [x] Skill index (name + description only) injected into system prompt at `before_agent_start` (`c6317dd`)
- [x] `view` action loads full skill content on demand (`c6317dd`)
- [x] Frozen snapshot — index captured at `session_start`, consistent throughout session (`c6317dd`)
### Auto-Trigger
- [x] `src/handlers/skill-auto-trigger.ts` — 8+ tool calls with 2+ distinct tool types (`c6317dd`)
- [x] Rate limit — max 1 auto-trigger per session (`c6317dd`)
### Command
- [x] `src/handlers/skills-command.ts` — `/memory-skills` command (`c6317dd`)
### Wiring
- [x] `src/index.ts` — wire SkillStore, registerSkillTool, setupSkillAutoTrigger, registerSkillsCommand (`c6317dd`)
### Tests
- [x] `tests/store/skill-store.test.ts` — 27 tests: CRUD, frontmatter, progressive disclosure, atomic writes (`83e7c46`)
- [x] `tests/tools/skill-tool.test.ts` — 10 tests: registration, action dispatch, validation (`83e7c46`)
- [x] `tests/handlers/skill-auto-trigger.test.ts` — 6 tests: threshold, distinct types, session limit (`83e7c46`)
---
## Epic 5: Documentation & Release
_Done when: v0.2.0 is tagged and released with updated docs._
- [x] Update `README.md` — skill tool, auto-consolidation, correction detection, new config, new commands (`4658529`)
- [x] Update `src/constants.ts` — verify all new prompts are finalized (`c6317dd`)
- [x] Update `docs/ROADMAP.md` — v0.2 roadmap documented (`d5b7518`)
- [x] `npm run check` passes with zero errors (`c6317dd`)
- [x] `npm test` — all 218 tests pass (`83e7c46`)
- [x] Bump `package.json` version to `0.2.0`
- [x] Tag v0.2.0 release
---
## Summary
| Epic | Priority | Est. Complexity | New Files | Modified Files |
|---|---|---|---|---|
| 2: Auto-Consolidation | HIGH | Low | 3 (src + test) | 5 (types, config, constants, memory-store, memory-tool, index) |
| 3: Correction Detection | HIGH | Low | 2 (src + test) | 3 (types, config, constants, index) |
| 4: Tool-Call Nudge | MEDIUM | Low | 0 | 3 (types, config, background-review, test) |
| 1: Skill Tool | CRITICAL | High | 8 (4 src + 4 test) | 3 (constants, index, memory-store) |
| 5: Documentation | NORMAL | Low | 0 | 4 (README, constants, ROADMAP, package.json) |
+216
View File
@@ -0,0 +1,216 @@
# Test Plan — v0.2.0: Skills + Smart Curation
> This document defines the test strategy for v0.2.0. Each section maps to an epic in the implementation plan.
## Current State
- **119 existing tests** — all passing after `add()` async migration
- **Zero new tests** yet for v0.2 features
- **Type check**: `npm run check` passes with zero errors
---
## Epic 2: Auto-Consolidation
### Unit Tests: `tests/handlers/auto-consolidate.test.ts`
| Test | What | Expected |
|---|---|---|
| `triggerConsolidation builds correct prompt` | Verify prompt includes current entries + CONSOLIDATION_PROMPT | Prompt contains entry text and consolidation instructions |
| `triggerConsolidation returns consolidated on success` | Mock `pi.exec()` to return code 0 | `{ consolidated: true }` |
| `triggerConsolidation returns error on failure` | Mock `pi.exec()` to return code 1 | `{ consolidated: false, error: "..." }` |
| `triggerConsolidation returns error on exception` | Mock `pi.exec()` to throw | `{ consolidated: false, error: "Consolidation failed..." }` |
| `/memory-consolidate consolidates both targets` | Mock handler, verify both "memory" and "user" get consolidated | UI notification contains both results |
| `/memory-consolidate skips empty targets` | Store has empty user entries | Report shows "(empty, nothing to consolidate)" for that target |
### Integration Tests: `tests/store/memory-store.test.ts` (extend existing)
| Test | What | Expected |
|---|---|---|
| `add() triggers consolidation when over limit` | Config `autoConsolidate: true`, mock consolidator returns success, entry exceeds limit | `add()` succeeds after consolidation + reload |
| `add() retries once after consolidation` | Verify consolidator called once, then `loadFromDisk()` called, then add succeeds | Entry appears in entries |
| `add() falls through to error if consolidation fails` | Mock consolidator returns `{ consolidated: false }` | Error about exceeding limit |
| `add() skips consolidation when disabled` | Config `autoConsolidate: false` | Error about exceeding limit (no consolidator call) |
| `add() skips consolidation when no consolidator set` | `setConsolidator()` not called | Error about exceeding limit |
| `add() consolidates for user target too` | Same test but target is "user" | Works identically |
---
## Epic 3: Correction Detection
### Unit Tests: `tests/handlers/correction-detector.test.ts`
#### Pattern Matching: `isCorrection()`
**Strong patterns (always trigger):**
| Input | Expected |
|---|---|
| `"don't do that"` | `true` |
| `"not like that"` | `true` |
| `"I said use yarn"` | `true` |
| `"I told you already"` | `true` |
| `"we already discussed this"` | `true` |
| `"please don't commit yet"` | `true` |
| `"that's not what I asked for"` | `true` |
**Weak patterns (need directive clause):**
| Input | Expected | Why |
|---|---|---|
| `"no, use yarn instead"` | `true` | "use" is directive |
| `"wrong, the file is in src/"` | `true` | "the" is directive |
| `"actually, don't use that"` | `true` | "don't" is directive |
| `"stop, fix the test first"` | `true` | "fix" is directive |
| `"no worries, I'll handle it"` | `false` | Negative pattern suppresses |
| `"no problem"` | `false` | Negative pattern suppresses |
| `"no thanks"` | `false` | Negative pattern suppresses |
| `"no need to change that"` | `false` | Negative pattern suppresses |
| `"actually, that looks great"` | `false` | Negative pattern suppresses |
| `"actually, perfect"` | `false` | Negative pattern suppresses |
| `"stop there"` | `false` | Negative pattern suppresses |
**Non-corrections (should NOT trigger):**
| Input | Expected |
|---|---|
| `"yes, do that"` | `false` |
| `"looks good"` | `false` |
| `"can you also check the tests?"` | `false` |
| `""` | `false` |
| `"thanks"` | `false` |
#### Handler Behavior
| Test | What | Expected |
|---|---|---|
| `triggers pi.exec on correction` | Emit user message "no, don't use npm", then turn_end | `pi.exec()` called with CORRECTION_SAVE_PROMPT |
| `does not trigger on normal message` | Emit user message "looks good", then turn_end | `pi.exec()` NOT called |
| `rate limits: 1 per 3 turns` | Emit correction at turn 1, correction at turn 2 | Only first correction triggers save |
| `rate limit resets after 3 turns` | Emit correction at turn 1, then normal turns 2-4, then correction at turn 5 | Both corrections trigger save |
| `does not trigger when in progress` | Emit correction, then another correction before first completes | Only first triggers |
| `disabled via config` | Config `correctionDetection: false` | No handler registered |
| `includes recent context (last 6 exchanges)` | Verify prompt content | Prompt includes recent messages + current memory |
---
## Epic 4: Tool-Call-Aware Nudge
### Unit Tests: `tests/handlers/background-review.test.ts` (extend existing)
| Test | What | Expected |
|---|---|---|
| `triggers on turn count threshold` | `turnsSinceReview >= 10`, `toolCallsSinceReview < 15` | Review triggers |
| `triggers on tool call count threshold` | `turnsSinceReview < 10`, `toolCallsSinceReview >= 15` | Review triggers |
| `triggers when both thresholds met` | Both thresholds exceeded | Review triggers |
| `does not trigger when neither threshold met` | Both below threshold | No review |
| `resets both counters after review` | After review completes | Both counters = 0 |
| `counts toolCall blocks from branch` | Branch has 3 assistant messages with 2 toolCall blocks each | `toolCallsSinceReview = 6` |
| `ignores text blocks in content` | Branch has text blocks only | `toolCallsSinceReview = 0` |
| `falls back gracefully if branch access fails` | `sessionManager.getBranch()` throws | No crash, continues with turn-based only |
---
## Epic 1: Skill Tool + Procedural Memory
### Unit Tests: `tests/store/skill-store.test.ts`
#### CRUD Operations
| Test | What | Expected |
|---|---|---|
| `create() writes SKILL.md with correct frontmatter` | Create skill with name, description, body | File exists with `---\nname: ...\n---\n` format |
| `create() slugifies name correctly` | Name: `"Debug TypeScript Errors!"` | File: `debug-typescript-errors.md` |
| `create() returns error for duplicate name` | Create same skill twice | Second returns error about existing skill |
| `create() returns error for empty name` | `name: ""` | Error: "Skill name is required." |
| `create() returns error for empty description` | Valid name, empty description | Error: "Skill description is required." |
| `create() returns error for empty body` | Valid name/desc, empty body | Error: "Skill body is required." |
| `create() scans content for security` | Body contains injection pattern | Error: "Blocked: content matches threat pattern" |
| `loadIndex() returns all skills` | Create 3 skills, call loadIndex | Returns 3 SkillIndex entries |
| `loadIndex() returns empty array when no skills` | Empty skills dir | Returns `[]` |
| `loadSkill() returns full document` | Load specific .md file | Returns SkillDocument with all fields |
| `loadSkill() returns null for missing file` | Nonexistent file | Returns `null` |
| `loadSkill() returns null for missing frontmatter` | File without `---` frontmatter | Returns `null` |
| `patch() replaces existing section` | Skill has `## Procedure`, patch it | New content replaces old section |
| `patch() appends new section` | Skill has no `## Pitfalls`, patch it | Section appended |
| `patch() increments version` | Patch a skill | Version goes from 1 → 2 |
| `patch() scans content` | New content has injection pattern | Blocked |
| `edit() replaces description and body` | Edit with new desc + body | Both updated |
| `edit() replaces only description` | Edit with new desc, empty body | Only description changes |
| `edit() increments version` | Edit a skill | Version incremented |
| `delete() removes file` | Delete a skill | File gone, loadIndex returns one fewer |
| `delete() returns error for missing file` | Delete nonexistent | Error: "not found" |
#### Frontmatter Parsing
| Test | What | Expected |
|---|---|---|
| `parses standard frontmatter` | `---\nname: foo\ndescription: bar\n---\nbody` | `{ name: "foo", description: "bar", body: "body" }` |
| `handles value with colons` | `description: uses this: that` | Description = `"uses this: that"` |
| `handles empty body` | Frontmatter only, no body after `---` | body = `""` |
| `handles no frontmatter` | Plain markdown without `---` | Returns `{ meta: {}, body: raw }` |
#### Progressive Disclosure
| Test | What | Expected |
|---|---|---|
| `formatIndexForSystemPrompt() returns formatted index` | 2 skills | String with skill names + descriptions |
| `formatIndexForSystemPrompt() returns empty when no skills` | No skills | Returns `""` |
| `index does not include body content` | Skills have long bodies | Index only shows name + description |
#### Atomic Writes
| Test | What | Expected |
|---|---|---|
| `create() uses atomic write (file exists after create)` | Create skill, read file | File exists with correct content |
| `file content is correct after create + patch` | Create then patch | File on disk reflects patch |
### Unit Tests: `tests/tools/skill-tool.test.ts`
| Test | What | Expected |
|---|---|---|
| `registers tool with name 'skill'` | Check tool registration | Tool name = "skill" |
| `create requires name, description, content` | Missing each param | Error for each missing param |
| `view without file_name lists all skills` | No file_name param | Returns skill index |
| `view with file_name returns full document` | Valid file_name | Returns SkillDocument |
| `view with invalid file_name returns error` | Nonexistent file | Error: "not found" |
| `patch requires file_name, section, content` | Missing params | Error for each |
| `edit requires file_name` | No file_name | Error |
| `delete requires file_name` | No file_name | Error |
| `unknown action returns error` | `action: "foo"` | Error: "Unknown action" |
### Unit Tests: `tests/handlers/skill-auto-trigger.test.ts`
| Test | What | Expected |
|---|---|---|
| `triggers at 8+ tool calls with 2+ types` | Branch has 8 toolCall blocks with 3 distinct tool names | `pi.exec()` called |
| `does not trigger below 8 tool calls` | Branch has 7 toolCall blocks | Not triggered |
| `does not trigger with only 1 tool type` | 10 toolCall blocks, all same tool | Not triggered |
| `only triggers once per session` | Two turn_end events both meeting threshold | Only first triggers |
| `handles branch access failure gracefully` | `getBranch()` throws | No crash |
---
## Epic 5: Documentation & Release
### Manual Verification
| Check | Command | Expected |
|---|---|---|
| Type check passes | `npm run check` | Zero errors |
| All tests pass | `npm test` | 119+ tests, 0 failures |
| README updated | Manual review | Mentions skill tool, auto-consolidation, correction detection |
| ROADMAP updated | Manual review | v0.2 marked complete |
| Version bumped | `cat package.json \| grep version` | `"version": "0.2.0"` |
| Git tagged | `git tag -l "v0.2*"` | `v0.2.0` exists |
---
## Summary
| Area | New Tests | Existing Tests Modified |
|---|---|---|
| Auto-Consolidation | 6 + 6 | `memory-store.test.ts` (6 tests for async+consolidator) |
| Correction Detection | ~20 (patterns + handler) | — |
| Tool-Call Nudge | 8 | `background-review.test.ts` (extend) |
| Skill Store | ~25 | — |
| Skill Tool | ~10 | — |
| Skill Auto-Trigger | 5 | — |
| **Total** | **~80 new tests** | **~14 modified** |