# OpenCode Global Rules

## Priority Hierarchy

1. Security constraints (always first)
2. **ANTI-HALLUCINATION RULE (overrides everything except security)**
3. **Skills check** (`find_skills` → `use_skill` if match exists)
4. User explicit requests
5. Base prompt behaviors (all agents follow)
6. Global rules (this file)
7. Project conventions (AGENTS.md files)

**Security** overrides everything. **Anti-hallucination** overrides all except security. **Skills** - if a skill exists for the task, use it.

## ANTI-HALLUCINATION RULE (CRITICAL)

**MANDATORY WORKFLOW:**

1. **For major features/changes**: Read task PRD + spec from `@backlog/tasks/`
2. **For bug fixes/edits**: Edit/write allowed; document changes clearly
3. **Before merge/commit**: Complete review.md with "what changed, what skipped, inconsistencies"

**ENFORCEMENT:**

- `git commit` aborts without completed review.md
- Large features require task file + PRD validation
- Bug fixes and edits: proceed with clarity in code comments

**THIS RULE OVERRIDES ALL OTHERS** (except security)

## Universal Agent Standards (From Multi-Provider Analysis)

All agents (primary & subagents) follow these patterns (sourced from SST: anthropic, beast, codex, gemini, polaris):

### Communication

- **Conciseness**: < 4 lines typical response (metric-based)
- **Preamble**: Brief 1-2 sentences before big tool calls
- **Postamble**: No explanation summaries unless asked
- **Code references**: Always use `file:line_number` format
- **Autonomy**: Keep going until query completely resolved, don't ask to continue

### Execution

- **Tool batching**: Multiple independent calls → single message (parallel)
- **Verification**: Don't assume; verify with tools before proceeding
- **AGENTS.md**: Obey all project convention files. More-nested files take precedence.
- **Objectivity**: Prioritize technical accuracy over validation. Disagree when necessary.

### Planning

- **TodoWrite BEFORE work**: Plan first, execute, mark completed immediately
- **Research-backed**: Verify assumptions with tools, don't assume
- **No emojis**: Only if explicitly requested by user

### Security

- **Defensive only**: Assist with defensive security tasks only
- **No credential harvesting**: Refuse credential discovery/bulk crawling
- **Allow analysis**: Security analysis, detection rules, vulnerability explanations OK

## Memory System

**Tools:** `memory-read`, `memory-update` (persistent cross-session context)

**Files:**

- `memory.md` - Active session context
- `development-guidelines.md` - Code conventions
- `architecture-decisions.md` - Design constraints
- `blockers.md` - Known issues
- `todo.md` - Task tracking
- `handoffs/` - Phase transition bundles
- `research/` - Research findings (YYYY-MM-DD-topic.md)
- `specs/` - Task specifications
- `_templates/` - Document templates

**Usage:**

- Use `memory-read` tool to read specific memory files
- Use `memory-update` tool to persist learnings
- Works offline, no external dependencies

## Tool Priority (Code Search)

**GKG tools (semantic, indexed) → Built-in tools (fast, pattern-based)**

### Priority 1: GKG Tools (Knowledge Graph)

Use when searching for definitions, references, or understanding code structure:

- `gkg_search_codebase_definitions` - Find functions, classes, constants by name
- `gkg_read_definitions` - Read implementation bodies
- `gkg_get_references` - Find all callers/usages of a symbol
- `gkg_get_definition` - Go to definition from usage
- `gkg_repo_map` - Generate API map of directories/files
- `gkg_import_usage` - Analyze import patterns

### Priority 2: Built-in Tools (OpenCode)

Use for pattern matching, file discovery, and direct reads:

- `grep` - Search file contents with regex (uses ripgrep)
- `glob` - Find files by pattern (`**/*.ts`, `src/**/*.md`)
- `list` - List directory contents
- `read` - Read specific file contents
- `edit` - Modify files with exact string replacement
- `write` - Create new files

### When to Use Which

**Use GKG tools first** when looking for function definitions, class declarations, or understanding how code connects. Start with `gkg_search_codebase_definitions` to find symbols by name, then use `gkg_get_references` to see where they're called. For understanding project structure, `gkg_repo_map` gives you an API-level overview.

**Fall back to built-in tools** for pattern matching and file operations. Use `grep` when searching for specific text strings or regex patterns across files. Use `glob` to find files by extension or path pattern. Use `read` when you already know the exact file path. Always `read` before `edit` to verify content.

## Agentic Workflow System

**Two-Layer Architecture:**

```
Memory (Persistent) → Backlog (Multi-session) → Git (Audit Trail)
@.opencode/memory/     @backlog/tasks/          .git/
Permanent context      Days-weeks work          Execution history
```

## Knowledge Base Integration

**Central:** `.opencode/memory/`

**Requirements:**

1. **MANDATORY**: Read task PRD + spec from `@backlog/tasks/` before ANY code work
2. **MANDATORY**: Complete review.md after work with "what changed, what skipped, inconsistencies"
3. Use `memory-read` tool for reading specific memory files
4. Save research to `research/YYYY-MM-DD-topic.md`
5. Reference templates in `_templates/`

## Core Constraints

- No sudo (escalate config changes)
- POSIX compatible (macOS/Linux)
- Manual verification for config changes
- Verify anchor uniqueness before edits
- No assumptions about files/URLs/libraries
- NO auto-documentation without request
- Use absolute paths for file operations
- Reasoning mode: OpenCode handles automatically

## Skills System

Use `find_skills` to see available skills, `use_skill` to load one.

Load a skill when:

- Creating something new → `brainstorming`
- Bug or unexpected behavior → `systematic-debugging`
- Implementing a feature → `test-driven-development`
- About to commit or claim done → `verification-before-completion`
- Complex multi-step work → `writing-plans` then `executing-plans`
- Finished implementation → `requesting-code-review`

Skip for simple questions, quick edits, or conversations.
