别再让 AI 瞎改代码:一套让大模型「收敛」的前端专家 Skill》

一套让 AI 只改最小必要代码的 Agent Skill

用大模型写前端,最容易翻车的三件事:臆造不存在的 API/字段、随手加默认值托底、顺手做了需求之外的重构 。为此我做了一套 Agent Skill,把「精准改动」固化成可复用规则:双模式(Surgical/Architect)+ 6 步强制工作流 + 防幻觉精度红线,并配套两份按需加载的手册------Bug 诊断手册省 token 手册 。本文完整开源这三份文件,可直接抄进 .codebuddy/skills/ 或 Claude/Cursor 的同类目录。


为什么需要它(背景 / Why)

典型翻车 本 Skill 的约束
凭记忆写 res.data.data,结果结构是 res.data 改 API 前必须搜索/读取真实定义
顺手给表单加 name: ''age: 0 占位 禁止默认值托底,只写明确需要的字段
为了消除报错加 ?.、包 try/catch 禁止用可选链/异常掩盖真实根因
改了 props 却忘了更新所有调用点 改公开契约前必须全局搜索
顺手重构了半屏无关代码 默认 Surgical 模式,diff 最小化
为改 2 行重写整文件、狂读无关文件 省 token 手册:先搜后读、用 diff、挑对文件

核心思路:先选模式,再开工;修根因,不修症状;省 token 不省正确性。


目录结构(文件树 / File Tree)

bash 复制代码
frontend-expert/
├── SKILL.md                              # 主技能:模式选择、工作流、精度红线、质量规范
└── references/
    ├── bug-diagnosis-playbook.md         # 分类型 Bug 诊断手册(Bug 修复前必读)
    └── token-saving-playbook.md          # 省 token 手册(非平凡任务前读)

下面三份文件完整给出。


一、主技能:SKILL.md(第一节:主技能文件)

markdown 复制代码
---
name: frontend-expert
description: >
  Use this skill for frontend code changes, UI component/page implementation,
  frontend bug fixes, layout/state/rendering issues, and requirement-to-code
  translation. Supports dual-mode operation: Surgical Mode for hotfixes and
  Architect Mode for new features/refactors, leveraging unlimited token budget
  for comprehensive context gathering and proactive quality enforcement.
---

# Frontend Expert(前端专家 Skill 主标题)

## Goal(目标)

Make frontend edits that are accurate, minimal, and consistent with the existing
project. Prefer direct file edits over long explanations. Do not invent APIs,
components, imports, fields, or dependencies unless explicitly permitted by the
active mode.

## Mode Selection (Token-Rich Environment)(模式选择·token 充足环境)

Since token budget is unlimited, dynamically select the appropriate mode based
on task nature **before** starting the workflow.

### Mode 1: Surgical Mode (Default)(精准修复模式·默认)

**Trigger**: Bug fixes, style tweaks, local logic adjustments, or when user
explicitly asks for a "quick fix".

- **Behavior**: Strictly follows all "Core Precision Rules" below.
- **Context**: Reads only the target file and direct dependencies.
- **Scope**: Minimal diffs. No refactoring. No new abstractions.
- **Changes**: Patches only the symptoms safely.

### Mode 2: Architect Mode (Active for large scopes)(架构级模式·大范围)

**Trigger**: New page/module development, global refactoring, performance
optimization, dependency upgrades, or when user asks "how to do this better".

- **Behavior**: Leverages unlimited tokens for system-level understanding and
  proactive quality enforcement.
- **Context**: Reads **5-15 related files** (routes, stores, API definitions,
  global types, shared components) to map the full data flow before editing.
- **Refactoring**: Allowed. If existing patterns are obsolete, propose a
  minimal, better approach. Document the reason in a brief comment if deviating.
- **Proactive Linting**: After edits, mentally or actually run `tsc --noEmit`
  and `lint` checks to resolve type errors and format issues automatically.
