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
+57
View File
@@ -0,0 +1,57 @@
# v0.6.6 Changelog
## Bug Fixes
### Fix legacy SQLite upgrade error: `no such column: category`
Some users upgrading from older versions had an existing `sessions.db` with a legacy
`memories` table that did not include v0.6 failure-memory columns. During schema init,
creating `idx_memories_category` failed and `/memory-index-sessions` crashed with:
`❌ Session indexing failed: no such column: category`
Fix:
- Added automatic legacy schema migration in `DatabaseManager`
- Detects missing `memories` columns and adds them idempotently:
- `category`
- `failure_reason`
- `tool_state`
- `corrected_to`
- Retries schema initialization after migration
- Added regression test: `should migrate legacy memories table without category column`
---
# v0.6.5 Changelog
## Bug Fixes
### Auto-review no longer blocks interactive chat (#10)
The background auto-review was `await`ing `pi.exec()` inside the `turn_end` handler, which
blocked the chat from responding while the review subprocess ran. Fixed by making the
review subprocess fire-and-forget — the turn_end handler returns immediately, and the
subprocess completes asynchronously.
- `pi.exec()` is no longer awaited — handler returns immediately
- `reviewInProgress` guard resets in `.then()` / `.catch()` callbacks
- Overlapping reviews are still prevented by the guard
- Notifications are delivered via `.then()` callback once the subprocess completes
### Auto-review failures on Windows no longer show errors (#9)
On Windows git-bash, `pi exec` subprocesses could exit with code 1 producing
`[hermes] auto-review failed (exit=1): unknown error` messages every few turns. Fixed by
making auto-review truly best-effort — non-zero exit codes and spawn errors are silently
ignored.
- Suppressed error notifications for non-zero exit codes
- Suppressed error notifications for subprocess failures (timeout, signal, spawn)
- The next review cycle will retry automatically
### Crash safety
- Snapshot-building code (`getBranch()`, message parsing) is wrapped in a minimal try/catch
to handle expired sessions gracefully
- Early return resets `reviewInProgress` guard to unblock future reviews
+202
View File
@@ -0,0 +1,202 @@
# v0.5 Plan: Failure Memory + Categories + Provenance
## Overview
Track **failures, corrections, and insights** as first-class memories with full provenance and category labels. Learn from failures like humans do.
## Motivation
From X/Twitter feedback:
> "Memory gets much more useful when it stores failures, not just conversations. I'd want every recalled session to carry provenance: source, timestamp, tool state, and whether the old answer survived contact with reality."
## Key Features
### 1. Memory Categories
Add category labels to differentiate memory types:
| Category | What It Is | Example |
|---|---|---|
| `failure` | What didn't work | "Tried localStorage for tokens — XSS risk" |
| `correction` | User corrected the agent | "Use pnpm, not npm" |
| `insight` | Learning from experience | "Auth0 SDK handles refresh tokens automatically" |
| `preference` | User preference | "Prefers dark theme" |
| `convention` | Project convention | "Monorepo uses turborepo" |
| `tool-quirk` | Tool-specific knowledge | "CI needs --frozen-lockfile" |
### 2. Failure Memory Structure
```typescript
interface FailureMemory {
category: 'failure' | 'correction' | 'insight' | 'preference' | 'convention' | 'tool-quirk';
content: string; // What was tried / what happened
failure_reason?: string; // Why it failed (for failures)
tool_state?: string; // Relevant tool state (error message, output)
corrected_to?: string; // What worked instead (if known)
project: string; // Which project
session_id?: string; // Which session
timestamp: string; // When it happened
}
```
### 3. Auto-Detect Failures
Detect failures from:
- **Explicit corrections**: "that didn't work", "use X instead", "no, do it this way"
- **Error messages**: stderr output, test failures, build errors
- **Agent retries**: When the agent tries multiple approaches
- **User feedback**: "this is wrong", "that's not right"
### 4. Failure Injection into System Prompt
Inject relevant recent failures into the system prompt at session start:
```
<memory-context>
RECENT FAILURES & LESSONS (learn from these):
• [failure] Tried: localStorage for JWT tokens — Failed: XSS vulnerability
→ Corrected to: httpOnly cookies with SameSite=Strict
• [correction] Use pnpm, not npm (corrected 2 days ago)
• [insight] Auth0 SDK handles refresh tokens automatically — no manual implementation needed
═══ END MEMORY ═══
</memory-context>
```
**Injection rules:**
- Only inject failures from last 7 days
- Only inject failures relevant to current project (or global)
- Max 5 failure entries to avoid prompt bloat
- Separate `<memory-context>` block from regular memory
### 5. Search with Categories
Update `memory_search` tool to support category filtering:
```
memory_search("auth", category: "failure") → Past auth failures
memory_search("deploy", category: "convention") → Deploy conventions
memory_search("typescript", category: "tool-quirk") → TS tool quirks
```
### 6. Store Failures in SQLite
Failures stored in `memories` table with `target: 'failure'`:
```sql
-- New target type
target TEXT CHECK (target IN ('memory', 'user', 'failure'))
-- Content stored as JSON with category
{
"category": "failure",
"content": "Tried localStorage for JWT tokens",
"failure_reason": "XSS vulnerability - tokens accessible via JS",
"tool_state": "Error: Token exposed in browser console",
"corrected_to": "httpOnly cookies with SameSite=Strict",
"project": "my-app",
"timestamp": "2026-05-03T10:30:00Z"
}
```
### 7. Update Background Review Prompt
Enhance the background review prompt to extract failures:
```
Review this conversation and extract:
1. FAILURES: What was tried but didn't work?
- What was attempted
- Why it failed
- What error occurred
- What worked instead (if found)
2. CORRECTIONS: Did the user correct the agent?
- What was wrong
- What is correct
3. INSIGHTS: What was learned?
- New knowledge about tools, APIs, patterns
- Project-specific learnings
4. CONVENTIONS: Any project conventions discovered?
- Coding style, naming, patterns
- Tool preferences
```
## Architecture Changes
### Memory Store (`src/store/memory-store.ts`)
```typescript
// Add to MemoryStore class
addFailure(content: string, options: {
category: MemoryCategory;
failureReason?: string;
toolState?: string;
correctedTo?: string;
}): void;
getFailureEntries(): string[]; // Returns recent failures for injection
```
### SQLite Memory Store (`src/store/sqlite-memory-store.ts`)
```typescript
// Update searchMemories to support category filter
searchMemories(db, query, { project, target, category, limit })
```
### Memory Search Tool (`src/tools/memory-search-tool.ts`)
```typescript
// Add category parameter
category: Type.Optional(StringEnum([
'failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk'
] as const, { description: 'Filter by memory category.' }))
```
### Background Review (`src/handlers/background-review.ts`)
- Extract failures during review
- Store with category labels
- Include failure context in review prompt
### Correction Detector (`src/handlers/correction-detector.ts`)
- Extract failure context when correction detected
- Store what was wrong + what is correct
### System Prompt Injection (`src/index.ts`)
- Add separate `<memory-context>` block for failures
- Inject only recent (7 days) and relevant (project match)
- Max 5 entries
## Files to Change
| File | Change |
|---|---|
| `src/types.ts` | Add `MemoryCategory` type |
| `src/constants.ts` | Update review prompt for failure extraction |
| `src/store/memory-store.ts` | Add `addFailure()`, `getFailureEntries()` |
| `src/store/sqlite-memory-store.ts` | Add category support to search |
| `src/tools/memory-search-tool.ts` | Add category parameter |
| `src/handlers/background-review.ts` | Extract failures during review |
| `src/handlers/correction-detector.ts` | Store failure context on corrections |
| `src/index.ts` | Inject failure memories into system prompt |
| `tests/store/memory-store.test.ts` | Test failure storage |
| `tests/store/sqlite-memory-store.test.ts` | Test category search |
| `tests/tools/memory-search-tool.test.ts` | Test category parameter |
## Complexity Assessment
- **Effort**: Medium (2-3 hours)
- **Risk**: Low (additive, no breaking changes)
- **Tests**: ~15 new tests
## Migration
- Existing memories get `category: null` (no migration needed)
- New memories get category assigned
- Search works with or without category filter
+144
View File
@@ -0,0 +1,144 @@
# v0.5 Tasks: Failure Memory + Categories + Provenance
## Status Legend
- `[ ]` Not started
- `[~]` In progress
- `[x]` Done
---
## Epic 1: Category Types & Schema
### Task 1.1: Add MemoryCategory type
- [ ] Add `MemoryCategory` type to `src/types.ts`
- [ ] Categories: `failure`, `correction`, `insight`, `preference`, `convention`, `tool-quirk`
### Task 1.2: Update SQLite schema
- [ ] Update `src/store/schema.ts` — add `category` column to memories table
- [ ] Add index on category for faster filtering
---
## Epic 2: Failure Memory Store
### Task 2.1: Update MemoryStore
- [ ] Add `addFailure()` method to `src/store/memory-store.ts`
- [ ] Store failures in MEMORY.md with category metadata
- [ ] Add `getFailureEntries()` to retrieve recent failures (last 7 days)
- [ ] Update `formatForSystemPrompt()` to include failure section
### Task 2.2: Update SQLite Memory Store
- [ ] Add category support to `src/store/sqlite-memory-store.ts`
- [ ] Update `addMemory()` to accept category
- [ ] Update `searchMemories()` to filter by category
- [ ] Add `getRecentFailures()` method
### Task 2.3: Tests
- [ ] Test `addFailure()` in `tests/store/memory-store.test.ts`
- [ ] Test category filtering in `tests/store/sqlite-memory-store.test.ts`
- [ ] Test `getRecentFailures()` returns only last 7 days
---
## Epic 3: Failure Detection
### Task 3.1: Update Correction Detector
- [ ] Update `src/handlers/correction-detector.ts`
- [ ] Extract failure context when correction detected
- [ ] Store: what was wrong, what is correct, category
### Task 3.2: Update Background Review Prompt
- [ ] Update `src/constants.ts` — enhance `CONSOLIDATION_PROMPT`
- [ ] Add failure extraction instructions
- [ ] Prompt to categorize findings (failure, correction, insight, etc.)
### Task 3.3: Auto-Detect Failures in Conversation
- [ ] Add failure pattern detection in `src/handlers/background-review.ts`
- [ ] Detect: "that didn't work", "use X instead", error messages
- [ ] Store failures with `tool_state` (error output)
### Task 3.4: Tests
- [ ] Test failure detection in `tests/handlers/correction-detector.test.ts`
- [ ] Test failure extraction in `tests/handlers/background-review.test.ts`
---
## Epic 4: Failure Injection
### Task 4.1: Update System Prompt Injection
- [ ] Update `src/index.ts` — add failure memory block
- [ ] Separate `<memory-context>` block for failures
- [ ] Only inject recent (7 days) and relevant (project match)
- [ ] Max 5 failure entries
### Task 4.2: Failure Injection Format
- [ ] Format:
```
RECENT FAILURES & LESSONS (learn from these):
• [failure] Tried: X — Failed: Y → Corrected to: Z
• [correction] Use X, not Y (corrected N days ago)
• [insight] Learned: X
```
### Task 4.3: Tests
- [ ] Test failure injection in `tests/handlers/system-prompt.test.ts`
- [ ] Test: only recent failures injected
- [ ] Test: max 5 entries enforced
---
## Epic 5: Search with Categories
### Task 5.1: Update Memory Search Tool
- [ ] Update `src/tools/memory-search-tool.ts`
- [ ] Add `category` parameter using `StringEnum`
- [ ] Categories: `failure`, `correction`, `insight`, `preference`, `convention`, `tool-quirk`
### Task 5.2: Update Search Implementation
- [ ] Update `src/store/sqlite-memory-store.ts` — `searchMemories()`
- [ ] Filter by category when provided
- [ ] Include category in search results
### Task 5.3: Tests
- [ ] Test category search in `tests/store/sqlite-memory-store.test.ts`
- [ ] Test: `memory_search("auth", category: "failure")` returns failures only
---
## Epic 6: Integration & Polish
### Task 6.1: Wire Everything Together
- [ ] Update `src/index.ts` — ensure all components work together
- [ ] Test end-to-end flow: detect → store → inject → search
### Task 6.2: Update README
- [ ] Add "Learning from Failures" section
- [ ] Document categories and how they work
- [ ] Add examples of failure memory
### Task 6.3: Version Bump
- [ ] Bump to `0.5.5`
- [ ] Run full test suite
- [ ] Publish to npm
---
## Summary
| Epic | Files Changed | Tests |
|---|---|---|
| 1. Category Types | types.ts, schema.ts | 2 |
| 2. Failure Store | memory-store.ts, sqlite-memory-store.ts | 6 |
| 3. Failure Detection | correction-detector.ts, background-review.ts, constants.ts | 4 |
| 4. Failure Injection | index.ts | 3 |
| 5. Category Search | memory-search-tool.ts, sqlite-memory-store.ts | 3 |
| 6. Integration | index.ts, README.md | — |
| **Total** | **8 files** | **~18 tests** |
## Implementation Order
```
Epic 1 (Types) → Epic 2 (Store) → Epic 3 (Detection) → Epic 4 (Injection) → Epic 5 (Search) → Epic 6 (Polish)
```
Each epic builds on the previous one. Epics 3-5 can be done in parallel after Epic 2.