写作与翻译

跨编程语言代码移植助手

提供源代码和目标语言,保留原有功能,按目标语言习惯改写实现,并用测试验证行为一致。

# 代码转换

在保留功能的同时,将代码从一种编程语言转换为另一种,并适配目标语言的惯用写法和最佳实践。

## 转换工作流程

### 1. 分析源代码

了解代码的功能:
- 核心功能和算法
- 依赖项和外部库
- 使用的语言特性
- 性能特征

### 2. 选择转换策略

**直接转换**:保留结构,逐字转换
- **适用场景**:简单算法、数据转换、工具函数
- **优点**:速度更快,更容易验证正确性
- **缺点**:可能不符合目标语言的惯用写法

**惯用写法转换**:适配目标语言的模式
- **适用场景**:生产代码、公共 API、长期维护
- **优点**:代码更符合语言习惯、性能更好、易于维护
- **缺点**:耗时更长,需要深入了解语言

**推荐**:先直接转换,再优化为惯用写法。

### 3. 转换代码

遵循目标语言的模式和约定进行转换。

### 4. 验证正确性

确保转换后的代码与源代码行为一致:
- 移植现有测试
- 添加行为测试
- 比较相同输入下的输出

## 快速转换示例

### Python → JavaScript

**源代码(Python)**
```python
def calculate_total(items):
    """Calculate total price with tax."""
    subtotal = sum(item['price'] * item['quantity'] for item in items)
    tax = subtotal * 0.08
    return subtotal + tax

# Usage
items = [
    {'name': 'Widget', 'price': 10.0, 'quantity': 2},
    {'name': 'Gadget', 'price': 15.0, 'quantity': 1}
]
total = calculate_total(items)
```

**目标代码(JavaScript)**
```javascript
function calculateTotal(items) {
    // Calculate total price with tax
    const subtotal = items.reduce(
        (sum, item) => sum + item.price * item.quantity,
        0
    );
    const tax = subtotal * 0.08;
    return subtotal + tax;
}

// Usage
const items = [
    { name: 'Widget', price: 10.0, quantity: 2 },
    { name: 'Gadget', price: 15.0, quantity: 1 }
];
const total = calculateTotal(items);
```

### JavaScript → Python

**源代码(JavaScript)**
```javascript
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error(`Failed to fetch user: ${error.message}`);
        return null;
    }
}
```

**目标代码(Python)**
```python
import aiohttp
import logging

async def fetch_user_data(user_id: int) -> dict | None:
    """Fetch user data from API."""
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f'/api/users/{user_id}') as response:
                if not response.ok:
                    raise ValueError(f'HTTP {response.status}')
                return await response.json()
    except Exception as e:
        logging.error(f'Failed to fetch user: {e}')
        return None
```

### Java → Go

**源代码(Java)**
```java
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }

    public Optional<User> findById(Long id) {
        return repository.findById(id);
    }

    public List<User> findAll() {
        return repository.findAll();
    }
}
```

**目标代码(Go)**
```go
type UserService struct {
    repository UserRepository
}

func NewUserService(repository UserRepository) *UserService {
    return &UserService{repository: repository}
}

func (s *UserService) FindById(id int64) (*User, error) {
    return s.repository.FindById(id)
}

func (s *UserService) FindAll() ([]User, error) {
    return s.repository.FindAll()
}
```

## 常见转换模式

### 数据结构

**列表/数组**
```python
# Python
numbers = [1, 2, 3]
numbers.append(4)
```
```javascript
// JavaScript
const numbers = [1, 2, 3];
numbers.push(4);
```
```go
// Go
numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
```

**字典/映射**
```python
# Python
user = {"name": "Alice", "age": 30}
```
```javascript
// JavaScript
const user = { name: "Alice", age: 30 };
```
```go
// Go
user := map[string]interface{}{
    "name": "Alice",
    "age":  30,
}
```

### 错误处理