- **Clarification**: If requirements are vague, ask **exactly one specific
  question** about layout, interaction, or data structure before coding.
- **TODO Allowance**: Up to 2 specific `// TODO` placeholders are allowed only
  for clear backend dependencies that are not yet implemented.

---

## Priority Order(优先级顺序)

1. Obey current user instructions and project instructions first.
2. Follow existing project patterns, naming, framework conventions, and design
   system components.
3. Apply this skill's frontend quality rules.
4. **Mode-specific overrides**: Architect Mode may refine (not break) contracts.
5. Ask one concise question only when the task cannot safely continue.

If the user or project says not to run tests, lint, build, create temp files, or
output a plan, do not do those things **unless Architect Mode is active and the
user did not explicitly forbid them**.

---

## Mandatory Workflow(强制工作流)

For every frontend task:

1. **Determine Mode**: Classify the task as Surgical or Architect based on the
   triggers above.
2. **Read Context**:
   - If **Surgical**: Read the target file before editing it.
   - If **Architect**: Read the target file + at least 5 related files (types,
     APIs, stores, parent/child components).
   - **Bug Fix**: Regardless of mode, when handling a bug fix task, read
     `references/bug-diagnosis-playbook.md` first before starting diagnosis.
   - **Token Economy**: For non-trivial tasks (Architect Mode, or any task
     requiring 3+ file reads / edits to existing large files), consult
     `references/token-saving-playbook.md` before context gathering to minimize
     token consumption (search before reading, read ranges, parallelize reads).
3. **Search**: Search related files for real usage before changing imports,
   props, events, route names, API params, store fields, enum values, or type
   names.
4. **Plan**: Identify the smallest behavior change that satisfies the request.
   (In Architect Mode, "smallest" may include small-scale refactoring to
   eliminate tech debt).
5. **Edit**: Edit only files required by that behavior change. Prefer
   `replace_in_file` (targeted diff) over `write_to_file` for existing files;
   keep `old_str` minimal but unique; batch adjacent edits into one call. See
   `references/token-saving-playbook.md` for full editing-economy rules.
6. **Self-Check**:
   - If Architect: Re-run type checks mentally or via command.
   - Re-check the final diff for unrelated rewrites, phantom symbols, and broken
     contracts.

---

## Precision Rules for 你点模型名称(精度规则·防幻觉)

Use these rules to reduce hallucination and incomplete code:

- Never rely on memory for project APIs. Search or read the actual definition.
- **Surgical Mode only**: Never create a new helper, component, dependency, or
  abstraction when an existing project pattern already solves the problem.
- **Architect Mode only**: May create new helpers/components if they have
  **at least 2 clear reuse scenarios** and you document the rationale.
- Never change public props/events/API contracts without updating all known
  callsites (use global search).
- Avoid placeholder code like `mock`, `any`, or pseudocode unless it's a
  deliberate `// TODO` in Architect Mode.
- **NO DEFAULT VALUES**: Never add default values, example data, placeholder
  fields, or sample content unless explicitly requested. Only include fields,
  properties, and values that are explicitly required by the user or clearly
  inferred from existing project patterns.
- **MINIMAL IMPLEMENTATION**: Generate only the code necessary to fulfill the
  explicit requirement. Do not add:
  - Unrequested form fields or form data properties
  - Example/default values for inputs (e.g., `name: ''`, `age: 0`)
  - Sample data arrays or mock objects
  - Comment examples showing how to use code
  - Optional features or "nice to have" enhancements
- In **Surgical Mode**, never mix refactor, visual redesign, bug fix, and
  feature work in one edit unless the user explicitly asks.
- In **Architect Mode**, mixing is allowed only if the refactor accounts for
  **less than 20%** of the total lines changed.
- Keep naming consistent with nearby code, even if a different convention would
  be preferred in a new project.
- If a symbol is uncertain, stop and search. If it still cannot be found, state
  the uncertainty instead of guessing.

---

## Task Handling(任务处理方式)

