@tekmidian/pai 0.3.1 → 0.4.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 (61) hide show
  1. package/dist/cli/index.mjs +352 -33
  2. package/dist/cli/index.mjs.map +1 -1
  3. package/dist/hooks/capture-all-events.mjs +238 -0
  4. package/dist/hooks/capture-all-events.mjs.map +7 -0
  5. package/dist/hooks/capture-session-summary.mjs +198 -0
  6. package/dist/hooks/capture-session-summary.mjs.map +7 -0
  7. package/dist/hooks/capture-tool-output.mjs +105 -0
  8. package/dist/hooks/capture-tool-output.mjs.map +7 -0
  9. package/dist/hooks/cleanup-session-files.mjs +129 -0
  10. package/dist/hooks/cleanup-session-files.mjs.map +7 -0
  11. package/dist/hooks/context-compression-hook.mjs +283 -0
  12. package/dist/hooks/context-compression-hook.mjs.map +7 -0
  13. package/dist/hooks/initialize-session.mjs +206 -0
  14. package/dist/hooks/initialize-session.mjs.map +7 -0
  15. package/dist/hooks/load-core-context.mjs +110 -0
  16. package/dist/hooks/load-core-context.mjs.map +7 -0
  17. package/dist/hooks/load-project-context.mjs +548 -0
  18. package/dist/hooks/load-project-context.mjs.map +7 -0
  19. package/dist/hooks/security-validator.mjs +159 -0
  20. package/dist/hooks/security-validator.mjs.map +7 -0
  21. package/dist/hooks/stop-hook.mjs +625 -0
  22. package/dist/hooks/stop-hook.mjs.map +7 -0
  23. package/dist/hooks/subagent-stop-hook.mjs +152 -0
  24. package/dist/hooks/subagent-stop-hook.mjs.map +7 -0
  25. package/dist/hooks/sync-todo-to-md.mjs +322 -0
  26. package/dist/hooks/sync-todo-to-md.mjs.map +7 -0
  27. package/dist/hooks/update-tab-on-action.mjs +90 -0
  28. package/dist/hooks/update-tab-on-action.mjs.map +7 -0
  29. package/dist/hooks/update-tab-titles.mjs +55 -0
  30. package/dist/hooks/update-tab-titles.mjs.map +7 -0
  31. package/package.json +4 -2
  32. package/scripts/build-hooks.mjs +51 -0
  33. package/src/hooks/pre-compact.sh +4 -0
  34. package/src/hooks/session-stop.sh +4 -0
  35. package/src/hooks/ts/capture-all-events.ts +179 -0
  36. package/src/hooks/ts/lib/detect-environment.ts +53 -0
  37. package/src/hooks/ts/lib/metadata-extraction.ts +144 -0
  38. package/src/hooks/ts/lib/pai-paths.ts +124 -0
  39. package/src/hooks/ts/lib/project-utils.ts +914 -0
  40. package/src/hooks/ts/post-tool-use/capture-tool-output.ts +78 -0
  41. package/src/hooks/ts/post-tool-use/sync-todo-to-md.ts +230 -0
  42. package/src/hooks/ts/post-tool-use/update-tab-on-action.ts +145 -0
  43. package/src/hooks/ts/pre-compact/context-compression-hook.ts +155 -0
  44. package/src/hooks/ts/pre-tool-use/security-validator.ts +258 -0
  45. package/src/hooks/ts/session-end/capture-session-summary.ts +185 -0
  46. package/src/hooks/ts/session-start/initialize-session.ts +155 -0
  47. package/src/hooks/ts/session-start/load-core-context.ts +104 -0
  48. package/src/hooks/ts/session-start/load-project-context.ts +394 -0
  49. package/src/hooks/ts/stop/stop-hook.ts +407 -0
  50. package/src/hooks/ts/subagent-stop/subagent-stop-hook.ts +212 -0
  51. package/src/hooks/ts/user-prompt/cleanup-session-files.ts +45 -0
  52. package/src/hooks/ts/user-prompt/update-tab-titles.ts +88 -0
  53. package/tab-color-command.sh +24 -0
  54. package/templates/ai-steering-rules.template.md +58 -0
  55. package/templates/pai-skill.template.md +24 -0
  56. package/templates/skills/createskill-skill.template.md +78 -0
  57. package/templates/skills/history-system.template.md +371 -0
  58. package/templates/skills/hook-system.template.md +913 -0
  59. package/templates/skills/sessions-skill.template.md +102 -0
  60. package/templates/skills/skill-system.template.md +214 -0
  61. package/templates/skills/terminal-tabs.template.md +120 -0
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Tab Title Update Hook
4
+ * Updates tab title based on user prompt
5
+ *
6
+ * Note: All context loading handled by PAI skill system (core identity in skill description, full context in SKILL.md)
7
+ */
8
+
9
+ import { execSync } from 'child_process';
10
+
11
+ interface HookInput {
12
+ session_id: string;
13
+ prompt: string;
14
+ transcript_path: string;
15
+ hook_event_name: string;
16
+ }
17
+
18
+ /**
19
+ * Read stdin with timeout
20
+ */
21
+ async function readStdinWithTimeout(timeout: number = 5000): Promise<string> {
22
+ return new Promise((resolve, reject) => {
23
+ let data = '';
24
+ const timer = setTimeout(() => {
25
+ reject(new Error('Timeout reading from stdin'));
26
+ }, timeout);
27
+
28
+ process.stdin.on('data', (chunk) => {
29
+ data += chunk.toString();
30
+ });
31
+
32
+ process.stdin.on('end', () => {
33
+ clearTimeout(timer);
34
+ resolve(data);
35
+ });
36
+
37
+ process.stdin.on('error', (err) => {
38
+ clearTimeout(timer);
39
+ reject(err);
40
+ });
41
+ });
42
+ }
43
+
44
+ async function main() {
45
+ try {
46
+ // Read the hook input from stdin
47
+ const input = await readStdinWithTimeout();
48
+ const data: HookInput = JSON.parse(input);
49
+
50
+ const prompt = data.prompt || '';
51
+
52
+ // UPDATE TAB TITLE
53
+ // Generate quick fallback tab title
54
+ let tabTitle = 'Processing request...';
55
+ if (prompt) {
56
+ const words = prompt.replace(/[^\w\s]/g, ' ').trim().split(/\s+/)
57
+ .filter(w => w.length > 2 && !['the', 'and', 'but', 'for', 'are', 'with', 'you', 'can'].includes(w.toLowerCase()))
58
+ .slice(0, 3);
59
+
60
+ if (words.length > 0) {
61
+ tabTitle = words[0].charAt(0).toUpperCase() + words[0].slice(1).toLowerCase();
62
+ if (words.length > 1) {
63
+ tabTitle += ' ' + words.slice(1).map(w => w.toLowerCase()).join(' ');
64
+ }
65
+ tabTitle += '...';
66
+ }
67
+ }
68
+
69
+ // Set initial tab title with recycle emoji
70
+ try {
71
+ const titleWithEmoji = '♻️ ' + tabTitle;
72
+ const escapedTitle = titleWithEmoji.replace(/'/g, "'\\''");
73
+ execSync(`printf '\\033]0;${escapedTitle}\\007' >&2`);
74
+ execSync(`printf '\\033]2;${escapedTitle}\\007' >&2`);
75
+ execSync(`printf '\\033]30;${escapedTitle}\\007' >&2`);
76
+ } catch (e) {
77
+ // Silently fail
78
+ }
79
+
80
+ process.exit(0);
81
+ } catch (error) {
82
+ // Silently fail to not interrupt Claude's flow
83
+ console.error('Tab title update error:', error);
84
+ process.exit(0);
85
+ }
86
+ }
87
+
88
+ main();
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env bash
2
+ # PAI Tab Color State Manager
3
+ # Sets iTerm2 tab background color based on Claude Code session state.
4
+ # Silently exits on non-iTerm2 terminals.
5
+ #
6
+ # Usage: tab-color-command.sh <state>
7
+ # States: working, completed, awaiting, error, active, reset
8
+
9
+ [[ -z "$ITERM_SESSION_ID" ]] && exit 0
10
+
11
+ set_color() {
12
+ printf '\033]6;1;bg;red;brightness;%d\a' "$1"
13
+ printf '\033]6;1;bg;green;brightness;%d\a' "$2"
14
+ printf '\033]6;1;bg;blue;brightness;%d\a' "$3"
15
+ }
16
+
17
+ case "${1:-reset}" in
18
+ working|processing) set_color 255 158 100 ;; # Orange
19
+ completed|done) set_color 158 206 106 ;; # Green
20
+ awaiting|input) set_color 125 207 255 ;; # Cyan/Teal
21
+ error|failed) set_color 247 118 142 ;; # Red
22
+ active) set_color 122 162 247 ;; # Blue
23
+ reset|*) printf '\033]6;1;bg;*;default\a' ;;
24
+ esac
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: AI Steering Rules
3
+ description: Universal behavioral rules for AI assistants. Loaded at startup to enforce quality standards.
4
+ ---
5
+
6
+ <!-- Generated by PAI Setup -->
7
+
8
+ # AI Steering Rules
9
+
10
+ These rules apply to ALL responses, ALL tasks, ALL contexts. They are non-negotiable.
11
+
12
+ ## Surgical Fixes Only
13
+
14
+ - Make every change as simple as possible
15
+ - Impact minimal code — don't refactor unrelated areas
16
+ - The best solution is often the simplest one
17
+
18
+ ## Never Assert Without Verification
19
+
20
+ - Don't claim something works without proving it
21
+ - Run tests, check logs, demonstrate correctness
22
+ - "I believe this should work" is not verification
23
+
24
+ ## One Change When Debugging
25
+
26
+ - Change ONE thing at a time when debugging
27
+ - Verify after each change before moving on
28
+ - If you change three things and it works, you don't know which fixed it
29
+
30
+ ## Read Before Modifying
31
+
32
+ - Always read a file before editing it
33
+ - Understand existing patterns before suggesting changes
34
+ - Never propose changes to code you haven't seen
35
+
36
+ ## Find Root Causes
37
+
38
+ - No temporary fixes, no workarounds, no "good enough for now"
39
+ - If a fix feels hacky, stop and find the elegant solution
40
+ - Treat symptoms only as diagnostic clues, not as things to patch
41
+
42
+ ## Prove It Works
43
+
44
+ - For bug fixes: show the error before, show it fixed after
45
+ - For features: demonstrate end-to-end functionality
46
+ - For refactors: prove behavior is unchanged
47
+
48
+ ## Don't Over-Engineer
49
+
50
+ - Only make changes that are directly requested or clearly necessary
51
+ - Don't add features, refactor code, or make "improvements" beyond what was asked
52
+ - Three similar lines of code is better than a premature abstraction
53
+
54
+ ## Fail Honestly
55
+
56
+ - Say "I don't know" when you don't know
57
+ - Mark unverified claims explicitly
58
+ - Fabricating an answer is worse than admitting uncertainty
@@ -374,6 +374,30 @@ Bulk/repetitive work consumes context. Delegate it to conserve your main convers
374
374
 
