Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:39 +08:00
commit d0feb2b434
18 changed files with 2296 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
# Code Comparison
Compare code implementations for equivalence, similarity, or differences with accurate classification.
## Comparison Dimensions
| Dimension | Question |
|-----------|----------|
| **Behavioral** | Same outputs for same inputs? Same side effects? |
| **Semantic** | Same intent/purpose? Same business logic? |
| **Syntactic** | Similar names, structure, formatting? |
| **Algorithmic** | Same approach? Same complexity (Big O)? |
| **Style** | Functional vs imperative? Recursive vs iterative? |
## Common Scenarios
| Scenario | Focus |
|----------|-------|
| Refactoring | Behavioral equivalence (must match) |
| Bug fix | Specific case differs, normal matches |
| API compat | Signature, returns, errors, side effects |
| Plagiarism | Structure, naming, logic patterns |
## Output Format
Start with **[YES]** or **[NO]** immediately.
Then provide justification with specific examples from both items.
## Analysis Checklist
- [ ] Inputs (same params, types?)
- [ ] Outputs (same returns?)
- [ ] Side effects (same state changes?)
- [ ] Error handling (same exceptions?)
- [ ] Edge cases (null, empty, boundary?)
- [ ] Performance (same complexity?)
## Example
```
[YES] Behaviorally equivalent
Both functions:
1. Return same results for all inputs
2. Handle null by returning empty array
3. Use same filtering logic
The refactoring improves readability (modern array methods) without changing behavior.
```
## Pitfalls
- Don't stop at surface differences (naming != different behavior)
- Check edge cases (factorial(-1) may differ)
- Consider context (Promise vs callback may be equivalent in modern Node)

View File

@@ -0,0 +1,62 @@
# Code Refactoring
Modify code with clean, secure, maintainable changes that precisely meet requirements.
## Workflow
1. **Discover:** Glob for files, Grep for patterns
2. **Read:** Always read before modifying
3. **Modify:** Edit existing (prefer over Write)
4. **Verify:** Run tests
## Rules
| Rule | Details |
|------|---------|
| Read first | Never modify unread files |
| Edit > Write | Use Edit for existing, Write only for new |
| Delete completely | No `_unused` prefixes or `// removed` comments |
| Match style | Follow existing conventions exactly |
| Minimal changes | Only what's requested |
## Security Checklist
**Prevent:**
- Command injection → Use arrays, not string interpolation: `exec('cmd', [args])`
- XSS → Use `textContent`, not `innerHTML`
- SQL injection → Use parameterized queries
- Path traversal → Validate with `path.basename()`
## Tool Usage
```
Glob: pattern: "**/*.js" # Find files
Grep: pattern: "func", output_mode: "files_with_matches" # Search
Read: file_path: "/path/file.js" # Read before edit
Edit: file_path, old_string, new_string # Modify
```
Parallelize independent Read calls. Chain sequentially: Read → Edit → Bash (test).
## Quality
- Three similar lines > premature abstraction
- Meaningful names, focused functions
- Comments only where logic isn't obvious
- Refactor only when explicitly requested
## Example
```javascript
// Before: Bug - off-by-one error
function getLastItem(arr) {
return arr[arr.length] // Wrong: returns undefined
}
// After: Fix
function getLastItem(arr) {
return arr[arr.length - 1]
}
```
Change is minimal and targeted - only fix what's requested.

View File

@@ -0,0 +1,58 @@
# Code Review
Provide constructive, actionable feedback on security, correctness, performance, and maintainability.
## Review Dimensions
| Dimension | Key Checks |
|-----------|------------|
| **Security** | Injection (SQL, XSS, command), auth gaps, data exposure, CORS, SSRF |
| **Correctness** | Logic errors, edge cases, race conditions, off-by-one |
| **Performance** | O(n²) loops, N+1 queries, memory leaks, missing indexes |
| **Readability** | Naming, nesting depth, magic numbers, DRY |
| **Error Handling** | Silent swallowing, missing cleanup, unhelpful messages |
| **Testability** | Tight coupling, hidden dependencies, side effects |
## Severity Levels
| Level | Criteria | Action |
|-------|----------|--------|
| 🔴 CRITICAL | Security vulns, data loss, crashes | Block merge |
| 🟠 HIGH | Bugs, performance issues | Fix before merge |
| 🟡 MEDIUM | Code smells, refactoring | Fix soon |
| 🟢 LOW | Style, alternatives | Optional |
## Output Format
```markdown
## Summary
[2-3 sentences: quality, strengths, concerns]
## 🔴 Critical Issues
**Location:** file.js:42
**Issue:** SQL injection
**Impact:** Data breach
**Fix:** Use parameterized query
\`\`\`js
// Before
db.query(`SELECT * FROM users WHERE id = ${id}`)
// After
db.query('SELECT * FROM users WHERE id = ?', [id])
\`\`\`
## 🟠 High Priority
[Same format]
## 🟡/🟢 Other
[Same format]
## ✅ Positive
[Good patterns observed]
```
## Principles
- Specific locations, not vague criticism
- Explain impact, not just what's wrong
- Code examples for fixes
- Balance criticism with recognition

