oneie 3.6.5 → 3.6.7

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 (98) hide show
  1. package/.claude/commands/onboard.md +179 -0
  2. package/.claude/commands/one copy.md +565 -0
  3. package/.claude/commands/one.md +125 -487
  4. package/.claude/commands/server.md +333 -0
  5. package/.claude/hooks/README-knowledge-hooks.md +265 -0
  6. package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
  7. package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
  8. package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
  9. package/.claude/hooks/check-filenames.py +40 -0
  10. package/.claude/hooks/clean-post.py +301 -0
  11. package/.claude/hooks/clean-pre.py +308 -0
  12. package/.claude/hooks/done.py +175 -0
  13. package/.claude/hooks/format-hook.sh +75 -0
  14. package/.claude/hooks/hook-logger.sh +59 -0
  15. package/.claude/hooks/knowledge-post.py +251 -0
  16. package/.claude/hooks/knowledge-pre.py +150 -0
  17. package/.claude/hooks/notification-hook.sh +112 -0
  18. package/.claude/hooks/security-hook.sh +157 -0
  19. package/.claude/hooks/tag-all-docs.py +338 -0
  20. package/.claude/hooks/todo.py +298 -0
  21. package/.claude/hooks/validate-ontology-structure.py +455 -0
  22. package/.claude/skills/astro/add-content-collection.md +30 -0
  23. package/.claude/skills/astro/check-build.md +29 -0
  24. package/.claude/skills/astro/create-component.md +29 -0
  25. package/.claude/skills/astro/create-page.md +30 -0
  26. package/.claude/skills/astro/optimize-performance.md +21 -0
  27. package/.claude/skills/convex/check-deployment.md +46 -0
  28. package/.claude/skills/convex/create-mutation.md +405 -0
  29. package/.claude/skills/convex/create-query.md +52 -0
  30. package/.claude/skills/convex/read-schema.md +373 -0
  31. package/.claude/skills/convex/test-function.md +50 -0
  32. package/.claude/skills/deployment/check-deployment-health.md +20 -0
  33. package/.claude/skills/deployment/create-release.md +21 -0
  34. package/.claude/skills/deployment/deploy-cloudflare.md +31 -0
  35. package/.claude/skills/deployment/deploy-convex.md +30 -0
  36. package/.claude/skills/deployment/sync-repositories.md +19 -0
  37. package/.claude/skills/design/check-accessibility.md +21 -0
  38. package/.claude/skills/design/create-component-spec.md +27 -0
  39. package/.claude/skills/design/generate-design-tokens.md +24 -0
  40. package/.claude/skills/design/generate-wireframe.md +30 -0
  41. package/.claude/skills/documentation/create-migration-guide.md +20 -0
  42. package/.claude/skills/documentation/generate-api-docs.md +27 -0
  43. package/.claude/skills/documentation/generate-readme.md +22 -0
  44. package/.claude/skills/documentation/update-knowledge.md +20 -0
  45. package/.claude/skills/integration/connect-external-system.md +21 -0
  46. package/.claude/skills/integration/implement-a2a.md +20 -0
  47. package/.claude/skills/integration/implement-acp.md +20 -0
  48. package/.claude/skills/integration/verify-integration.md +20 -0
  49. package/.claude/skills/ontology/README.md +255 -0
  50. package/.claude/skills/ontology/check-dimension.md +307 -0
  51. package/.claude/skills/ontology/generate-entity-type.md +339 -0
  52. package/.claude/skills/ontology/validate-schema.md +229 -0
  53. package/.claude/skills/ontology/verify-relationships.md +310 -0
  54. package/.claude/skills/problem-solving/analyze-test-failure.md +21 -0
  55. package/.claude/skills/problem-solving/identify-root-cause.md +20 -0
  56. package/.claude/skills/problem-solving/propose-solution.md +29 -0
  57. package/.claude/skills/problem-solving/verify-fix.md +21 -0
  58. package/.claude/skills/sales/generate-demo-script.md +21 -0
  59. package/.claude/skills/sales/qualify-lead.md +30 -0
  60. package/.claude/skills/sales/track-trial.md +20 -0
  61. package/.claude/skills/sales/verify-kyc.md +20 -0
  62. package/.claude/skills/testing/analyze-coverage.md +24 -0
  63. package/.claude/skills/testing/generate-tests.md +24 -0
  64. package/.claude/skills/testing/run-tests.md +27 -0
  65. package/.claude/skills/testing/validate-e2e.md +25 -0
  66. package/.mcp.json +30 -3
  67. package/dist/commands/init.d.ts.map +1 -1
  68. package/dist/commands/init.js +13 -6
  69. package/dist/commands/init.js.map +1 -1
  70. package/dist/utils/launch-claude.d.ts +3 -2
  71. package/dist/utils/launch-claude.d.ts.map +1 -1
  72. package/dist/utils/launch-claude.js +64 -29
  73. package/dist/utils/launch-claude.js.map +1 -1
  74. package/folders.yaml +1 -1
  75. package/one/.obsidian/workspace.json +22 -22
  76. package/one/events/CREATE-WEBSITE.md +442 -0
  77. package/one/events/CUSTOM-DOMAIN.md +357 -0
  78. package/one/events/DEPLOYMENT copy.md +426 -0
  79. package/one/events/ECOMMERCE-BEFORE-AFTER.md +251 -0
  80. package/one/events/ECOMMERCE-ENHANCEMENTS.md +576 -0
  81. package/one/events/ECOMMERCE-HIGH-CONVERTING-ELEMENTS.md +421 -0
  82. package/one/events/ECOMMERCE-REFACTOR-SUMMARY.md +196 -0
  83. package/one/events/ECOMMERCE-SETUP-SUMMARY.md +396 -0
  84. package/one/events/INSTALLATION_FOLDERS.md +516 -0
  85. package/one/events/INSTALLATION_FOLDERS_FILES.md +205 -0
  86. package/one/events/INSTALLATION_FOLDERS_SUMMARY.md +419 -0
  87. package/one/events/LICENSE.md +89 -0
  88. package/one/events/MCP-CONFIGURATION.md +336 -0
  89. package/one/events/MCP-SETUP-COMPLETE.md +205 -0
  90. package/one/events/NODE-UPGRADE.md +111 -0
  91. package/one/events/PACKAGE-STRUCTURE.md +310 -0
  92. package/one/events/PLAYBOOK-SETUP-SUMMARY.md +331 -0
  93. package/one/events/PROMPT_FIX_FRONTEND_ONLY.md +567 -0
  94. package/one/events/SIMPLE_FIX_FRONTEND_ONLY.md +262 -0
  95. package/one/events/STRIPE-INTEGRATION.md +414 -0
  96. package/one/events/STRIPE-SETUP-GUIDE.md +462 -0
  97. package/one/events/TRANSPARENCY-FIXES.md +275 -0
  98. package/package.json +4 -2
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ONE Platform - Done Hook
4
+ Marks current inference complete and advances to next inference.
5
+
6
+ This hook runs on Stop event to:
7
+ - Mark current inference as complete
8
+ - Capture lessons learned (if any)
9
+ - Advance to next inference
10
+ - Save updated state
11
+ """
12
+ import json
13
+ import sys
14
+ import os
15
+ from pathlib import Path
16
+ from typing import Dict, Any
17
+
18
+ # Import task descriptions from todo hook
19
+ from todo import INFERENCE_TASKS, get_dimensions_for_inference, get_specialist_for_inference
20
+
21
+
22
+ def load_state() -> Dict[str, Any]:
23
+ """Load current inference state from .claude/state/inference.json"""
24
+ state_file = Path(os.environ.get("CLAUDE_PROJECT_DIR", ".")) / ".claude" / "state" / "inference.json"
25
+
26
+ if not state_file.exists():
27
+ # Initialize default state
28
+ default_state = {
29
+ "current_inference": 1,
30
+ "completed_inferences": [],
31
+ "feature_name": "New Feature",
32
+ "organization": "Default Org",
33
+ "person_role": "platform_owner",
34
+ "lessons_learned": []
35
+ }
36
+ return default_state
37
+
38
+ return json.loads(state_file.read_text())
39
+
40
+
41
+ def save_state(state: Dict[str, Any]):
42
+ """Save inference state to .claude/state/inference.json"""
43
+ state_file = Path(os.environ.get("CLAUDE_PROJECT_DIR", ".")) / ".claude" / "state" / "inference.json"
44
+ state_file.parent.mkdir(parents=True, exist_ok=True)
45
+ state_file.write_text(json.dumps(state, indent=2))
46
+
47
+
48
+ def extract_lesson_from_transcript(transcript_path: str, inference: int) -> str:
49
+ """Extract lesson learned from conversation transcript"""
50
+ # TODO: Parse transcript JSONL to extract key learnings
51
+ # For now, return a placeholder
52
+ return f"Completed inference {inference} successfully"
53
+
54
+
55
+ def mark_complete_and_advance(state: Dict[str, Any], transcript_path: str) -> Dict[str, Any]:
56
+ """Mark current inference complete and advance to next"""
57
+ current = state["current_inference"]
58
+
59
+ # Mark current inference as complete
60
+ if current not in state["completed_inferences"]:
61
+ state["completed_inferences"].append(current)
62
+ state["completed_inferences"].sort()
63
+
64
+ # Extract lesson learned
65
+ lesson = extract_lesson_from_transcript(transcript_path, current)
66
+ state["lessons_learned"].append({
67
+ "inference": current,
68
+ "lesson": lesson,
69
+ "timestamp": os.times().elapsed
70
+ })
71
+
72
+ # Advance to next inference (unless we're at 100)
73
+ if current < 100:
74
+ state["current_inference"] = current + 1
75
+ else:
76
+ # Feature complete!
77
+ state["current_inference"] = 100
78
+ state["feature_complete"] = True
79
+
80
+ return state
81
+
82
+
83
+ def generate_completion_message(state: Dict[str, Any]) -> str:
84
+ """Generate message shown after marking complete"""
85
+ previous = state["current_inference"] - 1 if state["current_inference"] > 1 else 1
86
+ current = state["current_inference"]
87
+ completed_count = len(state["completed_inferences"])
88
+ progress_pct = (completed_count / 100) * 100
89
+
90
+ task = INFERENCE_TASKS.get(current, "Unknown task")
91
+ dimensions = get_dimensions_for_inference(current)
92
+ specialist = get_specialist_for_inference(current)
93
+
94
+ message = f"""
95
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
96
+ ✅ INFERENCE COMPLETE: Infer {previous}/100
97
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
98
+
99
+ **Progress:** {completed_count}/100 inferences complete ({progress_pct:.0f}%)
100
+ **Feature:** {state["feature_name"]}
101
+
102
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
103
+ 🎯 NEXT INFERENCE: Infer {current}/100
104
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
105
+
106
+ **Task:** {task}
107
+ **Ontology Dimensions:** {", ".join(dimensions) if dimensions else "Foundation"}
108
+ **Assigned Specialist:** {specialist if specialist else "Engineering Director"}
109
+
110
+ Ready to continue? Type your next prompt or use:
111
+ /done - Mark this inference complete (when finished)
112
+ /next - Skip to next inference (if not applicable)
113
+ /plan - View complete 100-inference plan
114
+
115
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
116
+ """
117
+
118
+ if completed_count == 100:
119
+ message = f"""
120
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
121
+ 🎉 FEATURE COMPLETE: {state["feature_name"]}
122
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
123
+
124
+ **All 100 inferences completed successfully!**
125
+
126
+ **Final Stats:**
127
+ - Organization: {state["organization"]}
128
+ - Person Role: {state["person_role"]}
129
+ - Lessons Learned: {len(state.get("lessons_learned", []))}
130
+
131
+ **Next Steps:**
132
+ 1. Review lessons learned: /lessons
133
+ 2. Start new feature: /one
134
+ 3. Generate documentation: /document
135
+
136
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
137
+ Congratulations! 🎊 Your feature is production-ready.
138
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
139
+ """
140
+
141
+ return message
142
+
143
+
144
+ def main():
145
+ try:
146
+ # Load hook input from stdin
147
+ input_data = json.load(sys.stdin)
148
+ transcript_path = input_data.get("transcript_path", "")
149
+
150
+ # Load current state
151
+ state = load_state()
152
+
153
+ # Mark complete and advance
154
+ state = mark_complete_and_advance(state, transcript_path)
155
+
156
+ # Save updated state
157
+ save_state(state)
158
+
159
+ # Generate completion message
160
+ message = generate_completion_message(state)
161
+
162
+ # Output message (shown in transcript mode with Ctrl-R)
163
+ print(message)
164
+
165
+ # Exit with success
166
+ sys.exit(0)
167
+
168
+ except Exception as e:
169
+ # Log error but don't block
170
+ print(f"Error in done hook: {e}", file=sys.stderr)
171
+ sys.exit(0)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
@@ -0,0 +1,75 @@
1
+ #!/bin/bash
2
+
3
+ # Format Hook - ONE Platform
4
+ # Auto-formats markdown and YAML files in /one directory
5
+
6
+ set -e
7
+
8
+ # Source the logger
9
+ source "$CLAUDE_PROJECT_DIR/.claude/hooks/hook-logger.sh"
10
+
11
+ # Get file path from stdin or argument
12
+ FILE_PATH="${1:-}"
13
+
14
+ # Log start
15
+ log_message "INFO" "Starting format-hook for: ${FILE_PATH:-all files}"
16
+ START_TIME=$(get_time_ms)
17
+
18
+ # Function to format markdown files
19
+ format_markdown() {
20
+ local file="$1"
21
+
22
+ if command -v prettier &> /dev/null; then
23
+ prettier --write "$file" --parser markdown 2>/dev/null && echo "✅ Formatted: $file"
24
+ else
25
+ echo "⚠️ prettier not found, skipping markdown formatting"
26
+ fi
27
+ }
28
+
29
+ # Function to format YAML files
30
+ format_yaml() {
31
+ local file="$1"
32
+
33
+ if command -v prettier &> /dev/null; then
34
+ prettier --write "$file" --parser yaml 2>/dev/null && echo "✅ Formatted: $file"
35
+ else
36
+ echo "⚠️ prettier not found, skipping YAML formatting"
37
+ fi
38
+ }
39
+
40
+ EXIT_CODE=0
41
+
42
+ # Check if specific file provided
43
+ if [ -n "$FILE_PATH" ]; then
44
+ # Format specific file
45
+ if [[ "$FILE_PATH" =~ \.md$ ]]; then
46
+ format_markdown "$FILE_PATH"
47
+ elif [[ "$FILE_PATH" =~ \.(yaml|yml)$ ]]; then
48
+ format_yaml "$FILE_PATH"
49
+ else
50
+ log_message "INFO" "File type not supported for formatting: $FILE_PATH"
51
+ fi
52
+ else
53
+ # Format all files in /one directory
54
+ if [ -d "$CLAUDE_PROJECT_DIR/one" ]; then
55
+ echo "🔧 Formatting files in /one directory..."
56
+
57
+ # Format markdown files
58
+ if command -v prettier &> /dev/null; then
59
+ find "$CLAUDE_PROJECT_DIR/one" -type f -name "*.md" -exec prettier --write {} \; 2>/dev/null || true
60
+ find "$CLAUDE_PROJECT_DIR/one" -type f \( -name "*.yaml" -o -name "*.yml" \) -exec prettier --write {} \; 2>/dev/null || true
61
+ echo "✅ Formatting completed"
62
+ else
63
+ echo "⚠️ prettier not installed. Install with: npm install -g prettier"
64
+ EXIT_CODE=0 # Don't fail if prettier not installed
65
+ fi
66
+ else
67
+ log_message "WARN" "/one directory not found"
68
+ fi
69
+ fi
70
+
71
+ # Log completion
72
+ END_TIME=$(get_time_ms)
73
+ log_hook_execution "format-hook" "$0 $*" "$START_TIME" "$END_TIME" "$EXIT_CODE"
74
+
75
+ exit $EXIT_CODE
@@ -0,0 +1,59 @@
1
+ #!/bin/bash
2
+
3
+ # Claude Code Hook Logger - ONE Platform
4
+ # Handles logging for hook execution with debug mode and performance metrics
5
+
6
+ LOG_FILE="${LOG_FILE:-$CLAUDE_PROJECT_DIR/.claude/hooks.log}"
7
+ DEBUG_MODE="${DEBUG_MODE:-false}"
8
+
9
+ # Create log directory if it doesn't exist
10
+ mkdir -p "$(dirname "$LOG_FILE")"
11
+
12
+ # Function to log messages
13
+ log_message() {
14
+ local level="$1"
15
+ local message="$2"
16
+ local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
17
+
18
+ echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
19
+
20
+ if [ "$DEBUG_MODE" = "true" ]; then
21
+ echo "[$timestamp] [$level] $message" >&2
22
+ fi
23
+ }
24
+
25
+ # Function to log hook execution
26
+ log_hook_execution() {
27
+ local hook_name="$1"
28
+ local command="$2"
29
+ local start_time="$3"
30
+ local end_time="$4"
31
+ local exit_code="$5"
32
+
33
+ local duration=$((end_time - start_time))
34
+
35
+ log_message "INFO" "Hook: $hook_name | Duration: ${duration}ms | Exit: $exit_code"
36
+
37
+ # Log performance warning if execution took too long
38
+ if [ "$duration" -gt 5000 ]; then
39
+ log_message "WARN" "Hook execution exceeded 5 seconds: $hook_name"
40
+ fi
41
+ }
42
+
43
+ # Function to get current time in milliseconds
44
+ get_time_ms() {
45
+ if [[ "$OSTYPE" == "darwin"* ]]; then
46
+ # macOS
47
+ python3 -c "import time; print(int(time.time() * 1000))" 2>/dev/null || echo $(($(date +%s) * 1000))
48
+ else
49
+ # Linux
50
+ echo $(($(date +%s%N) / 1000000))
51
+ fi
52
+ }
53
+
54
+ # Export functions for use in other scripts
55
+ export -f log_message
56
+ export -f log_hook_execution
57
+ export -f get_time_ms
58
+ export LOG_FILE
59
+ export DEBUG_MODE
@@ -0,0 +1,251 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ONE Platform - Knowledge Tagging Post-Hook
4
+ Tags created/modified artifacts as knowledge in the ontology.
5
+
6
+ This hook runs on PostToolUse to:
7
+ - Create knowledge entries for new artifacts
8
+ - Tag with appropriate labels (file type, dimension, feature)
9
+ - Link knowledge to related things (features, tasks, designs)
10
+ - Optionally generate embeddings for RAG search
11
+ """
12
+ import json
13
+ import sys
14
+ import os
15
+ import hashlib
16
+ from pathlib import Path
17
+ from datetime import datetime
18
+ from typing import Dict, Any, Optional, List
19
+
20
+ # Knowledge artifact types
21
+ KNOWLEDGE_ARTIFACT_TYPES = {
22
+ "code": ["py", "ts", "tsx", "js", "jsx", "astro", "json", "yaml", "yml"],
23
+ "documentation": ["md", "mdx", "txt"],
24
+ "design": ["fig", "sketch", "svg", "png", "jpg"],
25
+ "test": ["test.ts", "test.tsx", "spec.ts", "spec.tsx"],
26
+ "config": ["json", "yaml", "yml", "toml", "ini"],
27
+ }
28
+
29
+ # Knowledge labels based on file location/type
30
+ KNOWLEDGE_LABELS = {
31
+ "/web/src/components": ["component", "frontend", "ui"],
32
+ "/web/src/pages": ["page", "frontend", "routing"],
33
+ "/backend/convex/queries": ["query", "backend", "database"],
34
+ "/backend/convex/mutations": ["mutation", "backend", "database"],
35
+ "/backend/convex/services": ["service", "backend", "business-logic"],
36
+ "/one/things": ["documentation", "ontology", "things"],
37
+ "/one/connections": ["documentation", "ontology", "connections"],
38
+ "/one/events": ["documentation", "ontology", "events"],
39
+ "/one/knowledge": ["documentation", "ontology", "knowledge"],
40
+ "/test": ["test", "quality", "validation"],
41
+ }
42
+
43
+ def get_artifact_type(file_path: str) -> Optional[str]:
44
+ """Determine artifact type from file path"""
45
+ path = Path(file_path)
46
+ ext = path.suffix.lstrip(".")
47
+
48
+ # Check for test files first
49
+ if "test" in path.name or "spec" in path.name:
50
+ return "test"
51
+
52
+ # Check by extension
53
+ for artifact_type, extensions in KNOWLEDGE_ARTIFACT_TYPES.items():
54
+ if any(path.name.endswith(e) for e in extensions):
55
+ return artifact_type
56
+
57
+ return None
58
+
59
+ def get_knowledge_labels(file_path: str) -> List[str]:
60
+ """Generate knowledge labels based on file path"""
61
+ labels = []
62
+
63
+ # Add labels based on path patterns
64
+ for path_pattern, path_labels in KNOWLEDGE_LABELS.items():
65
+ if path_pattern in file_path:
66
+ labels.extend(path_labels)
67
+
68
+ # Add artifact type label
69
+ artifact_type = get_artifact_type(file_path)
70
+ if artifact_type:
71
+ labels.append(artifact_type)
72
+
73
+ # Add dimension label if in /one
74
+ if "/one/" in file_path:
75
+ parts = Path(file_path).parts
76
+ try:
77
+ one_index = parts.index("one")
78
+ if one_index + 1 < len(parts):
79
+ dimension = parts[one_index + 1]
80
+ labels.append(f"dimension-{dimension}")
81
+ except ValueError:
82
+ pass
83
+
84
+ return list(set(labels)) # Remove duplicates
85
+
86
+ def get_inference_context() -> Dict[str, Any]:
87
+ """Load current inference context from todo state"""
88
+ try:
89
+ todo_state_path = Path.home() / ".claude" / "todo-state.json"
90
+ if todo_state_path.exists():
91
+ with open(todo_state_path, 'r') as f:
92
+ state = json.load(f)
93
+ return {
94
+ "inference_number": state.get("current_inference", 0),
95
+ "feature": state.get("feature", "New Feature"),
96
+ "organization": state.get("organization", "Default Org"),
97
+ "person_role": state.get("person_role", "platform_owner"),
98
+ }
99
+ except Exception:
100
+ pass
101
+
102
+ return {
103
+ "inference_number": 0,
104
+ "feature": "New Feature",
105
+ "organization": "Default Org",
106
+ "person_role": "platform_owner",
107
+ }
108
+
109
+ def should_tag_as_knowledge(file_path: str, tool_name: str) -> bool:
110
+ """Determine if artifact should be tagged as knowledge"""
111
+ # Only tag Write and Edit operations
112
+ if tool_name not in ["Write", "Edit", "MultiEdit"]:
113
+ return False
114
+
115
+ # Don't tag temporary files
116
+ if "/tmp/" in file_path or "/.temp/" in file_path:
117
+ return False
118
+
119
+ # Don't tag generated files
120
+ if "/_generated/" in file_path or "/node_modules/" in file_path:
121
+ return False
122
+
123
+ # Only tag known artifact types
124
+ artifact_type = get_artifact_type(file_path)
125
+ if not artifact_type:
126
+ return False
127
+
128
+ return True
129
+
130
+ def generate_content_hash(file_path: str) -> str:
131
+ """Generate SHA256 hash of file content"""
132
+ try:
133
+ with open(file_path, 'rb') as f:
134
+ return hashlib.sha256(f.read()).hexdigest()[:16]
135
+ except Exception:
136
+ return ""
137
+
138
+ def create_knowledge_entry(file_path: str, content: Optional[str] = None) -> Dict[str, Any]:
139
+ """Create knowledge entry for artifact"""
140
+ path = Path(file_path)
141
+ artifact_type = get_artifact_type(file_path)
142
+ labels = get_knowledge_labels(file_path)
143
+ inference_ctx = get_inference_context()
144
+ content_hash = generate_content_hash(file_path)
145
+
146
+ # Build knowledge entry
147
+ entry = {
148
+ "type": "knowledge_item",
149
+ "artifact_type": artifact_type,
150
+ "file_path": str(path.absolute()),
151
+ "file_name": path.name,
152
+ "labels": labels,
153
+ "content_hash": content_hash,
154
+ "created_at": datetime.now().isoformat(),
155
+ "inference_number": inference_ctx["inference_number"],
156
+ "feature": inference_ctx["feature"],
157
+ "organization": inference_ctx["organization"],
158
+ "created_by_role": inference_ctx["person_role"],
159
+ "metadata": {
160
+ "file_size": path.stat().st_size if path.exists() else 0,
161
+ "directory": str(path.parent),
162
+ "extension": path.suffix,
163
+ }
164
+ }
165
+
166
+ # Add content preview if available
167
+ if content:
168
+ entry["content_preview"] = content[:500] if len(content) > 500 else content
169
+ elif path.exists():
170
+ try:
171
+ with open(path, 'r', encoding='utf-8') as f:
172
+ preview = f.read(500)
173
+ entry["content_preview"] = preview
174
+ except Exception:
175
+ pass
176
+
177
+ return entry
178
+
179
+ def save_knowledge_entry(entry: Dict[str, Any]) -> str:
180
+ """Save knowledge entry to knowledge log"""
181
+ # Create knowledge log directory
182
+ knowledge_log_dir = Path.home() / ".claude" / "knowledge-log"
183
+ knowledge_log_dir.mkdir(parents=True, exist_ok=True)
184
+
185
+ # Create daily log file
186
+ log_date = datetime.now().strftime("%Y-%m-%d")
187
+ log_file = knowledge_log_dir / f"knowledge-{log_date}.jsonl"
188
+
189
+ # Append entry
190
+ with open(log_file, 'a') as f:
191
+ f.write(json.dumps(entry) + "\n")
192
+
193
+ return str(log_file)
194
+
195
+ def main():
196
+ """Main hook execution"""
197
+ try:
198
+ # Read hook input from stdin
199
+ hook_input = json.load(sys.stdin)
200
+
201
+ hook_event = hook_input.get("hook_event_name")
202
+ tool_name = hook_input.get("tool_name")
203
+ tool_input = hook_input.get("tool_input", {})
204
+
205
+ # Only process PostToolUse for Write/Edit operations
206
+ if hook_event != "PostToolUse":
207
+ sys.exit(0)
208
+
209
+ file_path = tool_input.get("file_path")
210
+ if not file_path:
211
+ sys.exit(0)
212
+
213
+ # Check if should be tagged as knowledge
214
+ if not should_tag_as_knowledge(file_path, tool_name):
215
+ sys.exit(0)
216
+
217
+ # Create knowledge entry
218
+ content = tool_input.get("content") or tool_input.get("new_string")
219
+ entry = create_knowledge_entry(file_path, content)
220
+
221
+ # Save to knowledge log
222
+ log_file = save_knowledge_entry(entry)
223
+
224
+ # Output post-hook message
225
+ artifact_type = entry["artifact_type"]
226
+ labels = entry["labels"]
227
+ inference_num = entry["inference_number"]
228
+
229
+ msg = f"✨ Knowledge Tagged\n"
230
+ msg += f" Artifact: {entry['file_name']}\n"
231
+ msg += f" Type: {artifact_type}\n"
232
+ msg += f" Labels: {', '.join(labels[:5])}"
233
+ if len(labels) > 5:
234
+ msg += f" (+{len(labels) - 5} more)"
235
+ if inference_num > 0:
236
+ msg += f"\n Inference: {inference_num}/100"
237
+ msg += f"\n Hash: {entry['content_hash']}"
238
+ msg += f"\n → Logged to: {Path(log_file).name}"
239
+
240
+ print(msg)
241
+ sys.exit(0)
242
+
243
+ except json.JSONDecodeError as e:
244
+ print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
245
+ sys.exit(1)
246
+ except Exception as e:
247
+ print(f"Error in knowledge post-hook: {e}", file=sys.stderr)
248
+ sys.exit(1)
249
+
250
+ if __name__ == "__main__":
251
+ main()