375
375
  ---
376
376
 
377
+ ## TIME BUDGET AWARENESS (Always Active)
378
+
379
+ **Estimate effort tier BEFORE starting work, then stay within budget.**
380
+
381
+ | Tier | Budget | When |
382
+ |------|--------|------|
383
+ | **Quick** | < 2 min | Simple lookups, one-line fixes, direct answers |
384
+ | **Standard** | < 5 min | Single-file changes, focused research, one feature |
385
+ | **Extended** | < 15 min | Multi-file changes, moderate research, debugging |
386
+ | **Deep** | < 45 min | Architecture work, complex debugging, large features |
387
+ | **Comprehensive** | < 120 min | Major refactors, full implementations, deep research |
388
+
389
+ ### Rules
390
+
391
+ 1. **Estimate at start:** Before beginning work, classify the effort tier and announce it: "This is a Standard task (~5 min)."
392
+ 2. **Check at midpoint:** If you've used > 50% of the budget and aren't > 50% done, reassess.
393
+ 3. **Compress if over budget:** If elapsed > 150% of budget, simplify the approach:
394
+ - Drop nice-to-haves, focus on core requirement
395
+ - Use existing patterns instead of novel solutions
396
+ - Deliver partial result with clear "what's left" summary
397
+ 4. **Never silently overrun:** If a task needs more time than budgeted, say so: "This is taking longer than expected. The Quick fix became Extended because [reason]. Continuing."
398
+
399
+ ---
400
+
377
401
  ## STACK PREFERENCES (Always Active)
