# StateDock AI Agent Auto-Setup Guide

> **Audience**: AI Coding Agents (Claude Code, Cursor, Codex, Google Antigravity, Windsurf, Cline, Roo Code, Aider, etc.).
> **Objective**: Autonomously inspect your host environment, download the StateDock skill, configure the MCP connection with the user's token, bind the local repository, and adhere to the StateDock runtime protocol.

---

## 1. Context & Purpose

StateDock is an append-only goal and context ledger for AI Agents and humans. It maintains long-term project memory across sessions:

- **Human sees**: Concise high-level goals, discussions, decisions, and verified outcomes.
- **Agent gets**: Single-call project resume (`resume_project`), atomic queue claim (`claim_next_task`), blocker alerts (`pause_task`), and structured handoffs (`submit_handoff`).

When a user provides you with this guide and their StateDock Token (starts with `sdm_`), your goal is to set up everything automatically so the user does not need to manually configure config files.

---

## 2. Obtain Parameters

1. **StateDock Online Endpoint**: `https://statedock.dev/mcp`
2. **User Token**: A personal access token starting with `sdm_` (generated at `https://app.statedock.dev` under Settings / MCP Tokens).
   - _If the user did not provide a token in their message, ask them_:
     > "Please provide your StateDock Access Token (format: `sdm_...`, generated at https://app.statedock.dev under Settings / MCP Tokens), and I will complete the configuration and bind this project for you." / “请提供你在 StateDock 生成的 MCP 凭证 Token（格式形如 `sdm_...`，可在 https://app.statedock.dev 个人设置中生成），我将自动为您完成全部配置与项目绑定。”

---

---

## 3. Install StateDock Skill & Enforce Workspace Rules

Download the authoritative skill definition from `https://statedock.dev/skill.md` and place it according to your host environment.

### 3.1 Download Skill Definition

Run in workspace root:

```bash
mkdir -p skills/statedock && curl -fsSL https://statedock.dev/skill.md -o skills/statedock/SKILL.md
```

_(For Google Antigravity, also save to `~/.gemini/config/skills/statedock/SKILL.md` if writable)_.

### 3.2 ⚠️ MANDATORY: Inject Session Rules into Workspace Config

> **Why this is strictly required**: MCP is a passive tool server. The MCP protocol **cannot** autonomously trigger execution or inject context when a new chat session starts. Without workspace rules, the model will not remember to call StateDock when receiving new tasks.
> **You MUST inspect and append/create the StateDock lifecycle rules into the repository's active rule file during this setup step!**

#### Detect and update the appropriate rule file:

- **Claude Code**: Update `<workspace>/CLAUDE.md`
- **Cursor**: Update `<workspace>/.cursorrules` or `<workspace>/.cursor/rules/statedock.mdc`
- **Google Antigravity**: Update `<workspace>/AGENTS.md`
- **Windsurf**: Update `<workspace>/.windsurfrules`
- **Cline / Roo Code**: Update `<workspace>/.clinerules`
- **Fallback**: If no rule file exists, create both `<workspace>/AGENTS.md` and `<workspace>/CLAUDE.md`.

#### Mandatory Rule Content to Inject:

```markdown
# StateDock Project Workflow (MANDATORY)

1. **Session Startup (Automatic Context Recovery)**:
   At the start of ANY new session or when entering this project, immediately call MCP `resume_project(project)` to restore goals, active tasks, blockers, and recent handoffs. Do NOT wait for the human to remind you to create or resume a session.

2. **Incoming Execution Requests**:
   When the user asks to implement, modify, fix, refactor, or build any user-visible feature, IMMEDIATELY call `create_plan(status: 'WORKING')` to lock the task in StateDock BEFORE editing any code. Do not ask "should I start?".

3. **Preflight the Task and Workspace**:
   Before changing an existing task, read its exact record and verify its project, status, assigned identity, and claim owner. Use the current body, decisions, summary, relevant recent notes or feedback, and attachments as context. Inspect only relevant history, code, documentation, Git status/diffs, working directory, tools, and permissions needed to resolve uncertainties. Handle routine choices yourself, preserve unrelated changes, and do not ask the user to verify facts you can check. Ask only for a real conflict, missing authorization/access, or a decision only the user can make. Record important findings on the original task using existing fields; do not add management fields or expand scope into UI, database, approvals, or orchestration.

4. **Ideas & Discussions**:
   When the user discusses future ideas or topics without asking for immediate implementation, save to `create_plan(status: 'PLAN')`.

5. **Task Completion & Handoff**:
   After completing code changes and verifying them with tests, call `submit_handoff(reference, { changes, verification, nextSteps, codeReference? })` to record a structured handoff summary and mark the task DONE. When a Git repository exists, capture its full HEAD SHA, branch (or null for detached HEAD), and whether the working tree is clean or dirty, including staged, unstaged, and untracked changes. Optionally include a safe repository identifier and HTTPS commit/PR URL. A dirty HEAD may predate uncommitted changes; never claim otherwise. Omit this optional field outside Git repositories. Do not store diffs or treat the reference as verification or independent review evidence.

6. **Blockers & Decisions**:
   If blocked or awaiting human decision, call `pause_task(reference, reason)` to mark WAITING and notify the user.

7. **Language Alignment (Strict Rule)**:
   Always record all tasks (title, body, handoff, blocker reason, summary) in the same language you use to converse with and report to the user (e.g. Chinese if communicating in Chinese, English if in English).
```

---

## 4. Configure MCP Connection

Configure the `statedock` MCP server with the user's token (`<YOUR_TOKEN>`).

### Standard Streamable HTTP / SSE Config (Cursor, Claude Desktop, etc.)

If your client supports Streamable HTTP / SSE MCP natively:

```json
{
  "mcpServers": {
    "statedock": {
      "url": "https://statedock.dev/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_TOKEN>"
      }
    }
  }
}
```

- **Cursor Configuration File**:
  - Project level: `<workspace>/.cursor/mcp.json`
  - Global level: `~/.cursor/mcp.json`
- **Claude Desktop Configuration File**:
  - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  - Windows: `%APPDATA%\Claude\claude_desktop_config.json`

---

### Command Bridge Config (using `mcp-remote` for stdio hosts)

If your client runs MCP via stdio commands (e.g. Claude Code CLI, Codex CLI, or older clients):

```json
{
  "mcpServers": {
    "statedock": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://statedock.dev/mcp",
        "--header",
        "Authorization: Bearer <YOUR_TOKEN>"
      ]
    }
  }
}
```

- **Claude Code CLI command**:

  ```bash
  claude mcp add statedock -- npx -y mcp-remote https://statedock.dev/mcp --header "Authorization: Bearer <YOUR_TOKEN>"
  ```

- **Codex CLI command**:
  ```bash
  codex mcp add statedock -- npx -y mcp-remote https://statedock.dev/mcp --header "Authorization: Bearer <YOUR_TOKEN>"
  ```
  Or in `<workspace>/.codex/config.toml`:
  ```toml
  [mcp_servers.statedock]
  command = "npx"
  args = ["-y", "mcp-remote", "https://statedock.dev/mcp", "--header", "Authorization: Bearer <YOUR_TOKEN>"]
  ```

---

## 5. Verify & Bind Local Repository

After the MCP connection is established:

1. **Verify Connectivity**:
   Call MCP tool `list_projects` to confirm the server responds.

2. **Bind Project to Workspace**:
   - Check if an existing project matches your current workspace path (`localPath`).
   - If not found, call `create_project`:
     - `slug`: normalized workspace folder name (e.g. `my-project`).
     - `name`: repository name.
     - `localPath`: absolute directory path of current workspace.
     - `description`: brief description of the project.

3. **Resume Context**:
   Call `resume_project(project)`.
   Confirm project details, active tasks, and handoffs are returned.

