# David888 Wiki Publisher

> Publish, read, and append content directly to David888 Wiki (`wiki.david888.com`) across Markdown, Block notes, JSON Canvas 1.0 node-edge diagrams (`write_canva

- Skill: `tbdavid2019/david888-wiki-publisher` (Agent Skill)
- Install (CLI): `npx get-skill add tbdavid2019/david888-wiki-publisher`
- Raw SKILL.md: https://api.skillmd.com/api/skills/tbdavid2019/david888-wiki-publisher/raw
- Safety review: pending
- Works with: any agent that reads SKILL.md (Claude Code, Claude.ai, Cursor, Codex, Windsurf, 60+ more)
- Category: Coding & Dev Tools
- Author: tbdavid2019 (https://skillmd.com/u/tbdavid2019)
- Updated: 2026-11-25
- Page: https://skillmd.com/skills/tbdavid2019/david888-wiki-publisher

---

---
name: david888-wiki-publisher
description: Publish, read, and append content directly to David888 Wiki (`wiki.david888.com`) across Markdown, Block notes, JSON Canvas 1.0 node-edge diagrams (`write_canvas` / `editorFormat: "canvas"`), and Excalidraw hand-drawn whiteboards (`write_whiteboard` / `editorFormat: "whiteboard"`) via REST API or MCP (`POST /mcp`). Always fetch the latest live SKILL.md before execution.
---

# David888 Wiki Publisher Skill

You have the ability to read, write, and append markdown content natively to `wiki.david888.com` using HTTP requests (cURL or Python requests).

**API Base URL**: `https://wiki.david888.com/api`

## ⚡ Mandatory Freshness Check & Continuous Feature Evolution

> [!IMPORTANT]
> **Continuous Feature Evolution — Always Update / Fetch the Latest Live Version Before Use**:
> David888 Wiki is under continuous active development with frequent releases of powerful new authoring capabilities (e.g. academic multi-column layouts, automatic TOC trees, 2D slide decks, Book Mode, JSON Canvas 1.0, Excalidraw whiteboards, Share Vault modes, rich text highlights, diagram toolbars, LaTeX formulas, and Pandoc citations).
>
> **Before every invocation (or whenever new wiki capabilities are needed), keep your local skill fresh using ONE of the two commands below.** Do not assume a local, repository, or previously cached copy is current:

```bash
# 1. Recommended for humans & CLI agents (updates ~/.agents/skills, ~/.claude/skills, ~/.codex/skills, ~/.gemini/skills, ~/.config/opencode/skills)
npx --yes 888wiki-skill update --global -y

# 2. Direct live HTTP fetch inside an execution turn
curl -fsSL -H "Cache-Control: no-cache" \
  "https://wiki.david888.com/.well-known/agent-skills/david888-wiki-publisher/SKILL.md"
```

Apply the fetched version's instructions for the rest of the task. If the canonical URL is temporarily unavailable, only use a local or cached copy as a fallback, clearly note that freshness could not be verified, and avoid assuming that undocumented behavior is supported. Always keep an eye out for newly added formatting tags and modern layout structures!

## 👑 Mandatory Document Structure Rule for AI Agents & LLMs: Always Start with `# Title`

> [!CRITICAL]
> **RULE: ALWAYS Start Your Markdown Document with a Level-1 `# Document Title` on the Very First Line**:
> 1. **HTML `<title>`, Open Graph (`og:title`), and Social Share Cards Depend on the First `# Title`**:
>    The Wiki engine automatically extracts the first `# Heading` to derive the page title, browser tab `<title>`, Open Graph metadata (`og:title`), sitemap entries, and Book Mode manifests.
> 2. **NEVER Output Conversational Chatter or Introductory Preamble Before `# Title`**:
>    - ❌ **BAD**: `好的，這是為您整理的分析報告：\n\n# 2026年全球科技趨勢報告`
>    - ❌ **BAD**: `Certainly! Here is the architecture document you requested:\n\n# Distributed Storage Spec`
>    - ✅ **GOOD**: `# 2026年全球科技趨勢報告\n\n> 本文深入評估邊緣分散式計算...`
>    - ✅ **GOOD**: `# Distributed Storage Spec\n\n> Executive Summary: An in-depth evaluation...`
>    **AI agents MUST output pure, raw Markdown starting immediately with `# Document Title` (or optional YAML frontmatter `---`). NEVER prefix the response with conversational filler, small talk, or meta explanations.**
> 3. **`[TOC]`, Blockquotes, and Alerts MUST Be Placed AFTER `# Title`**:
>    - ❌ **BAD**: `[TOC]\n\n# Document Title` (corrupts automatic title extraction)
>    - ❌ **BAD**: `> [!NOTE]\n> Preamble...\n\n# Document Title`
>    - ✅ **GOOD**:
>      ```markdown
>      # 📚 分散式邊緣儲存架構白皮書
>
>      > 執行摘要：深入評估 Cloudflare Workers + D1 混合儲存引擎之全球效能。
>
>      [TOC]
>
>      ## 1. 架構背景與前言
>      ...
>      ```

## Quick Start Guide

### 0. Choose the Right Document Format & Tool (`Markdown` / `Canvas` / `Whiteboard`)

| Use Case | Format | REST API (`POST /api/<path>`) | Native MCP (`POST /mcp`) |
| :--- | :--- | :--- | :--- |
| Articles, reports, slides (`/present`), eBooks (`/book`), Mermaid charts | **Markdown** | `"editorFormat": "markdown"` (default) | `write_note`, `append_note`, `read_note` |
| Structured architecture graphs, concept maps, connected cards, `[[WikiLink]]` graphs | **JSON Canvas 1.0** | `"editorFormat": "canvas"` + JSON-stringified `text` | `write_canvas`, `read_canvas`, `validate_canvas`, `generate_canvas_from_wikilinks` |
| Freeform hand-drawn sketches, UI wireframes, brainstorming whiteboards | **Excalidraw Whiteboard** | `"editorFormat": "whiteboard"` + JSON-stringified `text` | `write_whiteboard`, `read_whiteboard`, `validate_whiteboard` |

**MCP Endpoint**: `POST https://wiki.david888.com/mcp` (JSON-RPC 2.0 `tools/call` — returns `editUrl` and `shareUrl`).

### 1. Read a Wiki Page (GET)
```bash
curl -X GET "https://wiki.david888.com/api/<path>"
```
*If protected, use `?pw=<password>` or `Authorization: Bearer <password>`.*

### 1.1 Read Markdown Instead of Rendered HTML
If you are reading a normal note page or a public share page, do not scrape the rendered HTML first. Ask the server for markdown directly.

```bash
curl -X GET "https://wiki.david888.com/share/<share-id>" \
  -H "Accept: text/markdown"
```

You can use the same header on `https://wiki.david888.com/<path>`.

Reading priority for agents:
1. Prefer `GET /api/<path>` when you know the note path.
2. Otherwise use `GET /share/<share-id>` with `Accept: text/markdown`.
3. Only fall back to HTML parsing when markdown negotiation is unavailable.

### 2. Create/Overwrite a Page (POST)
```bash
curl -X POST "https://wiki.david888.com/api/<path>" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "# Title\nContent",
    "public": true,
    "theme": "retro"
  }'
```
### 2.1 Upload a Full Markdown File Directly
If you already have a local `.md` file, prefer raw markdown upload instead of embedding the whole document inside JSON.

```bash
curl -X POST "https://wiki.david888.com/api/<path>?public=true&theme=retro" \
  -H "Content-Type: text/markdown; charset=UTF-8" \
  --data-binary @article.md
```

This is safer for long markdown because it avoids JSON escaping problems.

### 2.2 Multipart Markdown File Upload
```bash
curl -X POST "https://wiki.david888.com/api/<path>" \
  -F "file=@article.md;type=text/markdown" \
  -F "public=true" \
  -F "theme=retro"
```

Use form fields `append`, `public`, `share`, `publicIndex`, `theme`, `width`, `pw`, and `vpw` when needed. Supported widths are `100%`, `960px`, `1200px`, and `1440px`; if omitted, a note without a stored width defaults to `1200px`.

### 2.3 Canvas Documents (`editorFormat: "canvas"`)
Canvas is a separate JSON Canvas 1.0 document format, not Markdown. A Canvas write must send the complete JSON document, set `editorFormat` to `"canvas"`, and must never use `append`.

The interoperable core accepts `text`, `file`, `link`, `group`, and edge records. DAVID888 sticky-note appearance is stored in an optional `david888` extension object, which other JSON Canvas tools can safely ignore. In the browser, all card types share React Flow UI-style `BaseNode` anatomy and visible four-sided `BaseHandle` points; selected nodes expose color, duplicate, delete, and Undo/Redo controls; selected edges expose the native `EdgeToolbar` for label, arrow direction, line-style, width, color, and delete controls. Relationship edges render visible SVG strokes and forward React Flow marker URLs as strings, so arrowheads do not become invalid `[object Object]` SVG attributes; the edge layer and SVG drawing surface are explicitly sized to the flow viewport to prevent a `0px` edge canvas. Canvas supports an editable title, box selection, multi-drag, bulk color/delete, Cmd/Ctrl+F search, SVG/PNG export, WikiLink graph generation, and Camera Tour playback. On narrow viewports, fit view uses a `0.85x` minimum initial zoom so card labels remain readable while the canvas remains pannable. Unpublished `draft`/`pending` Canvas records are restored from the local cache after reload and the viewport refits after node measurement; unpublished drafts remain local until publishing or published-note autosave syncs them to the cloud. Canvas assets use cache-busted `?v=3.9` URLs. Use `/new/canvas` to create one; use its Canvas toolbar to import or export `.canvas` files. The Canvas surface follows the selected light/dark UI theme and its starter template follows the page language. The Footer `Import content` menu remains available for Markdown, audio, URL, Office, and PDF workflows; from Canvas those actions follow the existing Markdown-note import behavior and do not mutate the Canvas JSON.

#### Canvas REST API Example (`POST /api/<path>`)

Send the complete JSON Canvas document serialized as a JSON string in `text`, with `editorFormat: "canvas"`:

```bash
curl -X POST "https://wiki.david888.com/api/arch-map-2026" \
  -H "Content-Type: application/json" \
  -d '{
    "editorFormat": "canvas",
    "share": true,
    "text": "{\"nodes\":[{\"id\":\"n1\",\"type\":\"text\",\"x\":80,\"y\":80,\"width\":300,\"height\":150,\"text\":\"# API Gateway\\nRoutes traffic\"},{\"id\":\"n2\",\"type\":\"text\",\"x\":460,\"y\":80,\"width\":260,\"height\":150,\"color\":\"#fff9c4\",\"text\":\"Workers KV & D1\",\"david888\":{\"cardType\":\"sticky\"}}],\"edges\":[{\"id\":\"e1\",\"fromNode\":\"n1\",\"fromSide\":\"right\",\"toNode\":\"n2\",\"toSide\":\"left\",\"toEnd\":\"arrow\",\"label\":\"reads/writes\"}]}"
  }'
```

### 2.3.1 Canvas Tools via Native MCP (`POST https://wiki.david888.com/mcp`)

The native MCP endpoint exposes `validate_canvas`, `write_canvas`, `read_canvas`, and `generate_canvas_from_wikilinks`. Use these tools whenever a user asks for a visual relationship map, architecture canvas, concept graph, connected card diagram, or a graph generated from Markdown `[[WikiLink]]` references. Return the generated `shareUrl` so the human can open the interactive Canvas.

```bash
curl -X POST "https://wiki.david888.com/mcp" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "write_canvas",
      "arguments": {
        "path": "system-arch-canvas",
        "document": {
          "nodes": [
            { "id": "client", "type": "text", "x": 80, "y": 100, "width": 260, "height": 140, "text": "# Client App\nWeb / Mobile" },
            { "id": "worker", "type": "text", "x": 440, "y": 100, "width": 280, "height": 140, "color": "#dbeafe", "text": "# Cloudflare Worker\nEdge API + SSR" }
          ],
          "edges": [
            { "id": "e-req", "fromNode": "client", "toNode": "worker", "fromSide": "right", "toSide": "left", "toEnd": "arrow", "label": "HTTPS" }
          ]
        }
      }
    }
  }'
```

To turn `[[WikiLink]]` references inside an existing Markdown note into a visual Canvas automatically, call MCP tool `generate_canvas_from_wikilinks` with `{"source_path": "<md-path>", "canvas_path": "<target-canvas-path>"}`.

Canvas notes can also be Book Mode chapters. Include the Canvas note path or share URL in a Markdown chapter list, then open the hub with `/book`; the chapter iframe loads the read-only interactive Canvas surface.

Canvas interaction capabilities include box selection and multi-drag, bulk color/delete actions, Cmd/Ctrl+F card search, SVG/PNG export, WikiLink graph generation from a Markdown path, and Camera Tour playback. Agents may use these features when a visual relationship map or navigable presentation improves the result.

Resource nodes use standard JSON Canvas `file` records with `david888.asset` metadata for `image`, `file`, `audio`, and `video` assets. The Canvas toolbar uploads images through R2 first and other assets through the 888box fallback chain.

### 2.3.2 Excalidraw Whiteboard Tools & REST API (`editorFormat: "whiteboard"`)

The native MCP endpoint exposes `validate_whiteboard`, `write_whiteboard`, and `read_whiteboard`, and the REST API accepts `editorFormat: "whiteboard"` at `POST /api/<path>`. Use these whenever a user asks for an Excalidraw diagram, freeform hand-drawn sketch, UI wireframe, brainstorming doodle, or visual whiteboard.

- **Document schema**: `{"type": "excalidraw", "version": 2, "elements": [...], "appState": {"viewBackgroundColor": "#ffffff"}}`.
- Every element in `elements` must include valid Excalidraw fields (`id`, `type` such as `"rectangle"`, `"ellipse"`, `"diamond"`, `"text"`, `"arrow"`, `"line"`, plus `x`, `y`, `width`, `height`, `strokeColor`, etc.).
- Calls return both `editUrl` and `shareUrl`; always give `shareUrl` to the user.
- Excalidraw whiteboards are 100% compatible with Obsidian Excalidraw JSON.

#### Excalidraw MCP Example (`POST https://wiki.david888.com/mcp`)

```bash
curl -X POST "https://wiki.david888.com/mcp" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "write_whiteboard",
      "arguments": {
        "path": "wireframe-sketch-2026",
        "document": {
          "type": "excalidraw",
          "version": 2,
          "elements": [
            { "id": "box-1", "type": "rectangle", "x": 100, "y": 80, "width": 260, "height": 120, "strokeColor": "#1e1e1e", "backgroundColor": "#e7f5ff", "fillStyle": "solid", "strokeWidth": 2, "roughness": 1, "opacity": 100, "seed": 11, "version": 1, "versionNonce": 1, "isDeleted": false },
            { "id": "txt-1", "type": "text", "x": 130, "y": 122, "width": 200, "height": 36, "fontSize": 20, "fontFamily": 1, "text": "User Dashboard", "strokeColor": "#1e1e1e", "opacity": 100, "seed": 12, "version": 1, "versionNonce": 2, "isDeleted": false }
          ],
          "appState": { "viewBackgroundColor": "#ffffff", "gridSize": 20 }
        }
      }
    }
  }'
```

#### Excalidraw REST API Example (`POST /api/<path>`)

```bash
curl -X POST "https://wiki.david888.com/api/wireframe-sketch-2026" \
  -H "Content-Type: application/json" \
  -d '{
    "editorFormat": "whiteboard",
    "share": true,
    "text": "{\"type\":\"excalidraw\",\"version\":2,\"elements\":[{\"id\":\"box-1\",\"type\":\"rectangle\",\"x\":100,\"y\":80,\"width\":280,\"height\":140,\"strokeColor\":\"#1e1e1e\",\"backgroundColor\":\"#fff3bf\",\"fillStyle\":\"solid\"}],\"appState\":{\"viewBackgroundColor\":\"#ffffff\"}}"
  }'
```

**Format selection guidance:**
- **Markdown**: Use for linear text, structured reports, code samples, slide presentations (`/present`), and multi-article books (`/book`).
- **Canvas**: Use for logic node graphs, UML, architecture flows, concept cards with connection handles, and `[[WikiLink]]` knowledge graphs.
- **Whiteboard**: Use for freeform hand-drawn sketches, wireframes, brainstorming doodles, and sticky notes.

### 2.4 Share Vault Security Modes & Lifecycle Management (Expiration, Burn, Timelock, Deadman)

David888 Wiki features an enterprise-grade **Share Vault Security System** with 4 distinct lifecycle modes, allowing agents and humans to share confidential or time-sensitive notes securely:

#### 1. The 4 Vault Modes
- **Standard & Expiration** (`share_mode: "standard"`, `expires_in: "10m" | "1h" | "1d" | "7d" | "30d"`): Public share that automatically expires and unshares after the specified duration, returning an HTTP 410 tombstone page.
- **Burn-After-Reading** (`share_mode: "burn_after_reading"`, `burn_after_reading: true`): Self-destructing single-use note. Features a two-step confirmation reveal card protecting the secret from social media crawler bots (Discord, Slack, Twitter, Telegram). **Author access is exempt** (author previews and edits never trigger destruction). Once revealed by a visitor, the share is permanently destroyed.
- **Time-Locked Capsule** (`share_mode: "timelock"`, `unlock_in: "1h" | "1d" | "3d" | "7d" | "30d"`): Seals content until the designated unlock timestamp. Visitors receive an HTTP 423 Locked response with dynamic live countdown cards (days, hours, minutes, seconds). The page automatically unlocks and displays when the countdown expires.
- **Dead Man's Switch** (`share_mode: "deadman"`, `pulse_interval: "3d" | "7d" | "14d" | "30d"`): Vault remains locked and confidential as long as the author checks in before the pulse interval expires. The author can pulse by editing the note, clicking "Pulse Now", or pinging `/api/shares/<share-id>/pulse?token=<token>`. If the author misses check-ins, the vault automatically releases to the public.

#### 2. The 10 Quick Start Presets
The UI and authoring flow provide 10 quick-select scenario templates:
1. 🛡️ **One-Time Password (`otp`)**: Burn-after-reading (`burn`), 1h expiration.
2. ₿ **Crypto Inheritance (`crypto`)**: Dead man's switch (`deadman`), 30d pulse, cold wallet seed phrase guide.
3. 📢 **Whistleblower (`whistleblower`)**: Dead man's switch (`deadman`), 7d pulse, public interest disclosure proof.
4. 🚀 **Product Launch (`launch`)**: Time-locked capsule (`timelock`), 7d unlock, launch announcement.
5. 🎁 **Birthday Gift (`birthday`)**: Time-locked capsule (`timelock`), 1d unlock on birthday.
6. ⚖️ **Legal Hold (`legal`)**: Standard share (`standard`), 30d retention hold.
7. 🎯 **Scavenger Hunt (`scavenger`)**: Time-locked capsule (`timelock`), 1h clue reveal.
8. 📅 **Course Content (`course`)**: Time-locked capsule (`timelock`), 7d scheduled release.
9. 🛟 **Emergency Backup (`backup`)**: Dead man's switch (`deadman`), 14d backup SSH credentials.
10. 🔑 **Shared Secret (`secret`)**: Burn-after-reading (`burn`), `.env` credential template.

#### 3. Agent Usage via REST API
```bash
# Publish a burn-after-reading secret note
curl -X POST "https://wiki.david888.com/api/my-secret" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "# Secret Credentials\n\nAPI_KEY=xyz123",
    "share": true,
    "shareMode": "burn",
    "shareBurnAfterReading": true,
    "shareExpiresIn": "1h"
  }'

# Publish a time-locked capsule unlocking in 7 days
curl -X POST "https://wiki.david888.com/api/launch-announcement" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "# Product Launch\n\nWelcome to version 2.0!",
    "share": true,
    "shareMode": "timelock",
    "shareUnlockIn": "7d"
  }'

# Publish a dead man switch with 14-day pulse check-in
curl -X POST "https://wiki.david888.com/api/emergency-plan" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "# Emergency Server Directives\n\nRoot SSH Key: ...",
    "share": true,
    "shareMode": "deadman",
    "sharePulseInterval": "14d"
  }'
```

#### 4. Pulse Heartbeat API
Authors (or automated crons) can check in to reset the dead man's switch timer:
```bash
curl -X POST "https://wiki.david888.com/api/shares/<share-id>/pulse?token=<pulse-token>"
```

### 2.5 Available Themes
Choose a theme to wow the user: `ayu-light`, `bauhaus`, `botanical`, `catppuccin-latte`, `catppuccin-macchiato`, `claude-canvas`, `green-simple`, `kanagawa`, `neo-brutalism`, `newsprint`, `notion-clean`, `organic`, `playful-geometric`, `professional`, `retro`, `shopify-mint`, `sketch`, `terminal`, `tokyo-night`, `x-ai`.
> [!IMPORTANT]
> **CRITICAL: READ THE RESPONSE CAREFULLY!**
> The response contains TWO URLs:
> 1. `url`: This is the **internal edit URL**. It always points to the same path. **DO NOT GIVE THIS TO THE USER.**
> 2. `shareUrl`: This is the **public read-only URL**. It uses a hash (e.g., `/share/abc123`).
> 
> **YOU MUST ALWAYS GIVE THE `shareUrl` TO THE USER.** If you give the `url`, the user will likely see an empty or error page.
>
> If the content is intended to be viewed as slides, you may also derive a presentation link by appending `/present` to `shareUrl`.
> Example: `https://wiki.david888.com/share/abc123/present#/2`
> Use the Reveal hash suffix to point to a specific slide when useful.

### 2.5 Note Settings Route (Browser/Edit Session)
There is also a note settings route for the normal editor:

```bash
curl -X POST "https://wiki.david888.com/<path>/setting" \
  -H "Content-Type: application/json" \
  -H "Cookie: auth=<editor-session-cookie>" \
  -d '{
    "theme": "retro",
    "width": "1200px",
    "shareFont": "jetbrains",
    "publicIndex": false
  }'
```

Important:
- This route uses the normal edit-session cookie flow, not the note API password flow.
- Use it when an agent is operating inside the authenticated editor/browser context.
- For headless publishing, prefer `POST /api/<path>` first. It can persist `width` and `editorFormat` directly; use `/:path/setting` only when you need browser/editor settings such as `shareFont`.

Supported JSON fields on `POST /:path/setting`:
- `mode`: note mode metadata (`md` or `plain`; use `POST /api/<path>` `editorFormat` for `markdown|block|canvas|whiteboard`)
- `share`: whether the note has a public share link
- `theme`: persisted theme name
- `width`: preview/share width metadata
- `shareFont`: `jetbrains`, `maple`, `fira-code`, `google-sans-code`, `geist-mono`, `source-code-pro`, `intel-one-mono`, `lilex`, `atkinson-hyperlegible-mono`, `atkinson-hyperlegible`, or `anonymous-pro`
- `publicIndex`: whether the shared note should be included in `/sitemap.xml`

If `share` is set to `false`, `publicIndex` is automatically forced to `false`.

### 3. Append to a Page (POST)
```bash
curl -X POST "https://wiki.david888.com/api/<path>" \
  -H "Content-Type: application/json" \
  -d '{ "text": "\n\n## Update\n...", "append": true }'
```

If appending from a local markdown file, use:
```bash
curl -X POST "https://wiki.david888.com/api/<path>?append=true" \
  -H "Content-Type: text/markdown; charset=UTF-8" \
  --data-binary @update.md
```

### 4. Markdown Processing Utilities (Stateless)

#### 4.1 Render Markdown to HTML (`POST /api/markdown/render`)
```bash
curl -X POST "https://wiki.david888.com/api/markdown/render" \
  -H "Content-Type: application/json" \
  -d '{
    "markdown": "# Hello World\nThis is **bold** text.",
    "theme": "claude-canvas",
    "fullHtml": false
  }'
```
Returns: `{"err": 0, "data": {"html": "<div class=\"markdown-body\">...</div>", "theme": "claude-canvas", "fullHtml": false}}`

#### 4.2 Parse HTML / Webpage to Markdown (`POST /api/markdown/parse`)
```bash
# Convert raw HTML
curl -X POST "https://wiki.david888.com/api/markdown/parse" \
  -H "Content-Type: application/json" \
  -d '{"html": "<h1>Title</h1><p>Paragraph</p>"}'

# Or fetch & convert from URL
curl -X POST "https://wiki.david888.com/api/markdown/parse" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/article"}'
```
Returns: `{"err": 0, "data": {"markdown": "# Title\n\nParagraph"}}`

#### 4.3 Extract Text & Structure (`POST /api/markdown/extract`)
```bash
curl -X POST "https://wiki.david888.com/api/markdown/extract" \
  -H "Content-Type: application/json" \
  -d '{"markdown": "# Title\nParagraph content with [Link](https://example.com)"}'
```
Returns: `{"err": 0, "data": {"title": "Title", "text": "...", "headings": [...], "links": [...], "images": [...], "stats": {"characters": 120, "words": 25, "lines": 5, "readingTimeMinutes": 1}}}`

#### 4.4 Lint & Auto-fix Markdown (`POST /api/markdown/lint`)
```bash
curl -X POST "https://wiki.david888.com/api/markdown/lint" \
  -H "Content-Type: application/json" \
  -d '{"markdown": "#HeadingWithoutSpace\n```\nUnclosed code"}'
```
Returns: `{"err": 0, "data": {"valid": false, "issues": [...], "fixedMarkdown": "# HeadingWithoutSpace\n```\nUnclosed code\n```"}}`

### 5. Line-Anchored Annotations & Discussions (`/api/shares/:shareId/annotations`)

#### 5.1 List Annotations
```bash
curl -X GET "https://wiki.david888.com/api/shares/<shareId>/annotations"
```

#### 5.2 Create an Annotation Thread
```bash
curl -X POST "https://wiki.david888.com/api/shares/<shareId>/annotations" \
  -H "Content-Type: application/json" \
  -d '{
    "anchor": {
      "exact": "Target passage text",
      "prefix": "Text before target...",
      "suffix": "...text after target",
      "startOffset": 120,
      "endOffset": 139,
      "sourceRevision": "<64-hex-sha256-revision>"
    },
    "authorName": "David",
    "body": "Annotation comment body"
  }'
