# Investibook — Development Backlog

> Last updated: 2026-04-13
> Granularity: ~2 person-days per task. Grouped by category, sorted by priority within each category.

---

## Milestone #1

### Production Integration & Continuous Deployment

- [x] **CI/CD Pipeline** — GitHub Actions for automated testing + build + deployment, continuous deployment to EKS
- [x] **K8s Deployment** — Finalize `deployment/kustomize/` manifests; verify Ingress routing (ALB), ConfigMap injection of `ACP_AGENT_TYPE` / `ACP_MODEL` / `ACP_AGENT_BIN`; leave frontend `NEXT_PUBLIC_API_URL` empty in production (use relative paths)
- [x] **EBS Persistent Volume Mount** — Configure `data-pvc.yaml` to mount 100G EBS to backend pod's `DATA_DIR` (`/data`); ensure `data/db/` and `data/workspaces/` directories persist across pod restarts

### Authentication & User System

- [x] **Email Login Page (Frontend)** — Create `app/login/page.tsx`: email input + login button; call `POST /api/auth/login {email}`; on success, write `token` / `email` to `localStorage` (`investibook_token` / `investibook_email`); redirect all pages to `/login` when not authenticated
- [x] **Auth API (Backend)** — Implement `POST /api/auth/login` (get-or-create user, generate Bearer token, write to `user_sessions` table), `GET /api/auth/me`, `POST /api/auth/logout`; `get_current_user` FastAPI dependency (Bearer token → user row) for all protected routes
- [x] **Frontend Full Migration to fetchWithAuth** — Replace all bare `fetch()` calls with `fetchWithAuth()` from `lib/auth.ts`; ensure 401 → auto-clear credentials + redirect to `/login`; update `lib/workspaces.ts`, `lib/workspace.tsx`, ChatPanel, SourcesPanel, and all other request-making components
- [ ] **OAuth / SSO (Auth0 Google)** — Replace email login with OAuth; integrate Auth0; backend `get_current_user` FastAPI dependency already has OIDC swap interface reserved, switch to OIDC JWT validation; change frontend `/login` page to "Sign in with Google" button; remove email login logic

### Workspace Sharing & Collaboration

- [x] **Workspace Read-Only Sharing** — Implement `PUT /api/workspaces/{id}/share {is_shared: bool}`; add Share toggle (teal icon) and copy-link button to frontend Workspace Header; when non-owner opens shared link: disable `ChatPanel` input, hide "+" button in Sources panel, prevent Artifact deletion in Studio

### Backend Persistence

- [x] **SQLite Schema + Initialization** — Implement table creation in `backend/main.py` (or extract to `backend/db.py`): `users`, `user_sessions`, `workspaces`, `workspace_sources`, `workspace_artifacts`, `workspace_messages`, `workspace_sessions`; auto `CREATE TABLE IF NOT EXISTS` at app startup
- [x] **Workspace CRUD REST API** — Implement `GET/POST /api/workspaces`, `GET/PUT/DELETE /api/workspaces/{id}`; filter all queries by `user_id`; `require_workspace_owner()` middleware to intercept non-owner requests and return 403; migrate existing `setup-example` logic to new schema
- [x] **Sources & Artifacts & Messages REST API** — Implement `GET/PUT /api/workspace/{id}/sources`, `/artifacts`, `/messages`, `/session`; use JSON blob storage (`workspace_sources` etc. tables); `WorkspaceProvider` loads/saves from API, replacing all `localStorage` reads/writes
- [x] **Workspace Environment Variable API** — `GET/PUT /api/workspace/{id}/env`; each workspace has a `.env` file in its session directory readable and writable via dedicated API endpoints; `POST /api/workspaces` auto-creates the `.env` file so agents can read configuration before any manual setup

### Source Integration

