---
name: studio-project-doc-context
description: Read project document content from Studio AI platform — list documents, browse chapters, and retrieve content as LLM context. Use when you need document specifications (PRD, BRD, design docs) as AI context for code generation or SDD workflows.
metadata:
  version: "0.1.21"
---

## Prerequisites

两种使用环境，鉴权方式不同：

### A. 外部 AI IDE（Cursor / Claude Code 等）

- 用户先跑过 `studio-cli login`（token 落到 `~/.studio-ai/config.json`）
- 之后 `studio-cli` 自动读本地配置鉴权

### B. Studio AI Copilot 会话内（无需用户手动 login）

平台已经在会话工作目录写好 `.studio/runtime-context.json`（schema v2），含完整上下文：

```json
{
  "version": 2,
  "sessionId": "...",
  "currentUserId": "...",
  "apiToken": "eyJhbGc...",         // Sa-Token JWT
  "apiBase": "http://localhost:8080",
  "projectInstanceId": "...",        // 直接当 --project-id 用
  "documentInstanceId": "...",       // 直接当 --doc-id 用
  "entityInstanceId": "...",
  "configUnitId": "...",
  "nodeId": "..."
}
```

**所有需要的 ID 都在这里**——无需先调 `list` 查 projectId。

skill 脚本/LLM 跑 cli 命令时这样写（一次性读出所有需要字段）：

```bash
CTX=.studio/runtime-context.json
TOKEN=$(jq -r '.apiToken' "$CTX")
API_BASE=$(jq -r '.apiBase' "$CTX")
PID=$(jq -r '.projectInstanceId' "$CTX")
DID=$(jq -r '.documentInstanceId' "$CTX")

STUDIO_API_KEY="$TOKEN" STUDIO_API_BASE="$API_BASE" \
  studio-cli project-docs export-context \
    --project-id "$PID" --doc-id "$DID" --output ./aiko-studio --force
```

cli `requireConfig()` 优先读 `STUDIO_API_KEY` env，自动选 Authorization header（JWT 形态识别），跳过本地 `~/.studio-ai/config.json`。（特性自 0.1.8 起，当前 latest 0.1.11+ 始终具备。）

**单文档读取场景**用 `read` 命令（不需要导出包）：

```bash
studio-cli project-docs read --project-id "$PID" --doc-id "$DID"
```

**编码模式 session**（用户没绑文档）：runtime-context.json 中 `documentInstanceId` 等会是空字符串，此时让用户先选文档再调本 skill。

## Core Workflow

### 1. List documents (with document type)

```bash
studio-cli project-docs list --project-id <pid> --format json
```

Returns `data.items[]` with `{ id, name, docType, status, configUnitId }`.
`docType` is the human-readable type name (e.g. "PRD", "BRD", "设计规范").

### 2. Browse chapter tree (from document instance, including dynamic chapters)

```bash
studio-cli project-docs chapters --project-id <pid> --doc-id <did> --format json
```

Returns `data.chapters[]` as a **nested tree**:

```json
[
  { "id": "...", "title": "1. 概述" },
  {
    "id": "...", "title": "2. 功能详细规格", "dynamic": true,
    "children": [
      {
        "id": "...", "title": "车辆入场登记", "dynamic": true,
        "children": [
          { "id": "...", "title": "功能规格", "dynamic": true,
            "children": [
              { "id": "...", "title": "车辆信息录入", "dynamic": true }
            ]
          }
        ]
      }
    ]
  }
]
```

- Leaf nodes have no `children` key
- `dynamic: true` only present on dynamically expanded chapters
- This list is extracted from the document **instance** (not the template definition), so it includes dynamically expanded chapters

Terminal output uses tree-style formatting (`├─ / └─`).

### 3. Read content — default Markdown output

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did>
studio-cli project-docs read --project-id <pid> --doc-id <did> --chapter-id <cid>
```

Default output is **clean Markdown** with `#` headings reflecting chapter hierarchy. Large content (交互原型) is replaced with a retrieval command:

```markdown
#### 车辆信息录入

##### 功能流程图

```plantuml
@startuml
...full plantuml content inline...
@enduml
```

##### 交互原型

> 内容较大，已省略。需要查看时请执行：
> `studio-cli project-docs read --project-id xxx --doc-id xxx --chapter-id xxx --binding 交互原型`

##### 前置条件

...content inline...
```

When `--chapter-id` is omitted, returns all sections of the entire document.

### 4. Retrieve specific binding content (e.g. prototype HTML)

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did> --chapter-id <cid> --binding 交互原型
```

Returns **only** the raw content of the specified binding (e.g. the full HTML prototype), nothing else. Use this when you see a retrieval command placeholder in the Markdown output.

### 5. Read content by chapter title

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did> --chapter-title "1. 产品架构"
```

Resolves the title to a chapter ID automatically. Returns `CHAPTER_NOT_FOUND` or `CHAPTER_AMBIGUOUS` error with candidates if resolution fails.

### 6. Read as clean Markdown for LLM (explicit flag)

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did> --context-only
```

`--context-only` is equivalent to the default terminal output — clean Markdown text with no JSON envelope. Useful for piping to other tools.

### 7. JSON output

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did> --format json
```

Returns the full JSON envelope with `data.sections[]` containing structured bindings data.

### 8. JSON with embedded context text

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did> --for-context --format json
```

Returns the full JSON envelope with an additional `data.contextText` field containing the clean Markdown.

## Recommended Workflow

### Step-by-step discovery

```bash
# 1. Find your project's documents
studio-cli project-docs list --project-id <pid> --format json

# 2. Pick a document, see its chapter tree
studio-cli project-docs chapters --project-id <pid> --doc-id <did> --format json

# 3. Read a specific chapter as Markdown
studio-cli project-docs read --project-id <pid> --doc-id <did> --chapter-id <cid>

# 4. If you need a prototype, fetch it
studio-cli project-docs read --project-id <pid> --doc-id <did> --chapter-id <cid> --binding 交互原型

# 5. Or read the entire document
studio-cli project-docs read --project-id <pid> --doc-id <did>
```

### Quick full-document read

```bash
studio-cli project-docs read --project-id <pid> --doc-id <did>
```

### Export PRD context package for AI IDE development

```bash
studio-cli project-docs export-context --project-id <pid> --doc-id <prd-did>
```

This writes a local `.aiko-studio/` context package:

- `.aiko-studio/AGENTS.md` — cross-agent reading and planning protocol
- `.aiko-studio/spec.md` — primary entry point for implementation work
- `.aiko-studio/tasks.md` — PRD-derived task map for choosing one implementation scope
- `.aiko-studio/implementation-map.md` — maps tasks to PRD sections, prerequisites, and assets
- `.aiko-studio/llms.txt` — short LLM-readable index
- `.aiko-studio/llms-full.md` — expanded context for large-window models
- `.aiko-studio/context/<pid>/<did>/manifest.json` — machine-readable index
- `.aiko-studio/context/<pid>/<did>/relationships.json` — document / section / asset graph
- `.aiko-studio/context/<pid>/<did>/assets/prototypes/` — prototype HTML assets

AI should read `.aiko-studio/AGENTS.md` first, choose one task from `tasks.md`, then use `implementation-map.md` and `manifest.json` to locate only the relevant PRD sections, prerequisite summaries, and prototype files.

## Unified Output Envelope (JSON mode)

All commands return:

```json
{
  "ok": true,
  "data": { ... },
  "meta": { "projectId": "...", "docId": "..." },
  "error": null
}
```

## Error Codes

| Code | Meaning |
|------|---------|
| `CHAPTER_NOT_FOUND` | No chapter matched the given title; `candidates` lists available options |
| `CHAPTER_AMBIGUOUS` | Multiple chapters matched the given title; `candidates` lists the matches |
| `BINDING_NOT_FOUND` | No binding matched the given label in the chapter |
| `INVALID_ARGUMENT` | Required argument missing |

## Integration with SDD

For Spec-Driven Development workflows:
1. Use `list` to find the relevant document
2. Use `read` to get the full spec or specific chapters as Markdown
3. The clean Markdown output can be directly used as system context
4. Use `--binding` to fetch large content (prototypes) on demand
