verify-language

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Language-Specific Verification

语言专属验证

Purpose

用途

Verify code against language-specific best practices and idioms for Python, TypeScript/JavaScript, and Go. All analysis happens locally.
针对Python、TypeScript/JavaScript和Go,对照语言专属最佳实践与惯用写法验证代码。所有分析均在本地完成。

When to Use

适用场景

Trigger this skill when the user asks to:
  • "verify agent language"
  • "verify language"
  • "check types"
  • "check Python/TypeScript/Go code"
This skill is also auto-invoked by the main verification orchestrator based on detected language.
Note: For full verification including security, patterns, and quality checks, tell the user to say "verify agent".
当用户提出以下请求时触发此技能:
  • "verify agent language"
  • "verify language"
  • "check types"
  • "check Python/TypeScript/Go code"
基于检测到的语言,主验证编排器也会自动调用此技能。
注意: 若需包含安全、模式及质量检查的完整验证,请告知用户说 "verify agent"

Process

流程

Step 1: Detect Language

步骤1:检测语言

Identify the primary language by checking:
IndicatorLanguage
pyproject.toml
,
requirements.txt
,
setup.py
Python
package.json
,
tsconfig.json
TypeScript/JavaScript
go.mod
,
go.sum
Go
Cargo.toml
Rust
Also check file extensions in
src/
or project root:
  • .py
    → Python
  • .ts
    ,
    .tsx
    ,
    .js
    ,
    .jsx
    → TypeScript/JavaScript
  • .go
    → Go
  • .rs
    → Rust
通过以下标识识别主语言:
标识语言
pyproject.toml
,
requirements.txt
,
setup.py
Python
package.json
,
tsconfig.json
TypeScript/JavaScript
go.mod
,
go.sum
Go
Cargo.toml
Rust
同时检查
src/
目录或项目根目录下的文件扩展名:
  • .py
    → Python
  • .ts
    ,
    .tsx
    ,
    .js
    ,
    .jsx
    → TypeScript/JavaScript
  • .go
    → Go
  • .rs
    → Rust

Step 2: Run Language-Specific Checks

步骤2:执行语言专属检查

Apply checks based on detected language. Each section below is only applicable for its language.

根据检测到的语言应用对应检查。以下各部分仅适用于对应语言。

Python Checks

Python检查

[PATTERN]
Type Hints on Public Functions

[PATTERN]
公共函数的类型提示

Flag any
def
function in public scope (no leading
_
) that has parameters without type annotations.
Examples:
python
undefined
标记所有公共作用域(无前置
_
)中参数无类型注解的
def
函数。
示例:
python
undefined

⚠️ Warning - Missing type hints

⚠️ 警告 - 缺少类型提示

def get_user(user_id): return db.find_user(user_id)
def process_items(items, filter_fn): return [filter_fn(item) for item in items]
def get_user(user_id): return db.find_user(user_id)
def process_items(items, filter_fn): return [filter_fn(item) for item in items]

✅ Pass - Has type hints

✅ 通过 - 包含类型提示

def get_user(user_id: int) -> User: return db.find_user(user_id)
def process_items(items: list[Item], filter_fn: Callable[[Item], bool]) -> list[Item]: return [filter_fn(item) for item in items]

**Scope:**
- Public functions (no leading `_`)
- Class methods (except `__init__` can skip return type)
- Module-level functions

Severity: ⚠️ Warning

---
def get_user(user_id: int) -> User: return db.find_user(user_id)
def process_items(items: list[Item], filter_fn: Callable[[Item], bool]) -> list[Item]: return [filter_fn(item) for item in items]

**范围:**
- 公共函数(无前置`_`)
- 类方法(`__init__`可跳过返回类型)
- 模块级函数

严重程度:⚠️ 警告

---

[HEURISTIC]
Docstrings

[HEURISTIC]
文档字符串

Check for missing docstrings:
LocationRequirement
ModuleTop-level docstring explaining purpose
ClassDocstring explaining class responsibility
Public functionDocstring explaining args, returns, raises
Examples:
python
undefined
检查缺失的文档字符串:
位置要求
模块说明用途的顶层文档字符串
说明类职责的文档字符串
公共函数说明参数、返回值、异常的文档字符串
示例:
python
undefined

⚠️ Warning - Missing docstrings

⚠️ 警告 - 缺少文档字符串

class UserService: def get_user(self, user_id: int) -> User: return self.db.find(user_id)
class UserService: def get_user(self, user_id: int) -> User: return self.db.find(user_id)

✅ Pass - Documented

✅ 通过 - 已添加文档

