mcpField
W
workspace

workspace

github.com/alinaqi開発711191 回インストール2 週間前に更新
リポジトリ

workspace について

workspaceは、Claude Code向けのワークスペース分析スキルです。モノレポや複数リポジトリのモジュール、依存関係、API契約、主要ファイルを整理し、プロジェクト横断の情報を提供します。

主な機能

  1. 01モノレポと複数リポジトリの判定
  2. 02モジュール依存関係とAPI関係の整理
  3. 03API契約と型定義の抽出
  4. 04タスクに関連するファイルの特定
  5. 05ワークスペース分析成果物の生成

活用シーン

  1. 01フロントエンドとバックエンド間の依存関係の把握
  2. 02変更前の共有型とAPI契約の確認
  3. 03モジュール単位の作業で関連ファイルを特定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/alinaqi/maggy --skill workspace

インストール後、Claude Code で/workspaceを入力して読み込まれたか確認します。

詳細

ワークスペース分析スキル

Claude Code のための、動的なマルチリポジトリおよびモノレポ対応機能です。ワークスペースの構成を分析し、API コントラクトを追跡して、リポジトリ間のコンテキストを維持します。

問題

フロントエンドとバックエンドのリポジトリを分けている場合(または複数のアプリを含むモノレポの場合)、Claude Code はそれぞれを個別に扱います。以下の情報を把握できません。

  • モジュールやリポジトリ間の API コントラクト
  • 共有型とインターフェース
  • システム全体のアーキテクチャ
  • リポジトリ間の依存関係
  • システムの他の部分で変更された内容

その結果、次のような問題が発生します。

  • 型定義の重複
  • API コントラクトの不一致
  • 実行時まで検出されない破壊的変更
  • 他の場所にすでに存在する機能を Claude が再実装する

解決策:動的なワークスペース分析

古くなりやすい静的マニフェストの代わりに、Claude がワークスペースを動的に分析し、フックを通じて最新の状態を保つコンテキスト成果物を生成します。

┌─────────────────────────────────────────────────────────────────┐
│  WORKSPACE ANALYSIS SYSTEM                                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  /analyze-workspace (Full Analysis - ~2 min)                     │
│  ├── Topology discovery (monorepo vs multi-repo)                │
│  ├── Dependency graph (who calls whom)                          │
│  ├── Contract extraction (OpenAPI, GraphQL, types)              │
│  └── Key file identification (what to load when)                │
│                                                                  │
│  /sync-contracts (Incremental - ~15 sec)                         │
│  ├── Check contract source files for changes                    │
│  ├── Update CONTRACTS.md with diffs                             │
│  └── Validate consistency                                       │
│                                                                  │
│  Hooks (Automatic)                                               │
│  ├── Session start: Staleness advisory (~5 sec)                 │
│  ├── Post-commit: Auto-sync if contracts changed (~15 sec)      │
│  └── Pre-push: Validation gate (~10 sec)                        │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

ワークスペースの分類

検出パターン
種類判定の目印ファイルへのアクセス
モノレポpnpm-workspace.yaml、nx.json、turbo.json、lerna.json直接(同じツリー内)
マルチリポジトリ個別の .git を持つ兄弟ディレクトリシンボリックリンクまたはパス経由
ハイブリッドモノレポと外部リポジトリの依存関係混在
単一アプリが 1 つで、ワークスペース設定がない該当なし(existing-repo を使用)
モノレポの検出
# Check for monorepo indicators
ls package.json pnpm-workspace.yaml lerna.json nx.json turbo.json 2>/dev/null
ls apps/ packages/ services/ libs/ modules/ 2>/dev/null
マルチリポジトリの検出
# Check sibling directories for related repos
ls -la ../*.git 2>/dev/null
cat ../*/.git/config 2>/dev/null | grep "url"

# Look for naming patterns
ls .. | grep -E "(frontend|backend|api|web|shared|common)"
ポリグロットの検出
# Find all package manifests
find . -maxdepth 4 -name "package.json" -o -name "pyproject.toml" \
  -o -name "go.mod" -o -name "Cargo.toml" -o -name "pom.xml" \
  -o -name "build.gradle" -o -name "Gemfile"

分析プロトコル

