/**
 * Static resource: AI agent guide for working with Abracadabra documents.
 */
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

const AGENT_GUIDE = `# Abracadabra AI Agent Guide

## Core Principle: "Everything is a Document"

Every piece of visible data in Abracadabra — a calendar event, a kanban card, a table cell, a map marker — is a **document** in the tree. The document's **label** (name) IS the displayed value. Always.

- A column's name IS the column header
- A card's name IS the card title
- A cell's name IS the cell content
- An event's name IS the event title

**Page types are views over the same document hierarchy**, not isolated data stores. Switching a page from Kanban to Table to Outline works without migration — the tree doesn't change, only the rendering.

The same tree viewed as different page types:
\`\`\`
My Doc
├── "To Do"       → Kanban: column / Table: column / Outline: item
│   ├── "Fix bug" → Kanban: card   / Table: cell   / Outline: sub-item
│   └── "Add tests"
├── "In Progress"
│   └── "Refactor"
└── "Done"
    └── "Deploy"
\`\`\`

---

## Getting Oriented in a Space

Before creating any documents, always call \`list_spaces\` to understand the current workspace. Each space has a \`doc_id\` — this is the **hub document** (the space root). All user-created documents must be direct or indirect children of this hub doc.

\`\`\`
list_spaces → pick the active space → note its doc_id (= hub doc ID)
create_document(parentId: hubDocId, ...)   ← top-level pages go here
\`\`\`

The hub doc itself is a system document — do not rename, move, or write content to it. It is just a container.

If you are adding content to an existing space, call \`get_document_tree(rootId: hubDocId)\` first to understand what already exists before creating anything.

---

## Page Types Reference

### Core Types (always available)

| Type | Children Are | Grandchildren Are | Depth | Key Meta on Children |
|------|-------------|-------------------|-------|---------------------|
| **doc** | Sub-documents | Sub-sub-documents | ∞ | — |
| **kanban** | Columns | Cards | 2 | color, icon on cards |
| **table** | Columns | Cells (positional rows) | 2 | — |
| **calendar** | Events | — | 1 | datetimeStart, datetimeEnd, allDay, color, icon |
| **timeline** | Epics | Tasks | 2 | dateStart, dateEnd, taskProgress, color |
| **checklist** | Tasks | Sub-tasks | ∞ | checked, priority, dateEnd |
| **outline** | Items | Sub-items | ∞ | — |
| **graph** | Nodes | — | 1 | graphX, graphY, graphPinned, color |
| **gallery** | Items | — | 1 | geoLat, geoLng, datetimeStart, tags, rating, icon, color |
| **map** | Markers/Lines | Points (for lines) | 2 | geoType, geoLat, geoLng, icon, color |
| **slides** | Slides | Sub-slides | 2 | slidesTransition, color |
| **dashboard** | Items | — | 1 | deskX, deskY, deskZ, deskMode |
| **chart** | Data points | Data points | 2 | number (value), color, tags |
| **sheets** | Columns | Cells | 2 | formula, bold, italic, textColor, bgColor, align |
| **overview** | Pages | — | 1 | — |
| **call** | — (no children) | — | 0 | — |

Alias: \`desktop\` → \`dashboard\`.

### Plugin Types (require plugin enabled on the server)

| Type | Plugin | Children Are | Grandchildren Are | Depth | Key Meta on Children |
|------|--------|-------------|-------------------|-------|---------------------|
| **spatial** | spatial | Objects | Sub-parts | ∞ | spShape, spX/Y/Z, spRX/RY/RZ, spSX/SY/SZ, color, spOpacity |
| **media** | media | Tracks | — | ∞ | tags |
| **coder** | coder | Files/Folders | — | ∞ | fileType, entry |

> Spatial uses the universal \`color\` key for object color — there is no \`spColor\`.

---

## Document Tree Operations

### Creating Well-Structured Hierarchies

**Kanban board:**
1. \`create_document(parentId, "Project Board", "kanban")\`
2. Create columns: \`create_document(boardId, "To Do")\`, \`create_document(boardId, "In Progress")\`, \`create_document(boardId, "Done")\`
3. Create cards under columns: \`create_document(toDoColumnId, "Fix bug #123")\`
4. Optionally set card metadata: \`update_metadata(cardId, { color: "#ef4444", priority: 3, tags: ["urgent"] })\`
5. Optionally configure column width: \`update_metadata(boardId, { kanbanColumnWidth: "wide" })\`

**Table with data:**
1. \`create_document(parentId, "Contacts", "table")\`
2. Create columns: \`create_document(tableId, "Name")\`, \`create_document(tableId, "Email")\`, \`create_document(tableId, "Phone")\`
3. Create cells (children of columns): \`create_document(nameColId, "Alice")\`, \`create_document(emailColId, "alice@example.com")\`
4. **Rows are positional** — the Nth child of each column forms row N
5. Row count = max children across all columns. Missing cells render as empty.
6. To add a row: create a child under each column at the same index position
7. To delete row N: delete the Nth child from every column

**Calendar with events:**
1. \`create_document(parentId, "Team Calendar", "calendar")\`
2. Create events: \`create_document(calendarId, "Sprint Planning")\`
3. Set event times: \`update_metadata(eventId, { datetimeStart: "2026-03-20T10:00:00Z", datetimeEnd: "2026-03-20T11:00:00Z" })\`
4. All-day events: \`update_metadata(eventId, { datetimeStart: "2026-03-20", allDay: true })\`
5. Multi-day events: \`update_metadata(eventId, { datetimeStart: "2026-03-20", datetimeEnd: "2026-03-22", allDay: true })\`
6. Configure view: \`update_metadata(calendarId, { calendarView: "week" })\`

**Timeline (Gantt chart):**
1. \`create_document(parentId, "Q1 Roadmap", "timeline")\`
2. Create epics: \`create_document(timelineId, "Auth Rewrite")\`
3. Create tasks under epics: \`create_document(epicId, "Implement JWT refresh")\`
4. Set dates and progress: \`update_metadata(taskId, { dateStart: "2026-03-01", dateEnd: "2026-03-15", taskProgress: 50, color: "#6366f1" })\`

**Checklist (nested task list):**
1. \`create_document(parentId, "Sprint Tasks", "checklist")\`
2. Create tasks: \`create_document(checklistId, "Write tests")\`
3. Set task properties: \`update_metadata(taskId, { checked: false, priority: 3, dateEnd: "2026-04-01" })\`
4. Create sub-tasks (unlimited nesting): \`create_document(taskId, "Unit tests")\`

**Map with markers and lines:**
1. \`create_document(parentId, "Travel Map", "map")\`
2. Create markers: \`create_document(mapId, "Coffee Shop")\`
3. Set marker position: \`update_metadata(markerId, { geoType: "marker", geoLat: 37.7749, geoLng: -122.4194, icon: "coffee", color: "#f97316" })\`
4. Create a line/route: \`create_document(mapId, "Walking Route")\`
5. Set line properties: \`update_metadata(routeId, { geoType: "line", color: "#3b82f6" })\`
6. Create line points as children: \`create_document(routeId, "Start")\` then \`update_metadata(pointId, { geoLat: 37.7749, geoLng: -122.4194 })\`
7. Create measuring tool: set \`geoType: "measure"\` instead of "line"

**Gallery:**
1. \`create_document(parentId, "Photo Album", "gallery")\`
2. Create items: \`create_document(galleryId, "Sunset at Beach")\`
3. Set metadata: \`update_metadata(itemId, { geoLat: 37.7749, geoLng: -122.4194, tags: ["travel", "sunset"] })\`
4. Configure layout: \`update_metadata(galleryId, { galleryColumns: 4, galleryAspect: "16:9" })\`

**Graph (knowledge graph):**
1. \`create_document(parentId, "Tech Stack", "graph")\`
2. Create nodes: \`create_document(graphId, "React")\`, \`create_document(graphId, "Vue")\`
3. Set node properties: \`update_metadata(nodeId, { color: "#6366f1", icon: "file-code" })\`
4. Edges are created by parent-child relationships AND document references (doc embeds/links in content)
5. Enable reference edges: \`update_metadata(graphId, { showRefEdges: true })\`

**Dashboard:**
1. \`create_document(parentId, "Overview", "dashboard")\`
2. Create items: \`create_document(dashboardId, "Revenue Chart")\`
3. Position items on grid: \`update_metadata(itemId, { deskX: 0, deskY: 0, deskMode: "widget-lg" })\`
4. Modes: \`"icon"\` (small), \`"widget-sm"\` (240×180), \`"widget-lg"\` (400×320)
5. Grid uses 80px cells

**Spatial (3D scene)** *(requires spatial plugin):*
1. \`create_document(parentId, "3D Scene", "spatial")\`
2. Create objects: \`create_document(sceneId, "Red Cube")\`
3. Set 3D properties: \`update_metadata(objId, { spShape: "box", color: "#ef4444", spX: 0, spY: 1, spZ: 0, spSX: 2, spSY: 2, spSZ: 2 })\`
4. Shapes: \`"box"\`, \`"sphere"\`, \`"cylinder"\`, \`"cone"\`, \`"plane"\`, \`"torus"\`, \`"glb"\` (uploaded 3D model — set \`spModelUploadId\` and \`spModelDocId\`)
5. Rotation (degrees): \`spRX\`, \`spRY\`, \`spRZ\`. Scale: \`spSX\`, \`spSY\`, \`spSZ\` (default 1). Opacity: \`spOpacity\` (0–100)
6. Use the universal \`color\` key — **never \`spColor\`**

**Outline (nested items):**
1. \`create_document(parentId, "Meeting Notes", "outline")\`
2. Create items: \`create_document(outlineId, "Agenda Item 1")\`
3. Create sub-items (unlimited depth): \`create_document(itemId, "Sub-point")\`

**Slides (presentation with two-axis nav):**
1. \`create_document(parentId, "Q1 Review", "slides")\`
2. Create slides as direct children: \`create_document(deckId, "Intro")\`
3. Create sub-slides (vertical navigation) as grandchildren: \`create_document(slideId, "Deep dive")\`
4. Per-slide transition: \`update_metadata(slideId, { slidesTransition: "fade", color: "#6366f1" })\`
5. Deck-level theme: \`update_metadata(deckId, { slidesTheme: "dark" })\`

**Chart (data viz — manual or aggregation):**
1. \`create_document(parentId, "Sales", "chart")\`
2. Configure: \`update_metadata(chartId, { chartType: "bar", chartMetric: "value", chartShowLegend: true, chartLimit: 10 })\`
3. Modes:
   - **Manual data points**: create children with \`number\` (value) and optional \`tags\`/\`color\`
     \`create_document(chartId, "Q1")\` then \`update_metadata(dpId, { number: 42500, color: "#6366f1" })\`
   - **Aggregation**: set \`chartMetric\` to \`"type"\`/\`"tag"\`/\`"status"\`/\`"priority"\`/\`"activity"\`/\`"completion"\` and point the chart at a subtree — it aggregates the descendants' meta automatically
4. Chart types: \`"bar"\`, \`"stacked bar"\`, \`"line"\`, \`"donut"\`, \`"treemap"\`
5. Color schemes: \`"default"\`, \`"warm"\`, \`"cool"\`, \`"mono"\`

**Sheets (spreadsheet with formulas):**
1. \`create_document(parentId, "Budget", "sheets")\`
2. Create columns: \`create_document(sheetId, "A")\`, \`create_document(sheetId, "B")\`
3. Create cells under columns (positional rows, like \`table\`)
4. Formulas on cells: \`update_metadata(cellId, { formula: "=A1+B1" })\`
5. Cell formatting: \`update_metadata(cellId, { bold: true, bgColor: "#fef3c7", align: "right" })\`
6. Deck config: \`update_metadata(sheetId, { sheetsDefaultColWidth: 120, sheetsDefaultRowHeight: 28, sheetsShowGridlines: true, sheetsFreezeRows: 1, sheetsFreezeCols: 1 })\`

**Overview (space home):**
1. \`create_document(parentId, "Home", "overview")\`
2. No children required — renders activity, people, stats from the surrounding space
3. Children (if any) show as linked pages

**Call (video room):**
1. \`create_document(parentId, "Daily Standup", "call")\`
2. Video rooms have **no children** — do not add documents underneath

**Coder (multi-file collaborative editor)** *(requires coder plugin):*
1. \`create_document(parentId, "My App", "coder")\`
2. Create files/folders: \`create_document(projectId, "App.vue")\`, \`create_document(projectId, "src")\`
3. Set file type: \`update_metadata(fileId, { fileType: "vue", entry: true })\`
4. \`fileType\` options: \`"vue"\`, \`"ts"\`, \`"js"\`, \`"css"\`, \`"json"\`, \`"folder"\`
5. Mark the entry file with \`entry: true\` — the renderer uses it as the preview root

**Media (audio/video playlist)** *(requires media plugin):*
1. \`create_document(parentId, "Focus Mix", "media")\`
2. Create tracks: \`create_document(playlistId, "Track 1")\` — attach audio/video file via upload tool
3. Playlist config: \`update_metadata(playlistId, { mediaRepeat: "all", mediaShuffle: false })\`

---

## Document References

You can link and embed documents within rich-text content:

**Block-level doc embed** — renders an embedded document preview:
\`\`\`
![[docId]]
\`\`\`

**Inline link to another document:**
\`\`\`
[Link text](/doc/docId)
\`\`\`

**Inline wikilink** (shorthand — converted to doc link):
\`\`\`
[[docId]]
[[docId|Display Text]]
\`\`\`

Example — write content with references:
\`\`\`
write_document(docId, "# Project Overview\\n\\nSee the detailed spec:\\n\\n![[specDocId]]\\n\\nCheck the [timeline](/doc/timelineDocId) for dates.")
\`\`\`

In the **graph** page type, document references (embeds and links) create visible edges between nodes when \`showRefEdges\` is enabled.

---

## Metadata Reference

### Universal Keys (use these — never invent prefixed variants)

| Key | Type | Meaning |
|-----|------|---------|
| \`color\` | string | Hex/CSS color (e.g. "#6366f1") |
| \`icon\` | string | Lucide icon name in kebab-case (e.g. "star", "code-2", "users"). **Never emoji.** Omit for default. |
| \`datetimeStart\` / \`datetimeEnd\` | string | ISO datetime with time |
| \`allDay\` | boolean | Whether datetime is all-day |
| \`dateStart\` / \`dateEnd\` | string | ISO date-only (e.g. "2026-03-20") |
| \`timeStart\` / \`timeEnd\` | string | HH:MM time |
| \`tags\` | string[] | Tag labels |
| \`checked\` | boolean | Done/checked state |
| \`priority\` | number | 0=none, 1=low, 2=medium, 3=high, 4=urgent |
| \`status\` | string | Status string |
| \`rating\` | number | 0–5 stars |
| \`url\` | string | URL |
| \`email\` | string | Email address |
| \`phone\` | string | Phone number |
| \`number\` | number | Generic numeric value |
| \`unit\` | string | Unit label for \`number\` |
| \`subtitle\` | string | Secondary text |
| \`note\` | string | Free-text note |
| \`taskProgress\` | number | 0–100 progress (timeline tasks) |
| \`members\` | { id, label }[] | Assigned users |
| \`coverUploadId\` | string | Cover image (upload ID from upload_file) |

### Geo/Map Keys (for map children)

| Key | Type | Meaning |
|-----|------|---------|
| \`geoType\` | string | "marker", "line", or "measure" |
| \`geoLat\` | number | Latitude |
| \`geoLng\` | number | Longitude |
| \`geoDescription\` | string | Location description text |

### Renderer Config Keys (set on the page doc itself, not its children)

| Key | Type | Applies to | Values |
|-----|------|-----------|--------|
| \`kanbanColumnWidth\` | string | kanban | "narrow", "default", "wide" |
| \`galleryColumns\` | number | gallery | 1–6 |
| \`galleryAspect\` | string | gallery | "square", "4:3", "3:2", "16:9", "free" |
| \`galleryCardStyle\` | string | gallery | "default", "compact", "detailed" |
| \`galleryShowLabels\` | boolean | gallery | show item labels |
| \`gallerySortBy\` | string | gallery | "manual", "date", "name", "rating" |
| \`calendarView\` | string | calendar | "month", "week", "day" |
| \`calendarWeekStart\` | string | calendar | "sun", "mon" |
| \`calendarShowWeekNumbers\` | boolean | calendar | — |
| \`tableMode\` | string | table | "hierarchy", "flat" |
| \`tableSortKey\` | string | table | meta key to sort by |
| \`tableSortDir\` | string | table | "asc", "desc" |
| \`timelineZoom\` | string | timeline | "week", "month", "quarter" |
| \`timelinePixelsPerDay\` | number | timeline | zoom granularity |
| \`timelineCenterDate\` | string | timeline | ISO date to center view |
| \`checklistFilter\` | string | checklist | "all", "active", "completed" |
| \`checklistSort\` | string | checklist | "manual", "priority", "due" |
| \`mapShowLabels\` | boolean | map | — |
| \`graphSpacing\` | string | graph | "compact", "default", "spacious" |
| \`graphShowLabels\` | boolean | graph | — |
| \`graphEdgeThickness\` | string | graph | "thin", "normal", "thick" |
| \`showRefEdges\` | boolean | graph | show doc-reference edges |
| \`mmSpacing\` | string | mindmap-layout | spacing between branches |
| \`spatialGridVisible\` | boolean | spatial | show ground grid |
| \`slidesTheme\` | string | slides | "dark", "light" |
| \`chartType\` | string | chart | "bar", "stacked bar", "line", "donut", "treemap" |
| \`chartMetric\` | string | chart | "value", "type", "tag", "status", "priority", "activity", "completion" |
| \`chartColorScheme\` | string | chart | "default", "warm", "cool", "mono" |
| \`chartLimit\` | number | chart | 3–30 (max items) |
| \`chartShowLegend\` | boolean | chart | — |
| \`chartShowValues\` | boolean | chart | — |
| \`sheetsDefaultColWidth\` | number | sheets | 40–500 |
| \`sheetsDefaultRowHeight\` | number | sheets | 20–100 |
| \`sheetsShowGridlines\` | boolean | sheets | — |
| \`sheetsFreezeRows\` | number | sheets | frozen rows count |
| \`sheetsFreezeCols\` | number | sheets | frozen cols count |
| \`mediaRepeat\` | string | media | "off", "all", "one" (plugin) |
| \`mediaShuffle\` | boolean | media | plugin |

### Spatial 3D Keys (for spatial children — requires spatial plugin)

| Key | Type | Default | Meaning |
|-----|------|---------|---------|
| \`spShape\` | string | — | "box", "sphere", "cylinder", "cone", "plane", "torus", "glb" |
| \`color\` | string | — | CSS color — universal key, **not** \`spColor\` |
| \`spOpacity\` | number | 100 | 0–100 |
| \`spX\`, \`spY\`, \`spZ\` | number | 0 | Position |
| \`spRX\`, \`spRY\`, \`spRZ\` | number | 0 | Rotation (degrees) |
| \`spSX\`, \`spSY\`, \`spSZ\` | number | 1 | Scale |
| \`spModelUploadId\` | string | — | GLB upload ID (when \`spShape: "glb"\`) |
| \`spModelDocId\` | string | — | Doc ID that owns the GLB upload |

### Dashboard Keys (for dashboard children)

| Key | Type | Meaning |
|-----|------|---------|
| \`deskX\`, \`deskY\` | number | Grid position (80px cells) |
| \`deskZ\` | number | Z-index (layering) |
| \`deskMode\` | string | "icon", "widget-sm" (240×180), "widget-lg" (400×320) |

### Sheets Cell Formatting (per-cell meta)

| Key | Type | Meaning |
|-----|------|---------|
| \`formula\` | string | Cell formula (e.g. "=A1+B1") |
| \`bold\` | boolean | — |
| \`italic\` | boolean | — |
| \`textColor\` | string | CSS color |
| \`bgColor\` | string | CSS color |
| \`align\` | string | "left", "center", "right" |

### Coder Keys (for coder children — plugin)

| Key | Type | Meaning |
|-----|------|---------|
| \`fileType\` | string | "vue", "ts", "js", "css", "json", "folder" |
| \`entry\` | boolean | Mark this file as the preview entry point |

### Discovering What Metadata Applies

Use the \`list_page_types\` tool to enumerate all known page types and their declared \`metaSchema\` (fields that apply to children/descendants) and \`defaultMetaFields\` (renderer config fields on the page itself). It's the authoritative list of what meta keys make sense for any given page type.

---

## Content Structure

Documents use a TipTap editor schema. The body supports:
- Headings (# through ######)
- Paragraphs with **bold**, *italic*, ~~strikethrough~~, \\\`code\\\`, [links](url)
- Bullet lists, ordered lists, task lists (- [x] / - [ ])
- Code blocks with language
- Blockquotes
- Tables (pipe syntax)
- Horizontal rules
- Images: \`![alt](src){width="..." height="..."}\`
- Document embeds: \`![[docId]]\`
- Inline doc links: \`[[docId|label]]\` or \`[label](/doc/docId)\`
- MDC components: \`::tip\`, \`::note\`, \`::warning\`, \`::collapsible\`, \`::steps\`, \`::card\`, \`::accordion\`, \`::tabs\`, \`::code-group\`, etc.
- Badges: \`:badge[Label]{color="..."}\`
- Icons: \`:icon{name="star"}\`

### Writing Content with Frontmatter

Set document title and metadata via YAML frontmatter:

\`\`\`markdown
---
title: My Document
tags: [important, review]
color: "#6366f1"
icon: star
priority: high
checked: false
datetimeStart: "2026-03-20T10:00:00Z"
datetimeEnd: "2026-03-20T11:00:00Z"
allDay: false
geoLat: 37.7749
geoLng: -122.4194
geoType: marker
---

Content goes here...
\`\`\`

---

## Awareness / Presence

When you connect, you appear in the awareness system alongside human users. Presence runs at two levels:
- **Root awareness**: your name, color, and which document you're currently viewing (\`docId\`)
- **Child doc awareness**: per-document presence including TipTap cursor position and renderer-specific state

### What happens automatically

You do **not** need to call \`set_presence\` after reading or writing content — it's done for you:

| Action | Automatic effect |
|---|---|
| \`read_document\` | Root \`docId\` updated; TipTap cursor placed at start of document |
| \`write_document\` | Root \`docId\` updated; TipTap cursor placed at end of written content |
| \`create_document\` | Root \`docId\` updated to the new document |

### set_presence — manual overrides only

Use \`set_presence\` when you want to:
- Override \`status\` to communicate intent ("thinking", "reviewing", "writing")
- Explicitly update \`docId\` when browsing the document tree without reading content

### set_doc_awareness — renderer-specific item presence

For structured renderers (kanban, table, calendar, etc.), use \`set_doc_awareness(docId, fields)\` to broadcast which item you are interacting with. This is visible as highlighted cards, cells, events, etc. in the dashboard.

Always clear fields when done by setting them to \`null\`.

| Renderer | Key | Value | When to set |
|---|---|---|---|
| **Kanban** | \`kanban:hovering\` | cardId | Inspecting or about to edit a card |
| **Kanban** | \`kanban:dragging\` | \`{ cardId, toColumnId }\` | Moving a card between columns |
| **Table** | \`table:editing\` | \`{ rowIdx, fieldId }\` | Editing a cell |
| **Calendar** | \`calendar:focused\` | eventId | Interacting with an event |
| **Calendar** | \`calendar:viewing\` | "YYYY-MM" | The month/week you're looking at |
| **Outline** | \`outline:editing\` | nodeId | Editing an outline node |
| **Gallery** | \`gallery:focused\` | itemId | Item hovered/selected |
| **Timeline** | \`timeline:focused\` | taskId | Task selected |
| **Graph** | \`graph:focused\` | nodeId | Node hovered/selected |
| **Slides** | \`slides:current\` | slideId | Slide being presented |
| **Spatial** | \`spatial:selected\`, \`spatial:camera\` | objectId / camera state | plugin |
| **Media** | \`media:playing\`, \`media:position\` | trackId / 0–1 | plugin |
| **Coder** | \`coder:activeFile\` | fileId | plugin |
| **Map** | \`map:focused\` | markerId | Marker hovered/selected |
| **Doc** | \`doc:scroll\` | 0–1 number | Scroll position in document |

Example — mark a kanban card as being inspected, then clear:
\`\`\`
set_doc_awareness(boardDocId, { "kanban:hovering": cardId })
// ... do work ...
set_doc_awareness(boardDocId, { "kanban:hovering": null })
\`\`\`

---

## Receiving Instructions from Humans

**Channel events (preferred):** When running in channel mode, \`ai:task\` events from
human users arrive as \`<channel source="abracadabra" ...>\` notifications directly in
your session. Use the \`reply\` tool to send your response — it creates a reply document
and signals task completion.

**Chat messages:** Chat messages from the platform arrive as channel notifications. Use
\`send_chat_message\` to respond in the same channel.

**Polling (fallback):** Call \`poll_inbox\` to read the "AI Inbox" document.

---

## Common Patterns

### Explore a document fully (the correct way)
\`\`\`
1. read_document(docId)
   → returns { markdown, children: [...] }
2. The body may be empty — that does NOT mean the doc is empty.
   Children ARE the content. Read every child:
   read_document(childId1), read_document(childId2), ...
3. Continue recursively until no children remain.
\`\`\`

**Never conclude a document is "empty" just because its markdown body is empty.
Always check and traverse the \`children\` array returned by \`read_document\`.**

### Populate a kanban board from a list
\`\`\`
1. create_document → kanban parent
2. For each column: create_document under kanban
3. For each card: create_document under the appropriate column
4. Optionally set metadata (color, tags, priority) on cards
\`\`\`

### Write rich content with references
\`\`\`
1. read_document to see current content (and children)
2. write_document with markdown (mode: "replace" or "append")
3. Use ![[docId]] to embed other documents
4. Use [[docId|label]] for inline doc links
5. Include frontmatter for title/metadata if needed
\`\`\`

---

## Rules

### MUST:
- Call \`list_spaces\` first to find the hub doc ID before creating any documents
- Use document \`label\` as the display value — renaming a document renames it everywhere
- Create child documents for every visible item (columns, cards, events, etc.)
- Use universal meta keys (color, icon, dateStart) — never prefix with page type
- Set meaningful labels on every document you create
- Use \`get_document_tree\` to understand existing structure before adding to a space
- Traverse the full \`children\` tree when asked to "check out", "explore", or "summarize" a document

### MUST NOT:
- Conclude a document is empty because its markdown body is empty — check children first
- Stop at the top-level doc when exploring — children and grandchildren are part of the content
- Store display values in metadata — the label IS the display value
- Use special metadata to distinguish document roles — the hierarchy does that
- Create documents just for metadata — metadata lives ON documents
- Break interchangeability — switching page types must not lose data
- Use emoji as \`icon\` values — only lowercase kebab-case Lucide icon names are valid
- Create top-level documents without first confirming the correct hub doc ID
- Rename or write content to the space hub document itself
- Set \`type\` on child items (cards, cells, events) — only set type on the parent page
`;

export function registerAgentGuide(mcp: McpServer) {
  mcp.resource(
    "agent-guide",
    "abracadabra://agent-guide",
    {
      description:
        "Comprehensive guide for AI agents working with Abracadabra documents. Covers page types, tree operations, metadata, content structure, and best practices.",
      mimeType: "text/markdown",
    },
    async () => ({
      contents: [
        {
          uri: "abracadabra://agent-guide",
          text: AGENT_GUIDE,
          mimeType: "text/markdown",
        },
      ],
    }),
  );
}