class UserService: """Service for user-related operations."""
def get_user(self, user_id: int) -> User:
    """
    Retrieve a user by ID.
    
    Args:
        user_id: The unique identifier of the user
        
    Returns:
        User object if found
        
    Raises:
        UserNotFoundError: If user doesn't exist
    """
    return self.db.find(user_id)

Severity: ⚠️ Warning

---
class UserService: """用户相关操作服务。"""
def get_user(self, user_id: int) -> User:
    """
    根据ID获取用户。
    
    参数:
        user_id: 用户的唯一标识符
        
    返回:
        找到的User对象
        
    异常:
        UserNotFoundError: 用户不存在时抛出
    """
    return self.db.find(user_id)

严重程度:⚠️ 警告

---

[PATTERN]
Requirements Pinning

[PATTERN]
依赖版本锁定

Check
requirements.txt
and
pyproject.toml
dependencies:
PatternSeverity
package>=1.0
❌ Issue
package>1.0
❌ Issue
package
(no version)
❌ Issue
package==1.0.0
✅ Pass
package~=1.0
✅ Pass
In
pyproject.toml
:
toml
undefined
检查
requirements.txt
pyproject.toml
中的依赖:
模式严重程度
package>=1.0
❌ 问题
package>1.0
❌ 问题
package
(无版本)
❌ 问题
package==1.0.0
✅ 通过
package~=1.0
✅ 通过
pyproject.toml
示例:
toml
undefined

❌ Issue

❌ 问题

[project] dependencies = [ "langchain>=0.1.0", "openai", ]
[project] dependencies = [ "langchain>=0.1.0", "openai", ]

✅ Pass

✅ 通过

[project] dependencies = [ "langchain==0.1.0", "openai==1.12.0", ]

Severity: ❌ Issue

---
[project] dependencies = [ "langchain==0.1.0", "openai==1.12.0", ]

严重程度:❌ 问题

---

[HEURISTIC]
Python Idioms

[HEURISTIC]
Python惯用写法

Check for non-idiomatic patterns:
Anti-patternIdiomatic
if len(list) > 0:
if list:
if x == True:
if x:
list = list + [item]
list.append(item)
for i in range(len(list)):
for item in list:
or
enumerate()
dict.keys()
iteration
Direct dict iteration
Severity: ⚠️ Warning

检查非惯用模式:
反模式惯用写法
if len(list) > 0:
if list:
if x == True:
if x:
list = list + [item]
list.append(item)
for i in range(len(list)):
for item in list:
enumerate()
dict.keys()
迭代
直接遍历字典
严重程度:⚠️ 警告

TypeScript/JavaScript Checks

TypeScript/JavaScript检查

[PATTERN]
Strict Mode

[PATTERN]
严格模式

Check
tsconfig.json
for strict type checking:
json
// ❌ Issue - Not strict
{
  "compilerOptions": {
    "strict": false
  }
}

// ❌ Issue - Strict not set
{
  "compilerOptions": {
    "target": "ES2020"
  }
}

// ✅ Pass
{
  "compilerOptions": {
    "strict": true
  }
}
Severity: ❌ Issue (if
strict
is
false
or absent)

检查
tsconfig.json
中的严格类型检查配置:
json
// ❌ 问题 - 未启用严格模式
{
  "compilerOptions": {
    "strict": false
  }
}

// ❌ 问题 - 未设置strict
{
  "compilerOptions": {
    "target": "ES2020"
  }
}

// ✅ 通过
{
  "compilerOptions": {
    "strict": true
  }
}
严重程度:❌ 问题(若
strict
false
或未配置)

[PATTERN]
No
any
Types

[PATTERN]
禁用
any
类型

Flag unqualified
: any
type annotations:
typescript
// ⚠️ Warning
function process(data: any): any {
    return data.value;
}

const items: any[] = [];

// ✅ Pass - Specific types
function process(data: UserData): ProcessedData {
    return { value: data.value };
}

// ✅ Pass - Explicit unknown with narrowing
function process(data: unknown): ProcessedData {
    if (isUserData(data)) {
        return { value: data.value };
    }
    throw new Error("Invalid data");
}
Severity: ⚠️ Warning

标记未限定的
: any
类型注解:
typescript
// ⚠️ 警告
function process(data: any): any {
    return data.value;
}

const items: any[] = [];

// ✅ 通过 - 使用特定类型
function process(data: UserData): ProcessedData {
    return { value: data.value };
}

