oneie 3.6.26 → 3.6.28

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 (37) hide show
  1. package/.claude/agents/TROUBLESHOOTING.md +530 -0
  2. package/.claude/agents/agent-claude.md +645 -0
  3. package/.claude/agents/agent-clone.md +2 -0
  4. package/.claude/agents/agent-frontend.md +162 -21
  5. package/.claude/agents/agent-writer.md +722 -0
  6. package/.claude/commands/chat.md +504 -0
  7. package/.claude/commands/create.md +134 -18
  8. package/.claude/commands/fast.md +531 -0
  9. package/.claude/commands/one.md +79 -90
  10. package/.claude/commands/optimize.md +74 -0
  11. package/.claude/commands/plan.md +420 -373
  12. package/.claude/commands/review.md +99 -0
  13. package/.claude/commands/server.md +97 -48
  14. package/.claude/commands/start.md +182 -0
  15. package/.claude/commands/test.md +197 -0
  16. package/.claude/commands/validate.md +140 -0
  17. package/.claude/hooks/__pycache__/todo.cpython-312.pyc +0 -0
  18. package/.claude/hooks/auto-format.sh +106 -0
  19. package/.claude/hooks/formatting.py +187 -0
  20. package/.claude/hooks/ontology-validation.py +255 -0
  21. package/.claude/hooks/validate-imports.py +182 -0
  22. package/.claude/hooks/validate-ontology.py +140 -0
  23. package/.claude/hooks/write-news.sh +194 -0
  24. package/CLAUDE.md +150 -1057
  25. package/one/knowledge/cascading-context-specification.md +1617 -0
  26. package/one/knowledge/claude-code-integration.md +1293 -0
  27. package/one/knowledge/development-commands.md +251 -0
  28. package/one/knowledge/guidelines.md +314 -0
  29. package/one/knowledge/parallel-agents.md +932 -0
  30. package/one/knowledge/performance.md +459 -0
  31. package/one/knowledge/troubleshooting.md +434 -0
  32. package/one/things/plans/dsl-claude-code.md +1011 -0
  33. package/one/things/plans/video-backend.md +638 -0
  34. package/one/things/plans/video-frontend.md +432 -0
  35. package/one/things/plans/video-old-archived.md +656 -0
  36. package/package.json +1 -1
  37. package/.claude/agents/AUDIT-agent-ops-alignment.md +0 -379
