code-deduplication

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Deduplication Skill

代码去重技能

Load with: base.md
Purpose: Prevent semantic duplication and code bloat. Maintain a capability index so Claude always knows what exists before writing something new.

加载方式:base.md
目的: 避免语义重复与代码冗余。维护一个能力索引,让Claude在编写新内容前始终了解已有的功能。

Core Philosophy

核心理念

┌─────────────────────────────────────────────────────────────────┐
│  CHECK BEFORE YOU WRITE                                         │
│  ─────────────────────────────────────────────────────────────  │
│  AI doesn't copy/paste - it reimplements.                       │
│  The problem isn't duplicate code, it's duplicate PURPOSE.      │
│                                                                 │
│  Before writing ANY new function:                               │
│  1. Check CODE_INDEX.md for existing capabilities               │
│  2. Search codebase for similar functionality                   │
│  3. Extend existing code if possible                            │
│  4. Only create new if nothing suitable exists                  │
├─────────────────────────────────────────────────────────────────┤
│  AFTER WRITING: Update the index immediately.                   │
│  PERIODICALLY: Run /audit-duplicates to catch overlap.          │
└─────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────┐
│  CHECK BEFORE YOU WRITE                                         │
│  ─────────────────────────────────────────────────────────────  │
│  AI doesn't copy/paste - it reimplements.                       │
│  The problem isn't duplicate code, it's duplicate PURPOSE.      │
│                                                                 │
│  Before writing ANY new function:                               │
│  1. Check CODE_INDEX.md for existing capabilities               │
│  2. Search codebase for similar functionality                   │
│  3. Extend existing code if possible                            │
│  4. Only create new if nothing suitable exists                  │
├─────────────────────────────────────────────────────────────────┤
│  AFTER WRITING: Update the index immediately.                   │
│  PERIODICALLY: Run /audit-duplicates to catch overlap.          │
└─────────────────────────────────────────────────────────────────┘

Code Index Structure

代码索引结构

Maintain
CODE_INDEX.md
in project root, organized by capability not file location:
markdown
undefined
在项目根目录维护
CODE_INDEX.md
,按能力而非文件位置组织:
markdown
undefined

Code Index

Code Index

Last updated: [timestamp] Run
/update-code-index
to regenerate
Last updated: [timestamp] Run
/update-code-index
to regenerate

Quick Reference

Quick Reference