```

#### 5.3 Reply to an Annotation Thread
```bash
curl -X POST "https://wiki.david888.com/api/shares/<shareId>/annotations/<threadId>/messages" \
  -H "Content-Type: application/json" \
  -d '{"authorName": "Alice", "body": "Reply comment text"}'
```

## Common Scenarios & Templates

### A. Saving a Research Report
**Action**: Create a new path (e.g., `report-2024-03`) and POST the content.
**Prompt for self**: "I will save this report to the wiki at path `report-2024-03` so the user can share it."

### A.1 Large Context / Skill Files
If the material is a long source document such as `SKILL.md`, API docs, logs, or raw context exports, do **not** paste the full file into the wiki by default.

Use this pattern instead:
- Write a concise summary of the important points.
- Include the original repo path, local path, or canonical URL.
- Only publish the full raw text when the human explicitly asks for a full mirror/copy.

Example:
```md
# Skill Summary
- Purpose: publish markdown to the wiki API
- Key rule: return `shareUrl`, not `url`

# Source
- Repo path: `skills/SKILL.md`
```

### B. Appending to a Task Log
**Action**: Use `append: true` to avoid reading large history.
**Prompt for self**: "I'll append this status update to the `task-log` instead of overwriting."

### C. Handling Local Images
1. **Upload**: `curl -X POST "https://wiki.david888.com/api/upload" -F "image=@/local/path.png"`
2. **Replace**: Extract the returned URL and replace `/local/path.png` in your markdown.
3. **Publish**: POST the final markdown.

### D. Writing Mermaid and Flow Diagrams
Use fenced code blocks with language `mermaid`. Prefer standard Mermaid syntax and keep node labels plain.

````md
```mermaid
flowchart TD
    A["Start"] --> B{"Need share URL?"}
    B -->|Yes| C["Return shareUrl"]
    B -->|No| D["Keep editing"]