### Clear Small Change (Surgical)(清晰小改动·Surgical)

Implement directly. Keep the diff narrow. Do not add a plan.

### New Component or Page (Architect)(新组件/页面·Architect)

Before writing code, inspect nearby pages/components to copy structure,
imports, stores, API style, table/form patterns, styling conventions, and route
patterns. Build the first version with complete loading, empty, error, disabled,
and repeated-click states when those states are relevant.

### Bug Fix (Usually Surgical)(Bug 修复·通常 Surgical)

Fix the root cause, not the symptom.

**Always follow the diagnostic steps in `bug-diagnosis-playbook.md` before making any bug fix.**

Required steps:

1. Locate where the bad state, DOM output, style, or event originates.
2. Trace the data path from source to render or handler.
3. Patch the earliest correct point in that path.
4. Keep backward compatibility for callers.

Avoid symptom-only fixes:

- Do not hide real data bugs with optional chaining.
- Do not add `v-if` or conditional rendering only to silence an error.
- Do not use `try/catch` to swallow failures.
- Do not use `setTimeout` to mask ordering problems.
- Do not overwrite layout with broad `!important` rules unless the existing
  style system leaves no narrower option.

### Vague Requirement(模糊需求)

Infer conservatively from existing product behavior and implement the smallest
useful version.
- In **Surgical Mode**: Ask only when missing information changes the data
  contract, security behavior, routing, permissions, or irreversible action.
- In **Architect Mode**: Ask one clarifying question actively to avoid wrong
  assumptions, especially for UI/UX and state management.

---

## Frontend Quality Rules(前端质量规范)

### TypeScript(TypeScript 规范)
- Use explicit interfaces or existing types for props, emits, API payloads, and
  table/form data.
- Avoid `any`; use `unknown` plus narrowing for genuinely dynamic input.
- Keep nullable values explicit and handle `null`, `undefined`, empty arrays, and
  empty strings where they can occur.
- In **Architect Mode**, proactively fix implicit `any` types if they are within
  the edited files.

### Vue(Vue 规范)
- Prefer existing Vue style in the repo: Composition API, `script setup`, or
  Options API according to the surrounding files.
- Define props/emits with types when the file uses TypeScript.
- Use stable keys in `v-for`.
- Clean up timers, listeners, observers, and subscriptions in lifecycle cleanup.
- Avoid mutating props directly.

### React(React 规范)
- Follow the repo's existing hook and state patterns.
- Clean up effects that register listeners, timers, observers, or requests.
- Avoid stale closures in async handlers.
- Keep component props typed and avoid spreading unknown objects into DOM nodes.

### CSS and Layout(CSS 与布局)
- Match the existing styling system: scoped CSS, SCSS, CSS Modules, utility
  classes, or design-system tokens.
- Prefer flex/grid layout fixes over fixed pixel positioning.
- Handle long text with wrapping, truncation, or tooltip according to nearby UI.
- Avoid global style changes unless the bug is global and proven.
- Default to desktop admin constraints when the project has no mobile pattern;
  do not add mobile behavior unless the request or repo requires it.

### Accessibility and Interaction(无障碍与交互)
- Native controls are preferred for buttons, inputs, selects, checkboxes, and
  dialogs.
- Non-native interactive elements need keyboard support and ARIA labels.
- Disable or guard submit buttons during pending requests when duplicate actions
  would be harmful.
- Preserve focus behavior for modals, drawers, filters, and forms.

### Data and Async(数据与异步)
- Represent loading, success, empty, and error states explicitly when data is
  fetched.
- Prevent request races with request IDs, cancellation, or latest-response checks
  when multiple requests can overlap.
- Do not assume API response shape. Read API definitions or current callsites.
- Keep optimistic updates reversible or avoid them.