CategoryCountLocation
Date/Time5 functionssrc/utils/dates.ts
Validation8 functionssrc/utils/validate.ts
API Clients12 functionssrc/api/*.ts
Auth6 functionssrc/auth/*.ts

CategoryCountLocation
Date/Time5 functionssrc/utils/dates.ts
Validation8 functionssrc/utils/validate.ts
API Clients12 functionssrc/api/*.ts
Auth6 functionssrc/auth/*.ts

Date/Time Operations

Date/Time Operations

FunctionLocationDoes WhatParams
formatDate()
utils/dates.ts:15Formats Date → "Jan 15, 2024"
(date: Date, format?: string)
formatRelative()
utils/dates.ts:32Formats Date → "2 days ago"
(date: Date)
parseDate()
utils/dates.ts:48Parses string → Date
(str: string, format?: string)
isExpired()
auth/tokens.ts:22Checks if timestamp past now
(timestamp: number)
addDays()
utils/dates.ts:61Adds days to date
(date: Date, days: number)

FunctionLocationDoes WhatParams
formatDate()
utils/dates.ts:15Formats Date → "Jan 15, 2024"
(date: Date, format?: string)
formatRelative()
utils/dates.ts:32Formats Date → "2 days ago"
(date: Date)
parseDate()
utils/dates.ts:48Parses string → Date
(str: string, format?: string)
isExpired()
auth/tokens.ts:22Checks if timestamp past now
(timestamp: number)
addDays()
utils/dates.ts:61Adds days to date
(date: Date, days: number)

Validation

Validation

FunctionLocationDoes WhatParams
isEmail()
utils/validate.ts:10Validates email format
(email: string)
isPhone()
utils/validate.ts:25Validates phone with country
(phone: string, country?: string)
isURL()
utils/validate.ts:42Validates URL format
(url: string)
isUUID()
utils/validate.ts:55Validates UUID v4
(id: string)
sanitizeHTML()
utils/sanitize.ts:12Strips XSS from input
(html: string)
sanitizeSQL()
utils/sanitize.ts:28Escapes SQL special chars
(input: string)

FunctionLocationDoes WhatParams
isEmail()
utils/validate.ts:10Validates email format
(email: string)
isPhone()
utils/validate.ts:25Validates phone with country
(phone: string, country?: string)
isURL()
utils/validate.ts:42Validates URL format
(url: string)
isUUID()
utils/validate.ts:55Validates UUID v4
(id: string)
sanitizeHTML()
utils/sanitize.ts:12Strips XSS from input
(html: string)
sanitizeSQL()
utils/sanitize.ts:28Escapes SQL special chars
(input: string)

String Operations

String Operations

FunctionLocationDoes WhatParams
slugify()
utils/strings.ts:8Converts to URL slug
(str: string)
truncate()
utils/strings.ts:20Truncates with ellipsis
(str: string, len: number)
capitalize()
utils/strings.ts:32Capitalizes first letter
(str: string)
pluralize()
utils/strings.ts:40Adds s/es correctly
(word: string, count: number)

FunctionLocationDoes WhatParams
slugify()
utils/strings.ts:8Converts to URL slug
(str: string)
truncate()
utils/strings.ts:20Truncates with ellipsis
(str: string, len: number)
capitalize()
utils/strings.ts:32Capitalizes first letter
(str: string)
pluralize()
utils/strings.ts:40Adds s/es correctly
(word: string, count: number)

API Clients

API Clients

FunctionLocationDoes WhatReturns
fetchUser()
api/users.ts:15GET /users/:id
Promise<User>
fetchUsers()
api/users.ts:28GET /users with pagination
Promise<User[]>
createUser()
api/users.ts:45POST /users
Promise<User>
updateUser()
api/users.ts:62PATCH /users/:id
Promise<User>
deleteUser()
api/users.ts:78DELETE /users/:id
Promise<void>

FunctionLocationDoes WhatReturns
fetchUser()
api/users.ts:15GET /users/:id
Promise<User>
fetchUsers()
api/users.ts:28GET /users with pagination
Promise<User[]>
createUser()
api/users.ts:45POST /users
Promise<User>
updateUser()
api/users.ts:62PATCH /users/:id
Promise<User>
deleteUser()
api/users.ts:78DELETE /users/:id
Promise<void>

Error Handling

Error Handling

Function/ClassLocationDoes What
AppError
utils/errors.ts:5Base error class with code
ValidationError
utils/errors.ts:20Input validation failures
NotFoundError
utils/errors.ts:32Resource not found
handleAsync()
utils/errors.ts:45Wraps async route handlers
errorMiddleware()
middleware/error.ts:10Express error handler

Function/ClassLocationDoes What
AppError
utils/errors.ts:5Base error class with code
ValidationError
utils/errors.ts:20Input validation failures
NotFoundError
utils/errors.ts:32Resource not found
handleAsync()
utils/errors.ts:45Wraps async route handlers
errorMiddleware()
middleware/error.ts:10Express error handler

Hooks (React)

Hooks (React)

HookLocationDoes What
useAuth()
hooks/useAuth.tsAuth state + login/logout
useUser()
hooks/useUser.tsCurrent user data
useDebounce()
hooks/useDebounce.tsDebounces value changes
useLocalStorage()
hooks/useLocalStorage.tsPersisted state
useFetch()
hooks/useFetch.tsData fetching with loading/error

HookLocationDoes What
useAuth()
hooks/useAuth.tsAuth state + login/logout
useUser()
hooks/useUser.tsCurrent user data
useDebounce()
hooks/useDebounce.tsDebounces value changes
useLocalStorage()
hooks/useLocalStorage.tsPersisted state
useFetch()
hooks/useFetch.tsData fetching with loading/error

Components (React)

Components (React)

ComponentLocationDoes What
Button
components/Button.tsxStyled button with variants
Input
components/Input.tsxForm input with validation
Modal
components/Modal.tsxDialog overlay
Toast
components/Toast.tsxNotification popup
Spinner
components/Spinner.tsxLoading indicator

---
ComponentLocationDoes What
Button
components/Button.tsxStyled button with variants
Input
components/Input.tsxForm input with validation
Modal
components/Modal.tsxDialog overlay
Toast
components/Toast.tsxNotification popup
Spinner
components/Spinner.tsxLoading indicator

---

File Header Format

文件头部格式

Every file should have a summary header:
每个文件都应有一个摘要头部:

TypeScript/JavaScript

TypeScript/JavaScript

typescript
/**
 * @file User authentication utilities
 * @description Handles login, logout, session management, and token refresh.
 *
 * Key exports:
 * - login(email, password) - Authenticates user, returns tokens
 * - logout() - Clears session and tokens
 * - refreshToken() - Gets new access token
 * - validateSession() - Checks if session is valid
 *
 * @see src/api/auth.ts for API endpoints
 * @see src/hooks/useAuth.ts for React hook
 */