フェーズ 1:構成の発見(約 30 秒)

ワークスペースの構造を特定します。

## Discovery Checklist

1. [ ] Identify workspace root
2. [ ] Classify workspace type (monorepo/multi-repo/hybrid/single)
3. [ ] List all modules/apps/packages
4. [ ] Detect tech stack per module
5. [ ] Identify entry points per module

モジュール検出パターン:

workspace-root/
├── apps/           → Application modules
│   ├── web/        → Frontend app
│   └── api/        → Backend app
├── packages/       → Shared packages
│   ├── ui/         → Component library
│   ├── types/      → Shared types
│   └── db/         → Database layer
├── services/       → Microservices
└── libs/           → Internal libraries
フェーズ 2:依存関係グラフ(約 60 秒)

各モジュールについて、以下をマッピングします。

1. 内部依存関係

# TypeScript/JavaScript
grep -r "from ['\"]@" --include="*.ts" --include="*.tsx" | head -50
grep -r "workspace:" package.json

# Python
grep -r "from \." --include="*.py" | head -50

2. API 関係

# Find API calls
grep -rE "fetch|axios|httpx|requests\." --include="*.ts" --include="*.py" | \
  grep -E "/api|localhost|127\.0\.0\.1" | head -30

3. データベース接続

# Find DB access patterns
grep -rE "prisma|drizzle|sqlalchemy|sequelize|typeorm" --include="*.ts" --include="*.py"
フェーズ 3:コントラクトの抽出(約 45 秒)

API コントラクトを特定して解析します。

コントラクトの種類検出方法抽出内容
OpenAPIopenapi.json、swagger.yaml、/docs エンドポイントパス、スキーマを解析
GraphQLschema.graphql、*.gql、/graphql エンドポイント型、クエリ、ミューテーションを解析
tRPCtRPC ルーターファイル、@trpc/* のインポートルーター定義を解析
Protobuf*.proto ファイルサービス、メッセージを解析
TypeScript共有 .d.ts、エクスポートされたインターフェースエクスポートされた型を解析
PydanticBaseModel を含む schemas/、models/モデル定義を解析
Zodz.object を含む schemas/スキーマ定義を解析

コントラクトソースの優先順位:

  1. 生成済みの仕様(openapi.json)— 最も正確
  2. スキーマ定義(Pydantic、Zod)— 信頼できる唯一の情報源
  3. 型エクスポート(TypeScript .d.ts)— 利用側のコントラクト
  4. コードから推測 — 最終手段
フェーズ 4:重要なファイルの特定(約 30 秒)

各コンテキストで Claude が必ず把握すべきファイルを特定します。

カテゴリ検出パターントークンの優先度
ルート定義**/routes/**、**/api/**、@app.get、@router高
型定義**/types/**、*.d.ts、schemas/、models/高
設定.env.example、config/、settings.py中
エントリーポイントmain.ts、index.ts、app.py、server.py中
API クライアント**/api/client*、**/lib/api*高
データベーススキーマschema/、migrations/、prisma/schema.prisma中
テスト__tests__/、*_test.py、*.spec.ts低(必要に応じて)

生成される成果物

すべての成果物は _project_specs/workspace/ に保存されます。

_project_specs/workspace/
├── TOPOLOGY.md           # What modules exist, their roles
├── CONTRACTS.md          # API specs, shared types (summarized)
├── DEPENDENCY_GRAPH.md   # Who calls whom (visual + list)
├── KEY_FILES.md          # What to load for each context
├── CROSS_REPO_INDEX.md   # Capabilities across all modules
└── .contract-sources     # Files to monitor for changes
TOPOLOGY.md の形式
# Workspace Topology

Generated: 2026-01-20T14:32:00Z
Analyzer: maggy/workspace-analysis
Workspace Type: Monorepo (Turborepo)

## Overview

┌─────────────────────────────────────────────────┐ │ apps/web (Next.js) ←→ apps/api (FastAPI) │ │ ↓ ↓ │ │ packages/shared-types ← packages/db │ └─────────────────────────────────────────────────┘


## Modules