### Performance(性能优化)
In **Architect Mode**, proactively evaluate and apply the following optimization
strategies:
- **Virtual Scrolling for Large Lists**: When list data exceeds 100 items or
  involves paginated loading, consider virtual scrolling solutions (e.g.,
  `vue-virtual-scroller`, `@tanstack/vue-virtual`). Never render a large number
  of DOM nodes simultaneously.
- **Unnecessary Re-render Prevention**:
  - Vue: Use `computed` for expensive logic instead of method calls in templates;
    use `shallowRef` for large objects instead of `ref`; avoid calling side-effect
    functions directly in templates.
  - React: Use `React.memo` for presentational components; use `useMemo`/
    `useCallback` for callbacks that don't change with state; avoid creating new
    objects/arrays as props inside render functions.
- **Image Lazy Loading**: Use lazy loading for images below the fold
  (`loading="lazy"` or framework-provided lazy components). For large image lists,
  prefer a combination of virtual scrolling + lazy loading.
- **Bundle Size Optimization**:
  - Use dynamic imports (`import()`) for route-level or component-level code
    splitting of large third-party libraries.
  - Never import heavy dependencies (icon libraries, date libraries) fully; use
    on-demand imports or tree-shaking-friendly alternatives.
  - In Architect Mode, check the bundle size impact before introducing new
    dependencies (reference `bundlephobia` or similar tools).

---

## Final Self-Review(交付前自检清单)

Before delivering, check:

- Imports resolve to real files or installed dependencies.
- All new identifiers are defined or imported.
- Props, emits, API params, and route names match existing contracts.
- Nullable and empty states are handled.
- Cleanup exists for side effects.
- No unrelated formatting, refactor, or design drift was introduced (unless in
  Architect Mode and explicitly justified).
- No command forbidden by current instructions was run.

---

## Output Rules(输出规则)

- **MANDATORY Skill Activation Marker**: At the END of EVERY response when this
  skill is applied, you MUST include this exact marker on a separate line:

🔧 Skill Active: frontend-expert | Mode: {Surgical/Architect}

sql 复制代码
Replace `{Surgical/Architect}` with the actual mode used for this task.
This marker is REQUIRED for ALL frontend tasks handled by this skill.

- When editing an existing project, modify files directly and summarize the diff.
- Do not paste full file contents unless creating a new standalone file or the
user asks for full code.
- Keep final responses short: what changed, why, and what was not verified.
- Use `file:line` references when explaining specific code.

## References(参考文件索引)

- `references/bug-diagnosis-playbook.md`: Category-specific diagnosis guide for
bug fixes. When handling a bug task, this file must be read in Workflow Step 2
before starting diagnosis and repair.
- `references/token-saving-playbook.md`: Strategies to minimize token
consumption (context gathering, editing, response). Consult it before
Workflow Step 2 and Step 5 on non-trivial tasks (Architect Mode, or 3+ file
reads / edits to existing large files). Correctness always takes priority
over token savings --- never guess to save tokens.

二、Bug 诊断手册:references/bug-diagnosis-playbook.md(第二节:Bug 诊断手册)

触发时机:任何 Bug 修复任务,动手前先读,按分类定位根因,修根因不修症状

markdown 复制代码
# Bug Diagnosis Playbook(Bug 诊断手册主标题)

Detailed step-by-step diagnostic procedures for each frontend bug category.
Load this reference when diagnosing non-trivial bugs.

## 1. Layout Bugs(1. 布局类 Bug)

### Symptoms(症状)
- Element position offset, overlapping, unexpected whitespace
- Content overflow or clipping
- Responsive breakpoint breakage

### Diagnostic Steps(诊断步骤)

1. **Inspect box model** --- Open DevTools, check `width`/`height`/`padding`/`margin`
   computed values. Compare against expected.
2. **Check flex/grid context** --- Identify the nearest flex/grid container. Verify
   `flex-shrink`, `flex-grow`, `min-width: 0` (common flex overflow cause).
3. **Trace CSS source** --- Use DevTools to find which rule applies. Check for
   specificity conflicts (`!important`, inline styles, dynamic classes).
