5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Agent Rules, Skills, Workflows & Slash Commands:実践的な例とすぐに使えるテンプレート

5
Last updated at Posted at 2026-01-19

はじめに

前回の紹介記事Agent RulesSkillsWorkflowsSlash Commandsについて説明しました。この記事はその続編で、実践に焦点を当てています。

理論ではなく、以下を提供します:

  • 詳細なテンプレート - 必要なすべてのコンポーネントを含む完全なフレームワーク
  • 実例 - 本番環境で使用されているNestJS、Next.jsプロジェクトから
  • IDE別ガイド - 最もサポートが充実しているIDEの構造に従って記述

この記事の使い方:

  1. 技術に合ったテンプレートを選択
  2. コピーしてプロジェクト情報を入力
  3. Exampleを参考に適用方法を理解

1. Agent Rules

1.1. バックエンド向けRules

📝 TEMPLATE: Backend Rules Structure
# [PROJECT_NAME] - Backend Rules

## 1. Project Overview
- **Tech Stack**: [Framework, Language, Database, Cache...]
- **Architecture**: [Hexagonal/Clean/Layered Architecture]
- **Description**: [Brief project description]

---

## 2. Coding Standards

### 2.1. File Naming Conventions
- **Domain Layer**: `[entity].ts`
- **DTO Layer**: `[action]-[entity].dto.ts` (e.g., `create-user.dto.ts`)
- **Entity Layer**: `[entity].entity.ts`
- **Repository**: `[entity].repository.ts`
- **Service**: `[module].service.ts`
- **Controller**: `[module].controller.ts`
- **Module**: `[module].module.ts`
- **Mapper**: `[entity].mapper.ts`
- **Test Files**: `[name].spec.ts`

### 2.2. Casing Conventions
| Type              | Convention          | Example                                |
| ----------------- | ------------------- | -------------------------------------- |
| Classes           | PascalCase          | `UserService`, `CreateUserDto`         |
| Interfaces        | I + PascalCase      | `IUserRepository`, `IAuthService`      |
| Methods/Functions | camelCase           | `findById()`, `createUser()`           |
| Properties        | camelCase           | `userName`, `emailAddress`             |
| Constants         | UPPER_SNAKE_CASE    | `MAX_RETRY_COUNT`, `DEFAULT_PAGE_SIZE` |
| Env Variables     | UPPER_SNAKE_CASE    | `DATABASE_URL`, `JWT_SECRET`           |
| Files/Directories | kebab-case          | `user-service.ts`, `auth-module/`      |
| API Endpoints     | kebab-case          | `/api/users`, `/user-profiles`         |
| DB Tables         | snake_case (plural) | `users`, `order_items`                 |
| DB Columns        | snake_case          | `created_at`, `is_active`              |

### 2.3. Naming Patterns
- **Boolean Properties**: Prefix `is`, `has`, `can`, `should` (e.g., `isActive`, `hasPermission`)
- **Collections/Arrays**: Plural nouns (e.g., `users`, `orders`)
- **Getters**: `get` + noun (e.g., `getUserById`)
- **Finders**: `find` + criteria (e.g., `findByEmail`, `findActiveUsers`)
- **Validators**: `validate` + subject (e.g., `validateEmail`)
- **Transformers**: `transform` + subject (e.g., `transformUser`)

### 2.4. Code Style
- **Indentation**: [2 spaces / 4 spaces / tabs]
- **Max Line Length**: [80 / 100 / 120]
- **Quotes**: [single / double]
- **Semicolons**: [always / never]
- **Trailing Commas**: [all / es5 / none]
- **Import Order**: External → Internal → Domain → DTOs → Utilities → Relative

---

## 3. Architecture

### 3.1. Project Structure
```
src/
├── [module]/
│   ├── domain/                    # Pure business logic
│   │   └── [entity].ts
│   ├── dto/                       # Data Transfer Objects
│   │   ├── create-[entity].dto.ts
│   │   ├── update-[entity].dto.ts
│   │   └── query-[entity].dto.ts
│   ├── infrastructure/
│   │   └── persistence/
│   │       ├── [entity].repository.ts      # Abstract repository (Port)
│   │       └── relational/
│   │           ├── entities/
│   │           │   └── [entity].entity.ts  # ORM Entity
│   │           ├── mappers/
│   │           │   └── [entity].mapper.ts  # Domain ↔ Entity
│   │           └── repositories/
│   │               └── [entity].relational.repository.ts
│   ├── [module].service.ts        # Application logic
│   ├── [module].controller.ts     # HTTP layer
│   └── [module].module.ts         # DI configuration
├── common/                        # Shared utilities
│   ├── decorators/
│   ├── exceptions/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   ├── pipes/
│   └── utils/
├── config/                        # Configuration
└── database/                      # Database setup
```