### apps/web
- **Path**: /apps/web
- **Tech**: Next.js 14, TypeScript, TailwindCSS
- **Role**: Customer-facing dashboard
- **Consumes**: apps/api (REST), packages/shared-types
- **Entry**: src/app/layout.tsx
- **Key files**:
  - `src/lib/api/client.ts` - API client (187 lines)
  - `src/types/` - Frontend-specific types (12 files)
- **Token estimate**: ~15K (full), ~4K (summarized)

### apps/api
- **Path**: /apps/api
- **Tech**: FastAPI, Python 3.12, SQLAlchemy
- **Role**: REST API, business logic
- **Exposes**: OpenAPI at /docs (47 endpoints)
- **Consumes**: packages/db
- **Entry**: app/main.py
- **Key files**:
  - `app/routes/` - All endpoints (8 routers)
  - `app/schemas/` - Pydantic models (23 files)
  - `openapi.json` - Generated spec
- **Token estimate**: ~22K (full), ~6K (summarized)

### packages/shared-types
- **Path**: /packages/shared-types
- **Tech**: TypeScript
- **Role**: Shared type definitions
- **Consumed by**: apps/web, apps/api (codegen)
- **Key files**:
  - `src/index.ts` - All exports (340 lines)
- **Token estimate**: ~3K

### packages/db
- **Path**: /packages/db
- **Tech**: Drizzle ORM, TypeScript
- **Role**: Database schema, migrations
- **Consumed by**: apps/api
- **Key files**:
  - `schema/` - Table definitions (8 files)
  - `migrations/` - Migration history (23 files)
- **Token estimate**: ~8K (full), ~2K (schema only)
CONTRACTS.md の形式
# API Contracts

Generated: 2026-01-20T14:32:00Z
Last sync: 2026-01-20T16:45:00Z
Sources: 3 files monitored

## REST API: apps/api → apps/web

### Endpoints Summary (47 total)

| Domain | Count | Key Endpoints |
|--------|-------|---------------|
| /api/auth | 5 | POST /login, POST /register, POST /refresh |
| /api/users | 6 | GET /me, PATCH /me, GET /:id |
| /api/campaigns | 8 | CRUD + POST /bulk, GET /analytics |
| /api/analytics | 12 | GET /dashboard, GET /timeseries, GET /funnel |
| /api/settings | 4 | GET /, PATCH /, GET /integrations |

### Key Types

```typescript
// Campaign domain (from apps/api/app/schemas/campaign.py)
interface Campaign {
  id: string;
  name: string;
  status: 'draft' | 'active' | 'paused' | 'completed';
  budget: number;
  target_audience: TargetAudience;
  created_at: string;
  updated_at: string;
}

interface CampaignCreate {
  name: string;
  budget: number;
  target_audience?: TargetAudience;
}

// Auth domain (from apps/api/app/schemas/auth.py)
interface User {
  id: string;
  email: string;
  name: string;
  role: 'user' | 'admin';
}

interface TokenPair {
  access_token: string;
  refresh_token: string;
  expires_in: number;
}
コントラクトの検証状況
チェック状況詳細
OpenAPI とルートの一致✅47/47 のエンドポイントを文書化済み
型とスキーマの一致✅すべての Pydantic モデルをエクスポート済み
フロントエンドの型が最新か⚠️2 つの型を再生成する必要があります

共有型:packages/shared-types

エクスポートされた型(合計 34 件)
カテゴリ型使用先
ドメインモデルCampaign、User、Analyticsweb、api
API レスポンスApiResponse、PaginatedResponseweb
ユーティリティDateRange、FilterParamsweb、api

データベーススキーマ:packages/db

テーブル(合計 12 件)
テーブル主な列関連先
usersid、email、name、rolecampaigns、sessions
campaignsid、user_id、name、statusanalytics、targets
analyticsid、campaign_id、date、metricscampaigns

### DEPENDENCY_GRAPH.md Format

```markdown
# Dependency Graph

Generated: 2026-01-20T14:32:00Z

## Visual Overview

                ┌─────────────────┐
                │  packages/db    │
                │  (Drizzle ORM)  │
                └────────┬────────┘
                         │
                         ▼

┌─────────────────┐ ┌─────────────────┐ │ apps/web │◄──│ apps/api │ │ (Next.js) │ │ (FastAPI) │ └────────┬────────┘ └────────┬────────┘ │ │ ▼ ▼ ┌─────────────────────────────────────────┐ │ packages/shared-types │ │ (TypeScript) │ └─────────────────────────────────────────┘