**异常 → 错误返回值**
```python
# Python
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
```
```go
// Go
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}
```

**错误返回值 → 异常**
```go
// Go
result, err := divide(10, 0)
if err != nil {
    return err
}
```
```python
# Python
try:
    result = divide(10, 0)
except ValueError as e:
    print(f"Error: {e}")
```

### 异步/并发

**Python asyncio → JavaScript async/await**
```python
# Python
async def fetch_all(urls):
    tasks = [fetch(url) for url in urls]
    return await asyncio.gather(*tasks)
```
```javascript
// JavaScript
async function fetchAll(urls) {
    const promises = urls.map(url => fetch(url));
    return await Promise.all(promises);
}
```

**JavaScript Promises → Go Goroutines**
```javascript
// JavaScript
const results = await Promise.all([
    fetchUser(1),
    fetchUser(2),
    fetchUser(3)
]);
```
```go
// Go
var wg sync.WaitGroup
results := make([]*User, 3)

for i := 1; i <= 3; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        results[id-1] = fetchUser(id)
    }(i)
}
wg.Wait()
```

## 转换决策树

```
Is this a complete project migration?
├─ Yes → See [project_migration.md](references/project_migration.md)
│         Follow 8-phase migration process
│
└─ No → Is this a function/class/module?
        │
        ├─ Single function
        │  ├─ Simple logic? → Direct translation
        │  └─ Complex logic? → Idiomatic translation
        │
        ├─ Class with methods
        │  ├─ Does target language have classes?
        │  │  ├─ Yes → Translate class structure
        │  │  └─ No → Convert to module/functions
        │
        └─ Full module
           └─ Translate file by file
              Consider dependencies first
```

## 特定语言指南

### 惯用写法转换

参见 **[idiomatic_guide.md](references/idiomatic_guide.md)**,了解:
- 特定语言的惯用写法和模式
- 命名约定(snake_case、camelCase、PascalCase)
- 标准库用法
- 应避免的反模式
- 社区风格指南

### 特定语言对

参见 **[language_patterns.md](references/language_patterns.md)**,了解详细模式:
- Python ↔ JavaScript/TypeScript
- Java ↔ Python
- Python ↔ Go
- C++ ↔ Rust
- TypeScript ↔ Go
- 所有语言通用的模式

### 项目迁移

参见 **[project_migration.md](references/project_migration.md)**,了解:
- 8阶段迁移流程
- 依赖项映射
- 构建系统转换
- 测试策略
- 部署配置
- 增量迁移方法

## 最佳实践

### 1. 保留行为,而非结构

关注代码的功能,而非写法:
```python
# Python (imperative)
total = 0
for item in items:
    total += item.price
```
```javascript
// JavaScript (functional - different structure, same behavior)
const total = items.reduce((sum, item) => sum + item.price, 0);
```

### 2. 使用目标语言的特性

不要与语言的特性对着干——发挥它的优势:
```python
# Python - use list comprehensions
squares = [x**2 for x in range(10)]

# Not: Java-style loop
squares = []
for x in range(10):
    squares.append(x**2)
```

### 3. 尽可能保持类型安全

在静态类型语言中添加类型提示/注解:
```python
# Python source (dynamic)
def greet(name):
    return f"Hello, {name}"
```
```typescript
// TypeScript (add types)
function greet(name: string): string {
    return `Hello, ${name}`;
}
```

### 4. 处理库之间的差异

映射到等效的库或实现抽象层:
```python
# Python using requests
import requests
response = requests.get(url)
data = response.json()
```
```javascript
// JavaScript using fetch
const response = await fetch(url);
const data = await response.json();
```

### 5. 严格测试

验证转换后的代码行为完全一致:
```python
# Port tests alongside code
def test_calculate_total():
    items = [{"price": 10, "quantity": 2}]
    assert calculate_total(items) == 21.6  # 20 + 8% tax
```
```javascript
// Same test in target language
test('calculateTotal', () => {
    const items = [{ price: 10, quantity: 2 }];
    expect(calculateTotal(items)).toBe(21.6);
});
```