4. **Check conditional rendering** --- Async data causing height reflow? Add
   skeleton / reserve space.
5. **Verify z-index stacking** --- Check `position` + `z-index` of overlapping
   elements. Remember: stacking context is created by `position != static`,
   `opacity < 1`, `transform`, `filter`.

### Common Root Causes(常见根因)

- Missing `flex-shrink: 0` on fixed-width flex children
- `overflow: hidden` clipping absolute-positioned dropdowns
- `box-sizing` mismatch (content-box vs border-box)
- Async content loading causing layout shift (CLS)
- CSS `min-height` not set on parent of floated/auto-height children

## 2. State & Reactivity Bugs(2. 状态与响应式 Bug)

### Symptoms(症状)
- UI does not update after data change
- Stale data shown after navigation
- Form values not reflecting user input
- Computed property not recalculating

### Diagnostic Steps(诊断步骤)

1. **Vue reactivity** --- Check if mutation is reactive:
   - Direct array index assignment `arr[0] = x` is NOT reactive → use `arr.splice(0, 1, x)`
   - Adding new object property is NOT reactive (Vue 2) → use `Vue.set` / `this.$set`
   - Vue 3: destructuring a `reactive` object loses reactivity → use `toRefs`
2. **React dependency array** --- Check `useEffect`/`useMemo`/`useCallback` deps:
   - Missing dep → stale closure
   - Object/array dep → infinite loop if recreated each render
3. **Check key attribute** --- `v-for` without `:key` or with index as key causes
   state leakage between items on reorder.
4. **Async race condition** --- Multiple API calls returning out of order. Use
   AbortController or a request ID guard.
5. **Prop mutation** --- Child mutating prop directly breaks one-way data flow.
   Emit event to parent instead.

### Common Root Causes(常见根因)

- Non-reactive assignment (array index, new property)
- Stale closure in event handler / timer callback
- Missing `key` on list render
- Mutating props instead of emitting events
- Shared mutable state across components without proper ownership

## 3. Rendering & Lifecycle Bugs(3. 渲染与生命周期 Bug)

### Symptoms(症状)
- Blank screen on first render
- Content appears then disappears
- "Cannot read property X of undefined"
- Hydration mismatch (SSR)

### Diagnostic Steps(诊断步骤)

1. **Check initial data** --- Is the data `null`/`undefined` on first render before
   async load? Add `v-if` guard or default empty values.
2. **Lifecycle order** --- `created`/`mounted`/`beforeMount` timing. API calls in
   `created` run before DOM exists.
3. **Conditional render guard** --- `v-if` vs `v-show`. `v-if` destroys/recreates;
   `v-show` keeps in DOM with `display: none`.
4. **Watch vs computed** --- Computed is for derived state; watch is for side
   effects. Using watch for derived state causes double renders.
5. **Async component loading** --- Check `defineAsyncComponent` / `Suspense`
   fallback and error states.

### Common Root Causes(常见根因)

- Accessing nested property of undefined initial state (`data.user.name` when `user` is null)
- API call in wrong lifecycle hook
- `v-if` and `v-for` on same element (v-if has higher priority, skips items)
- Missing loading state causes flash of undefined data

## 4. Event & Interaction Bugs(4. 事件与交互 Bug)

### Symptoms(症状)
- Click does nothing
- Event fires multiple times
- Event fires on wrong element
- Keyboard interaction broken

### Diagnostic Steps(诊断步骤)

1. **Verify event binding** --- `@click` vs `@click.native` (Vue 2). Custom component
   events must be emitted, not native.
2. **Check propagation** --- `@click.stop` on child prevents parent handler. Use
   `event.target` vs `event.currentTarget` to verify origin.
3. **Disabled state** --- Element with `disabled` attribute does not fire click.
   Overlay `<div>` may intercept clicks (check `pointer-events`).
4. **Debounce/throttle** --- Rapid clicks bypassing debounce? Check if debounced
   function is recreated each render (loses timer reference).
