このドキュメントでは、Serenaのオンボーディングプロセスを各ステップごとに詳細に説明します。
オンボーディングとは
オンボーディングは、Serenaが新しいプロジェクトを初めて扱う際に、プロジェクトの構造、技術スタック、開発方法を自動的に理解するプロセスです。このプロセスにより、Serenaは以降の作業で効率的かつ正確にコードを扱えるようになります。
目的:
- プロジェクトの目的と構造の理解
- 開発に必要なコマンド(テスト、ビルド、フォーマット等)の特定
- コードスタイルと規約の把握
- プロジェクト知識の永続化(メモリファイルとして保存)
起動タイミング:
- 自動: プロジェクトをアクティベートした際、メモリファイルが存在しない場合
-
手動: ユーザーが明示的に
onboardingツールを呼び出した場合
オンボーディングフロー図
ステップ詳細解説
ステップ1: オンボーディングツール呼び出し
トリガー:
-
自動トリガー:
activate_projectツールを実行した際、.serena/memories/ディレクトリにメモリファイルが存在しない場合、Serenaは自動的にオンボーディングモードに切り替わります -
手動トリガー: ユーザーまたはAIエージェントが明示的に
onboardingツールを呼び出した場合
実装場所:
src/serena/tools/workflow_tools.py:OnboardingToolsrc/serena/resources/config/prompt_templates/simple_tool_outputs.yml:onboarding_prompt
ツールの動作:
def apply(self) -> str:
system = platform.system() # OS情報を取得(Windows, Linux, Darwin等)
return self.prompt_factory.create_onboarding_prompt(system=system)
このツールは、AIエージェントに対して以下の指示を含むプロンプトを返します:
収集すべき情報:
- プロジェクトの目的
- 使用技術スタック
- コードスタイルと規約(命名規則、型ヒント、ドキュメント文字列等)
- タスク完了時に実行すべきコマンド(リント、フォーマット、テスト等)
- コードベースの大まかな構造
- テスト、フォーマット、リントのコマンド
- プロジェクトのエントリーポイント実行コマンド
- システムユーティリティコマンド(git, ls, cd, grep, find等)
- 特定のガイドライン、スタイル、デザインパターン
重要な指示:
- 必要なファイルとディレクトリのみを読み込む(メモリ節約のため)
- プロジェクトから情報が得られない場合はユーザーに質問する
- 情報収集後、複数回の
write_memoryツール呼び出しでメモリファイルに保存する - 特に重要なのは
suggested_commands.mdファイル(開発に必要なコマンド一覧) - スタイルと規約用のメモリファイル作成
- タスク完了時の手順用メモリファイル作成
ステップ2: プロジェクト構造分析
このステップでは、AIエージェントがプロジェクトの全体像を把握するために、ディレクトリツリーとファイル構成を分析します。
使用するツール:
-
list_directory_tree- ディレクトリ構造の可視化 -
search_files_for_pattern- 特定のファイルパターンの検索 -
read_file- ファイル内容の読み取り
2-1. ディレクトリツリー取得
# 例: list_directory_tree ツールの実行
list_directory_tree(
path=".",
max_depth=3, # 深すぎると情報過多になるため適度な深さに制限
exclude_patterns=[".git", "node_modules", "__pycache__", "venv"]
)
出力例:
project-root/
├── src/
│ ├── main.py
│ ├── utils/
│ │ ├── __init__.py
│ │ └── helpers.py
│ └── models/
├── tests/
│ ├── test_main.py
│ └── test_utils.py
├── README.md
├── requirements.txt
└── pyproject.toml
2-2. 重要ファイル特定
AIエージェントは以下のような重要ファイルを特定します:
プロジェクトメタデータファイル:
-
README.md/README.rst- プロジェクトの説明 -
package.json(Node.js/TypeScript) -
requirements.txt/pyproject.toml/setup.py(Python) -
Cargo.toml(Rust) -
pom.xml/build.gradle(Java) -
go.mod(Go) -
composer.json(PHP) -
Gemfile(Ruby)
設定ファイル:
-
.gitignore- 無視されるファイルのパターン(どこにコードがないかを理解) -
.eslintrc/tslint.json- JavaScript/TypeScript リント設定 -
.pylintrc/mypy.ini/pyproject.toml- Python リント・型チェック設定 -
.prettierrc/.editorconfig- コードフォーマット設定 -
tsconfig.json- TypeScript 設定 -
pytest.ini/jest.config.js- テスト設定
2-3. ソースファイル数・種類カウント
# 例: 各言語のファイル数をカウント
search_files_for_pattern(pattern="*.py") # Python
search_files_for_pattern(pattern="*.ts") # TypeScript
search_files_for_pattern(pattern="*.rs") # Rust
search_files_for_pattern(pattern="*.go") # Go
この情報から以下を推定:
- 主要プログラミング言語(最も多いファイルタイプ)
- マルチ言語プロジェクトかどうか
- プロジェクトの規模(ファイル数)
ステップ3: 重要ファイル読み取り
特定された重要ファイルを読み取り、プロジェクトの詳細情報を取得します。
3-1. README.md の読み取り
read_file("README.md")
取得情報:
- プロジェクトの目的と概要
- インストール手順
- 使用方法
- 開発セットアップ手順
- 貢献ガイドライン
- ライセンス情報
例:
# MyProject
A Python-based web scraper for collecting data.
## Installation
pip install -r requirements.txt
## Usage
python src/main.py --url https://example.com
## Development
- Run tests: pytest
- Format code: black .
- Type check: mypy src/
この情報から、Serenaは:
- プロジェクトがPython製のWebスクレイパーであることを理解
- テストコマンド:
pytest - フォーマットコマンド:
black . - 型チェックコマンド:
mypy src/
を特定できます。
3-2. 依存関係ファイルの読み取り
Python (requirements.txt または pyproject.toml):
read_file("requirements.txt")
# または
read_file("pyproject.toml")
取得情報:
# requirements.txt の例
requests==2.28.0
beautifulsoup4==4.11.1
pytest==7.2.0
black==22.10.0
mypy==0.991
ここから以下を推定:
-
requests,beautifulsoup4→ Web スクレイピングライブラリ -
pytest→ テストフレームワーク -
black→ コードフォーマッター -
mypy→ 型チェッカー
Node.js (package.json):
read_file("package.json")
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"test": "jest",
"build": "webpack",
"start": "node dist/index.js",
"lint": "eslint src/",
"format": "prettier --write src/"
},
"dependencies": {
"express": "^4.18.0",
"mongoose": "^6.7.0"
},
"devDependencies": {
"jest": "^29.0.0",
"webpack": "^5.74.0",
"eslint": "^8.25.0",
"prettier": "^2.7.0"
}
}
ここから以下を特定:
- テストコマンド:
npm test(jest を実行) - ビルドコマンド:
npm run build(webpack を実行) - 起動コマンド:
npm start - リントコマンド:
npm run lint - フォーマットコマンド:
npm run format - 技術スタック: Express.js + MongoDB (mongoose)
3-3. .gitignore の読み取り
read_file(".gitignore")
取得情報:
node_modules/
dist/
.env
*.log
__pycache__/
.pytest_cache/
ここから以下を理解:
-
node_modules/→ Node.js プロジェクト -
dist/→ ビルド成果物ディレクトリ -
__pycache__/,.pytest_cache/→ Python プロジェクト -
.env→ 環境変数ファイル(機密情報を含む可能性)
3-4. 主要設定ファイルの読み取り
例: tsconfig.json (TypeScript):
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src"
}
}
ここから:
- ソースディレクトリ:
./src - 出力ディレクトリ:
./dist - 厳格な型チェック有効
- ES2020 ターゲット
ステップ4: エントリーポイント推定
プロジェクトのメイン実行ファイル(エントリーポイント)を特定します。
4-1. エントリーポイントファイルの特定
言語ごとの一般的なエントリーポイント:
| 言語 | 一般的なエントリーポイント |
|---|---|
| Python |
main.py, __main__.py, app.py, run.py, cli.py
|
| TypeScript/JavaScript |
index.ts, index.js, main.ts, app.ts, server.ts
|
| Rust |
main.rs, lib.rs
|
| Go | main.go |
| Java |
Main.java, Application.java, *Application.java (Spring Boot) |
| C# |
Program.cs, Startup.cs
|
| Ruby |
main.rb, app.rb
|
検出方法:
- package.json の scripts セクションから:
{
"scripts": {
"start": "node dist/index.js"
}
}
→ エントリーポイント: dist/index.js (ビルド後) → ソース: src/index.ts
- pyproject.toml の scripts セクションから:
[project.scripts]
myapp = "myapp.main:main"
→ エントリーポイント: myapp/main.py の main() 関数
- ファイル名パターンマッチング:
search_files_for_pattern(pattern="main.py")
search_files_for_pattern(pattern="index.ts")
4-2. シンボル概要取得
エントリーポイントが特定されたら、LSP (Language Server Protocol) を使用してシンボル情報を取得します。
# 例: main.py のシンボル概要を取得
request_full_symbol_tree(file_path="src/main.py")
取得されるシンボル情報:
[
{
"name": "main",
"kind": "Function",
"range": {"start": {"line": 10, "character": 0}, "end": {"line": 25, "character": 0}},
"children": []
},
{
"name": "parse_arguments",
"kind": "Function",
"range": {"start": {"line": 5, "character": 0}, "end": {"line": 8, "character": 0}},
"children": []
},
{
"name": "App",
"kind": "Class",
"range": {"start": {"line": 30, "character": 0}, "end": {"line": 50, "character": 0}},
"children": [
{
"name": "__init__",
"kind": "Method",
"range": {"start": {"line": 31, "character": 4}, "end": {"line": 35, "character": 0}}
},
{
"name": "run",
"kind": "Method",
"range": {"start": {"line": 37, "character": 4}, "end": {"line": 45, "character": 0}}
}
]
}
]
この情報から理解できること:
- メイン関数:
main() - 引数パーサー:
parse_arguments() - 主要クラス:
App(コンストラクタとrun()メソッドを持つ) - コードの構造と設計パターン
重要: この段階で、Serenaはシンボルレベルでコードを理解し始めます。これにより、後の編集操作で高い精度を実現できます。
ステップ5: テスト方法推定
プロジェクトのテスト戦略とテスト実行方法を特定します。
5-1. テストディレクトリ検出
一般的なテストディレクトリパターン:
-
tests/,test/ -
__tests__/(JavaScript/TypeScript) -
spec/(Ruby, JavaScript) -
src/*_test.go(Go - テストファイルがソースと同じディレクトリ)
# テストディレクトリの検出
list_directory_tree(path="tests", max_depth=2)
# または
search_files_for_pattern(pattern="test_*.py")
search_files_for_pattern(pattern="*.test.ts")
search_files_for_pattern(pattern="*_test.go")
5-2. テストフレームワーク特定
検出方法:
- 依存関係ファイルから:
# requirements.txt または pyproject.toml から
pytest==7.2.0
unittest2==1.1.0
# package.json から
"jest": "^29.0.0"
"mocha": "^10.0.0"
"vitest": "^0.25.0"
# Cargo.toml から (Rustは標準ライブラリにテスト機能がある)
[dev-dependencies]
- テストファイルの内容から:
read_file("tests/test_main.py")
# pytest を使用している例
import pytest
from myapp.main import main
def test_main():
result = main()
assert result == expected_value
@pytest.fixture
def app():
return App()
インポート文 import pytest と @pytest.fixture デコレータから、pytest を使用していることが分かります。
言語ごとの一般的なテストフレームワーク:
| 言語 | テストフレームワーク |
|---|---|
| Python | pytest, unittest, nose2 |
| TypeScript/JavaScript | Jest, Mocha, Jasmine, Vitest, AVA |
| Rust | Cargo test (標準), Criterion (ベンチマーク) |
| Go | go test (標準), Testify |
| Java | JUnit, TestNG, Mockito |
| C# | NUnit, xUnit, MSTest |
| Ruby | RSpec, Minitest |
| PHP | PHPUnit |
5-3. テストコマンド推定
検出優先順位:
- README.md から:
## Testing
Run tests with:
```bash
pytest tests/ -v
2. **package.json の scripts から**:
```json
{
"scripts": {
"test": "jest --coverage",
"test:watch": "jest --watch",
"test:unit": "jest tests/unit",
"test:integration": "jest tests/integration"
}
}
→ テストコマンド: npm test (カバレッジ付き jest)
- pyproject.toml から:
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = "-v --cov=src"
→ テストコマンド: pytest (自動的に tests/ ディレクトリを検索、カバレッジ付き)
- Makefile から:
test:
pytest tests/ --cov=src --cov-report=html
test-quick:
pytest tests/unit/
→ テストコマンド: make test または pytest tests/ --cov=src --cov-report=html
-
CI設定ファイルから (
.github/workflows/test.yml):
- name: Run tests
run: |
pytest tests/ --cov=src --cov-report=xml
最終的に特定されるテスト情報:
- テストフレームワーク: pytest
- テストコマンド:
pytest tests/ -v --cov=src - テストディレクトリ:
tests/ - カバレッジツール: pytest-cov
- テストファイルパターン:
test_*.py
ステップ6: ビルド方法推定
プロジェクトのビルドプロセスとビルドツールを特定します。
注意: インタープリタ言語(Python, Ruby, PHPなど)の場合、ビルドステップが存在しない場合もあります。
6-1. ビルドツール特定
言語ごとの一般的なビルドツール:
| 言語 | ビルドツール |
|---|---|
| TypeScript/JavaScript | webpack, Rollup, esbuild, Vite, Parcel, tsc |
| Rust | cargo |
| Go | go build |
| Java | Maven (mvn), Gradle |
| C# | MSBuild, dotnet build |
| C/C++ | Make, CMake, Ninja |
| Scala | sbt |
| Kotlin | Gradle, Maven |
検出方法:
- 設定ファイルの存在:
# webpack
read_file("webpack.config.js")
# Vite
read_file("vite.config.ts")
# Cargo
read_file("Cargo.toml")
# Maven
read_file("pom.xml")
# Gradle
read_file("build.gradle") または read_file("build.gradle.kts")
- package.json の scripts から:
{
"scripts": {
"build": "webpack --mode production",
"build:dev": "webpack --mode development",
"build:watch": "webpack --watch"
}
}
→ ビルドツール: webpack、ビルドコマンド: npm run build
6-2. ビルドコマンド推定
例1: TypeScript プロジェクト (webpack)
webpack.config.js:
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
package.json:
{
"scripts": {
"build": "webpack --mode production"
}
}
特定されるビルド情報:
- ビルドツール: webpack
- ビルドコマンド:
npm run buildまたはwebpack --mode production - エントリーポイント:
./src/index.ts - 出力ディレクトリ:
dist/ - 出力ファイル:
bundle.js
例2: Rust プロジェクト (Cargo)
Cargo.toml:
[package]
name = "myapp"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0"
tokio = { version = "1", features = ["full"] }
[[bin]]
name = "myapp"
path = "src/main.rs"
特定されるビルド情報:
- ビルドツール: cargo
- ビルドコマンド:
cargo build(デバッグ) またはcargo build --release(リリース) - バイナリ名:
myapp - エントリーポイント:
src/main.rs - 出力パス:
target/debug/myappまたはtarget/release/myapp
例3: Java プロジェクト (Maven)
pom.xml:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myapp</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
特定されるビルド情報:
- ビルドツール: Maven
- ビルドコマンド:
mvn compile(コンパイル) またはmvn package(JARファイル作成) - Javaバージョン: 17
- 出力ディレクトリ:
target/ - 成果物:
target/myapp-1.0-SNAPSHOT.jar
例4: Python プロジェクト (ビルド不要、ただし配布パッケージの場合)
pyproject.toml:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "myapp"
version = "1.0.0"
特定されるビルド情報:
- ビルドツール: hatchling (PEP 517準拠)
- ビルドコマンド:
python -m build(配布用 wheel/sdist 作成) - 出力ディレクトリ:
dist/ - 通常の実行: ビルド不要(インタープリタ言語)
ステップ7: アーキテクチャ理解
プロジェクトの全体的なアーキテクチャ、デザインパターン、主要コンポーネントを理解します。
7-1. 主要モジュール/パッケージ特定
方法:
- ディレクトリ構造の分析:
src/
├── controllers/ → MVCのController層
├── models/ → MVCのModel層
├── views/ → MVCのView層
├── services/ → ビジネスロジック層
├── repositories/ → データアクセス層
├── utils/ → ユーティリティ
└── config/ → 設定
この構造から、レイヤードアーキテクチャ または MVC パターン を使用していることが推定されます。
- 主要ファイルのシンボルツリー取得:
# 各主要モジュールのシンボル構造を取得
request_full_symbol_tree("src/models/user.py")
request_full_symbol_tree("src/controllers/user_controller.py")
request_full_symbol_tree("src/services/user_service.py")
例: models/user.py
class User:
def __init__(self, id: int, name: str, email: str):
self.id = id
self.name = name
self.email = email
def to_dict(self) -> dict:
return {"id": self.id, "name": self.name, "email": self.email}
シンボルツリー:
User (Class)
├── __init__ (Method)
└── to_dict (Method)
例: controllers/user_controller.py
class UserController:
def __init__(self, user_service: UserService):
self.user_service = user_service
def get_user(self, user_id: int) -> User:
return self.user_service.find_user_by_id(user_id)
def create_user(self, name: str, email: str) -> User:
return self.user_service.create_user(name, email)
シンボルツリー:
UserController (Class)
├── __init__ (Method)
├── get_user (Method)
└── create_user (Method)
7-2. 依存関係分析
import文の分析:
# user_controller.py
from models.user import User
from services.user_service import UserService
from repositories.user_repository import UserRepository
依存関係グラフ:
UserController
↓ depends on
UserService
↓ depends on
UserRepository
↓ depends on
Database
依存性注入 (DI) パターンの検出:
class UserController:
def __init__(self, user_service: UserService): # ← DIコンストラクタ
self.user_service = user_service
7-3. デザインパターン推定
検出可能なパターン:
- MVCパターン:
-
controllers/ディレクトリの存在 -
models/ディレクトリの存在 -
views/またはtemplates/ディレクトリの存在
- レイヤードアーキテクチャ:
- Controller層
- Service層(ビジネスロジック)
- Repository層(データアクセス)
- Model層(ドメインモデル)
- Repositoryパターン:
class UserRepository:
def find_by_id(self, user_id: int) -> User:
pass
def save(self, user: User) -> None:
pass
def delete(self, user_id: int) -> None:
pass
- Factoryパターン:
class UserFactory:
@staticmethod
def create_user(name: str, email: str) -> User:
return User(id=generate_id(), name=name, email=email)
- Singletonパターン:
class DatabaseConnection:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
- Strategyパターン:
class PaymentProcessor:
def __init__(self, payment_strategy: PaymentStrategy):
self.strategy = payment_strategy
def process(self, amount: float):
return self.strategy.process_payment(amount)
アーキテクチャドキュメントの読み取り:
# アーキテクチャドキュメントが存在する場合
read_file("docs/ARCHITECTURE.md")
read_file("ARCHITECTURE.md")
read_file("docs/design.md")
7-4. 技術スタックの特定
バックエンド:
- フレームワーク: Express.js, FastAPI, Django, Flask, Spring Boot, ASP.NET Core
- データベース: PostgreSQL, MySQL, MongoDB, Redis
- ORM: SQLAlchemy, TypeORM, Hibernate, Entity Framework
フロントエンド:
- フレームワーク: React, Vue.js, Angular, Svelte
- 状態管理: Redux, Vuex, Pinia, MobX
- UIライブラリ: Material-UI, Ant Design, Tailwind CSS
依存関係ファイルから推定:
// package.json
{
"dependencies": {
"express": "^4.18.0", // → Expressフレームワーク
"mongoose": "^6.7.0", // → MongoDB ODM
"jsonwebtoken": "^9.0.0", // → JWT認証
"bcrypt": "^5.1.0" // → パスワードハッシュ化
}
}
特定されるアーキテクチャ情報:
- アーキテクチャスタイル: レイヤードアーキテクチャ + MVC
- 主要パターン: Repository, Dependency Injection, Factory
- 技術スタック: Express.js + MongoDB + JWT認証
- データフロー: Controller → Service → Repository → Database
ステップ8: メモリ作成
収集した情報を構造化されたMarkdownファイルとして保存します。これらのメモリファイルは、今後のセッションで再利用されます。
保存場所: <project_root>/.serena/memories/
8-1. project_structure.md
プロジェクトの構造と概要を記述します。
内容例:
# Project Structure
## Overview
This is a Python-based web scraper application for collecting data from e-commerce websites.
## Directory Structure
```
project-root/
├── src/ # ソースコード
│ ├── main.py # エントリーポイント
│ ├── scraper/ # スクレイピングロジック
│ ├── parser/ # HTML/JSONパーサー
│ ├── storage/ # データ保存
│ └── utils/ # ユーティリティ関数
├── tests/ # テストコード
│ ├── test_scraper.py
│ ├── test_parser.py
│ └── fixtures/ # テストデータ
├── config/ # 設定ファイル
└── docs/ # ドキュメント
```
## Tech Stack
- Language: Python 3.11
- Key Libraries:
- requests (HTTP クライアント)
- beautifulsoup4 (HTML パーサー)
- pandas (データ処理)
- sqlalchemy (データベースORM)
## Main Components
- `Scraper`: ウェブページからデータを取得
- `Parser`: HTML/JSONをパース
- `Storage`: データをDBに保存
- `Scheduler`: 定期実行管理
## Entry Points
- Main application: `python src/main.py --url <URL>`
- Scheduled job: `python src/scheduler.py`
ツール呼び出し:
write_memory(
memory_name="project_structure.md",
content=project_structure_content
)
8-2. how_to_test.md
テスト方法とテスト戦略を記述します。
内容例:
# How to Test
## Test Framework
- Framework: pytest
- Coverage tool: pytest-cov
## Running Tests
### All tests
```bash
pytest tests/ -v
With coverage
pytest tests/ --cov=src --cov-report=html
Specific test file
pytest tests/test_scraper.py -v
Specific test function
pytest tests/test_scraper.py::test_fetch_page -v
Watch mode (requires pytest-watch)
ptw tests/
Test Structure
-
tests/test_scraper.py: スクレイピング機能のテスト -
tests/test_parser.py: パーサーのテスト -
tests/test_storage.py: データ保存のテスト -
tests/fixtures/: テスト用のHTMLサンプル
Test Conventions
- Test files:
test_*.py - Test functions:
test_* - Fixtures:
conftest.pyに定義 - Mock data:
tests/fixtures/に配置
CI/CD
- GitHub Actions で自動実行
- Pull Request ごとにテスト実行
- マージ前にカバレッジ80%以上が必須
**ツール呼び出し**:
```python
write_memory(
memory_name="how_to_test.md",
content=how_to_test_content
)
8-3. how_to_build.md
ビルド方法とデプロイ手順を記述します。
内容例(TypeScript プロジェクトの場合):
# How to Build
## Build Tool
- Tool: webpack 5
- Config: `webpack.config.js`
## Build Commands
### Production build
```bash
npm run build
# または
webpack --mode production
Development build
npm run build:dev
# または
webpack --mode development
Watch mode
npm run build:watch
# または
webpack --watch
Build Output
- Output directory:
dist/ - Entry point:
src/index.ts - Bundle file:
dist/bundle.js - Source maps:
dist/bundle.js.map(dev mode only)
Build Steps
- TypeScript compilation (ts-loader)
- Module bundling (webpack)
- Minification (production only)
- Source map generation (dev only)
Environment Variables
Create .env file:
API_URL=https://api.example.com
API_KEY=your_api_key
NODE_ENV=production
Deployment
# Build for production
npm run build
# Deploy to server
scp -r dist/ user@server:/var/www/app/
# Or deploy to cloud (e.g., AWS S3)
aws s3 sync dist/ s3://my-bucket/
**ツール呼び出し**:
```python
write_memory(
memory_name="how_to_build.md",
content=how_to_build_content
)
8-4. architecture.md
アーキテクチャとデザインパターンを記述します。
内容例:
# Architecture
## Architectural Style
Layered Architecture with MVC pattern
## Layers
### 1. Controller Layer (`src/controllers/`)
- HTTP リクエストの受付
- 入力バリデーション
- Service層の呼び出し
- レスポンス生成
### 2. Service Layer (`src/services/`)
- ビジネスロジック
- トランザクション管理
- Repository層の呼び出し
### 3. Repository Layer (`src/repositories/`)
- データベースアクセス
- クエリの構築
- ORM操作
### 4. Model Layer (`src/models/`)
- ドメインモデル
- データ構造の定義
- バリデーションルール
## Design Patterns
### Repository Pattern
データアクセスの抽象化
```python
class UserRepository:
def find_by_id(self, user_id: int) -> User:
pass
def save(self, user: User) -> None:
pass
Dependency Injection
コンストラクタインジェクション
class UserController:
def __init__(self, user_service: UserService):
self.user_service = user_service
Factory Pattern
複雑なオブジェクト生成
class UserFactory:
@staticmethod
def create_user(data: dict) -> User:
return User(**data)
Data Flow
HTTP Request
↓
Controller (validation)
↓
Service (business logic)
↓
Repository (data access)
↓
Database
↓
Repository (model creation)
↓
Service (transformation)
↓
Controller (response formatting)
↓
HTTP Response
Key Components
UserController
-
POST /users: ユーザー作成 -
GET /users/:id: ユーザー取得 -
PUT /users/:id: ユーザー更新 -
DELETE /users/:id: ユーザー削除
UserService
-
create_user(): ユーザー作成ビジネスロジック -
find_user(): ユーザー検索 -
update_user(): ユーザー更新 -
delete_user(): ユーザー削除
UserRepository
-
save(): DBへの保存 -
find_by_id(): ID検索 -
find_by_email(): メール検索 -
delete(): 削除
Technology Stack
- Framework: Express.js
- Database: PostgreSQL
- ORM: TypeORM
- Authentication: JWT
- Validation: class-validator
**ツール呼び出し**:
```python
write_memory(
memory_name="architecture.md",
content=architecture_content
)
8-5. key_symbols.md
重要なシンボル(クラス、関数、定数など)のリストを記述します。
内容例:
# Key Symbols
## Classes
### User (`src/models/user.py`)
ユーザードメインモデル
- Fields: id, name, email, created_at
- Methods: to_dict(), validate()
### UserController (`src/controllers/user_controller.py`)
ユーザー操作のコントローラー
- Methods: get_user(), create_user(), update_user(), delete_user()
### UserService (`src/services/user_service.py`)
ユーザー関連のビジネスロジック
- Methods: find_user_by_id(), create_user(), send_welcome_email()
### UserRepository (`src/repositories/user_repository.py`)
ユーザーデータアクセス
- Methods: save(), find_by_id(), find_by_email(), delete()
## Functions
### parse_arguments (`src/main.py`)
コマンドライン引数のパース
- Args: None
- Returns: argparse.Namespace
### setup_logging (`src/utils/logger.py`)
ログ設定の初期化
- Args: log_level: str
- Returns: logging.Logger
### connect_database (`src/database.py`)
データベース接続
- Args: config: DatabaseConfig
- Returns: Connection
## Constants
### DATABASE_URL (`src/config.py`)
データベース接続URL
### API_VERSION (`src/config.py`)
APIバージョン文字列
### MAX_RETRY_COUNT (`src/config.py`)
最大リトライ回数
## Important Variables
### app (`src/main.py`)
Express アプリケーションインスタンス
### db (`src/database.py`)
データベース接続オブジェクト
### logger (`src/utils/logger.py`)
アプリケーション全体で使用するロガー
ツール呼び出し:
write_memory(
memory_name="key_symbols.md",
content=key_symbols_content
)
8-6. suggested_commands.md (特に重要)
開発に必要なコマンド一覧を記述します。
内容例:
# Suggested Commands
## Setup
### Install dependencies
```bash
pip install -r requirements.txt
Setup database
python scripts/setup_db.py
Development
Run application
python src/main.py --config config/dev.yml
Run with auto-reload
watchmedo auto-restart -d src/ -p "*.py" -- python src/main.py
Testing
Run all tests
pytest tests/ -v
Run with coverage
pytest tests/ --cov=src --cov-report=html
Run specific test
pytest tests/test_scraper.py::test_fetch_page -v
Code Quality
Format code
black src/ tests/
Lint code
pylint src/
Type check
mypy src/
Run all checks (format + lint + type)
black src/ tests/ && pylint src/ && mypy src/
Building
Build (if applicable)
# Not required for Python (interpreted language)
Database
Run migrations
alembic upgrade head
Create migration
alembic revision --autogenerate -m "description"
Rollback migration
alembic downgrade -1
Git
Commit workflow
git add .
git commit -m "descriptive message"
git push origin feature-branch
Before commit checklist
- Run tests:
pytest tests/ -v - Format code:
black src/ tests/ - Type check:
mypy src/ - Lint:
pylint src/
Deployment
Deploy to production
./scripts/deploy.sh production
Deploy to staging
./scripts/deploy.sh staging
Task Completion Workflow
When a task is completed, always run:
-
black src/ tests/- Format code -
mypy src/- Type check -
pylint src/- Lint -
pytest tests/ -v- Run tests
If all pass, commit the changes.
**ツール呼び出し**:
```python
write_memory(
memory_name="suggested_commands.md",
content=suggested_commands_content
)
8-7. その他のメモリファイル(オプション)
プロジェクトによっては、以下のような追加のメモリファイルも作成される場合があります:
-
code_style.md: コーディング規約とスタイルガイド -
api_documentation.md: APIエンドポイントの一覧 -
environment_setup.md: 開発環境のセットアップ手順 -
troubleshooting.md: よくある問題と解決方法 -
dependencies.md: 依存関係の説明
すべてのメモリファイルの特徴:
- Markdown形式: 人間が読みやすく、編集しやすい
-
プロジェクト固有:
.serena/memories/に保存され、そのプロジェクト専用 - 永続化: セッションをまたいで利用可能
- 手動編集可能: ユーザーが直接編集して情報を追加・修正できる
- AIが参照: 今後の作業でSerenaがこれらを読み込み、コンテキストとして利用
ステップ9: オンボーディング完了フラグ設定
オンボーディングが完了したことを記録します。
9-1. 完了フラグファイルの作成
通常、以下のいずれかの方法で完了を記録します:
-
メモリファイルの存在自体が完了フラグ:
-
.serena/memories/ディレクトリにメモリファイルが存在すれば、オンボーディング完了とみなす -
CheckOnboardingPerformedToolはメモリファイルの有無をチェック:
def apply(self) -> str: memories = json.loads(list_memories_tool.apply()) if len(memories) == 0: return "Onboarding not performed yet" else: return "The onboarding was already performed" -
-
専用の完了フラグファイル (プロジェクトによっては):
touch .serena/onboarding_completeまたは
write_memory( memory_name="onboarding_status.md", content="Onboarding completed at 2025-10-25 12:00:00" )
9-2. チェックポイント
オンボーディング完了前に、以下を確認します:
必須メモリファイル:
- ✓
project_structure.mdが作成された - ✓
how_to_test.mdが作成された - ✓
suggested_commands.mdが作成された
推奨メモリファイル:
- ✓
architecture.mdが作成された(複雑なプロジェクトの場合) - ✓
how_to_build.mdが作成された(コンパイル言語の場合) - ✓
key_symbols.mdが作成された
情報の完全性:
- ✓ テストコマンドが特定された
- ✓ フォーマット/リントコマンドが特定された
- ✓ エントリーポイントが特定された
- ✓ 主要な技術スタックが特定された
9-3. ログ記録
Serenaはオンボーディングプロセスをログに記録します:
[INFO] Onboarding started for project: /path/to/project
[INFO] Project structure analyzed: Python project with 45 files
[INFO] Test framework detected: pytest
[INFO] Build tool detected: Not required (interpreted language)
[INFO] Entry point identified: src/main.py
[INFO] Memory created: project_structure.md
[INFO] Memory created: how_to_test.md
[INFO] Memory created: suggested_commands.md
[INFO] Memory created: architecture.md
[INFO] Memory created: key_symbols.md
[INFO] Onboarding completed successfully
ステップ10: 通常モードに切り替え
オンボーディングが完了したら、Serenaは通常の作業モードに切り替わります。
10-1. モード切り替えの仕組み
オンボーディングモード:
- 目的: プロジェクトの理解と情報収集
- 制限: コード編集ツールが無効化されている場合がある
- 許可されるツール:
list_directory_treesearch_files_for_patternread_filerequest_full_symbol_treewrite_memory-
execute_shell_command(情報収集用)
通常モード (editing, planning, interactiveなど):
- 目的: 実際の開発作業
- すべてのツールが利用可能:
- シンボル検索ツール
- シンボル編集ツール (
replace_symbol_body) - ファイル編集ツール (
replace_regex) - メモリ読み書きツール
- シェルコマンド実行
モード切り替えコード (SerenaAgent内部):
# オンボーディング状態確認
if not self.is_onboarding_completed():
self.switch_mode("onboarding")
else:
self.switch_mode(["editing", "interactive"])
10-2. 通常モードでの初回動作
オンボーディング完了後、ユーザーが初めてタスクを依頼すると:
- メモリファイルの確認:
check_onboarding_performed()
返答例:
The onboarding was already performed. Available memories:
- project_structure.md
- how_to_test.md
- how_to_build.md
- architecture.md
- key_symbols.md
- suggested_commands.md
Do not read them immediately, just remember that they exist.
You can read them later if necessary for the current task.
- タスクに応じたメモリ読み込み:
例: ユーザーが "Add a new API endpoint for user deletion" と依頼
Serenaは以下のメモリを読み込む可能性があります:
# アーキテクチャ理解のため
read_memory("architecture.md")
# 既存のコード構造理解のため
read_memory("key_symbols.md")
# タスク完了時の手順確認のため (テスト実行、フォーマット等)
read_memory("suggested_commands.md")
-
作業開始:
通常の開発ツールを使用して作業を開始:
# 既存のUserController を検索
find_symbol(query="UserController")
# UserController のシンボル情報取得
request_full_symbol_tree("src/controllers/user_controller.py")
# delete_user メソッドを追加
replace_symbol_body(
symbol_path="src/controllers/user_controller.py:UserController",
new_body=new_controller_code
)
# テスト実行
execute_shell_command("pytest tests/test_user_controller.py -v")
10-3. オンボーディング情報の活用
オンボーディングで収集した情報は、以下のように活用されます:
コード編集時:
-
architecture.mdから既存のデザインパターンを理解 - 新しいコードも同じパターンに従う
- 依存性注入、レイヤー構造を維持
テスト作成時:
-
how_to_test.mdからテストフレームワークとテストパターンを理解 - 既存のテストスタイルに合わせて新しいテストを作成
タスク完了時:
-
suggested_commands.mdから完了時の手順を確認 - フォーマット、リント、テストを順番に実行
コマンド実行時:
-
suggested_commands.mdから正しいコマンドを取得 - OS固有のコマンド(Windows vs Unix)を考慮
10-4. 継続的な学習
オンボーディング後も、Serenaはプロジェクトについて学習を続けます:
新しい情報の追加:
# 新しい設計決定を記録
write_memory(
memory_name="design_decision_auth.md",
content="JWT認証をBearerトークン方式で実装する決定..."
)
# 作業進捗の記録
write_memory(
memory_name="progress_api_redesign.md",
content="API再設計の進捗: 5/10 エンドポイント完了..."
)
既存メモリの更新:
- ユーザーが
.serena/memories/内のファイルを直接編集可能 - Serenaも必要に応じてメモリを更新(ただし通常は追加のみ)
オンボーディングのベストプラクティス
ユーザー側のベストプラクティス
-
README.mdを充実させる:
- プロジェクトの目的
- セットアップ手順
- 開発コマンド
- テスト方法
-
設定ファイルを整える:
-
package.jsonの scripts セクション -
pyproject.tomlの設定 - テスト設定ファイル
-
-
初回は手動でオンボーディングを確認:
# オンボーディング後、メモリファイルを確認 cat .serena/memories/suggested_commands.md -
不正確な情報があれば修正:
# 直接編集可能 vim .serena/memories/how_to_test.md
Serena側のベストプラクティス
-
必要最小限のファイルのみ読み込む:
- すべてのファイルを読むのではなく、重要なファイルのみ
- トークン効率を重視
-
ユーザーに質問する:
- 不明な点があれば推測せずに質問
- 例: "テストコマンドが見つかりませんでした。どのコマンドでテストを実行しますか?"
-
構造化されたメモリを作成:
- 見出し、リスト、コードブロックを活用
- Markdown形式で読みやすく
-
情報の検証:
- 推測したコマンドは実際に試す(dry-runがあれば)
- 例:
npm test --listTestsでテストファイル一覧を確認
オンボーディング完了後の動作例
シナリオ: バグ修正タスク
ユーザー: "fix the bug in user login function"
Serenaの動作:
- メモリ確認:
check_onboarding_performed()
# → "Onboarding already performed. Memories available."
- 関連メモリ読み込み:
read_memory("architecture.md") # ログイン機能がどの層にあるか確認
read_memory("key_symbols.md") # login関数の場所確認
- シンボル検索:
find_symbol(query="login")
# → Found: src/services/auth_service.py:AuthService.login
- コード読み取り:
request_full_symbol_tree("src/services/auth_service.py")
read_file("src/services/auth_service.py")
- バグ修正:
replace_symbol_body(
symbol_path="src/services/auth_service.py:AuthService.login",
new_body=fixed_code
)
- タスク完了手順確認:
read_memory("suggested_commands.md")
# → format: black src/, test: pytest tests/, lint: pylint src/
- コマンド実行:
execute_shell_command("black src/services/auth_service.py")
execute_shell_command("pytest tests/test_auth_service.py -v")
execute_shell_command("pylint src/services/auth_service.py")
結果: オンボーディングで収集した情報により、Serenaは:
- 正確にlogin関数を見つけた
- アーキテクチャに従って修正した
- 適切なテストを実行した
- プロジェクトのコーディング規約に従った
まとめ
Serenaのオンボーディングフローは、以下の10ステップで構成されています:
- オンボーディングツール呼び出し: 自動または手動でプロセス開始
- プロジェクト構造分析: ディレクトリツリーとファイル構成の把握
- 重要ファイル読み取り: README、依存関係ファイル、設定ファイルの読み取り
- エントリーポイント推定: メイン実行ファイルとシンボルの特定
- テスト方法推定: テストフレームワークとテストコマンドの特定
- ビルド方法推定: ビルドツールとビルドコマンドの特定
- アーキテクチャ理解: デザインパターンと技術スタックの理解
- メモリ作成: 収集した情報をMarkdownファイルとして永続化
- オンボーディング完了フラグ設定: 完了状態の記録
- 通常モードに切り替え: 実際の開発作業モードへ移行
このプロセスにより、Serenaは:
- プロジェクトの構造と目的を理解
- 開発に必要なコマンドを把握
- コードスタイルと規約を学習
- 今後の作業で高精度なコード操作を実現
オンボーディングは一度だけ実行され、その後はメモリファイルを参照して効率的に作業を行います。