## 转换检查清单

### 转换前
- [ ] 理解源代码的功能
- [ ] 确定依赖项和等效的库
- [ ] 选择转换策略(直接转换或惯用写法转换)
- [ ] 搭建目标项目结构

### 转换过程中
- [ ] 先转换核心逻辑
- [ ] 适配目标语言的惯用写法
- [ ] 处理错误处理方式的差异
- [ ] 恰当映射数据结构
- [ ] 转换异步/并发模式
- [ ] 翻译注释和文档

### 转换后
- [ ] 移植或创建测试
- [ ] 验证行为是否等效
- [ ] 审查代码是否符合惯用写法
- [ ] 进行性能测试
- [ ] 更新文档
- [ ] 在适用时添加类型提示/注解

## 常见陷阱

### 1. 逐字转换
❌ 逐行转换而不做适配
✅ 适配目标语言的模式

### 2. 忽视语言安全性
❌ 到处使用 `any`/`interface{}`/`Object`
✅ 正确处理类型和错误

### 3. 抽象层级错误
❌ 转换实现细节
✅ 转换行为和意图

### 4. 遗漏边界情况
❌ 假设边界情况下的行为相同
✅ 测试边界条件

### 5. 忽视性能
❌ 忽略性能特征
✅ 针对目标语言进行性能分析和优化

## 示例:完整转换

**Python 源代码**
```python
class Calculator:
    """Simple calculator with memory."""

    def __init__(self):
        self.memory = 0

    def add(self, a: float, b: float) -> float:
        """Add two numbers."""
        result = a + b
        self.memory = result
        return result

    def recall(self) -> float:
        """Recall last result."""
        return self.memory

    def clear(self):
        """Clear memory."""
        self.memory = 0
```

**TypeScript 转换代码**
```typescript
/**
 * Simple calculator with memory.
 */
class Calculator {
    private memory: number = 0;

    /**
     * Add two numbers.
     */
    add(a: number, b: number): number {
        const result = a + b;
        this.memory = result;
        return result;
    }

    /**
     * Recall last result.
     */
    recall(): number {
        return this.memory;
    }

    /**
     * Clear memory.
     */
    clear(): void {
        this.memory = 0;
    }
}
```

**Go 转换代码(惯用写法)**
```go
// Calculator is a simple calculator with memory.
type Calculator struct {
    memory float64
}

// NewCalculator creates a new calculator.
func NewCalculator() *Calculator {
    return &Calculator{memory: 0}
}

// Add two numbers and store result in memory.
func (c *Calculator) Add(a, b float64) float64 {
    result := a + b
    c.memory = result
    return result
}

// Recall returns the last result.
func (c *Calculator) Recall() float64 {
    return c.memory
}

// Clear resets the memory to zero.
func (c *Calculator) Clear() {
    c.memory = 0
}
```

同类提示词

写作与翻译

按叙事节奏拆分短片制作计划

提供短片构想,可补充时长和风格偏好,把故事拆成带开场钩子的场次,明确景别、动作、服装和剪辑节奏。

# 视频策划 使用此技能将用户的短片创意转化为实用的逐场景制作方案。该方案应适用于拍摄、剪辑、AI 视频生成,或与摄影师/剪辑师沟通。 最终方案应使用用户偏好的本地语言撰写。如果用户使用中文,除非明确要求其他语言,否则用中文输出方案。技能说明保持英文,但交付内容的语言应适应用户。 ## 主要目标 制作一份完整的短视频方案,满足以下要求: - 协商或推断总时长。 - 将视频划分为多个场景,每个场景至少为 4 seconds,且不超过 15 seconds。 - 在可行时优先采用 4、9、12 或 15 seconds 的场景时长。 - 使用清晰可
写作与翻译

三十天多渠道营销内容日历

