# OpenCodeKit Prompt Hierarchy: Three Alternatives + Recommendation

**Status:** Design Phase Complete | Recommendation: Alternative C (Scope-Based Inheritance)

---

## THE PROBLEM (First Principles Analysis)

**What teams need:**
1. **Discovery** - Where do prompts live and why?
2. **Predictability** - What happens when rules conflict?
3. **Mode-aware loading** - Which prompts activate where?
4. **Inheritance efficiency** - How to avoid duplication?

**Current state:** Implicit cascades hide these decisions from users.

---

## THREE ALTERNATIVES

### ALTERNATIVE A: Linear Cascade (Simplest)

**File Structure:**
```
~/.config/opencode/AGENTS.md          # Global baseline
project/AGENTS.md                      # Project override (inherits global)
project/.opencode/agent/{name}.md      # Agent customization
```

**Cascade Rule (Single precedence path):**
```
Agent > Project > Global (wins)
```

**Precedence Table:**
| Layer | Scope | Override | Example |
|-------|-------|----------|---------|
| Agent | Single agent behavior | Project + Global | Build's delegation strategy |
| Project | All agents in project | Global rules only | Custom agent list, domain workflows |
| Global | All projects, all agents | Nothing (immutable) | Security, core conventions |

**Inheritance Model:**
```
Global AGENTS.md (Foundation)
  ├─ Defines: Security, priority hierarchy, core agent list, skills system
  ├─ Cannot be: Modified at project level
  │
Project AGENTS.md (Customization)
  ├─ Inherits: Everything from Global
  ├─ Can override: Agent behavior, tool access, naming conventions
  ├─ Cannot override: Security constraints, priority hierarchy
  │
Agent config (Specialization)
  ├─ Inherits: Global + Project rules
  ├─ Defines: Agent-specific orchestration, communication style
  └─ Cannot override: Domain conventions set at project level
```

**Mode-Loading Rules:**
```
Primary Mode (Build):
  1. Load Global AGENTS.md
  2. Load Project AGENTS.md (overrides global)
  3. Load @.opencode/agent/build.md (specialization)
  4. Result: Full system prompt with all layers

Subagent Mode (Plan, Researcher, etc.):
  1. Load Global AGENTS.md (baseline security + constraints only)
  2. Skip Project AGENTS.md (avoid domain-specific context bleed)
  3. Load @.opencode/agent/plan.md (narrow task focus)
  4. Result: Focused agent with minimal project coupling
```

**Pros:**
- ✅ Simplest to understand ("Global → Project → Agent")
- ✅ Single precedence path (no ambiguity)
- ✅ Easy to implement (file path determines priority)

**Cons:**
- ❌ Security rules mixed with conventions (hard to identify immutable layer)
- ❌ No way to express "domain-specific" vs "agent-specific" vs "security" concerns
- ❌ Mode-aware loading requires special comments or file suffixes (brittle)
- ❌ Project customization layer is underspecified (what CAN you override?)

---

### ALTERNATIVE B: Layered Composition (Most Structured)

**File Structure:**
```
~/.config/opencode/
├── AGENTS-security.md        # Layer 1: Immutable security foundation
├── AGENTS-conventions.md      # Layer 2: Global conventions (core language features)
├── AGENTS-agents.md           # Layer 3: Agent definitions & roles
└── AGENTS-integrations.md     # Layer 4: Skills & tool configuration

project/
├── AGENTS-domain.md           # Layer 5: Domain-specific workflows & practices
├── AGENTS-agents-custom.md    # Layer 6: Project-specific agent customization
└── .opencode/agent/{name}.md  # Layer 7: Agent implementation details
```

**Cascade Rule (Strict layering):**
```
Layer 1 (Security) → Layer 2 (Conventions) → Layer 3 (Agents) → Layer 4 (Integrations)
       ↓                   ↓                        ↓                  ↓
Layer 5 (Domain) → Layer 6 (Custom Agents) → Layer 7 (Agent Impl)
```

**Inheritance by Layer:**
| Layer | Scope | Override | Immutable? |
|-------|-------|----------|-----------|
| 1 - Security | All projects/agents | Nothing | ✅ YES |
| 2 - Conventions | Language standards, naming | Layer 1 only | ✅ YES |
| 3 - Agents | Core agent list, roles | Layers 1-2 only | ❌ CAN override in Layer 6 |
| 4 - Integrations | Skills, tools, APIs | Layers 1-3 only | ❌ Can customize in Layer 6 |
| 5 - Domain | Project workflows, patterns | Layers 1-4 only | ❌ Project-specific |
| 6 - Custom Agents | Project agent modifications | All above | ❌ Project-specific |
| 7 - Agent Impl | Single agent behavior | All above | ❌ Agent-specific |