// ✅ 通过 - 显式unknown并进行类型收窄
function process(data: unknown): ProcessedData {
    if (isUserData(data)) {
        return { value: data.value };
    }
    throw new Error("Invalid data");
}
严重程度:⚠️ 警告

[HEURISTIC]
Async/Await Error Handling

[HEURISTIC]
Async/Await错误处理

Check that async functions handle errors:
typescript
// ⚠️ Warning - No error handling
async function fetchUser(id: string): Promise<User> {
    const response = await fetch(`/users/${id}`);
    return response.json();
}

// ✅ Pass - Has error handling
async function fetchUser(id: string): Promise<User> {
    try {
        const response = await fetch(`/users/${id}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return response.json();
    } catch (error) {
        logger.error("Failed to fetch user", { id, error });
        throw new UserFetchError(id, error);
    }
}
Severity: ⚠️ Warning

检查异步函数是否处理错误:
typescript
// ⚠️ 警告 - 无错误处理
async function fetchUser(id: string): Promise<User> {
    const response = await fetch(`/users/${id}`);
    return response.json();
}

// ✅ 通过 - 包含错误处理
async function fetchUser(id: string): Promise<User> {
    try {
        const response = await fetch(`/users/${id}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return response.json();
    } catch (error) {
        logger.error("Failed to fetch user", { id, error });
        throw new UserFetchError(id, error);
    }
}
严重程度:⚠️ 警告

[HEURISTIC]
Promise Handling

[HEURISTIC]
Promise处理

Check for common Promise anti-patterns:
Anti-patternIssue
Missing
.catch()
Unhandled rejection
new Promise()
with async executor
Anti-pattern
Fire-and-forget promisesNo await, no handling
typescript
// ⚠️ Warning - No catch
fetchData().then(process);

// ⚠️ Warning - Async executor
new Promise(async (resolve) => {
    const data = await fetchData();
    resolve(data);
});

// ✅ Pass
fetchData().then(process).catch(handleError);

// ✅ Pass - Using async/await
const data = await fetchData();
process(data);
Severity: ⚠️ Warning

检查常见的Promise反模式:
反模式问题
缺失
.catch()
未处理的拒绝
new Promise()
使用异步执行器
反模式
即发即弃的Promise无await,无处理
typescript
// ⚠️ 警告 - 无catch
fetchData().then(process);

// ⚠️ 警告 - 异步执行器
new Promise(async (resolve) => {
    const data = await fetchData();
    resolve(data);
});

// ✅ 通过
fetchData().then(process).catch(handleError);

// ✅ 通过 - 使用async/await
const data = await fetchData();
process(data);
严重程度:⚠️ 警告

Go Checks

Go检查

[PATTERN]
No Ignored Errors

[PATTERN]
不忽略错误

Flag any
_ = 
assignments where the right-hand side returns
error
:
go
// ❌ Issue - Ignored error
_ = file.Close()
_ = json.Unmarshal(data, &result)
result, _ := db.Query(sql)

// ✅ Pass - Error handled
if err := file.Close(); err != nil {
    log.Printf("failed to close file: %v", err)
}

result, err := db.Query(sql)
if err != nil {
    return nil, fmt.Errorf("query failed: %w", err)
}
Severity: ❌ Issue

标记所有右侧返回
error
_ = 
赋值:
go
// ❌ 问题 - 忽略错误
_ = file.Close()
_ = json.Unmarshal(data, &result)
result, _ := db.Query(sql)

// ✅ 通过 - 已处理错误
if err := file.Close(); err != nil {
    log.Printf("failed to close file: %v", err)
}

result, err := db.Query(sql)
if err != nil {
    return nil, fmt.Errorf("query failed: %w", err)
}
严重程度:❌ 问题

[HEURISTIC]
Context Propagation

[HEURISTIC]
Context传递

Check that context.Context is passed through call chains:
go
// ⚠️ Warning - Context not passed
func ProcessData(data []byte) error {
    result, err := externalAPI.Call(data)  // No context
    return err
}

// ✅ Pass - Context propagated
func ProcessData(ctx context.Context, data []byte) error {
    result, err := externalAPI.Call(ctx, data)
    return err
}
Check for:
  • HTTP handlers that don't use
    r.Context()
  • Functions that call external services without context
  • Long-running operations without context cancellation support
Severity: ⚠️ Warning

检查context.Context是否在调用链中传递:
go
// ⚠️ 警告 - 未传递Context
func ProcessData(data []byte) error {
    result, err := externalAPI.Call(data)  // 无context
    return err
}

// ✅ 通过 - 已传递Context
func ProcessData(ctx context.Context, data []byte) error {
    result, err := externalAPI.Call(ctx, data)
    return err
}
检查项:
  • 未使用
    r.Context()
    的HTTP处理器
  • 调用外部服务未传递context的函数
  • 不支持context取消的长时间运行操作
严重程度:⚠️ 警告

[HEURISTIC]
Proper Package Structure

[HEURISTIC]
合理的包结构

Check Go project structure:
IssueDescription
package main
with many files
Should split into packages
Circular importsPackage A imports B, B imports A
Internal packages exposedInternal code in public packages
Missing
internal/
Shared code that shouldn't be public
Severity: ⚠️ Warning

检查Go项目结构:
问题描述
package main
包含多个文件
应拆分为多个包
循环导入包A导入B,B导入A
内部包暴露公共包中包含内部代码
缺失
internal/
目录
存在不应公开的共享代码
严重程度:⚠️ 警告

[HEURISTIC]
Go Idioms

[HEURISTIC]
Go惯用写法

Check for non-idiomatic patterns:
Anti-patternIdiomatic
if err != nil { return err }
repeatedly
Consider helper or wrap
Naked returns in long functionsExplicit returns
interface{}
without type assertions
Use generics or specific types
Getters named
GetX()
Just
X()
Severity: ⚠️ Warning

检查非惯用模式:
反模式惯用写法
重复
if err != nil { return err }
考虑使用辅助函数或包装
长函数中使用裸返回使用显式返回
interface{}
无类型断言
使用泛型或特定类型
Getter命名为
GetX()
直接命名为
X()
严重程度:⚠️ 警告

Step 3: Generate Report

步骤3:生成报告

markdown
undefined
markdown
undefined

Language Verification Report

语言验证报告

Project: [name or path] Date: [current date] Language detected: [Python | TypeScript | JavaScript | Go] Files analyzed: [count]
项目: [名称或路径] 日期: [当前日期] 检测到的语言: [Python | TypeScript | JavaScript | Go] 分析文件数: [数量]

Summary

摘要

✅ X checks passed | ⚠️ Y warnings | ❌ Z issues
✅ X项检查通过 | ⚠️ Y项警告 | ❌ Z项问题

Type Safety

类型安全性

  • Types properly defined
  • ⚠️ Missing type hints at
    [file:line]
  • ❌ Strict mode not enabled in
    tsconfig.json
  • 类型定义合理
  • ⚠️
    [文件:行]
    处缺失类型提示
  • tsconfig.json
    未启用严格模式

Language Idioms

语言惯用写法

  • Code follows language best practices
  • ⚠️ Non-idiomatic pattern at
    [file:line]
  • 代码遵循语言最佳实践
  • ⚠️
    [文件:行]
    处存在非惯用模式

Error Handling

错误处理

  • Errors properly handled
  • ❌ Ignored error at
    [file:line]
  • 错误处理合理
  • [文件:行]
    处存在忽略错误的情况

Findings

检查结果

[P]
= pattern-matched ·
[H]
= heuristic
[P]
= 模式匹配 ·
[H]
= 启发式检查

✅ Passing

✅ 通过项

  • [P]
    [Check]: [confirmation]
  • [P]
    [检查项]: [确认信息]

⚠️ Warnings

⚠️ 警告项

  • [P|H]
    [Check]: [description]
    • Location: [file:line]
    • Language rule: [which idiom/pattern]
    • Suggestion: [how to fix]
  • [P|H]
    [检查项]: [描述]
    • 位置: [文件:行]
    • 语言规则: [对应惯用写法/模式]
    • 建议: [修复方式]

❌ Issues

❌ 问题项

  • [P]
    [Check]: [description]
    • Location: [file:line]
    • Rule: [which rule violated]
    • Fix: [specific remediation]
  • [P]
    [检查项]: [描述]
    • 位置: [文件:行]
    • 规则: [违反的规则]
    • 修复方案: [具体整改措施]

Language-Specific Recommendations

语言专属建议

Python

Python

  1. Add type hints to public functions
  2. Include docstrings for classes and functions
  1. 为公共函数添加类型提示
  2. 为类和函数添加文档字符串

TypeScript

TypeScript

  1. Enable strict mode in tsconfig.json
  2. Replace
    any
    with specific types
  1. 在tsconfig.json中启用严格模式
  2. 用特定类型替换
    any

Go

Go

  1. Handle all returned errors
  2. Propagate context through call chains

---

*For full verification including security, patterns, and quality checks, say "verify agent".*
  1. 处理所有返回的错误
  2. 在调用链中传递context

---

*若需包含安全、模式及质量检查的完整验证,请说"verify agent"。*