### 3.2. Layer Responsibilities
- **Controller**: HTTP handling only, no business logic
- **Service**: Application orchestration, business rules
- **Repository**: Data access abstraction
- **Domain**: Pure business entities, no infrastructure imports
- **Mapper**: Domain ↔ Infrastructure conversion

### 3.3. Design Patterns
- [Repository Pattern / Active Record]
- [Dependency Injection]
- [SOLID Principles]
- [Domain-Driven Design concepts]

---

## 4. Database

### 4.1. ORM & Migrations
- **ORM**: [TypeORM / Prisma / Sequelize / Mongoose]
- **Migration Location**: `src/database/migrations/`
- **Seeder Location**: `src/database/seeds/`
- **Migration Naming**: `[timestamp]-[description].ts`

### 4.2. Database Rules
- Never query database directly in Controller
- Use transactions for multi-step operations
- Migration MUST have down() method
- Add indexes for frequently queried columns

### 4.3. Naming Conventions
- **Primary Keys**: `id`
- **Foreign Keys**: `[referenced_table]_id` (e.g., `user_id`)
- **Timestamps**: `created_at`, `updated_at`, `deleted_at`
- **Indexes**: `idx_[table]_[column]` (e.g., `idx_users_email`)
- **Constraints**: `ck_[table]_[description]`

---

## 5. API Guidelines

### 5.1. RESTful Conventions
- `GET /resources` - List resources
- `POST /resources` - Create resource
- `GET /resources/:id` - Get single resource
- `PUT /resources/:id` - Full update
- `PATCH /resources/:id` - Partial update
- `DELETE /resources/:id` - Delete resource

### 5.2. Response Format
```json
{
  "success": true,
  "data": {},
  "message": "string",
  "meta": {
    "timestamp": "ISO8601",
    "pagination": {}
  }
}
```

### 5.3. Error Response Format
```json
{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human readable message",
    "details": []
  }
}
```

### 5.4. HTTP Status Codes
| Code | Usage                          |
| ---- | ------------------------------ |
| 200  | Success (GET, PUT, PATCH)      |
| 201  | Created (POST)                 |
| 204  | No Content (DELETE)            |
| 400  | Bad Request / Validation Error |
| 401  | Unauthorized                   |
| 403  | Forbidden                      |
| 404  | Not Found                      |
| 409  | Conflict                       |
| 500  | Internal Server Error          |

### 5.5. Pagination
- Query params: `?page=1&limit=20&sort=-createdAt`
- Default limit: [10 / 20 / 50]
- Max limit: [100]

---

## 6. Security

### 6.1. Authentication
- [JWT / OAuth2 / Session-based]
- Token expiry: [Access: X minutes, Refresh: X days]
- Token storage: [HttpOnly Cookie / Header]

### 6.2. Security Rules
- NEVER hardcode secrets, use environment variables
- Validate ALL user input
- Use parameterized queries
- Hash passwords with [bcrypt / argon2] (min rounds: 10)
- Enable CORS with whitelist domains
- Use Helmet.js for security headers

### 6.3. Logging
- Log requests/responses (exclude sensitive data)
- Log errors with stack traces
- Log security events (login, logout, failed attempts)
- NEVER log: passwords, tokens, credit cards, PII

---

## 7. Testing

### 7.1. Coverage Requirements
- Unit Tests: >= [80%]
- Integration Tests: Critical paths
- E2E Tests: Main user flows

### 7.2. Test Structure
- Location: Same folder as source (`*.spec.ts`)
- Naming: `describe('[ClassName]')``describe('[methodName]')``it('should...')`
- Pattern: Arrange → Act → Assert

### 7.3. Testing Rules
- Mock external dependencies
- Use factories for test data
- Test happy path, error cases, edge cases
- No tests depend on other tests

---

## 8. Documentation

### 8.1. Code Documentation
- JSDoc/TSDoc for public APIs
- Inline comments for complex logic
- README.md updated for new features