import { ... } from '...';
typescript
/**
 * @file User authentication utilities
 * @description Handles login, logout, session management, and token refresh.
 *
 * Key exports:
 * - login(email, password) - Authenticates user, returns tokens
 * - logout() - Clears session and tokens
 * - refreshToken() - Gets new access token
 * - validateSession() - Checks if session is valid
 *
 * @see src/api/auth.ts for API endpoints
 * @see src/hooks/useAuth.ts for React hook
 */

import { ... } from '...';

Python

Python

python
"""
User authentication utilities.

Handles login, logout, session management, and token refresh.

Key exports:
    - login(email, password) - Authenticates user, returns tokens
    - logout() - Clears session and tokens
    - refresh_token() - Gets new access token
    - validate_session() - Checks if session is valid

See Also:
    - src/api/auth.py for API endpoints
    - src/services/user.py for user operations
"""

from typing import ...

python
"""
User authentication utilities.

Handles login, logout, session management, and token refresh.

Key exports:
    - login(email, password) - Authenticates user, returns tokens
    - logout() - Clears session and tokens
    - refresh_token() - Gets new access token
    - validate_session() - Checks if session is valid

See Also:
    - src/api/auth.py for API endpoints
    - src/services/user.py for user operations
"""

from typing import ...

Function Documentation

函数文档规范

Every function needs a one-line summary:
每个函数都需要一行摘要:

TypeScript

TypeScript

typescript
/**
 * Formats a date into a human-readable relative string.
 * Examples: "2 minutes ago", "yesterday", "3 months ago"
 */
export function formatRelative(date: Date): string {
  // ...
}

/**
 * Validates email format and checks for disposable domains.
 * Returns true for valid non-disposable emails.
 */
export function isValidEmail(email: string): boolean {
  // ...
}
typescript
/**
 * Formats a date into a human-readable relative string.
 * Examples: "2 minutes ago", "yesterday", "3 months ago"
 */
export function formatRelative(date: Date): string {
  // ...
}

/**
 * Validates email format and checks for disposable domains.
 * Returns true for valid non-disposable emails.
 */
export function isValidEmail(email: string): boolean {
  // ...
}

Python

Python

python
def format_relative(date: datetime) -> str:
    """Formats a date into a human-readable relative string.

    Examples: "2 minutes ago", "yesterday", "3 months ago"
    """
    ...

def is_valid_email(email: str) -> bool:
    """Validates email format and checks for disposable domains.

    Returns True for valid non-disposable emails.
    """
    ...

python
def format_relative(date: datetime) -> str:
    """Formats a date into a human-readable relative string.

    Examples: "2 minutes ago", "yesterday", "3 months ago"
    """
    ...

def is_valid_email(email: str) -> bool:
    """Validates email format and checks for disposable domains.

    Returns True for valid non-disposable emails.
    """
    ...

Check Before Write Process

写前检查流程

Before Creating ANY New Function

在创建任何新函数之前

┌─────────────────────────────────────────────────────────────────┐
│  BEFORE WRITING NEW CODE                                        │
│  ─────────────────────────────────────────────────────────────  │
│                                                                 │
│  1. DESCRIBE what you need in plain English                     │
│     "I need to format a date as relative time"                  │
│                                                                 │
│  2. CHECK CODE_INDEX.md                                         │
│     Search for: date, time, format, relative                    │
│     → Found: formatRelative() in utils/dates.ts                 │
│                                                                 │
│  3. EVALUATE if existing code works                             │
│     - Does it do what I need? → Use it                          │
│     - Close but not quite? → Extend it                          │
│     - Nothing suitable? → Create new, update index              │
│                                                                 │
│  4. If extending, check for breaking changes                    │
│     - Add optional params, don't change existing behavior       │
│     - Update tests for new functionality                        │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│  BEFORE WRITING NEW CODE                                        │
│  ─────────────────────────────────────────────────────────────  │
│                                                                 │
│  1. DESCRIBE what you need in plain English                     │
│     "I need to format a date as relative time"                  │
│                                                                 │
│  2. CHECK CODE_INDEX.md                                         │
│     Search for: date, time, format, relative                    │
│     → Found: formatRelative() in utils/dates.ts                 │
│                                                                 │
│  3. EVALUATE if existing code works                             │
│     - Does it do what I need? → Use it                          │
│     - Close but not quite? → Extend it                          │
│     - Nothing suitable? → Create new, update index              │
│                                                                 │
│  4. If extending, check for breaking changes                    │
│     - Add optional params, don't change existing behavior       │
│     - Update tests for new functionality                        │
└─────────────────────────────────────────────────────────────────┘