- [x] **Backend Jira Issue Sync Module** — `backend/alert_sync.py`: `async def prepare_alert_source(alert_id, workspace_id)`; pull three files from S3 and write to `data/workspaces/{workspace-id}/`; implement `POST /api/sources/prepare` returning 202 + `task_id`; `GET /api/sources/prepare/{task_id}` to query progress (`processing` / `completed` / `error`)
- [x] **Frontend Jira Issue → Sync → Report Automation** — After `AddSourceModal` submission, call `POST /api/sources/prepare`; Jira issue `SourceCard` shows spinner; poll `GET /api/sources/prepare/{task_id}` (2s interval); on success: update Source status to `ready`, auto-add `cluster_meta` Source, auto-create Report + Anomaly Artifact, refresh file tree
- [x] **Source Status Indicator UI** — `SourceCard` supports `loading` / `ready` / `error` tri-state; `loading` shows spinner + "Preparing data…"; `ready` shows green ✓; `error` shows red ⚠ + error message; `Source` interface adds `status?: 'loading' | 'ready' | 'error'` and `statusMessage?` fields
- [x] **StudioPanel Dynamic Report Loading** — Dynamically load InsightReport data from `GET /api/workspace/{id}/file-content?path=insight.json`, replacing hardcoded `data/example-workspace/insight.json`; similarly load `diagnostic_package.json` for AnomaliesPanel; support Artifact data from API
- [x] **Alert Comment Summary** — After preparing an alert source, an AI-generated summary of the alert's comments is automatically surfaced in the workspace UI
- [x] **Jira Issue Source Unification** — The `alert` source type has been fully renamed and consolidated into `jira_issue` across backend API, CLI, and all frontend components. Source preparer now supports three Jira issue prefixes: `O11Y-*` (observability alerts), `TCOC-*` (TiDB Cloud Oncall tickets), `TCID-*` (TiDB Cloud Service tickets). UTF-8 encoding fixed for issue metadata output. ([#231], [#234], [#236], [#237], [#238], [#239], [#249])
- [ ] **OpenCode/Agent Created File Tracking** — Files created by the ACP Agent (e.g., diagnostic reports, analysis results) auto-add a specific prefix or suffix (e.g., `agent_`); Workspace file tree supports filtering to show these files; Studio panel provides a dedicated view for Agent-generated files, helping users distinguish and manage them
- [ ] Add delete functionality for Jira Issue Sources, including support for deletion during Preparing state

### MCP Integration

> **Architecture note (2026-04)**: Clinic / O11Y data access has been fully migrated to the `clinic-api` skill (curl-based Clinic REST API calls). The Clinic MCP server is disabled in `opencode.json.template`. Remaining active MCP servers: `jira` (Jira Issue read), `devops` (DevOps Portal), `resource-worker-mcp` (analysis reports).

- [x] ~~**Backend MCP Configuration Infrastructure**~~ — Obsolete. Clinic/O11Y data access is handled by the `clinic-api` skill. Jira/DevOps/Resource Worker MCP use static config in `opencode.json.template`.
- [x] ~~**O11Y / Clinic / Ops Portal MCP Integration**~~ — Obsolete. O11Y and Clinic are accessed via the `clinic-api` skill (PromQL metrics, Loki logs, Data Proxy SQL queries).
- [x] **Jira MCP Integration** — Jira MCP server (`aiops-mcp-demo/jira`) ships inside Investibook with `jira_get_issue`, `jira_get_alert_info`, `jira_add_comment`, `jira_get_comments` tools; runs in stdio mode; auto-configured when `jira` connector is active in workspace. ([#251])
- [ ] **Resource Worker MCP Integration** — Connect to Resource Worker MCP's `analyze_alert` tool (generates analysis reports); write `resource_worker_insight.json` to workspace file system; frontend StudioPanel supports rendering resource worker generated reports
- [x] **Grafana Screenshot MCP Integration** — Unified `diagnostic_screenshot` MCP tool implemented; agent captures Grafana dashboard panels as images; results stream back as `image` SSE events in the chat panel
- [x] ~~**Per-User Automatic MCP Token Mapping**~~ — Obsolete. Clinic API Key is auto-injected via `SKILL_CLINIC_API_KEY` environment variable at workspace creation.

### ACP Session & Chat Lifecycle & OpenCode Configuration

- [x] **ACP Session Persistence & Recovery** — Implement `GET/PUT /api/workspace/{id}/session` (store ACP `session_id` in `workspace_sessions` table); recover existing sessions after backend pod restart; ChatPanel loads historical messages from API on mount (migrate current localStorage logic to API)
- [x] **Chat History Backend Persistence** — ChatPanel calls `PUT /api/workspace/{id}/messages` to save to backend after each conversation turn; `loadMessagesFromAPI(workspaceId)` on mount; user can see complete history after Agent reconnection (instead of resetting to WELCOME_MESSAGE)
- [x] **Workspace Lifecycle Management Improvements** — Backend synchronously initializes directory structure and ACP session config when creating a Workspace; clean up backend data when deleting a Workspace (sources, artifacts, messages, session, workspace directory files); sync Workspace name/description updates to backend
- [ ] **OpenCode Session Persistence** — Make state records persistent when Workspace calls OpenCode via ACP, consistent with Workspace lifecycle. Reference: https://agentcommunicationprotocol.dev/core-concepts/stateful-agents. Current implementation has a bug: if the backend pod restarts, users can see chat history in the UI, but the Agent has none of that context — it starts with a completely fresh context.
- [ ] Add confirmation dialog when clearing history, noting that it will delete the OpenCode Session Context. (Or provide two entry points: one that only clears UI chat history, and one that also creates a new OpenCode session.)

### UI/UX Improvements

#### Mobile

- [x] Mobile support

#### General UI

- [x] **Logo and App Icons** — Application logo and favicon added to the web UI
- [x] **Workspace Header Simplification** — Removed clutter from the top bar; simplified button layout and typography for a cleaner three-column workspace view
- [x] **Ranking Page** — `/ranking` page surfacing the most effective skills and tools as a leaderboard; includes weekly trend chart, skill leaderboard, tool usage table, and trending techniques cards; currently backed by mock data. ([#243])

#### Agent Observability

- [x] **OpenCode Telemetry Plugin** — `ya-opencode-telemetry` OpenCode plugin hooks into every tool call, logging name, type, MCP server, session, duration, and success to `.opencode/statistics.db` per workspace; zero impact on agent behavior. ([#233])
- [x] **Admin Stats Dashboard** — `/admin/stats` aggregates `statistics.db` across all workspaces (total calls, breakdown by type, top skills/MCP tools/built-ins) via `GET /api/stats/summary`. ([#233])

### investibook-cli

> Design doc: [docs/INVESTIBOOK_CLI.md](INVESTIBOOK_CLI.md)

investibook-cli turns Investibook into an OpenClaw-invokable tool and a scriptable CLI for on-call engineers. All commands are thin wrappers over the same REST + SSE API used by the web UI — any `/chat` message from the CLI surfaces instantly in the web UI for co-viewers.

- [x] **CLI Framework & Auth** — Bootstrap `investibook-cli` as a single-binary Go CLI (or `npx investibook`); implement `investibook init --api <url> --email <email>` to store token in `~/.investibook/config.json`; support `INVESTIBOOK_API` / `INVESTIBOOK_TOKEN` / `INVESTIBOOK_WORKSPACE` env vars for scripting
- [x] **`/workspace` Command** — `investibook workspace create/list/use/show`; persist active workspace in `~/.investibook/session.json`; `--workspace <id>` flag on all commands as override
- [x] **`/chat` Command** — `investibook chat "<message>"` and `--interactive` REPL mode; stream Agent response via SSE to stdout (thinking/tool/text rendered in terminal colors); web UI co-viewers see the same messages in real time
- [x] **`/sources` Jira Issue Commands** — `investibook sources add jira-issues <issue-id>` triggers backend preparation pipeline (`POST /api/sources/prepare`), polls for completion with progress indicator; `investibook sources list`; `investibook sources remove <source-id>`
- [ ] (Not planned in Milestone #1) **`/sources` Skill Commands** — `investibook sources add skills <url>` fetches skill definitions from GitHub tree URLs and creates a `skill` source;
- [x] **`/reports` Command** — `investibook reports list`; `investibook reports get <id|latest> [--format json|text]`; renders Studio Artifacts as structured terminal output
- [x] **`/files` Command** — `investibook files list [--filter agent]`; `investibook files get <path>`
- [ ] (Not planned in Milestone #1) **`/files` Write Commands** — `investibook files edit <path>` (opens `$EDITOR`, writes back via `PUT /api/workspace/{id}/file-content`) 
- [ ] (Not planned in Milestone #1) **`/bash` Command** — `investibook bash "<cmd>"` (non-interactive, via `POST /api/workspace/{id}/exec`); `investibook bash --interactive` (WebSocket shell, depends on Pod Terminal Access)
- [x] **OpenClaw Tool Integration** — Publish `investibook-cli` as an MCP tool set (`investibook_create_workspace`, `investibook_add_issue`, `investibook_add_skill`, `investibook_chat`, `investibook_get_report`, `investibook_list_files`, `investibook_bash`); enables OpenClaw autopilot flow: add issue → chat → get report → done
- [x] **API Key Authentication for CLI** — `--api-key` flag and `INVESTIBOOK_API_KEY` env var as an alternative to email login, suitable for scripting and CI environments
- [x] **Cross-Platform Binary Distribution** — GitHub Actions CI builds binaries for `linux/amd64`, `linux/arm64`, `darwin/amd64`, `darwin/arm64` and publishes to S3 on every tagged release (`investibook/cli/v*`)
- [x] **CLI Auto-Update** — On every invocation, silently checks S3 for a newer binary (5 s timeout); if found, atomically replaces itself and re-executes — transparent to the user; `INVESTIBOOK_SKIP_UPDATE=1` disables the check; `BuildTime="0"` in dev builds also skips the check
- [x] **One-Click Install Script** — `cli/install.sh` detects OS/arch, downloads the correct binary from S3, and installs to `~/.local/bin/investibook` with `PATH` configuration
- [x] **CLI Release Workflow Documentation & Automation** — Documented two-mode release system in `docs/CLI_RELEASE.md` (linked release: `investibook/v*` auto-creates `investibook/cli/v*` via GitHub API; standalone: push `investibook/cli/v*` directly); CI creates the CLI tag automatically without requiring a PAT. ([#232])

### Nutshell Skills & Agent Knowledge

- [x] **Nutshell-Skills Integration** — TiDB Cloud ops team's `nutshell-skills` knowledge base (TiDB perf diagnosis docs, TiKV tuning decision trees, Clinic API guides, O11Y metrics tools, autoscaler dashboard skills, etc.) bundled directly into the repo and loaded into the OpenCode agent at runtime via `skills.paths` in each workspace's `opencode.json`
- [x] **Skills Sync Infrastructure** — `sync-skills.sh` script + CI job keeps the local nutshell-skills copy in sync with the upstream source; workspace-specific skill overrides (e.g., the Grafana panel finder) are listed in a protected manifest and never overwritten by sync
- [x] **Workspace Skill Auto-Configuration (`SKILL_CLINIC_API_KEY`)** — Backend auto-injects per-user Clinic API keys into `opencode.json` on workspace creation via the `SKILL_CLINIC_API_KEY` env var; skills that call Clinic APIs work without any manual token configuration
- [x] **Grafana Panel Finder Skill Refactor** — Rewritten from keyword-based matching to a goal-oriented approach; produces more reliable Grafana panel selection for screenshot and diagnostics workflows
- [x] **System Prompt Optimization** — Agent system prompt tuned to reduce noise, improve diagnostic focus, and better handle workspace context injected at session start
- [x] **Time-Conversion Skill** — New `time-conversion` skill for deterministic Unix timestamp conversion (s/ms/ns) across timezones; agent system prompt now mandates its use instead of manual timezone math, eliminating off-by-one errors in time-windowed queries. ([#241])
- [x] **Clinic Data Proxy API Integration** — Implemented via the `clinic-api` skill. The `tidb-clinic-diagnosis` skill uses `POST /data-proxy/query` for `slow_query_logs` and `topsql` table queries with `date` partition filtering. No separate MCP tools needed.

---

## Milestone #2: Diagnostic Quality Improvement

> Goal: Systematically improve diagnostic accuracy and efficiency through structured postmortems and automated replay validation.

### TCOC Postmortem SOP

- [x] **TCOC Postmortem SOP Document** — `docs/sops/tcoc-postmortem.md` (EN) + `docs/sops/tcoc-postmortem.zh.md` (ZH). 8-step workflow: run diagnosis → human-guided analysis → evaluate → document guidance → identify deficiencies → deduplicate against backlog → write postmortem → file PRs.
- [x] **Postmortem Evaluation Template** — `tools/replayer/cases/TEMPLATE.md`. Standardized sections: Issue Summary, Actual Root Cause, Agent Diagnosis Summary, Scores (5 dimensions), Human Guidance Log, Skill Deficiencies, Key Queries, Lessons Learned. Each case also produces `expected.md` as replayer baseline.
- [ ] **First Batch TCOC Case Postmortems** — Use the SOP to review 5-10 representative TCOC tickets, producing evaluation records and Skill improvement PRs, validating the SOP process feasibility. Progress: 4/5-10 completed (O11Y-2328599: score 2.2, O11Y-2179140: score 3.6, TCOC-4964: score 2.4, TCOC-5011: postmortem done).

### Skill Deficiency Backlog (from postmortems)

> Centralized tracking of all skill deficiencies discovered through TCOC postmortems. When a new postmortem finds the same deficiency, add the case to `Reproduced in` — do NOT create a duplicate.

| ID | Type | Priority | Skill | Title | Reproduced in | Status |
|----|------|----------|-------|-------|---------------|--------|
| D1 | FLOW | P0 | tidb-clinic-diagnosis | TopSQL not mandatory in diagnostic flow | O11Y-2328599, O11Y-2179140 | open |
| D2 | TEMPLATE | P0 | tidb-clinic-diagnosis | TopSQL/SlowQuery SQL template uses non-existent columns (`cluster_id`, `timestamp`) | O11Y-2328599, O11Y-2179140 | open |
| D3 | FLOW | P0 | tidb-clinic-diagnosis | No "hotspot node → drill down by instance" decision rule | O11Y-2328599 | open |
| D4 | TEMPLATE | P1 | tidb-clinic-diagnosis | SlowQuery analysis missing execution plan parsing (no `plan`/`decoded_plan` fetch) | O11Y-2328599, O11Y-2179140 | open |
| D5 | CROSS-REF | P1 | tidb-clinic-diagnosis | No cross-reference enforcement (can conclude from single data source) | O11Y-2328599 | open |
| D6 | KNOWLEDGE | P1 | clinic-api | TopSQL schema docs incomplete (`timestamps`, `instance` columns undocumented) | O11Y-2328599 | open |
| D7 | TEMPLATE | P2 | tidb-clinic-diagnosis | clinic-auth.sh path not deterministic, wastes tool calls on filesystem search | O11Y-2328599, O11Y-2179140 | open |
| D8 | REASONING | P1 | tidb-clinic-diagnosis | Premature root cause from single signal (e.g., ANALYZE in metrics → wrong conclusion) | O11Y-2328599 | open |
| D9 | REASONING | P1 | tidb-clinic-diagnosis | Execution plan analysis qualitative not quantitative (ignores operator time ranking) | O11Y-2328599 | open |
| D10 | FLOW | P1 | tidb-clinic-diagnosis | No structured summary auto-generated after Node E evidence collection | O11Y-2179140 | open |

### TCOC Auto Replayer

- [x] **Replayer Case Library Structure** — `tools/replayer/` directory with `cases.yaml`, `cases/{issue_id}/expected.md` + `postmortem.md`, and `references/` for progressive disclosure. 4 cases: O11Y-2328599, O11Y-2179140, TCOC-4964, TCOC-5011.
- [x] **Replayer Core Script** — `tools/replayer/replay.sh` provides atomic operations: `--create`, `--check`, `--followup`, `--eval-only`. Supports `--profile` for remote environments.
- [x] **Replayer Skill (SKILL.md)** — Claude Code skill with two capabilities: Postmortem (Mode B/D) and Regression (Mode F recommended). Progressive disclosure: core flow in SKILL.md (279 lines), code/templates in `references/`. Regression includes mandatory rubric comparison against `expected.md`.
- [x] **First Validation Set** — 4 cases with `expected.md` + scoring rubric. O11Y-2328599 regression validated: 6/6 rubric, 0 human interventions (vs original 10 interventions, score 2.2).
- [ ] **Pre/Post Skill Change Comparison** — Support comparison mode: after a Skill change, rerun all cases and compare scores against baseline, outputting a diff report (which cases improved / degraded / unchanged).
- [ ] (Future) **CI Integration** — Wire replayer into CI: push skill changes → auto-trigger replay → score changes as PR check → block merge if degradation exceeds threshold.

---

## Future / Backlog (Not Currently Planned)

### Production Integration & Infrastructure

- [ ] **Agent Workspace Per-User Pod Isolation** — All workspaces for each user share a dedicated pod; re-architect ACP session management
- [ ] **Docker Image Optimization + Local Dev One-Command Start** — Verify full `make install / make web / make api` workflow; update `Dockerfile` (frontend + backend) to ensure clean builds; docker-compose starts the full stack with a single command

### Authentication & User System

_(No additional backlog items beyond M1's OAuth/SSO task)_

### Workspace Sharing & Collaboration

- [ ] **Workspace Write-Access Sharing: Real-Time Control Handoff** — During diagnosis, owner can temporarily hand off UI control to another user (e.g., collaborator remote operation); during handoff, the delegate can send messages, operate Sources / Studio normally, while owner falls back to read-only observer mode; Workspace file ownership unchanged, all MCP calls still use original owner's credentials and permissions; `PUT /api/workspaces/{id}/control {delegate_email}` to authorize, `DELETE /api/workspaces/{id}/control` to revoke; frontend Share panel adds "Hand Off Control" entry, status bar shows current active controller. Owner can stop sharing. UI displays current controller and shows who the viewers are.

### Backend Persistence

- [ ] **Workspace Upgrades** — As features increase, Workspace data structures and file organization may need upgrades; design version compatibility strategy; implement data migration scripts; frontend displays Workspace version info and prompts users to upgrade

### Source Integration

- [ ] **Alert Source Watcher** — Allow adding a Source called Watcher that continuously monitors newly assigned Alerts for a user, e.g., monitoring all on-call alerts for the week and auto-adding them to the Workspace
- [ ] **Git Repo Source** — Connect code repository as Agent context; code already marked "Currently Not Supported"
- [ ] **Knowledge Source Type** — Add `'knowledge'` to `SourceType`; add corresponding metadata to `SOURCE_TYPE_META` (label: "Knowledge", icon 📚); show in `AddSourceModal` under Dev Mode; support manual Markdown text input; data stored in `workspace_sources` JSON blob
- [ ] **Skill Source Type** — Add `'skill'` to `SourceType`; support user-created reusable prompt templates / analysis frameworks; show in `AddSourceModal` under Dev Mode; Skill content injected into ACP Agent system prompt
- [ ] **Manual Cluster Meta Simulation Source** — Add a dev-only/manual source flow to provide mock `cluster_meta` values (e.g., cluster_id/org_id/version/time range) for testing MCP and prompt behavior without requiring alert preparation

### MCP / Skill Data Capability Extensions

> Note: Clinic / O11Y data access has migrated to the `clinic-api` skill. The following extensions can be implemented as skill subcommands or standalone skills, no longer requiring MCP.

- [ ] **Frontend-Configurable MCP Connector** — Users configure MCP connection parameters (endpoint, token) directly in the Sources panel, without modifying backend config files
- [ ] **MCP Remote Mode Support** — Add remote MCP transport support (beyond local stdio) in workspace `.opencode/opencode.json` generation and session bootstrap; support per-connector endpoint/auth configuration and health checks
- [x] ~~**Clinic Data Proxy API Integration**~~ — Done. Implemented via `clinic-api` skill's `POST /data-proxy/query` endpoint, supporting `slow_query_logs` and `topsql` table SQL queries.
- [ ] **Clinic: Profile Capture Capability** — Add skill/tool to capture/export runtime profile data (CPU/heap/goroutine or equivalent), persist artifacts in workspace files, and expose results in Studio/Files views
- [ ] **Clinic: Statement Query Capability** — Add skill/tool for SQL statement-level querying/inspection (filters by cluster, time range, digest/text); return structured output suitable for report generation
- [ ] **Clinic: Table Schema Introspection** — Add skill/tool to fetch table schema metadata (database/table DDL, indexes, partition info) to support root-cause analysis in chat/report flows
- [ ] **TiDB Control Plane Query Support (tidb-ctl)** — Add diagnostic command query capability with guardrails for read-only-safe operations and clear error/reporting output

### Testing & Evaluation

> Note: Core testing & evaluation capabilities have moved to Milestone #2 (TCOC Auto Replayer). The following are supplementary items.

- [ ] **Diagnostic Cost Evaluation** — Track and evaluate token/tooling/runtime costs per diagnosis run; define cost budgets and cost-quality tradeoff thresholds for release gating
- [ ] **Skills Prompt Injection Regression Tests** — Verify workspace skills are injected into system prompts in deterministic order, with deduplication and explicit precedence against built-in instructions
- [ ] **Skills-to-Diagnosis Impact Tests** — Add scenario evaluations validating that enabled skills improve diagnostic quality/efficiency and do not cause behavior leakage when disabled

### ACP Session & Chat Lifecycle & Agent Capabilities

- [ ] **Workspace Async Long-Running Tasks** — Support background long-running Agent tasks (e.g., full cluster diagnostic scan); task status via SSE push; task queue management
- [ ] **Workspace CronJob** — Support user-configured scheduled tasks for Workspaces (e.g., auto-analyze cluster status daily); CronJob configuration UI; backend triggers Agent execution on schedule, results auto-generate Report Artifact
- [ ] **Export Feature** — Export Investigation Workspace, supporting in-place permission configuration and connecting to OpenCode for self-debugging
- [ ] **Offline Continuous Analysis** — Background offline analysis of historical diagnostic data, continuously accumulating analysis conclusions, distilling Knowledge and Skills for use in subsequent diagnostics
- [ ] **Automatic Memory & Skills Maintenance** — Add automatic Memory and Skills maintenance system, forming capabilities similar to OpenClaw
- [ ] **Agent Automation Closed-Loop Autopilot** — Agent closed-loop problem diagnosis, fire-and-forget mode, users review results afterward. For example, user submits an Alert, Agent auto-analyzes and generates Report Artifact + Operation Artifacts, user doesn't need to wait for analysis in real-time and can review conclusions later.
- [ ] **Parallel Evidence Gathering (Weak Conclusion, Strong Evidence)** — Redesign diagnosis from serial single-agent to parallel subagent evidence collection. OpenCode v1.2.10 natively supports subagents via the `Task` tool (`opencode agent create --mode subagent`). Implementation phases:
  - **P0 — Custom Evidence Subagents + System Prompt** (1-2d): Create `.opencode/agents/` definitions for 4 evidence dimensions (metrics, topsql, slowquery/logs, events/github); modify `system_prompt.py` to instruct main agent to dispatch parallel `Task` tool calls; add agents dir copy to `workspace_setup.py`. Core risk: verify build agent can launch >1 parallel Task (plan agent hardcodes limit=1, build agent may not).
  - **P1 — Frontend Task Tool Rendering** (1-2d): ChatPanel already renders `ToolCallStart/Progress`; enhance to show subagent name and progress distinctly for Task-type tool calls.
  - **P2 — Studio Panel Real-Time Evidence Cards** (3-5d): Add `evidence` SSE event type; backend parses subagent Task output into structured evidence; frontend auto-creates Artifact cards in Studio Panel as evidence streams in.
  - Ref: OpenCode agents discovered at `{.opencode/agent/, .opencode/agents/}/**/*.md`; built-in subagents: `explore` (read-only), `general` (full tools).
- [ ] **Multi-Agent Capabilities** — https://github.com/openclaw/acpx — Allow some features to be invoked as Agent CLI; design Multi-Agent capabilities

### UI/UX Improvements

#### Studio Artifacts & Reports

- [ ] **Studio Action Cards Implementation (Report Generation)** — `StudioPanel` top Action Cards: click "📊 Report" to trigger Agent analysis → stream generation via Chat SSE → auto-create Report Artifact on completion; remove "Coming Soon" placeholder state
- [ ] **Studio Action Cards Implementation (Notes)** — Click "📝 Notes" to open `NoteModal`; support Markdown editing; create `note` type Artifact on save; Artifact list supports viewing/editing Notes
- [ ] **Operation List Artifact (Change Approval Form)** — Studio supports generating Operation List Artifact (one-click initiation of production change approval form, creating an approval form for a set of change actions); Agent generates change steps → frontend displays step list + "Submit for Approval" button; manual approval checkpoint (can be a UI confirmation dialog for now, integrate with real approval system in the future). This feature enables the closed loop of automated diagnosis + one-click remediation.

#### Workspace Low-Level Files & Command Line

- [ ] **File Editing Support** — Currently `FileViewer` (`components/StudioPanel/FileViewer.tsx`) is read-only; add inline editing for text files (`.md`, `.json`, `.yaml`, etc.); backend implements `PUT /api/workspace/{id}/file-content` endpoint to write file content back; frontend "Edit" button toggles read-only ↔ edit mode, Ctrl+S / Save button to submit; auto-refresh file tree and Agent context after save
- [ ] **Pod Terminal Access** (depends on Pod Isolation) — Add Terminal panel to frontend (Xterm.js); establish channel with backend via WebSocket (`/ws/workspace/{workspace_id}/terminal`); backend `exec` shell in the corresponding user pod, bidirectional I/O forwarding; support executing debug commands, viewing logs, and manually operating the file system within the Agent working directory

#### Dev Mode & Local Development Experience

- [ ] **Dev Mode Full-View Toggle** — Create `lib/devMode.ts`, export `useDevMode()` hook reading `NEXT_PUBLIC_DEV_FULL_VIEW`; integrate in `AddSourceModal`, `SourcesPanel`, `StudioPanel` to control show/hide of unimplemented features; production Dockerfile does not pass this variable

### Admin Dashboard

- [ ] **Admin Dashboard Skeleton** — Create `platform/admin/` directory (standalone FastAPI service); reuse `backend/db.py` SQLite connection; implement APIs: list all users and their workspace lists, view full state of any workspace (sources + artifacts + messages + files); add `workspace_snapshots` table (store complete snapshot JSON)
- [ ] **Reproduce & Impersonate** — Admin interface can select historical workspace → generate complete state snapshot → frontend opens from that workspace's perspective, reproducing the state at that time; underlying: `POST /admin/workspaces/{id}/snapshot`, `GET /admin/snapshots/{id}` for replay
- [ ] **Backend On-Demand Alert Ticket Assignment to Workspaces** — Support a category of consultation-style Workspaces where the backend auto-assigns tickets to the on-call engineer for the week, also sends IM notifications for ticket assignments. Also supports manual assignment: Admin interface selects any workspace → "Assign Alert" → enter Alert ID → backend writes the Alert-related data to workspace file system (`data/workspaces/{workspace-id}/`); frontend auto-detects new Source and triggers Agent analysis

### Skills Statistics & Management

- [x] **Popular Skills Dashboard** — Admin stats page at `/admin/stats` shows top skills, top MCP tools, and top built-in tools by call count across all workspaces; data sourced from per-workspace `statistics.db` written by the `ya-opencode-telemetry` OpenCode plugin. ([#233]) Remaining future work: time-series trends, success rate metrics, heatmap visualization.
- [ ] **Ranking Page Real-Data Connection** — The `/ranking` page (PR #243) currently uses mock data; connect it to the `statistics.db` telemetry backend (`GET /api/stats/summary`) to show live skill/tool leaderboards driven by actual usage across the fleet
- [ ] **Skills Hot Reload** — Implement hot reload mechanism for skills without requiring workspace restart; backend watches `agentkit/plugins/` and workspace `.opencode/skills/` directories for changes; automatically reimport updated skill files and refresh OpenCode plugin cache; add `POST /api/skills/reload` endpoint to trigger manual reload; frontend shows notification when skills are reloaded; preserve existing OpenCode session context during reload
- [ ] **Skills Hub & Marketplace** — Create Skills Hub UI at `/skills` for browsing and installing community skills; backend implements `GET /api/skills/hub` to fetch available skills from registry (GitHub repos, internal registry, etc.); support skill search, filtering by category/tags, and sorting by popularity/rating; each skill card shows description, author, version, usage count, and rating; implement `POST /api/workspace/{id}/skills/install` to install skill from Hub into specific workspace; support skill versioning and dependency management
- [ ] **User-Defined Skill Installation** — Allow users to install skills from custom sources (GitHub URL, local file upload, or direct text input); add "Install Skill" button in workspace Sources panel; implement skill validation (check SKILL.md format, required fields, security scan); support skill configuration UI for user-provided parameters (API keys, endpoints, etc.); installed skills auto-appear in workspace `.opencode/skills/` and become available to Agent immediately
- [ ] **Skills Usage Analytics Per Workspace** — Add per-workspace skill usage breakdown in workspace settings; show which skills are most used in each workspace; provide recommendations for relevant skills based on workspace type (alert diagnosis, performance analysis, etc.); track skill effectiveness metrics (success rate, user feedback, time saved)
- [ ] **Skills Dependency & Conflict Management** — Detect and resolve skill conflicts (duplicate names, overlapping functionality); support skill dependencies (skill A requires skill B); implement skill compatibility checking with OpenCode version; add skill health monitoring and automatic disable for failing skills
