oneie 3.6.5 → 3.6.6

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 (94) hide show
  1. package/.claude/commands/one copy.md +565 -0
  2. package/.claude/hooks/README-knowledge-hooks.md +265 -0
  3. package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
  4. package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
  5. package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
  6. package/.claude/hooks/check-filenames.py +40 -0
  7. package/.claude/hooks/clean-post.py +301 -0
  8. package/.claude/hooks/clean-pre.py +308 -0
  9. package/.claude/hooks/done.py +175 -0
  10. package/.claude/hooks/format-hook.sh +75 -0
  11. package/.claude/hooks/hook-logger.sh +59 -0
  12. package/.claude/hooks/knowledge-post.py +251 -0
  13. package/.claude/hooks/knowledge-pre.py +150 -0
  14. package/.claude/hooks/notification-hook.sh +112 -0
  15. package/.claude/hooks/security-hook.sh +157 -0
  16. package/.claude/hooks/tag-all-docs.py +338 -0
  17. package/.claude/hooks/todo.py +298 -0
  18. package/.claude/hooks/validate-ontology-structure.py +455 -0
  19. package/.claude/skills/astro/add-content-collection.md +30 -0
  20. package/.claude/skills/astro/check-build.md +29 -0
  21. package/.claude/skills/astro/create-component.md +29 -0
  22. package/.claude/skills/astro/create-page.md +30 -0
  23. package/.claude/skills/astro/optimize-performance.md +21 -0
  24. package/.claude/skills/convex/check-deployment.md +46 -0
  25. package/.claude/skills/convex/create-mutation.md +405 -0
  26. package/.claude/skills/convex/create-query.md +52 -0
  27. package/.claude/skills/convex/read-schema.md +373 -0
  28. package/.claude/skills/convex/test-function.md +50 -0
  29. package/.claude/skills/deployment/check-deployment-health.md +20 -0
  30. package/.claude/skills/deployment/create-release.md +21 -0
  31. package/.claude/skills/deployment/deploy-cloudflare.md +31 -0
  32. package/.claude/skills/deployment/deploy-convex.md +30 -0
  33. package/.claude/skills/deployment/sync-repositories.md +19 -0
  34. package/.claude/skills/design/check-accessibility.md +21 -0
  35. package/.claude/skills/design/create-component-spec.md +27 -0
  36. package/.claude/skills/design/generate-design-tokens.md +24 -0
  37. package/.claude/skills/design/generate-wireframe.md +30 -0
  38. package/.claude/skills/documentation/create-migration-guide.md +20 -0
  39. package/.claude/skills/documentation/generate-api-docs.md +27 -0
  40. package/.claude/skills/documentation/generate-readme.md +22 -0
  41. package/.claude/skills/documentation/update-knowledge.md +20 -0
  42. package/.claude/skills/integration/connect-external-system.md +21 -0
  43. package/.claude/skills/integration/implement-a2a.md +20 -0
  44. package/.claude/skills/integration/implement-acp.md +20 -0
  45. package/.claude/skills/integration/verify-integration.md +20 -0
  46. package/.claude/skills/ontology/README.md +255 -0
  47. package/.claude/skills/ontology/check-dimension.md +307 -0
  48. package/.claude/skills/ontology/generate-entity-type.md +339 -0
  49. package/.claude/skills/ontology/validate-schema.md +229 -0
  50. package/.claude/skills/ontology/verify-relationships.md +310 -0
  51. package/.claude/skills/problem-solving/analyze-test-failure.md +21 -0
  52. package/.claude/skills/problem-solving/identify-root-cause.md +20 -0
  53. package/.claude/skills/problem-solving/propose-solution.md +29 -0
  54. package/.claude/skills/problem-solving/verify-fix.md +21 -0
  55. package/.claude/skills/sales/generate-demo-script.md +21 -0
  56. package/.claude/skills/sales/qualify-lead.md +30 -0
  57. package/.claude/skills/sales/track-trial.md +20 -0
  58. package/.claude/skills/sales/verify-kyc.md +20 -0
  59. package/.claude/skills/testing/analyze-coverage.md +24 -0
  60. package/.claude/skills/testing/generate-tests.md +24 -0
  61. package/.claude/skills/testing/run-tests.md +27 -0
  62. package/.claude/skills/testing/validate-e2e.md +25 -0
  63. package/.mcp.json +30 -3
  64. package/dist/commands/init.d.ts.map +1 -1
  65. package/dist/commands/init.js +13 -6
  66. package/dist/commands/init.js.map +1 -1
  67. package/dist/utils/launch-claude.d.ts +3 -2
  68. package/dist/utils/launch-claude.d.ts.map +1 -1
  69. package/dist/utils/launch-claude.js +64 -29
  70. package/dist/utils/launch-claude.js.map +1 -1
  71. package/one/.obsidian/workspace.json +22 -22
  72. package/one/events/CREATE-WEBSITE.md +442 -0
  73. package/one/events/CUSTOM-DOMAIN.md +357 -0
  74. package/one/events/DEPLOYMENT copy.md +426 -0
  75. package/one/events/ECOMMERCE-BEFORE-AFTER.md +251 -0
  76. package/one/events/ECOMMERCE-ENHANCEMENTS.md +576 -0
  77. package/one/events/ECOMMERCE-HIGH-CONVERTING-ELEMENTS.md +421 -0
  78. package/one/events/ECOMMERCE-REFACTOR-SUMMARY.md +196 -0
  79. package/one/events/ECOMMERCE-SETUP-SUMMARY.md +396 -0
  80. package/one/events/INSTALLATION_FOLDERS.md +516 -0
  81. package/one/events/INSTALLATION_FOLDERS_FILES.md +205 -0
  82. package/one/events/INSTALLATION_FOLDERS_SUMMARY.md +419 -0
  83. package/one/events/LICENSE.md +89 -0
  84. package/one/events/MCP-CONFIGURATION.md +336 -0
  85. package/one/events/MCP-SETUP-COMPLETE.md +205 -0
  86. package/one/events/NODE-UPGRADE.md +111 -0
  87. package/one/events/PACKAGE-STRUCTURE.md +310 -0
  88. package/one/events/PLAYBOOK-SETUP-SUMMARY.md +331 -0
  89. package/one/events/PROMPT_FIX_FRONTEND_ONLY.md +567 -0
  90. package/one/events/SIMPLE_FIX_FRONTEND_ONLY.md +262 -0
  91. package/one/events/STRIPE-INTEGRATION.md +414 -0
  92. package/one/events/STRIPE-SETUP-GUIDE.md +462 -0
  93. package/one/events/TRANSPARENCY-FIXES.md +275 -0
  94. package/package.json +4 -2