给品牌资料、渠道、月目标和制作资源,按漏斗排三十天主题、发布及行动号召,发布前评分。

# 全球内容日历 > 规划一份为期 30 天的多渠道内容日历,确定漏斗比例、内容支柱和来源类型组合,并在发布前进行 AI 评分。 --- ## 第 0 步——读取上下文文件 生成日历前,读取 `.agents/product-marketing-context-global.md`,了解: - 品牌声音与语气 - 当前运营的渠道及粉丝基础 - 地区(决定最佳发布时间和渠道组合) - 货币(决定涉及金额的行动号召如何表述) 如果文件缺失,请用户先运行 `product-marketing-context-global`。 --- ## 信息
可填 1 项
写作与翻译

单场景分镜图与视频生成脚本

提供要制作的场景,按镜头时长生成分镜图和视频脚本,有现成人物图时沿用其造型。

# 视频分镜 使用此 skill 为特定场景制作一套可直接用于制作的分镜方案: 1. 将分镜图保存到 `storyboard/scene-XX.png`。 2. 将视频生成提示词脚本保存到 `storyboard/scene-XX.md`。 用英文编写 skill 指令,但面向用户的 `.md` 脚本应使用用户偏好的本地语言,除非用户明确要求使用其他语言。 ## 图像生成要求 分镜图必须由图像生成模型生成。不要用代码、SVG、HTML/CSS、canvas、图表、占位画或确定性形状脚本制作分镜画面。这些方法只可用于非视觉元数据或文件操作,绝不能
需参考图
写作与翻译

可灵短视频剧情与图生视频脚本

按单场景或多角色剧情编写生成指令,覆盖动作、运镜和音频;图生视频需上传参考图并说明变化。

# kling-prompter Kling 3.0(可灵 3.0,快手)的三套主流写法:4 部分基础 / 5 层进阶 / 图生视频。 ## 何时不用此 skill - 复杂多镜头分镜叙事(>15s) → 用 [seedance-storyboard](../seedance-storyboard/) - 5/10/15 秒紧凑短片,对原生音频要求不高 → 用 [happyhorse-prompter](../happyhorse-prompter/) - 已有 Seedance 提示词需修问题 → 用 [seedance-debugger](..
需参考图中文原创
写作与翻译

明确交付物和负责人的工作坊

提供工作坊目标与参会情况,围绕一个成果设计议程,安排分组讨论、决策和会后负责人。

# 工作坊设计师 大多数工作坊都以同一种方式失败:讨论了很多,产生了无人记录的“共识”,然后又发出下一场工作坊的日历邀请。这个技能设计的会议以**确定的成果和明确的负责人**收尾,因为只有这样才值得占用参与者一周中的时间。 检验任何工作坊的标准:**这间会议室里会产出什么成果,谁负责下一步?** 如果答不上来,就不要举办工作坊。 --- ## 设计选择 - **只设一个结果,不要三个。** 有三个目标的工作坊一个也达不成。强制排序,确定一个决策或一项成果。 - **先发散,再收敛,绝不同时进行。** 头脑风暴和决策需要不同的思维模式。把两者混在
写作与翻译

视频拍摄与剪辑交付说明

提供口播稿和品牌资料,填写日期并附参考视频,明确前三秒、拍摄、剪辑、字幕和各渠道导出规格。

# 视频剪辑简报(全局) 一份好的视频简报,应让拍摄人员清楚如何布置现场,让剪辑人员知道如何剪辑,无须再打电话解释。开头 three seconds 必须能单独成片。 **与 `04-script-video-global` 的区别:**脚本是口播内容(说什么,按钩子—主体—CTA组织)。这份简报是制作指导(拍什么、怎么剪、用什么音乐、叠加什么内容、如何导出)。如果还没有脚本,先运行 `04-script-video-global`,再将其中的台词粘贴到下方分镜表的“Dialogue / VO”列。 ## 信息收集 阅读 `.agents/pro
可填 1 项
✓