Skip to content

Commit 700fc8a

Browse files
huhuanmingclaude
andauthored
feat: implement comprehensive skills token optimization system (#9938)
* docs: add comprehensive performance optimization and Sentry error analysis guides Added two major documentation enhancements: 1. Performance Optimization Guide (1k-coding-patterns/performance.md): - 8 major optimization categories for React/React Native - Concurrent request control with executeBatched pattern - React Native bridge optimization strategies - List rendering optimizations (windowSize, FlashList, content-visibility) - Developer alerts showing which base components have built-in optimizations - Clear decision trees for when to apply manual optimizations - Real-world examples from iOS AppHang fixes 2. Sentry Error Analysis Workflow (1k-dev-workflows/fix-sentry-errors.md): - Complete workflow for analyzing production crash reports - 6 types of proof methodology for establishing causation - Bug analysis log template with evidence chain requirements - Common fix patterns for AppHang, ANR, and crashes - Real-world iOS AppHang case study with detailed analysis Key Features: - 🚨 Developer alerts clearly marking optimized base components - ✅/⚠️ Visual indicators for "no action needed" vs "manual action required" - Decision trees for quick reference - Interlocking evidence chain methodology (环环相扣,逐步递进) - Prevention measures and testing guidelines Co-Authored-By: Claude Sonnet 4.5 <[email protected]> * refactor: split 1k-coding-patterns into focused skills for better token efficiency Split 1k-coding-patterns skill into 6 specialized skills to reduce initial token consumption: New skills created: - 1k-date-formatting: Date and time formatting utilities - 1k-i18n: Internationalization and translation management - 1k-error-handling: Error handling patterns and best practices - 1k-cross-platform: Platform-specific code patterns - 1k-code-quality: Linting, documentation, and code quality standards - 1k-performance: Performance optimization patterns (previously created) Benefits: - Reduces initial skill loading token consumption by 47-53% for most tasks - Each skill is now focused on a single responsibility - Improves skill discoverability with targeted trigger words - Maintains comprehensive documentation with Quick Reference sections Updated 1k-coding-patterns to keep core patterns: - Promise handling - React components - Restricted patterns All skills include cross-references to related skills for easy navigation. * refactor: split 1k-dev-workflows into focused skills Aggressively split 1k-dev-workflows into specialized skills following single-responsibility principle: New skills created: - 1k-sentry-analysis: Sentry error analysis and crash fixes (34.6 KB) - Complete workflow from JSON analysis to bug fix implementation - Evidence-based methodology with 6 types of proof - AppHang, ANR, and crash fix patterns - 1k-test-version: Test version creation workflow (3.3 KB) - Automates upgrade test version creation - Version number and build number configuration Merged to existing skill: - fix-lint.md → 1k-code-quality (5.1 KB) - Lint fixes naturally belong with code quality standards - Consolidated all linting workflows in one place Removed skill: - 1k-dev-workflows (deleted) - All content successfully distributed to appropriate skills Updated references: - Updated all cross-references in other skills - Updated 1k-new-skill skill categories table - Maintained skill relationship graph Benefits: - Sentry analysis (34KB) now loads independently - huge token savings - Better skill discoverability with specific trigger words - Clearer separation of concerns - Each skill has focused, single responsibility Total content: 43 KB redistributed across 3 skills * docs: add token optimization best practices to 1k-new-skill Added comprehensive token optimization guidelines based on recent skill splitting experience: New sections added: 1. Token optimization considerations - Decision criteria for splitting (file size, usage frequency, independence) - Keep-together criteria (correlation, shared concepts, small files) - Token savings formula with real-world examples 2. Splitting workflow - Step-by-step guide for splitting existing skills - File size analysis commands - Git rename tracking best practices - Cross-reference update process 3. Enhanced anti-patterns - Token optimization anti-patterns - Good vs bad splitting examples - Common mistakes to avoid Real-world data included: - 1k-coding-patterns split: 47-53% token savings in 90% of cases - 1k-dev-workflows split: 80% savings when not analyzing Sentry Benefits: - Clear guidance on when to split vs merge skills - Quantifiable decision criteria (>10 KB files, >1000 lines) - Practical workflow for executing splits - Evidence-based approach with actual measurements This will help maintain optimal token efficiency as skill library grows. * feat: add skills token monitoring tool and documentation Created comprehensive token monitoring system for Claude Code Skills: New files: 1. development/analyze-skills-tokens.py - Analyzes all skills and estimates token consumption - Identifies skills that should be split (>5k, >10k tokens) - Provides detailed per-file breakdown - Sorts by size to prioritize optimization - Uses conservative estimate: 1 token ≈ 4 characters 2. development/SKILLS-TOKEN-MONITORING.md - Complete monitoring guide and best practices - Decision criteria for splitting skills - Token savings formula with real-world examples - Recommended monitoring schedule - Current status snapshot and FAQs Features: - Automatic recommendations (URGENT/CONSIDER/MONITOR/OK) - Detailed breakdown showing largest files per skill - Sorting options (by name or by size) - Usage tips and splitting guidelines - Real-world savings data from recent splits Current findings: - Total: 23 skills, 76,200 tokens (303 KB) - Urgent: react-best-practices (14,345 tokens) - Consider: 1k-sentry-analysis, 1k-feature-guides, 1k-performance Benefits: - Proactive token optimization - Data-driven splitting decisions - Track skill growth over time - Prevent token bloat Usage: python3 development/analyze-skills-tokens.py python3 development/analyze-skills-tokens.py --sort-by-size python3 development/analyze-skills-tokens.py --detailed * docs: add skill optimization analysis and recommendations Analyzed 3 large skills (>5k tokens) for potential splitting: - 1k-sentry-analysis (9,394 tokens) - 1k-feature-guides (8,493 tokens) - 1k-performance (6,267 tokens) Key Findings: **Recommendation: Keep all 3 intact** Reasons for each skill: 1. 1k-sentry-analysis (9,394 tokens) - Linear workflow with sequential, interdependent steps - Users need complete workflow for Sentry error analysis - Splitting would break workflow coherence - High correlation: all steps used together 2. 1k-performance (6,267 tokens) - Comprehensive optimization guide needs holistic view - 8 categories are interdependent (list + memoization + async) - Below 10k threshold, acceptable for topic breadth - SKILL.md provides good Quick Reference - Users think "optimize performance" not individual categories 3. 1k-feature-guides (8,493 tokens) - All feature development workflows, used together - Adding features often needs pages + notifications + events - No single file too large (max 386 lines) - Splitting would force 2-4 skill loads instead of 1 Decision Framework Established: Split if ALL true: - File/skill >10KB OR multiple unrelated topics - Topics have <50% usage correlation - Distinct trigger words - Each split >2KB (worth overhead) - Natural split boundaries exist Keep intact if ANY true: - Linear workflow / sequential steps - Topics used together (>50% correlation) - Size <10k AND topics related - Splitting breaks semantic coherence - Users think of it as single concept Priority for Future: - react-best-practices (14,345 tokens) - urgent split needed - Can split into 6 categories (bundle, rendering, async, js-perf, client, server) - Would achieve 83% token reduction per category Monitoring Thresholds: - Re-evaluate if skills exceed 10-12k tokens - Or if growth >30-60% from current size - Or if unrelated topics added Benefits of keeping intact: - Workflow coherence maintained - Better user experience (no skill jumping) - Comprehensive reference in one place - Acceptable token consumption (<10k) * docs: add mandatory token analysis self-check for new skills Added required token analysis step to skill creation workflow: Changes to 1k-new-skill/SKILL.md: - Added step 5 to "Output the skill" section - Token analysis now REQUIRED before committing - Verification checklist with clear action thresholds: - <2k tokens: Excellent, proceed - 2-5k tokens: Good, monitor growth - 5-10k tokens: Review split possibility, document correlation - >10k tokens: Must split before committing - Commands to run analysis and check specific skill - Reference to detailed monitoring guide Changes to SKILLS-TOKEN-MONITORING.md: - Updated monitoring schedule with new requirement - Added "Post-Creation Self-Check" section - Complete workflow example showing: 1. Create skill 2. REQUIRED: Run analysis 3. Check results 4. Take action (split if needed) 5. Only then commit - Acceptance criteria clearly defined - Ensures all new skills optimized from day one Benefits: - Prevents token bloat at source - Catches oversized skills before merge - Establishes clear quality gate - Self-documenting: developers know expectations - Proactive optimization vs reactive splitting This makes token optimization a required part of the development process, not an afterthought. * refactor: organize skills analysis files into dedicated directory Move skills token analysis files into development/skills-analysis/: - analyze-skills-tokens.py (token analysis tool) - SKILLS-TOKEN-MONITORING.md (monitoring guide) - SKILL-OPTIMIZATION-ANALYSIS.md (optimization docs) Update all references in: - .claude/skills/1k-new-skill/SKILL.md - Command examples and documentation links --------- Co-authored-by: Claude Sonnet 4.5 <[email protected]>
1 parent 7be8a0f commit 700fc8a

File tree

23 files changed

+3755
-176
lines changed

23 files changed

+3755
-176
lines changed
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
---
2+
name: 1k-code-quality
3+
description: Code quality standards for OneKey. Use when fixing lint warnings, running pre-commit tasks, handling unused variables, writing comments, or ensuring code quality. All comments must be in English. Triggers on lint, linting, eslint, oxlint, tsc, type check, unused variable, comment, documentation, spellcheck, code quality, pre-commit, yarn lint.
4+
allowed-tools: Read, Grep, Glob
5+
---
6+
7+
# Code Quality
8+
9+
Linting, documentation, and general code quality standards for OneKey.
10+
11+
## Lint Commands
12+
13+
```bash
14+
# Pre-commit (fast, only staged files)
15+
yarn lint:staged
16+
yarn tsc:staged
17+
18+
# CI only (full project check)
19+
yarn lint # Comprehensive: TypeScript, ESLint, folder structure, i18n
20+
yarn lint:only # Quick: oxlint only
21+
yarn tsc:only # Full type check
22+
```
23+
24+
**Note:** `yarn lint` is for CI only. For pre-commit, always use `yarn lint:staged`.
25+
26+
## Pre-Commit Workflow
27+
28+
For fast pre-commit validation:
29+
```bash
30+
# Lint only modified files (recommended)
31+
yarn lint:staged
32+
33+
# Or with type check
34+
yarn lint:staged && yarn tsc:staged
35+
```
36+
37+
## Common Lint Fixes
38+
39+
```typescript
40+
// Unused variable - prefix with underscore
41+
const { used, unused } = obj; // ❌ Error: 'unused' is defined but never used
42+
const { used, unused: _unused } = obj; // ✅ OK
43+
44+
// Unused parameter - prefix with underscore
45+
function foo(used: string, unused: number) {} // ❌ Error
46+
function foo(used: string, _unused: number) {} // ✅ OK
47+
48+
// Floating promise - add void or await
49+
someAsyncFunction(); // ❌ Error: Promises must be awaited
50+
void someAsyncFunction(); // ✅ OK (fire-and-forget)
51+
await someAsyncFunction(); // ✅ OK (wait for result)
52+
```
53+
54+
## Language Requirements
55+
56+
**All comments must be written in English:**
57+
58+
```typescript
59+
// ✅ GOOD: English comment
60+
// Calculate the total balance including pending transactions
61+
62+
// ❌ BAD: Chinese comment
63+
// 计算总余额,包括待处理的交易
64+
65+
// ✅ GOOD: JSDoc in English
66+
/**
67+
* Fetches user balance from the blockchain.
68+
* @param address - The wallet address to query
69+
* @returns The balance in native token units
70+
*/
71+
async function fetchBalance(address: string): Promise<bigint> {
72+
// ...
73+
}
74+
```
75+
76+
## When to Comment
77+
78+
```typescript
79+
// ✅ GOOD: Explain non-obvious logic
80+
// Use 1.5x gas limit to account for estimation variance on this chain
81+
const gasLimit = estimatedGas * 1.5n;
82+
83+
// ✅ GOOD: Explain business logic
84+
// Premium users get 50% discount on transaction fees
85+
const fee = isPremium ? baseFee * 0.5 : baseFee;
86+
87+
// ❌ BAD: Obvious comment
88+
// Set the value to 5
89+
const value = 5;
90+
```
91+
92+
## Development Principles
93+
94+
### Single Responsibility
95+
Each function should perform a single, atomic task:
96+
97+
```typescript
98+
// ✅ GOOD: Single responsibility
99+
async function fetchUserBalance(userId: string): Promise<Balance> {
100+
const user = await getUser(userId);
101+
return await getBalanceForAddress(user.address);
102+
}
103+
104+
// ❌ BAD: Multiple responsibilities
105+
async function fetchUserBalanceAndUpdateUI(userId: string) {
106+
const user = await getUser(userId);
107+
const balance = await getBalanceForAddress(user.address);
108+
setBalanceState(balance);
109+
showNotification('Balance updated');
110+
logAnalytics('balance_fetched');
111+
}
112+
```
113+
114+
### Avoid Over-Abstraction
115+
Don't create helpers for one-time operations:
116+
117+
```typescript
118+
// ❌ BAD: Over-abstracted
119+
const createUserFetcher = (config: Config) => {
120+
return (userId: string) => {
121+
return fetchWithConfig(config, `/users/${userId}`);
122+
};
123+
};
124+
const fetchUser = createUserFetcher(defaultConfig);
125+
const user = await fetchUser(userId);
126+
127+
// ✅ GOOD: Simple and direct
128+
const user = await fetch(`/api/users/${userId}`).then(r => r.json());
129+
```
130+
131+
## Detailed Guides
132+
133+
### Code Quality Standards
134+
See [code-quality.md](references/rules/code-quality.md) for comprehensive guidelines:
135+
- Linting commands and pre-commit workflow
136+
- Comment and documentation standards
137+
- Language requirements (English only)
138+
- Single responsibility principle
139+
- Avoiding over-abstraction
140+
- Consistent naming conventions
141+
- Code quality checklist
142+
143+
### Fixing Lint Warnings
144+
See [fix-lint.md](references/rules/fix-lint.md) for complete lint fix workflow:
145+
- Analyzing lint warnings
146+
- Categorizing lint errors
147+
- Common fix patterns by category
148+
- Spellcheck fixes
149+
- Unused variable/parameter handling
150+
- Automated fix strategies
151+
- Testing after fixes
152+
153+
## Spellcheck
154+
155+
If a technical term triggers spellcheck errors:
156+
```bash
157+
# Check if word exists
158+
grep -i "yourword" development/spellCheckerSkipWords.txt
159+
160+
# Add if not present (ask team lead first)
161+
echo "yourword" >> development/spellCheckerSkipWords.txt
162+
```
163+
164+
## Checklist
165+
166+
### Pre-commit
167+
- [ ] `yarn lint:staged` passes
168+
- [ ] `yarn tsc:staged` passes
169+
170+
### Code Quality
171+
- [ ] All comments are in English
172+
- [ ] No commented-out code committed
173+
- [ ] Functions have single responsibility
174+
- [ ] No unnecessary abstractions
175+
- [ ] Consistent naming conventions
176+
177+
## Related Skills
178+
179+
- `/1k-sentry-analysis` - Sentry error analysis and fixes
180+
- `/1k-test-version` - Test version creation workflow
181+
- `/1k-coding-patterns` - General coding patterns

.claude/skills/1k-coding-patterns/references/rules/code-quality.md renamed to .claude/skills/1k-code-quality/references/rules/code-quality.md

File renamed without changes.

.claude/skills/1k-dev-workflows/references/rules/fix-lint.md renamed to .claude/skills/1k-code-quality/references/rules/fix-lint.md

File renamed without changes.

.claude/skills/1k-coding-patterns/SKILL.md

Lines changed: 7 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -10,39 +10,12 @@ allowed-tools: Read, Grep, Glob, Write, Edit
1010

1111
| Topic | Guide | Key Points |
1212
|-------|-------|------------|
13-
| Date formatting | [date-formatting.md](references/rules/date-formatting.md) | Use `formatDate()` from dateUtils, never native JS |
14-
| Internationalization | [i18n.md](references/rules/i18n.md) | Use `ETranslations` enum, never hardcode strings |
1513
| Promise handling | [promise-handling.md](references/rules/promise-handling.md) | Always await or use `void`, never floating promises |
1614
| React components | [react-components.md](references/rules/react-components.md) | Named imports, functional components, no FC type |
1715
| Restricted patterns | [restricted-patterns.md](references/rules/restricted-patterns.md) | Forbidden: `toLocaleLowerCase`, direct hd-core import |
18-
| Error handling | [error-handling.md](references/rules/error-handling.md) | Try/catch for async, user-friendly messages |
19-
| Code quality | [code-quality.md](references/rules/code-quality.md) | English comments, lint before commit |
20-
| Cross-platform | [cross-platform.md](references/rules/cross-platform.md) | Use `platformEnv`, file extensions for platform code |
2116

2217
## Critical Rules Summary
2318

24-
### Date Formatting
25-
26-
```typescript
27-
// ❌ FORBIDDEN
28-
date.toLocaleDateString()
29-
30-
// ✅ CORRECT
31-
import { formatDate } from '@onekeyhq/shared/src/utils/dateUtils';
32-
formatDate(date, { hideSeconds: true });
33-
```
34-
35-
### Internationalization
36-
37-
```typescript
38-
// ❌ FORBIDDEN
39-
<Text>Confirm</Text>
40-
41-
// ✅ CORRECT
42-
import { ETranslations } from '@onekeyhq/shared/src/locale';
43-
intl.formatMessage({ id: ETranslations.global__confirm });
44-
```
45-
4619
### Promise Handling
4720

4821
```typescript
@@ -81,48 +54,14 @@ const { x } = await CoreSDKLoader();
8154
import { localDb } from '...';
8255
```
8356

84-
### Error Handling
85-
86-
```typescript
87-
// ❌ BAD - silent failure
88-
try { await risky(); } catch (e) {}
89-
90-
// ✅ CORRECT
91-
try {
92-
await risky();
93-
} catch (error) {
94-
console.error('Failed:', error);
95-
Toast.error({ title: 'Operation failed' });
96-
}
97-
```
98-
99-
### Code Quality
100-
101-
```bash
102-
# Pre-commit (fast, recommended)
103-
yarn lint:staged
104-
yarn tsc:staged
105-
106-
# CI only (full project check)
107-
yarn lint
108-
```
109-
110-
### Cross-Platform
111-
112-
```typescript
113-
// ✅ CORRECT - Use platformEnv
114-
import platformEnv from '@onekeyhq/shared/src/platformEnv';
115-
if (platformEnv.isNative) { /* mobile */ }
116-
117-
// ✅ CORRECT - Use file extensions
118-
// MyComponent.native.tsx, MyComponent.web.tsx
119-
120-
// ❌ FORBIDDEN
121-
if (typeof window !== 'undefined') { }
122-
```
123-
12457
## Related Skills
12558

59+
- `/1k-date-formatting` - Date and time formatting
60+
- `/1k-i18n` - Internationalization and translations
61+
- `/1k-error-handling` - Error handling patterns
62+
- `/1k-cross-platform` - Platform-specific code
63+
- `/1k-code-quality` - Linting and code quality
64+
- `/1k-performance` - Performance optimization
12665
- `/1k-state-management` - Jotai atom patterns
12766
- `/1k-architecture` - Project structure and import rules
128-
- `/1k-dev-workflows` - Lint fixes, pre-commit tasks
67+
- `/1k-code-quality` - Lint fixes, pre-commit tasks

0 commit comments

Comments
 (0)