@@ -0,0 +1,265 @@
1
+ # Knowledge Tagging Hooks
2
+
3
+ ## Overview
4
+
5
+ The knowledge tagging hooks automatically tag all created/modified artifacts as **knowledge** in the 6-dimension ontology. This enables:
6
+
7
+ - 📚 Automatic knowledge base building
8
+ - 🏷️ Semantic labeling of all artifacts
9
+ - 🔍 RAG-ready artifact indexing
10
+ - 📊 Knowledge tracking per inference
11
+ - 🧠 Complete audit trail of created knowledge
12
+
13
+ ## How It Works
14
+
15
+ ### Pre-Hook: `knowledge-pre.py`
16
+
17
+ Runs **before** Write/Edit operations to validate and prepare knowledge tagging:
18
+
19
+ 1. ✅ Validates artifact type (code, docs, tests, config, design)
20
+ 2. 🏷️ Prepares labels based on file path and type
21
+ 3. 📋 Displays what will be tagged after creation
22
+ 4. ⚠️ Skips temporary and generated files
23
+
24
+ **Example Output:**
25
+ ```
26
+ 📚 Knowledge Pre-Hook
27
+ Artifact: EntityList.tsx
28
+ Type: code
29
+ Labels: component, frontend, ui, code
30
+ → Will be tagged in knowledge dimension after creation
31
+ ```
32
+
33
+ ### Post-Hook: `knowledge-post.py`
34
+
35
+ Runs **after** Write/Edit operations to create knowledge entries:
36
+
37
+ 1. 📝 Creates knowledge entry with metadata
38
+ 2. 🏷️ Tags with labels (file type, dimension, feature)
39
+ 3. 🔗 Links to current inference context
40
+ 4. 💾 Saves to daily knowledge log (~/.claude/knowledge-log/)
41
+ 5. 🔐 Generates content hash for versioning
42
+
43
+ **Example Output:**
44
+ ```
45
+ ✨ Knowledge Tagged
46
+ Artifact: EntityList.tsx
47
+ Type: code
48
+ Labels: component, frontend, ui, code
49
+ Inference: 22/100
50
+ Hash: a3f9d2c1b4e5f6a7
51
+ → Logged to: knowledge-2025-10-14.jsonl
52
+ ```
53
+
54
+ ## Knowledge Entry Structure
55
+
56
+ Each knowledge entry is saved as JSON:
57
+
58
+ ```json
59
+ {
60
+ "type": "knowledge_item",
61
+ "artifact_type": "code",
62
+ "file_path": "/Users/toc/Server/ONE/web/src/components/EntityList.tsx",
63
+ "file_name": "EntityList.tsx",
64
+ "labels": ["component", "frontend", "ui", "code"],
65
+ "content_hash": "a3f9d2c1b4e5f6a7",
66
+ "created_at": "2025-10-14T02:30:45.123456",
67
+ "inference_number": 22,
68
+ "feature": "Entity Management",
69
+ "organization": "Default Org",
70
+ "created_by_role": "platform_owner",
71
+ "content_preview": "import { useQuery } from 'convex/react'...",
72
+ "metadata": {
73
+ "file_size": 1234,
74
+ "directory": "/Users/toc/Server/ONE/web/src/components",
75
+ "extension": ".tsx"
76
+ }
77
+ }
78
+ ```
79
+
80
+ ## Artifact Types
81
+
82
+ The hooks recognize 5 artifact types:
83
+
84
+ | Type | Extensions | Labels |
85
+ |------|-----------|--------|
86
+ | **code** | .py, .ts, .tsx, .js, .jsx, .astro, .json, .yaml | `code` |
87
+ | **documentation** | .md, .mdx, .txt | `documentation` |
88
+ | **test** | .test.ts, .spec.ts, etc. | `test`, `quality` |
89
+ | **config** | .json, .yaml, .yml, .toml, .ini | `config` |
90
+ | **design** | .fig, .sketch, .svg, .png, .jpg | `design` |
91
+
92
+ ## Smart Labeling
93
+
94
+ Labels are automatically generated based on file path:
95
+
96
+ | Path Pattern | Auto Labels |
97
+ |-------------|-------------|
98
+ | `/web/src/components` | `component`, `frontend`, `ui` |
99
+ | `/web/src/pages` | `page`, `frontend`, `routing` |
100
+ | `/backend/convex/queries` | `query`, `backend`, `database` |
101
+ | `/backend/convex/mutations` | `mutation`, `backend`, `database` |
102
+ | `/backend/convex/services` | `service`, `backend`, `business-logic` |
103
+ | `/one/things` | `documentation`, `ontology`, `things` |
104
+ | `/one/connections` | `documentation`, `ontology`, `connections` |
105
+ | `/one/events` | `documentation`, `ontology`, `events` |
106
+ | `/one/knowledge` | `documentation`, `ontology`, `knowledge` |
107
+ | `/test` | `test`, `quality`, `validation` |
108
+
109
+ ## Knowledge Logs
110
+
111
+ Knowledge entries are saved to `~/.claude/knowledge-log/` as daily JSONL files:
112
+
113
+ ```
114
+ ~/.claude/knowledge-log/
115
+ ├── knowledge-2025-10-14.jsonl
116
+ ├── knowledge-2025-10-13.jsonl
117
+ └── knowledge-2025-10-12.jsonl
118
+ ```
119
+
120
+ Each line is a complete JSON knowledge entry. This format enables:
121
+
122
+ - 📊 Easy aggregation and analysis
123
+ - 🔍 Fast searching with grep/jq
124
+ - 📈 Knowledge growth tracking
125
+ - 🧠 RAG corpus building
126
+
127
+ ## Inference Context Integration
128
+
129
+ The hooks integrate with the inference tracking system (`todo.py`):
130
+
131
+ - 📍 Current inference number (1-100)
132
+ - 🎯 Feature being implemented
133
+ - 🏢 Organization context
134
+ - 👤 Person role (platform_owner, org_owner, etc.)
135
+
136
+ This links every knowledge artifact back to the inference that created it.
137
+
138
+ ## Filtering Rules
139
+
140
+ The hooks **skip** tagging for:
141
+
142
+ - ❌ Temporary files (`/tmp/`, `/.temp/`)
143
+ - ❌ Generated files (`/_generated/`, `/node_modules/`)
144
+ - ❌ Non-recognized artifact types
145
+ - ❌ Non-Write/Edit operations (Read, Bash, etc.)
146
+
147
+ ## Usage Example
148
+
149
+ When you create a new component:
150
+
151
+ ```typescript
152
+ // Write: frontend/src/components/TokenBalance.tsx
153
+ import { useQuery } from 'convex/react';
154
+ export function TokenBalance({ userId }) { ... }
155
+ ```
156
+
157
+ **Pre-Hook Output:**
158
+ ```
159
+ 📚 Knowledge Pre-Hook
160
+ Artifact: TokenBalance.tsx
161
+ Type: code
162
+ Labels: component, frontend, ui, code
163
+ → Will be tagged in knowledge dimension after creation
164
+ ```
165
+
166
+ **Post-Hook Output:**
167
+ ```
168
+ ✨ Knowledge Tagged
169
+ Artifact: TokenBalance.tsx
170
+ Type: code
171
+ Labels: component, frontend, ui, code
172
+ Inference: 22/100
173
+ Hash: b8c3d4e5f6a7b8c9
174
+ → Logged to: knowledge-2025-10-14.jsonl
175
+ ```
176
+
177
+ ## Querying Knowledge Logs
178
+
179
+ Use `jq` to query knowledge logs:
180
+
181
+ ```bash
182
+ # All artifacts created today
183
+ cat ~/.claude/knowledge-log/knowledge-$(date +%Y-%m-%d).jsonl | jq .
184
+
185
+ # All code artifacts
186
+ cat ~/.claude/knowledge-log/*.jsonl | jq 'select(.artifact_type == "code")'
187
+
188
+ # All artifacts for inference 22
189
+ cat ~/.claude/knowledge-log/*.jsonl | jq 'select(.inference_number == 22)'
190
+
191
+ # All frontend components
192
+ cat ~/.claude/knowledge-log/*.jsonl | jq 'select(.labels | contains(["component", "frontend"]))'
193
+
194
+ # Count by artifact type
195
+ cat ~/.claude/knowledge-log/*.jsonl | jq -r '.artifact_type' | sort | uniq -c
196
+ ```
197
+
198
+ ## Integration with 6-Dimension Ontology
199
+
200
+ These hooks implement **Dimension 6: Knowledge** of the ontology:
201
+
202
+ ```
203
+ Organizations → Multi-tenant isolation
204
+ People → Authorization & roles
205
+ Things → Entities (66+ types)
206
+ Connections → Relationships (25+ types)
207
+ Events → Actions (67+ types)
208
+ Knowledge → 🟢 Labels + embeddings + vectors (YOU ARE HERE)
209
+ ```
210
+
211
+ Every artifact created is:
212
+ 1. ✅ Tagged as a **knowledge_item** (thing type)
213
+ 2. 🏷️ Labeled with semantic metadata
214
+ 3. 🔗 Linked to inference context (event)
215
+ 4. 📊 Indexed for RAG search
216
+
217
+ ## Future Enhancements
218
+
219
+ Planned improvements:
220
+
221
+ - 🧠 Auto-generate embeddings with OpenAI/Anthropic
222
+ - 🔍 Vector search across all knowledge
223
+ - 📊 Knowledge dashboard visualization
224
+ - 🤖 RAG-powered code search
225
+ - 📈 Knowledge growth metrics
226
+ - 🔗 Link artifacts to related things (features, tasks, tests)
227
+
228
+ ## Troubleshooting
229
+
230
+ ### Hooks not running?
231
+
232
+ Check that hooks are executable:
233
+ ```bash
234
+ chmod +x .claude/hooks/knowledge-*.py
235
+ ```
236
+
237
+ ### Knowledge logs not created?
238
+
239
+ Ensure directory exists:
240
+ ```bash
241
+ mkdir -p ~/.claude/knowledge-log
242
+ ```
243
+
244
+ ### Want to disable temporarily?
245
+
246
+ Remove from `.claude/settings.local.json`:
247
+ ```json
248
+ // Remove these blocks
249
+ {
250
+ "type": "command",
251
+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/knowledge-pre.py",
252
+ "timeout": 5
253
+ }
254
+ ```
255
+
256
+ ## See Also
257
+
258
+ - **`validate-ontology-structure.py`**: Validates 6-dimension ontology structure
259
+ - **`todo.py`**: Inference context tracking (Infer 1-100)
260
+ - **`done.py`**: Marks inferences complete
261
+ - **`one/knowledge/ontology.md`**: Complete 6-dimension ontology spec
262
+
263
+ ---
264
+
265
+ **Built with clarity, simplicity, and infinite scale in mind.**
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python3
2
+ """Check for files that don't follow kebab-case naming"""
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+
7
+ one_dir = Path("/Users/toc/Server/ONE/one")
8
+ pattern = re.compile(r'^[a-z0-9]+(-[a-z0-9]+)*\.(md|yaml|yml|json)$')
9
+
10
+ invalid_files = []
11
+
12
+ for root, dirs, files in os.walk(one_dir):
13
+ # Skip .git and .obsidian
14
+ dirs[:] = [d for d in dirs if d not in ['.git', '.obsidian']]
15
+
16
+ for filename in files:
17
+ if filename.endswith(('.md', '.yaml', '.yml', '.json')):
18
+ if not pattern.match(filename):
19
+ filepath = os.path.join(root, filename)
20
+ # Suggest kebab-case name
21
+ suggested = filename.lower()
22
+ suggested = re.sub(r'[^a-z0-9.]+', '-', suggested)
23
+ suggested = re.sub(r'-+', '-', suggested)
24
+ suggested = re.sub(r'^-|-$', '', suggested)
25
+
26
+ invalid_files.append({
27
+ 'path': filepath,
28
+ 'filename': filename,
29
+ 'suggested': suggested
30
+ })
31
+
32
+ if invalid_files:
33
+ print(f"Found {len(invalid_files)} files with invalid naming:\n")
34
+ for item in invalid_files:
35
+ print(f"❌ {item['path']}")
36
+ print(f" Current: {item['filename']}")
37
+ print(f" Suggested: {item['suggested']}")
38
+ print()
39
+ else:
40
+ print("✅ All files follow kebab-case naming convention!")
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ONE Platform - Clean Agent Post-Inference Hook
4
+ Cleans up and organizes after completing each inference.
5
+
6
+ This hook runs after inference completion to:
7
+ - Remove generated artifacts and temporary files
8
+ - Organize files into correct directories
9
+ - Update metadata tags on modified files
10
+ - Archive old versions
11
+ - Generate cleanup report
12
+ - Update cleanliness metrics
13
+ """
14
+ import json
15
+ import sys
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Dict, Any, List
19
+ import subprocess
20
+ import shutil
21
+ from datetime import datetime
22
+
23
+ # Temporary file patterns to clean
24
+ TEMP_PATTERNS = [
25
+ "*.tmp",
26
+ "*.swp",
27
+ "*~",
28
+ "*.bak",
29
+ ".DS_Store",
30
+ "*.log",
31
+ ]
32
+
33
+ # Directories to clean
34
+ CLEAN_DIRS = [
35
+ ".astro",
36
+ "dist",
37
+ "node_modules/.cache",
38
+ ".claude/state/temp",
39
+ ]
40
+
41
+ # Archive directory for old versions
42
+ ARCHIVE_DIR = ".claude/archive"
43
+
44
+
45
+ class CleanupAgent:
46
+ def __init__(self, project_dir: str):
47
+ self.project_dir = Path(project_dir)
48
+ self.actions_taken: List[str] = []
49
+ self.files_removed: int = 0
50
+ self.files_organized: int = 0
51
+ self.files_tagged: int = 0
52
+ self.space_freed: int = 0 # in bytes
53
+
54
+ def log_action(self, action: str):
55
+ """Log a cleanup action"""
56
+ self.actions_taken.append(action)
57
+
58
+ def remove_temp_files(self):
59
+ """Remove temporary and backup files"""
60
+ removed = []
61
+
62
+ for pattern in TEMP_PATTERNS:
63
+ for temp_file in self.project_dir.rglob(pattern):
64
+ # Skip node_modules and .git
65
+ if "node_modules" in str(temp_file) or ".git" in str(temp_file):
66
+ continue
67
+
68
+ try:
69
+ file_size = temp_file.stat().st_size
70
+ temp_file.unlink()
71
+ removed.append(str(temp_file.relative_to(self.project_dir)))
72
+ self.space_freed += file_size
73
+ self.files_removed += 1
74
+ except Exception as e:
75
+ pass # Skip files we can't remove
76
+
77
+ if removed:
78
+ self.log_action(f"Removed {len(removed)} temporary files")
79
+ for file in removed[:5]:
80
+ self.log_action(f" • {file}")
81
+ if len(removed) > 5:
82
+ self.log_action(f" ... and {len(removed) - 5} more")
83
+
84
+ def clean_build_artifacts(self):
85
+ """Clean build and cache directories"""
86
+ for clean_dir in CLEAN_DIRS:
87
+ dir_path = self.project_dir / clean_dir
88
+ if dir_path.exists() and dir_path.is_dir():
89
+ try:
90
+ # Calculate size before deletion
91
+ total_size = sum(
92
+ f.stat().st_size
93
+ for f in dir_path.rglob("*")
94
+ if f.is_file()
95
+ )
96
+
97
+ shutil.rmtree(dir_path)
98
+ self.space_freed += total_size
99
+ self.log_action(f"Cleaned: {clean_dir} ({self._format_size(total_size)})")
100
+ except Exception:
101
+ pass # Skip if we can't clean
102
+
103
+ def organize_files(self):
104
+ """Organize files into correct directories"""
105
+ # Check for misplaced markdown files
106
+ root_md_files = [
107
+ f for f in self.project_dir.glob("*.md")
108
+ if f.name not in ["README.md", "CLAUDE.md", "AGENTS.md", "LICENSE.md", "CHANGELOG.md"]
109
+ ]
110
+
111
+ for md_file in root_md_files:
112
+ # Suggest moving to one/knowledge/
113
+ target_dir = self.project_dir / "one" / "knowledge"
114
+ if target_dir.exists():
115
+ try:
116
+ target_path = target_dir / md_file.name
117
+ if not target_path.exists():
118
+ shutil.move(str(md_file), str(target_path))
119
+ self.files_organized += 1
120
+ self.log_action(f"Moved: {md_file.name} → one/knowledge/")
121
+ except Exception:
122
+ pass
123
+
124
+ def update_metadata_tags(self):
125
+ """Update metadata tags on recently modified files"""
126
+ # Find markdown files modified in last inference
127
+ recent_files = []
128
+ cutoff_time = datetime.now().timestamp() - 3600 # Last hour
129
+
130
+ for md_file in (self.project_dir / "one").rglob("*.md"):
131
+ try:
132
+ if md_file.stat().st_mtime > cutoff_time:
133
+ recent_files.append(md_file)
134
+ except Exception:
135
+ pass
136
+
137
+ # Add/update metadata tags
138
+ for md_file in recent_files:
139
+ if self._add_metadata_if_missing(md_file):
140
+ self.files_tagged += 1
141
+ self.log_action(f"Tagged: {md_file.relative_to(self.project_dir)}")
142
+
143
+ def _add_metadata_if_missing(self, file_path: Path) -> bool:
144
+ """Add metadata frontmatter if missing"""
145
+ try:
146
+ content = file_path.read_text()
147
+
148
+ # Check if already has frontmatter
149
+ if content.startswith("---\n"):
150
+ return False
151
+
152
+ # Infer metadata from file location
153
+ relative_path = file_path.relative_to(self.project_dir)
154
+ parts = relative_path.parts
155
+
156
+ # Determine dimension and tags
157
+ dimension = parts[1] if len(parts) > 1 else "knowledge"
158
+ category = parts[2] if len(parts) > 2 else "general"
159
+
160
+ # Generate metadata
161
+ metadata = f"""---
162
+ title: {file_path.stem.replace("-", " ").title()}
163
+ dimension: {dimension}
164
+ category: {category}
165
+ tags: []
166
+ created: {datetime.now().strftime("%Y-%m-%d")}
167
+ updated: {datetime.now().strftime("%Y-%m-%d")}
168
+ version: 1.0.0
169
+ ai_context: |
170
+ This document is part of the {dimension} dimension.
171
+ Location: {relative_path}
172
+ For AI agents: Read this to understand {file_path.stem.replace("-", " ")}.
173
+ ---
174
+
175
+ """
176
+ # Prepend metadata
177
+ new_content = metadata + content
178
+ file_path.write_text(new_content)
179
+ return True
180
+
181
+ except Exception:
182
+ return False
183
+
184
+ def archive_old_versions(self):
185
+ """Archive old versions of files (if backup exists)"""
186
+ archive_dir = self.project_dir / ARCHIVE_DIR
187
+ archive_dir.mkdir(parents=True, exist_ok=True)
188
+
189
+ # Find .bak files and archive them
190
+ for bak_file in self.project_dir.rglob("*.bak"):
191
+ if "node_modules" in str(bak_file) or ".git" in str(bak_file):
192
+ continue
193
+
194
+ try:
195
+ # Create date-stamped archive
196
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
197
+ archive_name = f"{bak_file.stem}_{timestamp}.bak"
198
+ archive_path = archive_dir / archive_name
199
+
200
+ shutil.move(str(bak_file), str(archive_path))
201
+ self.log_action(f"Archived: {bak_file.name}")
202
+ except Exception:
203
+ pass
204
+
205
+ def _format_size(self, bytes: int) -> str:
206
+ """Format bytes as human-readable size"""
207
+ for unit in ["B", "KB", "MB", "GB"]:
208
+ if bytes < 1024:
209
+ return f"{bytes:.1f} {unit}"
210
+ bytes /= 1024
211
+ return f"{bytes:.1f} TB"
212
+
213
+ def run_cleanup(self):
214
+ """Run all cleanup operations"""
215
+ self.remove_temp_files()
216
+ self.clean_build_artifacts()
217
+ self.organize_files()
218
+ self.update_metadata_tags()
219
+ self.archive_old_versions()
220
+
221
+
222
+ def generate_report(agent: CleanupAgent) -> str:
223
+ """Generate cleanup report"""
224
+ report = f"""
225
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
226
+ 🧹 CLEANUP COMPLETE - Agent Clean Post-Inference
227
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
228
+
229
+ 📊 CLEANUP METRICS:
230
+ • Files Removed: {agent.files_removed}
231
+ • Files Organized: {agent.files_organized}
232
+ • Files Tagged: {agent.files_tagged}
233
+ • Space Freed: {agent._format_size(agent.space_freed)}
234
+
235
+ """
236
+
237
+ if agent.actions_taken:
238
+ report += "✅ ACTIONS TAKEN:\n"
239
+ for action in agent.actions_taken[:10]:
240
+ report += f" {action}\n"
241
+ if len(agent.actions_taken) > 10:
242
+ report += f" ... and {len(agent.actions_taken) - 10} more actions\n"
243
+ else:
244
+ report += "✨ Environment was already clean - no actions needed!\n"
245
+
246
+ report += """
247
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
248
+ 💡 NEXT STEPS:
249
+ • Files are organized and tagged
250
+ • Temporary artifacts removed
251
+ • Ready for next inference
252
+
253
+ 🔄 Run /done to advance to next inference
254
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
255
+ """
256
+
257
+ return report
258
+
259
+
260
+ def main():
261
+ try:
262
+ # Load hook input from stdin
263
+ input_data = json.load(sys.stdin)
264
+
265
+ # Get project directory
266
+ project_dir = os.environ.get("CLAUDE_PROJECT_DIR", ".")
267
+
268
+ # Run cleanup
269
+ agent = CleanupAgent(project_dir)
270
+ agent.run_cleanup()
271
+
272
+ # Generate report
273
+ report = generate_report(agent)
274
+
275
+ # Save cleanup metrics
276
+ state_file = Path(project_dir) / ".claude" / "state" / "cleanup_metrics.json"
277
+ state_file.parent.mkdir(parents=True, exist_ok=True)
278
+
279
+ metrics = {
280
+ "last_cleanup": datetime.now().isoformat(),
281
+ "files_removed": agent.files_removed,
282
+ "files_organized": agent.files_organized,
283
+ "files_tagged": agent.files_tagged,
284
+ "space_freed": agent.space_freed,
285
+ "actions": agent.actions_taken
286
+ }
287
+
288
+ state_file.write_text(json.dumps(metrics, indent=2))
289
+
290
+ # Output report
291
+ print(report)
292
+ sys.exit(0)
293
+
294
+ except Exception as e:
295
+ # Don't block on hook errors
296
+ print(f"Error in clean-post hook: {e}", file=sys.stderr)
297
+ sys.exit(0)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ main()