4. **Report Back to User**:
   Notify the user in their language (English default, Chinese if prompt was Chinese):
   > "✅ StateDock is successfully connected and configured!
   >
   > - Skill definition loaded;
   > - Lifecycle rules injected into workspace rules (`AGENTS.md` / `CLAUDE.md` / `.cursorrules`);
   > - MCP connection verified;
   > - Project bound to StateDock.
   >   Future development goals and handoffs will be recorded automatically." /
   >   “✅ StateDock 已成功配置就绪！
   > - Skill 已下载并生效；
   > - 工作区生命周期规则已注入（`AGENTS.md` / `CLAUDE.md` / `.cursorrules`），后续开启任何新会话或接收任务时，将 100% 自动调用 StateDock 恢复上下文与记录任务；
   > - MCP 连接已连通；
   > - 当前项目已与 StateDock 绑定。
   >   后续开发目标将自动同步与记录。”

---

## 6. Runtime Protocol Quick Reference

During day-to-day collaboration, strictly follow these 6 core MCP actions:

| Trigger                                          | MCP Action                                                        | Description                                                                                                                                             |
| ------------------------------------------------ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **New Session / 新会话启动**                     | `resume_project`                                                  | Atomic recovery of goals, active tasks, blockers, and recent handoffs. / 恢复项目上下文与阻塞。                                                         |
| **User Implementation Request / 新增或修复目标** | `create_plan(..., status: "WORKING")`                             | Lock task immediately before editing code. Never ask "should I start?". / 立即建项执行。                                                                |
| **Ideas & Backlog / 待讨论与暂存**               | `create_plan(..., status: "PLAN")`                                | Preserve ideas and architectural trade-offs without unprompted execution. / 存入待办池。                                                                |
| **Autonomous Queue Execution / 队列自动执行**    | `claim_next_task`                                                 | Atomically claim the next READY task; PLAN ideas are not executable. Lease tasks without multi-agent race conditions. / 只认领 READY，PLAN 保留待讨论。 |
| **Blockers & Decisions / 遇到阻碍或技术决策**    | `pause_task(reference, reason)`                                   | Mark WAITING, flag blocker reason, and trigger instant outbound notification. / 挂起并触发即时通知。                                                    |
| **Completion & Tests / 开发与测试验证完成**      | `submit_handoff(reference, { changes, verification, nextSteps, codeReference? })` | Record the 3-part summary and optional structured Git reference, then mark DONE. / 提交三段式结果与可选 Git 版本引用。 |

Keep human-facing summaries concise (what was changed, verification evidence, next steps) and omit code diffs or line numbers.

## Planned 与 Ready

PLAN / Planned 是待讨论或暂存的想法。READY / Ready 表示用户已明确允许执行。PWA 可手动切换；Telegram、Discord 与 Inbox 默认创建 PLAN，归类到项目不会自动变成 READY。用户要求依次执行某项目 Ready 任务时，明确指定 project，调用 claim_next_task 串行认领、执行及交付，队列为空即停止；遇阻暂停并通知。任务状态不会自动唤醒 Agent，本阶段没有定时调度器。

## 执行前自主核对

开始已有任务前，Agent 应先读取该任务当前记录，核对项目、状态、分配身份和领取者，并阅读目标、最近决定、摘要及相关讨论或反馈；有附件时也要读取。随后只恢复完成这项工作所需的项目上下文。遇到不确定处，先自行检查相关历史、代码、文档、Git 状态与相关差异、当前工作目录及可用工具和权限。能依据目标和既有决定解决的常规歧义，由 Agent 自行处理；保留无关的本地改动，不要求用户代查可直接验证的事实。

只有任务与决定确有冲突、缺少必要授权或访问权限，或必须由用户选择时才询问。身份不匹配或任务由另一个 Agent 执行时，不得领取或覆盖；应说明情况并等待重新分配。重要发现写回原任务的现有讨论或活动记录，不新增管理字段，也不扩展成 UI、数据库、审批或编排功能。Ready 队列任务在首次写入前，先核对实例、项目绑定和当前身份，再通过 `claim_next_task` 原子领取。