## Dependency Matrix

| Module | Depends On | Depended By |
|--------|------------|-------------|
| apps/web | shared-types, apps/api (runtime) | - |
| apps/api | shared-types (codegen), db | apps/web |
| packages/shared-types | - | apps/web, apps/api |
| packages/db | - | apps/api |

## Import Analysis

### apps/web imports:

@repo/shared-types:23 ファイル apps/api(fetch 経由):15 ファイル


### apps/api imports:

packages/db:12 ファイル packages/shared-types(コード生成):8 ファイル


## API Call Graph

apps/web apps/api ───────── ──────── src/lib/api/client.ts ──────────► app/routes/auth.py └── login() POST /api/auth/login └── register() POST /api/auth/register

src/app/campaigns/page.tsx ─────► app/routes/campaigns.py └── getCampaigns() GET /api/campaigns └── createCampaign() POST /api/campaigns

KEY_FILES.md の形式
# Key Files by Context

## Context: Frontend API Integration
**When**: Modifying API calls, response handling, or API types in frontend

Load these files (~8K tokens):

apps/web/src/lib/api/client.ts # API クライアントの実装 apps/web/src/types/api.d.ts # フロントエンド API 型 apps/api/openapi.json # API 仕様全体(または概要) packages/shared-types/src/index.ts # 共有型定義


## Context: Backend Endpoint Development
**When**: Adding/modifying API endpoints

Load these files (~12K tokens):

apps/api/app/routes/ # 既存のルートパターン apps/api/app/schemas/ # Pydantic モデル(関連するドメイン) apps/api/app/dependencies/ # 認証、DB の依存関係 packages/db/schema/ # 関連するテーブル定義


## Context: Database Changes
**When**: Schema modifications, migrations, queries

Load these files (~6K tokens):

packages/db/schema/ # すべてのテーブル定義 packages/db/migrations/ # 直近 5 件のマイグレーション apps/api/app/models/ # ORM モデルの使用箇所


## Context: Shared Types
**When**: Modifying interfaces used across modules

Load these files (~4K tokens):

packages/shared-types/src/ # 型のソースファイル apps/web/src/types/api.d.ts # 利用側(フロントエンド) apps/api/app/schemas/ # ソース(バックエンド)


## Context: Authentication
**When**: Auth flow, sessions, tokens

Load these files (~5K tokens):

apps/api/app/routes/auth.py # 認証エンドポイント apps/api/app/dependencies/auth.py # 認証ミドルウェア apps/web/src/lib/auth/ # フロントエンドの認証処理 packages/shared-types/src/auth.ts # 認証型


## Load-on-Demand Triggers

| Claude detects... | Load additionally |
|-------------------|-------------------|
| "check the API contract" | Full OpenAPI spec |
| Import from another module | That module's exports |
| Database query pattern | Full schema definitions |
| Test failure in other module | That module's test files |
| "breaking change" | Both sides of the contract |
CROSS_REPO_INDEX.md の形式
# Cross-Repository Capability Index

Generated: 2026-01-20T14:32:00Z

## Capabilities by Domain

### Authentication
| Capability | Location | Module | Type |
|------------|----------|--------|------|
| Login user | POST /api/auth/login | apps/api | endpoint |
| Register user | POST /api/auth/register | apps/api | endpoint |
| Refresh token | POST /api/auth/refresh | apps/api | endpoint |
| Auth context | src/contexts/AuthContext.tsx | apps/web | component |
| Auth hook | src/hooks/useAuth.ts | apps/web | hook |
| User type | src/auth.ts | shared-types | type |
| Session type | src/auth.ts | shared-types | type |

### Campaigns
| Capability | Location | Module | Type |
|------------|----------|--------|------|
| List campaigns | GET /api/campaigns | apps/api | endpoint |
| Create campaign | POST /api/campaigns | apps/api | endpoint |
| Campaign CRUD | app/routes/campaigns.py | apps/api | router |
| Campaign form | src/components/CampaignForm.tsx | apps/web | component |
| Campaign type | src/campaign.ts | shared-types | type |
| campaigns table | schema/campaigns.ts | packages/db | table |