### 8.2. API Documentation
- Swagger/OpenAPI decorators on all endpoints
- Request/Response examples
- Error response documentation
📋 EXAMPLE: NestJS Backend Rules (Claude Code Format)

ファイル: CLAUDE.md または .claude/CLAUDE.md

# NestJS E-Commerce API Rules

## Project Overview
- **Tech Stack**: NestJS, TypeScript, PostgreSQL, Redis, TypeORM
- **Architecture**: Hexagonal Architecture (Ports & Adapters)
- **Description**: E-Commerce platform API with multi-tenant support

---

## Coding Standards

### File Naming
- Domain: `user.ts`, `order.ts`
- DTO: `create-user.dto.ts`, `update-order.dto.ts`
- Entity: `user.entity.ts`
- Repository: `user.repository.ts`, `user.relational.repository.ts`
- Service: `users.service.ts`
- Controller: `users.controller.ts`

### Casing
| Type       | Convention       | Example                        |
| ---------- | ---------------- | ------------------------------ |
| Classes    | PascalCase       | `UserService`, `CreateUserDto` |
| Interfaces | I + PascalCase   | `IUserRepository`              |
| Methods    | camelCase        | `findById()`, `createUser()`   |
| Constants  | UPPER_SNAKE_CASE | `MAX_LOGIN_ATTEMPTS`           |
| Files      | kebab-case       | `user-service.ts`              |
| DB Tables  | snake_case       | `users`, `order_items`         |
| DB Columns | snake_case       | `created_at`, `user_id`        |