**Mode-Loading Rules:**
```
Primary Mode (Build):
  Load Layers 1, 2, 3, 4, 5, 6, 7 (full stack)
  = Global security + conventions + agents + integrations + domain + custom + impl

Subagent Mode (Plan):
  Load Layers 1, 2, 3, 4, 7 (skip domain + custom agents)
  = Global security + conventions + agents + integrations + impl
  = Narrower context, no project-specific domain bleeding
```

**Pros:**
- ✅ Security layer is clearly immutable (Layer 1)
- ✅ Clear separation by concern (security ≠ conventions ≠ agents)
- ✅ Easy to explain: "Which layer answers this question?"
- ✅ Mode-aware loading is explicit (just list layers to load)
- ✅ Extensible: add Layer 8 (Monitoring), Layer 9 (Performance) without breaking cascade

**Cons:**
- ❌ High complexity (7 files minimum for small project)
- ❌ Overhead for simple projects (overkill structure)
- ❌ Inheritance path is complex (must understand all 7 layers)
- ❌ Maintenance burden (7 files to keep in sync)
- ❌ Hard to quickly find "which file controls X?" (too many places to look)

---

### ALTERNATIVE C: Scope-Based Inheritance (RECOMMENDED)

**File Structure:**
```
~/.config/opencode/
└── AGENTS.md                 # Global baseline (immutable + extensible)
    ├── Section: Security Rules (immutable)
    ├── Section: Priority Hierarchy (immutable)
    ├── Section: Core Conventions (can extend at project level)
    ├── Section: Skills System (extensible)
    └── Section: Agent Definitions (can customize per project)

project/
├── AGENTS.md                 # Project customization (extends global, inherits immutable)
│   ├── Section: Inherits from global - Security Rules (reference only)
│   ├── Section: Custom Domain Workflows (new section)
│   ├── Section: Custom Conventions (extends global conventions)
│   └── Section: Custom Agent Configs (extends/overrides global agents)
│
└── .opencode/
    └── agent/{name}.md       # Agent implementation (inherits all above)
        ├── YAML frontmatter (tools, model, temperature)
        └── Markdown body (behavior, delegation rules, tools strategy)
```

**Cascade Rule (Scope + Layer):**
```
IMMUTABLE (All Projects):
  └─ Global AGENTS.md:Security + PriorityHierarchy

EXTENSIBLE (Per Project):
  ├─ Global AGENTS.md:Conventions, SkillsSystem, AgentDefinitions
  ├─ Project AGENTS.md:DomainWorkflows, CustomConventions, CustomAgentConfigs (extends/overrides)
  └─ .opencode/agent/{name}.md:Implementation (specializes from above)
```

**Precedence Table (Clear & Concise):**
| What | Global | Project | Agent | Override Rules |
|------|--------|---------|-------|-----------------|
| Security Rules | YES | Reference | NO | Global wins (immutable) |
| Code Conventions | YES | Extend | NO | Project extends global, agent uses combined |
| Agent Roles | YES | Override | Specialize | Agent > Project > Global |
| Tool Access | YES | Extend | YES | Agent > Project > Global, but respects security |
| Communication Style | NO | Maybe | YES | Agent-specific, can reference project conventions |
| Domain Workflows | NO | YES | Reference | Project-specific only |

**Inheritance Rules Matrix:**

```markdown
## Inheritance by Concept

### Security Rules (IMMUTABLE)
- Defined by: Global only
- Can override: NEVER (security is non-negotiable)
- Project level: "Inherits from global, no changes allowed"
- Agent level: Must respect security rules

### Code Conventions (EXTENSIBLE)
- Defined by: Global (baseline)
- Can extend by: Project (project-specific patterns)
- Can override by: Agent (agent-specific communication)
- Precedence: Agent > Project > Global

### Agent Definitions (CUSTOMIZABLE)
- Defined by: Global (core agent list + responsibilities)
- Can override by: Project (custom agents, modified roles)
- Can specialize by: Agent config (agent-specific rules)
- Precedence: Agent config > Project > Global

### Tool Access (SECURITY-AWARE)
- Defined by: Global (baseline tool list)
- Can extend by: Project (enable optional tools)
- Can specialize by: Agent config (agent-specific tools)
- Precedence: Most restrictive wins (security-first)
```