### Analytics
| Capability | Location | Module | Type |
|------------|----------|--------|------|
| Dashboard data | GET /api/analytics/dashboard | apps/api | endpoint |
| Timeseries | GET /api/analytics/timeseries | apps/api | endpoint |
| Analytics hook | src/hooks/useAnalytics.ts | apps/web | hook |
| Chart components | src/components/charts/ | apps/web | components |

## Search Index

Before implementing new functionality, search this index:

Q: 「現在のユーザーを取得するには?」 A: apps/web/src/hooks/useAuth.ts の useAuth() フックを使用します または apps/api の GET /api/users/me エンドポイントを使用します

Q: 「キャンペーンの型はどこで定義されていますか?」 A: 信頼できる唯一の情報源:packages/shared-types/src/campaign.ts バックエンドのスキーマ:apps/api/app/schemas/campaign.py フロントエンドの型:apps/web/src/types/api.d.ts(生成済み)

Q: 「新しい API エンドポイントを追加するには?」 A: apps/api/app/routes/campaigns.py のパターンを参照します apps/api/app/routes/init.py に登録します packages/shared-types に型を追加します フロントエンドの型を再生成します


トークン予算の管理

コンテキストの上限
┌─────────────────────────────────────────────────────────────────┐
│  TOKEN BUDGET ALLOCATION                                         │
├─────────────────────────────────────────────────────────────────┤
│  Total context: ~200K tokens                                     │
│  Reserve for output: ~50K tokens                                 │
│  Working budget: ~150K tokens                                    │
├─────────────────────────────────────────────────────────────────┤
│  P0 (Must have):     50K │ Current module (full)                │
│  P1 (Should have):   40K │ Directly related modules (summary)   │
│  P2 (Nice to have):  30K │ Contracts + shared types             │
│  P3 (If room):       20K │ Decisions, todos, history            │
│  Buffer:             10K │ Dynamic loading during session       │
└─────────────────────────────────────────────────────────────────┘
自動要約

モジュールをまたぐコンテキストを読み込む際は、次の内容を要約します。

コンテンツの種類全文読み込みのしきい値要約方法
OpenAPI 仕様< 50 エンドポイントエンドポイントと主要な型のみ
型ファイル< 30 型エクスポートされた型のみ
ルートファイル< 200 行シグネチャとドキュメント文字列
設定ファイル< 50 行キーのみ(値やシークレットを除く)
テストファイル全文読み込みは行わない明示的なリクエストがあった場合のみ
コンテキスト読み込み戦略
┌─────────────────────────────────────────────────────────────────┐
│  CONTEXT LOADING HIERARCHY                                       │
├─────────────────────────────────────────────────────────────────┤
│  Level 1: Always loaded (~5K tokens)                             │
│  ├── TOPOLOGY.md (workspace structure)                          │
│  ├── CONTRACTS.md (API summary)                                 │
│  └── CROSS_REPO_INDEX.md (capability search)                    │
│                                                                  │
│  Level 2: Loaded based on current file (~15K tokens)            │
│  ├── KEY_FILES.md recommendations for current context           │
│  ├── Related module summaries                                   │
│  └── Relevant type definitions                                  │
│                                                                  │
│  Level 3: On-demand expansion (variable)                        │
│  ├── Full OpenAPI spec (when "check API contract")              │
│  ├── Full type files (when modifying interfaces)                │
│  └── Other module's full files (when cross-repo change)         │
└─────────────────────────────────────────────────────────────────┘

複数リポジトリのファイルアクセス

複数リポジトリのワークスペース(.git ディレクトリが個別にある場合)では、次の方法を使用します。

方法 1:兄弟ディレクトリ規約(推奨)
~/code/
├── myapp-frontend/     # git repo
├── myapp-backend/      # git repo
├── myapp-shared/       # git repo
└── .workspace/         # workspace config (optional)
    └── myapp.yaml

Claude は相対パス ../myapp-backend/ でアクセスします。

