create-walle 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/bin/create-walle.js +134 -0
  2. package/package.json +18 -0
  3. package/template/.env.example +40 -0
  4. package/template/CLAUDE.md +12 -0
  5. package/template/LICENSE +21 -0
  6. package/template/README.md +167 -0
  7. package/template/bin/setup.js +100 -0
  8. package/template/claude-code-skill.md +60 -0
  9. package/template/claude-task-manager/api-prompts.js +1841 -0
  10. package/template/claude-task-manager/api-reviews.js +275 -0
  11. package/template/claude-task-manager/approval-agent.js +454 -0
  12. package/template/claude-task-manager/bin/restart-ctm.sh +16 -0
  13. package/template/claude-task-manager/db.js +1721 -0
  14. package/template/claude-task-manager/docs/PROMPT-MANAGEMENT-DESIGN.md +631 -0
  15. package/template/claude-task-manager/git-utils.js +214 -0
  16. package/template/claude-task-manager/package-lock.json +1607 -0
  17. package/template/claude-task-manager/package.json +31 -0
  18. package/template/claude-task-manager/prompt-harvest.js +1148 -0
  19. package/template/claude-task-manager/public/css/prompts.css +880 -0
  20. package/template/claude-task-manager/public/css/reviews.css +430 -0
  21. package/template/claude-task-manager/public/css/walle.css +732 -0
  22. package/template/claude-task-manager/public/favicon.ico +0 -0
  23. package/template/claude-task-manager/public/icon.svg +37 -0
  24. package/template/claude-task-manager/public/index.html +8346 -0
  25. package/template/claude-task-manager/public/js/prompts.js +3159 -0
  26. package/template/claude-task-manager/public/js/reviews.js +1292 -0
  27. package/template/claude-task-manager/public/js/walle.js +3081 -0
  28. package/template/claude-task-manager/public/manifest.json +13 -0
  29. package/template/claude-task-manager/public/prompts.html +4353 -0
  30. package/template/claude-task-manager/public/setup.html +216 -0
  31. package/template/claude-task-manager/queue-engine.js +404 -0
  32. package/template/claude-task-manager/server-state.js +5 -0
  33. package/template/claude-task-manager/server.js +2254 -0
  34. package/template/claude-task-manager/session-utils.js +124 -0
  35. package/template/claude-task-manager/start.sh +17 -0
  36. package/template/claude-task-manager/tests/test-ai-search.js +61 -0
  37. package/template/claude-task-manager/tests/test-editor-ux.js +76 -0
  38. package/template/claude-task-manager/tests/test-editor-ux2.js +51 -0
  39. package/template/claude-task-manager/tests/test-features-v2.js +127 -0
  40. package/template/claude-task-manager/tests/test-insights-cached.js +78 -0
  41. package/template/claude-task-manager/tests/test-insights.js +124 -0
  42. package/template/claude-task-manager/tests/test-permissions-v2.js +127 -0
  43. package/template/claude-task-manager/tests/test-permissions.js +122 -0
  44. package/template/claude-task-manager/tests/test-pin.js +51 -0
  45. package/template/claude-task-manager/tests/test-prompts.js +164 -0
  46. package/template/claude-task-manager/tests/test-recent-sessions.js +96 -0
  47. package/template/claude-task-manager/tests/test-review.js +104 -0
  48. package/template/claude-task-manager/tests/test-send-dropdown.js +76 -0
  49. package/template/claude-task-manager/tests/test-send-final.js +30 -0
  50. package/template/claude-task-manager/tests/test-send-fixes.js +76 -0
  51. package/template/claude-task-manager/tests/test-send-integration.js +107 -0
  52. package/template/claude-task-manager/tests/test-send-visual.js +34 -0
  53. package/template/claude-task-manager/tests/test-session-create.js +147 -0
  54. package/template/claude-task-manager/tests/test-sidebar-ux.js +83 -0
  55. package/template/claude-task-manager/tests/test-url-hash.js +68 -0
  56. package/template/claude-task-manager/tests/test-ux-crop.js +34 -0
  57. package/template/claude-task-manager/tests/test-ux-review.js +130 -0
  58. package/template/claude-task-manager/tests/test-zoom-card.js +76 -0
  59. package/template/claude-task-manager/tests/test-zoom.js +92 -0
  60. package/template/claude-task-manager/tests/test-zoom2.js +67 -0
  61. package/template/docs/site/api/README.md +187 -0
  62. package/template/docs/site/guides/claude-code.md +58 -0
  63. package/template/docs/site/guides/configuration.md +96 -0
  64. package/template/docs/site/guides/quickstart.md +158 -0
  65. package/template/docs/site/index.md +14 -0
  66. package/template/docs/site/skills/README.md +135 -0
  67. package/template/wall-e/.dockerignore +11 -0
  68. package/template/wall-e/Dockerfile +25 -0
  69. package/template/wall-e/adapters/adapter-base.js +37 -0
  70. package/template/wall-e/adapters/ctm.js +193 -0
  71. package/template/wall-e/adapters/slack.js +56 -0
  72. package/template/wall-e/agent.js +319 -0
  73. package/template/wall-e/api-walle.js +1073 -0
  74. package/template/wall-e/brain.js +1235 -0
  75. package/template/wall-e/channels/agent-api.js +172 -0
  76. package/template/wall-e/channels/channel-base.js +14 -0
  77. package/template/wall-e/channels/imessage-channel.js +113 -0
  78. package/template/wall-e/channels/slack-channel.js +118 -0
  79. package/template/wall-e/chat.js +778 -0
  80. package/template/wall-e/decision/confidence.js +93 -0
  81. package/template/wall-e/deploy.sh +35 -0
  82. package/template/wall-e/docs/specs/2026-04-01-publish-plan.md +112 -0
  83. package/template/wall-e/docs/specs/SKILL-FORMAT.md +326 -0
  84. package/template/wall-e/extraction/contradiction.js +168 -0
  85. package/template/wall-e/extraction/knowledge-extractor.js +190 -0
  86. package/template/wall-e/fly.toml +24 -0
  87. package/template/wall-e/loops/ingest.js +34 -0
  88. package/template/wall-e/loops/reflect.js +63 -0
  89. package/template/wall-e/loops/tasks.js +487 -0
  90. package/template/wall-e/loops/think.js +125 -0
  91. package/template/wall-e/package-lock.json +533 -0
  92. package/template/wall-e/package.json +18 -0
  93. package/template/wall-e/scripts/ingest-slack-search.js +85 -0
  94. package/template/wall-e/scripts/pull-slack-via-claude.js +98 -0
  95. package/template/wall-e/scripts/slack-backfill.js +295 -0
  96. package/template/wall-e/scripts/slack-channel-history.js +454 -0
  97. package/template/wall-e/server.js +93 -0
  98. package/template/wall-e/skills/_bundled/email-digest/SKILL.md +95 -0
  99. package/template/wall-e/skills/_bundled/email-sync/SKILL.md +65 -0
  100. package/template/wall-e/skills/_bundled/email-sync/mail-reader.jxa +104 -0
  101. package/template/wall-e/skills/_bundled/email-sync/run.js +213 -0
  102. package/template/wall-e/skills/_bundled/google-calendar/SKILL.md +73 -0
  103. package/template/wall-e/skills/_bundled/google-calendar/cal-reader.swift +81 -0
  104. package/template/wall-e/skills/_bundled/google-calendar/run.js +181 -0
  105. package/template/wall-e/skills/_bundled/memory-search/SKILL.md +92 -0
  106. package/template/wall-e/skills/_bundled/morning-briefing/SKILL.md +131 -0
  107. package/template/wall-e/skills/_bundled/morning-briefing/run.js +264 -0
  108. package/template/wall-e/skills/_bundled/slack-backfill/SKILL.md +60 -0
  109. package/template/wall-e/skills/_bundled/slack-sync/SKILL.md +55 -0
  110. package/template/wall-e/skills/claude-code-reader.js +144 -0
  111. package/template/wall-e/skills/mcp-client.js +407 -0
  112. package/template/wall-e/skills/skill-executor.js +163 -0
  113. package/template/wall-e/skills/skill-loader.js +410 -0
  114. package/template/wall-e/skills/skill-planner.js +88 -0
  115. package/template/wall-e/skills/slack-ingest.js +329 -0
  116. package/template/wall-e/skills/slack-pull-live.js +270 -0
  117. package/template/wall-e/skills/tool-executor.js +188 -0
  118. package/template/wall-e/tests/adapter-base.test.js +20 -0
  119. package/template/wall-e/tests/adapter-ctm.test.js +122 -0
  120. package/template/wall-e/tests/adapter-slack.test.js +98 -0
  121. package/template/wall-e/tests/agent-api.test.js +256 -0
  122. package/template/wall-e/tests/api-walle.test.js +222 -0
  123. package/template/wall-e/tests/brain.test.js +602 -0
  124. package/template/wall-e/tests/channels.test.js +104 -0
  125. package/template/wall-e/tests/chat.test.js +103 -0
  126. package/template/wall-e/tests/confidence.test.js +134 -0
  127. package/template/wall-e/tests/contradiction.test.js +217 -0
  128. package/template/wall-e/tests/ingest.test.js +113 -0
  129. package/template/wall-e/tests/mcp-client.test.js +71 -0
  130. package/template/wall-e/tests/reflect.test.js +103 -0
  131. package/template/wall-e/tests/server.test.js +111 -0
  132. package/template/wall-e/tests/skills.test.js +198 -0
  133. package/template/wall-e/tests/slack-ingest.test.js +103 -0
  134. package/template/wall-e/tests/think.test.js +435 -0
  135. package/template/wall-e/tools/local-tools.js +697 -0
  136. package/template/wall-e/tools/slack-mcp.js +290 -0
