Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 30 additions & 106 deletions .claude/rules/custom-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,125 +123,50 @@ Even if plan separates TDD into individual steps (e.g., Step 1: Write test, Step

<CODINGBUDDY_CRITICAL_RULE>

**When user message starts with PLAN, ACT, EVAL, or AUTO keyword (or localized: Korean 계획/실행/평가/자동, Japanese 計画/実行/評価/自動, Chinese 计划/执行/评估/自动, Spanish PLANIFICAR/ACTUAR/EVALUAR/AUTOMÁTICO):**
**When user message starts with PLAN, ACT, EVAL, or AUTO keyword (or localized equivalents):**

1. **IMMEDIATELY** call `parse_mode` MCP tool with the user's prompt
2. Follow the returned `instructions` **EXACTLY**
3. Apply the returned `rules` as context
4. If `warnings` are present, inform the user

**This is MANDATORY, not optional.**

Failure to call `parse_mode` when these keywords are present will result in:
- Missed critical checklists (Devil's Advocate Analysis, Impact Radius Analysis)
- Incomplete evaluations
- Quality issues not caught before deployment

**Red Flags** (STOP if you think these):
| Thought | Reality |
|---------|---------|
| "I can handle EVAL myself" | NO. Call parse_mode FIRST. |
| "The rules are similar anyway" | NO. Each mode has specific checklists. |
| "I'll save a tool call" | NO. parse_mode MUST be called FIRST. |
| "I already know what to do" | NO. Rules may have been updated. |
1. Call `activate` MCP tool with the user's prompt (preferred in Claude Code)
2. **Fallback**: Call `parse_mode` if `activate` is unavailable
3. Follow the returned `rules` as context
4. Use returned `specialists` to run a council via Claude native Teams

</CODINGBUDDY_CRITICAL_RULE>

Examples:
- `PLAN design auth feature` → **immediately** call parse_mode → work in PLAN mode
- `AUTO implement user dashboard` → **immediately** call parse_mode → autonomous PLAN→ACT→EVAL cycle

## 🔴 MANDATORY: Parallel Specialist Agent Execution

<PARALLEL_EXECUTION_MANDATORY_RULE>

**When `parse_mode` returns `dispatchReady`, use it directly with the Task tool — no extra calls needed.**

**Outer Transport Selection (before dispatch):**
- [ ] Check `availableStrategies` in `parse_mode` response (outer transport options)
- [ ] If `["subagent", "taskmaestro"]` → AskUserQuestion to choose outer strategy
- [ ] If `taskmaestroInstallHint` present and user wants taskmaestro → guide installation
- [ ] Pass chosen strategy to `dispatch_agents(executionStrategy: ...)`
- [ ] Teams (inner coordination, experimental) may be used within a session if APIs are available

**Quick Checklist (Auto-Dispatch - Preferred):**
- [ ] Check `dispatchReady` in `parse_mode` response
- [ ] Use `dispatchReady.primaryAgent.dispatchParams` with Task tool
- [ ] Use `dispatchReady.parallelAgents[].dispatchParams` with Task tool (`run_in_background: true`)
- [ ] Collect results with `TaskOutput`
- [ ] Summarize all findings

**Fallback (if `dispatchReady` is not present):**
- [ ] Call `dispatch_agents` or `prepare_parallel_agents` with recommended specialists
- [ ] Execute each agent via Task tool (`subagent_type: "general-purpose"`, `run_in_background: true`)
- [ ] Display activation status
- [ ] Collect results with `TaskOutput`
- [ ] Summarize all findings

**Mode-specific Specialists:**

| Mode | Specialists |
|------|-------------|
| **PLAN** | 🏛️ architecture, 🧪 test-strategy, 📨 event-architecture, 🔗 integration, 📊 observability, 🔄 migration |
| **ACT** | 📏 code-quality, 🧪 test-strategy, 📨 event-architecture, 🔗 integration |
| **EVAL** | 🔒 security, ♿ accessibility, ⚡ performance, 📏 code-quality, 📨 event-architecture, 🔗 integration, 📊 observability, 🔄 migration |
| **AUTO** | 🏛️ architecture, 🧪 test-strategy, 🔒 security, 📏 code-quality, 📨 event-architecture, 🔗 integration, 📊 observability, 🔄 migration |

> **Note:** SubAgent and TaskMaestro are **outer transport** strategies (one per invocation, user choice).
> Teams is an **inner coordination** layer (experimental) that can optionally run within either outer strategy.
> See the [Execution Model](../../packages/rules/.ai-rules/adapters/claude-code.md#execution-model-outer-transport-vs-inner-coordination) for details.

**📖 Full Guide:** [Parallel Specialist Agents Execution](../../packages/rules/.ai-rules/adapters/claude-code.md#parallel-specialist-agents-execution)

</PARALLEL_EXECUTION_MANDATORY_RULE>

## 🔴 MANDATORY: Auto-Dispatch Enforcement

<AUTO_DISPATCH_ENFORCEMENT_RULE>

**When `parse_mode` returns `dispatch="auto"`, you MUST dispatch all recommended specialists. No exceptions.**

### Core Rule

If the `parse_mode` response contains `dispatch="auto"` or `dispatchReady` with specialist agents:
1. **MUST** dispatch every listed specialist — skipping any is a protocol violation
2. Use the selected **outer transport** (SubAgent or TaskMaestro) to dispatch specialists
3. **Optionally** use Teams as inner coordination within a session (experimental, requires runtime API availability)
4. **Report results** via the dispatch mechanism (TaskOutput for SubAgent, SendMessage for Teams)

### Red Flags (STOP if you think these)

| Thought | Reality |
|---------|---------|
| "I can handle this analysis myself" | NO. Specialists have domain expertise you lack. Dispatch them. |
| "It's just a small change, no need for specialists" | NO. dispatch="auto" means the system determined specialists are needed. |
| "I'll save time by skipping dispatch" | NO. Skipping specialists causes missed issues that cost more time later. |
| "The specialists will just repeat what I already know" | NO. Specialists catch domain-specific issues you would miss. |
| "I'll dispatch them later after I look at the code" | NO. Dispatch IMMEDIATELY when dispatch="auto" is returned. |
## 🔴 MANDATORY: Specialist Council Execution

</AUTO_DISPATCH_ENFORCEMENT_RULE>
<SPECIALIST_COUNCIL_RULE>

## 🔴 MANDATORY: Context Document Management
**When `activate` returns specialists, run them as a council via Claude native Teams.**

<CONTEXT_DOCUMENT_RULE>
### Workflow

**Fixed file `docs/codingbuddy/context.md` persists PLAN → ACT → EVAL context across context compaction.**
1. Call `activate({ prompt })` → get rules, primaryAgent, specialists
2. Create a Claude native Team with the returned specialists as teammates
3. Each specialist independently analyzes the task
4. Specialists cross-review each other's findings
5. Collect consensus: approve | concern | reject
6. Summarize all findings to user

### How It Works
### Fallback (non-Teams environments)

`parse_mode` **automatically** manages the context document:
If Teams is not available, dispatch specialists as parallel subagents:
- Use `Agent` tool with `run_in_background: true` for each specialist
- Collect results and synthesize

- **PLAN/AUTO mode**: Resets (deletes and recreates) the context document
- **ACT/EVAL mode**: Appends a new section to the existing document
</SPECIALIST_COUNCIL_RULE>

### Required Workflow
## Claude Code Native Feature Mapping

**In ALL modes:**
1. `parse_mode` automatically reads/creates context
2. Review `contextDocument` for previous decisions and notes
3. Before completing: `update_context` to persist current work
Use Claude Code native features instead of codingbuddy equivalents:

</CONTEXT_DOCUMENT_RULE>
| Need | Native Feature | Instead of |
|------|----------------|------------|
| Cross-session context | **Claude Code Memory** | `update_context` / `create_briefing` / `resume_session` |
| Specialist debate | **Claude native Teams** | `dispatch_agents` subagent strategy |
| Task exploration | **/dream** | `analyze_task` |
| Planning with approval | **EnterPlanMode** | `parse_mode` planning stage |
| Repeated execution | **/loop** | AUTO mode repetition |
| Clarification | **AskUserQuestion** | clarification gate |

## Claude Code Specific

Expand All @@ -250,7 +175,6 @@ If the `parse_mode` response contains `dispatch="auto"` or `dispatchReady` with
- Provide clear, actionable feedback
- Reference project context from `packages/rules/.ai-rules/rules/project.md`
- Follow PLAN → ACT → EVAL workflow when appropriate
- Use AUTO mode for autonomous quality-driven development cycles

## Full Documentation

Expand Down
74 changes: 40 additions & 34 deletions .claude/rules/tool-priority.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,79 @@
# Tool Priority: codingbuddy vs oh-my-claudecode (OMC)
# Tool Priority: Claude Code Native > codingbuddy > OMC

## Core Principle

**codingbuddy FIRST** — Use codingbuddy tools for all workflow management, agent dispatch, and quality control.
**OMC for unique features only** — Use OMC tools when they provide capabilities codingbuddy does not.
1. **Claude Code native FIRST** — Memory, Teams, Plan mode, /dream, /loop handle orchestration natively
2. **codingbuddy for unique value** — Rules, agents, checklists, quality reports are codingbuddy's core
3. **OMC for dev tools** — LSP, AST grep, REPL, git-master when needed

---

## codingbuddy FIRST
## Layer 1: Claude Code Native (highest priority)

Always reach for these codingbuddy tools before any OMC equivalent:
These features are built into Claude Code and should be used instead of codingbuddy equivalents:

| Native Feature | Purpose | Replaces |
|----------------|---------|----------|
| **Claude Code Memory** | Cross-session context persistence | `update_context`, `create_briefing`, `resume_session` |
| **Claude native Teams** | Run specialist agents as teammates for real-time debate | `dispatch_agents` subagent strategy |
| **EnterPlanMode** | Structured planning with user approval | `parse_mode` planning stage routing |
| **/dream** | Autonomous task exploration and analysis | `analyze_task` |
| **/loop** | Recurring execution on interval | `parse_mode` AUTO mode repetition |
| **AskUserQuestion** | Clarification from user | `parse_mode` clarification gate |

---

## Layer 2: codingbuddy (unique value)

Use codingbuddy tools for capabilities Claude Code does not provide natively:

| Tool | Purpose |
|------|---------|
| `parse_mode` | Mode management (PLAN/ACT/EVAL/AUTO), agent activation, context init |
| `dispatch_agents` | Agent dispatch with Task tool-ready params |
| `analyze_task` | Pre-planning task analysis, risk assessment, specialist recommendations |
| `update_context` | Context persistence across PLAN → ACT → EVAL modes |
| `generate_checklist` | Contextual checklists (security, a11y, performance, testing) |
| `activate` | **One-shot entry point**: rules + primary agent + specialists + discussion format |
| `parse_mode` | Legacy mode entry (for non-Claude Code hosts: Cursor, Codex, etc.) |
| `search_rules` | Query project rules and guidelines |
| `get_agent_details` | Agent profile and expertise lookup |
| `generate_checklist` | Contextual checklists (security, a11y, performance, testing) |
| `get_project_config` | Tech stack, architecture, language settings |
| `prepare_parallel_agents` | Ready-to-use prompts for parallel specialist agents |
| `pr_quality_report` | Run specialist agents on changed files for PR quality |
| `create_briefing` | Capture session state for cross-session recovery |
| `resume_session` | Load previous session briefing |
| `get_rule_impact_report` | Rule effectiveness analytics |

---

## OMC Only
## Layer 3: OMC (dev tools)

Use these OMC tools when the capability is not available in codingbuddy:
Use OMC tools for capabilities neither Claude Code nor codingbuddy provide:

| Tool / Skill | Purpose |
|--------------|---------|
| LSP tools (`lsp_hover`, `lsp_goto_definition`, `lsp_find_references`, etc.) | Language server protocol — type info, definitions, references |
| AST grep (`ast_grep_search`, `ast_grep_replace`) | Structural code search and refactoring |
| Python REPL (`python_repl`) | Interactive data analysis and computation |
| State tools (`state_read`, `state_write`, `state_clear`) | Mode state persistence for autopilot/ralph/ultrawork |
| Notepad tools (`notepad_read`, `notepad_write_*`) | Session notes and compaction-resilient memory |
| Project memory (`project_memory_*`) | Long-term project knowledge persistence |
| `/git-master` | Atomic commits, rebasing, history management |
| `/build-fix` | Build and TypeScript error resolution |
| `/deepsearch` | Thorough multi-pass codebase search |
| `/team`, `/swarm` | Multi-agent coordination with shared task lists |
| `/ultrawork`, `/autopilot`, `/ralph` | Autonomous execution loops |
| `/pipeline` | Sequential/branching agent workflows |

---

## Overlap Matrix

When both tools could apply, codingbuddy wins:
## Quick Decision Matrix

| Use Case | Use This | Not This |
|----------|----------|----------|
| Starting PLAN/ACT/EVAL mode | `parse_mode` | OMC mode state tools |
| Dispatching specialist agents | `dispatch_agents` | OMC `/team` or `/swarm` |
| Code/security review | codingbuddy `search_rules` + specialists | OMC `/code-review`, `/security-review` |
| Context across sessions | `update_context` | OMC notepad/project memory |
| Task analysis before planning | `analyze_task` | Ad-hoc OMC tools |
| Checklists (security, a11y) | `generate_checklist` | Manual OMC review |
| Starting a workflow | `activate` | `parse_mode` (in Claude Code) |
| Running specialist council | Claude native Teams | subagent dispatch |
| Cross-session context | Claude Code Memory | `update_context` / `create_briefing` |
| Task analysis | `/dream` | `analyze_task` |
| Repeated execution | `/loop` | AUTO mode cycle |
| Clarification | AskUserQuestion | clarification gate |
| Rules & checklists | codingbuddy `search_rules`, `generate_checklist` | — |
| Code review quality | codingbuddy `pr_quality_report` | OMC `/code-review` |
| Type info & references | OMC LSP tools | — |

---

## Decision Rationale

- codingbuddy tools are project-aware and integrate with the PLAN/ACT/EVAL workflow
- OMC tools are general-purpose developer tools without project context
- Using codingbuddy first ensures consistent quality gates and audit trail via `docs/codingbuddy/context.md`
- OMC's unique capabilities (LSP, AST, REPL) complement codingbuddy; they do not replace it
- Claude Code native features handle orchestration (memory, teams, planning, loops) better than MCP tools
- codingbuddy's unique value is **rules, agents, and checklists** — domain knowledge, not orchestration
- OMC's unique value is **dev tooling** (LSP, AST, REPL) — code intelligence, not workflow
- `parse_mode` remains available for backward compatibility with non-Claude Code hosts
61 changes: 59 additions & 2 deletions apps/mcp-server/src/agent/teams-capability.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,28 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { TeamsCapabilityService } from './teams-capability.service';
import type { ConfigService } from '../config/config.service';

function createMockConfigService(experimental?: { teamsCoordination?: boolean }): ConfigService {
function createMockConfigService(
experimental?: { teamsCoordination?: boolean },
clientName?: string,
): ConfigService {
return {
getSettings: vi.fn().mockResolvedValue({ experimental }),
getClientName: vi.fn().mockReturnValue(clientName),
} as unknown as ConfigService;
}

describe('TeamsCapabilityService', () => {
let originalEnv: string | undefined;
let originalClaudeCode: string | undefined;
let originalClaudeEntrypoint: string | undefined;

beforeEach(() => {
originalEnv = process.env.CODINGBUDDY_TEAMS_ENABLED;
originalClaudeCode = process.env.CLAUDE_CODE;
originalClaudeEntrypoint = process.env.CLAUDE_CODE_ENTRYPOINT;
delete process.env.CODINGBUDDY_TEAMS_ENABLED;
delete process.env.CLAUDE_CODE;
delete process.env.CLAUDE_CODE_ENTRYPOINT;
});

afterEach(() => {
Expand All @@ -22,6 +32,16 @@ describe('TeamsCapabilityService', () => {
} else {
delete process.env.CODINGBUDDY_TEAMS_ENABLED;
}
if (originalClaudeCode !== undefined) {
process.env.CLAUDE_CODE = originalClaudeCode;
} else {
delete process.env.CLAUDE_CODE;
}
if (originalClaudeEntrypoint !== undefined) {
process.env.CLAUDE_CODE_ENTRYPOINT = originalClaudeEntrypoint;
} else {
delete process.env.CLAUDE_CODE_ENTRYPOINT;
}
});

describe('getStatus', () => {
Expand Down Expand Up @@ -125,6 +145,43 @@ describe('TeamsCapabilityService', () => {
});
});

describe('Claude Code auto-detection', () => {
it('should auto-enable when CLAUDE_CODE=1 is set', async () => {
process.env.CLAUDE_CODE = '1';
const service = new TeamsCapabilityService(createMockConfigService());
const status = await service.getStatus();

expect(status.available).toBe(true);
expect(status.source).toBe('claude-native');
expect(status.reason).toContain('Claude Code');
});

it('should auto-enable when CLAUDE_CODE_ENTRYPOINT is set', async () => {
process.env.CLAUDE_CODE_ENTRYPOINT = '/some/path';
const service = new TeamsCapabilityService(createMockConfigService());
const status = await service.getStatus();

expect(status.available).toBe(true);
expect(status.source).toBe('claude-native');
});

it('should auto-enable when clientName is claude-code', async () => {
const service = new TeamsCapabilityService(createMockConfigService(undefined, 'claude-code'));
const status = await service.getStatus();

expect(status.available).toBe(true);
expect(status.source).toBe('claude-native');
});

it('should not auto-enable for other clients', async () => {
const service = new TeamsCapabilityService(createMockConfigService(undefined, 'cursor'));
const status = await service.getStatus();

expect(status.available).toBe(false);
expect(status.source).toBe('default');
});
});

describe('readEnvFlag', () => {
it('should return undefined when env var is not set', () => {
const service = new TeamsCapabilityService(createMockConfigService());
Expand Down Expand Up @@ -166,7 +223,7 @@ describe('TeamsCapabilityService', () => {
expect(status).toHaveProperty('source');
expect(typeof status.available).toBe('boolean');
expect(typeof status.reason).toBe('string');
expect(['config', 'environment', 'default']).toContain(status.source);
expect(['config', 'environment', 'claude-native', 'default']).toContain(status.source);
});
});
});
Loading
Loading