Decision Tree

决策树

Need new functionality
Check CODE_INDEX.md for similar
        ├─► Found exact match ──────► USE IT
        ├─► Found similar ──────────► Can it be extended?
        │                                   │
        │                    ┌──────────────┴──────────────┐
        │                    ▼                             ▼
        │               Yes: Extend                   No: Create new
        │               (add params)                  (update index)
        └─► Nothing found ──────────► Create new (update index)

Need new functionality
Check CODE_INDEX.md for similar
        ├─► Found exact match ──────► USE IT
        ├─► Found similar ──────────► Can it be extended?
        │                                   │
        │                    ┌──────────────┴──────────────┐
        │                    ▼                             ▼
        │               Yes: Extend                   No: Create new
        │               (add params)                  (update index)
        └─► Nothing found ──────────► Create new (update index)

Common Duplication Patterns

常见重复模式

Pattern 1: Utility Function Reimplementation

模式1:工具函数重复实现

Bad: Creating
validateEmail()
when
isEmail()
exists
typescript
// DON'T: This already exists as isEmail()
function validateEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
Good: Check index first, use existing
typescript
import { isEmail } from '@/utils/validate';

if (isEmail(userInput)) { ... }
不良实践:
isEmail()
已存在时创建
validateEmail()
typescript
// DON'T: This already exists as isEmail()
function validateEmail(email: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
良好实践: 先检查索引,使用现有函数
typescript
import { isEmail } from '@/utils/validate';

if (isEmail(userInput)) { ... }

Pattern 2: Slightly Different Versions

模式2:略有差异的版本

Bad: Multiple date formatters with slight variations
typescript
// In file A
function formatDate(d: Date) { return d.toLocaleDateString(); }

// In file B
function displayDate(d: Date) { return d.toLocaleDateString('en-US'); }

// In file C
function showDate(d: Date) { return d.toLocaleDateString('en-US', { month: 'short' }); }
Good: One function with options
typescript
// utils/dates.ts
function formatDate(d: Date, options?: { locale?: string; format?: 'short' | 'long' }) {
  const locale = options?.locale ?? 'en-US';
  const formatOpts = options?.format === 'short'
    ? { month: 'short', day: 'numeric' }
    : { month: 'long', day: 'numeric', year: 'numeric' };
  return d.toLocaleDateString(locale, formatOpts);
}
不良实践: 多个略有差异的日期格式化函数
typescript
// In file A
function formatDate(d: Date) { return d.toLocaleDateString(); }

// In file B
function displayDate(d: Date) { return d.toLocaleDateString('en-US'); }

// In file C
function showDate(d: Date) { return d.toLocaleDateString('en-US', { month: 'short' }); }
良好实践: 一个带选项的函数
typescript
// utils/dates.ts
function formatDate(d: Date, options?: { locale?: string; format?: 'short' | 'long' }) {
  const locale = options?.locale ?? 'en-US';
  const formatOpts = options?.format === 'short'
    ? { month: 'short', day: 'numeric' }
    : { month: 'long', day: 'numeric', year: 'numeric' };
  return d.toLocaleDateString(locale, formatOpts);
}

Pattern 3: Inline Logic That Should Be Extracted

模式3:应提取的内联逻辑

Bad: Same validation logic scattered across files
typescript
// In signup.ts
if (!email || !email.includes('@') || email.length < 5) { ... }

// In profile.ts
if (!email || !email.includes('@') || email.length < 5) { ... }

// In invite.ts
if (!email || !email.includes('@') || email.length < 5) { ... }
Good: Extract once, import everywhere
typescript
// utils/validate.ts
export const isEmail = (email: string) =>
  email && email.includes('@') && email.length >= 5;

// Everywhere else
import { isEmail } from '@/utils/validate';
if (!isEmail(email)) { ... }

不良实践: 相同的验证逻辑分散在多个文件中
typescript
// In signup.ts
if (!email || !email.includes('@') || email.length < 5) { ... }

// In profile.ts
if (!email || !email.includes('@') || email.length < 5) { ... }

// In invite.ts
if (!email || !email.includes('@') || email.length < 5) { ... }
良好实践: 提取一次,在各处导入使用
typescript
// utils/validate.ts
export const isEmail = (email: string) =>
  email && email.includes('@') && email.length >= 5;

// Everywhere else
import { isEmail } from '@/utils/validate';
if (!isEmail(email)) { ... }

Periodic Audit

定期审计

Run
/audit-duplicates
periodically to catch semantic overlap:
定期运行
/audit-duplicates
以发现语义重叠:

Audit Checklist

审计检查清单

  • Utility functions: Any functions doing similar things?
  • API calls: Multiple ways to fetch same data?
  • Validation: Scattered inline validation logic?
  • Error handling: Inconsistent error patterns?
  • Components: Similar UI components that could merge?
  • Hooks: Custom hooks with overlapping logic?
  • 工具函数:是否有功能相似的函数?
  • API调用:是否有多种方式获取相同数据?
  • 验证逻辑:是否有分散的内联验证逻辑?
  • 错误处理:是否有不一致的错误模式?
  • 组件:是否有可合并的相似UI组件?
  • Hooks:是否有逻辑重叠的自定义Hooks?

Audit Output Format

审计输出格式

markdown
undefined
markdown
undefined

Duplicate Audit - [DATE]

Duplicate Audit - [DATE]

🔴 High Priority (Merge These)

🔴 High Priority (Merge These)

  1. Date formatting - 3 similar functions found
    • formatDate()
      in utils/dates.ts
    • displayDate()
      in components/Header.tsx
    • showDate()
      in pages/Profile.tsx
    • Action: Consolidate into utils/dates.ts
  2. Email validation - Inline logic in 5 files
    • signup.ts:42
    • profile.ts:28
    • invite.ts:15
    • settings.ts:67
    • admin.ts:33
    • Action: Extract to utils/validate.ts
  1. Date formatting - 3 similar functions found
    • formatDate()
      in utils/dates.ts
    • displayDate()
      in components/Header.tsx
    • showDate()
      in pages/Profile.tsx
    • Action: Consolidate into utils/dates.ts
  2. Email validation - Inline logic in 5 files
    • signup.ts:42
    • profile.ts:28
    • invite.ts:15
    • settings.ts:67
    • admin.ts:33
    • Action: Extract to utils/validate.ts

🟡 Medium Priority (Consider Merging)

🟡 Medium Priority (Consider Merging)

  1. User fetching - 2 different patterns
    • fetchUser()
      in api/users.ts
    • getUser()
      in services/user.ts
    • Action: Decide on one pattern
  1. User fetching - 2 different patterns
    • fetchUser()
      in api/users.ts
    • getUser()
      in services/user.ts
    • Action: Decide on one pattern

🟢 Low Priority (Monitor)

🟢 Low Priority (Monitor)

  1. Button components - 3 variants exist
    • May be intentional for different use cases
    • Action: Document the differences

---
  1. Button components - 3 variants exist
    • May be intentional for different use cases
    • Action: Document the differences

---

Vector DB Integration (Optional)

向量数据库集成(可选)

For large codebases (100+ files), add vector search:
对于大型代码库(100+文件),添加向量搜索:

Setup with ChromaDB

使用ChromaDB设置

python
undefined
python
undefined

scripts/index_codebase.py

scripts/index_codebase.py

import chromadb from chromadb.utils import embedding_functions
import chromadb from chromadb.utils import embedding_functions

Initialize

Initialize

client = chromadb.PersistentClient(path="./.chroma") ef = embedding_functions.DefaultEmbeddingFunction() collection = client.get_or_create_collection("code_index", embedding_function=ef)
client = chromadb.PersistentClient(path="./.chroma") ef = embedding_functions.DefaultEmbeddingFunction() collection = client.get_or_create_collection("code_index", embedding_function=ef)

Index a function

Index a function

collection.add( documents=["Formats a date into human-readable relative string like '2 days ago'"], metadatas=[{"function": "formatRelative", "file": "utils/dates.ts", "line": 32}], ids=["formatRelative"] )
collection.add( documents=["Formats a date into human-readable relative string like '2 days ago'"], metadatas=[{"function": "formatRelative", "file": "utils/dates.ts", "line": 32}], ids=["formatRelative"] )

Search before writing

Search before writing

results = collection.query( query_texts=["format date as relative time"], n_results=5 )
results = collection.query( query_texts=["format date as relative time"], n_results=5 )

Returns: formatRelative in utils/dates.ts - 0.92 similarity

Returns: formatRelative in utils/dates.ts - 0.92 similarity

undefined
undefined

Setup with LanceDB (Lighter)

使用LanceDB设置(更轻量)

python
undefined
python
undefined

scripts/index_codebase.py

scripts/index_codebase.py

import lancedb
db = lancedb.connect("./.lancedb")
import lancedb
db = lancedb.connect("./.lancedb")

Create table

Create table

data = [ {"function": "formatRelative", "file": "utils/dates.ts", "description": "Formats date as relative time"}, {"function": "isEmail", "file": "utils/validate.ts", "description": "Validates email format"}, ] table = db.create_table("code_index", data)
data = [ {"function": "formatRelative", "file": "utils/dates.ts", "description": "Formats date as relative time"}, {"function": "isEmail", "file": "utils/validate.ts", "description": "Validates email format"}, ] table = db.create_table("code_index", data)

Search

Search

results = table.search("validate email address").limit(5).to_list()
undefined
results = table.search("validate email address").limit(5).to_list()
undefined

When to Use Vector DB

何时使用向量数据库

Codebase SizeRecommendation
< 50 filesMarkdown index only
50-200 filesMarkdown + periodic audit
200+ filesAdd vector DB
500+ filesVector DB essential

Codebase SizeRecommendation
< 50 filesMarkdown index only
50-200 filesMarkdown + periodic audit
200+ filesAdd vector DB
500+ filesVector DB essential

Claude Instructions

Claude使用说明

At Session Start

会话开始时

  1. Read
    CODE_INDEX.md
    if it exists
  2. Note the categories and key functions available
  3. Keep this context for the session
  1. CODE_INDEX.md
    存在则阅读该文件
  2. 记录可用的分类和关键函数
  3. 在会话中保留此上下文

Before Writing New Code

编写新代码前

  1. Pause and check: "Does something like this exist?"
  2. Search CODE_INDEX.md for similar capabilities
  3. If unsure, search the codebase:
    grep -r "functionName\|similar_term" src/
  4. Only create new if confirmed nothing suitable exists
  1. 暂停并检查:"是否已有类似功能?"
  2. CODE_INDEX.md
    中搜索相似能力
  3. 若不确定,搜索代码库:
    grep -r "functionName\|similar_term" src/
  4. 仅在确认没有合适的现有功能时才创建新内容

After Writing New Code

编写新代码后

  1. Immediately update CODE_INDEX.md
  2. Add file header if new file
  3. Add function docstring
  4. Commit index update with code
  1. 立即更新
    CODE_INDEX.md
  2. 若为新文件则添加文件头部
  3. 添加函数文档字符串
  4. 提交代码时同步提交索引更新

When User Says "Add X functionality"

当用户说"添加X功能"时

Before implementing, let me check if we already have something similar...

[Checks CODE_INDEX.md]

Found: `existingFunction()` in utils/file.ts does something similar.
Options:
1. Use existing function as-is
2. Extend it with new capability
3. Create new (if truly different use case)

Which approach would you prefer?

Before implementing, let me check if we already have something similar...

[Checks CODE_INDEX.md]

Found: `existingFunction()` in utils/file.ts does something similar.
Options:
1. Use existing function as-is
2. Extend it with new capability
3. Create new (if truly different use case)

Which approach would you prefer?

Quick Reference

快速参考

Update Index Command

更新索引命令

bash
/update-code-index
bash
/update-code-index

Audit Command

审计命令

bash
/audit-duplicates
bash
/audit-duplicates

File Header Template

文件头部模板

typescript
/**
 * @file [Short description]
 * @description [What this file does]
 *
 * Key exports:
 * - function1() - [what it does]
 * - function2() - [what it does]
 */
typescript
/**
 * @file [Short description]
 * @description [What this file does]
 *
 * Key exports:
 * - function1() - [what it does]
 * - function2() - [what it does]
 */

Function Template

函数模板

typescript
/**
 * [One line description of what it does]
 */
export function name(params): ReturnType {
typescript
/**
 * [One line description of what it does]
 */
export function name(params): ReturnType {

Index Entry Template

索引条目模板

markdown
| `functionName()` | path/file.ts:line | Does what in plain English | `(params)` |
markdown
| `functionName()` | path/file.ts:line | Does what in plain English | `(params)` |