5. **Keyboard accessibility** --- Non-`<button>` elements need `tabindex="0"` and
   `@keydown.enter` / `@keydown.space` handlers.

### Common Root Causes(常见根因)

- `@click.stop` blocking legitimate parent handler
- Overlapping absolutely-positioned elements intercepting clicks
- Debounced function recreated on each render (move to ref/useMemo)
- `pointer-events: none` not set on decorative overlays
- Missing keyboard handlers on `<div role="button">`

## 5. Performance Bugs(5. 性能类 Bug)

### Symptoms(症状)
- Visible lag / janky scrolling
- Slow initial render (> 3s)
- Memory usage grows over time
- Input lag on typing

### Diagnostic Steps(诊断步骤)

1. **Profile with DevTools** --- Performance tab → Record → Identify long tasks.
   Look for forced reflows (layout thrashing).
2. **Check list rendering** --- Large lists (> 100 items) need virtualization
   (`vue-virtual-scroller`, `react-window`).
3. **Check watchers** --- Deep watchers (`deep: true`) on large objects are expensive.
   Prefer shallow watchers or computed.
4. **Check re-renders** --- React: wrap in `React.memo`, check props equality.
   Vue: check if reactive dependency is too broad.
5. **Memory leak detection** --- Heap snapshot comparison. Look for detached DOM
   nodes, unreleased timers/intervals, event listeners on `window`/`document`.

### Common Root Causes(常见根因)

- Layout thrashing (read then write DOM in loop)
- Deep watch on large reactive objects
- Unvirtualized large lists
- Timers/listeners not cleaned up in `onBeforeUnmount`
- Heavy synchronous computation blocking main thread
- Image resources not lazy-loaded

## 6. Cross-Browser Bugs(6. 跨浏览器 Bug)

### Symptoms(症状)
- Works in Chrome, broken in Firefox/Edge
- CSS renders differently
- JS API not available

### Diagnostic Steps(诊断步骤)

1. **Check CSS prefix** --- `appearance`, `user-select`, `backdrop-filter` may need
   `-webkit-` prefix.
2. **Check JS API support** --- `structuredClone`, `Array.at`, `Object.hasOwn`
   have varying support. Use polyfill or Babel transform.
3. **Check date parsing** --- `new Date('2026-01-01')` vs `new Date('2026/01/01')`
   --- Safari/Firefox stricter on ISO format without time.
4. **Check flexbox gap** --- `gap` in flexbox not supported in older browsers.
   Use margin fallback.
5. **Check `position: sticky`** --- Needs non-`visible` overflow on all ancestors.

### Common Root Causes(常见根因)

- Missing CSS vendor prefixes
- Use of non-polyfilled modern JS APIs
- Date string format differences
- Flexbox `gap` support gaps
- `sticky` position broken by ancestor `overflow: hidden`

三、省 Token 手册:references/token-saving-playbook.md(第三节:省 Token 手册)

触发时机:非平凡任务(Architect 模式,或需读 3+ 文件 / 改现有大文件)前读。省 token 不省正确性------拿不准就读真实定义,绝不猜。

markdown 复制代码
# Token-Saving Playbook(省 Token 手册主标题)

Strategies to minimize token consumption when using an LLM to write frontend code.
Load this reference before context gathering and editing on non-trivial tasks
(Architect Mode, or any task requiring 3+ file reads / edits to existing large
files). The goal: spend fewer tokens gathering context and emitting changes,
without sacrificing correctness.

## Core Principle(核心原则)

Tokens are spent in three places: **reading context**, **editing files**, and
**responding to the user**. Reduce all three. Never trade correctness for
tokens --- if uncertain, read the real definition rather than guess.

## 1. Context Gathering Economy(1. 上下文读取省 token)

### Search Before Reading(先搜后读)
- Use `search_content` / `search_file` to locate symbols, not blind
  `list_dir` + `read_file` chains. Grep returns only matching lines.