```
````

Practical rules:
- Prefer `flowchart TD` or `flowchart LR` for process diagrams.
- Keep one diagram per code fence.
- Avoid wrapping Mermaid inside HTML blocks.
- Use short node labels when possible, especially for mixed CJK and English text.
- When the user asks for a flowchart, sequence diagram, state diagram, gantt chart, or mindmap, emit Mermaid markdown directly unless they explicitly ask for an image.

> [!CRITICAL]
> **Mermaid Syntax & Lexical Safeguards (Preventing Parser/Render Errors):**
> 1. **ALWAYS wrap node text in double quotes `"`**: Write `NODE["Label Text"]` instead of `NODE[Label Text]`.
> 2. **NEVER put unquoted URL paths or slashes inside node brackets**:
>    - ❌ **BAD**: `PROXY[/api/proxy]` (Mermaid treats `[/` as the start of a parallelogram node shape `[/.../]` and fails with a lexical error when finding `]`).
>    - ✅ **GOOD**: `PROXY["/api/proxy"]`
> 3. **Escape or quote special characters**: Characters like `/`, `\`, `(`, `)`, `[`, `]`, `{`, `}`, `:`, and `|` MUST be inside double quotes `"..."`.
>    - ❌ **BAD**: `CRM[CRM System (V2)]` or `CRM[` (incomplete bracket)
>    - ✅ **GOOD**: `CRM["CRM System (V2)"]`
> 4. **Always ensure brackets are balanced**: Ensure every opening bracket (`[`, `(`, `{`) has its matching closing bracket on the same line before connecting arrows `-->`.

### E. Appearance Settings and Allowed Values
When an agent needs to preserve the reader/editor presentation, use these persisted metadata values:

- `theme`: one of the bundled theme names listed above
- `width`: `100%`, `960px`, `1200px`, or `1440px`
- `shareFont`:
  - Built-in local: `jetbrains` (JetBrains Mono), `maple` (Maple Mono)
  - On-demand Google Fonts CDN: `fira-code`, `google-sans-code`, `geist-mono`, `source-code-pro`, `intel-one-mono`, `lilex`, `atkinson-hyperlegible-mono`, `atkinson-hyperlegible`, `anonymous-pro`
- `previewDevice`: `desktop` or `mobile`
- `publicIndex`: `true` or `false`

Practical guidance:
- Use `width: "100%"` when the user does not specify a reading width.
- Use `shareFont: "jetbrains"` as the default shared-reader font.
- Use `previewDevice: "mobile"` only when the human explicitly wants a phone-oriented preview state saved with the note.
- If you are only publishing content and do not need to control note appearance, you can omit all of these fields.

### F. Writing 2D Presentation Slides (Slidev-Lite 2.0)
Presentation mode is available at `shareUrl + '/present'`.

Authoring rules:
- Use `---` for horizontal slide transitions.
- Use `--` for vertical deep-dive sub-slides (e.g. detailed breakdown of a parent slide).
- Navigation supports 4-way arrow keys (`↑` `↓` `←` `→`), laser pointer (`L`), blackout pause (`B`), fullscreen (`F`), and 2D matrix overview grid (`O`).
- Use YAML frontmatter at the very top of the markdown note to configure transitions and themes:
  ```yaml
  ---
  transition: slide
  theme: claude-canvas
  ---
  ```
- Use `::left::` and `::right::` for a two-column slide layout.
- Use `{v-click}` for progressive reveal items.

Example:

````md
---
transition: fade
---

# Product Architecture Update

---

## High-Level Architecture
- Distributed Cloudflare Workers
- Hybrid D1 Database & KV Storage

--

### Vertical Sub-Slide: D1 Storage Deep-Dive
- 10 version snapshots with rollback
- Anonymous unique view deduplication

---

::left::
## Frontend Features
- Instant Markdown rendering
- 20+ CSS Themes

::right::
```mermaid
flowchart TD
    A["Draft"] --> B["Publish"]
    B --> C["Share Link"]
```
````

### G. Writing Books & Multi-Chapter Manuals (Book Mode & Multi-Article Orchestration)
Any note containing a list of chapter links automatically functions as a **Book Manifest**. Readers can view the collection as a modern dual-pane interactive eBook by appending `/book` to the share link: `shareUrl + '/book'`.

#### G.1 The 4-Step Standard SOP for AI Agents to Build a Multi-Article Book
When a human asks you to create a comprehensive course, tutorial series, documentation handbook, or multi-chapter book:

1. **Step 1: Outline & Chapter Planning**
   - Design a logical module/chapter structure (e.g. Overview, Module 1, Module 2, Advanced Topics, Case Studies).
   - Determine unique, descriptive path slugs for each chapter (e.g. `ts-intro`, `ts-generics`, `ts-decorators`, `ts-handbook-hub`).

2. **Step 2: Iteratively Author & Publish Every Chapter Note**
   - Write and publish each chapter as an independent, fully-formatted markdown note via `write_note` (or `POST /api/<chapter-path>`).
   - Collect each chapter's returned `shareUrl` (or relative share path like `/share/<id>` or direct path `/<path>`).
   - *Tip*: You can freely mix normal Markdown chapters with 2D slide decks (`/share/<id>/present`) inside the book!

3. **Step 3: Author the Book Manifest / Hub Note**
   - Create a central hub note (e.g. `ts-complete-handbook`) containing the master Table of Contents.
   - **Manifest Structure Rules**:
     - Use `# Book Title` (H1) for the main book title.
     - Add a blockquote `> ...` for the book's executive summary, target audience, or reading guide.
     - Use `## Module Title` or `### Section Title` for chapter groupings.
     - Use `- [Chapter Name](/share/<id>)` or `1. [Chapter Name](/<path>)` for chapter links.
     - Use 2-space indentation `- [Sub-Chapter Name](/share/<id>)` for hierarchical nested sub-chapters.

4. **Step 4: Deliver the Interactive Book Reader URL to the User**
   - Take the Hub Note's returned `shareUrl` and append `/book`.
   - **Always return the `/book` link to the human**: `https://wiki.david888.com/share/<hub-share-id>/book`.

#### G.2 Example Book Manifest Note (`ts-complete-handbook`)

````md
# 📘 TypeScript 現代全端實戰手冊 (TypeScript Modern Fullstack Handbook)

> 本書為全端工程師設計，從底層型別推導到分散式架構實戰，涵蓋現代 TypeScript 所有關鍵技術。

## 📖 核心章節目錄 (Table of Contents)

### 第一單元：現代型別核心基礎
- [01. TypeScript 5.x 核心觀念與型別系統概覽](/share/ts-ch01)
- [02. 泛型 (Generics) 與條件型別實戰](/share/ts-ch02)
  - [02-1. 深入 infer 與樣板字面型別 (Template Literal Types)](/share/ts-ch02-infer)
- [03. 型別守衛與斷言技巧](/share/ts-ch03)

### 第二單元：架構模式與簡報
- [04. Clean Architecture 與領域驅動設計](/share/ts-ch04)
- [05. 2D 簡報：分散式系統型別安全架構](/share/ts-ch05/present)

### 第三單元：邊緣運算與 API 整合
- [06. Cloudflare Workers + D1 全端型別共享](/share/ts-ch06)
- [07. WebMCP 與 AI Agent 工具端點開發](/share/ts-ch07)
````

#### G.3 Reader Features Supported in Book Mode (`/book`)
- **Dual-Pane Split Layout**: Left pane displays the hierarchical table of contents with live search filtering; right pane renders the chapter via fast embed (`?embed=1`).
- **Draggable Splitter**: Readers can freely drag the boundary between sidebar and reading pane (180px to 65% width) or double-click to reset.
- **Embedded Slides & Media**: Slides (`/present`), code copy tabs, KaTeX formulas, Mermaid diagrams, and zoomable images all render natively without leaving the book interface.
- **Keyboard Shortcuts**: Readers can press `[` (Previous Chapter) and `]` (Next Chapter) to navigate through the entire book.

### H. Extended Markdown Syntax & Rich Formatting Reference
When authoring content on David888 Wiki, AI agents can leverage these rich formatting syntaxes:

| Syntax Feature | Markdown Syntax Example | Visual & Render Output |
| :--- | :--- | :--- |
| **🖍️ Text Highlighter** | `==highlighted text==` | `<mark class="markdown-highlight">` with soft yellow glow across light/dark themes. |
| **🎨 Custom Text/BG Colors** | `[color=red]red text[/color]`<br>`[bg=yellow]yellow bg[/bg]`<br>`[color=#3b82f6 bg=#eff6ff]badge[/color]` | Custom font and background colors with sanitized Hex, RGB, and CSS color names. |
| **🔢 Code Block Line Numbers** | ```` ```js=1 ```` (start from line 1)<br>```` ```js=10 ```` (start from line 10) | Generates non-selectable line numbers gutter on the left of code fences. |
| **📑 Code Block Title Tabs** | ```` ```js [app.js] ````<br>```` ```js=1 [server.mjs] ```` | Renders filename tab header with language badge and one-click copy button. |
| **💬 GitHub Alerts** | `> [!NOTE]` / `> [!TIP]`<br>`> [!IMPORTANT]` / `> [!WARNING]`<br>`> [!CAUTION]` | Styled callout boxes with icons and theme-adaptive border and background. |
| **📝 Standard Footnotes** | `Text with note[^1]`<br>`[^1]: Footnote text` | Numbered footnote with glassmorphic hover card popover and smooth scroll. |
| **📝 Inline Footnotes** | `Text with ^[inline note text]` | Pandoc/HackMD inline footnotes, auto-numbered with bottom definition list. |
| **🎓 Pandoc Citations** | `[@smith04]`, `[@doe2023, p. 42]` | Hover popover cards with academic citation details (APA, IEEE, BibTeX, MLA). |
| **📊 Tables** | `\| Col 1 \| Col 2 \|`<br>`\| --- \| --- \|`<br>`\| Val 1 \| Val 2 \|` | Formatted responsive tables (auto-converts from copied Excel/Google Sheets). |
| **📑 Table of Contents** | `[TOC]` (on its own line) | Generates interactive, smooth-scrolling nested TOC navigation tree. |
| **🔤 Multi-Column Layouts** | `<div class="two-column-layout">...</div>`<br>`<div class="three-column-layout">...</div>` | Academic paper / magazine 2-column or 3-column layout (stacks on mobile). |

### H.1 Multi-Column Layouts (Academic & Magazine Layout)
For research papers, executive briefings, feature comparisons, or bilingual side-by-side text, wrap content inside `<div class="two-column-layout">` or `<div class="three-column-layout">`. Sections are automatically partitioned by the child headings (e.g. `###`):

````html
<div class="two-column-layout">

### 1. Traditional Architecture
- Monolithic backend servers
- Centralized database bottlenecks
- High regional latency

### 2. Modern Edge Architecture
- Distributed Cloudflare Workers
- Hybrid D1 database + KV caching
- Sub-50ms global latency

</div>
````

For three parallel columns:
````html
<div class="three-column-layout">

### 🚀 Speed
Edge computing delivers instant response times worldwide.

### 🛡️ Reliability
Multi-tier failover and distributed snapshots prevent downtime.

### 🔌 Extensibility
Native MCP, WebMCP, and REST APIs for full AI agent integration.

</div>
````

### H.2 Automatic Table of Contents (`[TOC]`)
For comprehensive reports, technical specs, long-form articles, and documentation, **AI agents are strongly encouraged to include `[TOC]`** near the top of the article (right after the title or executive summary):

````md
# 📚 Distributed Systems & Edge Storage Architecture Report

> Executive Summary: An in-depth evaluation of serverless edge storage engines.

[TOC]

## 1. Introduction & Background
...

## 2. Core Architecture
...

### 2.1 Cloudflare Workers Runtime
...

### 2.2 D1 Hybrid Database Storage
...

## 3. Experimental Evaluation
...
````
- Inserting `[TOC]` automatically scans all `#` through `######` headings and builds an accessible `<nav class="markdown-toc">` with nested lists and smooth-scrolling deep anchor links.

### H.3 Academic References & Footnotes (`[^1]` & `^[inline]`)
**AI agents and LLMs are strongly encouraged to actively use footnotes** whenever citing research papers, quoting sources, referencing external GitHub repositories/tools, or adding supplementary annotations:

1. **Standard Footnotes (`[^1]` / `[^key]`)**:
   Use inline references like `[^1]` or `[^voko]` in sentences, and define them at the bottom of the article:
   ````md
   Modern multi-agent systems rely on secure process sandboxing[^1] and distributed channels[^2].

   ---

   ## 8. 參考資源與官方連結

   [^1]: **VOKO 運行時倉庫**：[https://github.com/laoyudashu/voko](https://github.com/laoyudashu/voko)
   [^2]: **Ranxy/laelia 協作平台**：[https://github.com/Ranxy/laelia](https://github.com/Ranxy/laelia)
   ````
2. **Inline Footnotes (`^[inline explanation]`)**:
   Use Pandoc/HackMD inline footnotes directly inside paragraphs:
   ````md
   Edge database storage^[Cloudflare D1 runs SQLite at the edge with automated read replication] ensures global sub-50ms latency.
   ````
   The renderer automatically numbers, extracts, and places them into the bottom footnotes list.
3. **Interactive Reader Experience**:
   - **Glassmorphic Hover Cards**: Readers hovering over footnote numbers see an instant glassmorphic popover preview without losing their reading spot.
   - **Smooth Bidirectional Jump**: Clicking jumps smoothly to the target definition, and clicking `↩` returns directly to the referring text passage.

### H.4 Print-Ready Layouts, Page Breaks & Editable `.pptx` / Motion Slides
When generating formal documents (One-Pagers, Whitepapers, Resumes/CVs, Meeting Minutes) or presentations:

1. **Explicit Page Breaks (`<div class="page-break"></div>`)**:
   - Insert `<div class="page-break"></div>` between major sections when the user requests clean PDF/print pagination. Both Takumi vector PDF export (`/api/pdf/export`) and `@media print` enforce `break-before: page` alongside running headers (`David888 Wiki`), page counters (`Page X of Y` / `counter(page) / counter(pages)`), `break-after: avoid` on headings, `break-inside: avoid` on callouts, tables, diagrams, and column blocks, and `orphans: 3; widows: 3` paragraph hygiene.
2. **Built-in Paper & Slide Templates (`Cmd/Ctrl + Shift + P`)**:
   - Four bilingual templates are available in the editor's Tools Palette: **One-Pager**, **Whitepaper**, **Resume / CV**, **Meeting Minutes**, and **2D Slides Deck**.
3. **Motion Loops & Editable `.pptx` Slides**:
   - Presentation YAML frontmatter supports `transition: fade | slide | convex | zoom | none` and `motionLoop: off | aurora | mesh | orbits` (12-second seamless procedural Canvas backdrops respecting `prefers-reduced-motion`).
   - Use standard `---` (horizontal) and `--` (vertical) separators plus `<!-- layout: cover -->` so presentations can both play live at `/share/<id>/present` and export directly to editable 16:9 PowerPoint (`.pptx`) files.


## Editor Features and Operational Tips

The wiki also includes a browser-based Markdown editor. When helping a user author a note, these features are available:

- **Markdown toolbar**: headings, bold, italic, strikethrough, links, blockquotes, unordered/ordered/task lists, **Inline code**, fenced code blocks, horizontal rules, tables, image insertion, attachment upload, fullscreen editing, Undo / Redo, and AI formatting. Toolbar labels and inserted placeholders follow the selected interface language.
- **Image Insertion & Local OCR**: the toolbar image button, paste, and drag-and-drop support R2 upload or pure client-side PaddleOCR.js (`PP-OCRv6 tiny` default / `PP-OCRv6 small` enhanced ~30 MB toggleable in the Command Palette alongside Auto-OCR on image import, loaded on demand with a serial mutex queue).
- **888box Attachment Uploads**: the toolbar attachment button uploads videos, audio, documents, archives, and generic files to `box.david888.com`, falling back to `box.aiurl.tw` and then `box.glsoft.ai`. The editor inserts `<video>` for videos, `<audio>` for audio, and Markdown links for files. Images remain on the built-in R2 image upload flow.
- **ECharts**: put valid JSON chart options in an `echarts` fenced code block to render an interactive chart in the preview. Keep the fence language exactly `echarts`; malformed JSON cannot be rendered as a chart.

````md
```echarts
{
  "title": { "text": "Traffic sources" },
  "tooltip": { "trigger": "item" },
  "series": [{
    "type": "pie",
    "data": [
      { "value": 1048, "name": "Search" },
      { "value": 735, "name": "Direct" },
      { "value": 580, "name": "Referral" }
    ]
  }]
}
```
````

- **Undo / Redo** tracks typing, toolbar Markdown commands, image insertion, and pasted content. Use the toolbar or the normal `Ctrl/Cmd+Z`, `Ctrl/Cmd+Shift+Z`, and `Ctrl/Cmd+Y` shortcuts.
- **AI formatting** is available in both the top toolbar and the footer. It restructures Markdown while preserving the draft's meaning. AI Edit can rewrite a selected passage or the full note only after the user supplies an explicit instruction.
- **Footer Copy** is beside Markdown Export. It prefers rich HTML and includes Markdown/plain-text fallback for editors such as Notion and Jira, then shows a localized check animation after success.
- **Grouped view controls**: Preview, Layout, and Device are one footer group. Layout switches between side-by-side and stacked panes; Device switches between desktop and mobile preview. The editor defaults to desktop preview (`100%` width), and authors can toggle to mobile preview or stacked layouts anytime.
- **Share links**: links in rendered Markdown on `/share/...` pages open in a new tab with `noopener noreferrer`.
- **Startup tips**: the editor randomly chooses a bilingual tip from `static/data/editor-tips.json` and types it below the Stray Birds placeholder with the same typewriter animation. Future user-facing features that deserve a hint must add one object with `id`, `zh-TW`, and `en-US` fields, then update `README.md` and `CHANGELOG.md`.
- **Admin dashboard**: the route is configured by the runtime `SCN_ADMIN_PATH` binding. The dashboard supports URL/title search, Markdown full-text search, modified-date filters, sortable columns, pagination, URL/public/protected/Sitemap totals, and retained version counts. `views` is a legacy field and may not be available in current data.

## Auth Rules
- **Edit Password (`pw`)**: This is the edit lock. It protects editing.
- **View Password (`vpw`)**: This is the read/view lock. It protects reading and is stronger than the edit lock.
- If a note has `vpw`, readers must authenticate before reading the note/share page.
- If a note only has `pw`, the direct note page can still be readable to visitors, but editing remains locked.
- If only a View Lock exists, its password is the sole owner credential and grants edit access after authentication.
- If both locks exist, the View Lock is read-only and the Edit Lock is required to modify the note, change settings, change locks, restore history, or invoke AI editing.
- For a share page with both locks, a valid `vpw` can read the content but must not be treated as edit authorization.
- For `GET /api/<path>`, if either `pw` or `vpw` is set, provide a password through `Authorization: Bearer <password>` or `?pw=<password>`.
- For API reads, either valid password is sufficient to read protected content; API writes require the edit password or an edit-role session.
- For `POST /api/<path>`, `pw` and `vpw` can be used to set or update those locks as part of the save request.
- In the editor/browser flow, `POST /:path/pw` can also update locks with JSON `{ "passwd": "...", "type": "edit" }` or `{ "passwd": "...", "type": "view" }` after edit-session authentication.
- If you get a **401/403**, ask the user: "This page is protected, please provide the password."

## Troubleshooting
- **Error 1101**: A server-side exception occurred. I have added logging; check the returned JSON `msg` for the stack trace or error details.
- **500 on a very long article/context dump**: Treat this as a payload-size or backend-runtime risk, even if auth is correct. The pragmatic fallback is to publish a concise summary plus the original file path/URL instead of embedding the entire long source document.
- **Markdown with lots of quotes / backslashes / code fences keeps failing in curl**: Prefer `Content-Type: text/markdown` with `--data-binary @file.md`, or multipart `-F "file=@file.md"`, instead of wrapping the full markdown inside JSON.
- **I fetched a share page and only got full HTML**: Retry with `Accept: text/markdown`. For public reads, prefer `GET /share/<id>` or `GET /<path>` with that header instead of parsing rendered DOM output.
- **The URL is always the same / IP Restriction?**: No! The `url` field is the *permanent edit link* for that path. If you see the same URL, it means you successfully updated the same page. This is NOT an IP block. **Always check the `shareUrl` for the unique view link.**
- **Missing `shareUrl`**: Ensure you are looking at the `.data.shareUrl` field in the JSON response.
- **Need a slideshow link?**: If the page is slide-oriented, derive it from `shareUrl + '/present'`. For a specific slide, append a Reveal hash like `#/2`.