### Import Order
1. External (@nestjs/*, typeorm, etc.)
2. Internal modules (../users/*, ../orders/*)
3. Domain entities
4. DTOs
5. Utilities
6. Relative imports

---

## Architecture

### Module Structure
```
src/users/
├── domain/user.ts
├── dto/
│   ├── create-user.dto.ts
│   ├── update-user.dto.ts
│   └── query-user.dto.ts
├── infrastructure/persistence/
│   ├── user.repository.ts
│   └── relational/
│       ├── entities/user.entity.ts
│       ├── mappers/user.mapper.ts
│       └── repositories/user.relational.repository.ts
├── users.service.ts
├── users.controller.ts
└── users.module.ts
```

### Layer Rules
- Controller: HTTP only, delegate to Service
- Service: Business logic, logging, transactions
- Repository: Data access via abstract port
- Domain: Pure TypeScript, no decorators

---

## Database (TypeORM)

### Migrations
- Location: `src/database/migrations/`
- Generate: `npm run migration:generate -- -n MigrationName`
- Run: `npm run migration:run`
- Rollback: `npm run migration:revert`

### Rules
- Always have `down()` method
- Test migration on staging first
- Index columns in WHERE, JOIN, ORDER BY

---

## API Guidelines

### Endpoints
- Versioning: `/api/v1/`
- Pagination: `?page=1&limit=20`
- Sorting: `?sort=-createdAt`

### Response
```typescript
{
  data: T | T[],
  message?: string,
  meta?: {
    pagination: { page, limit, total, totalPages }
  }
}
```

---

## Security

- JWT access token: 15 minutes
- JWT refresh token: 7 days
- Password: bcrypt, 12 rounds
- Validate with class-validator
- Guards for protected routes
- NEVER log passwords, tokens

---

## Testing

- Coverage: >= 80%
- Unit tests: `*.spec.ts`
- E2E tests: `test/*.e2e-spec.ts`
- Pattern: Arrange → Act → Assert

1.2. フロントエンド向けRules

📝 TEMPLATE: Frontend Rules Structure
# [PROJECT_NAME] - Frontend Rules

## 1. Project Overview
- **Framework**: [Next.js / React / Vue / Angular]
- **Language**: [TypeScript / JavaScript]
- **Styling**: [Tailwind CSS / CSS Modules / Styled Components]
- **State Management**: [Zustand / Redux / Jotai / React Query]

---

## 2. Coding Standards

### 2.1. File Naming Conventions
| Type             | Convention            | Example                           |
| ---------------- | --------------------- | --------------------------------- |
| Components       | PascalCase            | `UserProfile.tsx`, `Button.tsx`   |
| Hooks            | camelCase, use prefix | `useAuth.ts`, `useUserProfile.ts` |
| Utilities        | camelCase             | `formatDate.ts`, `validators.ts`  |
| Types/Interfaces | PascalCase            | `User.ts`, `ApiResponse.ts`       |
| Constants        | UPPER_SNAKE_CASE file | `constants.ts`                    |
| Pages (Next.js)  | kebab-case folder     | `user-profile/page.tsx`           |
| API Routes       | kebab-case            | `api/users/route.ts`              |

### 2.2. Component File Structure
```typescript
// 1. Imports (external → internal → types → styles)
// 2. Types/Interfaces  
// 3. Constants
// 4. Component definition
// 5. Helper functions (if small)
// 6. Export
```

### 2.3. Naming Patterns
- **Components**: Noun (e.g., `UserCard`, `LoginForm`)
- **Hooks**: use + Action/Resource (e.g., `useUsers`, `useFetchData`)
- **Handlers**: handle + Event (e.g., `handleClick`, `handleSubmit`)
- **Boolean Props**: is/has/can/should (e.g., `isLoading`, `hasError`)

---

## 3. Component Guidelines

### 3.1. Component Rules
- Functional components only (no class components)
- One component per file
- Props interface: `[ComponentName]Props`
- Max component size: [200 / 300] lines
- Extract to sub-components when > [100] lines

### 3.2. Component Structure
```typescript
interface ComponentNameProps {
  // props
}

export function ComponentName({ prop1, prop2 }: ComponentNameProps) {
  // hooks first
  // derived state
  // handlers
  // effects
  // render
}
```

### 3.3. Server vs Client Components (Next.js App Router)
- Default: Server Components
- Use `'use client'` only when needed:
  - Event handlers (onClick, onChange)
  - Browser APIs (localStorage, window)
  - React hooks (useState, useEffect)
  - Third-party client libraries
- Push `'use client'` boundary as deep as possible

---

## 4. State Management

### 4.1. State Categories
| Type          | Solution            | Example             |
| ------------- | ------------------- | ------------------- |
| Local UI      | useState/useReducer | Form inputs, modals |
| Server        | TanStack Query      | API data, caching   |
| Global Client | [Zustand/Redux]     | User session, theme |
| URL           | useSearchParams     | Filters, pagination |
| Form          | React Hook Form     | Complex forms       |

### 4.2. State Rules
- Colocate state with the component using it
- Lift state only when sharing is needed
- Server state ≠ Client state
- Avoid prop drilling > 2 levels

---

## 5. Project Structure

```
src/
├── app/                    # Next.js App Router
│   ├── (auth)/            # Route group
│   ├── (dashboard)/
│   ├── api/               # API routes
│   ├── layout.tsx
│   └── page.tsx
├── components/
│   ├── ui/                # Reusable UI (Button, Input...)
│   ├── forms/             # Form components
│   ├── layouts/           # Layout components
│   └── [feature]/         # Feature-specific
├── hooks/                 # Custom hooks
├── lib/                   # Utilities, configs
├── services/              # API calls
├── stores/                # State management
├── types/                 # TypeScript types
└── styles/                # Global styles
```

---

## 6. Styling

### 6.1. Styling Rules
- [Tailwind CSS / CSS Modules / Styled Components]
- Mobile-first responsive design
- Design tokens in centralized location
- Avoid inline styles except dynamic values

### 6.2. Breakpoints
```
sm: 640px
md: 768px  
lg: 1024px
xl: 1280px
2xl: 1536px
```

---

## 7. Data Fetching

### 7.1. Fetching Patterns
- Server Components: Native fetch with caching
- Client Components: TanStack Query / SWR
- Mutations: Server Actions (Next.js) or TanStack Query

### 7.2. Caching Strategy
```typescript
// Static (build time)
fetch(url, { cache: 'force-cache' })

// Dynamic (every request)  
fetch(url, { cache: 'no-store' })

// Revalidate (ISR)
fetch(url, { next: { revalidate: 60 } })
```

---

## 8. Performance

### 8.1. Optimization Rules
- Lazy load routes and heavy components
- Optimize images with next/image
- Use `useMemo`/`useCallback` appropriately
- Avoid unnecessary re-renders
- Bundle analyze periodically

### 8.2. Core Web Vitals Targets
- LCP: < 2.5s
- FID: < 100ms  
- CLS: < 0.1

---

## 9. Testing

### 9.1. Testing Stack
- Unit: Jest + React Testing Library
- E2E: [Playwright / Cypress]
- Visual: [Storybook / Chromatic]

### 9.2. Testing Rules
- Test user behavior, not implementation
- Mock API calls
- Coverage: >= [70%]
- Test files: `*.test.tsx` or `__tests__/`
📋 EXAMPLE: Next.js 14 Frontend Rules (Cursor Format)

ファイル: .cursor/rules または .cursorrules

# Next.js 14 Dashboard Rules

## Overview
- Framework: Next.js 14 (App Router)
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS + shadcn/ui
- State: Zustand + TanStack Query

---

## File Naming
- Components: PascalCase (`UserCard.tsx`)
- Hooks: camelCase with use (`useAuth.ts`)
- Utilities: camelCase (`formatDate.ts`)
- Pages: `page.tsx` in route folders

---

## Component Rules
- Functional components only
- Props interface: `ComponentNameProps`
- Server Components by default
- 'use client' only when needed

## Server vs Client
Use `'use client'` for:
- onClick, onChange handlers
- useState, useEffect
- localStorage, window APIs

Keep as Server Component:
- Data fetching
- Static content
- SEO metadata

---

## Project Structure
```
src/
├── app/(dashboard)/
│   ├── layout.tsx
│   └── [feature]/page.tsx
├── components/
│   ├── ui/              # shadcn components
│   └── features/        # feature components
├── hooks/
├── lib/
├── services/
└── types/
```

---

## State Management
- Server state: TanStack Query
- Client state: Zustand
- Forms: React Hook Form + Zod
- URL state: useSearchParams

---

## Data Fetching
```typescript
// Server Component
async function Page() {
  const data = await fetch(url, { 
    next: { revalidate: 60 } 
  });
}

// Client Component  
function ClientPage() {
  const { data } = useQuery({ queryKey, queryFn });
}
```

---

## Styling
- Tailwind CSS classes
- Mobile-first: sm → md → lg → xl
- shadcn/ui for UI components
- CSS variables for theming

---

## Performance
- Dynamic imports for heavy components
- next/image for images
- Suspense boundaries
- Loading states in loading.tsx

2. Agent Workflows

📝 TEMPLATE: Workflow File Structure
---
description: [Brief description - IMPORTANT for AI discovery]
---

# Workflow: [Workflow Name]

## Purpose
[Explain what problem this workflow solves]

## When to Use
- [Situation 1]
- [Situation 2]

## Input
[Describe required input]

---

## Steps

### Step 1: [Step Name]
[Detailed description]

**Checklist:**
- [ ] [Task 1]
- [ ] [Task 2]

### Step 2: [Step Name]
[Detailed description]

**Template/Code:**
```[language]
[Code template]
```

---

## Output Format
```
[Expected output template]
```

## Notes
- [Important notes]
📋 EXAMPLE: Code Review Workflow (Google AntiGravity Format)

ファイル: .agent/workflows/code-review.md

---
description: Review code with checklist for security, performance, quality
---

# Code Review Workflow

## Input
File or changes to review

## Steps

### 1. Security Check
- [ ] Input validation
- [ ] SQL/NoSQL injection
- [ ] XSS vulnerabilities
- [ ] Auth/Authorization
- [ ] Sensitive data exposure

### 2. Performance Check
- [ ] Algorithm complexity
- [ ] Database queries (N+1?)
- [ ] Memory leaks
- [ ] Caching opportunities

### 3. Code Quality
- [ ] Naming conventions
- [ ] Single Responsibility
- [ ] DRY principle
- [ ] Error handling
- [ ] Type safety

### 4. Testing
- [ ] Unit tests exist
- [ ] Edge cases covered

## Output
```
## Summary
[1-2 sentences]

## 🔴 Critical
[Must fix before merge]

## 🟡 Improvements  
[Should improve]

## 🟢 Good
[Well done]
```
📋 EXAMPLE: Generate Tests Workflow

ファイル: .agent/workflows/generate-tests.md

---
description: Generate unit tests for function or class
---

# Generate Tests Workflow

## Input
Function/class to test

## Steps

### 1. Analyze
- Identify public methods
- List dependencies to mock
- Identify input/output types

### 2. Generate Test Cases
- Happy path
- Error cases  
- Edge cases (empty, null, boundary)

### 3. Write Tests

**Jest Template:**
```typescript
describe('[ClassName]', () => {
  let service: Service;
  let mockDep: jest.Mocked<Dependency>;

  beforeEach(() => {
    mockDep = { method: jest.fn() };
    service = new Service(mockDep);
  });

  describe('[methodName]', () => {
    it('should [expected] when [condition]', async () => {
      // Arrange
      const input = {};
      mockDep.method.mockResolvedValue(expected);
      
      // Act
      const result = await service.method(input);
      
      // Assert
      expect(result).toEqual(expected);
    });

    it('should throw when [error condition]', async () => {
      await expect(service.method(invalid))
        .rejects.toThrow(ExpectedError);
    });
  });
});
```

3. Agent Skills

📝 TEMPLATE: Skill File Structure (SKILL.md)
---
name: [skill-name-kebab-case]
description: [ACTION] + [SPECIFIC TASKS]. Activate when [TRIGGER KEYWORDS].
---

# [Skill Name]

## Capabilities
- [Capability 1]
- [Capability 2]
- [Capability 3]

## When Activated
This skill activates when:
- [Trigger condition 1]
- [Trigger condition 2]

## Guidelines

### Best Practices
- [Practice 1]
- [Practice 2]

### Avoid
- [Anti-pattern 1]
- [Anti-pattern 2]

## Patterns

### Pattern 1: [Name]
```[language]
[Code template]
```

## Examples

### Example 1
**Input:** [Description]
**Output:**
```[language]
[Result]
```
📋 EXAMPLE: Database Skill

ファイル: .agent/skills/database/SKILL.md または .claude/skills/database/SKILL.md

---
name: database-operations
description: Design schema, write queries, optimize database. Activate when working with SQL, PostgreSQL, MySQL, schema design, migrations, queries.
---

# Database Operations Skill

## Capabilities
- Schema design
- Query optimization
- Migration creation
- Index recommendations

## Guidelines

### Naming Conventions
- Tables: snake_case, plural (`users`, `order_items`)
- Columns: snake_case (`created_at`, `user_id`)
- Primary keys: `id`
- Foreign keys: `[table]_id`
- Indexes: `idx_[table]_[column]`

### Query Optimization
```sql
-- BAD
SELECT * FROM users WHERE status = 'active';

-- GOOD
SELECT id, name, email 
FROM users 
WHERE status = 'active';
```

### Migration Pattern
```typescript
// Always include down()
export class Migration implements MigrationInterface {
  async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.addColumn('users', 
      new TableColumn({ name: 'phone', type: 'varchar(20)', isNullable: true })
    );
  }

  async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.dropColumn('users', 'phone');
  }
}
```

### Index Guidelines
- Index columns in WHERE, JOIN, ORDER BY
- Composite indexes for frequently combined columns
- Avoid over-indexing (slows writes)

4. Slash Commands

Slash Commandsは、AIチャットで一般的なタスクを素早く実行するためのショートカットです。各IDEには、ビルトインまたはカスタマイズ可能な独自のコマンドセットがあります。

4.1. GitHub Copilot Slash Commands

GitHub Copilotは、使用環境に応じて異なるSlash Commandsを提供しています。

VS CodeでのSlash Commands

Command 説明
/clear チャット履歴をクリアし、新しい会話を開始
/explain 選択したコードを詳しく説明
/fix コードのバグを見つけて修正を提案
/fixTestFailure 失敗したテストケースを分析して修正
/help 利用可能なコマンド一覧を表示
/new 説明からファイルやプロジェクトを新規作成
/tests 選択したコードのユニットテストを自動生成

Visual StudioでのSlash Commands

Command 説明
/doc コードのドキュメントやコメントを生成
/explain 選択したコードを説明
/fix 修正を提案
/help ヘルプを表示
/optimize パフォーマンス最適化を提案
/tests ユニットテストを作成

XcodeでのSlash Commands

Command 説明
/doc ドキュメントを生成
/explain コードを説明
/fix バグを修正
/simplify 複雑なコードをシンプルに書き直し
/tests テストを作成

Chat Participants(@で使用)

Participant 説明
@workspace ワークスペース全体のコードベースについて質問
@vscode VS Codeの使い方について質問
@terminal ターミナルコマンドについて質問またはコマンド生成
@github GitHubリポジトリ、Issues、PRについて質問
@azure Azureサービスとデプロイについて質問

Chat Variables(#で使用)

Variable 説明
#file 特定のファイルを参照
#selection 選択中のコード
#block 現在のコードブロック
#function 現在のfunction
#class 現在のclass
📋 Prompt Filesでカスタムスラッシュコマンドを作成

ファイル: .github/prompts/review.prompt.md

---
mode: agent
description: Review code with security and performance checks
---
Review this code based on the following criteria:
1. Security vulnerabilities
2. Performance issues
3. Code quality
4. Test coverage

使い方: Copilot Chatで/reviewと入力して起動


4.2. Cursor Slash Commands

Command 説明
/edit AIでコードを編集し、変更をファイルに直接適用
/chat ファイルを変更せずにコードについてチャット
/composer 複数ファイルを同時に編集(マルチファイル編集)
/terminal ターミナルコマンドを作成して実行
/add ファイルをコンテキストに追加してAIの理解を深める
/reference 特定のファイル、ドキュメント、シンボルを参照
📋 Rulesでカスタムコマンドを作成

ファイル: .cursor/rules

When user types /api, perform:
1. Create new endpoint following RESTful conventions
2. Include validation with class-validator
3. Add Swagger documentation
4. Generate basic tests

4.3. Claude Code Slash Commands

Claude Codeは、ターミナルベースのワークフロー向けに最も豊富なコマンドセットを持っています。

Command 説明
/init プロジェクト構造からCLAUDE.mdファイルを自動生成
/clear 会話履歴をすべてクリア
/compact 会話を要約してコンテキストウィンドウを節約
/config Claude Code設定ファイルを開く
/cost セッションで使用したAPIコストを表示
/doctor 設定エラーをチェックして診断
/help 利用可能なすべてのコマンドを表示
/login Anthropicアカウントにログイン
/logout アカウントからログアウト
/memory CLAUDE.mdメモリを表示・管理
/model Claudeモデル間を切り替え(Opus、Sonnet、Haiku)
/permissions ファイルとツールへのアクセス権限を管理
/review 変更に対する包括的なコードレビューを実行
/status 現在のセッションステータスを表示
/vim エディターでvimキーバインドをオン/オフ

4.4. Google AntiGravity Slash Commands

Google AntiGravityはworkflowsをslash commandsとして使用します。.agent/workflows/内の各ワークフローファイルが呼び出し可能なコマンドになります。

使い方 説明
/[workflow-name] ファイル名でワークフローを呼び出し(.md拡張子を除く)

例:

  • .agent/workflows/code-review.mdがある場合 → /code-reviewと入力
  • .agent/workflows/test.mdがある場合 → /testと入力

よく使われるワークフロー:

Workflow 説明
/review コードレビューワークフロー
/test コードのテストを生成
/docs ドキュメントを生成
/refactor ベストプラクティスに従ってコードをリファクタリング
/migrate データベースマイグレーションを作成
/debug バグをデバッグして原因を特定

ヒント: .agent/workflows/内に対応するワークフローファイルを作成することで、任意のslash commandを作成できます!


5. IDEファイル配置まとめ

機能 GitHub Copilot Cursor Claude Code Google AntiGravity
Project Rules .github/copilot-instructions.md .cursor/rules or .cursorrules CLAUDE.md or .claude/CLAUDE.md GEMINI.md or .agent/rules.md
Global Rules Settings → Copilot → Instructions Settings → Rules for AI ~/.claude/CLAUDE.md ~/.gemini/GEMINI.md
Workflows .github/prompts/*.prompt.md Via rules Via Skills .agent/workflows/*.md
Skills .github/skills/[name]/SKILL.md .cursor/skills/ .claude/skills/[name]/SKILL.md .agent/skills/[name]/SKILL.md
Slash Commands Built-in + Prompt Files Built-in + Custom Built-in Via Workflows

6. トラブルシューティング

Rulesが動作しない場合

チェックリスト:

  1. ファイルが正しい場所にある?
  2. Markdown構文が正しい?
  3. IDEをリロードした?
  4. Rulesが長すぎない?(100行以下推奨)

Skillがアクティブにならない場合

  1. descriptionにトリガーキーワードが含まれているか確認
  2. テスト:「Use skill [name] to...」と入力
  3. SKILL.mdが正しい場所にあるか確認

Workflowが正しく動作しない場合

  1. Descriptionは明確か?
  2. Stepsに十分な詳細があるか?
  3. Output formatが指定されているか?

参考資料

元の記事:

Google AntiGravity:

Claude Code:

Cursor:

GitHub Copilot:


この記事がお役に立てば幸いです!質問やフィードバックがあれば、ぜひコメントで教えてください

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?