@@ -0,0 +1,631 @@
1
+ # Prompt Management System — Design Document
2
+
3
+ > **Status**: All 4 phases implemented and verified
4
+ > **Date**: 2026-03-20
5
+ > **Files modified**: `db.js`, `api-prompts.js`, `prompt-harvest.js` (new), `public/js/prompts.js`, `public/index.html`, `public/prompts.html`
6
+
7
+ ### Important: Two UI Entry Points
8
+
9
+ The prompt editor exists in **two places**:
10
+ 1. **`public/js/prompts.js`** + **`public/index.html`** — The **embedded** prompt editor accessed via `index.html#prompts`. This is the **primary entry point** users use.
11
+ 2. **`public/prompts.html`** — The **standalone** prompt editor at `/prompts.html`. Legacy entry point.
12
+
13
+ All Phase 1-4 features are implemented in BOTH. The embedded component (`js/prompts.js`) is a self-contained IIFE module (`const PE = (function() { ... })()`) that exposes a public API via the `PE` namespace.
14
+
15
+ ---
16
+
17
+ ## Table of Contents
18
+
19
+ 1. [Overview](#overview)
20
+ 2. [Architecture](#architecture)
21
+ 3. [Phase 1: DB Schema + Harvester + Prompt-Session Mapping](#phase-1)
22
+ 4. [Phase 2: Local Autocomplete + Similar Prompts + Pattern Cache](#phase-2)
23
+ 5. [Phase 3: Prompt Copilot Chat Sidekick](#phase-3)
24
+ 6. [Phase 4: Prompt Lifecycle + Sidebar Redesign + UI Integration](#phase-4)
25
+ 7. [Data Model](#data-model)
26
+ 8. [API Reference](#api-reference)
27
+ 9. [UI Components](#ui-components)
28
+ 10. [Configuration & Dependencies](#configuration)
29
+ 11. [Known Limitations & Future Work](#limitations)
30
+
31
+ ---
32
+
33
+ ## Overview <a id="overview"></a>
34
+
35
+ The Prompt Management System extends Claude Task Manager with intelligent prompt reuse, history analysis, and AI-powered prompt improvement. It bridges the gap between ad-hoc prompting and systematic prompt engineering by:
36
+
37
+ - **Harvesting** user messages from Claude Code session history (JSONL files)
38
+ - **Building** a searchable index of prompts with fuzzy autocomplete
39
+ - **Detecting** reusable patterns across sessions and projects
40
+ - **Providing** an AI copilot for prompt improvement (Haiku model, cost-aware)
41
+ - **Tracking** prompt lifecycle from draft to proven template
42
+ - **Mapping** bidirectional links between prompts and sessions
43
+
44
+ ---
45
+
46
+ ## Architecture <a id="architecture"></a>
47
+
48
+ ```
49
+ ┌────────────────────────────────────────────────────────────┐
50
+ │ Browser (UI Layer) │
51
+ │ ┌──────────────────┐ ┌────────────────────────────────┐ │
52
+ │ │ prompts.html │ │ index.html │ │
53
+ │ │ - Autocomplete │ │ - Queue autocomplete │ │
54
+ │ │ - Copilot panel │ │ - Save to Library button │ │
55
+ │ │ - Harvest modal │ │ - Linked Prompts button │ │
56
+ │ │ - Patterns view │ │ │ │
57
+ │ │ - Lifecycle │ │ │ │
58
+ │ └────────┬─────────┘ └──────────────┬──────────────────┘ │
59
+ └───────────┼────────────────────────────┼────────────────────┘
60
+ │ HTTP/REST │
61
+ ┌───────────┼────────────────────────────┼────────────────────┐
62
+ │ ▼ ▼ │
63
+ │ ┌─────────────────────────────────────────────────────┐ │
64
+ │ │ api-prompts.js (API Layer) │ │
65
+ │ │ 13 new endpoints for harvest/autocomplete/copilot │ │
66
+ │ └────────────────────────┬────────────────────────────┘ │
67
+ │ │ │
68
+ │ ┌────────────────────────▼────────────────────────────┐ │
69
+ │ │ prompt-harvest.js (Engine) │ │
70
+ │ │ - Session parser (JSONL → structured messages) │ │
71
+ │ │ - Image dedup (MD5 hash) │ │
72
+ │ │ - Autocomplete index (in-memory, 60s cache) │ │
73
+ │ │ - Pattern detection (normalize → group → count) │ │
74
+ │ │ - Copilot (Anthropic API → Haiku model) │ │
75
+ │ │ - Prompt-session mapping (bidirectional) │ │
76
+ │ │ - Multi-session question surfacing │ │
77
+ │ └────────────────────────┬────────────────────────────┘ │
78
+ │ │ │
79
+ │ ┌────────────────────────▼────────────────────────────┐ │
80
+ │ │ db.js (Data Layer) │ │
81
+ │ │ SQLite (WAL mode, better-sqlite3) │ │
82
+ │ │ 3 new tables + 1 new column + 4 indexes │ │
83
+ │ └─────────────────────────────────────────────────────┘ │
84
+ │ Server (Node.js) │
85
+ └──────────────────────────────────────────────────────────────┘
86
+
87
+
88
+ ┌──────────────────────────────────┐
89
+ │ ~/.claude/projects/*/ │
90
+ │ Session JSONL files │
91
+ │ (read-only, harvested) │
92
+ └──────────────────────────────────┘
93
+ ```
94
+
95
+ ---
96
+
97
+ ## Phase 1: DB Schema + Harvester + Prompt-Session Mapping <a id="phase-1"></a>
98
+
99
+ ### Goal
100
+ Extract and store user messages from Claude Code session history for search, analysis, and reuse.
101
+
102
+ ### New Tables
103
+
104
+ #### `prompt_executions`
105
+ Stores every user/assistant message harvested from session JSONL files.
106
+
107
+ | Column | Type | Description |
108
+ |--------|------|-------------|
109
+ | `id` | INTEGER PK | Auto-increment |
110
+ | `session_id` | TEXT NOT NULL | Claude Code session UUID |
111
+ | `message_text` | TEXT NOT NULL | Full message content (up to 10,000 chars) |
112
+ | `message_index` | INTEGER | Position in conversation (0-based) |
113
+ | `role` | TEXT | `user` or `assistant` |
114
+ | `tool_uses` | TEXT | JSON array of `{name, input_summary}` for assistant messages |
115
+ | `image_refs` | TEXT | JSON array of `{id, filename, path}` for deduped images |
116
+ | `project_path` | TEXT | Project directory path |
117
+ | `cwd` | TEXT | Working directory at time of message |
118
+ | `source` | TEXT | `harvested` (from JSONL) or `sent` (from UI) |
119
+ | `outcome` | TEXT | Optional outcome tracking (success/partial/failed) |
120
+ | `outcome_notes` | TEXT | Optional notes on outcome |
121
+ | `executed_at` | TEXT | Original timestamp from session |
122
+ | `created_at` | TEXT | When record was created |
123
+
124
+ **Unique constraint**: `(session_id, message_index)` — prevents duplicate harvesting.
125
+
126
+ **Indexes**: `session_id`, `role`, `project_path`, `executed_at`
127
+
128
+ #### `prompt_patterns`
129
+ Detected reusable prompt patterns (prompts used 2+ times across sessions).
130
+
131
+ | Column | Type | Description |
132
+ |--------|------|-------------|
133
+ | `id` | INTEGER PK | Auto-increment |
134
+ | `normalized_text` | TEXT UNIQUE | Normalized form (stopwords removed, lowercased) |
135
+ | `frequency` | INTEGER | How many times this pattern appears |
136
+ | `example_text` | TEXT | One actual example of this pattern |
137
+ | `sessions` | TEXT | JSON array of session IDs where used (up to 5) |
138
+ | `projects` | TEXT | JSON array of project paths |
139
+ | `last_used_at` | TEXT | Most recent usage timestamp |
140
+ | `created_at` / `updated_at` | TEXT | Record timestamps |
141
+
142
+ #### `harvest_state`
143
+ Singleton row tracking incremental harvest progress.
144
+
145
+ | Column | Type | Description |
146
+ |--------|------|-------------|
147
+ | `id` | INTEGER PK | Always 1 (CHECK constraint) |
148
+ | `last_scan_at` | TEXT | Timestamp of last harvest run |
149
+ | `files_scanned` | INTEGER | Cumulative files scanned |
150
+ | `prompts_harvested` | INTEGER | Cumulative messages harvested |
151
+
152
+ ### New Column
153
+
154
+ - `prompts.lifecycle_status` — TEXT DEFAULT 'draft', added to existing `prompts` table
155
+
156
+ ### Harvester Engine (`prompt-harvest.js`)
157
+
158
+ **Session parsing** (`parseFullSession`):
159
+ - Reads JSONL files line by line
160
+ - Extracts user messages (text + image blocks)
161
+ - Extracts assistant messages (text + tool_use blocks)
162
+ - Summarizes tool inputs for context (file paths, commands, patterns)
163
+
164
+ **Image deduplication** (`saveHarvestedImage`):
165
+ - Computes MD5 hash of base64 image data
166
+ - Stores in `CTM_DATA_DIR/images/{hash}.{ext}`
167
+ - Skips write if file with same hash already exists
168
+ - Records in `images` table with `prompt_id = NULL` for harvested images
169
+
170
+ **Incremental harvesting** (`runHarvest`):
171
+ - Scans `~/.claude/projects/*/` for JSONL session files
172
+ - Supports scopes: `all` (full rescan) or `incremental` (only modified since last scan)
173
+ - Supports filters: `maxDays` (time window), `projectFilter` (specific project)
174
+ - Progress callback for UI updates
175
+ - Transactional batch inserts with `INSERT OR IGNORE` for dedup
176
+
177
+ **Harvest preview** (`getHarvestPreview`):
178
+ - Returns stats without scanning: total sessions, size, date range, projects breakdown
179
+ - Used by UI to show what will be harvested before running
180
+
181
+ ### Prompt-Session Mapping
182
+
183
+ **Bidirectional**:
184
+ - `getSessionsForPrompt(promptId)` — finds sessions where a library prompt was sent (via `prompt_usage` table)
185
+ - `getPromptsForSession(sessionId)` — returns all harvested user messages + any library prompts linked to the session
186
+
187
+ ### Outcome Tracking
188
+
189
+ - `setExecutionOutcome(executionId, outcome, notes)` — mark a harvested message with success/partial/failed
190
+ - `getExecutionStats(promptId)` — aggregate outcome stats for a prompt
191
+
192
+ ### Verification Results
193
+ - 20,267 messages harvested from 224 sessions
194
+ - 53 patterns detected
195
+ - Harvest state persisted correctly
196
+ - Incremental mode works (0 files on re-scan)
197
+
198
+ ---
199
+
200
+ ## Phase 2: Local Autocomplete + Similar Prompts + Pattern Cache <a id="phase-2"></a>
201
+
202
+ ### Goal
203
+ Provide fast, local fuzzy search across harvested prompts, library prompts, and Claude's tool usage history.
204
+
205
+ ### Autocomplete Index
206
+
207
+ **In-memory cache** with 60-second TTL (`buildAutocompleteIndex`):
208
+
209
+ Three source types indexed:
210
+ 1. **`history`** — User messages from `prompt_executions` (last 5,000, first line as display text, full text up to 1,000 chars)
211
+ 2. **`tool_context`** — Assistant tool uses from `prompt_executions` (e.g., `[Read] /path/to/file.js`, `[Bash] npm test`)
212
+ 3. **`library`** — Prompts from the library (title + content)
213
+
214
+ **Fuzzy search** (`searchAutocomplete`):
215
+ - Minimum 3 character query
216
+ - Scoring: prefix match = 100, word-in-text = 10, word-in-fullText = 5
217
+ - All query words must match somewhere (AND logic)
218
+ - Sorted by score descending, then by recency
219
+ - Returns up to 8 results
220
+
221
+ ### Similar Prompts
222
+
223
+ **`findSimilarPrompts`** — more thorough than autocomplete, for the copilot panel:
224
+ - Minimum 20 character input
225
+ - Filters to words > 3 characters (removes stopwords naturally)
226
+ - Requires 40%+ word match ratio
227
+ - Excludes `tool_context` type (only matches user prompts and library)
228
+ - Deduplicates by first 100 chars
229
+
230
+ ### Pattern Detection
231
+
232
+ **`detectPatterns`**:
233
+ - Reads last 2,000 user messages
234
+ - Normalizes: lowercase → remove stopwords → remove punctuation → collapse whitespace
235
+ - Groups by normalized form
236
+ - Patterns with 2+ occurrences saved to `prompt_patterns` table
237
+ - Upsert with `ON CONFLICT` for idempotent re-detection
238
+
239
+ **Normalization** (`normalizePrompt`):
240
+ - Removes: `the, a, an, is, are, was, were, be, been, being, have, has, had, do, does, did, will, would, could, should, can, may, might, shall, this, that, these, those, it, its, my, your, our, their`
241
+ - Removes quotes, punctuation
242
+ - Collapses whitespace
243
+
244
+ ### Multi-Session Question Surfacing
245
+
246
+ **`getFrequentQuestions`**:
247
+ - Finds user messages appearing in 2+ sessions
248
+ - Two strategies merged:
249
+ 1. **Exact match** — SQL `GROUP BY message_text HAVING COUNT(DISTINCT session_id) >= 2`
250
+ 2. **Normalized match** — group by `normalizePrompt()` output for fuzzy duplicates
251
+ - Merged, deduplicated, sorted by session count
252
+
253
+ ### Verification Results
254
+ - 3,703 entries in autocomplete index (1,750 history + 1,921 tool_context + 32 library)
255
+ - Autocomplete returns results in < 10ms
256
+ - 53 patterns detected with frequency data
257
+ - 20 frequent questions surfaced
258
+
259
+ ---
260
+
261
+ ## Phase 3: Prompt Copilot Chat Sidekick <a id="phase-3"></a>
262
+
263
+ ### Goal
264
+ AI-powered prompt improvement and history Q&A, cost-aware with Haiku model.
265
+
266
+ ### Auto-Suggestion (`getCopilotSuggestion`)
267
+
268
+ **Trigger conditions** (client-side):
269
+ - 3-second debounce after typing stops
270
+ - Minimum 80 characters typed (prevents trivial triggers)
271
+ - Only fires when editor has focus
272
+
273
+ **API call**:
274
+ - Model: `claude-haiku-4-5-20251001` (cost-effective)
275
+ - Max tokens: 300
276
+ - Builds context from similar prompts found in history
277
+ - Includes project path if available
278
+ - Supports `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` for proxy setups (e.g., Portkey)
279
+
280
+ **Response format**:
281
+ ```json
282
+ {
283
+ "suggestion": "Brief improvement advice",
284
+ "improved": "Full improved prompt text (or null if already good)",
285
+ "quality": "good" | "needs_work" | "vague"
286
+ }
287
+ ```
288
+
289
+ **Graceful degradation**: Returns `null` if `ANTHROPIC_API_KEY` is not set — UI handles this silently.
290
+
291
+ ### Copilot Chat (`copilotChat`)
292
+
293
+ **Context provided to Haiku**:
294
+ - Last 20 user messages from `prompt_executions`
295
+ - Top 10 patterns from `prompt_patterns`
296
+ - Full conversation history (up to 10 prior messages)
297
+
298
+ **System prompt** instructs the copilot to help with:
299
+ - Finding past prompts ("what did I ask about auth last week?")
300
+ - Improving prompts ("how can I make this clearer?")
301
+ - Suggesting approaches ("best way to ask Claude to refactor X?")
302
+ - Pattern insights ("what kinds of prompts do I use most?")
303
+
304
+ **Cost awareness**:
305
+ - Haiku model (much cheaper than Opus/Sonnet)
306
+ - Max 500 tokens per response
307
+ - Conversation history capped at 10 messages
308
+
309
+ ### Verification Results
310
+ - Copilot suggest endpoint returns structured JSON with quality assessment
311
+ - Copilot chat endpoint returns conversational replies with prompt history context
312
+ - Both gracefully handle missing API key
313
+
314
+ ---
315
+
316
+ ## Phase 4: Prompt Lifecycle + Sidebar Redesign + UI Integration <a id="phase-4"></a>
317
+
318
+ ### Goal
319
+ Add lifecycle management, integrate all Phase 1-3 features into the UI, connect session manager with prompt library.
320
+
321
+ ### Lifecycle Status
322
+
323
+ **States**: `draft` → `tested` → `proven` → `template` → `archived`
324
+
325
+ - **draft** — New or untested prompt (default)
326
+ - **tested** — Has been used in at least one session
327
+ - **proven** — Consistently produces good results
328
+ - **template** — Promoted to reusable template with variables
329
+ - **archived** — No longer actively used
330
+
331
+ **DB**: `prompts.lifecycle_status` column (TEXT, default 'draft')
332
+
333
+ **API**: `listPrompts` supports `?lifecycle_status=` filter. `updatePrompt` accepts `lifecycle_status` field.
334
+
335
+ ### UI Components (prompts.html)
336
+
337
+ #### Sidebar Enhancements
338
+ - **Lifecycle filter dropdown** — filter prompt list by lifecycle status
339
+ - **Autocomplete in search** — typing in search bar triggers fuzzy autocomplete dropdown with results from harvested history + library
340
+ - **Lifecycle badges** — colored badges next to each prompt in the sidebar list
341
+
342
+ #### Topbar Buttons
343
+ - **Patterns** — opens patterns view showing detected reusable patterns with frequency
344
+ - **Harvest** — opens modal to preview and run session harvesting
345
+ - **Copilot** — toggles the copilot panel
346
+
347
+ #### Copilot Panel (right side, 4 tabs)
348
+ 1. **Similar** — shows similar past prompts for the currently open prompt
349
+ 2. **Copilot** — chat interface for Q&A about prompt history
350
+ 3. **Sessions** — shows which sessions used the current prompt, with outcome tracking
351
+ 4. **Frequent** — multi-session questions (prompts used across 2+ sessions)
352
+
353
+ #### Copilot Suggestion Bar
354
+ - Appears above the editor when auto-suggestion fires
355
+ - Shows quality badge (good/needs_work/vague)
356
+ - "Apply" button replaces editor content with improved version
357
+ - "Dismiss" button hides the suggestion
358
+
359
+ #### Harvest Modal
360
+ - Shows preview stats: total sessions, size, date range, projects
361
+ - Run buttons: "Scan All" or "Incremental Only"
362
+ - Progress bar during harvest
363
+ - Results summary after completion
364
+
365
+ #### Patterns View
366
+ - Lists detected patterns sorted by frequency
367
+ - Each pattern shows: normalized text, frequency, example, session count, project list
368
+ - "Re-detect" button to refresh patterns
369
+
370
+ #### Lifecycle Selector
371
+ - Dropdown in the prompt meta bar (next to context type, folder)
372
+ - Updates immediately via API on change
373
+
374
+ ### UI Components (index.html)
375
+
376
+ #### Queue Panel Autocomplete
377
+ - Inline textarea in queue builder gets autocomplete from harvested prompts
378
+ - Arrow key navigation, Enter to select
379
+ - Functions: `qpAutocompleteInput()`, `qpRenderAc()`, `qpSelectAc()`, `qpHideAc()`
380
+
381
+ #### Session Review Integration
382
+ - **"Save to Library" button** — saves the first user message from a session as a new prompt in the library
383
+ - **"Linked Prompts" button** — shows all harvested messages and any library prompts linked to the session
384
+ - Both appear in `renderReviewActions()` for every reviewed session
385
+
386
+ ### Verification Results (Browser Tests)
387
+ - Zero JS errors on page load
388
+ - All UI elements present: search autocomplete, lifecycle filter, copilot panel (4 tabs), harvest modal, patterns view
389
+ - Save to Library: successfully creates prompt from session data (tested with prompt #114)
390
+ - Linked Prompts: correctly displays 27 harvested messages for test session
391
+ - Autocomplete: returns 8 results for "test" query
392
+
393
+ ---
394
+
395
+ ## Data Model <a id="data-model"></a>
396
+
397
+ ```
398
+ ┌─────────────┐ ┌──────────────────┐ ┌─────────────────┐
399
+ │ prompts │ │ prompt_usage │ │ sessions │
400
+ │ (library) │◄──────│ (explicit │──────►│ (JSONL files) │
401
+ │ │ 1:N │ sends) │ N:1 │ │
402
+ │ + lifecycle │ └──────────────────┘ │ │
403
+ │ _status │ │ │
404
+ └──────┬───────┘ ┌──────────────────┐ │ │
405
+ │ │ prompt_executions│ │ │
406
+ │ │ (harvested msgs) │◄──────│ │
407
+ │ │ + outcome │ └─────────────────┘
408
+ │ │ + image_refs │
409
+ │ └────────┬─────────┘
410
+ │ │
411
+ │ ┌────────▼─────────┐
412
+ │ │ prompt_patterns │
413
+ │ │ (detected │
414
+ │ │ reusable │
415
+ │ │ patterns) │
416
+ │ └──────────────────┘
417
+
418
+
419
+ ┌──────────────┐ ┌──────────────────┐
420
+ │ images │ │ harvest_state │
421
+ │ (deduped │ │ (singleton │
422
+ │ via MD5) │ │ watermark) │
423
+ └──────────────┘ └──────────────────┘
424
+ ```
425
+
426
+ ---
427
+
428
+ ## API Reference <a id="api-reference"></a>
429
+
430
+ ### Harvest APIs
431
+
432
+ | Method | Endpoint | Description |
433
+ |--------|----------|-------------|
434
+ | GET | `/api/harvest/preview` | Stats preview (total sessions, size, projects, last scan) |
435
+ | POST | `/api/harvest` | Run harvest. Body: `{scope: "all"|"incremental", maxDays?, projectFilter?}` |
436
+
437
+ ### Autocomplete & Search APIs
438
+
439
+ | Method | Endpoint | Description |
440
+ |--------|----------|-------------|
441
+ | GET | `/api/autocomplete?q=<query>` | Fuzzy autocomplete (min 3 chars). Returns `{results: [{text, type, ...}]}` |
442
+ | GET | `/api/similar?text=<text>` | Find similar prompts (min 20 chars). Returns `{results: [...]}` |
443
+
444
+ ### Pattern APIs
445
+
446
+ | Method | Endpoint | Description |
447
+ |--------|----------|-------------|
448
+ | GET | `/api/patterns` | List detected patterns (top 50 by frequency) |
449
+ | POST | `/api/patterns/detect` | Re-run pattern detection |
450
+
451
+ ### Copilot APIs
452
+
453
+ | Method | Endpoint | Description |
454
+ |--------|----------|-------------|
455
+ | POST | `/api/copilot/suggest` | Auto-suggestion. Body: `{text, context?}`. Returns `{suggestion, improved, quality}` |
456
+ | POST | `/api/copilot/chat` | Chat. Body: `{messages: [{role, content}]}`. Returns `{reply, error?}` |
457
+
458
+ ### Prompt Execution APIs
459
+
460
+ | Method | Endpoint | Description |
461
+ |--------|----------|-------------|
462
+ | GET | `/api/prompt-executions?limit=&offset=` | List harvested executions |
463
+ | GET | `/api/prompt-executions/session/<id>` | Get all messages for a session. Returns `{executions, sentPrompts}` |
464
+ | POST | `/api/prompt-executions/<id>/outcome` | Set outcome. Body: `{outcome, notes?}` |
465
+
466
+ ### Prompt-Session Mapping APIs
467
+
468
+ | Method | Endpoint | Description |
469
+ |--------|----------|-------------|
470
+ | GET | `/api/prompts/<id>/sessions` | Get sessions where this prompt was used |
471
+ | GET | `/api/frequent-questions?limit=20` | Multi-session questions (prompts in 2+ sessions) |
472
+
473
+ ### Modified Existing APIs
474
+
475
+ | Endpoint | Change |
476
+ |----------|--------|
477
+ | GET `/api/prompts` | Added `?lifecycle_status=` filter param |
478
+ | PUT `/api/prompts/<id>` | Added `lifecycle_status` field in body |
479
+
480
+ ---
481
+
482
+ ## UI Components <a id="ui-components"></a>
483
+
484
+ ### prompts.html — New Functions (28 total)
485
+
486
+ | Function | Phase | Purpose |
487
+ |----------|-------|---------|
488
+ | `fetchAutocomplete(q)` | 2 | Fetch autocomplete results from API |
489
+ | `renderAutocomplete(items)` | 2 | Render dropdown under search input |
490
+ | `selectAutocomplete(idx)` | 2 | Select an autocomplete item |
491
+ | `hideAutocomplete()` | 2 | Close autocomplete dropdown |
492
+ | `openHarvestModal()` | 1 | Open harvest preview modal |
493
+ | `closeHarvestModal()` | 1 | Close harvest modal |
494
+ | `runHarvest(scope)` | 1 | Execute harvest and show progress |
495
+ | `toggleCopilotPanel()` | 3 | Show/hide copilot panel |
496
+ | `switchCopilotTab(tab)` | 3 | Switch between Similar/Copilot/Sessions/Frequent |
497
+ | `loadSimilarPrompts()` | 3 | Load similar prompts for current prompt |
498
+ | `loadPromptSessions()` | 3 | Load sessions linked to current prompt |
499
+ | `setOutcomeForSession(sid, outcome)` | 1 | Set outcome on a harvested execution |
500
+ | `sendCopilotMsg()` | 3 | Send message in copilot chat |
501
+ | `loadFrequentQuestions()` | 3 | Load multi-session questions |
502
+ | `useFrequentQuestion(el)` | 3 | Insert frequent question into editor |
503
+ | `triggerCopilotSuggestion()` | 3 | Start 3s debounce for auto-suggestion |
504
+ | `showCopilotSuggestion(data)` | 3 | Display suggestion bar above editor |
505
+ | `applyCopilotSuggestion()` | 3 | Apply improved prompt to editor |
506
+ | `dismissCopilotSuggestion()` | 3 | Dismiss suggestion bar |
507
+ | `loadPatterns()` | 2 | Load and render patterns view |
508
+ | `detectPatterns()` | 2 | Trigger pattern re-detection |
509
+ | `onQueueInputChange()` | 2 | Autocomplete for queue builder input |
510
+ | `renderQueueAc(items)` | 2 | Render queue autocomplete dropdown |
511
+ | `selectQueueAc(idx)` | 2 | Select queue autocomplete item |
512
+ | `onQueueInputKeydown(event)` | 2 | Keyboard navigation for queue autocomplete |
513
+ | `onLifecycleChange()` | 4 | Update prompt lifecycle status |
514
+ | `onSearchInput()` | 2 | Replaced original — now includes autocomplete |
515
+ | `onSearchKeydown()` | 2 | Replaced original — keyboard nav for autocomplete |
516
+
517
+ ### index.html — New Functions (6 total)
518
+
519
+ | Function | Phase | Purpose |
520
+ |----------|-------|---------|
521
+ | `saveSessionToLibrary(sessionId)` | 4 | Save first session message to prompt library |
522
+ | `viewLinkedPrompts(sessionId)` | 4 | Show linked prompts/messages for session |
523
+ | `qpAutocompleteInput()` | 2 | Autocomplete for queue panel textarea |
524
+ | `qpRenderAc(items)` | 2 | Render queue panel autocomplete |
525
+ | `qpSelectAc(idx)` | 2 | Select queue panel autocomplete item |
526
+ | `qpHideAc()` | 2 | Hide queue panel autocomplete |
527
+
528
+ ---
529
+
530
+ ## Configuration & Dependencies <a id="configuration"></a>
531
+
532
+ ### Environment Variables
533
+
534
+ | Variable | Default | Purpose |
535
+ |----------|---------|---------|
536
+ | `CTM_DATA_DIR` | `~/.claude-task-manager/` | Database, images, backups directory |
537
+ | `ANTHROPIC_API_KEY` | (none) | Required for Copilot AI features (Phase 3) |
538
+ | `ANTHROPIC_BASE_URL` | `https://api.anthropic.com` | API base URL (for proxy setups) |
539
+ | `ANTHROPIC_CUSTOM_HEADERS` | (none) | Comma-separated `key:value` pairs for custom headers |
540
+
541
+ ### Dependencies
542
+
543
+ - `better-sqlite3` — SQLite with WAL mode (existing)
544
+ - `crypto` — MD5 hashing for image dedup (Node.js built-in)
545
+ - `fetch` — Anthropic API calls for Copilot (Node.js built-in)
546
+
547
+ ### Session Files Location
548
+
549
+ Harvester scans: `~/.claude/projects/*/` for `*.jsonl` files (via `session-utils.js`)
550
+
551
+ ---
552
+
553
+ ## Known Limitations & Future Work <a id="limitations"></a>
554
+
555
+ ### Current Limitations
556
+
557
+ 1. **Copilot requires API key** — Phase 3 AI features (suggest/chat) need `ANTHROPIC_API_KEY`. Without it, UI gracefully degrades (hidden suggestion bar, error message in chat).
558
+
559
+ 2. **Autocomplete index size** — Limited to last 5,000 messages to keep memory bounded. Very active users may not see older prompts in autocomplete (they're still in DB, just not indexed).
560
+
561
+ 3. **Pattern detection is batch** — Runs on-demand via "Re-detect" button, not continuously. Patterns may be slightly stale.
562
+
563
+ 4. **Similar prompts API param** — Uses `?text=` parameter, not `?q=` (which autocomplete uses). This is intentional (different semantics) but worth noting for API consumers.
564
+
565
+ 5. **Linked Prompts display** — Currently uses `alert()` dialog in index.html. A modal or panel would be better UX.
566
+
567
+ ### Potential Future Work
568
+
569
+ 1. **Prompt threading** — Structured thread mode for iterative prompts (spec → discussion → follow-ups). The infrastructure exists (parent_id, children) but no dedicated thread UI.
570
+
571
+ 2. **Automatic lifecycle promotion** — Auto-move prompts from draft → tested → proven based on outcome tracking data.
572
+
573
+ 3. **Cross-project prompt sharing** — Share proven prompts/templates across projects with metadata.
574
+
575
+ 4. **Embedding-based similarity** — Replace word-overlap matching with embedding vectors for semantic similarity.
576
+
577
+ 5. **Streaming copilot responses** — Currently waits for full response. SSE streaming would improve chat UX.
578
+
579
+ 6. **Scheduled harvesting** — Background cron-style harvest instead of manual trigger.
580
+
581
+ ---
582
+
583
+ ## Implementation Checklist
584
+
585
+ ### Phase 1: DB Schema + Harvester + Prompt-Session Mapping
586
+ - [x] `prompt_executions` table with indexes
587
+ - [x] `prompt_patterns` table with unique constraint
588
+ - [x] `harvest_state` singleton table
589
+ - [x] `lifecycle_status` column on `prompts` table
590
+ - [x] Session JSONL parser (user messages + assistant tool uses)
591
+ - [x] Image dedup via MD5 hash
592
+ - [x] Incremental harvest (modified-since filtering)
593
+ - [x] Harvest preview (stats without scanning)
594
+ - [x] Bidirectional prompt-session mapping
595
+ - [x] Outcome tracking (set/get)
596
+ - [x] 6 API endpoints: harvest/preview, harvest, executions, session executions, outcome, prompt sessions
597
+
598
+ ### Phase 2: Local Autocomplete + Similar Prompts + Pattern Cache
599
+ - [x] In-memory autocomplete index (3 source types, 60s cache)
600
+ - [x] Fuzzy search with scoring (prefix > word-in-text > word-in-fullText)
601
+ - [x] Similar prompts (40% word match threshold, dedup)
602
+ - [x] Pattern detection (normalize → group → count → persist)
603
+ - [x] Multi-session question surfacing (exact + normalized matching)
604
+ - [x] Autocomplete UI in prompts.html search bar
605
+ - [x] Autocomplete UI in prompts.html queue builder
606
+ - [x] Autocomplete UI in index.html queue panel
607
+ - [x] Patterns view with detect/refresh
608
+ - [x] 4 API endpoints: autocomplete, similar, patterns, patterns/detect, frequent-questions
609
+
610
+ ### Phase 3: Prompt Copilot Chat Sidekick
611
+ - [x] Copilot suggest (Haiku model, structured JSON response)
612
+ - [x] Copilot chat (conversation history, prompt context)
613
+ - [x] 3-second debounce + 80 char gate (client-side)
614
+ - [x] Cost-aware design (Haiku model, capped tokens)
615
+ - [x] Graceful degradation without API key
616
+ - [x] Copilot panel with 4 tabs (Similar/Copilot/Sessions/Frequent)
617
+ - [x] Auto-suggestion bar above editor
618
+ - [x] Apply/dismiss suggestion actions
619
+ - [x] 2 API endpoints: copilot/suggest, copilot/chat
620
+
621
+ ### Phase 4: Prompt Lifecycle + Sidebar Redesign + UI Integration
622
+ - [x] Lifecycle status management (draft/tested/proven/template/archived)
623
+ - [x] Lifecycle filter in sidebar
624
+ - [x] Lifecycle badges on prompt list items
625
+ - [x] Lifecycle selector in prompt meta bar
626
+ - [x] Topbar buttons (Patterns, Harvest, Copilot)
627
+ - [x] Harvest modal with preview + run + progress
628
+ - [x] Save to Library (index.html → session review)
629
+ - [x] Linked Prompts (index.html → session review)
630
+ - [x] `listPrompts` lifecycle_status filter
631
+ - [x] `updatePrompt` lifecycle_status field