跳至主要內容

建置開發助理

本指南將帶你建置一個整合所有 Workspace 功能的完整開發助理:

你將建立包含範例專案的 Workspace,並以 Skill 加入程式碼規範。接著,你會建立一個依循 TDD 實務撰寫程式碼的 Agent。完成後,Agent 將能讀取現有程式碼、撰寫新的實作,然後在 Sandbox 中執行測試,並根據結果反覆調整。

先決條件
「先決條件」的直接連結

  • 已安裝 Node.js v22.13.0 或更新版本
  • 受支援的 Model Provider 所提供的 API 金鑰
  • 現有的 Mastra 專案(請依照安裝指南建立新專案)

安裝 Vitest
「安裝 Vitest」的直接連結

開發助理會使用 Vitest 在 Workspace Sandbox 內執行測試。請將它安裝為專案的開發相依套件:

npm install -D vitest

設定 Workspace
「設定 Workspace」的直接連結

Workspace 使用本機 filesystem 管理文件檔案。Agent 會讀寫 Workspace 目錄內的檔案。在 src/mastra/index.ts 檔案中,匯入 WorkspaceLocalFilesystemLocalSandbox 類別。

此外,請啟用 BM25 搜尋索引,並從 skills 目錄載入 Skills。

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { resolve } from 'node:path'
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'

const workspace = new Workspace({
filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }),
sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }),
skills: ['skills'],
bm25: true,
autoIndexPaths: ['docs', 'src'],
})

export const mastra = new Mastra({
workspace,
})

在專案根目錄建立名為 workspace 的新資料夾。Agent 會在此儲存及管理所有檔案。

新增範例專案檔案
「新增範例專案檔案」的直接連結

Workspace 採用以下資料夾結構:

  • workspace/src/:範例專案的原始碼
  • workspace/tests/:測試檔案
  • workspace/docs/:專案文件
  • workspace/skills/:以 Agent Skills 形式提供的程式碼規範與指南

首先建立包含數個公用函式的 workspace/src/utils/string-helpers.ts 檔案,以及對應的測試檔案 workspace/tests/string-helpers.test.ts

workspace/src/utils/string-helpers.ts
export function capitalize(str: string): string {
if (!str) return str
return str.charAt(0).toUpperCase() + str.slice(1)
}

export function slugify(str: string): string {
return str
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
}
workspace/tests/string-helpers.test.ts
import { describe, it, expect } from 'vitest'
import { capitalize, slugify } from '../src/utils/string-helpers'

describe('String Helpers', () => {
describe('capitalize', () => {
it('capitalizes first letter', () => {
expect(capitalize('hello')).toBe('Hello')
})
})

describe('slugify', () => {
it('converts to lowercase and replaces spaces', () => {
expect(slugify('Hello World')).toBe('hello-world')
})
})
})

workspace/skills/coding-standards/SKILL.md 建立 Skill 定義,告訴 Agent 如何撰寫及測試程式碼:

workspace/skills/coding-standards/SKILL.md
---
name: coding-standards
description: Project coding standards and testing guidelines
---

# Coding Standards

## Code quality

- Functions under 50 lines
- Use descriptive variable names
- Always add TypeScript types

## Testing

- Test all exported functions
- Use AAA pattern: Arrange, Act, Assert
- Cover happy paths and edge cases

## Before committing

1. Write implementation
2. Write comprehensive tests
3. Run tests: `npm test`
4. All tests must pass

workspace/skills/coding-standards/references/testing-guide.md 建立參考檔案,加入詳細的測試模式:

workspace/skills/coding-standards/references/testing-guide.md
# Testing Guide

## AAA pattern

```typescript
it('descriptive test name', () => {
// Arrange: Set up test data
const input = 'test'

// Act: Execute the function
const result = doSomething(input)

// Assert: Verify the result
expect(result).toBe('expected')
})
```

## What to test

- Happy paths (normal inputs)
- Edge cases (empty, null, boundary values)
- Error cases (invalid inputs, exceptions)

建立開發助理
「建立開發助理」的直接連結

Workspace 設定完成後,接著建立開發助理 Agent。此 Agent 會收到使用測試驅動開發(TDD)新增功能的指示。

建立新檔案 src/mastra/agents/dev-assistant.ts 並定義 Agent:

src/mastra/agents/dev-assistant.ts
import { Agent } from '@mastra/core/agent'

export const devAssistant = new Agent({
id: 'dev-assistant',
name: 'Dev Assistant',
instructions: `You are a development assistant.

When adding features:
1. Activate 'coding-standards' skill
2. Search workspace for similar code examples
3. Write the implementation following standards
4. Write comprehensive tests. Leave existing tests in place, only add your new tests
5. Execute the command \`npx vitest run\` to validate that all tests pass
6. Update documentation if needed

For every new feature: Write code → Write tests → Run tests → Update docs

Always explain your reasoning and steps.`,
model: 'openai/gpt-5.6-sol',
})

src/mastra/index.ts 中匯入 Agent,並向 Mastra 執行個體註冊:

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { resolve } from 'node:path'
import { Workspace, LocalFilesystem, LocalSandbox } from '@mastra/core/workspace'
import { devAssistant } from './agents/dev-assistant'

const workspace = new Workspace({
filesystem: new LocalFilesystem({ basePath: resolve(import.meta.dirname, '../../workspace') }),
sandbox: new LocalSandbox({ workingDirectory: resolve(import.meta.dirname, '../../workspace') }),
skills: ['skills'],
bm25: true,
autoIndexPaths: ['docs', 'src'],
})

export const mastra = new Mastra({
workspace,
agents: { devAssistant },
})

測試助理
「測試助理」的直接連結

啟動 Studio 並與 Agent 互動,查看實際運作情形。

npm run dev

開啟 localhost:4111,然後前往開發助理。

試著要求 Agent 使用 TDD 新增函式:

Add a 'truncate' function to string-helpers.ts that shortens strings to a max length. Add '...' if truncated.

Follow TDD: write tests first, then implementation.

由於 Agent 的回應具有非確定性,實際輸出會有所不同。不過,你應該會看到 Agent 採取類似以下的流程:

  1. 啟用 coding-standards Skill

  2. 在 Workspace 中搜尋類似的程式碼模式

  3. 先撰寫測試,例如:

    describe('truncate', () => {
    it('truncates long strings', () => {
    expect(truncate('Hello World', 5)).toBe('He...')
    })

    it('keeps short strings unchanged', () => {
    expect(truncate('Hi', 10)).toBe('Hi')
    })

    it('handles edge cases', () => {
    expect(truncate('', 5)).toBe('')
    })
    })
  4. 撰寫實作,例如:

    export function truncate(str: string, maxLength: number): string {
    if (!str || maxLength < 0) return str
    if (str.length <= maxLength) return str
    if (maxLength === 0) return '...'
    return str.slice(0, maxLength - 3) + '...'
    }
  5. 執行測試並確認全部通過

後續步驟
「後續步驟」的直接連結

你可以擴充此助理,以便:

  • 為不同語言或框架新增更多 Skills
  • 建立後端、前端或 DevOps 專用的 Agent
  • 與 GitHub 整合,自動審查 PR
  • 建置 CI/CD 自動化流程
  • 新增多 Agent Workflow