方法 2:ワークスペースのシンボリックリンク
# In frontend repo
mkdir -p .workspace/repos
ln -s ../../myapp-backend .workspace/repos/backend
ln -s ../../myapp-shared .workspace/repos/shared
方法 3:Git サブモジュール
# Add related repos as submodules (read-only)
git submodule add --depth 1 ../myapp-shared .workspace/shared
ファイルアクセスのルール
## Multi-Repo Access Protocol

WHEN accessing files from another repo:
1. Use relative paths from workspace root
2. Read-only access (never modify other repos)
3. Cache contract files locally in _project_specs/workspace/cache/
4. Log cross-repo reads in decisions.md

BEFORE making cross-repo changes:
1. Document the change in BOTH repos' decisions.md
2. Create linked todos in BOTH repos
3. Implement in dependency order (shared → backend → frontend)

リポジトリ間の変更検出

Claude が他のモジュールに影響する変更を検出した場合:

┌─────────────────────────────────────────────────────────────────┐
│  ⚠️  CROSS-REPO CHANGE DETECTED                                  │
├─────────────────────────────────────────────────────────────────┤
│  This change affects: apps/api                                   │
│  Specifically: Endpoint POST /api/campaigns expects new field    │
│                                                                  │
│  Impact Analysis:                                                │
│  ├── apps/web/src/lib/api/client.ts - needs update              │
│  ├── packages/shared-types/src/campaign.ts - needs new field    │
│  └── apps/api/app/schemas/campaign.py - source of change        │
│                                                                  │
│  Recommended Order:                                              │
│  1. Update packages/shared-types first (source of truth)         │
│  2. Update apps/api schema                                       │
│  3. Regenerate frontend types                                    │
│  4. Update apps/web API client                                   │
│  5. Run /sync-contracts                                          │
│                                                                  │
│  [Proceed with guidance] [Load full context] [Cancel]            │
└─────────────────────────────────────────────────────────────────┘
変更による影響のパターン
変更の種類影響先対応
新しい API エンドポイントフロントエンドクライアント、型両方に追加し、コントラクトを同期
レスポンスの変更フロントエンドの型、テスト型を再生成し、テストを更新
新しい必須フィールドすべてのコンシューマー破壊的変更のプロトコルを適用
フィールド名の変更すべてのコンシューマー移行と非推奨化
新しい共有型次回使用時のコンシューマーshared-types からエクスポート
スキーマの移行API モデル、クエリ移行を実行し、クエリを検証

コントラクトの鮮度管理システム

古さの検出
# .contract-sources file (auto-generated)
# Files that define contracts - monitored for changes

# OpenAPI specs
apps/api/openapi.json
apps/api/docs/openapi.yaml

# Type definitions
packages/shared-types/src/index.ts
packages/shared-types/src/api.ts