378
402
 
379
403
  - **TypeScript > Python** — Use TypeScript unless explicitly told otherwise
@@ -0,0 +1,78 @@
1
+ <!-- Generated by PAI Setup -->
2
+ ---
3
+ name: Createskill
4
+ description: MANDATORY skill creation framework for ALL skill creation requests. USE WHEN user wants to create, validate, update, or canonicalize a skill, OR user mentions skill creation, skill development, new skill, build skill, OR user references skill compliance, skill structure, or skill architecture.
5
+ ---
6
+
7
+ # Createskill
8
+
9
+ MANDATORY skill creation framework for ALL skill creation requests.
10
+
11
+ ## Authoritative Source
12
+
13
+ **Before creating ANY skill, READ:** `${PAI_DIR}/skills/CORE/SkillSystem.md`
14
+
15
+ **Canonical example to follow:** Look at existing skills in `~/.claude/skills/` for structure reference.
16
+
17
+ ## TitleCase Naming Convention
18
+
19
+ **All naming must use TitleCase (PascalCase).**
20
+
21
+ | Component | Format | Example |
22
+ |-----------|--------|---------|
23
+ | Skill directory | TitleCase | `Blogging`, `Daemon`, `CreateSkill` |
24
+ | Workflow files | TitleCase.md | `Create.md`, `UpdateDaemonInfo.md` |
25
+ | Reference docs | TitleCase.md | `ProsodyGuide.md`, `ApiReference.md` |
26
+ | Tool files | TitleCase.ts | `ManageServer.ts` |
27
+ | Help files | TitleCase.help.md | `ManageServer.help.md` |
28
+
29
+ **Wrong (NEVER use):**
30
+ - `createskill`, `create-skill`, `CREATE_SKILL`
31
+ - `create.md`, `update-info.md`, `SYNC_REPO.md`
32
+
33
+ ## Workflow Routing
34
+
35
+ **When executing a workflow, output this notification directly:**
36
+
37
+ ```
38
+ Running the **WorkflowName** workflow from the **Createskill** skill...
39
+ ```
40
+
41
+ | Workflow | Trigger | File |
42
+ |----------|---------|------|
43
+ | **CreateSkill** | "create a new skill" | `workflows/CreateSkill.md` |
44
+ | **ValidateSkill** | "validate skill", "check skill" | `workflows/ValidateSkill.md` |
45
+ | **UpdateSkill** | "update skill", "add workflow" | `workflows/UpdateSkill.md` |
46
+ | **CanonicalizeSkill** | "canonicalize", "fix skill structure" | `workflows/CanonicalizeSkill.md` |
47
+
48
+ ## Examples
49
+
50
+ **Example 1: Create a new skill from scratch**
51
+ ```
52
+ User: "Create a skill for managing my recipes"
53
+ → Invokes CreateSkill workflow
54
+ → Reads SkillSystem.md for structure requirements
55
+ → Creates skill directory with TitleCase naming
56
+ → Creates SKILL.md, workflows/, tools/
57
+ → Generates USE WHEN triggers based on intent
58
+ ```
59
+
60
+ **Example 2: Fix an existing skill that's not routing properly**
61
+ ```
62
+ User: "The research skill isn't triggering - validate it"
63
+ → Invokes ValidateSkill workflow
64
+ → Checks SKILL.md against canonical format
65
+ → Verifies TitleCase naming throughout
66
+ → Verifies USE WHEN triggers are intent-based
67
+ → Reports compliance issues with fixes
68
+ ```
69
+
70
+ **Example 3: Canonicalize a skill with old naming**
71
+ ```
72
+ User: "Canonicalize the daemon skill"
73
+ → Invokes CanonicalizeSkill workflow
74
+ → Renames workflow files to TitleCase
75
+ → Updates routing table to match
76
+ → Ensures Examples section exists
77
+ → Verifies all checklist items
78
+ ```
@@ -0,0 +1,371 @@
1
+ <!-- Generated by PAI Setup -->
2
+ # Universal Output Capture System (UOCS) - History System Documentation
3
+
4
+ **Location:** `${PAI_DIR}/History/`
5
+ **Purpose:** Automated documentation of ALL work performed by PAI and specialized agents
6
+ **Status:** Configure during `pai setup`
7
+
8
+ ---
9
+
10
+ ## Overview
11
+
12
+ The Universal Output Capture System (UOCS) is PAI's automatic memory - capturing every feature, bug fix, decision, learning, research, and session through hooks with **zero manual effort**.
13
+
14
+ **Core Principle:** Work normally, documentation handles itself.
15
+
16
+ ---
17
+
18
+ ## Quick Reference
19
+
20
+ This file is the **complete reference** for the history system. All specifications, conventions, and usage patterns are documented below.
21
+
22
+ ---
23
+
24
+ ## Directory Structure
25
+
26
+ ```
27
+ ${PAI_DIR}/History/
28
+ ├── Sessions/YYYY-MM/ # Session summaries (SessionEnd hook)
29
+ ├── Learnings/YYYY-MM/ # Problem-solving narratives (Stop hook + manual)
30
+ ├── Research/YYYY-MM/ # Investigation reports (Researcher agents)
31
+ ├── Decisions/YYYY-MM/ # Architectural decisions (Architect agent)
32
+ ├── Execution/
33
+ │ ├── Features/YYYY-MM/ # Feature implementations (Engineer/Designer)
34
+ │ ├── Bugs/YYYY-MM/ # Bug fixes (Engineer)
35
+ │ └── Refactors/YYYY-MM/ # Code improvements (Engineer)
36
+ └── Raw-Outputs/YYYY-MM/ # JSONL logs (PostToolUse hook)
37
+ ```
38
+
39
+ **Quick Decision Guide:**
40
+ - "What happened this session?" → `Sessions/`
41
+ - "What did we learn?" → `Learnings/`
42
+ - "What features were built?" → `Execution/Features/`
43
+ - "What broke and when?" → `Execution/Bugs/`
44
+ - "What was improved?" → `Execution/Refactors/`
45
+ - "Why this approach?" → `Decisions/`
46
+ - "What did we investigate?" → `Research/`
47
+ - "Raw execution logs?" → `Raw-Outputs/`
48
+
49
+ ---
50
+
51
+ ## Project Session Storage
52
+
53
+ **Location:** `${PAI_DIR}/projects/{encoded-path}/`
54
+
55
+ Claude Code stores session transcripts per-project. PAI organizes these with a clean structure:
56
+
57
+ ```
58
+ ${PAI_DIR}/projects/{encoded-path}/
59
+ ├── sessions/ # Session transcripts (auto-organized)
60
+ │ ├── {uuid}.jsonl # Main session transcripts
61
+ │ └── agent-*.jsonl # Subagent transcripts
62
+ ├── Notes/ # Session notes (PAI extension)
63
+ │ └── NNNN_YYYY-MM-DD_desc.md
64
+ └── TODO.md # Project task tracking
65
+ ```
66
+
67
+ **Path Encoding:** Directory paths are encoded by replacing `/` and `.` with `-`
68
+ - `/Users/you/Projects/myapp` → `-Users-you-Projects-myapp`
69
+
70
+ **Session File Lifecycle:**
71
+ 1. **During session:** Claude Code writes `.jsonl` to project root
72
+ 2. **On UserPromptSubmit:** Cleanup hook moves stray files from previous sessions
73
+ 3. **On Stop:** `stop-hook.ts` moves current session files to `sessions/`
74
+ 4. **On SessionStart:** Context loader creates structure and migrates any stragglers
75
+
76
+ **Key Files:**
77
+ - `{uuid}.jsonl` - Full conversation transcript with token usage
78
+ - `agent-*.jsonl` - Subagent (Task tool) transcripts
79
+ - `Notes/*.md` - Human-readable session summaries
80
+ - `TODO.md` - Synced from TodoWrite tool
81
+
82
+ ---
83
+
84
+ ## File Naming Convention
85
+
86
+ **Unified format:**
87
+ ```
88
+ YYYY-MM-DD-HHMMSS_[PROJECT]_[TYPE]_[HIERARCHY]_[DESCRIPTION].md
89
+ ```
90
+
91
+ **Components:**
92
+ - **Timestamp:** `YYYY-MM-DD-HHMMSS` - Enables chronological sorting
93
+ - **Project:** Optional identifier (e.g., `dashboard`, `website`, `PAI`)
94
+ - **Type:** Mandatory classification
95
+ - `FEATURE` - New functionality
96
+ - `BUG` - Bug fix
97
+ - `REFACTOR` - Code improvement
98
+ - `RESEARCH` - Investigation
99
+ - `DECISION` - Architectural decision
100
+ - `LEARNING` - Problem-solving narrative
101
+ - `SESSION` - Session summary
102
+ - **Hierarchy:** Optional task number (e.g., `T1.2.3`)
103
+ - **Description:** Kebab-case, max 60 chars
104
+
105
+ **Examples:**
106
+ ```
107
+ 2025-10-13-140000_dashboard_FEATURE_T1.1_database-schema-setup.md
108
+ 2025-10-13-153000_dashboard_BUG_T1.2_jwt-expiry-validation.md
109
+ 2025-10-13-092000_PAI_DECISION_unified-capture-architecture.md
110
+ 2025-10-13-083000_LEARNING_kitty-remote-control-api.md
111
+ 2025-10-13-180000_SESSION_feature-implementation-day-1.md
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Hook Integration
117
+
118
+ ### 1. PostToolUse Hook
119
+ **Triggers:** Every tool execution (Bash, Edit, Write, Read, Task, etc.)
120
+ **Implementation:** `${PAI_DIR}/Hooks/capture-all-events.ts --event-type PostToolUse`
121
+ **Output:** Daily JSONL logs in `Raw-Outputs/YYYY-MM/YYYY-MM-DD_all-events.jsonl`
122
+ **Purpose:** Raw execution data for forensics and analytics
123
+
124
+ **Key Feature:** Completely generic - captures ENTIRE payload automatically
125
+ - **Future-proof**: New fields added to hooks are automatically captured
126
+ - No code updates needed when Claude Code adds new fields
127
+
128
+ ### 2. Stop Hook
129
+ **Triggers:** Main agent task completion
130
+ **Implementation:** `${PAI_DIR}/Hooks/stop-hook.ts`
131
+ **Output:** Auto-captured files in `Learnings/` or `Sessions/` based on content
132
+ **Purpose:** Lightweight capture of work summaries and learning moments
133
+
134
+ **How it works:**
135
+ 1. Extracts structured response format sections
136
+ 2. Analyzes for learning indicators (problem, solved, discovered, fixed)
137
+ 3. Categorizes as LEARNING (2+ indicators) or WORK (general session)
138
+ 4. Generates appropriate filename and saves to history
139
+
140
+ ### 3. SubagentStop Hook
141
+ **Triggers:** Specialized agent task completion
142
+ **Implementation:** `${PAI_DIR}/Hooks/subagent-stop-hook.ts`
143
+ **Output:** Categorized documents in appropriate directories
144
+ **Purpose:** Organized work documentation by agent type
145
+
146
+ **Categorization Logic:**
147
+ - Architect → `Decisions/` (DECISION)
148
+ - Engineer/Principal-Engineer → `Execution/Features|Bugs|Refactors/`
149
+ - Designer → `Execution/Features/` (FEATURE)
150
+ - Researchers (all types) → `Research/` (RESEARCH)
151
+ - Pentester → `Research/` (RESEARCH)
152
+ - Intern → `Research/` (mixed - defaults to RESEARCH)
153
+
154
+ ### 4. SessionEnd Hook
155
+ **Triggers:** Session exit (when you quit Claude Code)
156
+ **Implementation:** `${PAI_DIR}/Hooks/capture-session-summary.ts`
157
+ **Output:** Session summary in `Sessions/YYYY-MM/`
158
+ **Purpose:** High-level session documentation
159
+
160
+ ### 5. SessionStart Hook
161
+ **Triggers:** Session initialization (when you start Claude Code)
162
+ **Implementation:** `${PAI_DIR}/Hooks/initialize-pai-session.ts`
163
+ **Purpose:** Load core context and prepare session environment
164
+
165
+ ---
166
+
167
+ ## Custom Slash Commands
168
+
169
+ ### /search-history [query]
170
+ **Purpose:** Full-text search across all history
171
+ **Example:** `/search-history authentication bug`
172
+ **Implementation:** Uses ripgrep with context lines
173
+
174
+ ### /show-project-history [project]
175
+ **Purpose:** Chronological timeline for project
176
+ **Example:** `/show-project-history dashboard`
177
+ **Output:** Most recent 30 files for project
178
+
179
+ ### /trace-feature [task-number]
180
+ **Purpose:** Complete implementation history for task
181
+ **Example:** `/trace-feature T1.2`
182
+ **Output:** Features, bugs, refactors related to task
183
+
184
+ ### /bug-timeline [feature]
185
+ **Purpose:** Bug introduction and fix timeline
186
+ **Example:** `/bug-timeline authentication`
187
+ **Output:** Chronological list of related bugs
188
+
189
+ ---
190
+
191
+ ## Metadata Schema
192
+
193
+ Every capture file includes YAML frontmatter:
194
+
195
+ ```yaml
196
+ ---
197
+ # Core classification
198
+ capture_type: FEATURE|BUG|REFACTOR|RESEARCH|DECISION|LEARNING|SESSION
199
+ timestamp: 2025-10-13T14:30:22-07:00
200
+ duration_minutes: 45
201
+
202
+ # Context
203
+ project: dashboard
204
+ executor: main|architect|engineer|designer|researcher
205
+ session_id: uuid
206
+
207
+ # Development tracking (when applicable)
208
+ hierarchy: T1.2.3
209
+ spec_kit_feature: 001-user-authentication
210
+ spec_kit_task: T005
211
+ user_story: US1
212
+ phase: 2
213
+
214
+ # Technical details
215
+ files_changed:
216
+ - path/to/file.ts
217
+ technologies:
218
+ - TypeScript
219
+ - Vitest
220
+
221
+ # Outcomes
222
+ status: completed|blocked|partial
223
+ tests_added: 12
224
+ tests_passing: 12
225
+ coverage_change: +5.2%
226
+
227
+ # Bug tracking (for bugs only)
228
+ bug_severity: critical|high|medium|low
229
+ bug_introduced_by: T1.1
230
+
231
+ # Relationships
232
+ related_to:
233
+ - other-capture-file.md
234
+ depends_on:
235
+ - prerequisite-file.md
236
+
237
+ # Searchability
238
+ tags:
239
+ - authentication
240
+ keywords:
241
+ - user model
242
+ ---
243
+ ```
244
+
245
+ ---
246
+
247
+ ## Common Usage Patterns
248
+
249
+ ### Before Starting Work
250
+
251
+ ```bash
252
+ # Has this been done before?
253
+ /search-history [feature-name]
254
+
255
+ # What decisions were made about this?
256
+ ls ${PAI_DIR}/History/Decisions/*/[project]_*
257
+
258
+ # What did we learn about this domain?
259
+ /search-history [domain-term]
260
+ ```
261
+
262
+ ### During Development
263
+
264
+ **No action required** - work normally, everything captured automatically.
265
+
266
+ ### After Encountering Issues
267
+
268
+ ```bash
269
+ # When did this break?
270
+ /bug-timeline [feature-name]
271
+
272
+ # Complete history of this feature
273
+ /trace-feature T1.2.3
274
+
275
+ # What similar bugs have we fixed?
276
+ /search-history "[bug description]"
277
+ ```
278
+
279
+ ### Periodic Review
280
+
281
+ ```bash
282
+ # What did we accomplish this week?
283
+ ls -lt ${PAI_DIR}/History/Sessions/$(date +%Y-%m)/ | head -7
284
+
285
+ # All decisions made this month
286
+ ls ${PAI_DIR}/History/Decisions/$(date +%Y-%m)/
287
+
288
+ # Learnings from this quarter
289
+ ls ${PAI_DIR}/History/Learnings/$(date +%Y-%m)/
290
+ ```
291
+
292
+ ---
293
+
294
+ ## Advanced Queries
295
+
296
+ ### Find all features for project
297
+ ```bash
298
+ find ${PAI_DIR}/History/Execution/Features -name "*_dashboard_*"
299
+ ```
300
+
301
+ ### Find bugs introduced in specific task
302
+ ```bash
303
+ rg "bug_introduced_by: T1.2" ${PAI_DIR}/History/Execution/Bugs/
304
+ ```
305
+
306
+ ### Find all work from specific date
307
+ ```bash
308
+ find ${PAI_DIR}/History -name "$(date +%Y-%m-%d)-*"
309
+ ```
310
+
311
+ ### Analyze tool usage patterns
312
+ ```bash
313
+ cat ${PAI_DIR}/History/Raw-Outputs/$(date +%Y-%m)/*.jsonl | \
314
+ jq -r '.tool' | sort | uniq -c | sort -rn
315
+ ```
316
+
317
+ ### Extract all architectural decisions
318
+ ```bash
319
+ find ${PAI_DIR}/History/Decisions -name "*.md" | \
320
+ xargs grep -l "Alternatives considered"
321
+ ```
322
+
323
+ ---
324
+
325
+ ## Benefits
326
+
327
+ - **Root Cause Analysis** - "When did we break this?" instantly answerable
328
+ - **Decision Tracking** - Every architectural choice preserved with rationale
329
+ - **Learning Accumulation** - Problem-solving patterns captured and queryable
330
+ - **Process Improvement** - Complete history enables identifying bottlenecks
331
+ - **Knowledge Harvesting** - Past solutions easily found and reused
332
+ - **Zero Overhead** - Completely automated capture
333
+
334
+ ---
335
+
336
+ ## Maintenance
337
+
338
+ ### Automated (No Action Required)
339
+ - Hooks capture all work automatically
340
+ - Files created with proper naming
341
+ - Metadata populated by hooks
342
+ - Categorization handled by hook logic
343
+
344
+ ### Manual (Periodic)
345
+
346
+ **Monthly:**
347
+ - Review directory sizes
348
+ - Archive older months if getting large (>1000 files/month)
349
+ - Validate hook functionality
350
+
351
+ **Quarterly:**
352
+ - Extract common learnings into best practices
353
+ - Analyze bug patterns for process improvements
354
+ - Review categorization accuracy
355
+
356
+ ---
357
+
358
+ ## Routing Triggers
359
+
360
+ **Load this documentation when the user says:**
361
+ - "history system" or "UOCS"
362
+ - "how does capture work" or "automatic documentation"
363
+ - "where are sessions saved" or "history directory"
364
+ - "how to search history" or "find past work"
365
+ - "SubagentStop hook" or "capture hooks"
366
+ - "learning capture" or "session summaries"
367
+ - Questions about file organization in History/
368
+
369
+ ---
370
+
371
+ **This is the memory of your AI infrastructure - it remembers everything so you don't have to.**