**Mode-Loading Semantics:**

```markdown
## Mode-Aware Loading

### Primary Mode (Build Agent)
Loads:
1. Global AGENTS.md (all sections)
2. Project AGENTS.md (all sections, overrides global non-immutable)
3. @.opencode/agent/build.md (full frontmatter + body)

System prompt composition:
- Security Rules (from Global, immutable)
- Code Conventions (Global + Project merged)
- Agent Definitions (Global overridden by Project if specified)
- Domain Workflows (from Project only)
- Build-specific delegations (from agent config)

### Subagent Mode (Plan, Researcher, etc.)
Loads:
1. Global AGENTS.md (immutable sections only: Security, Priority Hierarchy)
2. Global AGENTS.md:SkillsSystem (for skill discovery)
3. @.opencode/agent/plan.md (full implementation)

SKIPS:
- Project AGENTS.md (avoid domain context bleed)
- Project AGENTS.md:DomainWorkflows (irrelevant to planning)

Rationale:
- Subagents need security baseline + skill discovery
- Subagents should NOT know project domain specifics (focused task scope)
- Prevents accidental coupling between agents

System prompt composition:
- Security Rules (minimal baseline)
- Agent-specific communication style + delegation rules
- Task-focused tool access (no domain tools unless needed)
```

**Pros:**
- ✅ Simplicity: 3 files max (Global, Project, Agent config)
- ✅ Clarity: Immutable vs. Extensible distinction is clear
- ✅ Scalability: Can add sections without breaking structure
- ✅ Explicit: Mode-aware loading is documented and clear
- ✅ Maintainability: Single Global baseline, project extends it, agents specialize
- ✅ Elegant: Scope defines inheritance rules (immutable ≠ extensible ≠ specializable)

**Cons:**
- ⚠️ Requires careful section labeling (must be consistent)
- ⚠️ Larger individual files (must manage file size well)

---

## RECOMMENDATION: ALTERNATIVE C (Scope-Based Inheritance)

### Why Alternative C is Inevitable

**Assessment Matrix:**

| Criterion | A: Linear | B: Layered | C: Scope-Based | Winner |
|-----------|-----------|-----------|---|---|
| **Simplicity** | 9/10 | 4/10 | 9/10 | A, C |
| **Clarity** (immutable vs. extensible) | 5/10 | 10/10 | 10/10 | B, C |
| **Maintenance Burden** | 3 files | 7+ files | 3 files | A, C |
| **Extensibility** (adding new layers) | 4/10 | 10/10 | 9/10 | B, C |
| **Explainability** (why a rule applies) | Medium | Complex | Simple | A, C |
| **Team Onboarding** | Fast | Slow | Fast | A, C |
| **Mode-aware loading clarity** | Implicit | Explicit | Explicit | B, C |

**Why NOT Alternative A (Linear Cascade):**
- Security layer is indistinguishable from conventions
- Cannot express "immutable vs. extensible" distinction
- Subagent mode-aware loading requires special comments (brittle)
- Hard to explain to new team member: "What can the project layer override?"

**Why NOT Alternative B (Layered Composition):**
- 7+ files is overkill for 80% of projects
- Precedence path is complex (7 layers to understand)
- Maintenance burden (keep 7 files in sync)
- New team members ask: "Which of 7 files do I edit?" (decision paralysis)

**Why Alternative C WINS:**
1. **Balances simplicity + clarity** (3 files, but with clear section labeling)
2. **Immutable/Extensible distinction is obvious** (security vs. conventions vs. agent definitions)
3. **Mode-aware loading is explicit** (document which sections agents load)
4. **Extensible without adding files** (add sections to existing files)
5. **New team members understand immediately:**
   - "Edit global AGENTS.md" = core rules (immutable sections)
   - "Edit project AGENTS.md" = domain-specific customization
   - "Edit .opencode/agent/{name}.md" = agent behavior specialization
6. **Scales from 1-person to 50-person teams** (same structure, more detailed project AGENTS.md)

**One-Paragraph Explanation:**
> Global AGENTS.md defines immutable security rules and extensible conventions. Projects inherit everything, customize via their own AGENTS.md (extending conventions, overriding agent configs, defining domain workflows). Agents load their specialized configs which inherit all above. Subagents load only security + skills (skip project domain to avoid context bleed). This respects the principle: **immutable rules → extensible conventions → specializable agents**.

