# How It Works

# How It Works

`@maestria/opencode` is a pure plugin with no filesystem side effects. It uses three OpenCode lifecycle hooks to wire itself into every session.

## Plugin Hook Architecture

The plugin factory runs synchronously at initialization:

1. **Load agents** — Scans the bundled `agents/` directory for `.md` files
2. **Parse frontmatter** — Extracts name, description, mode, permissions, and prompt from each file
3. **Register hooks** — Returns an object with `config` and `session.compacting` hooks

## Hook 1: Config

The `config` hook fires when OpenCode initializes:

- Reads all 8 agent `.md` files from the bundled `agents/` directory
- Parses YAML frontmatter using a custom parser (~120 lines)
- Merges agents into `input.agent`: `{ ...input.agent, ...parsedAgents }`
- Appends the path to `rules/AGENTS.md` into `input.instructions`

This means every agent definition and every global rule is available from the first prompt.

## Hook 2: session.compacting

The `session.compacting` hook fires when OpenCode compacts a session (to manage context window size):

- Pushes a context preservation note into `output.context`
- Notes that task tracking via `todowrite` is maintained
- Remembers active context: files, decisions, blockers
- Allows the session to continue seamlessly after compaction

## Agent File Loading

The agent loading pipeline:

```
agents/*.md
  → readFileSync (all files)
  → split on "---" (frontmatter delimiter)
  → parseFrontmatter (custom YAML parser)
  → { name, config: { description, mode, prompt, permission } }
  → merged into input.agent
```

## Rule Injection

Global rules are loaded from `rules/AGENTS.md` and injected via `input.instructions`, not via a `system.transform` hook. This means the rules are part of the session's system prompt from the start, not appended after the fact.
**Note:** The plugin uses `input.instructions` (not `system.transform`) to inject global rules. This ensures
  rules are present from the very first response, not appended mid-session.