- Prefer semantic/symbol search ("where is X defined / called") over reading
  whole files to find one usage.
- Use `outputMode: "files_with_matches"` first to find candidate files, then
  read only the relevant one with context.

### Read Only What You Need(只读所需片段)
- For files >300 lines, read the relevant range with `offset`/`limit` first;
  expand only if the region is insufficient. Do not read the whole file by
  default.
- Skip generated/irrelevant files: `components.d.ts`, `*.lock`, `dist/`,
  `node_modules/`, minified bundles, large config dumps.
- Do not read test files unless the task touches tests.
- Do not re-read a file already in context (within the last ~5 messages) unless
  an edit failed or the user may have modified it.

### Parallelize Independent Reads(并行批读)
- Batch independent read-only calls (multiple `search_content` with different
  patterns, multiple `read_file`) in ONE turn. Sequential drip-calls multiply
  round-trips and re-sent context.
- Gather all needed context in one parallel batch, then edit.

### Pick the Right Files, Don't Blanket-Read(挑对文件·不盲读)
- **Surgical**: read target file + direct dependencies only. No "just in case"
  reads.
- **Architect**: read 5--15 files, but use search to SELECT which files matter
  (the actual API definition, the actual store module, the actual route file),
  not a guess-list.

## 2. Editing Economy(2. 编辑省 token)

### Prefer Targeted Diff Over Full Rewrite(用 diff 而非整文件重写)
- Use `replace_in_file` (old_str → new_str) for existing files. NEVER use
  `write_to_file` to rewrite an existing file --- it re-sends every unchanged
  line as tokens.
- `write_to_file` only for genuinely new files.

### Minimal, Unique old_str(最小且唯一的 old_str)
- Keep `old_str` just large enough to be unique. Include only the lines needed
  to disambiguate (often 1--5 lines), not the whole function. Less context =
  fewer tokens and lower mismatch risk.
- Add a surrounding line only when the target string appears multiple times.

### Batch Adjacent Edits(合并相邻改动)
- Edits within ~20 lines of each other in the same file → combine into ONE
  `replace_in_file` call (single old_str covering the block).
- Non-adjacent edits (>20 lines apart) → separate calls, but still issue them
  in the same turn when independent.

### Don't Re-Read Unless Necessary(非必要不重读)
- After a successful edit, do not re-read the file to "verify" --- trust the diff.
- Only re-read if an edit fails (old_str mismatch) or the user reports changes.

## 3. Response Economy(3. 回复省 token)

### Summarize, Don't Dump(摘要而非倾倒全文)
- Describe the diff in prose: what changed, why, `file:line` references. Do not
  paste full file contents or large unchanged blocks.
- For new files, give complete content (necessary) but keep it lean --- no
  redundant comments, example blocks, or "nice to have" extras.
- Do not echo context back to the user (they know their code).

### Keep Answers Short(回复从简)
- Final answer: what changed, why, what was not verified. Skip narration of
  tool steps already shown.
- Avoid restating requirements; jump to the result.

## 4. Avoid Common Waste Patterns(4. 常见浪费模式)

- **Re-reading files in context**: wastes tokens and context window.
- **Full-file rewrites for a 2-line fix**: the #1 token sink. Always diff.
- **Blanket `list_dir` on large trees**: use targeted `search_file` patterns.
- **Reading large lock/generated files**: skip unless explicitly needed.
- **Sequential single-file reads** when a parallel batch would do.
- **Over-gathering context in Surgical Mode**: read only target + direct deps.
- **Verbose `old_str`**: trim to the minimal unique snippet.

## 5. Quick Checklist (Before Acting)(5. 行动前速查清单)

- [ ] Will I read >3 files? → Batch them in parallel; search to pick the right ones.
- [ ] Is the target file >300 lines? → Read the relevant range first.
- [ ] Am I editing an existing file? → Use `replace_in_file`, minimal `old_str`.
- [ ] Are edits adjacent? → Combine into one call.
- [ ] Is the file already in my context? → Don't re-read.
- [ ] Am I about to dump full code in chat? → Summarize the diff instead.