# Pydantic schemas
apps/api/app/schemas/*.py

# Database schema
packages/db/schema/*.ts
鮮度レベル
レベルトリガー対応時間ブロック
1セッション開始古さを確認~5sいいえ
2コミット後コントラクトが変更されていれば自動同期~15sいいえ
3プッシュ前検証ゲート~10sはい(回避可能)
4PR 作成時CI 検証~30sはい
5毎週の cron全体を再分析~2minいいえ
鮮度インジケーター
## Contract Status (shown in CONTRACTS.md header)

Last full analysis: 2026-01-18T10:00:00Z
Last sync: 2026-01-20T14:32:00Z
Staleness: 🟢 Fresh (synced 2 hours ago)

## Confidence Levels

🟢 Fresh     - Synced within 24 hours, no source changes
🟡 Stale     - Sources changed since last sync
🔴 Outdated  - Over 7 days since last analysis
⚠️  Drift    - Validation found inconsistencies

既存のスキルとの統合

existing-repo.md との連携

workspace.md は各モジュールについて existing-repo.md による分析を実行します。

## Module Analysis Delegation

For each module in workspace:
1. Run existing-repo analysis on that module
2. Extract: tech stack, conventions, guardrails status
3. Aggregate into TOPOLOGY.md
4. Don't duplicate - reference existing-repo output
session-management.md との連携
## Session State Integration

Workspace context files are part of session state:
- TOPOLOGY.md → structural context (rarely changes)
- CONTRACTS.md → API context (check freshness each session)
- KEY_FILES.md → loading guidance (static reference)

On session start:
1. Load _project_specs/workspace/*.md into context
2. Check contract freshness
3. Advise if sync needed
code-review.md との連携
## Cross-Repo Review Checks

When reviewing code that touches contracts:

1. Check if change affects other modules
2. Verify contract consistency
3. Flag if CONTRACTS.md needs update
4. Warn about breaking changes

Add to review output:
### 🔗 Cross-Repo Impact
- [ ] This change affects: apps/web (API client)
- [ ] Contract update needed: Yes
- [ ] Breaking change: No

コマンド

/analyze-workspace

ワークスペース全体を分析します。初回セットアップ時または大きな変更後に実行してください。

完全な仕様については、commands/analyze-workspace.md を参照してください。

/sync-contracts

コントラクトを軽量かつ段階的に更新します。頻繁に実行してください。

完全な仕様については、commands/sync-contracts.md を参照してください。

/workspace-status

簡易ステータスを確認します。

📊 Workspace Status: myapp

Type: Monorepo (Turborepo)
Modules: 4 (2 apps, 2 packages)
Contracts: 🟢 Fresh (synced 2h ago)
Token estimate: 45K / 150K budget

Quick actions:
  /sync-contracts     - Update contracts
  /analyze-workspace  - Full refresh

CI/CD との統合

GitHub Actions:コントラクトの検証
# .github/workflows/contracts.yml
name: Contract Validation

on:
  pull_request:
    paths:
      - 'apps/api/**'
      - 'packages/shared-types/**'
      - 'packages/db/schema/**'

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Check contract freshness
        run: |
          CHANGED=$(git diff --name-only origin/main HEAD | \
            grep -E "openapi|schema|types" || true)

          if [ -n "$CHANGED" ]; then
            echo "Contract sources changed:"
            echo "$CHANGED"

            if ! git diff --name-only origin/main HEAD | grep -q "CONTRACTS.md"; then
              echo "::error::Contract sources changed but CONTRACTS.md not updated"
              echo "Run /sync-contracts before merging"
              exit 1
            fi
          fi

      - name: Validate consistency
        run: |
          if [ -f "apps/api/openapi.json" ]; then
            ENDPOINTS=$(jq -r '.paths | keys | length' apps/api/openapi.json)
            DOCUMENTED=$(grep -c "^| /" _project_specs/workspace/CONTRACTS.md || echo 0)

            if [ "$ENDPOINTS" != "$DOCUMENTED" ]; then
              echo "::warning::Endpoint count mismatch"
            fi
          fi
コミット前フック
#!/bin/bash
# hooks/pre-commit-contracts

WORKSPACE_DIR="_project_specs/workspace"
[ ! -f "$WORKSPACE_DIR/.contract-sources" ] && exit 0

# Check if staged files include contract sources
STAGED=$(git diff --cached --name-only)
CONTRACT_SOURCES=$(cat "$WORKSPACE_DIR/.contract-sources")

for source in $CONTRACT_SOURCES; do
  if echo "$STAGED" | grep -q "$source"; then
    echo "📝 Contract source staged: $source"
    echo "Remember to run /sync-contracts before pushing"
  fi
done

トラブルシューティング

「ワークスペースが検出されません」
# Check for workspace indicators
ls -la package.json pnpm-workspace.yaml turbo.json nx.json 2>/dev/null

# If multi-repo, check sibling directories
ls -la ../

# Manual classification
/analyze-workspace --type monorepo
/analyze-workspace --type multi-repo --repos "../backend,../shared"
「コントラクトの同期に失敗しました」
# Check contract sources exist
cat _project_specs/workspace/.contract-sources

# Verify file access
for f in $(cat .contract-sources); do
  ls -la "$f" 2>/dev/null || echo "Missing: $f"
done

# Force full refresh
/analyze-workspace --force
「トークンの予算を超過しました」
# Check current estimates
/workspace-status

# Reduce context loading
# Edit KEY_FILES.md to prioritize
# Or work on one module at a time
「リポジトリ間のアクセスが拒否されました」
# Check paths are correct
ls ../backend/  # or wherever related repo is

# Set up symlinks if needed
mkdir -p .workspace/repos
ln -s ../../backend .workspace/repos/backend

# Or configure in workspace
/analyze-workspace --repo-path backend=../myapp-backend

コメント