---

## IMPLEMENTATION ROADMAP

### Phase 1: Codify Global AGENTS.md (Immutable + Extensible Sections)

**Current state:** 170 lines, mixed concerns

**Target state:** Clearly labeled sections
```
# Global Agent Baseline

## 🔒 IMMUTABLE SECTIONS (All Projects)

### Security Rules (Never override)
- [existing security content]

### Priority Hierarchy (Never override)
- [existing priority hierarchy]

## 🔧 EXTENSIBLE SECTIONS (Projects can extend/override)

### Core Conventions
- [existing conventions]
- NOTE: Projects can extend with domain-specific conventions

### Skills System
- [existing skills content]

### Agent Definitions & Roles
- [existing agent descriptions]
- NOTE: Projects can add custom agents, override roles
```

**Work required:**
- Add section headers with 🔒 (immutable) vs 🔧 (extensible) badges
- Add inheritance notes for each section
- Clarify which layer (global/project/agent) controls each concept

### Phase 2: Refactor Project AGENTS.md (Customization Layer)

**Current state:** 16 lines (code style only)

**Target state:** Full project customization layer
```
# Project Customization (OpenCodeKit Template)

## Inherits from: Global AGENTS.md
- Security rules: INHERITED, not modified
- Core conventions: EXTENDED with project-specific patterns

## 🔧 Customization Sections

### Project-Specific Conventions
- TypeScript: Extended rules for this project
- Python: Extended rules for this project

### Custom Agent Configurations
- Build agent: Override delegations if needed
- Plan agent: Custom planning patterns

### Domain Workflows
- [Project-specific workflows not in global baseline]

### Tool Access Customizations
- Which optional tools enabled for this project?
```

**Work required:**
- Add explicit "Inherits from" header
- Organize into clear sections
- Document which sections extend global, which override
- Currently underutilized; will be ~50-80 lines after expansion

### Phase 3: Document Inheritance in Agent Configs

**Current state:** YAML frontmatter + markdown, no inheritance notes

**Target state:** Explicit inheritance annotations
```yaml
---
name: build
description: ...
mode: primary
# INHERITANCE RULES
inherits_from: 
  - global:AGENTS.md#AgentDefinitions
  - project:AGENTS.md#CustomAgentConfigs
---

# Build Agent: Core Orchestrator

Note: This agent inherits:
1. Security rules from global AGENTS.md (non-negotiable)
2. Core conventions from global AGENTS.md
3. Custom conventions from project AGENTS.md
4. Custom agent configs from project AGENTS.md
5. This file defines specializations
```

**Work required:**
- Add `inherits_from` field to YAML frontmatter
- Add inheritance note at top of markdown body
- Document which sections of global/project this agent uses

### Phase 4: Create Mode-Loading Documentation

**Deliverable:** New file `@.opencode/PROMPT-LOADING-SEMANTICS.md`

Contents:
```markdown
# Prompt Loading & Mode Semantics

## Primary Mode (Build Agent)

Loads sections from:
1. Global AGENTS.md:ImMUTABLE (Security + Priority)
2. Global AGENTS.md:EXTENSIBLE (Conventions + Skills + Agents)
3. Project AGENTS.md (Customizations + Domain)
4. @.opencode/agent/build.md (Specializations)

System prompt = Merge(1,2,3,4) with 4 > 3 > 2 > 1 precedence

## Subagent Mode (Plan, Researcher, etc.)

Loads sections from:
1. Global AGENTS.md:IMMUTABLE (Security + Priority only)
2. Global AGENTS.md:EXTENSIBLE (Skills system only)
3. @.opencode/agent/plan.md (Specializations)

SKIPS: Project AGENTS.md (domain context isolation)

Rationale: Subagents should not know project domain details
```

---

## SUCCESS CRITERIA

✅ **New team member can:**
- Understand prompt hierarchy in <5 minutes
- Predict which prompt controls any given behavior
- Customize for new project without touching global files
- Add new agent without modifying 3+ files
- Explain cascade to colleague in one paragraph

✅ **Architecture is elegant:**
- Folder structure makes hierarchy obvious
- Override rules are explicit (precedence table)
- No duplication (inheritance model prevents copy-paste)
- Mode-aware (primary vs. subagent shapes loading)
- Portable (projects are self-contained)

---

**Status:** ✅ RECOMMENDATION COMPLETE  
**Next Step:** Phase 1 implementation (codify global AGENTS.md sections)