View File

@@ -0,0 +1,51 @@
# Data Extraction
Extract specific information from unstructured/semi-structured data with completeness and accuracy.
## Common Patterns
| Type | Pattern | Validation |
|------|---------|------------|
| Email | `user@domain.ext` | Has `@` and `.` after @ |
| URL | `http(s)://domain...` | Valid protocol and domain |
| Date | ISO, US, EU, timestamp | Valid ranges (month 1-12) |
| Phone | Various formats | 7-15 digits |
| IP | IPv4: `x.x.x.x`, IPv6 | Octets 0-255 |
| Key-Value | `key=value`, `key: value` | Handle quoted/nested |
## Process
1. **Analyze:** Format, delimiters, variations, headers to skip
2. **Extract:** Match all instances, capture context, handle partial matches
3. **Clean:** Trim, normalize (dates to ISO, phones to digits), validate
4. **Format:** Consistent fields, proper escaping, sort/dedupe if needed
## Output Formats
**JSON:** `{"results": [...], "summary": {"total": N, "unique": N}}`
**CSV:** Headers + rows
**Markdown:** Table with headers
**Plain:** Bullet list
## Principles
- **Complete:** Extract ALL matches, don't stop early
- **Accurate:** Preserve exact values, maintain case
- **Handle edge cases:** Missing → null, malformed → flag, duplicates → note
## Output Structure
```
[Extracted data]
## Summary
- Total: X
- Unique: Y
- Issues: Z
## Notes
- Line 42: Partial match "user@" (missing domain)
```

View File

@@ -0,0 +1,64 @@
# Documentation Generator
Create clear, comprehensive documentation matched to audience needs.
## Documentation Types
| Type | Structure |
|------|-----------|
| **API Reference** | Overview → Auth → Endpoints (params, returns, errors) → Examples |
| **README** | Description → Install → Quick Start → Usage → Config |
| **Docstrings** | Summary → Params (type, desc) → Returns → Exceptions → Example |
| **User Guide** | Intro → Prerequisites → Steps → Troubleshooting |
| **Tech Spec** | Overview → Architecture → Data Models → APIs → Security |
## Writing Principles
- **Active voice:** "Returns user" not "User is returned"
- **Examples:** Concrete, runnable, with expected output
- **Complete:** All params, returns, errors documented
- **Consistent:** Same terminology throughout
## Audience Adaptation
| Audience | Focus |
|----------|-------|
| External devs | Complete setup, all public APIs, integration patterns |
| Internal team | Architecture diagrams, "why" decisions, non-obvious behaviors |
| End users | No jargon, screenshots, task-focused, troubleshooting |
## Format Templates
**JSDoc:**
```javascript
/**
* Brief description.
* @param {Type} name - Description
* @returns {Type} Description
* @throws {Error} When condition
*/
```
**Python:**
```python
def func(param: Type) -> Return:
"""Brief description.
Args:
param: Description
Returns:
Description
Raises:
Error: When condition
"""
```
## Checklist
- [ ] All public APIs documented
- [ ] Params have types and descriptions
- [ ] Examples are runnable
- [ ] Edge cases noted
- [ ] Consistent formatting

View File

@@ -0,0 +1,58 @@
# Test Generation
Create thorough, maintainable test suites covering happy paths, edge cases, and error handling.
## Test Design
| Principle | Application |
|-----------|-------------|
| Clear names | `should return X when Y` |
| AAA pattern | Arrange → Act → Assert |
| One behavior | Each test verifies one thing |
| Isolation | No shared state between tests |
| Specific asserts | `toEqual([1,2,3])` not `toBeTruthy()` |
## Coverage Checklist
-**Happy path:** Normal operation
-**Edge cases:** null, empty, 0, -1, MAX_INT, special chars
-**Errors:** Invalid inputs, missing params, exceptions
-**Integration:** External deps mocked
## Framework Quick Reference
| Framework | Structure | Assert | Mock |
|-----------|-----------|--------|------|
| **Jest** | `describe/it` | `expect().toBe/toEqual` | `jest.mock()` |
| **pytest** | `test_name()` | `assert x == y` | `mocker.patch()` |
| **JUnit** | `@Test` | `assertEquals()` | `@Mock` + Mockito |
| **Mocha** | `describe/it` | Chai `expect().to` | Sinon |
| **RSpec** | `describe/it` | `expect().to eq` | `allow().to receive` |
| **Go** | `TestName(t)` | `t.Error()` | Manual/testify |
## Mocking Strategy
**Mock:** API calls, DB, file system, time, external services
**Don't mock:** Simple data, pure functions, code under test
## Example Structure
```javascript
describe('UserService', () => {
describe('createUser', () => {
it('should create user with valid data', () => {
// Arrange
const data = { name: 'John', email: 'john@test.com' }
// Act
const user = createUser(data)
// Assert
expect(user.name).toBe('John')
})
it('should throw when email invalid', () => {
expect(() => createUser({ email: 'bad' })).toThrow(ValidationError)
})
})
})
```