@@ -0,0 +1,197 @@
1
+ # /test - Run tests and fix failures
2
+
3
+ Run comprehensive test suite for `$ARGUMENTS`, analyze failures, fix issues, and ensure 100% pass rate.
4
+
5
+ ## Testing Workflow
6
+
7
+ ### 1. Run Tests
8
+
9
+ ```bash
10
+ # Run specific test file
11
+ bun test $ARGUMENTS
12
+
13
+ # Run with coverage
14
+ bun test --coverage $ARGUMENTS
15
+
16
+ # Run in watch mode (during development)
17
+ bun test --watch $ARGUMENTS
18
+ ```
19
+
20
+ ### 2. Analyze Failures
21
+
22
+ For each failing test:
23
+ - **Read error message**: Understand what assertion failed
24
+ - **Check test intent**: Preserve original test purpose
25
+ - **Identify root cause**: Implementation bug vs test bug
26
+ - **Verify ontology compliance**: Ensure fix maintains 6-dimension structure
27
+
28
+ ### 3. Fix Issues
29
+
30
+ **Priority order:**
31
+ 1. **Critical**: Security vulnerabilities, data corruption, multi-tenant violations
32
+ 2. **High**: Broken features, missing event logging, schema violations
33
+ 3. **Medium**: Performance issues, incomplete error handling
34
+ 4. **Low**: Code style, minor optimizations
35
+
36
+ **Fix principles:**
37
+ - Preserve test intent (don't just make tests pass by changing assertions)
38
+ - Maintain ontology compliance (all fixes respect 6 dimensions)
39
+ - Follow existing patterns (pattern convergence, not divergence)
40
+ - Add missing tests (if coverage gaps found)
41
+
42
+ ### 4. Re-run Until Pass
43
+
44
+ ```bash
45
+ # Fix and re-run iteratively
46
+ bun test $ARGUMENTS
47
+ # ... fix issues ...
48
+ bun test $ARGUMENTS
49
+ # ... repeat until 100% pass ...
50
+ ```
51
+
52
+ ### 5. Report Results
53
+
54
+ ## Test Categories
55
+
56
+ ### Unit Tests
57
+ - **Services**: Effect.ts business logic (pure functions)
58
+ - **Utilities**: Helper functions, validators
59
+ - **Components**: React component behavior (not visual)
60
+
61
+ ### Integration Tests
62
+ - **Frontend → Backend**: Convex query/mutation flows
63
+ - **Authentication**: All 6 auth methods (email/password, OAuth, magic links, etc.)
64
+ - **Multi-tenant**: Group isolation and hierarchy
65
+ - **Event Logging**: Mutation → Event creation
66
+
67
+ ### E2E Tests (Future)
68
+ - **User Flows**: Complete user journeys
69
+ - **Cross-feature**: Multiple features working together
70
+ - **Performance**: Load testing, query optimization
71
+
72
+ ## Ontology Validation in Tests
73
+
74
+ Every test should validate:
75
+ - ✓ Entities map to correct dimensions
76
+ - ✓ Multi-tenant scoping (groupId filtering)
77
+ - ✓ Event logging for state changes
78
+ - ✓ Schema compliance (required fields)
79
+ - ✓ Authorization (role-based access)
80
+
81
+ ## Output Format
82
+
83
+ ```
84
+ TEST RESULTS: [file/component name]
85
+
86
+ SUMMARY:
87
+ ✓ Passed: X/Y tests
88
+ ❌ Failed: N tests
89
+ ⏭️ Skipped: M tests
90
+ 📊 Coverage: XX%
91
+
92
+ FAILURES:
93
+
94
+ Test: "should create entity with groupId"
95
+ File: backend/convex/mutations/entities.test.ts:45
96
+ Error: Expected groupId to be defined, got undefined
97
+ Root Cause: Missing groupId parameter in mutation
98
+ Fix Applied: Added groupId validation and parameter
99
+ Status: ✓ FIXED
100
+
101
+ Test: "should log entity_created event"
102
+ File: backend/convex/mutations/entities.test.ts:67
103
+ Error: Expected 1 event, found 0
104
+ Root Cause: Event logging not implemented
105
+ Fix Applied: Added event insertion after entity creation
106
+ Status: ✓ FIXED
107
+
108
+ ONTOLOGY COMPLIANCE:
109
+ ✓ All entities have groupId
110
+ ✓ Event logging complete
111
+ ✓ Schema validation passes
112
+ ✓ Multi-tenant safe
113
+
114
+ COVERAGE GAPS:
115
+ ⚠️ Missing tests for error cases
116
+ 💡 Suggestion: Add tests for invalid groupId
117
+
118
+ FINAL STATUS: ✓ ALL TESTS PASSING (Y/Y)
119
+ ```
120
+
121
+ ## Example Usage
122
+
123
+ ```bash
124
+ /test test/auth
125
+ /test backend/convex/mutations/entities.test.ts
126
+ /test web/src/components/features/EntityList.test.tsx
127
+ /test test/
128
+ ```
129
+
130
+ ## Test Fixtures
131
+
132
+ Use ontology-compliant fixtures:
133
+
134
+ ```typescript
135
+ // Test fixture for groups
136
+ const testGroup = {
137
+ _id: "group123" as Id<"groups">,
138
+ name: "Test Organization",
139
+ type: "organization" as const,
140
+ parentGroupId: undefined,
141
+ properties: { plan: "starter" as const },
142
+ status: "active" as const,
143
+ createdAt: Date.now(),
144
+ updatedAt: Date.now(),
145
+ };
146
+
147
+ // Test fixture for things
148
+ const testEntity = {
149
+ _id: "entity123" as Id<"things">,
150
+ groupId: testGroup._id,
151
+ type: "user",
152
+ name: "Test User",
153
+ properties: { email: "test@example.com" },
154
+ status: "active" as const,
155
+ createdAt: Date.now(),
156
+ updatedAt: Date.now(),
157
+ };
158
+ ```
159
+
160
+ ## Common Test Patterns
161
+
162
+ ### Testing Multi-tenant Isolation
163
+ ```typescript
164
+ test("should only return entities for specified group", async () => {
165
+ const group1Entities = await ctx.runQuery(api.queries.entities.list, {
166
+ groupId: group1._id,
167
+ });
168
+ const group2Entities = await ctx.runQuery(api.queries.entities.list, {
169
+ groupId: group2._id,
170
+ });
171
+
172
+ expect(group1Entities).not.toContainEqual(group2Entities[0]);
173
+ });
174
+ ```
175
+
176
+ ### Testing Event Logging
177
+ ```typescript
178
+ test("should log event on entity creation", async () => {
179
+ await ctx.runMutation(api.mutations.entities.create, args);
180
+
181
+ const events = await ctx.runQuery(api.queries.events.list, {
182
+ type: "entity_created",
183
+ });
184
+
185
+ expect(events).toHaveLength(1);
186
+ expect(events[0].actorId).toBeDefined();
187
+ });
188
+ ```
189
+
190
+ ## Test Quality Standards
191
+
192
+ - ✓ **Descriptive names**: Test names explain intent clearly
193
+ - ✓ **Single assertion**: One test, one thing (mostly)
194
+ - ✓ **Isolated**: Tests don't depend on each other
195
+ - ✓ **Fast**: Unit tests run in milliseconds
196
+ - ✓ **Deterministic**: Same input → same output
197
+ - ✓ **Ontology-aware**: Validate dimension compliance
@@ -0,0 +1,140 @@
1
+ # /validate - 6-dimension structure validation
2
+
3
+ Validate `$ARGUMENTS` against the 6-dimension ontology specification (Version 1.0.0).
4
+
5
+ ## Validation Checklist
6
+
7
+ ### 1. Groups Dimension
8
+ - ✓ All groups have required fields: name, type, status, timestamps
9
+ - ✓ Group types are valid: friend_circle, business, community, dao, government, organization
10
+ - ✓ Parent-child relationships are valid (parentGroupId references exist)
11
+ - ✓ Hierarchical nesting makes sense (no circular references)
12
+ - ✓ Organization groups have plan: starter/pro/enterprise
13
+
14
+ ### 2. People Dimension
15
+ - ✓ People represented as things with `type: 'creator'`
16
+ - ✓ Role metadata exists: platform_owner, org_owner, org_user, customer
17
+ - ✓ Every action has an actor (person)
18
+ - ✓ Authorization checks use role-based access control
19
+
20
+ ### 3. Things Dimension
21
+ - ✓ All things have groupId (multi-tenant scope)
22
+ - ✓ Entity types from 66+ defined types
23
+ - ✓ Required fields: name, type, status, groupId, timestamps
24
+ - ✓ Status lifecycle valid: draft → active → published → archived
25
+ - ✓ Properties field contains type-specific data
26
+ - ✓ No orphaned entities (groupId references exist)
27
+
28
+ ### 4. Connections Dimension
29
+ - ✓ Connection types from 25+ defined types
30
+ - ✓ Required fields: fromId, toId, type, groupId, timestamps
31
+ - ✓ Bidirectional relationships maintained
32
+ - ✓ Temporal validity (validFrom/validTo) if applicable
33
+ - ✓ Both entities exist (no broken references)
34
+ - ✓ Scoped to correct group
35
+
36
+ ### 5. Events Dimension
37
+ - ✓ Event types from 67+ defined types
38
+ - ✓ Required fields: type, actorId, targetId, timestamp, groupId
39
+ - ✓ Complete audit trail (actor → action → target)
40
+ - ✓ Metadata includes protocol info (for consolidated events)
41
+ - ✓ Immutable (no updates, only inserts)
42
+ - ✓ Chronological ordering
43
+
44
+ ### 6. Knowledge Dimension
45
+ - ✓ Labels exist and are categorized
46
+ - ✓ Embeddings have proper vector dimensions
47
+ - ✓ Linked to things via junction table
48
+ - ✓ Scoped to groups (groupId)
49
+ - ✓ Supports semantic search patterns
50
+
51
+ ## Multi-tenant Validation
52
+
53
+ ### Data Isolation
54
+ - ✓ All queries filter by groupId
55
+ - ✓ No cross-group data access without hierarchy
56
+ - ✓ Parent groups can access child data (if configured)
57
+ - ✓ Each group has independent data, billing, quotas
58
+
59
+ ### Schema Compliance
60
+ - ✓ All dimensions include groupId field
61
+ - ✓ Indexes include groupId for query performance
62
+ - ✓ Foreign key references are valid
63
+
64
+ ## Output Format
65
+
66
+ ```
67
+ ONTOLOGY VALIDATION: [component/file name]
68
+
69
+ DIMENSION COMPLIANCE:
70
+
71
+ Groups:
72
+ ✓ Valid types and nesting
73
+ ✓ All groups have required fields
74
+ ❌ Issue: [specific violation with line number]
75
+
76
+ People:
77
+ ✓ Role metadata correct
78
+ ⚠️ Warning: [potential issue]
79
+
80
+ Things:
81
+ ✓ All entities have groupId
82
+ ✓ Types from defined schema (66+)
83
+ ❌ Issue: [specific violation]
84
+
85
+ Connections:
86
+ ✓ Types from defined schema (25+)
87
+ ✓ No broken references
88
+
89
+ Events:
90
+ ✓ Types from defined schema (67+)
91
+ ✓ Complete audit trail
92
+ ⚠️ Warning: [missing event logging]
93
+
94
+ Knowledge:
95
+ ✓ Labels and embeddings valid
96
+ ✓ Properly linked
97
+
98
+ MULTI-TENANT SAFETY:
99
+ ✓ All queries filter by groupId
100
+ ✓ No data leakage across groups
101
+
102
+ VIOLATIONS FOUND: [count]
103
+ WARNINGS: [count]
104
+
105
+ REMEDIATION STEPS:
106
+ 1. [Specific fix with code example]
107
+ 2. [Specific fix with code example]
108
+
109
+ STATUS: [VALID / NEEDS FIXES / CRITICAL ISSUES]
110
+ ```
111
+
112
+ ## Example Usage
113
+
114
+ ```bash
115
+ /validate backend/convex/schema.ts
116
+ /validate backend/convex/mutations/entities.ts
117
+ /validate backend/convex/
118
+ ```
119
+
120
+ ## Validation Levels
121
+
122
+ - **Critical**: Data integrity, multi-tenant violations, missing groupId
123
+ - **Error**: Schema violations, invalid types, broken references
124
+ - **Warning**: Missing event logging, suboptimal patterns
125
+ - **Info**: Suggestions for improvement
126
+
127
+ ## Auto-remediation
128
+
129
+ For common violations, provide auto-fix code snippets:
130
+
131
+ ```typescript
132
+ // Before (missing groupId filter)
133
+ const entities = await ctx.db.query("things").collect();
134
+
135
+ // After (multi-tenant safe)
136
+ const entities = await ctx.db
137
+ .query("things")
138
+ .withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
139
+ .collect();
140
+ ```
@@ -0,0 +1,106 @@
1
+ #!/bin/bash
2
+ #
3
+ # Auto-Format Hook for ONE Platform
4
+ #
5
+ # Automatically formats files based on extension after Edit/Write operations:
6
+ # - TypeScript/JavaScript: Prettier
7
+ # - Astro: astro check --fix
8
+ # - JSON: Prettier
9
+ # - CSS/SCSS: Prettier
10
+ #
11
+
12
+ set -e
13
+
14
+ # ANSI color codes
15
+ GREEN='\033[92m'
16
+ YELLOW='\033[93m'
17
+ RED='\033[91m'
18
+ BLUE='\033[94m'
19
+ RESET='\033[0m'
20
+
21
+ # Get file path from environment or command line
22
+ FILE_PATH="${CLAUDE_EDIT_FILE:-${1:-}}"
23
+
24
+ if [ -z "$FILE_PATH" ]; then
25
+ echo -e "${YELLOW}⚠ Auto-Format: No file path provided${RESET}"
26
+ exit 0
27
+ fi
28
+
29
+ if [ ! -f "$FILE_PATH" ]; then
30
+ echo -e "${YELLOW}⚠ Auto-Format: File does not exist: $FILE_PATH${RESET}"
31
+ exit 0
32
+ fi
33
+
34
+ # Get file extension
35
+ EXT="${FILE_PATH##*.}"
36
+ BASENAME=$(basename "$FILE_PATH")
37
+
38
+ # Skip formatting for certain files
39
+ if [[ "$FILE_PATH" == *"node_modules"* ]] || \
40
+ [[ "$FILE_PATH" == *"_generated"* ]] || \
41
+ [[ "$FILE_PATH" == *".git"* ]] || \
42
+ [[ "$FILE_PATH" == *"dist/"* ]] || \
43
+ [[ "$FILE_PATH" == *".next/"* ]]; then
44
+ exit 0
45
+ fi
46
+
47
+ # Format based on extension
48
+ case "$EXT" in
49
+ ts|tsx|js|jsx|json|css|scss)
50
+ # Check if prettier is available
51
+ if command -v prettier &> /dev/null; then
52
+ echo -e "${BLUE}→ Formatting $BASENAME with Prettier...${RESET}"
53
+ prettier --write "$FILE_PATH" --log-level=error 2>&1
54
+ if [ $? -eq 0 ]; then
55
+ echo -e "${GREEN}✓ Formatted: $BASENAME${RESET}"
56
+ else
57
+ echo -e "${YELLOW}⚠ Prettier formatting failed for $BASENAME${RESET}"
58
+ fi
59
+ elif [ -f "web/package.json" ] && grep -q "prettier" "web/package.json"; then
60
+ # Try using bun/npm from web directory
61
+ cd web
62
+ echo -e "${BLUE}→ Formatting $BASENAME with Prettier (via bun)...${RESET}"
63
+ bun run prettier --write "../$FILE_PATH" --log-level=error 2>&1 || true
64
+ if [ $? -eq 0 ]; then
65
+ echo -e "${GREEN}✓ Formatted: $BASENAME${RESET}"
66
+ fi
67
+ cd ..
68
+ fi
69
+ ;;
70
+
71
+ astro)
72
+ # Check if in web directory for astro check
73
+ if [[ "$FILE_PATH" == *"/web/"* ]] && [ -f "web/package.json" ]; then
74
+ cd web
75
+ echo -e "${BLUE}→ Checking $BASENAME with Astro...${RESET}"
76
+ bunx astro check --minimumSeverity warning 2>&1 | grep -v "Getting diagnostics" || true
77
+ if [ $? -eq 0 ]; then
78
+ echo -e "${GREEN}✓ Astro check: $BASENAME${RESET}"
79
+ fi
80
+ cd ..
81
+ fi
82
+
83
+ # Also run prettier on .astro files
84
+ if command -v prettier &> /dev/null; then
85
+ prettier --write "$FILE_PATH" --log-level=error 2>&1 || true
86
+ fi
87
+ ;;
88
+
89
+ md|mdx)
90
+ # Format markdown with prettier if available
91
+ if command -v prettier &> /dev/null; then
92
+ echo -e "${BLUE}→ Formatting $BASENAME with Prettier...${RESET}"
93
+ prettier --write "$FILE_PATH" --log-level=error 2>&1 || true
94
+ if [ $? -eq 0 ]; then
95
+ echo -e "${GREEN}✓ Formatted: $BASENAME${RESET}"
96
+ fi
97
+ fi
98
+ ;;
99
+
100
+ *)
101
+ # Skip other file types
102
+ exit 0
103
+ ;;
104
+ esac
105
+
106
+ exit 0
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Formatting Hook - ONE Platform
4
+ PostToolUse hook that auto-formats TypeScript, Astro, and React files
5
+
6
+ Triggered after: Edit, Write tools
7
+ Formats: .ts, .tsx, .astro files using prettier
8
+ Also formats: .json, .css files
9
+
10
+ Uses prettier with ONE Platform configuration:
11
+ - Tailwind v4 CSS formatting
12
+ - TypeScript strict mode
13
+ - React 19 JSX
14
+ - Astro 5 syntax
15
+
16
+ Exit Codes:
17
+ 0 - Formatting completed successfully or not needed
18
+ 1 - Formatting failed (should not block workflow)
19
+ """
20
+ import json
21
+ import sys
22
+ import os
23
+ import subprocess
24
+ from pathlib import Path
25
+
26
+ # File extensions to format
27
+ FORMATTABLE_EXTENSIONS = {
28
+ '.ts', '.tsx', '.astro', '.json', '.css', '.js', '.jsx', '.md'
29
+ }
30
+
31
+ # Files to skip (generated or config)
32
+ SKIP_PATTERNS = [
33
+ '_generated',
34
+ 'node_modules',
35
+ '.next',
36
+ 'dist',
37
+ 'build',
38
+ '.astro',
39
+ 'package-lock.json',
40
+ 'bun.lockb'
41
+ ]
42
+
43
+ def should_format(file_path: str) -> bool:
44
+ """Check if file should be formatted"""
45
+ # Check extension
46
+ ext = Path(file_path).suffix
47
+ if ext not in FORMATTABLE_EXTENSIONS:
48
+ return False
49
+
50
+ # Skip generated files and dependencies
51
+ for pattern in SKIP_PATTERNS:
52
+ if pattern in file_path:
53
+ return False
54
+
55
+ return True
56
+
57
+ def format_file(file_path: str) -> tuple[bool, str]:
58
+ """
59
+ Format file using prettier
60
+
61
+ Returns:
62
+ (success, message)
63
+ """
64
+ if not os.path.exists(file_path):
65
+ return True, "File does not exist (may have been deleted)"
66
+
67
+ try:
68
+ # Determine parser based on extension
69
+ ext = Path(file_path).suffix
70
+ parser_map = {
71
+ '.ts': 'typescript',
72
+ '.tsx': 'typescript',
73
+ '.astro': 'astro',
74
+ '.json': 'json',
75
+ '.css': 'css',
76
+ '.js': 'babel',
77
+ '.jsx': 'babel',
78
+ '.md': 'markdown'
79
+ }
80
+ parser = parser_map.get(ext, 'typescript')
81
+
82
+ # Run prettier
83
+ result = subprocess.run(
84
+ ['prettier', '--write', '--parser', parser, file_path],
85
+ capture_output=True,
86
+ text=True,
87
+ timeout=10
88
+ )
89
+
90
+ if result.returncode == 0:
91
+ return True, f"✅ Formatted: {file_path}"
92
+ else:
93
+ # Prettier errors are warnings, not failures
94
+ return True, f"⚠️ Prettier warning: {result.stderr.strip()}"
95
+
96
+ except FileNotFoundError:
97
+ # Prettier not installed - not a blocker
98
+ return True, "⚠️ Prettier not installed (npm install -g prettier)"
99
+ except subprocess.TimeoutExpired:
100
+ return True, f"⚠️ Formatting timeout: {file_path}"
101
+ except Exception as e:
102
+ return True, f"⚠️ Formatting error: {str(e)}"
103
+
104
+ def check_imports(file_path: str) -> tuple[bool, list[str]]:
105
+ """
106
+ Check import organization and suggest improvements
107
+
108
+ Returns:
109
+ (is_organized, suggestions)
110
+ """
111
+ suggestions = []
112
+
113
+ try:
114
+ with open(file_path, 'r') as f:
115
+ content = f.read()
116
+
117
+ # Check for React 19 edge imports
118
+ if 'react-dom/server' in content and 'react-dom/server.edge' not in content:
119
+ if file_path.endswith('.astro') or 'ssr' in content.lower():
120
+ suggestions.append("💡 Use 'react-dom/server.edge' for Cloudflare Pages SSR")
121
+
122
+ # Check for proper path aliases
123
+ if '../' * 3 in content: # More than 2 levels up
124
+ suggestions.append("💡 Use path alias '@/' instead of '../../../'")
125
+
126
+ # Check for Convex direct imports in frontend components
127
+ if 'web/src/components' in file_path:
128
+ if 'from "convex"' in content or "from 'convex'" in content:
129
+ suggestions.append("💡 Import Convex hooks from '@/services' layer, not directly")
130
+
131
+ # Check for missing nanostores in frontend-only apps
132
+ if 'web/src/' in file_path and 'useState' in content:
133
+ if 'nanostores' not in content and 'convex' not in content:
134
+ suggestions.append("💡 Consider using nanostores for persistent state (frontend-only)")
135
+
136
+ except Exception:
137
+ pass
138
+
139
+ return len(suggestions) == 0, suggestions
140
+
141
+ def main():
142
+ """Main hook entry point"""
143
+ try:
144
+ # Read hook event from stdin
145
+ hook_event = json.loads(sys.stdin.read())
146
+
147
+ # Extract file path
148
+ tool_name = hook_event.get("tool_name", "")
149
+ tool_input = hook_event.get("tool_input", {})
150
+
151
+ # Only run on Edit and Write operations
152
+ if tool_name not in ["Edit", "Write"]:
153
+ sys.exit(0)
154
+
155
+ file_path = tool_input.get("file_path", "")
156
+
157
+ # Check if we should format this file
158
+ if not should_format(file_path):
159
+ sys.exit(0)
160
+
161
+ # Format the file
162
+ success, message = format_file(file_path)
163
+
164
+ # Check imports and organization
165
+ is_organized, suggestions = check_imports(file_path)
166
+
167
+ # Print results
168
+ if not success:
169
+ print(message)
170
+ elif suggestions:
171
+ print(f"✅ Formatted: {file_path}")
172
+ print("")
173
+ print("💡 Import Suggestions:")
174
+ for suggestion in suggestions:
175
+ print(f" {suggestion}")
176
+ print("")
177
+
178
+ # Always exit 0 (formatting issues are warnings, not blockers)
179
+ sys.exit(0)
180
+
181
+ except Exception as e:
182
+ # Don't fail the workflow on hook errors
183
+ print(f"⚠️ Formatting hook error: {str(e)}", file=sys.stderr)
184
+ sys.exit(0)
185
+
186
+ if __name__ == "__main__":
187
+ main()