ts-audit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTypeScript Audit
TypeScript 审计
Audit TypeScript code against 9 expert-level references covering type safety, generics, advanced patterns, React integration, type transformations, and testing. The goal is to surface concrete improvements the author may not have considered — not to nitpick style, but to catch real type-safety gaps, missed narrowing opportunities, and patterns that would make the code more robust.
依据 9 个专家级参考资料对 TypeScript 代码进行审计,涵盖 type safety、generics、advanced patterns、React integration、type transformations 和 testing。目标是发现代码作者可能未曾考虑的具体改进空间——不为样式细节吹毛求疵,而是找出真实的 type-safety 缺口、错失的 narrowing 机会,以及能让代码更健壮的模式。
Invocation
调用方式
The user provides a target: a file path, directory, or glob pattern. Examples:
/ts-audit src/db/queries.ts/ts-audit src/pipeline//ts-audit src/**/*.tsx
用户需提供目标:文件路径、目录或 glob 模式。示例:
/ts-audit src/db/queries.ts/ts-audit src/pipeline//ts-audit src/**/*.tsx
Invocation Position
调用定位
This is a side-route skill for TypeScript code quality auditing, not a default pipeline step.
Use when you want to audit TypeScript or React code against expert-level patterns from the bundled TypeScript library references — whether on a single file, a directory, or a glob of changed files.
/ts-auditDo not use it as a substitute for architectural review (which checks structural principles) or (which enforces red-green-refactor). It complements both by focusing specifically on type-safety gaps and TypeScript idiom improvements.
/pre-merge/tddFor TypeScript projects, pairs naturally with Phase 3 (Architectural Review) — running it on changed files provides type-safety analysis that complements the structural review dimensions defined in .
/ts-audit/pre-mergepre-merge/review-checklist.md这是用于 TypeScript 代码质量审计的旁路 Skill,而不是默认 pipeline 步骤。
当你想依据随附的 TypeScript 库参考资料,对单个文件、目录或变更文件 glob 中的 TypeScript 或 React 代码进行审计时,使用 。
/ts-audit不要将其用作 architectural review(检查结构原则)或 (强制 red-green-refactor)的替代品。它专注于 type-safety 缺口和 TypeScript idiom 改进,从而补充二者。
/pre-merge/tdd对于 TypeScript 项目, 可自然搭配 Phase 3(Architectural Review)——在变更文件上运行它,可提供 type-safety 分析,补充 中定义的结构性审查维度。
/ts-audit/pre-mergepre-merge/review-checklist.mdStep 1: Read the target code
Step 1:读取目标代码
- Single file: read it directly
- Directory: glob for and
**/*.tsfiles within it**/*.tsx - Glob pattern: expand the glob
For large targets (>15 files), focus on files with the richest type-level code — interfaces, generics, service layers, component props. Skip auto-generated files (, ).
*.gen.ts*.d.ts- 单文件:直接读取
- 目录:在目录内对 和
**/*.ts文件进行 glob 匹配**/*.tsx - Glob 模式:展开 glob
对于大型目标(超过 15 个文件),重点检查类型层级代码最丰富的文件——包括 interfaces、generics、service layers 和 component props。跳过自动生成的文件(、)。
*.gen.ts*.d.tsStep 2: Load the relevant library references
Step 2:加载相关库参考资料
Resolve the library path:
bash
echo "${CLAUDE_LIBRARY_DIR:-$([ -f "$HOME/.claude/library/index.json" ] && echo "$HOME/.claude/library" || echo "NOT_FOUND")}"Select which books to load based on what's in the target. This keeps context lean — only pay for what you need.
Always load (core):
| Book | What it covers |
|---|---|
| Core type system — inference, narrowing, unions, |
| Essential patterns — annotations, type guards, discriminated unions |
| Generic scope, constraints, inference, overloads |
| Mapped types, conditional types, template literals, |
| Branded types, assertion functions, identity functions, |
Load if target contains files or files that import React:
.tsx| Book | What it covers |
|---|---|
| React props typing, hooks, |
Load if target contains test files (, , ):
*.test.ts*.test.tsx*.spec.ts| Book | What it covers |
|---|---|
| Test structure, assertions, async testing |
| Fixtures, custom assertions, performance testing |
| MSW, dependency injection, fake timers, typed mocks |
Read each selected SKILL.md (path: ) into context. These contain lookup tables, decision matrices, and anti-pattern catalogs that form the audit criteria.
{LIB}/books/<name>/SKILL.mdAlso consult these companion skills when the target uses Zod (these live in , not the library):
~/.claude/skills/| Skill | Load when |
|---|---|
| Any source file in target imports |
| Test files in target import |
Read each companion skill's (path: ) and any rule files it points at. Treat them as authoritative for Zod-specific findings the same way Total TypeScript books are authoritative for general type-system findings.
SKILL.md~/.claude/skills/<name>/SKILL.md解析库路径:
bash
echo "${CLAUDE_LIBRARY_DIR:-$([ -f "$HOME/.claude/library/index.json" ] && echo "$HOME/.claude/library" || echo "NOT_FOUND")}"根据目标内容选择要加载的书籍。这样可以保持 context 精简——只按需加载。
始终加载(核心):
| 资料 | 涵盖内容 |
|---|---|
| 核心类型系统——inference、narrowing、unions、 |
| 基础模式——annotations、type guards、discriminated unions |
| Generic scope、constraints、inference、overloads |
| Mapped types、conditional types、template literals、 |
| Branded types、assertion functions、identity functions、 |
如果目标包含 文件或导入 React 的文件,则加载:
.tsx| 资料 | 涵盖内容 |
|---|---|
| React props typing、hooks、 |
如果目标包含测试文件(、、),则加载:
*.test.ts*.test.tsx*.spec.ts| 资料 | 涵盖内容 |
|---|---|
| Test structure、assertions、async testing |
| Fixtures、custom assertions、performance testing |
| MSW、dependency injection、fake timers、typed mocks |
将每个选中的 SKILL.md(路径:)读入 context。这些文件包含 lookup tables、decision matrices 和 anti-pattern catalogs,共同构成审计标准。
{LIB}/books/<name>/SKILL.md当目标使用 Zod 时,还需查阅以下 companion skills(这些文件位于 ,而不是 library 中):
~/.claude/skills/| Skill | 加载条件 |
|---|---|
| 目标中的任何源文件导入 |
| 测试文件导入 |
读取每个 companion skill 的 SKILL.md(路径:)及其指向的任何 rule 文件。对于 Zod 专项发现,应将这些文件视为 authoritative,就像将 Total TypeScript 书籍视为 general type-system findings 的依据一样。
~/.claude/skills/<name>/SKILL.mdStep 3: Analyze the code
Step 3:分析代码
Work through each file and check against the loaded references. The categories below describe what to look for — the specific rules come from the library references you just loaded.
逐个检查文件,并对照已加载的参考资料。以下类别说明检查方向——具体规则来自刚刚加载的库参考资料。
Type Safety (total-typescript-book, ts-essentials)
类型安全(total-typescript-book、ts-essentials)
- Widened types where narrower literals exist (e.g., when only
status: stringare valid)"approved" | "denied" | "tabled" - where
anywould be saferunknown - type assertions that bypass narrowing — could the code use a type guard or discriminated union instead?
as - Missing return type annotations on exported/public functions
- Loose or
stringwhere branded types would prevent value confusionnumber - Library-callback return wrapper types without . A local type that wraps a library-provided callback's return (agent hooks, middleware, proxy, tool handlers, render props, lifecycle methods) and gets returned from the callback as a typed variable. TS excess-property check does not run on returns of typed values — fields not declared by the library's signature are silently dropped at runtime. Remedy: end the returned object expression with
satisfies, return a fresh object literal, or derive the local type viasatisfies LibraryReturnType/ReturnType<…>. Cite: ts-essentials Rule 31, "UseParameters<…>for type validation without losing inference precision."satisfies
- 存在更窄 literal type 时却使用了 widened type(例如,只有 有效,却写成
"approved" | "denied" | "tabled")status: string - 使用 ,而
any会更安全unknown - 使用 type assertion 绕过 narrowing——能否改用 type guard 或 discriminated union?
as - exported/public functions 缺少 return type annotations
- 使用宽松的 或
string,而 branded types 可以防止值混淆number - 包装 library-provided callback 返回值的 local type 缺少 。 某个 local type 包装 library-provided callback 的返回值(Agent hooks、middleware、proxy、tool handlers、render props、lifecycle methods),并作为 typed variable 从 callback 返回。TS excess-property check 不会在 typed value 的 return 上运行——library 签名未声明的字段会在运行时被静默丢弃。修复方式:让返回的对象表达式以
satisfies结尾、返回新的 object literal,或通过satisfies LibraryReturnType/ReturnType<…>推导 local type。引用:ts-essentials Rule 31,“使用Parameters<…>在不损失 inference 精度的前提下进行类型验证。”satisfies
Generics (ts-generics)
Generics(ts-generics)
- Generics declared at too broad a scope (class-level when function-level suffices)
- Missing or overly loose constraints (with no
T)extends - Redundant generic parameters the compiler could infer
- Cases where function overloads would clarify input-dependent return types
- Generics 声明的 scope 过于宽泛(class-level 足以覆盖的场景却使用了 function-level 之外的 scope)
- Constraints 缺失或过于宽松(没有
T)extends - 存在 compiler 本可自行 infer 的冗余 generic parameters
- 某些场景可使用 function overloads 更清晰地表达依赖于输入的 return types
Discriminated Unions & Narrowing (total-typescript-book, ts-essentials)
Discriminated Unions 与 Narrowing(total-typescript-book、ts-essentials)
- Boolean props/flags where a discriminated union would be clearer and safer
- Destructured discriminated union parameters (breaks narrowing)
- Switch/if chains on union types missing exhaustive checks
- Filtering arrays of unions without type predicates (result stays wide)
- 使用 Boolean props/flags,而 discriminated union 会更清晰、更安全
- 对 discriminated union parameters 进行解构,导致 narrowing 失效
- 针对 union types 的 switch/if chains 缺少 exhaustive checks
- 过滤 union arrays 时未使用 type predicates,导致结果类型仍然过宽
Advanced Patterns (advanced-ts-patterns)
Advanced Patterns(advanced-ts-patterns)
- Assertion functions using arrow syntax (must use declarations)
function - Opportunities for parameter to preserve literal types
const T - Places where branded types would prevent mixing semantically distinct values (e.g., vs
userId)orderId - Builder/accumulator patterns that could leverage generic intersection
- 使用 arrow syntax 编写 assertion functions(必须使用 declarations)
function - 可以利用 parameter 保留 literal types 的机会
const T - 可以使用 branded types 防止语义不同的值混用(例如 与
userId)orderId - Builder/accumulator patterns 可以利用 generic intersection 的机会
Type Transformations (ts-type-transforms)
Type Transformations(ts-type-transforms)
- Manual type duplication where , mapped types, or conditional types would derive from a single source of truth
typeof - instead of
ReturnType<fn>ReturnType<typeof fn> - Opportunities for template literal types
- 手动重复类型定义,而本可通过 、mapped types 或 conditional types 从单一 source of truth 推导
typeof - 使用 ,而不是
ReturnType<fn>ReturnType<typeof fn> - 可以利用 template literal types 的机会
React Patterns (react-ts-patterns) — .tsx
files or files importing React
.tsxReact Patterns(react-ts-patterns)——适用于 .tsx
文件或导入 React 的文件
.tsx- HTML wrapper components not using
ComponentProps<"element"> - Missing generic parameters on ,
useStateuseRef - Mutually exclusive props modeled as optional booleans instead of discriminated unions
- Event handlers manually typed instead of derived from React types
- HTML wrapper components 未使用
ComponentProps<"element"> - 、
useState缺少 generic parametersuseRef - 将 mutually exclusive props 建模为 optional booleans,而不是 discriminated unions
- 手动定义 event handlers 类型,而不是从 React types 推导
Zod Schema Validation (/zod
) — files importing zod
/zodzodZod Schema Validation(/zod
)——适用于导入 zod
的文件
/zodzod- at trust boundaries where
parse()would let the caller branch on validation failure without exceptionssafeParse() - Hand-maintained TypeScript types alongside a Zod schema where would derive them from a single source of truth
z.infer<typeof Schema> - in code targeting Zod v4 (removed — use
z.nativeEnum()over the values, orz.enum()unions)z.literal - String formats expressed as regex when Zod v4's first-class formats (
.refine(...),z.email(),z.url(),z.uuid(), etc.) applyz.iso.datetime() - chains that mask which check failed — splitting into multiple
.refine()calls with distinct messages, or moving to.refine()with.superRefine(), surfaces clearer error pathsctx.addIssue - Reading for programmatic handling where
.error.format()(the flat array) is the v4-preferred shape.error.issues - Untyped around
try/catch— the thrown value isparse(), not generic;ZodError+ discriminant check preserves the typed error channelsafeParse - Schemas defined inside hot paths (request handlers, render bodies) that should be hoisted to module scope so they aren't reconstructed per call
- 在 trust boundaries 使用 ;此处改用
parse()可让调用方根据 validation failure 分支处理,而无需抛出异常safeParse() - 在 Zod schema 旁手动维护 TypeScript types;应使用 从单一 source of truth 推导类型
z.infer<typeof Schema> - 面向 Zod v4 的代码中使用 (已移除——应对 values 使用
z.nativeEnum(),或使用z.enum()unions)z.literal - 当 Zod v4 的 first-class formats(、
z.email()、z.url()、z.uuid()等)适用时,字符串格式却通过z.iso.datetime()regex 表达.refine(...) - chains 掩盖了具体失败的检查——可拆分为多个带有不同 messages 的
.refine()calls,或使用.refine()将逻辑移至ctx.addIssue,以呈现更清晰的 error paths.superRefine() - 在需要 programmatic handling 的场景中读取 ;v4 更推荐使用扁平数组形式
.error.format().error.issues - 在 周围使用未类型化的
parse()——抛出的值是try/catch,而非 generic;使用ZodError+ discriminant check 可以保留 typed error channelsafeParse - 在 hot paths(request handlers、render bodies)中定义 schemas;应将其提升至 module scope,避免每次调用时重新创建
Zod Schema Testing (/zod-testing
) — test files referencing zod schemas
/zod-testingZod Schema Testing(/zod-testing
)——适用于引用 zod schemas 的测试文件
/zod-testing- Schemas without tests covering both the valid-input accept path and the invalid-input reject path
- Error assertions that check only without asserting on
expect(result.success).toBe(false)orresult.error.issues[i].code— the test passes for any rejection reason, not the intended onepath - Mock data hand-rolled inline when (or equivalent) would generate conforming fixtures from the schema itself
zod-schema-faker - Missing boundary-value tests for /
.min()constraints (off-by-one edges).max() - Snapshot tests of API response shapes that could use as a structural assertion instead of brittle object snapshots
z.toJSONSchema(Schema) - Integration tests that hit handlers with raw objects when the same handler accepts schema-parsed input — the test bypasses the validation it's meant to exercise
- Schemas 缺少同时覆盖 valid-input accept 路径和 invalid-input reject 路径的测试
- Error assertions 仅检查 ,却未断言
expect(result.success).toBe(false)或result.error.issues[i].code——测试会因任何 rejection reason 而通过,并非仅验证预期原因path - Inline 手动编写 mock data,而 (或同类工具)可以根据 schema 本身生成符合约束的 fixtures
zod-schema-faker - 缺少针对 /
.min()constraints 的 boundary-value tests(off-by-one edges).max() - API response shapes 的 snapshot tests 可以使用 作为 structural assertion,从而避免脆弱的 object snapshots
z.toJSONSchema(Schema) - Integration tests 使用 raw objects 调用 handlers,而同一 handler 可以接受 schema-parsed input——这会绕过测试本应验证的 validation
Testing Patterns (testing-fundamentals, advanced-vitest-patterns, mocking-techniques) — test files only
Testing Patterns(testing-fundamentals、advanced-vitest-patterns、mocking-techniques)——仅适用于测试文件
- Mocking that could use dependency injection
- Untyped mocks
- Tests not following arrange/act/assert structure
- API mocking that should use MSW
- Mocking 可以改用 dependency injection
- 未类型化的 mocks
- Tests 未遵循 arrange/act/assert 结构
- API mocking 应使用 MSW
Step 3b: Go deeper — surface what the library knows that general knowledge doesn't
Step 3b:深入分析——发现 library 中超出一般知识的模式
After catching the obvious issues above, make a second pass specifically looking for opportunities to apply the non-obvious patterns from each loaded reference. These are the findings that differentiate this audit from what any TypeScript developer would notice:
From advanced-ts-patterns: Look for functions that accept or parameters where the values are semantically distinct (e.g., a and an both typed as ). Suggest branded types at the boundaries. Look for assertion functions written as arrow functions — they must use declarations. Check if any generic function would benefit from to preserve literal types from callers.
stringnumberuserIdorderIdstringfunctionconst TFrom ts-type-transforms: Look for manually duplicated type shapes across files (write-side vs read-side types, DTO vs entity). Suggest , , intersection types, or mapped types to derive from a single source of truth. Check for that should be .
PickOmitReturnType<fn>ReturnType<typeof fn>From ts-generics: Look for generics placed at class or module scope that could be narrowed to function scope. Look for functions returning different types based on input where overloads would make the contract clearer. Check for unconstrained parameters that should have bounds.
TextendsFrom react-ts-patterns (if loaded): Look for components wrapping HTML elements that don't use to forward props. Check for mutually exclusive prop combinations modeled as separate optional props instead of a discriminated union. Look for manual event handler types that could be derived from React's event types.
ComponentProps<"element">From testing books (if loaded): Look for fixture opportunities where multiple tests share the same setup. Check for typed mock patterns — are mocks losing type information? Look for API calls being mocked inline that should use MSW for more realistic testing. Check if Effect-based code is being tested via + instead of which preserves the typed error channel.
test.extend()runPromiserejects.toThrow()runPromiseExitFrom , (if loaded): Look for places where a Zod schema and a manually-declared TS type describe the same shape — collapses the drift surface. Look for calls at system boundaries (HTTP handlers, form submissions, env var parsing) where would let the caller respond gracefully instead of throwing. Check for v3-isms in v4 code (, custom regex for emails/URLs, for programmatic flow). In test files, check that error assertions inspect / — not just — so the test actually pins down which validation failed. Watch for schemas reconstructed inside hot paths (request handlers, render bodies) that should be hoisted to module scope, and for handler/integration tests that bypass the schema layer they exist to verify.
/zod/zod-testingz.infer<typeof Schema>parse()safeParse()nativeEnum.error.format()issues[i].codepathsuccess === falseThe goal of this second pass is to surface at least 1-2 findings per loaded library that go beyond what a developer would catch from general TypeScript knowledge alone. If a library's patterns genuinely don't apply to the target code, that's fine — skip it. But look carefully before deciding nothing applies.
在发现上述显而易见的问题后,再进行第二轮检查,专门寻找每个已加载参考资料中那些不容易察觉的模式。这些发现正是本次审计区别于普通 TypeScript 开发者所能发现问题的关键:
来自 advanced-ts-patterns: 查找接受 或 parameters、但值在语义上彼此不同的 functions(例如 和 都使用 类型)。建议在 boundaries 使用 branded types。查找以 arrow functions 编写的 assertion functions——它们必须使用 declarations。检查是否有 generic function 可以通过 保留 callers 传入的 literal types。
stringnumberuserIdorderIdstringfunctionconst T来自 ts-type-transforms: 查找跨文件手动重复的 type shapes(write-side 与 read-side types、DTO 与 entity)。建议使用 、、intersection types 或 mapped types,从单一 source of truth 推导。检查 是否应改为 。
PickOmitReturnType<fn>ReturnType<typeof fn>来自 ts-generics: 查找位于 class 或 module scope、但可以缩小至 function scope 的 generics。查找根据 input 返回不同 types、且通过 overloads 能够更清晰表达 contract 的 functions。检查未受约束、但应设置 bounds 的 parameters。
extendsT来自 react-ts-patterns(如果已加载): 查找未使用 转发 props 的 HTML element wrapper components。检查 mutually exclusive prop combinations 是否被建模为多个 separate optional props,而不是 discriminated union。检查是否可以从 React event types 推导 manual event handler types。
ComponentProps<"element">来自 testing books(如果已加载): 查找多个 tests 共享相同 setup、且可以使用 fixtures 的机会。检查 typed mock patterns——mocks 是否丢失了 type information?检查 inline mocked API calls 是否应使用 MSW,以获得更真实的 testing。检查 Effect-based code 是否使用 + 进行测试,而不是使用能够保留 typed error channel 的 。
test.extend()runPromiserejects.toThrow()runPromiseExit来自 、(如果已加载): 查找同一个 shape 同时由 Zod schema 和 manually-declared TS type 描述的位置——使用 可以消除 drift surface。查找 system boundaries(HTTP handlers、form submissions、env var parsing)中的 calls;改用 可让调用方优雅处理失败,而不是抛出异常。检查 v4 代码中是否存在 v3-isms(、用于 emails/URLs 的 custom regex、programmatic flow 中的 )。在 test files 中,检查 error assertions 是否查看 /,而不是只检查 ,以确保测试真正固定了具体失败的 validation。留意在 hot paths(request handlers、render bodies)中重新创建、而本应提升至 module scope 的 schemas,以及绕过 schema layer 的 handler/integration tests。
/zod/zod-testingz.infer<typeof Schema>parse()safeParse()nativeEnum.error.format()issues[i].codepathsuccess === false本轮目标是每个已加载 library 至少找出 1–2 个超出一般 TypeScript 知识范围的发现。如果某个 library 的 patterns 确实不适用于目标代码,可以跳过;但在认定其不适用之前,务必仔细检查。
Step 4: Generate the report
Step 4:生成报告
Redact secrets before writing the report
撰写报告前遮蔽 secrets
The report quotes source code verbatim, and it is a portable artifact — users paste it into a PR, drop it in chat, or hand it to another agent. Source files routinely carry secrets, so masking is not optional and not best-effort: run this pass on every snippet before it goes into the report.
- Mask the value of any line matching a high-signal secret shape — ,
*_KEY,*_SECRET,*_TOKEN,*_PASSWORD,AKIA…,sk-…,ghp_…, bearer tokens,xox[baprs]-…and other credentialed URIs, PEM blocks.postgres://user:pass@… - Keep the key, mask the value — keeps the finding legible without leaking the credential. The type pattern is what the finding is about; the secret is not.
STRIPE_SECRET_KEY=sk_live_•••••••• - When in doubt, redact. A masked line the reader can ask about is recoverable; a leaked one in a copied report is not.
- If you masked anything, say so once near the top of the report ("N value(s) masked") so the reader knows the artifact is sanitized, not incomplete.
Structure the report as markdown:
markdown
undefined报告会逐字引用源代码,并且是可移植 artifact——用户会将其粘贴到 PR、发送到聊天或交给另一个 Agent。源文件经常包含 secrets,因此 masking 不是可选项,也不是 best-effort:报告中的每个 snippet 都必须先经过此处理。
- 对任何匹配高信号 secret shape 的行,遮蔽其 value——包括 、
*_KEY、*_SECRET、*_TOKEN、*_PASSWORD、AKIA…、sk-…、ghp_…、bearer tokens、xox[baprs]-…、带凭证的 URIs 和 PEM blockspostgres://user:pass@… - 保留 key,遮蔽 value——例如 ,这样仍能清晰表达 finding,而不会泄露 credential
STRIPE_SECRET_KEY=sk_live_•••••••• - 如有疑问,直接遮蔽。被遮蔽的行仍可供读者进一步询问;复制报告时泄露 credential 则无法挽回
- 如果遮蔽了任何内容,请在报告顶部附近说明一次(“已遮蔽 N 个值”),让读者知道该 artifact 已完成 sanitization,而非内容不完整
将报告组织为 markdown:
markdown
undefinedTypeScript Audit Report
TypeScript 审计报告
Target: <file or directory>
Files analyzed: <count>
Findings: <count>
目标: <文件或目录>
已分析文件数: <数量>
发现数量: <数量>
<Category Name>
<类别名称>
Source: <library book name(s)>
来源:<library book name(s)
<Short description of the finding>
<finding 的简短说明>
File: :<line>
<path>Current code:
```ts
// the relevant snippet
```
Suggested change:
```ts
// the improved version
```
Why: <1-2 sentences explaining what pattern this violates and why the suggestion is better, grounded in the library reference>
**Grouping:** by category (Type Safety, Generics, etc.), not by file. Within each category, order findings by file path then line number.
**What to include in each finding:**
- The actual code snippet (keep it focused — just the relevant lines), with secret values masked per the redaction step above
- A concrete suggested replacement, not just "consider using X"
- A brief explanation referencing the specific concept from the library
**What to omit:**
- Categories with zero findings — leave them out entirely
- Style preferences (semicolons, quotes, formatting)
- Findings that would break the code's runtime behavior without a broader refactor
End with a summary table:
```markdown文件:
<path>:<line>当前代码:
ts
// 相关代码建议修改:
ts
// 改进后的版本原因: <用 1–2 句话说明该代码违反了什么模式,以及建议方案为何更好;依据应来自 library reference>
**分组方式:**按类别(Type Safety、Generics 等),而不是按文件。在每个类别内,先按文件路径排序,再按行号排序。
**每个 finding 应包含:**
- 实际代码 snippet(仅保留相关行),并按照 redaction 步骤遮蔽 secret values
- 具体的建议替换方案,而不只是“考虑使用 X”
- 简短说明,并引用 library 中的具体概念
**应省略:**
- 没有 findings 的类别——完全不显示
- Style preferences(分号、引号、格式)
- 如果不进行更广泛的 refactor 就会破坏代码 runtime behavior 的 findings
最后附上 summary table:
```markdownSummary
汇总
| Category | Findings |
|---|---|
| Type Safety | N |
| Generics | N |
| ... | ... |
| Total | N |
If no findings at all:
> No issues found. The code aligns well with the patterns from the TypeScript library collection.| 类别 | 发现数量 |
|---|---|
| 类型安全 | N |
| Generics | N |
| ... | ... |
| 总计 | N |
如果完全没有 findings:
> 未发现问题。代码与 TypeScript 资料库集合中的模式高度一致。Handoff
交接
- Expected input: a file path, directory, or glob pattern pointing to TypeScript or React code to audit
- Produces: a structured markdown audit report with findings grouped by category, each grounded in a specific bundled library reference
- May feed into: when findings warrant code changes, or
/executewhen the audit informs the architectural review conversation/pre-merge - What comes next: return to the workflow that invoked the audit — the user decides which findings to act on
- **预期输入:**指向 TypeScript 或 React 代码的 file path、directory 或 glob pattern
- **产出:**结构化的 markdown audit report,findings 按类别分组,每项均基于具体的 bundled library reference
- **可衔接至:**当 findings 需要代码修改时衔接至 ,或当 audit 为 architectural review 提供依据时衔接至
/execute/pre-merge - **后续步骤:**返回调用本次 audit 的 workflow——由用户决定处理哪些 findings