## Ready 队列执行契约

只有用户明确要求执行某项目 Ready 队列，或授权此项目在 Agent 空闲时领取 Ready，才进入队列执行模式。用户授权空闲领取并不会自动创建调度器，也不保证宿主结束当前运行后能自行唤醒；支持远程指令或已授权定时任务的宿主可以复用相同协议。

1. 在任何写入前，调用当前连接的 `get_instance_info`，验证实例 publicOrigin/mcpUrl；核对项目 UUID、slug 与本机仓库绑定。不能只按项目名称猜测，不能回退到其他实例。
2. 每次 `claim_next_task(project: UUID)` 只原子领取一条 READY，PLAN 保留待讨论。任务目标、决定、反馈和附件提供执行依据，不依赖历史聊天上下文，不扩大授权。
3. 认领后核对任务项目，在已绑定仓库执行并完成必要验证。成功后 `submit_handoff` 写入真实结果，再认领下一条。不得接管其他 Agent 的 WORKING。
4. 需求不明确或受阻时 `pause_task` 标为 WAITING、说明需要补充的信息，暂停队列。无 Ready 时安静结束，不自行创建轮询、提醒或定时任务。
5. 用户明确给出固定编号批次时仍只执行那个批次，不能替换为动态 Ready 队列。未授权的发布、删除及外部通信仍需要遵循宿主权限规则。

## Agent Identities and assigned Ready tasks

Create identities to assign tasks and group MCP connections. An identity doesn't create or launch an AI agent. `Codex-Mac` and `Codex-Cloud` can be separate identities even when both use Codex. Multiple tokens bound to one identity share its assigned task queue.

1. Open **MCP Connections → Agent Identities**. Enter a name and click **Add Identity**. The **Identities** list shows existing identities; adding one does not select it for a new token.
2. For a new token, choose **Assign to identity**, then **Create Token**. For an existing token, change its **Identity** selector. The existing token value stays valid; its binding takes effect on subsequent MCP requests without replacing the token or updating the skill. The token's display name does not determine its identity.
3. For OAuth, select an identity on the consent page. To change an existing OAuth connection's identity, reconnect and authorize it again. Independent authorizations can coexist even when clients share a client ID and callback; each keeps its own identity and scopes. A host may need a fresh chat or refreshed tool connection to discover changes.
4. Open a task, choose **Assigned Identity**, save it, and set it to **Ready**. Use the task list's identity filter to review each queue. For a task already **Working**, explicitly return it to **Ready** before reassigning it.
5. Tell the connected agent to execute its own Ready tasks. `list_ready_tasks(project, mode="mine")` and `claim_next_task(project, mode="mine")` only use the identity verified from its credentials. Other identities' tasks and **Unassigned** tasks are excluded. Only use `mode="unassigned"` when the user explicitly authorizes that queue. Claiming is atomic; clients sharing an identity cannot claim the same task twice.

**Unbound** means a connection has no identity; **Unassigned** means a task has no assigned identity. Unbound connections cannot claim remote Ready queues. StateDock records and assigns work; setting Ready does not wake or launch an agent.

Delete an identity with the delete button in **Identities**. Deletion is blocked while it has Working tasks. Otherwise, bound tokens become Unbound and assignments on Planned, Ready and Waiting tasks are cleared; completed task history is retained. Move or complete active work before deleting its identity.

To refresh an agent's instructions, ask it to download the latest `/skill.md` from **the same connected StateDock instance** and update its installed StateDock skill. Then ask it to call `get_instance_info` and report `publicOrigin`, `mcpUrl`, `agentId` and `agentName`; match `agentId` and `agentName` to the identity in MCP Connections. It must not infer its identity from its software name or token label. Remote Cloudflare MCP uses identity queues; the standalone local SQLite adapter keeps its local queue behavior.