## 6. When NOT to Optimize(6. 何时不应优化)

- **Correctness first**: if a symbol is uncertain, read the real definition.
  Never guess to save tokens --- a wrong guess costs more in follow-up fixes.
- **Bug fixes**: the bug-diagnosis playbook takes priority; do not skip reading
  it to save tokens.
- **New files**: full content is required; do not truncate to save tokens.

四、三份文件如何配合(第四节:文件协作)

文件 角色 何时加载
SKILL.md 总纲:模式选择 + 6 步工作流 + 精度红线 + 质量规范 任何前端任务启动时自动加载
bug-diagnosis-playbook.md Bug 诊断手册(6 大类) Bug 修复任务,工作流第 2 步动手前读
token-saving-playbook.md 省 token 手册(读取/编辑/回复三维度) 非平凡任务(Architect 或读 3+ 文件/改大文件),第 2、5 步前读

一次典型任务的流转(典型任务处理流程)

  1. 来了个需求 → SKILL.md 判断模式(小修= Surgical,新页面= Architect)。
  2. 是 Bug?先读 bug-diagnosis-playbook.md 按分类定位根因。
  3. 要读多个文件?先读 token-saving-playbook.md,按「先搜后读、读片段、并行批读」拿上下文。
  4. 改现有文件 → 用 replace_in_file 最小 diff,相邻改动合并。
  5. 自检 diff 无无关重写、幽灵符号、契约破坏。
  6. 回复只给「改了什么、为什么、哪些未验证」+ file:line,末尾带激活标记。

五、怎么用进你的项目(第五节:接入方式)

把上面目录结构原样放进 Agent 的 skills 目录即可(CodeBuddy 为 .codebuddy/skills/frontend-expert/,Cursor/Claude 同类目录同理)。效果:每次给 AI 提前端需求或报 Bug,它会先判断模式、读真实代码、搜调用点,再给出最小且可验证的改动,并在回复末尾标注当前模式。


六、小结(第六节:总结)

这套 Skill 不追求「多写」,而是追求**「写对、写少、写稳」**:

  • 双模式区分改动强度------Surgical 锁死最小 diff,Architect 允许有节制的重构;
  • 6 步强制工作流逼着「先读后改、先搜后改」;
  • 精度红线堵住臆造 API、默认值托底、过度重构三类高频幻觉;
  • Bug 诊断手册把「修症状」逼回「修根因」;
  • 省 token 手册 让上下文与改动都精打细算,但正确性永远优先于省 token

如果你有更刁钻的前端幻觉场景,也欢迎补充进诊断手册。

相关推荐
kisshyshy3 小时前
给端侧大模型装上“发动机”:React 合成事件 + 进度条组件全解
前端·react.js·node.js
hunterandroid3 小时前
DataStore 工程化实践:迁移、并发更新与异常恢复
android·前端
晓说前端3 小时前
TypeScript 核心语法进阶 —— 字面量类型与类型推论
前端·typescript
不简说3 小时前
JS 代码技巧 vol.8 — 20 个函数式编程实战,把 if/else 拍扁的骚操作
前端·javascript·面试
头茬韭菜3 小时前
4.9 SSRF 防护 — Web 工具的出站安全与私有 IP 拦截
前端·tcp/ip·安全
Cobyte4 小时前
模板 DSL 解析器中的状态机设计
前端·javascript·vue.js
颜酱4 小时前
# 02 | 搭骨架:用 LangGraph 编排 12 步工作流(思路)
前端·人工智能·后端
颜酱4 小时前
02 | 搭骨架:用 LangGraph 编排 12 步工作流
前端·人工智能·后端
刘卓航众创芯云服务部5 小时前
Kimi K3复杂任务实测:我把团队最头疼的三个场景全跑了一遍
前端