Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
docs: cut docs/ to design + product-overview, English by default (MUL-5698) (#6364)
Jiayuan Zhangc1ec1f46466b
diff --git a/.env.example b/.env.exampleindex 66c0529e81..4014558fc4 100644--- a/.env.example+++ b/.env.example@@ -101,7 +101,7 @@ MULTICA_CODEX_TIMEOUT=20m# every flag falls through to the caller's default, which lets the server# boot before any flag config is authored. When set, the file is read once# at startup and a parse / IO error fails fast — same loud-failure shape as-# DATABASE_URL or JWT_SECRET misconfig. See docs/feature-flags.md for the+# DATABASE_URL or JWT_SECRET misconfig. See server/pkg/featureflag for the# full schema; the minimum example is:## billing_new_invoice_email:@@ -358,7 +358,7 @@ DISABLE_WORKSPACE_CREATION=# ==================== Analytics (PostHog) ====================# Product analytics events feed the acquisition → activation → expansion funnel.# Leave POSTHOG_API_KEY empty for local dev / self-hosted instances; the server-# will run a no-op analytics client and ship nothing. See docs/analytics.md.+# will run a no-op analytics client and ship nothing.POSTHOG_API_KEY=POSTHOG_HOST=https://us.i.posthog.com# Optional override for the `environment` PostHog event property.diff --git a/AGENTS.md b/AGENTS.mdindex 97da794840..66c67eafe7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -17,10 +17,13 @@ Go backend + monorepo frontend (pnpm workspaces + Turborepo) with shared package- `server/` - Go backend (Chi router, sqlc, gorilla/websocket)- `apps/web/` - Next.js frontend (App Router)- `apps/desktop/` - Electron desktop app+- `apps/mobile/` - Expo / React Native iOS app (read `apps/mobile/CLAUDE.md` first)+- `apps/docs/` - Fumadocs documentation site- `packages/core/` - Headless business logic (Zustand stores, React Query hooks, API client)- `packages/ui/` - Atomic UI components (shadcn/Base UI, zero business logic)- `packages/views/` - Shared business pages/components- `packages/tsconfig/` - Shared TypeScript config+- `packages/eslint-config/` - Shared ESLint config### State Management (critical)diff --git a/CLAUDE.md b/CLAUDE.mdindex 8dc766b177..d4f9e88b28 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -19,10 +19,12 @@ Multica is an AI-native task management platform for small teams, with agents as- `apps/web/`: Next.js App Router.- `apps/desktop/`: Electron desktop app.- `apps/mobile/`: Expo / React Native iOS app. Read `apps/mobile/CLAUDE.md` before touching it.+- `apps/docs/`: Fumadocs documentation site.- `packages/core/`: headless business logic, API client, React Query hooks, Zustand stores.- `packages/ui/`: atomic UI components only.- `packages/views/`: shared business pages/components for web and desktop.- `packages/tsconfig/`: shared TypeScript config.+- `packages/eslint-config/`: shared ESLint config.Shared packages export raw `.ts` / `.tsx` and are compiled by consuming apps. Dependency direction is `views -> core + ui`; `core` and `ui` must stay independent.diff --git a/apps/mobile/docs/project-v1-gap-audit.md b/apps/mobile/docs/project-v1-gap-audit.mddeleted file mode 100644index fff72bcc96..0000000000--- a/apps/mobile/docs/project-v1-gap-audit.md+++ /dev/null@@ -1,142 +0,0 @@-# Project surface — v1 gap audit (apps/mobile/)--**Status**: Pre-implementation. Pairs with `project-v1-plan.md` (the execution plan).-**Date**: 2026-05-20--## Context--Mobile is preparing the first user-facing release (not demo). Core use cases are **操作 issue / 派活 / 聊天**. This document inventories every gap between mobile's current Project surface and the web reference — both for the items addressed in this PR and the items consciously deferred to later PRs.--The gap inventory is the work product. The plan to close the in-scope gaps lives in `project-v1-plan.md`.--## Methodology--Compared mobile files in:-- `apps/mobile/app/(app)/[workspace]/more/projects.tsx`-- `apps/mobile/app/(app)/[workspace]/project/{new,[id],[id]/edit,[id]/add-resource,[id]/picker/lead}.tsx`-- `apps/mobile/components/project/*`--…against web reference in:-- `packages/views/projects/components/{projects-page,project-detail,project-resources-section,project-picker}.tsx`-- `packages/views/projects/components/modals/create-project.tsx`-- `packages/core/projects/` (queries, mutations, ws-updaters, schemas)--For each affordance: cite web file:line + mobile file:line + classify severity per the rules in `apps/mobile/CLAUDE.md` "Behavioral parity":--- 🔴 **Important** — parity violation; product semantics diverge between clients-- 🟡 **UX gap** — feature exists on web, useful on mobile, not critical for release semantics-- ⚪ **Intentional divergence** — small-screen incompatible, deliberately omitted on mobile-- 🟢 **Quality sweep** — hardcoded colors, hand-drawn icons; baseline alignment with the just-landed inbox / my-issues / Issues UI--## In-scope for v1 PR (🔴 + 🟢)--### 1. Tier B picker migration not finished--Two project pickers stayed on the legacy `<Modal transparent>` shell when `feat(mobile): migrate sheet modals to route-level pageSheet (cc61ae3a)` landed:--| File | Issue |-|---|---|-| `components/project/pickers/project-status-picker-sheet.tsx` | Still uses `<Modal transparent fade>` centered card |-| `components/project/pickers/project-priority-picker-sheet.tsx` | Same |--**Why this matters**: project detail's attribute row now has **mixed gestures** — tap *lead* gives native iOS pageSheet drag-to-dismiss; tap *status / priority* gives the old transparent-Modal centered card with backdrop tap dismiss. Mobile CLAUDE.md Lesson 6 "picker-row consistency" explicitly forbids mixed-gesture rows. `project/[id].tsx:69` already has a TODO comment acknowledging this.--### 2. Progress bar missing on detail--Web `project-detail.tsx:596-620` renders a horizontal progress bar with `done_count / issue_count` and percentage. Mobile detail page has **zero progress visibility** — the project schema (`packages/core/types/project.ts:17-18`) has `issue_count` and `done_count` fields, but mobile never reads them.--Users on mobile have no answer to "how done is this project?". Real behavioral parity violation.--### 3. View mode switcher + Board view on detail's issues--Web `project-detail.tsx:211-237, 311` exposes Board / List / Gantt selector for the issues section. Mobile `components/project/project-related-issues.tsx` hardcodes a **two-bucket "Open / Done" rollup** that doesn't exist on web — web groups by full `BOARD_STATUSES` (backlog/todo/in_progress/in_review/done/blocked).--This is *silent semantic divergence*: a user expects "Open" on mobile and "Backlog + Todo + In Progress + In Review + Blocked" on web to be the same five categories. They are not.--Gantt stays deferred (small-screen incompatible — see ⚪ section).--### 4. Create form has no draft persistence--Web `create-project.tsx:120-150` uses `useProjectDraftStore` to survive backgrounding — type title, get a call, come back, title still there. Mobile `project/new.tsx` has no draft store. Per mobile CLAUDE.md "cellular edge hazard": on flaky network or interrupted use, users lose work mid-form.--The pattern is already present in mobile via `new-issue-draft-store.ts` (landed in the Tier B sheet migration PR). New `new-project-draft-store.ts` should mirror that exact shape.--### 5. Hardcoded hex sweep (🟢 quality)--The just-landed UI baseline scrubbed `#71717a` / `#a1a1aa` style hex from inbox / my-issues / more-issues. Project domain is the last hold-out.--| File:line | Hex | Notes |-|---|---|---|-| `project-properties-section.tsx:135` | `#a1a1aa` | Chevron stroke |-| `project-resources-section.tsx:112` | `#71717a` | GitHub icon color |-| `project-related-issues.tsx:184` | `#71717a` | Chevron stroke |-| `project/[id].tsx:156` | `#71717a` | Android header menu fallback |-| `more/projects.tsx:108-127` | `#0a84ff` ×2 | Hand-drawn PlusButton SVG stroke |--All become `THEME[scheme].mutedForeground` (Ionicons color prop) or NativeWind semantic tokens. Dark-mode breakage is the failure mode they cause.--### 6. Hand-drawn SVG icons (🟢 quality, Principle 1)--| File:line | Replacement |-|---|---|-| `more/projects.tsx:108-127` PlusButton | `<IconButton name="add" />` |-| `project-properties-section.tsx:130-142` chevron | `<Ionicons name="chevron-forward" />` |-| `project-related-issues.tsx:168-191` chevron | `<Ionicons name="chevron-forward" />` |--Existing `IconButton` + `Ionicons` already used everywhere else in mobile. These three are pre-baseline legacy.--## Out of scope for this PR (recorded, not done)--### 🟡 UX gaps — defer to v1.1+--| Affordance | Reason for deferring |-|---|---|-| Pin / unpin project | Mobile has **no pin API methods and no "Pinned" consumer surface** (no pinned-items list anywhere). Building only the pin toggle button without a list to show pinned items = dead UI. Needs a dedicated PR that does pin endpoints + storage + a pinned-items surface end-to-end. |-| Inline title edit on detail header | Mobile routes to `/[id]/edit` for title changes — extra tap but functional. Inline edit on phones has keyboard-management issues; deferring acceptable. |-| Icon emoji picker on create + edit | Currently a 4-char TextInput. Needs a third-party emoji picker library or a built-in grid component. UX divergence but no functional gap. |-| Issue filter UI on Project detail | Consistent with my-issues / Issues — fine-grained filters (assignee / creator / label) are not in v1 anywhere on mobile. |-| Resources attachment at create time | Web allows selecting repos before project exists. Mobile creates first, then adds resources. Adds a step but not a parity violation. |-| Section collapse (Properties / Description / Resources) | Web pattern (MUL-2275). Small-screen sidebars don't need collapse — content is already short. |-| Description visibility on Detail | Currently only editable on `/edit`. Read-only display on detail screen could be added but lower priority. |-| Copy link menu item | Mobile has "Open on web" which serves a similar purpose. iOS native `Share.share` would also work. |--### ⚪ Intentional divergence — never--| Affordance | Why |-|---|---|-| Gantt view on Project detail | Web added scheduled-only Gantt (MUL-1881, 54368fd8). Phone screens are too narrow for meaningful Gantt rendering — Linear iOS / Asana iOS don't ship Gantt either. Permanent mobile divergence; document inline at the call site once the issues section is touched. |-| Breadcrumb in header | Web shows "Workspace > Project". Mobile uses native iOS Stack title bar (single line). Platform-correct divergence. |--## What's already aligned (no work needed)--- **Data layer hygiene**: `projectKeys` 3-segment factory, `queryFn { signal }` forwarding, `parseWithFallback` on every typed response-- **Mutations**: optimistic three-step (snapshot → patch → rollback) + settle invalidate for create / update / delete / resource add / resource remove-- **Realtime**: `useProjectRealtime` per-record, `useProjectsRealtime` listing-level, both via `useWSSubscriptions` + typed `ws.on<E>()`, scoped reconnect invalidate-- **Error surfacing**: matches MUL-2317 (`Alert.alert(err.message)` on mutation failures) — equivalent to web's toast pattern-- **Status / Priority / Lead enum coverage**: all values present (status: planned / in_progress / paused / completed / cancelled; priority: urgent / high / medium / low / none; lead: member / agent)-- **Resource CRUD**: add via route modal, remove via long-press + Alert (acceptable platform divergence from web's hover-delete)-- **List page**: web itself has no filter / sort / scope tabs → mobile correctly mirrors the minimal surface--## Out of scope at the *release* level (record only, separate PRs)--These are blockers for mobile v1 release but unrelated to Project:--- **Push notifications (APNs registration + tap-to-issue routing)** — blocks the 派活 use-case loop-- **Chat surface full audit** — wasn't depth-reviewed yet-- **Error boundaries + Sentry crash reporting** — release telemetry baseline-- **App Store metadata** (icon, splash, launch storyboard, privacy manifest, version, About / privacy-policy links)-- **First-launch onboarding** (welcome → login → workspace pick/create → optional tour)-- **i18n (Chinese)** — v1 ships English-only by default; can change if product disagrees--Each gets its own PR / planning doc later. They are NOT addressed in the Project v1 PR.--## Severity summary--| Tier | Count | In this PR |-|---|---|---|-| 🔴 Important (parity) | 4 | Yes — all four |-| 🟢 Quality sweep | 2 | Yes — all (hex + SVG) |-| 🟡 UX gap | 7 | No — deferred to v1.1+ |-| ⚪ Intentional divergence | 2 | No — permanent |--PR scope = **6 items** (Tier B picker collapse counts as one).diff --git a/apps/mobile/docs/project-v1-plan.md b/apps/mobile/docs/project-v1-plan.mddeleted file mode 100644index 41fe02d056..0000000000--- a/apps/mobile/docs/project-v1-plan.md+++ /dev/null@@ -1,186 +0,0 @@-# Project surface — v1 implementation plan--**Status**: Pre-implementation, awaiting approval.-**Pairs with**: `project-v1-gap-audit.md` (the audit identifying every gap).-**Date**: 2026-05-20--## Context--This PR brings mobile's Project surface to release-quality parity with web/desktop for the **operate / assign-work / collaborate** use cases. The deferred items (Pin, inline title edit, emoji picker, filters, Gantt, etc.) are documented in the gap audit and not addressed here.--## Scope--Six items, one PR:--1. **Tier B finish**: migrate `project-status-picker-sheet.tsx` + `project-priority-picker-sheet.tsx` → route-modal `*-body.tsx` + route file-2. **Progress section** on detail (horizontal bar + `done / total` text)-3. **View mode switcher** on detail's related-issues area (Board / List), with Board view as new-4. **Create-form draft persistence** (mirror `new-issue-draft-store`)-5. **Hardcoded hex sweep** (5 occurrences → tokens or `THEME[scheme].mutedForeground`)-6. **Hand-drawn SVG → existing primitives** (3 occurrences → `IconButton` / `Ionicons`)--## Out of scope--See `project-v1-gap-audit.md` "Out of scope" section. Don't touch.--## Component decisions (waterfall per item)--| # | Item | Component | Reason |-|---|---|---|---|-| 1a | Status picker shell | New file `app/(app)/[workspace]/project/[id]/picker/status.tsx` (route) | Mirrors existing `picker/lead.tsx` and the issue pickers — established mobile route-modal pattern |-| 1a | Status picker body | New file `components/project/pickers/project-status-picker-body.tsx` | Rename + extract from `project-status-picker-sheet.tsx` |-| 1b | Priority picker | Same pattern: `picker/priority.tsx` route + `project-priority-picker-body.tsx` body | Same |-| 2 | Progress bar | Inline composition in `project-header-card.tsx`: `<View className="h-1.5 bg-secondary rounded-full"><View className="h-full bg-brand" style={{ width: `${pct}%` }} /></View>` | Trivial primitive composition; no new component needed (below three-occurrence threshold) |-| 2 | Progress text | `<Text className="text-xs text-muted-foreground">` | Existing token |-| 3 | View mode switcher | iOS native `SegmentedControl` (`@react-native-segmented-control/segmented-control`) — already installed | Principle 3 native > RNR > discuss; same pattern as workspace Issues scope tabs |-| 3 | Board view | `ScrollView horizontal pagingEnabled={false}` + per-status column = `FlatList` of `IssueRow` | Reuses `IssueRow`; no new primitive |-| 3 | View mode state | Local `useState` in `project-related-issues.tsx`, NOT a Zustand store | No cross-component need; matches mobile/CLAUDE.md "Don't add state unless explicitly required" |-| 4 | Draft store | New `apps/mobile/data/stores/new-project-draft-store.ts`, mirroring `new-issue-draft-store.ts` exactly | Three-occurrence threshold: new-issue, new-project — close to threshold but pattern is small enough that the duplicated store is cheaper than a generic abstraction |-| 5 | Hex → token | `text-muted-foreground` class via `Ionicons color={THEME[scheme].mutedForeground}` | Same pattern as the my-issues `Chip` X icon |-| 6a | PlusButton → IconButton | `<IconButton name="add" />` | Existing primitive |-| 6b | Chevron → Ionicons | `<Ionicons name="chevron-forward" size={14} color={THEME[scheme].mutedForeground} />` | Existing |--## API / data layer--No new endpoints. All data already available:--- Progress bar: `Project.issue_count` + `Project.done_count` (already in schema, `packages/core/types/project.ts:17-18`)-- View mode switcher: same `issueListOptions` filtered by `project_id` already used in `project-related-issues.tsx`-- Tier B picker migration: existing `useUpdateProject` mutation (no API change)-- Draft persistence: pure client state, no backend--## State / store changes--| Store | Change |-|---|---|-| `new-project-draft-store.ts` (new) | `title`, `description`, `icon`, `status`, `priority`, in-memory zustand store; `clear()` action on submit success; no persist middleware in v1 (matches `new-issue-draft-store.ts`) |-| (no other store touched) | Status / Priority picker state stays in the existing `useUpdateProject` mutation flow; view mode is local component state |--## File-by-file--### New files--```-apps/mobile/app/(app)/[workspace]/project/[id]/picker/status.tsx-apps/mobile/app/(app)/[workspace]/project/[id]/picker/priority.tsx-apps/mobile/components/project/pickers/project-status-picker-body.tsx (renamed/extracted from -sheet.tsx)-apps/mobile/components/project/pickers/project-priority-picker-body.tsx (renamed/extracted from -sheet.tsx)-apps/mobile/data/stores/new-project-draft-store.ts-```--### Deleted files--```-apps/mobile/components/project/pickers/project-status-picker-sheet.tsx-apps/mobile/components/project/pickers/project-priority-picker-sheet.tsx-```--### Modified files--```-apps/mobile/app/(app)/[workspace]/_layout.tsx- - register two new Stack screens for status + priority picker routes- - presentation: "formSheet" with detents matching the lead picker--apps/mobile/app/(app)/[workspace]/project/[id].tsx- - swap inline Modal opens for `router.push({ pathname: "[workspace]/project/[id]/picker/status", ... })`- - same for priority- - remove the two Modal state variables and Modal JSX- - update the headerRight platform-conditional icon color to use THEME[scheme] (line 156 hardcoded hex)--apps/mobile/app/(app)/[workspace]/project/new.tsx- - import useNewProjectDraftStore- - read draft into form on mount, write on every field change- - call clearDraft on successful create--apps/mobile/components/project/project-header-card.tsx- - add progress section: horizontal bar + "{done_count} / {issue_count}" text + percentage- - reuse existing card padding--apps/mobile/components/project/project-related-issues.tsx- - add view mode local state (`"list" | "board"`)- - add SegmentedControl two-segment header- - List mode: refactor current "Open / Done" two-bucket grouping into proper status grouping (BOARD_STATUSES — matches web)- - Board mode: horizontal ScrollView, each column = status header + FlatList of IssueRow- - replace hand-drawn chevron SVG (line 168-191, 184) with Ionicons- - drop react-native-svg import if no other usage--apps/mobile/components/project/project-properties-section.tsx- - replace hand-drawn chevron SVG (line 130-142, 135) with Ionicons- - drop react-native-svg import if no other usage--apps/mobile/components/project/project-resources-section.tsx- - replace hardcoded #71717a (line 112) with THEME[scheme].mutedForeground--apps/mobile/app/(app)/[workspace]/more/projects.tsx- - replace hand-drawn PlusButton SVG (line 108-127) with <IconButton name="add">- - drop react-native-svg import if no other usage-```--## Implementation order--Optimal order to keep typecheck green at each step:--1. **State store**: create `new-project-draft-store.ts` (no consumers yet, isolated)-2. **Picker bodies**: create `*-picker-body.tsx` files (rename of `-sheet.tsx`); existing imports still point to old, intermediate state OK-3. **Picker routes**: create `picker/status.tsx` and `picker/priority.tsx` route files that mount the bodies-4. **Register in `_layout.tsx`**: add new routes to Stack config-5. **`project/[id].tsx`**: switch from Modal opens to `router.push` for both pickers; delete old Modal state and JSX-6. **Delete old picker sheet files** (`-sheet.tsx`) — at this point nothing imports them-7. **Progress section in `project-header-card.tsx`**-8. **View mode switcher in `project-related-issues.tsx`** — Board view + status-grouped List, replacing Open/Done buckets-9. **Hex / SVG sweep** in `project-properties-section.tsx`, `project-resources-section.tsx`, `more/projects.tsx`-10. **`new.tsx` draft integration**: wire `useNewProjectDraftStore` into the create form-11. **Typecheck** (`pnpm --filter @multica/mobile exec tsc --noEmit`) — must exit 0--## Verification--### Required before PR open--1. `pnpm --filter @multica/mobile exec tsc --noEmit` → exit 0-2. Manual on simulator (cold start app, login, pick workspace):- - **Tier B picker**: open a project → tap status chip → native iOS pageSheet drags down → pick new status → reflects in chip. Same for priority. Compare gesture to lead picker (already migrated) — should be identical.- - **Progress bar**: detail screen shows horizontal bar + "X / Y" matching the project's actual `done_count` / `issue_count`. Bar fills proportionally; 0 issues shows empty bar (no divide-by-zero crash).- - **View mode switcher**: tap "Board" → see horizontal scroll of status columns; tap "List" → see vertical SectionList grouped by `BOARD_STATUSES`. Verify "Cancelled" status issues do NOT render in either view (matches web).- - **Draft persistence**: open new-project form → type title "Test" → background app via home button → re-foreground → title still "Test". Tap Cancel → re-open new-project → form is empty.- - **Dark mode**: toggle Settings → Appearance → Dark. Open project list, project detail, properties section, resources section. All icons / chevrons / +Add button now grey-appropriately for dark mode (no stuck `#71717a` slate).-3. Cross-client parity: open the same project on web and mobile, verify progress numbers match exactly.--### Optional checks--- Test on iPad in split-screen (the Board horizontal scroll should still behave)-- Test with a project that has zero issues (progress bar empty, Board / List show empty state)-- Test with a project that has 100+ issues (Board horizontal scroll smooth)--## Risks & rollback--| Risk | Mitigation |-|---|---|-| Board view perf with many issues | Use `FlatList` inside each status column, not `ScrollView` of rows. RNGH respects scroll within scroll. |-| Status-grouped List rendering "Cancelled" issues by accident | Mirror `BOARD_STATUSES` filtering from `more/issues.tsx:97-102` — already the canonical pattern in mobile. |-| Draft store leak between projects | `useNewProjectDraftStore` is global; `clearDraft` is called on submit success AND on Cancel button. If user backs out via swipe-back, draft persists — intentional, mirroring `new-issue-draft-store`. |-| `project/[id].tsx` becomes too long with both Modal removal + progress wiring | Acceptable for one PR; split if it crosses ~600 lines. |--Rollback: revert the diff. No DB / API / cache key changes. WS subscribers unchanged.--## Estimated diff size--- ~80 lines (picker migration: 2 new bodies + 2 new routes + edits to `[id].tsx` + `_layout.tsx`)-- ~40 lines (progress bar in header card)-- ~120 lines (view mode + Board view in related-issues)-- ~50 lines (draft store + integration in `new.tsx`)-- ~30 lines (hex/SVG sweep across 4 files)-- ~10 lines (route registrations in `_layout.tsx`)--**Total**: ~330 lines net, distributed across ~10 files (5 new, 2 deleted, 6 modified).--## Open questions (none blocking — defaults captured below)--These are decisions already made by me as the engineering choices. Listed for transparency.--1. **Board view orientation**: horizontal column scroll (each column = one status), not vertical scroll of status sections. Why: Board's job is "see all statuses side-by-side"; vertical defeats the point. Linear iOS / Things use horizontal.-2. **List mode status grouping**: full `BOARD_STATUSES` (6 groups), replacing the current "Open / Done" rollup. Why: parity with web; the rollup was a mobile-only invention.-3. **Draft persistence storage**: in-memory zustand only, no `expo-secure-store` persist middleware. Why: matches existing `new-issue-draft-store` pattern; cold-kill resilience can come in v2 if user feedback demands.-4. **Status / Priority picker presentation**: iOS `formSheet` (medium detent), matching lead picker. Why: gesture consistency across the attribute row.--If any of these defaults need to change, flag before execution.diff --git a/apps/mobile/docs/rnr-migration.md b/apps/mobile/docs/rnr-migration.mdindex 04ba00b059..647e1c0106 100644--- a/apps/mobile/docs/rnr-migration.md+++ b/apps/mobile/docs/rnr-migration.md@@ -1,6 +1,6 @@# RNR migration — design, alternatives, and three-phase rollout-**Status**: Phase 0 (research & docs) — complete. Phase 1 (base infrastructure) — not started.+**Status**: Phase 0 (research & docs) — complete. Phase 1 (base infrastructure) — complete: `global.css` CSS variables, `tailwind.config.js` `darkMode: "class"` + `hsl(var(--))` mappings, `lib/theme.ts`, `lib/use-color-scheme.ts`, `components.json`, `ThemeProvider` + `PortalHost` in `app/_layout.tsx`, and the Settings → Appearance picker are all shipped. Phase 2 (canary component) — not started.**Audience**: anyone touching `apps/mobile/components/ui/` or adding new UI to the mobile app. Read this once; refer to `apps/mobile/CLAUDE.md` "UI components & theming" for the durable rules.@@ -8,13 +8,15 @@## 1. Why this doc exists-The mobile baseline (`apps/mobile/CLAUDE.md`) has named **react-native-reusables (RNR)** as the shadcn equivalent since SDK 55 was bootstrapped. RNR was never actually installed. As a result:+> **Baseline note.** Everything in this section describes the state **before Phase 1**, which is the problem this migration was written to solve. Phase 1 has since shipped — see the Status line above and §6. The theming half of this list is fixed; the component half is not.-- `apps/mobile/components/ui/` contains **21 hand-written components, ~1,379 lines**, all built from raw `<View/Text/Pressable/Modal>`.-- `apps/mobile/components/` contains **18 hand-written sheet/modal files**, all copying the same shape (`Modal transparent fade` + hand-drawn backdrop). CLAUDE.md Lesson 6 (lines 250–269) already documents that this pattern is wrong for most content and has produced a series of bugs (keyboard squashing, `maxHeight` clipping FlatLists, `useSafeAreaInsets` returning 0 inside `Modal`).-- There is no dark/light theming infrastructure. `tailwind.config.js` uses hard-coded hex values; `global.css` has only the three `@tailwind` directives; no CSS variables, no `darkMode`, no theme switcher.+The mobile baseline (`apps/mobile/CLAUDE.md`) has named **react-native-reusables (RNR)** as the shadcn equivalent since SDK 55 was bootstrapped. RNR was never actually installed. As a result, at the time of writing:-This doc records why we are migrating to RNR, what alternatives we evaluated, and how the migration is sequenced.+- `apps/mobile/components/ui/` contained **21 hand-written components, ~1,379 lines**, all built from raw `<View/Text/Pressable/Modal>`. *(Still true — Phase 2/3 work.)*+- `apps/mobile/components/` contained **18 hand-written sheet/modal files**, all copying the same shape (`Modal transparent fade` + hand-drawn backdrop). CLAUDE.md Lesson 6 already documents that this pattern is wrong for most content and has produced a series of bugs (keyboard squashing, `maxHeight` clipping FlatLists, `useSafeAreaInsets` returning 0 inside `Modal`). *(Partly resolved — `sheet-shell.tsx` is deleted and long-list/form sheets are now Expo Router `formSheet` routes.)*+- There was no dark/light theming infrastructure: `tailwind.config.js` used hard-coded hex values, `global.css` had only the three `@tailwind` directives, and there were no CSS variables, no `darkMode`, and no theme switcher. **✅ Resolved in Phase 1** — `global.css` now defines `:root` / `.dark:root` variable blocks, `tailwind.config.js` sets `darkMode: "class"` with `hsl(var(--))` mappings, and Settings → Appearance switches Light / Dark / System.++This doc records why we migrated to RNR, what alternatives we evaluated, and how the migration is sequenced.## 2. Alternatives considered@@ -184,14 +186,14 @@ app/_layout.tsx reads persisted preference at startup,### 5.2 Token strategy-The current `tailwind.config.js` has hard-coded hex values for ~20 semantic tokens (`background`, `foreground`, `card`, `primary`, …). These become CSS variables under `:root` (light) and `.dark:root` (dark) in `global.css`. Tailwind config switches to `hsl(var(--background))` etc.+**Shipped in Phase 1.** The pre-Phase-1 `tailwind.config.js` carried hard-coded hex values for ~20 semantic tokens (`background`, `foreground`, `card`, `primary`, …). Those are now CSS variables under `:root` (light) and `.dark:root` (dark) in `global.css`, and the Tailwind config resolves them through `hsl(var(--background))` and friends.-Dark mode colors are not in the current config and need to be authored. Two options:+Dark-mode colours did not exist in the old config and had to be authored. Two options were considered:-1. **Use shadcn's neutral-base dark palette** (`--background: 0 0% 3.9%`, etc., per RNR's default install) — fastest, gets us a working dark mode immediately, may need a second pass for brand alignment.+1. **Use shadcn's neutral-base dark palette** (`--background: 0 0% 3.9%`, etc., per RNR's default install) — fastest, gets a working dark mode immediately, may need a second pass for brand alignment.2. **Author dark mode by hand** mirroring the web/desktop dark theme — slower, but stays visually consistent with desktop.-Phase 1 starts with **option 1** (shadcn default dark palette) for velocity. A later pass can tune to match desktop's `packages/ui/styles/tokens.css` dark theme once the infrastructure is proven.+Phase 1 took **option 1** (shadcn default dark palette) for velocity. A later pass can tune it to match desktop's `packages/ui/styles/tokens.css` dark theme now that the infrastructure is proven.Multica-specific tokens not in shadcn's default (`brand`, `brand-foreground`, `success`, `warning`, `info`, `priority`, `code-surface`) get their own CSS variables in both `:root` and `.dark:root`, mapped through `tailwind.config.js` the same way.@@ -211,36 +213,36 @@ When the user picks `system`, we call `setColorScheme('system')` (NativeWind v4- [x] Inspect current mobile state (`tailwind.config.js`, `global.css`, `app/_layout.tsx`, `metro.config.js`, `babel.config.js`)- [x] Update `apps/mobile/CLAUDE.md` with the new UI & theming rules- [x] Write this migration doc-- [ ] **User verification gate**+- [x] **User verification gate**-### Phase 1 — base infrastructure+### Phase 1 — base infrastructure — ✅ completeGoal: install RNR scaffolding without touching a single existing component. Verification = app builds and runs identically to before; theme switcher in settings works end-to-end.-Checklist:+Every item below shipped. The checklist is kept as the record of what Phase 1 covered:-1. **Add dependencies** (per RNR manual install Step 3):+1. ✅ **Add dependencies** (per RNR manual install Step 3):- `npx expo install tailwindcss-animate class-variance-authority clsx tailwind-merge @rn-primitives/portal`- Confirm `class-variance-authority`, `clsx`, `tailwind-merge`, `@rn-primitives/slot` are already present (they are) — only `tailwindcss-animate` and `@rn-primitives/portal` are new.-2. **Update `metro.config.js`** to set `inlineRem: 16` on `withNativeWind(...)`.-3. **Rewrite `global.css`** with `:root` and `.dark:root` CSS variable blocks (light + dark palettes including Multica's custom tokens).-4. **Rewrite `tailwind.config.js`** to use `hsl(var(--...))` mappings, set `darkMode: 'class'`, register `tailwindcss-animate` plugin, add `hairlineWidth()` border width. Keep mobile-specific overrides (`borderRadius`, custom tokens).-5. **Create `lib/theme.ts`** — TS mirror of CSS variables + `NAV_THEME` for React Navigation.-6. **Create `lib/use-color-scheme.ts`** — wraps NativeWind's `useColorScheme()`, loads/persists preference from `expo-secure-store` on mount, exposes `{ colorScheme, isDarkColorScheme, setColorScheme }`.-7. **Create `components.json`** with the standard RNR configuration (`style: "new-york"`, paths, aliases pointing at `@/components`, `@/lib/utils`).-8. **Update `app/_layout.tsx`**:+2. ✅ **Update `metro.config.js`** to set `inlineRem: 16` on `withNativeWind(...)`.+3. ✅ **Rewrite `global.css`** with `:root` and `.dark:root` CSS variable blocks (light + dark palettes including Multica's custom tokens).+4. ✅ **Rewrite `tailwind.config.js`** to use `hsl(var(--...))` mappings, set `darkMode: 'class'`, register `tailwindcss-animate` plugin, add `hairlineWidth()` border width. Keep mobile-specific overrides (`borderRadius`, custom tokens).+5. ✅ **Create `lib/theme.ts`** — TS mirror of CSS variables + `NAV_THEME` for React Navigation.+6. ✅ **Create `lib/use-color-scheme.ts`** — wraps NativeWind's `useColorScheme()`, loads/persists preference from `expo-secure-store` on mount, exposes `{ colorScheme, isDarkColorScheme, setColorScheme }`.+7. ✅ **Create `components.json`** with the standard RNR configuration (`style: "new-york"`, paths, aliases pointing at `@/components`, `@/lib/utils`).+8. ✅ **Update `app/_layout.tsx`**:- Read persisted theme preference (sync read from secure-store at module init or first effect; default `system`).- Apply it via `setColorScheme(...)` before children render.- Wrap `Stack` in `ThemeProvider(NAV_THEME[isDarkColorScheme ? 'dark' : 'light'])` from `@react-navigation/native`.- Mount `<PortalHost />` from `@rn-primitives/portal` as the last child of providers.-9. **Settings → Appearance picker**: add an "Appearance" `SectionGroup` to `app/(app)/[workspace]/more/settings.tsx` with three rows (Light / Dark / System), calling `setColorScheme(mode)` + persisting. UI mirrors the existing `WorkspaceRow` pattern; no new dependencies.-10. **Verify**: app builds; all existing screens render unchanged in light mode; toggle Dark → backgrounds invert + text inverts; toggle System → matches the simulator's OS appearance; kill app, reopen → preference persisted.+9. ✅ **Settings → Appearance picker**: add an "Appearance" `SectionGroup` to `app/(app)/[workspace]/more/settings.tsx` with three rows (Light / Dark / System), calling `setColorScheme(mode)` + persisting. UI mirrors the existing `WorkspaceRow` pattern; no new dependencies.+10. ✅ **Verify**: app builds; all existing screens render unchanged in light mode; toggle Dark → backgrounds invert + text inverts; toggle System → matches the simulator's OS appearance; kill app, reopen → preference persisted.**Phase 1 does NOT replace any existing component.** Buttons, inputs, sheets are still the hand-written versions. The dark mode "works" against the existing hex-derived semantic tokens because we are simply remapping them through CSS variables — the same `bg-background` class now resolves to a CSS variable that has two values instead of one.-**Risk**: components that style with hard-coded hex (e.g. `<Ionicons color="#71717a">`, `bg-[#fafafa]`) will not respond to theme change. Phase 1 includes a grep sweep for `#[0-9a-fA-F]{3,6}` in `components/` and `app/` — every hit is either (a) replaceable with a token now, or (b) flagged for Phase 3 with a `TODO(rnr-migration):` comment.+**Residual risk (carried into Phase 3)**: components that style with hard-coded hex (e.g. `<Ionicons color="#71717a">`, `bg-[#fafafa]`) do not respond to theme change. Phase 1 included a grep sweep for `#[0-9a-fA-F]{3,6}` in `components/` and `app/`; each hit was either replaced with a token or flagged for Phase 3 with a `TODO(rnr-migration):` comment.-### Phase 2 — first component (canary)+### Phase 2 — first component (canary) — not startedGoal: prove the migration mechanics on the simplest non-trivial component before doing 20 of them.diff --git a/docs/agent-quick-create-plan.md b/docs/agent-quick-create-plan.mddeleted file mode 100644index ad25f4647d..0000000000--- a/docs/agent-quick-create-plan.md+++ /dev/null@@ -1,555 +0,0 @@-# Agent 快速创建 — 三阶段实施计划--> Status: Draft (设计阶段,未动工)-> Owner: TBD-> Last updated: 2026-05-13--## TL;DR--- **目标**:降低用户创建 Agent 的门槛,从「手工填表 + 一个个挑 skill」演进到「一键模板」「AI 推荐 skill」「AI 直接创建 agent」三档-- **三阶段**:Template(必做、独立)→ Skill Finder(AI 推荐 skill)→ AI Create Agent(AI 直接创建)-- **架构关键**:Phase 2/3 复用现有 Quick-create Issue 基础设施(派任务给 agent + tool calling + inbox 通知),不引入新 LLM 调用路径-- **不需要新基础设施**:无 SSE、无 server-side LLM、无新 WS channel-- **soft blocker**:两处 routine 重构(`createSkillWithFiles` TX 拆分、skill 同名 find-or-create)-- **不做**:接入 Anthropic 官方 marketplace(plugin 体系跟单体 skill 形态不匹配)、接入 ClawHub(战略对位错误 + 实际使用率低,见 §5)-------## 1. 背景与目标--### 1.1 当前现状--当前用户创建一个 Agent 需要走的步骤:--1. 进 `/agents` 页面 → 点 "Create Agent"-2. 手工填 name / description / runtime / model-3. 手工写 instructions(空白文本框,用户自己思考措辞)-4. 创建完后进 Agent 详情页 → 点 "Add Skill" → 一个一个挑 skill 关联-5. 如果 workspace 还没有需要的 skill,得先去别处建/导入 skill(`POST /api/skills/import` 支持 skills.sh / GitHub / ClawHub 三种 URL)--**痛点**:-- 用户得**预先知道**自己需要哪些 skill,这要求他对 skill 生态熟悉-- 写 instructions 是空白文本编辑,大多数用户不知道写什么-- 跨多页操作,体感上"创建一个能用的 Agent"是个项目,不是个动作--### 1.2 三阶段方案--| Phase | 提供给用户的能力 | 是否需要 AI | 独立可发布 |-|---|---|---|---|-| **1. Template** | 选模板 → 自动 import 模板带的 skill + 预填 instructions | 否 | ✅ |-| **2. Skill Finder** | 描述需求 → AI 推荐 skill 列表 → 一键导入到 workspace | ✅ | ✅(独立功能,任何场景都能用) |-| **3. AI Create Agent** | 描述需求 → AI 自己 find skill + 写 instructions + 创建 agent | ✅ | 依赖 Phase 2 |--每个 phase **本身有用户价值**,不需要等下一个 phase 才能用:-- Phase 1 用户能用模板创建 agent,即使后两阶段没做-- Phase 2 用户能在任何地方"用 AI 找 skill"(创建 agent 时、给现有 agent 加 skill 时、单纯逛 skill 时)-- Phase 3 是 1+2 的组合--### 1.3 不在范围内--明确不做的事(及理由,见 §5):-- 接入 Anthropic 官方 plugin marketplace(`anthropics/claude-plugins-official`)-- 接入 ClawHub 的"发现/搜索"层(import 路径已经存在,但是死代码,建议下线)-- 让 AI 直接装 skill 到用户本地 `~/.claude/skills/`(npx skills CLI 行为)-- Server-side LLM 调用(后端目前没有 LLM SDK,这条路引入新基础设施,而 Quick-create 模式可以避开)-------## 2. 关键概念回顾--> 这一节给没参与前期讨论的同事看。已经熟悉 skill 系统的可跳到 §3。--### 2.1 Skill 是什么--Skill 是一个**按需加载的能力包**,本质是 SKILL.md 文件 + 可选附件。Anthropic 2025-12 把它发布为开放标准(agentskills.io),Cursor / OpenAI / GitHub Copilot 等都已采纳——同一份 SKILL.md 跨多个 agent 工具都能用。--每个 runtime(Claude Code / Cursor / Codex 等)启动时**自动扫**自己约定的目录(`~/.claude/skills/`、`.cursor/skills/` 等),读 SKILL.md 的 frontmatter 形成"我手上有这些 skill"的清单注入 system prompt。具体 skill 正文只在被触发时才进 context。--### 2.2 Multica 的 Skill 数据模型--3 张表(migration `008_structured_skills.up.sql`):--| 表 | 关键字段 |-|---|---|-| `skill` | `id, workspace_id, name, description, content (=SKILL.md 正文), config (含 origin 元数据)` |-| `skill_file` | `skill_id, path, content`(SKILL.md 的附件,如 examples/*.md、scripts/*.py) |-| `agent_skill` | `agent_id, skill_id`(M:N 关联) |--**关键约束**:`UNIQUE(workspace_id, name)` — 同 workspace 内 skill 名字必须唯一。--### 2.3 Skill 流转链路(数据库 → runtime)--任务运行时,skill 从 PG 到 runtime 的完整路径:--```-1. 数据库:skill + skill_file + agent_skill 三张表的行--2. Daemon claim 任务:- POST /api/runtimes/{runtimeId}/tasks/claim- handler/daemon.go:1018-1098 (ClaimTaskByRuntime)- → service/task.go:1447-1463 (LoadAgentSkills)- → 把 agent 关联的所有 skill 全文塞进 HTTP 响应--3. Daemon 算工作目录:- server/internal/daemon/execenv/execenv.go:114, 124- workDir = {WorkspacesRoot}/{wsID}/{shortTaskID}/workdir--4. Daemon 按 runtime 算 skill 目录:- server/internal/daemon/execenv/context.go:121-158 (resolveSkillsDir)- claude → {workDir}/.claude/skills- cursor → {workDir}/.cursor/skills- codex → 特殊:{codexHome}/skills--5. Daemon 把字符串写成磁盘文件:- context.go:175-204 (writeSkillFiles)- 核心就两行 os.WriteFile--6. Daemon 启动 runtime,cwd = workDir- runtime 自己扫 .claude/skills/(等)→ 加载 frontmatter--7. 任务结束:os.RemoveAll(workDir)- PG 是真相源,workDir 是每次任务临时复印件-```--**核心 invariant**:Multica 不教 runtime 怎么用 skill,只把文件摆到 runtime 已经会扫的位置。--### 2.4 Template = Instructions + Skill 引用--Template 是个**静态 JSON 定义**,包含:-- 预写好的 instructions-- 一组 skill 引用(用 URL 指向 skills.sh / GitHub)--用户选模板时,后端:-1. 对每个 skill 引用,**复用现有 `/api/skills/import` 的 fetcher**(`fetchFromSkillsSh` / `fetchFromGitHub`)拉内容-2. 物化到 workspace(同名复用 / 新建)-3. CreateAgent + setAgentSkills-4. 整个流程一个事务--skill 引用为什么用 URL 而不是内联 SKILL.md 内容:-- 复用现有 import 基础设施,零新代码-- skill 内容跟 GitHub 同步,不需要 vendoring 进 multica 仓库-- 模板 JSON 体积小,git review 友好--### 2.5 Quick-create Issue 模式(Phase 2/3 复用的基础设施)--当前 `POST /api/issues/quick-create`(handler/issue.go:877-982)的流程:--```-1. 后端 enqueue 任务:- - agent_task_queue 加一行,issue_id = NULL,context JSONB = {type: "quick-create", prompt: ...}- - 立即返回 202 Accepted + task_id--2. Daemon claim 任务时识别 quick-create:- - 检查 task.Context != nil AND !task.IssueID.Valid- - 解析为 QuickCreateContext (service/task.go:1810-1811)--3. Daemon 构造 prompt:- - daemon/prompt.go:45-106 (buildQuickCreatePrompt)- - 把用户的自然语言 prompt 作为语义核心- - 加上"调用 multica issue create CLI 命令"的指令--4. Agent 跑 LLM + tool calling:- - LLM 输出形如 `multica issue create --title="..." --description="..."` 的命令- - daemon 执行 CLI 命令,CLI 调 POST /api/issues 创建 issue- - CLI 自动在请求里带上 MULTICA_QUICK_CREATE_TASK_ID env(daemon/daemon.go:2081)- → 让创建出来的 issue 带 origin_type='quick_create' + origin_id=<task_id>--5. 后端 link + 通知:- - 完成检测:GetIssueByOrigin(workspace_id, "quick_create", task_id)- - LinkTaskToIssue(task_id, issue_id) 把任务行的 issue_id 补上- - 写 inbox_item 通知用户(notifyQuickCreateCompleted, service/task.go:1908-1920)-```--**关键洞察**:这个模式**完全通用化**了。复用它只需要:-1. 新的 context JSONB type(比如 `"skill-find"`、`"agent-create"`)-2. 新的 prompt builder-3. 新的"完成检测 + inbox 通知"--不需要任何 daemon / 任务队列层面的改动。-------## 3. 三阶段详细设计--### Phase 1:Agent Template--**目标**:用户选模板 → 一键得到一个可用的 agent(自带 skill + instructions),不需要 AI 参与。--#### 设计--- **Template 定义存放**:静态 JSON,commit 在 `server/internal/agenttmpl/templates/*.json`-- **Template JSON 形态**:- ```json- {- "slug": "code-reviewer",- "name": "Code Reviewer",- "description": "审代码用的 agent",- "instructions": "你审代码,关注 N+1 查询、错误处理、类型安全...",- "skills": [- { "source_url": "https://skills.sh/obra/superpowers/tdd" },- { "source_url": "https://github.com/foo/bar/tree/main/skills/code-style" }- ]- }- ```-- **新 endpoint**:`POST /api/agents/from-template`- - 请求:`{template_slug, name, runtime_id, ...overrides}`- - 后端流程(**全部在一个事务里**):- 1. 加载 template JSON- 2. 对每个 skill source_url:- - 调用 `detectImportSource(url)`(skill.go:586-617)分发到对应 fetcher- - 通过 GetSkillByWorkspaceAndName 检查 workspace 是否已有同名 skill- - 有 → 复用现有 skill_id- - 无 → 调 `createSkillWithFilesInTx`(待重构,见 §4)物化- 3. `CreateAgent`(复用 agent.go:CreateAgent 的内部逻辑)- 4. 批量 `AddAgentSkill` 关联- - 响应:`{agent: {...}, imported_skill_ids: [...], reused_skill_ids: [...]}`-- **前端**:`CreateAgentDialog`(packages/views/agents/components/create-agent-dialog.tsx)加 "From template" 模式,跟现有 manual / duplicate 模式并列- - 模板选择器 → 预览(instructions + skill 列表)→ 提交调新 endpoint- - 响应里的 `reused_skill_ids` 用 toast 提示"以下 skill 已存在,沿用了 workspace 现有版本"--#### 起步模板清单(初版,可调)--- `code-reviewer` — 代码审查-- `tdd-pair` — TDD 配对编程-- `db-reviewer` — 数据库 / SQL 审查-- `pr-summarizer` — PR 摘要-- `docs-writer` — 文档撰写--具体每个模板选哪些 skill URL,在 Phase 1 启动时单独决定(需要逛 skills.sh 选高质量 skill)。--#### Phase 1 改动清单--| 文件 / 位置 | 改动 |-|---|---|-| `server/internal/agenttmpl/`(新包) | 加载 JSON 模板的代码 |-| `server/internal/agenttmpl/templates/*.json`(新文件) | 5 个起步模板 |-| `server/internal/handler/agent.go` | 新 handler `CreateAgentFromTemplate` |-| `server/internal/handler/skill_create.go` | **重构**:拆出 `createSkillWithFilesInTx` 变体(见 §4) |-| `server/pkg/db/queries/skill.sql` | 加 `GetSkillByWorkspaceAndName`(见 §4) |-| `server/cmd/server/router.go` | 注册新 endpoint |-| `packages/views/agents/components/create-agent-dialog.tsx` | 加 template 模式 |-| `packages/core/api/agent.ts` | 加 `createAgentFromTemplate` API 调用 |-| `packages/views/agents/components/template-picker.tsx`(新文件) | 模板选择器组件 |--### Phase 2:Skill Finder--**目标**:用户用自然语言描述需求(如"我想审 SQL"),AI 推荐一组 skill,用户勾选一键导入到 workspace。--#### 设计--- **架构选型**:走 quick-create 模式,**不是后端直接调 LLM**-- **新 endpoint**:`POST /api/skills/find`- - 请求:`{prompt, agent_id}`(agent_id 是用来跑这个 LLM 任务的 agent,跟 Quick-create Issue 一样要求预先有 agent)- - 后端流程:- 1. enqueue 任务:`agent_task_queue` 加一行,context JSONB = `{type: "skill-find", prompt}`- 2. 返回 202 + task_id-- **Daemon prompt builder**:`daemon/prompt.go` 加 `buildSkillFindPrompt`(类比 buildQuickCreatePrompt)- - 喂给 agent 的 prompt 大致:- ```- 用户需求:{user_prompt}-- 你的任务:从以下 curated skill 清单里选 3-5 个最相关的推荐给用户。-- 可选 skill 清单(JSON):- {curated_skill_index}-- 输出:调用 `multica skill find --output-results '<JSON>'` 命令,- JSON 形态为 [{name, description, source_url, reason}, ...]- ```-- **CLI 命令**(新):`multica skill find --output-results <JSON>`- - 不发起 HTTP 请求,只把 JSON 写到 daemon 通过 env 指定的临时文件- - daemon 读这个文件,把内容塞进 inbox notification 的 payload-- **Curated skill 索引**:`server/internal/agenttmpl/skill_index.json`(新文件)- - 几十到上百条精选 skill,每条:`{name, description, source_url, tags, install_count}`- - 维护方式:工程师/产品手工维护,代码 review 卡内容质量- - MVP **不做**实时 GitHub Code Search 或 skills.sh 爬虫-- **完成通知**:写 inbox_item,type = `skill_find_done`,payload 含推荐结果数组-- **前端**:- - 独立"Find Skill"页面(`/skills/find` 或 `/skills?ai=true`)- - skill list page 上"用 AI 找 skill"按钮入口- - 用户输入 prompt → 提交 → 等通知 → inbox item 里展示 skill 卡片(name + description + source_url + reason)- - 用户勾选 → 一键批量调现有 `POST /api/skills/import`(每个 skill 一次,可考虑加 batch endpoint 但 MVP 不必要)--#### Phase 2 改动清单--| 文件 / 位置 | 改动 |-|---|---|-| `server/internal/handler/skill.go` | 新 handler `FindSkill`(enqueue task) |-| `server/internal/service/task.go` | 加 `EnqueueSkillFindTask` + 完成检测 + inbox 通知 |-| `server/internal/daemon/prompt.go` | 加 `buildSkillFindPrompt` |-| `server/internal/daemon/daemon.go` | 加 `SkillFindContext` 识别 + env 注入 |-| `server/cmd/multica/cmd_skill.go` | 加 `find --output-results` 子命令 |-| `server/internal/agenttmpl/skill_index.json`(新文件) | curated 清单 |-| `packages/views/skills/components/find-skills-dialog.tsx`(新文件) | UI |-| `packages/core/api/skill.ts` | 加 `findSkills` API |-| `packages/views/inbox/items/skill-find-result.tsx`(新文件) | inbox item 渲染 |--### Phase 3:AI Create Agent--**目标**:用户描述需求,AI 自己 find skill + 写 instructions + 创建 agent。--#### 设计--- **架构选型**:走 quick-create 模式,**组合 Phase 2 的 find 能力 + 新的 agent create CLI**-- **新 endpoint**:`POST /api/agents/ai-draft`- - 请求:`{prompt, host_agent_id}`(host_agent_id 是跑这个元任务的 agent)- - 后端:enqueue 任务,context = `{type: "agent-create", prompt}`,返回 202 + task_id-- **Daemon prompt builder**:`buildAgentCreatePrompt` 指挥 agent 三步走:- ```- 1. 调用 `multica skill find --output-results ...` 选 skill- (或直接看 curated 清单选)- 2. 基于选定 skill 写 instructions- 3. 调用 `multica agent create --name ... --instructions ... --skill-ids ...`- 创建 agent 并关联 skill- ```-- **CLI 命令**(新):`multica agent create`- - 后端 handler 已存在(handler/agent.go:CreateAgent),只需要绑 CLI(~50 行)- - 创建时带 `MULTICA_AI_DRAFT_TASK_ID` env,服务端用它做 origin 标记 + LinkTaskToAgent-- **完成通知**:inbox_item type = `agent_draft_done`,payload 含 agent_id + 摘要-- **前端**:`CreateAgentDialog` 加 "AI" 模式- - 输入需求 → 提交 → 等通知 → inbox 通知里点击 → 跳新 agent 详情页(用户在那儿编辑/调整)--#### Phase 3 改动清单--| 文件 / 位置 | 改动 |-|---|---|-| `server/internal/handler/agent.go` | 新 handler `AIDraftAgent`(enqueue task) |-| `server/internal/service/task.go` | 加 `EnqueueAgentDraftTask` + 完成检测 + inbox 通知 |-| `server/internal/daemon/prompt.go` | 加 `buildAgentCreatePrompt` |-| `server/cmd/multica/cmd_agent.go` | 加 `create` 子命令(handler 已有) |-| `packages/views/agents/components/create-agent-dialog.tsx` | 加 "AI" 模式 |-| `packages/core/api/agent.ts` | 加 `aiDraftAgent` API |-| `packages/views/inbox/items/agent-draft-result.tsx`(新文件) | inbox item 渲染 |-------## 4. Blocker 清单与修复方案--### 4.1 [SOFT] `createSkillWithFiles` 不可组合事务--**问题**:`server/internal/handler/skill_create.go:21-71` 这个函数自己 `Begin()` 一个事务,执行完 `Commit()`。Phase 1 需要在外层事务里**多次**调用它(import N 个 skill + createAgent + setAgentSkills 都在一个 TX),但现在没法这么用。--**影响范围**:Phase 1--**修复方案**:--```go-// 拆成两个函数(保持原 API 向后兼容):--// 新增:接受外部 qtx,不管事务-func createSkillWithFilesInTx(- ctx context.Context,- qtx *db.Queries,- input skillCreateInput,-) (*SkillWithFilesResponse, error) {- // 不 Begin/Commit,只调 qtx.CreateSkill + qtx.UpsertSkillFile loop-}--// 改造:原函数变成包装层,内部调 InTx 版-func (h *Handler) createSkillWithFiles(- ctx context.Context,- input skillCreateInput,-) (*SkillWithFilesResponse, error) {- tx, _ := h.TxStarter.Begin(ctx)- defer tx.Rollback()- qtx := h.Queries.WithTx(tx)- result, err := createSkillWithFilesInTx(ctx, qtx, input)- if err != nil { return nil, err }- tx.Commit()- return result, nil-}-```--旧调用方完全不变。Phase 1 新 endpoint 自己 Begin,然后多次调 `*InTx` 变体,最后统一 Commit。--**工作量**:小(< 100 行重构)--### 4.2 [SOFT] Skill 同名冲突--**问题**:`skill` 表有 `UNIQUE(workspace_id, name)` 约束。Phase 1 模板导入时,如果模板里的 skill 跟 workspace 已有 skill 同名,INSERT 会报 PG 错误 23505,整个 from-template 流程挂掉。--**影响范围**:Phase 1--**修复方案**:加 find-or-create 模式:--1. 新 query `GetSkillByWorkspaceAndName`(`server/pkg/db/queries/skill.sql`)-2. Phase 1 流程改成:- - 对每个模板 skill,先查 workspace 是否已有同名- - 有 → 复用现有 skill_id,跳过 import- - 无 → 调 `createSkillWithFilesInTx` 物化-3. 响应里返回 `reused_skill_ids: [...]`,前端 toast "以下 skill 已存在,沿用现有版本"--**不选择"覆盖"或"加后缀"的原因**:用户可能已经改过本地版本,覆盖会丢用户修改;加后缀污染 skill 列表。--**工作量**:小(< 50 行 + 1 条 sqlc query)--### 4.3 [SOFT] 缺 `multica skill find` CLI--**影响范围**:Phase 2--**方案**:加一个 CLI 子命令,模仿 `multica skill import` 的实现(`server/cmd/multica/cmd_skill.go:55-60, 323-357`)。**注意**:这个命令不发 HTTP 请求,只是 LLM agent 用来"输出推荐结果"的 channel——它把 LLM 推荐的 JSON 写到 daemon 指定的临时文件,daemon 读完塞进 inbox notification。--**工作量**:小(~80 行)--### 4.4 [SOFT] 缺 `multica agent create` CLI--**影响范围**:Phase 3--**方案**:后端 handler 已有(`handler/agent.go:CreateAgent`),只需在 `server/cmd/multica/cmd_agent.go` 加 `create` 子命令。--**工作量**:小(~50 行)--### 4.5 [非 blocker] System Agent 问题--**之前误判为 hard blocker,实际不是**:--Quick-create Issue 当前的设计就要求用户**预先有一个 agent** 才能用——AI 路径不为"零 agent 起步"服务。Phase 2/3 沿用这个前提,所以**新 workspace 没 agent 时 AI 功能不可用**是符合现有产品模型的,不需要 bootstrap 一个 system agent。--产品自然解锁路径:-1. 新用户进 workspace-2. 用 **Phase 1 Template**(无需 AI、无需现有 agent)创建第一个 agent-3. 之后 Phase 2/3 即可用,host_agent 就用刚创建的那个-------## 5. 关键设计决策(及理由)--### 5.1 为什么不接 Anthropic 官方 marketplace?--**结构错配**。Anthropic 官方 marketplace(`anthropics/claude-plugins-official`)是 **plugin 体系**:每个 plugin 是个 bundle,包含 `.claude-plugin/plugin.json` + `skills/` + `agents/` + `hooks/` + `.mcp.json`。--Multica 只有**单体 skill**(SKILL.md + skill_file),没有 plugin / bundle 概念。要接入得新写 plugin parser + 拆分逻辑,工作量大,而 skills.sh 已经覆盖了同一批高质量内容(skills.sh 后端就是 GitHub raw,绝大多数 skill 作者就在 GitHub 上,Anthropic plugin 体系里的 skill 通常也在作者的 GitHub repo 里有单体副本)。--### 5.2 为什么走 quick-create 模式而不是后端直接调 LLM?--代码事实:`server/` 目前**完全没有任何 LLM SDK**(grep `anthropic-sdk-go` / `openai-go` / 任何 LLM provider 都是 0 命中)。所有 LLM 调用都通过 daemon → runtime → CLI 这条路。--走 quick-create 模式的优势:-- **不引入新基础设施**(SSE / LLM client / API key 管理)-- **复用 agent 的 instructions / model / runtime 配置**(用户已经在某个 agent 里配置过的偏好自动生效)-- **统一计费 / 用量监控**(LLM 调用都计在用户 agent 的 quota 里)--代价:-- 用户得**预先有一个 agent**(参见 §4.5,这跟 Quick-create Issue 现状一致)-- LLM 调用通过 daemon 多一跳,延迟略增(但不阻塞 202 响应)--### 5.3 为什么 Skill Finder 是 endpoint 不是 SKILL.md?--**Skill Finder 名字里的 "Skill" 是它的产物(找的是 skill),不是它自己实现成 SKILL.md**。--如果做成 SKILL.md 文件:-- 它得装进某个 agent 里才能用 → 单点功能变得需要前置配置-- skill 教 agent 调什么?调 `npx skills`(装到本地,目标错)?调 Multica API(那要写 tool channel,绕一大圈)-- AI 创建 Agent(Phase 3)那条路要"启动 agent → agent 调 skill → skill 调 tool",链路复杂三倍--做成 endpoint:-- 用户独立可用(独立 UI 入口)-- AI 创建 Agent 后端直接调 endpoint,两个功能共用一段逻辑-- 简单--### 5.4 Curated Skill 索引 vs 实时搜索--**MVP 用 curated 清单**(几十条精选 URL + 摘要 commit 在 repo 里)。理由:-- 质量可控-- 不踩 GitHub Code Search rate limit-- 不被 LLM 编 URL(LLM 知识 cutoff + hallucinate URL 是真问题)-- 维护成本低--进阶可加 `search_skills(query)` tool 实时打 GitHub Code Search,等用户反馈"清单太窄"再做。--### 5.5 不做 ClawHub(顺手清理建议)--**现状**:`POST /api/skills/import` 当前支持 3 个 source(`fetchFromClawHub` skill.go:642-744、`fetchFromSkillsSh` skill.go:757-879、`fetchFromGitHub` skill.go:1363-1463)。ClawHub 是个独立 HTTP 客户端,不复用 GitHub 基础设施。--**判断**(详见之前讨论):-- ClawHub 服务的是 OpenClaw 平台(Multica 同生态位竞品的内容生态)-- UI 没有发现/搜索层,用户只能粘 URL,而 ClawHub 装机量远低于 skills.sh,用户主动逛的概率极低-- 独立代码路径,API 演进时单独跟进--**建议**(独立于本计划,可以一起做也可以延后):-- 跑 `SELECT count(*) FROM skill WHERE config->'origin'->>'type' = 'clawhub'` 看实际使用量-- 接近 0 → 渐进下线(先去 UI SourceCard,后续 release 删 fetcher)-- 有量 → 留着,但仍不为它做新功能-------## 6. 实施依赖与排期--```-[Phase 1] Template- └── 独立,无依赖- └── 包含 2 个 soft blocker 的修复(§4.1 §4.2)- ↓-[Phase 2] Skill Finder- └── 依赖 Phase 1 中的 skill import 路径(已存在,沿用)- └── 含 1 个 soft blocker(§4.3)- ↓-[Phase 3] AI Create Agent- └── 依赖 Phase 2(复用 find skill 能力)- └── 含 1 个 soft blocker(§4.4)-```--**真实排期建议**:-- Phase 1 可单独发版,有独立价值-- Phase 2 独立可发版(找 skill 是高频独立场景)-- Phase 3 等 Phase 2 ready 后开始--每个 phase 启动时单独开 PR 设计 doc,本文档只是路线图。-------## 7. 风险与缓解--| 风险 | 缓解 |-|---|---|-| GitHub rate limit(模板 import 多个 skill 时) | 已有 `GITHUB_TOKEN` env 支持(skill.go:1163-1166),5000/h 配额够用。生产环境确保配置 |-| 模板里引用的 skill repo 被作者删除 | from-template handler 容错:某个 skill fetch 失败 → 整个事务回滚,前端展示具体哪个 URL 挂了。模板自己也定期 review |-| LLM 推荐编造 URL(Phase 2) | 用 curated 清单作为 context,**不让 LLM 自由发挥 URL**,推荐范围限定在清单内 |-| Phase 3 LLM 写出离谱 instructions | 用户在 inbox 通知里点击 → 跳新 agent 详情页**编辑模式**,不直接进入"已就绪"状态。用户必须确认 |-| 模板格式后续要演进(加字段) | Template JSON 加 `version` 字段,后端按 version 兼容老格式 |-| Curated skill 清单过时(作者改 repo / 删 skill) | 加 CI 任务定期跑一遍清单 URL,挂掉的报警通知维护者 |-------## 8. 不在本文档范围(已识别的下一步话题)--- 跨 workspace 模板共享 / marketplace 化(用户能把自己的 agent 存成模板分享)-- 实时 GitHub Code Search tool(Phase 2 进阶)-- Server-side LLM 调用基础设施(如果未来需要 streaming 等场景)-- ClawHub 下线决策(独立讨论,见 §5.5)-- Skill 版本管理(workspace skill 版本号 / 升级提示)-------## 附录 A:代码索引--> 给接手开发的同事的快速参考。每条 file:line 都在本计划里被引用过,记录在这里方便跳转。--| 主题 | 位置 |-|---|---|-| Skill DB 模型 | `server/migrations/008_structured_skills.up.sql:4-32` |-| Skill 创建 handler + 事务 | `server/internal/handler/skill.go:143-162` + `skill_create.go:21-71` |-| Skill import 入口(支持 3 个 source) | `server/internal/handler/skill.go:1538` |-| Skill import source 分发 | `server/internal/handler/skill.go:586-617` (`detectImportSource`) |-| Skills.sh fetcher | `server/internal/handler/skill.go:757-879` (`fetchFromSkillsSh`) |-| GitHub fetcher | `server/internal/handler/skill.go:1363-1463` (`fetchFromGitHub`) |-| ClawHub fetcher | `server/internal/handler/skill.go:642-744` (`fetchFromClawHub`) |-| Agent 创建 handler | `server/internal/handler/agent.go:380-399` (request) + `:422-564` (CreateAgent) |-| Agent 创建 sqlc | `server/pkg/db/queries/agent.sql:19-25` |-| Agent-Skill 关联 sqlc | `server/pkg/db/queries/agent.sql:86-103` |-| 当前 Agent Duplication(前端模式) | `packages/views/agents/components/agents-page.tsx:286-301`(post-create skill copy) |-| Agent 创建 dialog | `packages/views/agents/components/create-agent-dialog.tsx` |-| Skill add dialog | `packages/views/agents/components/skill-add-dialog.tsx` |-| Quick-create Issue handler | `server/internal/handler/issue.go:877-982` (`QuickCreateIssue`) |-| Quick-create task enqueue | `server/internal/service/task.go:488+` (`EnqueueQuickCreateTask`) |-| Daemon claim + load skills | `server/internal/handler/daemon.go:1018-1098` + `service/task.go:1447-1463` |-| Daemon prompt build | `server/internal/daemon/prompt.go:17-36` (dispatch) + `:45-106` (`buildQuickCreatePrompt`) |-| Daemon execenv prepare | `server/internal/daemon/execenv/execenv.go:103-176` |-| Skill 目录约定(runtime mapping) | `server/internal/daemon/execenv/context.go:121-158` (`resolveSkillsDir`) |-| Skill 文件落盘 | `server/internal/daemon/execenv/context.go:175-204` (`writeSkillFiles`) |-| Quick-create 完成检测 + inbox | `server/internal/service/task.go:1810-1949` |-| LinkTaskToIssue | `server/internal/handler/agent.go:97-105` |-| Quick-create Issue 前端 modal | `packages/views/modals/quick-create-issue.tsx:48-570+` |-| Multica CLI 入口 | `server/cmd/multica/main.go:62-79` |-| Skill CLI 命令 | `server/cmd/multica/cmd_skill.go:17-96`(已有 import,无 find) |-| Agent CLI 命令 | `server/cmd/multica/cmd_agent.go:101-112`(已有 list/get,无 create) |diff --git a/docs/analytics.md b/docs/analytics.mddeleted file mode 100644index 70e15afc65..0000000000--- a/docs/analytics.md+++ /dev/null@@ -1,840 +0,0 @@-# Product Analytics--Multica's product analytics live in the **operational database** and in-**Prometheus / Grafana**. This document is the catalogue of instrumentation and-its history.--See [MUL-1122](https://github.com/multica-ai/multica) for the original design-context and [MUL-4127](https://github.com/multica-ai/multica) for the PostHog-retirement below.--> **MUL-4127 — PostHog retired for product analytics.** PostHog had become a-> chaotic, largely-unused second copy of data we already query from the DB, so-> the redundant instrumentation was removed:->-> - **Every server-side event is now Prometheus-only.** `signup`,-> `workspace_created`, `issue_created`, `issue_executed`, `chat_message_sent`,-> `team_invite_sent` / `team_invite_accepted`, `onboarding_started` /-> `onboarding_questionnaire_submitted` / `onboarding_completed`,-> `agent_created`, `cloud_waitlist_joined`, `feedback_submitted`,-> `contact_sales_submitted`, `squad_created`, `autopilot_created` — all are-> now flagged by `analytics.IsMetricsOnly`, so `metrics.RecordEvent`-> increments the Grafana counter but no longer ships to PostHog. The-> `analytics.*` event constructors are retained solely to drive those-> Prometheus counters; the underlying DB rows remain the source of truth. The-> runtime lifecycle (`runtime_*`), autopilot run lifecycle-> (`autopilot_run_*`), and `agent_task_*` were already Prometheus-only.-> - **The frontend funnel instrumentation was removed**: `$pageview`,-> `download_intent_expressed` / `download_page_viewed` / `download_initiated`,-> the frontend `onboarding_started` mirror, `onboarding_runtime_path_selected`,-> `onboarding_runtime_detected`, `feedback_opened`, and the-> `source_backfill_*` events.-> - **What still ships to PostHog (frontend only):** `$exception` autocapture-> (with `before_send` redaction + dedupe) and the desktop stability events-> `client_crash` / `client_unresponsive` — error / crash monitoring that has-> no DB equivalent. Identity (`$identify` / `$set`) is retained only to attach-> those.-> - The `multica_signup_source` attribution cookie (`captureSignupSource`,-> independent of `$pageview`) is kept: it still feeds the `signup_source`-> Prometheus label. Persisting the raw source-channel / country to the DB —-> the one signal PostHog uniquely held — is tracked separately.->-> The per-event sections below document the historical shapes for reference; the-> server events still describe the `analytics.Event` that drives the Prometheus-> counter, just no longer a PostHog contract.--## Configuration--All analytics shipping is toggled by environment variables (see `.env.example`):--| Variable | Meaning | Default |-|---|---|---|-| `POSTHOG_API_KEY` | PostHog project API key. Empty = no events are shipped. | `""` |-| `POSTHOG_HOST` | PostHog host (US or EU cloud, or self-hosted URL). | `https://us.i.posthog.com` |-| `ANALYTICS_ENVIRONMENT` | Optional override for the standard `environment` event property. Normalized to `production`, `staging`, or `dev`; defaults from `APP_ENV`. | `APP_ENV` / `dev` |-| `ANALYTICS_DISABLED` | Set to `true`/`1` to force the no-op client even when `POSTHOG_API_KEY` is set. | `""` |--Local dev and self-hosted instances run with `POSTHOG_API_KEY=""`, so **no-events leave the process unless the operator explicitly opts in**.--### Self-hosted instances--Self-hosters should **never inherit a Multica-issued `POSTHOG_API_KEY`** —-that would route their users' behavior to our analytics project. The-defaults guarantee this:--- `.env.example` ships `POSTHOG_API_KEY=` empty. The Docker self-host- compose does not set a default either.-- With the key unset, `NewFromEnv` returns `NoopClient` and logs- `analytics: POSTHOG_API_KEY not set, using noop client` at startup — a- visible confirmation that nothing is shipped.-- Operators who want their own analytics can set `POSTHOG_API_KEY` and- `POSTHOG_HOST` to point at their own PostHog project (Cloud or- self-hosted PostHog).-- The frontend receives the key via `/api/config` (planned for PR 2), so- self-hosts' blank server config also disables frontend event shipping- automatically — no separate frontend opt-out plumbing required.--## Architecture--```-handler → analytics.Client.Capture(Event) ← non-blocking, returns immediately- │- ▼- bounded queue (1024 events)- │- ▼- background worker: batch + POST /batch/- │- ▼- PostHog-```--- `analytics.Capture` is **never allowed to block a request handler**. A- broken backend must not degrade the product — when the queue is full,- events are dropped and counted (visible via `slog` + the `dropped` counter- on shutdown).-- Batches flush either when `BatchSize` is reached or every `FlushEvery`- (default 10 s), whichever comes first.-- `Close()` drains remaining events during graceful shutdown. Called from- `server/cmd/server/main.go` via `defer`.--## Identity model--- **`distinct_id`** — always the user's UUID for logged-in events. The- frontend's `posthog.identify(user.id)` merges any prior anonymous events- under the same identity, so acquisition attribution (UTM / referrer) stays- intact across signup.-- **`workspace_id`** — added to every event as a property when present. v1- uses event property filtering (free tier) rather than PostHog Groups- Analytics (paid) to compute workspace-level metrics.-- **PII** — events carry `email_domain` (e.g. `gmail.com`), not the full- email. Full email is stored once in person properties via `$set_once` so- it's available for individual debugging but not broadcast with every- event.-- **Person properties (`$set`)** — use for mutable cohort signals- (role, use_case, team_size, platform_preference) that a user can- legitimately change during onboarding. `Event.Set` on the backend- maps to `$set`; the frontend helper is- `setPersonProperties()` in `@multica/core/analytics`. Use- `$set_once` only for values that must never be overwritten (email,- initial attribution, first-completion timestamp).--## Taxonomy (historical)--These categories described the PostHog dashboards each event once fed. After-MUL-4127 those dashboards are retired: server events are Prometheus-only (DB is-the source of truth) and the frontend funnel events were deleted. The `Status`-column records where each event stands now.--| Category | Events | Status after MUL-4127 |-|---|---|---|-| `core_loop` | `workspace_created`, `agent_created`, `issue_created`, `chat_message_sent`, `issue_executed`, `autopilot_created`, `squad_created` | Prometheus-only |-| `onboarding_support` (server) | `onboarding_started`, `onboarding_questionnaire_submitted`, `onboarding_completed` | Prometheus-only |-| `onboarding_support` (frontend) | frontend `onboarding_started` mirror, `onboarding_runtime_path_selected`, `onboarding_runtime_detected` | **Removed** |-| `acquisition` (server) | `signup`, `cloud_waitlist_joined`, `contact_sales_submitted` | Prometheus-only |-| `acquisition` (frontend) | `download_intent_expressed`, `download_page_viewed`, `download_initiated` | **Removed** |-| `ops_feedback` | `feedback_submitted` (server), `feedback_opened` (frontend) | server → Prometheus-only; frontend **removed** |-| `attribution backfill` (frontend) | `source_backfill_shown` / `_submitted` / `_skipped` / `_dismissed` | **Removed** (modal kept; PATCHes DB) |-| **still in PostHog (frontend only)** | `$exception`, `client_crash`, `client_unresponsive`, `$identify`, `$set` | **Shipped** |-| `operational` (already Prometheus-only) | `runtime_registered/ready/failed/offline`, `agent_task_*`, `autopilot_run_started/completed/failed` | Prometheus-only |--The v0 core dashboard must use only `core_loop` plus the specific-`onboarding_support` steps used by the activation funnel. Acquisition,-feedback, and system/noise events stay in separate dashboards. The-`operational` row is **not shipped to PostHog** — those signals live in-Grafana via `multica_*` business counters (see `server/internal/metrics`).--## Standard core properties--Canonical core events should carry these properties whenever the entity exists:--| Property | Type | Notes |-|---|---|---|-| `environment` | string | `production` / `staging` / `dev`; stamped by backend and frontend analytics clients. |-| `event_schema_version` | int | Current version: `2`. |-| `user_id` | string UUID | Human user ID when known. Agent/system events may omit it. |-| `workspace_id` | string UUID | Required for workspace-scoped events. |-| `agent_id` | string UUID | Required for agent/task events. |-| `task_id` | string UUID | Required for `agent_task_*` events. |-| `issue_id` / `chat_session_id` / `autopilot_run_id` | string UUID | Relevant source entity for the task/entry event. |-| `source` | string | Canonical values: `onboarding`, `manual`, `chat`, `autopilot`, `api`. UI surface details use `surface` or `trigger_source`. |-| `runtime_mode` | string | `cloud` / `local` when a runtime/agent task is involved. |-| `provider` | string | `claude`, `codex`, `cursor`, etc. when a runtime/agent task is involved. |-| `is_demo` | bool | Currently always `false`; reserved for future demo/test workspace filtering. |--Task terminal events additionally carry `duration_ms`; failures carry-`failure_reason`, `error_type`, and `will_retry`. Runtime failure events carry-`recoverable`; runtime ready events carry `runtime_id`, `ready_duration_ms`-only when it is actually measured, and `daemon_id` for local runtimes.--Schema v2 is the first canonical core-metrics schema. It replaces early v1-drafts that mirrored `failure_reason` into `error_type`, used `recoverable`-for task/autopilot failures, and emitted `ready_duration_ms: 0` before the-registration path had a measured duration.--## Event contract--### `signup`--Fires when a new user is created. Covers both verification-code and Google-OAuth entry points (`findOrCreateUser` is the single emission site).--| Property | Type | Description |-|---|---|---|-| `email_domain` | string | Lower-cased domain portion of the user's email. |-| `signup_source` | string | Opaque attribution bundle from the frontend cookie `multica_signup_source` (UTM + referrer). Empty when the cookie is absent. |-| `auth_method` | string | Optional. `"google"` for Google OAuth signups. Absent for verification-code signups. |--Historical PostHog person properties (`$set_once`) — **no longer emitted** since-MUL-4127, because `signup` is now Prometheus-only and never reaches PostHog:--| Property | Type | Description |-|---|---|---|-| `email` | string | Full email. Was never broadcast per-event. |-| `signup_source` | string | Attribution bundle. Today only its bucketed form survives, as the `multica_signup_total{signup_source}` Prometheus label (see `NormalizeSignupSource`); it is no longer set as a person property for segmentation. |--### `workspace_created`--Fires after a `CreateWorkspace` transaction commits successfully.--| Property | Type | Description |-|---|---|---|-| `workspace_id` | string (UUID) | Added globally; present here for clarity. |--**Note on "first workspace" segmentation** — we deliberately do *not* stamp-an `is_first_workspace` boolean at emit time. Computing it correctly would-require an extra column or transaction-scoped logic that still races under-concurrent creates. Instead, PostHog answers the same question exactly by-looking at whether the user has a prior `workspace_created` event (use a-funnel with "first time user does X" or a cohort on-`person_properties.$initial_event`). No information is lost.--### `runtime_registered`--> **Prometheus-only — not shipped to PostHog** (see the note at the top of this-> doc). The `analytics.Event` is still constructed so `metrics.IncForEvent` can-> derive the Prometheus counter; the fields below are that **event** shape, not-> a PostHog contract. Only the low-cardinality fields (`runtime_mode`,-> `provider`) become Prometheus labels — ids like `runtime_id` / `daemon_id`-> are not labels.--Fires the first time a `(workspace_id, daemon_id, provider)` tuple is-upserted. Heartbeats and repeat registrations never re-emit. First-time-detection uses Postgres `xmax = 0` on the upsert RETURNING clause — no-extra query, no race.--| Property | Type | Description |-|---|---|---|-| `runtime_id` | string (UUID) | The newly created agent_runtime row id. |-| `daemon_id` | string | Local daemon identity when available. |-| `runtime_mode` | string | Currently `local`; reserved for cloud runtimes. |-| `provider` | string | e.g. `"codex"`, `"claude"`. |-| `runtime_version` | string | Version of the agent runtime binary. |-| `cli_version` | string | Version of the `multica` CLI that registered it. |--`distinct_id` is the authenticated owner's user id when the daemon was-registered via a member's JWT/PAT; daemon-token registrations fall back to-`workspace:<workspace_id>` so PostHog doesn't bucket unrelated daemons-under a single "anonymous" person.--### `runtime_ready`--> **Prometheus-only — not shipped to PostHog.**--Fires when a runtime is first registered in an online/ready state. This is the-activation-funnel step that should replace treating `runtime_registered` as-proof of readiness. The backend emits this only on the INSERT path for a new-`agent_runtime` row; ordinary daemon reconnects update the existing row and do-not emit another `runtime_ready`. Dashboard funnels should still count-distinct `runtime_id`.--| Property | Type | Description |-|---|---|---|-| `runtime_id` | string (UUID) | The `agent_runtime` row id. |-| `daemon_id` | string | Local daemon identity when available. |-| `ready_duration_ms` | int64 | Optional. Time from registration start to ready; omitted until the registration path can measure it. |-| `runtime_mode` | string | `local` / `cloud`. |-| `provider` | string | Runtime provider. |--### `runtime_failed`--> **Prometheus-only — not shipped to PostHog.**--Fires when runtime setup/registration fails before a ready runtime can be-recorded. Today this is scoped to backend registration persistence failures;-future setup flows should reuse it for provider detection or daemon boot-failures.--| Property | Type | Description |-|---|---|---|-| `daemon_id` | string | Local daemon identity when available. |-| `provider` | string | Runtime provider attempted. |-| `failure_reason` | string | Stable coarse reason. |-| `error_type` | string | Stable error classifier. |-| `recoverable` | bool | Whether retrying setup may succeed. |--### `runtime_offline`--> **Prometheus-only — not shipped to PostHog.**--Fires when a runtime is explicitly deregistered or the backend sweeper marks it-offline after missed heartbeats. This is not an activation step; it supports-local runtime retention and drop-off diagnosis.--### `issue_created`--Fires after an issue row is created, including manual UI/API issue creation,-quick-create issue creation by an agent, and autopilot `create_issue` runs.--| Property | Type | Description |-|---|---|---|-| `issue_id` | string (UUID) | Created issue. |-| `agent_id` | string (UUID) | Agent assignee or creating agent when applicable. |-| `task_id` | string (UUID) | Present for quick-create issue creation. |-| `autopilot_run_id` | string (UUID) | Present for autopilot-created issues. |-| `source` | string | `manual`, `api`, or `autopilot`. |--### `chat_message_sent`--Fires after a user chat message is persisted and the corresponding agent task-is queued.--| Property | Type | Description |-|---|---|---|-| `chat_session_id` | string (UUID) | Chat session. |-| `task_id` | string (UUID) | Queued agent task. |-| `agent_id` | string (UUID) | Chat agent. |-| `source` | string | Always `chat`. |--### agent task lifecycle (Prometheus-only)--> **Not shipped to PostHog and has no `analytics.Event`.** The agent task-> lifecycle is recorded directly to Prometheus by the typed-> `BusinessMetrics.RecordTask*` methods in `server/internal/service/task.go`.-> The old PostHog event names (`agent_task_queued` / `dispatched` / `started` /-> `completed` / `failed` / `cancelled`) and their properties (`task_id`,-> `agent_id`, `issue_id`, `chat_session_id`, `autopilot_run_id`, `duration_ms`,-> `error_type`, `will_retry`) no longer exist anywhere — those high-cardinality-> ids were never Prometheus labels and must not be used in dashboards or-> reconciliation.--The actual metrics (defined in `server/internal/metrics/business.go`; label-sets in `server/internal/metrics/labels.go`):--| Metric | Type | Labels |-|---|---|---|-| `multica_agent_task_enqueued_total` | counter | `source`, `runtime_mode` |-| `multica_agent_task_dispatched_total` | counter | `source`, `runtime_mode` |-| `multica_agent_task_started_total` | counter | `source`, `runtime_mode`, `provider` |-| `multica_agent_task_terminal_total` | counter | `source`, `runtime_mode`, `terminal_status` |-| `multica_agent_task_failed_total` | counter | `source`, `runtime_mode`, `failure_reason` |-| `multica_agent_task_queue_wait_seconds` | histogram | `source`, `runtime_mode` |-| `multica_agent_task_run_seconds` | histogram | `source`, `runtime_mode`, `terminal_status` |-| `multica_agent_task_total_seconds` | histogram | `source`, `runtime_mode`, `terminal_status` |--- `terminal_status` is the task's final `agent_task_queue.status` —- `completed` / `failed` / `cancelled`. There is **no** separate- completed/cancelled metric: all three land on- `multica_agent_task_terminal_total{terminal_status=…}`. Failures- additionally increment `multica_agent_task_failed_total` carrying the coarse- `failure_reason` (`agent_task_queue.failure_reason`, default `agent_error`).-- Task wall-clock lives in the `*_seconds` histograms (queue wait / run /- total), replacing the old `duration_ms` event property.-- `source` / `runtime_mode` / `provider` are the normalized label values- (`NormalizeTaskSource` / `NormalizeRuntimeMode` / `NormalizeRuntimeProvider`).--### `autopilot_run_started` / `autopilot_run_completed` / `autopilot_run_failed`--> **Prometheus-only — not shipped to PostHog.** The `analytics.*` constructors-> are retained only so `metrics.IncForEvent` can derive the Prometheus counter;-> `analytics.IsMetricsOnly` keeps them out of PostHog. Only `cadence`,-> `trigger_kind`, and `terminal_status` become Prometheus labels — the-> `autopilot_id` / `autopilot_run_id` / `agent_id` fields below are event shape,-> not labels.--Fires from `autopilot_run` lifecycle changes. `source` is always-`autopilot`; the trigger origin is carried in `trigger_source` (`manual`,-`schedule`, `webhook`, or `api`).--| Property | Type | Description |-|---|---|---|-| `autopilot_id` | string (UUID) | Autopilot definition. |-| `autopilot_run_id` | string (UUID) | Run row. |-| `agent_id` | string (UUID) | Assigned agent. |-| `trigger_source` | string | `manual`, `schedule`, `webhook`, or `api`. |-| `duration_ms` | int64 | Terminal events only. |-| `failure_reason` | string | Failed events only. |-| `error_type` | string | Failed events only; stable coarse classifier such as `configuration`, `issue_terminal`, `dispatch_error`, `task_error`, or `autopilot_error`. |-| `will_retry` | bool | Failed events only; currently `false` because autopilot retry cadence is owned by triggers/schedules. |--### `issue_executed`--Fires **at most once per issue** — when the first task on that issue-reaches terminal `done` state. Backed by an atomic-`UPDATE issue SET first_executed_at = now() WHERE id = $1 AND first_executed_at IS NULL RETURNING *`;-retries, re-assignments, and comment-triggered follow-up tasks all hit the-WHERE clause and no-op, so the `≥1 / ≥2 / ≥5 / ≥10` funnel buckets count-distinct issues, not tasks.--| Property | Type | Description |-|---|---|---|-| `issue_id` | string (UUID) | |-| `task_id` | string (UUID) | Completing task. |-| `agent_id` | string (UUID) | Completing agent. |-| `source` | string | `manual`, `chat`, or `autopilot`. |-| `runtime_mode` | string | `local` / `cloud`. |-| `provider` | string | Runtime provider. |-| `task_duration_ms` | int64 | Wall-clock time between `task.started_at` and `task.completed_at`. Zero when the task was created in a completed state (rare). |--`distinct_id` prefers the issue's human creator so agent-executed events-flow into the issue-author's person profile (same place `signup` and-`workspace_created` land). Agent-created issues prefix with `agent:` to-keep PostHog from merging the agent into a user record.--**Note on workspace-Nth ordinals** — we deliberately do *not* stamp-`nth_issue_for_workspace` at emit time. Computing it correctly would-require either a serialised transaction or an advisory lock per workspace;-two concurrent first-completions could otherwise both read `count=1` and-emit `n=1`. PostHog answers the same question at query time via-`row_number() OVER (PARTITION BY properties.workspace_id ORDER BY timestamp)`,-and funnel steps of the form "workspace has had ≥2 `issue_executed`-events" are expressible without the property. No information is lost.--`issue_executed` is the canonical core-loop success signal. Since MUL-4127 it is-metrics-only like every server event: recorded to Prometheus as-`multica_issue_executed_total{source}` (not PostHog) and backed in the DB by-`issue.first_executed_at`. Per-task completion counts live in Grafana via-`BusinessMetrics.RecordTaskTerminal`; use `multica_issue_executed_total` for the-activation funnel and break down by `source` as needed.--### `team_invite_sent`--Fires from `CreateInvitation` after the DB row is written.--| Property | Type | Description |-|---|---|---|-| `invited_email_domain` | string | Lower-cased domain; full email lives in the invitation row, not the event. |-| `invite_method` | string | Currently always `"email"`. Future non-email invite flows (share link, SCIM) should pass their own value. |--`distinct_id` is the inviter's user id.--### `team_invite_accepted`--Fires from `AcceptInvitation` after both the invitation row is marked-accepted and the member row is inserted in the same transaction.--| Property | Type | Description |-|---|---|---|-| `days_since_invite` | int64 | Whole days from invitation creation to acceptance. Lets us segment "accepted same day" (warm) from "dug out of email weeks later" (cold). |--`distinct_id` is the invitee's user id — this is the event that closes the-expansion funnel.--### `onboarding_started`--Fires once when the onboarding shell mounts and the initial workspace list has-resolved. Existing-workspace users carry `workspace_id`; brand-new users do-not have a workspace yet.--| Property | Type | Description |-|---|---|---|-| `workspace_id` | string (UUID) | Present only when the user already has a workspace. |-| `source` | string | Always `onboarding`. |--### `onboarding_questionnaire_submitted`--Fires on the first PatchOnboarding that transitions the user's-questionnaire JSONB from "at least one slot empty" to "all three-filled" (team_size, role, use_case). Revisions past that point don't-re-emit — the funnel counts users, not edits.--| Property | Type | Description |-|---|---|---|-| `team_size` | string | `solo` / `team` / `other`. |-| `role` | string | `developer` / `product_lead` / `writer` / `founder` / `other`. |-| `use_case` | string | `coding` / `planning` / `writing_research` / `explore` / `other`. |-| `team_size_has_other` | bool | `true` when the user filled the Q1 free-text escape. |-| `role_has_other` | bool | Ditto Q2. |-| `use_case_has_other` | bool | Ditto Q3. |--Person properties set with `$set` (not once — users can go back and-change answers before submitting again):--| Property | Type | Description |-|---|---|---|-| `team_size` | string | Mirrors the event property for cohort queries. |-| `role` | string | Same. |-| `use_case` | string | Same. |--`distinct_id` is the user's id. No workspace_id — the questionnaire is-per-user, not per-workspace.--### `agent_created`--Fires on every successful `POST /api/workspaces/:id/agents`. Not-onboarding-specific — the `is_first_agent_in_workspace` property-isolates the Step 4 signal from later agent additions.--| Property | Type | Description |-|---|---|---|-| `agent_id` | string (UUID) | |-| `provider` | string | Runtime provider the agent is bound to (`claude`, `codex`, etc). |-| `runtime_mode` | string | Runtime mode copied from the bound runtime. |-| `template` | string | Template slug used to seed the agent (`coding` / `planning` / `writing` / `assistant`). Empty when the caller didn't come from a template picker. |-| `is_first_agent_in_workspace` | bool | `true` when the workspace had zero agents before this insert. |--`distinct_id` is the authenticated owner's user id.--### `onboarding_completed`--Fires from CompleteOnboarding on the first call that actually flips-`user.onboarded_at` from NULL. Retries are idempotent server-side but-deliberately do NOT re-emit, so the funnel counts first-completions-only. The client sends `completion_path` in the POST body to label-which exit the user took.--| Property | Type | Description |-|---|---|---|-| `workspace_id` | string (UUID) | Present for workspace-linked onboarding completions. |-| `completion_path` | string | One of `full` / `runtime_skipped` / `cloud_waitlist` / `skip_existing` / `invite_accept` / `unknown`. See below. |-| `joined_cloud_waitlist` | bool | Derived from `user.cloud_waitlist_email`. Orthogonal to `completion_path` — a user may submit the waitlist form and still pick CLI. |--Person properties set with `$set_once`:--| Property | Type | Description |-|---|---|---|-| `onboarded_at` | string (RFC3339) | Timestamp the first completion landed. Enables cohort queries like "users onboarded before X" directly from person_properties. |--`completion_path` values:--- `full` — Reached Step 5 (first_issue) with a runtime connected.-- `runtime_skipped` — Completed without connecting a runtime (user hit Skip in Step 3).-- `cloud_waitlist` — Submitted the cloud waitlist form and skipped Step 3.-- `skip_existing` — "I've done this before" from Welcome. The user already had a workspace.-- `invite_accept` — Accepted at least one workspace invitation.-- `unknown` — Legacy fallback when the client didn't send a path. Should stay near zero after rollout.--### `cloud_waitlist_joined`--Fires from JoinCloudWaitlist whenever a user submits the Step 3 cloud-waitlist form. Not a completion signal — it's orthogonal to the main-funnel and used to size hosted-runtime interest.--| Property | Type | Description |-|---|---|---|-| `has_reason` | bool | Presence flag for the free-text reason field. The free text stays in the DB; we don't broadcast it. |--`distinct_id` is the user's id.--### `contact_sales_submitted`--Fires from `CreateContactSales` after the `contact_sales_inquiry` row is-inserted. The endpoint is public and unauthenticated, so the-`distinct_id` is the inquiry id (no user identity to attach to). The-free-text `goals` field stays in the DB and is never broadcast.--| Property | Type | Description |-|---|---|---|-| `inquiry_id` | string | Stable inquiry id; same as `distinct_id`. Useful for joining to operational data. |-| `company_size` | string | Closed enum from the form dropdown (`1-10`, `11-50`, `51-200`, `201-500`, `501-1000`, `1000+`). |-| `country_region` | string | Country / region label submitted from the dropdown. |-| `use_case` | string | Closed enum (`evaluate` / `adopt_team` / `self_host` / `integrate` / `partner` / `other`). |-| `has_goals` | bool | Presence flag for the free-text goals field. |--### `feedback_submitted`--Fires from `CreateFeedback` after the `feedback` row is inserted and the-hourly per-user rate-limit check has passed. Retries within the same hour-that were rate-limited (429) don't emit. The free-text message is stored-in the DB and never broadcast.--| Property | Type | Description |-|---|---|---|-| `message_length_bucket` | string | `0-100` / `100-500` / `500-2000` / `2000+` — coarse bucket of `len(message)` so we can tell "quick note" from "bug report with repro steps" without leaking content. |-| `has_images` | bool | `true` when the markdown contains at least one `` image reference — signals bug reports with visual evidence. |-| `platform` | string | Client platform from `X-Client-Platform` header (`web` / `desktop`). Omitted when the header is absent. |-| `app_version` | string | Client version from `X-Client-Version` header. Omitted when absent. |--`distinct_id` is the submitter's user id; `workspace_id` is attached from-the modal's current-workspace context and may be empty when feedback is-sent from a pre-workspace surface.--### Frontend-only events--> **Removed in MUL-4127**, except `$exception` (unchanged) and the-> `client_crash` / `client_unresponsive` desktop stability events (documented in-> `packages/core/diagnostics`). `$pageview`, `download_intent_expressed`,-> `download_page_viewed`, `download_initiated`, `onboarding_runtime_path_selected`,-> `onboarding_runtime_detected`, the frontend `onboarding_started` mirror,-> `feedback_opened`, and `source_backfill_*` no longer fire. The descriptions-> below are kept as historical reference only.--- `$pageview` — fired by the web tracker- (`apps/web/components/pageview-tracker.tsx`) on Next.js App Router- **pathname** changes, and by the desktop tracker- (`apps/desktop/.../pageview-tracker.tsx`) on visible-surface changes.- Both mount once at the root and drive the acquisition funnel's- `/ → signup` step. posthog-js's automatic pageview capture is- disabled in `initAnalytics` so we own the event shape.- `capturePageview` (`packages/core/analytics`) **section-normalizes** the- path before emitting: query string / hash are stripped and resource-id- segments are collapsed, so `/acme/issues/8d5c…` and `/acme/issues/MUL-12`- both report as `/acme/issues`, and consecutive views of the same section- are deduplicated. This keeps PostHog at section granularity rather than- billing a `$pageview` per resource or per filter/sort/search change. The- tracker is deliberately NOT keyed on the query string.-- `onboarding_runtime_path_selected` — fired from- `packages/views/onboarding/steps/step-platform-fork.tsx` when the web- user clicks one of the three Step 3 fork cards (before any server- call happens, so it's frontend-only). Properties: `path`- (`download_desktop` / `cli` / `cloud_waitlist`), `source`- (`onboarding`), `surface` (`step3`), `workspace_id`, and `is_mac`.- Also writes `platform_preference` (`web` / `desktop`) to person- properties so every subsequent event on the user can be broken down- by chosen platform. **Note**: semantic "download- intent" is now better served by `download_intent_expressed` below —- `path: "download_desktop"` signals Step 3 path choice specifically,- not actual download start.--- `onboarding_runtime_detected` — fired from- `packages/views/onboarding/steps/step-runtime-connect.tsx` (desktop- Step 3) once per mount, when the scanning phase resolves — either- immediately on first runtime registration, or after the 5 s empty- timeout. Answers the question "did the user have any AI CLI- installed on this machine when they hit Step 3" — currently- unanswerable from the existing funnel because the bundled daemon- fails to register at all when zero CLIs are on PATH, so- `runtime_registered` is silent on that cohort. Splits- `completion_path=runtime_skipped` into "had CLIs, skipped anyway"- vs "no CLIs available, had no choice". Properties:- - `source`: `onboarding`.- - `surface`: `step3_desktop`.- - `workspace_id`: current onboarding workspace.- - `outcome`: `found` (at least one runtime registered before the- 5 s grace window expired) or `empty` (none registered by then).- - `runtime_count`: number of runtimes visible to this user at- resolution time.- - `online_count`: subset of `runtime_count` whose `status` is- `online`.- - `providers`: sorted array of distinct provider names (e.g.- `["claude", "codex"]`).- - `has_claude` / `has_codex` / `has_cursor`: convenience booleans- derived from `providers` for funnel breakdowns without array- filtering in HogQL.- - `detect_ms`: wall-clock ms from component mount to resolution.- Surfaces daemon boot latency — `found` events with a high- `detect_ms` approach the timeout threshold and inform whether- to lengthen the grace period.-- Person properties set with `$set`:- - `has_any_cli`: boolean — cohort signal for "user has at least- one local AI CLI detected on this machine".- - `detected_cli_count`: number — granular cohort signal.-- Not emitted from the web Step 3 (`step-platform-fork.tsx`) — web- users don't run the bundled daemon, so their runtime list reflects- daemons from other machines and would corrupt the- "CLI installed locally" signal.--- `download_intent_expressed` — fired whenever a user clicks a CTA- that points at the `/download` page. Surfaces five sources across- the funnel, letting the top-of-funnel entry be split cleanly.- Wrapper lives in `packages/core/analytics/download.ts`- (`captureDownloadIntent`). Properties:- - `source`: `landing_hero` / `landing_footer` / `login` / `welcome`- / `step3`- Also writes `platform_preference: "desktop"` to person properties.--- `download_page_viewed` — fired once per `/download` mount after OS- detect resolves (`apps/web/app/(landing)/download/download-client.tsx`).- Properties:- - `detected_os`: `mac` / `windows` / `linux` / `unknown`- - `detected_arch`: `arm64` / `x64` / `unknown`- - `detect_confident`: `true` when detect used- `userAgentData.getHighEntropyValues` (Chromium); `false` when it- fell back to the UA string (Safari on Mac always lands here —- lets us isolate the arm64-default-for-Intel risk cohort).- - `version_available`: `false` when the GitHub API fetch failed- and the page is in the "Version unavailable" degraded state.- Also writes `first_detected_os` / `first_detected_arch` via- `$set_once` so every downstream event gains a platform dimension- without re-emitting.--- `download_initiated` — fired when the user clicks a specific- installer link on `/download`. Both the hero CTA and the All- Platforms matrix rows emit this; split by `primary_cta`.- Properties:- - `platform`: `mac` / `windows` / `linux`- - `arch`: `arm64` / `x64`- - `format`: `dmg` / `zip` / `exe` / `appimage` / `deb` / `rpm`- - `version`: release tag (e.g. `v0.2.13`) — correlates adoption- with release cadence.- - `primary_cta`: `true` for the hero-recommended installer, `false`- for a manual pick from the All Platforms matrix.- - `matched_detect`: `true` when the chosen platform+arch matches- what the page detected. `false` lets us quantify detect misses- from the single event (no cross-join needed).-- `feedback_opened` — fired when the in-app Feedback modal mounts- (user clicked "Feedback" in the Help launcher). Paired with the- backend's `feedback_submitted` to give a completion rate for the- form. Wrapper lives in `packages/core/analytics/feedback.ts`- (`captureFeedbackOpened`). Properties:- - `source`: `help_menu` (reserved — future entry points like- keyboard shortcut or error-toast CTA will pass their own value)- - `workspace_id`: string (UUID) when the modal opens inside a- workspace. Omitted on pre-workspace surfaces.--- Attribution is NOT a separate event; UTM + referrer origin are written- to the `multica_signup_source` cookie on the first anonymous pageview- and read by the backend's `signup` emission. The cookie carries a JSON- payload URL-encoded at write time (`encodeURIComponent`) and- URL-decoded at read time (`url.QueryUnescape`) — the JSON is never- mid-truncated; individual values are capped at 96 chars before- `JSON.stringify`, and the entire payload is dropped if it still exceeds- 512 chars. That way PostHog sees either intact JSON or nothing at all.--## Reconciliation--Per-task completion is no longer shipped to PostHog. Task success now-reconciles **DB ↔ Prometheus** instead of DB ↔ PostHog: the-`BusinessMetrics.RecordTaskTerminal` counter (exported as a `multica_*` task-metric) should track the operational source of truth:--```sql-SELECT date_trunc('day', completed_at AT TIME ZONE 'UTC') AS day,- count(*) AS db_completed_tasks-FROM agent_task_queue-WHERE status = 'completed'- AND completed_at >= now() - interval '30 days'-GROUP BY 1-ORDER BY 1;-```--Compare against the equivalent Prometheus counter in Grafana. The expected-difference should be near zero; sustained drift means either an emission site-is missing or the metrics pipeline is unhealthy.--`issue_executed` remains the product-level success signal (at most one per-issue). Since MUL-4127 it is Prometheus-only, so reconcile-`multica_issue_executed_total` against `issue.first_executed_at` rather than a-PostHog event.--## Daily client usage and local runtime state--`client_usage_daily` is the operational source of truth for Web/Desktop usage-and Desktop built-in-provider conversion. Its primary key is-`(user_id, client_type, install_id, activity_date)`, where `activity_date` is-derived by the server in UTC. `install_id` is a random UUID stored in the Web-origin or Electron app profile and reused across restarts, upgrades, logout,-and login. Clearing/resetting that profile intentionally creates a new-installation. Web and Desktop never share an installation ID.--Clients report after authentication when that installation has no successful-report for the current UTC day, and re-check on focus/resume. Desktop updates-the same daily row after its first local-runtime probe and whenever the-same-day runtime signature changes. Reports contain only client kind/version,-a coarse OS bucket, optional current workspace context, and aggregate runtime-provider/online/offline counts. The server supplies user, date, and timestamps.-Device names, hostnames, local usernames, filesystem paths, raw user agents,-IP addresses, and raw probe errors are not stored here.--`first_active_at` and `last_active_at` are the first and latest successful-reports **within that UTC day**, not lifetime installation timestamps. Compute-historical first use with `min(first_active_at)` across the installation's daily-rows. The client's UTC day is only a best-effort request throttle; the server's-UTC date is authoritative, so clock skew near midnight can delay the next row-until a later focus/resume without assigning activity to the wrong server day.--Desktop runtime availability is deliberately a daemon-level approximation in-this MVP, not a connection test for each provider. The probe counts locally-detected **built-in provider CLIs**; workspace custom runtime profiles are not-included. Consequently, treat `runtime_count = 0` as "no built-in provider CLI-detected", not proof that the user has no custom profile. If the managed daemon-is running, all detected built-in providers are reported online, and otherwise-they are reported offline. Use `probe_result = 'error'` as unknown rather than-treating a failed probe as zero runtimes. Covering custom profiles requires a-separate inventory contract that remains available after the daemon stops; do-not infer it from this snapshot.--Use this query for a 30-day client split and user-level Desktop built-in-provider-state. It first selects the latest non-null probe for each installation, then-rolls installations up to the user so multi-device users are not double counted-and missing probes remain `unknown` rather than being classified as having no-built-in runtime:--```sql-WITH window_rows AS (- SELECT *- FROM client_usage_daily- WHERE activity_date >= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date - 29-),-active_clients AS (- SELECT DISTINCT user_id, client_type, install_id FROM window_rows-),-latest_desktop_probe AS (- SELECT DISTINCT ON (user_id, install_id)- user_id, install_id, probe_result, runtime_count, online_count- FROM window_rows- WHERE client_type = 'desktop' AND probe_result IS NOT NULL- ORDER BY user_id, install_id, activity_date DESC, runtime_probed_at DESC-),-desktop_by_user AS (- SELECT- a.user_id,- count(*) AS installation_count,- count(*) FILTER (WHERE p.probe_result = 'success') AS successful_probe_count,- coalesce(sum(p.runtime_count) FILTER (WHERE p.probe_result = 'success'), 0) AS runtime_count,- coalesce(sum(p.online_count) FILTER (WHERE p.probe_result = 'success'), 0) AS online_count- FROM active_clients a- LEFT JOIN latest_desktop_probe p USING (user_id, install_id)- WHERE a.client_type = 'desktop'- GROUP BY a.user_id-),-desktop_state AS (- SELECT user_id,- CASE- WHEN successful_probe_count < installation_count THEN 'unknown'- WHEN runtime_count = 0 THEN 'no_builtin_runtime'- WHEN online_count = 0 THEN 'all_builtin_runtimes_offline'- ELSE 'builtin_runtime_available'- END AS runtime_state- FROM desktop_by_user-)-SELECT- (SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'web') AS active_web_users,- (SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop') AS active_desktop_users,- count(*) FILTER (WHERE runtime_state = 'builtin_runtime_available')- AS desktop_users_with_builtin_runtime,- count(*) FILTER (WHERE runtime_state = 'no_builtin_runtime')- AS desktop_users_without_builtin_runtime,- round(100.0 * count(*) FILTER (WHERE runtime_state = 'no_builtin_runtime')- / nullif((SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop'), 0), 2)- AS desktop_users_without_builtin_runtime_pct,- count(*) FILTER (WHERE runtime_state = 'all_builtin_runtimes_offline')- AS desktop_users_all_builtin_runtimes_offline,- round(100.0 * count(*) FILTER (WHERE runtime_state = 'all_builtin_runtimes_offline')- / nullif((SELECT count(DISTINCT user_id) FROM active_clients WHERE client_type = 'desktop'), 0), 2)- AS desktop_users_all_builtin_runtimes_offline_pct,- count(*) FILTER (WHERE runtime_state = 'unknown') AS desktop_users_unknown-FROM desktop_state;-```--The initial retention policy is 180 UTC days. This MVP deliberately does not-add another in-process background job; operators should run-`DELETE FROM client_usage_daily WHERE activity_date < (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date - 179`-through the existing database-maintenance schedule until a shared retention-worker exists. Deleting a workspace nulls its optional context, while deleting-a user must delete that user's daily rows in the same application transaction-because this table has no foreign keys by repository policy. There is currently-no production account hard-delete path; any future one must add that explicit-cleanup before it deletes the user row.--## Governance--Before adding, renaming, or removing any event:--1. Update this document first.-2. Update `server/internal/analytics/events.go` constants and helpers to- match.-3. PR description must state which existing funnel / insight is affected.diff --git a/docs/codex-sandbox-troubleshooting.md b/docs/codex-sandbox-troubleshooting.mddeleted file mode 100644index cd6ebd02b4..0000000000--- a/docs/codex-sandbox-troubleshooting.md+++ /dev/null@@ -1,107 +0,0 @@-# Codex sandbox troubleshooting (macOS `no such host`)--This doc explains the failure mode that caused [MUL-963][mul-963] and the-matrix the daemon now follows when writing Codex's per-task `config.toml`.--[mul-963]: https://multica-api.copilothub.ai/issues/28c34ad2-102a-4f46-91ac-336ed78c5859--## Symptom fingerprint--| Error text | Likely cause |-| ------------------------------------------------------------- | ------------------------------------------------------------------------------- |-| `dial tcp: lookup HOST: no such host` | **Codex Seatbelt sandbox blocking DNS** (macOS, `workspace-write` mode). |-| `dial tcp IP:PORT: connect: connection refused` | Server/daemon not running on that port (app-level, not sandbox). |-| `dial tcp IP:PORT: i/o timeout` | Container-level network policy or firewall (not Codex sandbox). |-| `x509: certificate signed by unknown authority` | TLS/CA issue, unrelated. |--If you see `no such host` *inside a Codex session on macOS* but `curl https://multica-api.copilothub.ai` from a plain shell on the same machine works, you are hitting the Seatbelt bug below.--## Root cause--Upstream issue: [openai/codex#10390][codex-10390]. On macOS, Codex's Seatbelt-profile for `sandbox_mode = "workspace-write"` silently ignores the-`[sandbox_workspace_write] network_access = true` setting. The seatbelt-policy hard-codes `CODEX_SANDBOX_NETWORK_DISABLED=1`, which blocks DNS/UDP-syscalls. Go's `net.LookupHost` surfaces that as `no such host`.--Linux (Landlock) is **not** affected — only macOS Seatbelt.--[codex-10390]: https://github.com/openai/codex/issues/10390--## What the daemon does now--The daemon writes a *multica-managed* block into each task's-`$CODEX_HOME/config.toml`, delimited by `# BEGIN multica-managed` /-`# END multica-managed` markers. Anything outside the markers is left-untouched so users can still tune Codex behavior.--Decision matrix (see [`server/internal/daemon/execenv/codex_sandbox.go`](../server/internal/daemon/execenv/codex_sandbox.go)):--| Host OS | Codex version | Managed block emits |-| --------- | ------------------------------------------------ | ------------------------------------------------------------------------- |-| non-darwin | any | `sandbox_mode = "workspace-write"` + `sandbox_workspace_write.network_access = true` (dotted-key form) |-| darwin | ≥ `CodexDarwinNetworkAccessFixedVersion` | same as above (upstream fix in effect) |-| darwin | older / unknown (current default) | `sandbox_mode = "danger-full-access"` + warn-level log |--The managed block is always hoisted to the top of `config.toml` and uses-TOML dotted-key syntax rather than a `[sandbox_workspace_write]` section-header. Both are load-bearing: if the block sat after a user table like-`[permissions.multica]`, a bare `sandbox_mode = "..."` line would be parsed-as `permissions.multica.sandbox_mode` and Codex would silently ignore it.--`CodexDarwinNetworkAccessFixedVersion` is an empty string today, meaning *no-known fixed release yet*. Bump it once a tagged Codex release includes the-upstream fix.--When the daemon falls back to `danger-full-access`, it logs at `WARN`:--```-codex sandbox: falling back to danger-full-access on macOS- reason=codex on macOS: seatbelt ignores sandbox_workspace_write.network_access (openai/codex#10390) ...- codex_version=0.121.0- hint=upgrade Codex CLI (e.g. `brew upgrade codex` or `npm i -g @openai/codex`) ...- config_path=/.../codex-home/config.toml-```--## Quick self-check commands--From the host shell (outside the sandbox):--```bash-# Is the Multica API reachable at all?-curl -sSf https://multica-api.copilothub.ai/healthz-```--From inside a Codex session (after the daemon writes its config):--```bash-multica issue list --limit 1 --output json >/dev/null && echo OK-```--If the host curl works but the Codex-session call fails with `no such host`,-the sandbox is the culprit; confirm the daemon picked the right policy by-looking at the managed block in `$CODEX_HOME/config.toml`.--## Options and trade-offs--- **A. Domain-scoped `permissions` profile** (tight): when the upstream- `network_access` fix is available, prefer writing a `permissions.multica`- profile that allows only `multica-api.copilothub.ai` and- `multica-static.copilothub.ai`. Keeps filesystem sandbox intact.-- **B. `danger-full-access`** (current macOS fallback): drops the whole- Seatbelt profile. Simplest reliable workaround until the upstream fix is- released.-- **C. Upgrade Codex CLI**: `brew upgrade codex` or `npm i -g @openai/codex`.- Once a release containing [openai/codex#10390][codex-10390] is installed,- bump `CodexDarwinNetworkAccessFixedVersion` in `codex_sandbox.go` and- option A/the workspace-write path takes over automatically.--## If you need to hand-verify--```bash-# Inspect the managed block the daemon wrote for a given task.-sed -n '/# BEGIN multica-managed/,/# END multica-managed/p' \- ~/multica_workspaces/$WORKSPACE_ID/$TASK_SHORT/codex-home/config.toml-```--The block is idempotent — re-running a task rewrites it in place.diff --git a/docs/codex-usage-cache-backfill.md b/docs/codex-usage-cache-backfill.mddeleted file mode 100644index fa0f9e3cd9..0000000000--- a/docs/codex-usage-cache-backfill.md+++ /dev/null@@ -1,91 +0,0 @@-# Codex Usage Cache Backfill--This runbook describes the one-time hosted data repair for Codex usage rows-created before cached input was normalized at ingestion time.--Do not run this as an automatic database migration. The write step needs an-operator-selected cutoff, dry-run review, and an explicit execute command.--## When To Run--Run this only after the backend image containing `backfill_codex_usage_cache`-has been deployed, and only for databases that need historical Codex usage-correction.--Use the actual hosted deployment time of PR #4083 as `--cutoff`. Do not use the-PR merge time unless it is also the real production cutover time.--## Execution Model--Run the command from the released backend image as a one-time operator job, such-as a Kubernetes Job with the normal backend database secret and network access.-Override the command to execute `./backfill_codex_usage_cache`.--The command defaults to dry-run. It mutates data only when `--execute` is passed.--## Dry Run--First run:--```bash-./backfill_codex_usage_cache --cutoff <RFC3339_DEPLOY_TIME>-```--Optionally limit scope while validating:--```bash-./backfill_codex_usage_cache --cutoff <RFC3339_DEPLOY_TIME> --workspace-id <workspace-uuid>-```--Review the per-workspace/date output:--- `rows`-- `input_before`-- `input_after`-- `input_tokens_removed`-- `clamped_rows`--Proceed only if the totals match the expected overcount shape.--## Execute--After dry-run review:--```bash-./backfill_codex_usage_cache --cutoff <RFC3339_DEPLOY_TIME> --execute-```--For large datasets, throttle writes:--```bash-./backfill_codex_usage_cache \- --cutoff <RFC3339_DEPLOY_TIME> \- --execute \- --batch-size 500 \- --sleep-between-batches 1s-```--By default, execution rebuilds affected hourly rollups by calling-`rollup_task_usage_hourly_window(...)` for the database update window. Leave-`--rebuild-rollup=true` unless an operator intentionally plans a separate rollup-rebuild.--## Verification--After execution, run the dry-run command again with the same cutoff and scope.-Eligible rows should be zero.--Then verify Usage / Runtime dashboard periods that were previously inflated.--## Safety Boundaries--The command updates only rows that match all of these conditions:--- `provider = 'codex'`-- `cache_read_tokens > 0`-- `input_tokens > 0`-- `COALESCE(updated_at, created_at) < --cutoff`-- optional `--workspace-id` match--Rows without persisted `cache_read_tokens` are intentionally ignored because the-current database cannot accurately reconstruct cached input for them.diff --git a/docs/custom-runtimes.md b/docs/custom-runtimes.mddeleted file mode 100644index 126b9e2cca..0000000000--- a/docs/custom-runtimes.md+++ /dev/null@@ -1,61 +0,0 @@-# Custom runtimes--Custom runtime profiles let a workspace register an AI CLI that speaks one of-Multica's supported protocol families but is launched through a team-specific-command.--## Command and arguments--Paste the same argv-style command you would run in a terminal:--```sh-agent --model composer-2.5-```--Multica stores this as:--- `command_name`: `agent`-- `fixed_args`: `["--model", "composer-2.5"]`--The daemon starts the process directly with `exec.Command(command_name,-fixed_args...)`; it does not run a shell.--Supported input:--- plain arguments separated by whitespace-- single or double quotes for values with spaces-- backslash escaping for literal spaces or quote characters--The UI parser is argv-oriented, not a full POSIX shell. Inside double quotes,-`\` escapes the next character directly; use single quotes when you need `$` or-backticks to stay literal. Running tasks keep the launch args they started with;-profile command or argument edits apply to newly claimed tasks after the daemon-re-registers.--Unsupported input:--- pipes, redirects, `;`, `&&`, `||`-- backticks-- `$VAR` or `$(...)` expansion--Use a wrapper script when the runtime needs shell behavior.--## Command not found--Desktop-launched daemons may not inherit the same `PATH` as an interactive-terminal. If a custom runtime shows a registration error even though the command-works in your shell, pin the absolute path on that machine:--```sh-multica runtime profile set-path <profile-id> --path /abs/path/to/agent-```--Then restart or refresh the daemon so it re-registers the profile.--## Upgrade order--Custom runtime arguments and registration-error reporting require both the-server and daemon versions that support `fixed_args` launch specs and-`failed_profiles` registration reports. In mixed deployments, upgrade the server-before rolling out newer daemons so failed custom-only profiles can be recorded-instead of being rejected as an empty runtime registration.diff --git a/docs/design.md b/docs/design.mdindex 2472bad90b..80cbf88db3 100644--- a/docs/design.md+++ b/docs/design.md@@ -1,445 +1,449 @@# Multica Design System-本文档定义 Multica 的视觉语言和交互规范。所有 UI 开发以此为准。+This document defines Multica's visual language and interaction conventions. All UI work follows it.-页面级信息架构、布局组合与一致性治理见 [`ui-consistency-audit.md`](./ui-consistency-audit.md)。+> 中文版本:[`design.zh.md`](./design.zh.md)。----## 1. 设计哲学+## 1. Design philosophy-三条核心原则:+Three core principles:-1. **克制即高级。** 默认做减法。每个元素必须有存在的理由——多余的分割线、装饰性图标、"以防万一"的提示文字,都是噪音。留白本身就是设计。-2. **层次靠灰度,颜色是信号。** 界面的主体是中性色。颜色只在需要传递语义时出现(状态、品牌、错误)。如果两个区域在视觉上竞争注意力,解法是让一个退后,而不是两个都加色。-3. **一致性大于个性。** 同类交互必须有相同的视觉反馈。一个 hover 效果在 sidebar、dropdown、table row 里应该"感觉一样"。这种一致性通过 token 而非硬编码实现。+1. **Restraint reads as quality.** Subtract by default. Every element must earn its place — a redundant divider, a decorative icon, a "just in case" hint is noise. Whitespace is itself a design decision.+2. **Hierarchy comes from grey; colour is a signal.** The interface is predominantly neutral. Colour appears only when it carries meaning (status, brand, error). If two regions compete for attention, the fix is to push one back, not to colour both.+3. **Consistency beats personality.** The same class of interaction must produce the same visual feedback. A hover effect should "feel identical" in the sidebar, in a dropdown, and on a table row. That consistency comes from tokens, never from hardcoded values.----## 2. 颜色体系+## 2. Colour system-基于 OKLCh 色彩空间,通过 CSS 变量定义。所有颜色使用 shadcn token,**禁止硬编码 Tailwind 色值**(如 `text-gray-500`、`bg-blue-600`)。+Built on the OKLCh colour space and exposed as CSS variables. All colours use shadcn tokens; **hardcoded Tailwind colour values are forbidden** (`text-gray-500`, `bg-blue-600`, and the like).-### 2.1 Surface 层级+### 2.1 Surface hierarchy-Surface 系统描述的是容器之间的关系,不是把每一段内容都包进卡片。基础 token 定义在 `packages/ui/styles/tokens.css`,并同时覆盖 light / dark mode。+The surface system describes the relationship *between containers* — it is not a licence to wrap every block of content in a card. Base tokens live in `packages/ui/styles/tokens.css` and cover light and dark mode together.-| 层级 | Token / Class | 用途 | 不应用于 |-|------|---------------|------|----------|-| App Shell | `app-shell` / `bg-app-shell` | 窗口最外层、sidebar 与 page canvas 之间的留白 | 页面正文、表单组 |-| Page Canvas | `page-canvas` / `bg-page-canvas` | 页面主体;list、board、chat 等持续滚动的内容区 | 独立设置组、弹窗 |-| Surface / Card | `surface`、`surface-border`、`--surface-shadow` | 有独立边界的表单组、设置组、摘要卡 | 每一行列表、每一列 board、整页正文 |-| Floating Surface | `surface-raised`、`--floating-shadow` | dialog、dropdown、popover、sheet、浮动 chat | 常驻页面布局 |+| Level | Token / class | Use for | Do not use for |+|---|---|---|---|+| App shell | `app-shell` / `bg-app-shell` | Outermost window chrome; the gutter between sidebar and page canvas | Page body, form groups |+| Page canvas | `page-canvas` / `bg-page-canvas` | The page body; continuously scrolling regions such as lists, boards, chat | Standalone settings groups, dialogs |+| Surface / card | `surface`, `surface-border`, `--surface-shadow` | Form groups, settings groups, and summary cards that need their own boundary | Every list row, every board column, whole-page body copy |+| Floating surface | `surface-raised`, `--floating-shadow` | Dialog, dropdown, popover, sheet, floating chat | Persistent page layout |-规则:+Rules:-- Page Canvas 是默认内容面。需要分组时先用间距和分割线,只有独立操作或独立信息块才使用 Surface。-- 浅色模式中,`app-shell` 与 sidebar 使用 `#f3f3f4`,`page-canvas` 使用 `#fbfbfb`,Card 使用 `#ffffff`;不能只靠 border 区分设置组和页面背景。三者形成接近 Linear 的克制层级,由外向内逐步变亮。-- Card 使用 `bg-surface border-surface-border shadow-[var(--surface-shadow)]`;浮层使用 `bg-surface-raised ring-surface-border shadow-[var(--floating-shadow)]`。-- `surface-hover` 只表示指针经过;`surface-selected` 表示持续选中,并保持中性灰,不额外叠加 brand 色。选中项 hover 时必须保留 `surface-selected`,不能退回 hover 状态。-- focus 一律使用 `focus-visible` ring。不要用阴影、尺寸变化或品牌大面积填充代替键盘焦点。-- 不为 light / dark mode 手写一组平行 class。基础 surface token 已按主题解析,并通过 `color-scheme` 同步原生控件。+- Page canvas is the default content plane. When you need grouping, reach for spacing and dividers first; use a surface only for a self-contained action or information block.+- In light mode, `app-shell` and the sidebar use `#f3f3f4`, `page-canvas` uses `#fbfbfb`, and cards use `#ffffff`. Never rely on a border alone to separate a settings group from the page background. The three together form a restrained, Linear-like hierarchy that brightens from the outside in.+- Cards use `bg-surface border-surface-border shadow-[var(--surface-shadow)]`; floating layers use `bg-surface-raised ring-surface-border shadow-[var(--floating-shadow)]`.+- `surface-hover` means the pointer is passing over. `surface-selected` means a persistent selection and stays a neutral grey — do not layer brand colour on top. A selected item that is hovered must keep `surface-selected`; it must not fall back to the hover state.+- Focus always uses a `focus-visible` ring. Never substitute a shadow, a size change, or a large brand fill for keyboard focus.+- Do not hand-write a parallel set of classes for light and dark mode. The base surface tokens already resolve per theme and sync native controls through `color-scheme`.-### 2.2 中性色阶梯+### 2.2 The neutral ramp-界面 90% 的面积由中性色构成。灰度等级即信息层级:+Neutrals cover 90% of the interface. Grey level *is* information hierarchy:-| 角色 | Light Token | Dark Token | 用途 |-|------|-------------|------------|------|-| 背景 | `page-canvas` / `background` | `page-canvas` / `background` | 页面主体 |-| 卡片/浮层 | `surface` / `surface-raised` | `surface` / `surface-raised` | 有边界的内容组与临时覆盖层 |-| 次级表面 | `muted` / `secondary` | `muted` / `secondary` | hover 背景、标签底色 |-| 边框 | `border` | `border` | 分隔线、输入框边框 |-| 输入框边框 | `input` | `input` | 比 border 略重 |-| 主要文字 | `foreground` | `foreground` | 标题、正文 |-| 次要文字 | `muted-foreground` | `muted-foreground` | 描述、元数据、placeholder |-| 最强调文字 | `primary` | `primary` | 按钮文字(反色)、关键标签 |+| Role | Light token | Dark token | Use for |+|---|---|---|---|+| Background | `page-canvas` / `background` | `page-canvas` / `background` | Page body |+| Card / floating layer | `surface` / `surface-raised` | `surface` / `surface-raised` | Bounded content groups and transient overlays |+| Secondary surface | `muted` / `secondary` | `muted` / `secondary` | Hover backgrounds, tag fills |+| Border | `border` | `border` | Dividers, input borders |+| Input border | `input` | `input` | Slightly heavier than `border` |+| Primary text | `foreground` | `foreground` | Headings, body copy |+| Secondary text | `muted-foreground` | `muted-foreground` | Descriptions, metadata, placeholders |+| Strongest text | `primary` | `primary` | Button labels (inverted), key tags |-**规则:** 同一屏幕内,文字颜色最多使用 3 个层级(`foreground` / `muted-foreground` / 某个语义色)。超过 3 级说明层次设计有问题。+**Rule:** within one screen, use at most three text-colour levels (`foreground` / `muted-foreground` / one semantic colour). More than three means the hierarchy itself is wrong.-### 2.3 语义色+### 2.3 Semantic colours-颜色只用于传递含义,不做装饰:+Colour conveys meaning; it never decorates:-| Token | 含义 | 使用场景 |-|-------|------|----------|-| `brand` | 品牌标识 | Logo、品牌按钮、极少量强调 |-| `destructive` | 危险/错误 | 删除按钮、表单校验错误、危险操作 |-| `success` | 成功 | 状态标签(完成、已解决) |-| `warning` | 警告 | 注意状态、到期提醒 |-| `info` | 信息 | 提示、链接、次要信息标记 |-| `priority` | 优先级 | 高优先级标签 |+| Token | Meaning | Where it appears |+|---|---|---|+| `brand` | Brand identity | Logo, brand buttons, a very small amount of emphasis |+| `destructive` | Danger / error | Delete buttons, form validation errors, destructive actions |+| `success` | Success | Status tags (done, resolved) |+| `warning` | Warning | Attention states, due-date reminders |+| `info` | Information | Hints, links, secondary markers |+| `priority` | Priority | High-priority tags |-**规则:**-- 语义色主要用于小面积元素(badge、icon、border)。大面积着色用该色的 10%-20% 透明度变体(如 `bg-destructive/10`)。-- 每屏同时出现的语义色不宜超过 2-3 种。如果一个界面同时有红黄绿蓝紫,说明信息密度过高,需要重新组织。+**Rules:**-### 2.4 暗色模式+- Semantic colours belong on small elements (badge, icon, border). For a large fill, use a 10–20% alpha variant of the same colour (e.g. `bg-destructive/10`).+- No more than two or three semantic colours on screen at once. If an interface shows red, yellow, green, blue, and purple simultaneously, the information density is too high and the content needs reorganising.-暗色模式不是简单的反转。它是独立设计的一套配色:+### 2.4 Dark mode-- 背景使用深灰(`oklch(0.18 ...)`),不是纯黑——纯黑在 LCD 屏上刺眼。-- 边框使用 `oklch(1 0 0 / 10%)`(白色 10% 透明度),比 light 模式更微妙。-- 语义色在 dark 模式下适当提亮(如 `success` 从 `0.55` 提到 `0.65`),保证对比度。-- 所有 UI 变更必须同时在两个模式下验证。+Dark mode is not an inversion. It is a separately designed palette:++- Backgrounds use a deep grey (`oklch(0.18 ...)`), not pure black — pure black is harsh on LCD panels.+- Borders use `oklch(1 0 0 / 10%)` (white at 10% alpha), subtler than in light mode.+- Semantic colours are lifted in dark mode (e.g. `success` from `0.55` to `0.65`) to hold contrast.+- Every UI change must be verified in both modes.----## 3. 字体规范+## 3. Typography++### 3.1 Font families-### 3.1 字体家族+| Role | Font | Use for |+|---|---|---|+| Body / UI | Inter (`--font-sans`) | Default for all interface text; CJK characters fall back automatically to the system font (PingFang SC / Microsoft YaHei / Noto Sans CJK SC) |+| Code / data | Geist Mono (`--font-mono`) | Code blocks, IDs, timestamps, monospaced data |+| Headings | `--font-heading` (= `--font-sans`) | Page and section headings |-| 角色 | 字体 | 用途 |-|------|------|------|-| 正文/UI | Inter (`--font-sans`) | 所有界面文字的默认字体;CJK 字符自动 fallback 到系统字体(PingFang SC / Microsoft YaHei / Noto Sans CJK SC) |-| 代码/数据 | Geist Mono (`--font-mono`) | 代码块、ID、时间戳、等宽数据 |-| 标题 | `--font-heading`(= `--font-sans`) | 页面标题、区块标题 |+The font stack is declared in two places — `apps/web/app/layout.tsx` and `apps/desktop/src/renderer/src/globals.css`. Keep them in sync.-字体栈在 `apps/web/app/layout.tsx` 和 `apps/desktop/src/renderer/src/globals.css` 两处声明,修改时需同步。+### 3.2 Type-size discipline-### 3.2 字号纪律+**The entire project uses three core sizes plus one special case:**-**整个项目只使用 3 个核心字号 + 1 个特殊字号:**+| Tailwind class | Size | Role | Where |+|---|---|---|---|+| `text-base` (16px) | Body | Page titles, primary content | Page titles, editor body, empty-state copy |+| `text-sm` (14px) | Default | The workhorse size | Menu items, buttons, forms, list rows, body copy |+| `text-xs` (12px) | Supporting | Metadata, tags | Badge text, timestamps, status bar, secondary information |+| `text-[0.8rem]` | Transitional | `sm` buttons only | Reserved for shadcn `button size="sm"` |-| Tailwind Class | 大小 | 角色 | 使用场景 |-|----------------|------|------|----------|-| `text-base` (16px) | 正文 | 页面标题、主要内容 | 页面标题、编辑器正文、空状态说明 |-| `text-sm` (14px) | 默认 | 界面的主力字号 | 菜单项、按钮、表单、列表项、正文 |-| `text-xs` (12px) | 辅助 | 元数据、标签 | badge 文字、时间戳、状态栏、次要信息 |-| `text-[0.8rem]` | 过渡 | 仅限 sm 按钮 | shadcn button size="sm" 专用 |+**Forbidden:**-**禁止:**-- 使用 `text-lg`、`text-xl`、`text-2xl` 等——任务管理工具追求信息密度,不需要大字号。-- 使用任意像素值如 `text-[11px]`、`text-[13px]`——坚持 Tailwind 内置 scale。-- 在同一个区块里混用超过 2 个字号。如果需要第 3 个字号来区分层次,先试试用 `font-medium` vs `font-normal` 或 `text-muted-foreground` 来解决。+- `text-lg`, `text-xl`, `text-2xl`, and friends — a task-management tool optimises for information density and does not need large type.+- Arbitrary pixel values such as `text-[11px]` or `text-[13px]` — stay on Tailwind's built-in scale.+- More than two sizes inside one block. If you need a third size to express hierarchy, try `font-medium` vs `font-normal`, or `text-muted-foreground`, first.-### 3.3 字重+### 3.3 Font weight-只使用两个:+Two weights only:-| 字重 | 用途 |-|------|------|-| `font-normal` (400) | 正文、描述、大部分文字 |-| `font-medium` (500) | 标签、按钮、导航项、标题、选中状态 |+| Weight | Use for |+|---|---|+| `font-normal` (400) | Body copy, descriptions, most text |+| `font-medium` (500) | Labels, buttons, navigation items, headings, selected state |-**禁止** `font-bold` / `font-semibold`——任务管理工具追求信息密度和"轻"感,加粗会破坏层次节奏。如果需要更强的强调,用更大的字号或 `foreground` 色值,而不是加粗。+**`font-bold` and `font-semibold` are forbidden.** A density-oriented tool needs to feel light, and heavy weights break the rhythm of the hierarchy. When you need stronger emphasis, use a larger size or the `foreground` colour — not more weight.----## 4. 间距体系+## 4. Spacing-基于 Tailwind 的 4px 基础网格。间距传递信息——它不只是"好看",而是告诉用户"什么属于什么"。+Built on Tailwind's 4px base grid. Spacing carries information: it is not "what looks nice", it tells the user what belongs to what.-### 4.1 间距语义+### 4.1 Spacing semantics-| 间距 | Tailwind | 含义 |-|------|----------|------|-| 4px | `gap-1` / `p-1` | **紧密关联** — icon 与文字、label 与值 |-| 6px | `gap-1.5` / `p-1.5` | **组件内部** — 按钮内部 padding、列表项间距 |-| 8px | `gap-2` / `p-2` | **同组不同项** — 表单字段间、列表项间 |-| 12px | `gap-3` / `p-3` | **小节内** — 卡片内部 padding |-| 16px | `gap-4` / `p-4` | **组间分隔** — 不同区块之间 |-| 24px | `gap-6` / `p-6` | **大节分隔** — 页面主要区域间 |+| Spacing | Tailwind | Meaning |+|---|---|---|+| 4px | `gap-1` / `p-1` | **Tightly bound** — icon and label, label and value |+| 6px | `gap-1.5` / `p-1.5` | **Inside a component** — button padding, list-row spacing |+| 8px | `gap-2` / `p-2` | **Sibling items in a group** — between form fields, between list rows |+| 12px | `gap-3` / `p-3` | **Within a section** — card padding |+| 16px | `gap-4` / `p-4` | **Between groups** — separating distinct blocks |+| 24px | `gap-6` / `p-6` | **Between major sections** — top-level page regions |-**规则:如果需要分割线,说明间距不够。** 优先通过增大间距来分隔内容,而不是加 `<Separator />`。分割线应该是最后手段。+**Rule: if you need a divider, your spacing is too tight.** Prefer increasing spacing over adding a `<Separator />`. A divider is the last resort.-### 4.2 容器策略(按优先级排序)+### 4.2 Container strategy, in order of preference-当需要在视觉上分隔两个区域时:+When two regions need visual separation:-1. **仅间距** — 增大两个区域的间距(首选)-2. **单条分割线** — 一根细线 `border-border`-3. **背景色变化** — 一个区域用 `bg-surface-hover` 或 `bg-surface`-4. **完整卡片** — border + radius + padding(最重手段)+1. **Spacing alone** — increase the gap (preferred)+2. **A single divider** — one hairline, `border-border`+3. **A background shift** — give one region `bg-surface-hover` or `bg-surface`+4. **A full card** — border + radius + padding (heaviest)-用最轻的工具完成分隔。+Use the lightest tool that achieves the separation.----## 5. 交互状态+## 5. Interaction states-这是设计一致性的核心。每种状态必须在所有组件中表现一致。+This is the core of visual consistency. Every state must look the same across every component.-### 5.1 状态层级概览+### 5.1 State progression```-默认 (rest) → hover → active/pressed → selected/active → focused → disabled+rest → hover → active/pressed → selected/active → focused → disabled```-### 5.2 Hover 状态+### 5.2 Hover-Hover 是"我注意到你了",视觉变化应该轻微、即时:+Hover says "I noticed you". The change should be slight and immediate:-| 元素类型 | Hover 效果 | Token |-|----------|-----------|-------|-| 列表项/菜单项 | 背景变浅灰 | `hover:bg-muted` |-| Ghost 按钮 | 背景变浅灰 + 文字变前景色 | `hover:bg-muted hover:text-foreground` |-| 次要按钮 | 背景加深 20% | `hover:bg-secondary/80` |-| 主按钮 | 背景加深 20% | `hover:bg-primary/80` |-| 文字链接 | 下划线出现 | `hover:underline` |-| Tab 标签 | 文字从次要变主要 | `hover:text-foreground`(从 `text-muted-foreground`) |-| 图标按钮 | 背景变浅灰 | `hover:bg-muted` |-| 危险按钮 | 背景透明度加深 | `hover:bg-destructive/20` |+| Element | Hover effect | Token |+|---|---|---|+| List row / menu item | Background lightens to grey | `hover:bg-muted` |+| Ghost button | Grey background + text to foreground | `hover:bg-muted hover:text-foreground` |+| Secondary button | Background darkens 20% | `hover:bg-secondary/80` |+| Primary button | Background darkens 20% | `hover:bg-primary/80` |+| Text link | Underline appears | `hover:underline` |+| Tab | Text goes from secondary to primary | `hover:text-foreground` (from `text-muted-foreground`) |+| Icon button | Grey background | `hover:bg-muted` |+| Destructive button | Background alpha deepens | `hover:bg-destructive/20` |-**规则:**-- hover 时不改变尺寸(无 `scale`)、不加阴影(无 `shadow`)。-- hover 的背景色永远比 selected/active 更淡。这样用户能区分"悬停"和"已选中"。-- 所有 hover 使用 `transition-colors`、`transition-shadow` 或列出具体属性;不要使用 `transition-all`。时长由 Tailwind 默认值(150ms)处理,不需要自定义。+**Rules:**-### 5.3 Active / Selected 状态+- Hover never changes size (no `scale`) and never adds a shadow.+- A hover background is always lighter than selected/active, so the user can tell "hovering" from "selected".+- Use `transition-colors`, `transition-shadow`, or an explicit property list — never `transition-all`. Duration comes from Tailwind's default (150ms); do not customise it.-Active 是"我已经被选中了",视觉比 hover 更重:+### 5.3 Active / selected-| 元素类型 | Active 效果 | Token |-|----------|------------|-------|-| Sidebar 菜单项 | 背景 + 文字加重 + font-medium | `data-active:bg-sidebar-accent data-active:font-medium` |-| Tab | 下方指示条 + 文字变前景色 + font-medium | `data-[state=active]:text-foreground` |-| 列表选中行 | 背景加深 | `bg-muted` 或 `bg-accent` |-| Toggle(开) | 背景反色 | `data-[state=on]:bg-primary data-[state=on]:text-primary-foreground` |+Active says "I am the chosen one". It is visually heavier than hover:-**关键区分:** Hover = `bg-muted`,Active = `bg-muted` + `font-medium` + `text-foreground`。Active 始终比 hover 多一个视觉维度(字重或颜色变化),而不仅仅是背景更深。+| Element | Active effect | Token |+|---|---|---|+| Sidebar menu item | Background + heavier text + `font-medium` | `data-active:bg-sidebar-accent data-active:font-medium` |+| Tab | Underline indicator + foreground text + `font-medium` | `data-[state=active]:text-foreground` |+| Selected list row | Deeper background | `bg-muted` or `bg-accent` |+| Toggle (on) | Inverted background | `data-[state=on]:bg-primary data-[state=on]:text-primary-foreground` |-### 5.3.1 Active 不被 Hover 覆盖+**The key distinction:** hover = `bg-muted`; active = `bg-muted` + `font-medium` + `text-foreground`. Active always adds a visual dimension beyond a darker background — weight or colour.-这是最容易出 bug 的地方:用户 hover 到一个已选中的项目上,hover 样式覆盖了 active 样式,导致选中态"闪回"普通 hover 态,视觉上像取消了选中。+### 5.3.1 Active must survive hover-**原则:Active 状态在任何时候都必须保持可辨识——包括被 hover 时。**+This is the most common source of bugs: the user hovers an already-selected item, the hover style overrides the active style, and the selection appears to "flash back" to a plain hover — visually reading as a deselection.-实现方式:+**Principle: an active state must stay identifiable at all times, including while hovered.**-**方式一:Active 使用 hover 不涉及的维度**+Three ways to achieve it:-如果 hover 只改背景,那 active 用字重 + 文字颜色来区分。即使 hover 背景叠上去,字重和颜色不变,用户仍能识别"这个是选中的":+**Option 1 — express active on a dimension hover does not touch.**++If hover only changes the background, express active through weight and text colour. Even when the hover background lands on top, weight and colour are unchanged and the user still reads "this one is selected":```-// ✅ hover 只管背景,active 靠字重和颜色-hover:bg-muted // hover:浅灰背景-data-active:font-medium data-active:text-foreground // active:字重+颜色(hover 不会覆盖)+// ✅ hover owns the background; active owns weight and colour+hover:bg-muted // hover: light grey background+data-active:font-medium data-active:text-foreground // active: weight + colour (hover cannot override)```-**方式二:Active + Hover 组合样式**+**Option 2 — an explicit active+hover compound style.**-当 active 也用了背景色时,需要显式定义 "active 且 hover" 的复合状态,确保 hover 不会把 active 的背景拉回低层级:+When active also uses a background colour, define the "active and hovered" compound state explicitly so hover cannot drag the active background back down a level:```tsx-// ✅ 显式处理 active+hover 复合态+// ✅ compound state handled explicitlycn(- "hover:bg-muted/50", // 普通 hover+ "hover:bg-muted/50", // plain hover"data-active:bg-muted data-active:text-foreground", // active- "data-active:hover:bg-muted" // active+hover:保持 active 背景,不降级+ "data-active:hover:bg-muted" // active+hover: hold the active background, no downgrade)``````tsx-// ❌ 反例:hover 覆盖 active+// ❌ anti-pattern: hover overrides activecn(- "hover:bg-muted/50", // hover 背景比 active 更淡- "data-active:bg-muted", // active 背景- // 没有处理复合态 → hover 到 active 项时背景从 muted 闪回 muted/50+ "hover:bg-muted/50", // hover background is lighter than active+ "data-active:bg-muted", // active background+ // compound state unhandled → hovering an active row flashes from muted back to muted/50)```-**方式三:CSS 选择器优先级**+**Option 3 — CSS selector specificity.**-利用 `:not()` 让 hover 只作用于非 active 的元素:+Use `:not()` so hover only applies to non-active elements:```-// ✅ hover 不作用于 active 项+// ✅ hover does not apply to the active item[data-active]:bg-muted [data-active]:text-foregroundnot-data-active:hover:bg-muted/50```-**检查方法:** 写完任何带 hover + active 状态的组件后,必须手动验证——先点击选中一项,然后鼠标移到该项上再移开,确认视觉不会"闪烁"或"降级"。+**How to check:** after writing any component with both hover and active states, verify by hand — select an item, move the pointer onto it and off again, and confirm nothing flickers or downgrades.-### 5.4 Pressed 状态+### 5.4 Pressed-物理反馈感——按下按钮时有微小的位移:+Physical feedback — a tiny displacement on press:```active:not-aria-[haspopup]:translate-y-px```-这个 1px 的下移在 shadcn button 上已全局配置。对于触发弹出菜单的按钮不添加(因为弹出即松开,位移会闪烁)。+This 1px shift is configured globally on the shadcn button. It is excluded for buttons that open a popup, because the popup appears on release and the shift would flicker.-### 5.5 Focus 状态+### 5.5 Focus-Focus 为键盘导航服务。所有可交互元素统一使用:+Focus serves keyboard navigation. Every interactive element uses:```focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50```-- 使用 `focus-visible`(非 `focus`),避免鼠标点击时出现 focus ring。-- ring 颜色使用 `ring` token(中灰),不跟组件颜色走——保持全局一致。+- Use `focus-visible`, not `focus`, so a mouse click does not produce a focus ring.+- The ring uses the `ring` token (mid grey) and does not follow the component's own colour — it stays globally consistent.-### 5.6 Disabled 状态+### 5.6 Disabled```disabled:pointer-events-none disabled:opacity-50```-简单统一。不需要为每个组件定制 disabled 样式。+Simple and uniform. Do not customise disabled styling per component.-### 5.7 Error / Invalid 状态+### 5.7 Error / invalid```aria-invalid:border-destructive aria-invalid:ring-destructive/20```-- 使用 `aria-invalid` 属性触发,与表单校验库自然对接。-- 只改变边框和 ring,不改背景。错误信息用内联文字展示,不用 toast 或 alert banner。+- Triggered by the `aria-invalid` attribute, which maps naturally onto form-validation libraries.+- Only the border and ring change; the background does not. Error messages render as inline text, never as a toast or alert banner.----## 6. 图标规范+## 6. Icons++### 6.1 Icon library-### 6.1 图标库+**Lucide React** (`lucide-react`) exclusively.-统一使用 **Lucide React**(`lucide-react`)。+Do not mix in other icon libraries (Heroicons, Phosphor, etc.), and do not hand-roll SVG icons unless Lucide genuinely lacks a suitable one.-禁止混用其他图标库(Heroicons、Phosphor 等),也禁止自制 SVG 图标(除非 Lucide 确实没有合适的)。+### 6.2 Icon sizing-### 6.2 图标尺寸+Icon size is bound to component size:-图标尺寸与组件尺寸绑定:+| Component size | Icon size | Example |+|---|---|---|+| xs (`h-6`) | `size-3` (12px) | Compact buttons, icons inside a badge |+| sm (`h-7`) | `size-3.5` (14px) | Small buttons, compact lists |+| default (`h-8`) | `size-4` (16px) | Standard buttons, menu items, table actions |+| lg (`h-9`) | `size-4` (16px) | Large buttons (the icon does not need to grow) |-| 组件尺寸 | 图标尺寸 | 示例 |-|----------|---------|------|-| xs(h-6) | `size-3` (12px) | 紧凑按钮、badge 内图标 |-| sm(h-7) | `size-3.5` (14px) | 小按钮、紧凑列表 |-| default(h-8) | `size-4` (16px) | 标准按钮、菜单项、表格操作 |-| lg(h-9) | `size-4` (16px) | 大按钮(图标不需要更大) |+**Rules:**-**规则:**-- 独立装饰性图标(如空状态插图)最大 `size-8` (32px)。-- 所有图标默认继承父元素文字颜色。需要弱化时用 `text-muted-foreground`。-- 图标与文字的间距:`gap-1`(xs)/ `gap-1.5`(sm/default)/ `gap-2`(宽松排列)。+- A standalone decorative icon (an empty-state illustration, say) is at most `size-8` (32px).+- Icons inherit the parent's text colour by default. To de-emphasise, use `text-muted-foreground`.+- Icon-to-text spacing: `gap-1` (xs) / `gap-1.5` (sm and default) / `gap-2` (loose arrangements).-### 6.3 图标颜色+### 6.3 Icon colour-- **导航/操作图标:** `text-muted-foreground`,hover 时跟随文字变为 `text-foreground`-- **状态图标:** 使用对应语义色(如 `text-success`、`text-destructive`)-- **Active 状态图标:** `text-foreground`+- **Navigation / action icons:** `text-muted-foreground`, following the text to `text-foreground` on hover+- **Status icons:** the matching semantic colour (`text-success`, `text-destructive`, …)+- **Active-state icons:** `text-foreground`----## 7. 圆角规范+## 7. Border radius-基于 `--radius: 0.625rem`(10px)的动态 scale:+A dynamic scale derived from `--radius: 0.625rem` (10px):-| Token | 值 | 用途 |-|-------|-----|------|-| `rounded-sm` | 6px | Checkbox、小标签 |-| `rounded-md` | 8px | 输入框、小按钮、dropdown item |-| `rounded-lg` | 10px | 标准按钮、卡片、dialog |-| `rounded-xl` | 14px | 大卡片、sheet |-| `rounded-full` | 999px | 头像、pill badge |+| Token | Value | Use for |+|---|---|---|+| `rounded-sm` | 6px | Checkboxes, small tags |+| `rounded-md` | 8px | Inputs, small buttons, dropdown items |+| `rounded-lg` | 10px | Standard buttons, cards, dialogs |+| `rounded-xl` | 14px | Large cards, sheets |+| `rounded-full` | 999px | Avatars, pill badges |-**禁止** 硬编码像素值如 `rounded-[6px]`(除非 shadcn 组件内部需要响应式计算如 `rounded-[min(var(--radius-md),12px)]`)。+**Hardcoded pixel values such as `rounded-[6px]` are forbidden** — the exception is shadcn internals that need a responsive calculation, e.g. `rounded-[min(var(--radius-md),12px)]`.----## 8. 动效规范+## 8. Motion-### 8.1 原则+### 8.1 Principles-- **快速、克制。** 动效是为了帮助用户理解变化,不是展示技术。-- **淡入淡出优先。** 元素出现/消失优先用 opacity 过渡,而不是滑动。-- **无弹跳。** 不使用 spring / bounce 缓动。缓动曲线统一用 `ease-out`。+- **Fast and restrained.** Motion exists to help the user understand a change, not to show off.+- **Fade first.** Prefer an opacity transition over a slide when something appears or disappears.+- **No bounce.** No spring or bounce easing. Easing is uniformly `ease-out`.-### 8.2 时长+### 8.2 Duration-| 场景 | 时长 | 示例 |-|------|------|------|-| 颜色/透明度变化 | 150ms | hover 背景变化、文字颜色变化 |-| 展开/收起 | 200ms | accordion、collapsible |-| 弹层出入 | 150-200ms | dialog、dropdown、popover |-| 页面切换 | 无动效 | 路由跳转无过渡动画 |+| Case | Duration | Example |+|---|---|---|+| Colour / opacity change | 150ms | Hover background, text colour |+| Expand / collapse | 200ms | Accordion, collapsible |+| Overlay enter / exit | 150–200ms | Dialog, dropdown, popover |+| Page change | none | Route transitions have no animation |-### 8.3 使用的 transition+### 8.3 Transitions in use-| Tailwind Class | 用途 |-|----------------|------|-| `transition-colors` | 纯颜色变化(hover、active)— 首选 |-| `transition-all` | 多属性同时变化 |-| `transition-opacity` | 元素淡入淡出 |-| `transition-transform` | 位移动画(pressed 效果) |+| Tailwind class | Use for |+|---|---|+| `transition-colors` | Pure colour change (hover, active) — preferred |+| `transition-all` | Several properties changing together |+| `transition-opacity` | Fading elements in and out |+| `transition-transform` | Displacement (the pressed effect) |----## 9. 组件使用规范+## 9. Component conventions-### 9.1 shadcn 优先+### 9.1 shadcn first-所有 UI 组件优先使用已安装的 shadcn 组件(55 个可用)。新增 UI 需求时:+Prefer the already-installed shadcn components (55 available). For a new UI need:-1. 先查 shadcn 是否有对应组件 → `npx shadcn add <component>`-2. 需要变体 → 用 CVA 在现有组件上扩展-3. 确实没有 → 自建组件,但必须遵循本规范的 token / 交互状态+1. Check whether shadcn has it → `npx shadcn add <component>`+2. Need a variant → extend the existing component with CVA+3. Genuinely absent → build your own, but follow the tokens and interaction states in this document-### 9.2 按钮层级+### 9.2 Button hierarchy-从最强调到最弱:+From strongest to weakest:-| 变体 | 视觉重量 | 使用场景 |-|------|---------|----------|-| `default`(primary) | ██████ | 页面主操作(每屏最多 1 个) |-| `outline` | ████░░ | 次要操作 |-| `secondary` | ███░░░ | 辅助操作、工具栏 |-| `ghost` | █░░░░░ | 图标按钮、内联操作、紧凑工具栏 |-| `destructive` | ████░░ | 删除、危险操作(红色调) |-| `link` | █░░░░░ | 内联文字链接 |+| Variant | Visual weight | Use for |+|---|---|---|+| `default` (primary) | ██████ | The page's primary action (at most one per screen) |+| `outline` | ████░░ | Secondary actions |+| `secondary` | ███░░░ | Supporting actions, toolbars |+| `ghost` | █░░░░░ | Icon buttons, inline actions, compact toolbars |+| `destructive` | ████░░ | Delete and other destructive actions (red) |+| `link` | █░░░░░ | Inline text links |-**规则:** 一个视图里的 primary 按钮最多 1 个。其他都用更弱的变体。如果有多个同等重要的操作,全部用 `outline` 或 `secondary`。+**Rule:** at most one primary button per view. Everything else uses a weaker variant. If several actions are equally important, make them all `outline` or all `secondary`.-### 9.3 Dropdown / Popover+### 9.3 Dropdown / popover-- 内容宽度使用 `w-auto`,**禁止** 固定宽度如 `w-52`、`w-56`(会导致文字换行)。-- 菜单项统一 `text-sm`,图标 `size-4`。-- 选中项通过 checkmark 图标或左侧指示条标记,不改变背景色。-- 危险操作项使用 `text-destructive`,放在最底部,上方用分割线隔开。+- Content width uses `w-auto`. **Fixed widths such as `w-52` or `w-56` are forbidden** — they force text to wrap.+- Menu items are uniformly `text-sm` with `size-4` icons.+- Mark the selected item with a checkmark icon or a leading indicator, not a background change.+- Destructive items use `text-destructive`, sit at the bottom, and are separated by a divider above.-### 9.4 表单输入+### 9.4 Form inputs-- 输入框统一使用 `border-input` 边框,focus 时 `border-ring` + ring。-- Label 使用 `text-sm font-medium`。-- 描述/帮助文字使用 `text-xs text-muted-foreground`。-- 错误信息使用 `text-xs text-destructive`,放在输入框正下方。+- Inputs use a `border-input` border, switching to `border-ring` plus a ring on focus.+- Labels use `text-sm font-medium`.+- Description and help text use `text-xs text-muted-foreground`.+- Error messages use `text-xs text-destructive`, directly below the input.----## 10. 反模式清单+## 10. Anti-patterns-以下做法**禁止**出现在代码中:+The following are **forbidden** in the codebase:-| 禁止 | 原因 | 替代 |-|------|------|------|-| 硬编码颜色 `text-red-500`、`bg-gray-100` | 破坏主题一致性 | 使用 token:`text-destructive`、`bg-muted` |-| 任意像素 `text-[11px]`、`w-[137px]` | 脱离设计系统 | 使用 Tailwind 内置 scale |-| `font-bold` / `font-semibold` | 过重,破坏轻感 | `font-medium` + `text-foreground` |-| `text-lg` / `text-xl` / `text-2xl` | 信息密度型工具不需要大字 | `text-base` 已是最大 |-| `shadow-sm` / `shadow-md` / `shadow-lg` | 拟物风格,与扁平设计冲突 | 使用 `border` 分隔层级 |-| hover 时 `scale-105` | 突兀,与克制风格冲突 | `hover:bg-muted` |-| 多色 gradient 背景 | 装饰性,分散注意力 | 纯色 token |-| Skeleton loading | 与简洁风格不匹配 | Spinner(`Loader2Icon animate-spin`)或内联 loading 文字 |-| Toast 做操作确认 | 转瞬即逝,用户容易错过 | 内联状态文字或 Sonner 仅用于错误/重要提示 |-| 固定宽度 dropdown `w-52` | 文字换行不可控 | `w-auto` |-| 纯黑背景 `#000` / `oklch(0 0 0)` | LCD 上刺眼 | Dark 模式用深灰 `background` token |+| Forbidden | Why | Instead |+|---|---|---|+| Hardcoded colours `text-red-500`, `bg-gray-100` | Breaks theme consistency | Use tokens: `text-destructive`, `bg-muted` |+| Arbitrary values `text-[11px]`, `w-[137px]` | Escapes the design system | Use Tailwind's built-in scale |+| `font-bold` / `font-semibold` | Too heavy; breaks the light feel | `font-medium` + `text-foreground` |+| `text-lg` / `text-xl` / `text-2xl` | A density-oriented tool does not need large type | `text-base` is already the maximum |+| `shadow-sm` / `shadow-md` / `shadow-lg` | Skeuomorphic; conflicts with a flat design | Use `border` to separate levels |+| `scale-105` on hover | Jarring; conflicts with a restrained style | `hover:bg-muted` |+| Multi-colour gradient backgrounds | Decorative; distracting | A solid token colour |+| Skeleton loading | Does not match the minimal style | A spinner (`Loader2Icon animate-spin`) or inline loading text |+| A toast to confirm an action | Transient; easy to miss | Inline status text; reserve Sonner for errors and important notices |+| Fixed-width dropdown `w-52` | Text wrapping is uncontrollable | `w-auto` |+| Pure black background `#000` / `oklch(0 0 0)` | Harsh on LCD | Use the deep-grey `background` token in dark mode |----## 11. 检查清单--在提交任何 UI 变更前,过一遍:--- [ ] 所有颜色是否使用 token?有没有硬编码?-- [ ] 字号是否只在 `text-xs` / `text-sm` / `text-base` 范围内?-- [ ] 字重是否只用了 `font-normal` 和 `font-medium`?-- [ ] Hover 状态是否比 active 状态更淡?-- [ ] Active 项被 hover 时,active 样式是否仍然可辨识(不被 hover 覆盖)?-- [ ] 图标尺寸是否与组件尺寸匹配?-- [ ] 间距是否使用 Tailwind 内置 scale(无任意值)?-- [ ] Dark 模式下是否正常?-- [ ] 有没有不必要的分割线(可以用间距替代)?-- [ ] Dropdown / Popover 是否 `w-auto`?-- [ ] 一个视图里 primary 按钮是否不超过 1 个?+## 11. Checklist++Run through this before submitting any UI change:++- [ ] Are all colours tokens? Anything hardcoded?+- [ ] Are type sizes confined to `text-xs` / `text-sm` / `text-base`?+- [ ] Are weights confined to `font-normal` and `font-medium`?+- [ ] Is the hover state lighter than the active state?+- [ ] When an active item is hovered, does the active style stay identifiable (not overridden by hover)?+- [ ] Do icon sizes match their component sizes?+- [ ] Is spacing on Tailwind's built-in scale (no arbitrary values)?+- [ ] Does it work in dark mode?+- [ ] Are there unnecessary dividers that spacing could replace?+- [ ] Are dropdowns and popovers `w-auto`?+- [ ] Is there at most one primary button in the view?diff --git a/docs/design.zh.md b/docs/design.zh.mdnew file mode 100644index 0000000000..60d1bd5187--- /dev/null+++ b/docs/design.zh.md@@ -0,0 +1,445 @@+# Multica Design System++本文档定义 Multica 的视觉语言和交互规范。所有 UI 开发以此为准。++> 英文版是默认版本:[`design.md`](./design.md)。++---++## 1. 设计哲学++三条核心原则:++1. **克制即高级。** 默认做减法。每个元素必须有存在的理由——多余的分割线、装饰性图标、"以防万一"的提示文字,都是噪音。留白本身就是设计。+2. **层次靠灰度,颜色是信号。** 界面的主体是中性色。颜色只在需要传递语义时出现(状态、品牌、错误)。如果两个区域在视觉上竞争注意力,解法是让一个退后,而不是两个都加色。+3. **一致性大于个性。** 同类交互必须有相同的视觉反馈。一个 hover 效果在 sidebar、dropdown、table row 里应该"感觉一样"。这种一致性通过 token 而非硬编码实现。++---++## 2. 颜色体系++基于 OKLCh 色彩空间,通过 CSS 变量定义。所有颜色使用 shadcn token,**禁止硬编码 Tailwind 色值**(如 `text-gray-500`、`bg-blue-600`)。++### 2.1 Surface 层级++Surface 系统描述的是容器之间的关系,不是把每一段内容都包进卡片。基础 token 定义在 `packages/ui/styles/tokens.css`,并同时覆盖 light / dark mode。++| 层级 | Token / Class | 用途 | 不应用于 |+|------|---------------|------|----------|+| App Shell | `app-shell` / `bg-app-shell` | 窗口最外层、sidebar 与 page canvas 之间的留白 | 页面正文、表单组 |+| Page Canvas | `page-canvas` / `bg-page-canvas` | 页面主体;list、board、chat 等持续滚动的内容区 | 独立设置组、弹窗 |+| Surface / Card | `surface`、`surface-border`、`--surface-shadow` | 有独立边界的表单组、设置组、摘要卡 | 每一行列表、每一列 board、整页正文 |+| Floating Surface | `surface-raised`、`--floating-shadow` | dialog、dropdown、popover、sheet、浮动 chat | 常驻页面布局 |++规则:++- Page Canvas 是默认内容面。需要分组时先用间距和分割线,只有独立操作或独立信息块才使用 Surface。+- 浅色模式中,`app-shell` 与 sidebar 使用 `#f3f3f4`,`page-canvas` 使用 `#fbfbfb`,Card 使用 `#ffffff`;不能只靠 border 区分设置组和页面背景。三者形成接近 Linear 的克制层级,由外向内逐步变亮。+- Card 使用 `bg-surface border-surface-border shadow-[var(--surface-shadow)]`;浮层使用 `bg-surface-raised ring-surface-border shadow-[var(--floating-shadow)]`。+- `surface-hover` 只表示指针经过;`surface-selected` 表示持续选中,并保持中性灰,不额外叠加 brand 色。选中项 hover 时必须保留 `surface-selected`,不能退回 hover 状态。+- focus 一律使用 `focus-visible` ring。不要用阴影、尺寸变化或品牌大面积填充代替键盘焦点。+- 不为 light / dark mode 手写一组平行 class。基础 surface token 已按主题解析,并通过 `color-scheme` 同步原生控件。++### 2.2 中性色阶梯++界面 90% 的面积由中性色构成。灰度等级即信息层级:++| 角色 | Light Token | Dark Token | 用途 |+|------|-------------|------------|------|+| 背景 | `page-canvas` / `background` | `page-canvas` / `background` | 页面主体 |+| 卡片/浮层 | `surface` / `surface-raised` | `surface` / `surface-raised` | 有边界的内容组与临时覆盖层 |+| 次级表面 | `muted` / `secondary` | `muted` / `secondary` | hover 背景、标签底色 |+| 边框 | `border` | `border` | 分隔线、输入框边框 |+| 输入框边框 | `input` | `input` | 比 border 略重 |+| 主要文字 | `foreground` | `foreground` | 标题、正文 |+| 次要文字 | `muted-foreground` | `muted-foreground` | 描述、元数据、placeholder |+| 最强调文字 | `primary` | `primary` | 按钮文字(反色)、关键标签 |++**规则:** 同一屏幕内,文字颜色最多使用 3 个层级(`foreground` / `muted-foreground` / 某个语义色)。超过 3 级说明层次设计有问题。++### 2.3 语义色++颜色只用于传递含义,不做装饰:++| Token | 含义 | 使用场景 |+|-------|------|----------|+| `brand` | 品牌标识 | Logo、品牌按钮、极少量强调 |+| `destructive` | 危险/错误 | 删除按钮、表单校验错误、危险操作 |+| `success` | 成功 | 状态标签(完成、已解决) |+| `warning` | 警告 | 注意状态、到期提醒 |+| `info` | 信息 | 提示、链接、次要信息标记 |+| `priority` | 优先级 | 高优先级标签 |++**规则:**+- 语义色主要用于小面积元素(badge、icon、border)。大面积着色用该色的 10%-20% 透明度变体(如 `bg-destructive/10`)。+- 每屏同时出现的语义色不宜超过 2-3 种。如果一个界面同时有红黄绿蓝紫,说明信息密度过高,需要重新组织。++### 2.4 暗色模式++暗色模式不是简单的反转。它是独立设计的一套配色:++- 背景使用深灰(`oklch(0.18 ...)`),不是纯黑——纯黑在 LCD 屏上刺眼。+- 边框使用 `oklch(1 0 0 / 10%)`(白色 10% 透明度),比 light 模式更微妙。+- 语义色在 dark 模式下适当提亮(如 `success` 从 `0.55` 提到 `0.65`),保证对比度。+- 所有 UI 变更必须同时在两个模式下验证。++---++## 3. 字体规范++### 3.1 字体家族++| 角色 | 字体 | 用途 |+|------|------|------|+| 正文/UI | Inter (`--font-sans`) | 所有界面文字的默认字体;CJK 字符自动 fallback 到系统字体(PingFang SC / Microsoft YaHei / Noto Sans CJK SC) |+| 代码/数据 | Geist Mono (`--font-mono`) | 代码块、ID、时间戳、等宽数据 |+| 标题 | `--font-heading`(= `--font-sans`) | 页面标题、区块标题 |++字体栈在 `apps/web/app/layout.tsx` 和 `apps/desktop/src/renderer/src/globals.css` 两处声明,修改时需同步。++### 3.2 字号纪律++**整个项目只使用 3 个核心字号 + 1 个特殊字号:**++| Tailwind Class | 大小 | 角色 | 使用场景 |+|----------------|------|------|----------|+| `text-base` (16px) | 正文 | 页面标题、主要内容 | 页面标题、编辑器正文、空状态说明 |+| `text-sm` (14px) | 默认 | 界面的主力字号 | 菜单项、按钮、表单、列表项、正文 |+| `text-xs` (12px) | 辅助 | 元数据、标签 | badge 文字、时间戳、状态栏、次要信息 |+| `text-[0.8rem]` | 过渡 | 仅限 sm 按钮 | shadcn button size="sm" 专用 |++**禁止:**+- 使用 `text-lg`、`text-xl`、`text-2xl` 等——任务管理工具追求信息密度,不需要大字号。+- 使用任意像素值如 `text-[11px]`、`text-[13px]`——坚持 Tailwind 内置 scale。+- 在同一个区块里混用超过 2 个字号。如果需要第 3 个字号来区分层次,先试试用 `font-medium` vs `font-normal` 或 `text-muted-foreground` 来解决。++### 3.3 字重++只使用两个:++| 字重 | 用途 |+|------|------|+| `font-normal` (400) | 正文、描述、大部分文字 |+| `font-medium` (500) | 标签、按钮、导航项、标题、选中状态 |++**禁止** `font-bold` / `font-semibold`——任务管理工具追求信息密度和"轻"感,加粗会破坏层次节奏。如果需要更强的强调,用更大的字号或 `foreground` 色值,而不是加粗。++---++## 4. 间距体系++基于 Tailwind 的 4px 基础网格。间距传递信息——它不只是"好看",而是告诉用户"什么属于什么"。++### 4.1 间距语义++| 间距 | Tailwind | 含义 |+|------|----------|------|+| 4px | `gap-1` / `p-1` | **紧密关联** — icon 与文字、label 与值 |+| 6px | `gap-1.5` / `p-1.5` | **组件内部** — 按钮内部 padding、列表项间距 |+| 8px | `gap-2` / `p-2` | **同组不同项** — 表单字段间、列表项间 |+| 12px | `gap-3` / `p-3` | **小节内** — 卡片内部 padding |+| 16px | `gap-4` / `p-4` | **组间分隔** — 不同区块之间 |+| 24px | `gap-6` / `p-6` | **大节分隔** — 页面主要区域间 |++**规则:如果需要分割线,说明间距不够。** 优先通过增大间距来分隔内容,而不是加 `<Separator />`。分割线应该是最后手段。++### 4.2 容器策略(按优先级排序)++当需要在视觉上分隔两个区域时:++1. **仅间距** — 增大两个区域的间距(首选)+2. **单条分割线** — 一根细线 `border-border`+3. **背景色变化** — 一个区域用 `bg-surface-hover` 或 `bg-surface`+4. **完整卡片** — border + radius + padding(最重手段)++用最轻的工具完成分隔。++---++## 5. 交互状态++这是设计一致性的核心。每种状态必须在所有组件中表现一致。++### 5.1 状态层级概览++```+默认 (rest) → hover → active/pressed → selected/active → focused → disabled+```++### 5.2 Hover 状态++Hover 是"我注意到你了",视觉变化应该轻微、即时:++| 元素类型 | Hover 效果 | Token |+|----------|-----------|-------|+| 列表项/菜单项 | 背景变浅灰 | `hover:bg-muted` |+| Ghost 按钮 | 背景变浅灰 + 文字变前景色 | `hover:bg-muted hover:text-foreground` |+| 次要按钮 | 背景加深 20% | `hover:bg-secondary/80` |+| 主按钮 | 背景加深 20% | `hover:bg-primary/80` |+| 文字链接 | 下划线出现 | `hover:underline` |+| Tab 标签 | 文字从次要变主要 | `hover:text-foreground`(从 `text-muted-foreground`) |+| 图标按钮 | 背景变浅灰 | `hover:bg-muted` |+| 危险按钮 | 背景透明度加深 | `hover:bg-destructive/20` |++**规则:**+- hover 时不改变尺寸(无 `scale`)、不加阴影(无 `shadow`)。+- hover 的背景色永远比 selected/active 更淡。这样用户能区分"悬停"和"已选中"。+- 所有 hover 使用 `transition-colors`、`transition-shadow` 或列出具体属性;不要使用 `transition-all`。时长由 Tailwind 默认值(150ms)处理,不需要自定义。++### 5.3 Active / Selected 状态++Active 是"我已经被选中了",视觉比 hover 更重:++| 元素类型 | Active 效果 | Token |+|----------|------------|-------|+| Sidebar 菜单项 | 背景 + 文字加重 + font-medium | `data-active:bg-sidebar-accent data-active:font-medium` |+| Tab | 下方指示条 + 文字变前景色 + font-medium | `data-[state=active]:text-foreground` |+| 列表选中行 | 背景加深 | `bg-muted` 或 `bg-accent` |+| Toggle(开) | 背景反色 | `data-[state=on]:bg-primary data-[state=on]:text-primary-foreground` |++**关键区分:** Hover = `bg-muted`,Active = `bg-muted` + `font-medium` + `text-foreground`。Active 始终比 hover 多一个视觉维度(字重或颜色变化),而不仅仅是背景更深。++### 5.3.1 Active 不被 Hover 覆盖++这是最容易出 bug 的地方:用户 hover 到一个已选中的项目上,hover 样式覆盖了 active 样式,导致选中态"闪回"普通 hover 态,视觉上像取消了选中。++**原则:Active 状态在任何时候都必须保持可辨识——包括被 hover 时。**++实现方式:++**方式一:Active 使用 hover 不涉及的维度**++如果 hover 只改背景,那 active 用字重 + 文字颜色来区分。即使 hover 背景叠上去,字重和颜色不变,用户仍能识别"这个是选中的":++```+// ✅ hover 只管背景,active 靠字重和颜色+hover:bg-muted // hover:浅灰背景+data-active:font-medium data-active:text-foreground // active:字重+颜色(hover 不会覆盖)+```++**方式二:Active + Hover 组合样式**++当 active 也用了背景色时,需要显式定义 "active 且 hover" 的复合状态,确保 hover 不会把 active 的背景拉回低层级:++```tsx+// ✅ 显式处理 active+hover 复合态+cn(+ "hover:bg-muted/50", // 普通 hover+ "data-active:bg-muted data-active:text-foreground", // active+ "data-active:hover:bg-muted" // active+hover:保持 active 背景,不降级+)+```++```tsx+// ❌ 反例:hover 覆盖 active+cn(+ "hover:bg-muted/50", // hover 背景比 active 更淡+ "data-active:bg-muted", // active 背景+ // 没有处理复合态 → hover 到 active 项时背景从 muted 闪回 muted/50+)+```++**方式三:CSS 选择器优先级**++利用 `:not()` 让 hover 只作用于非 active 的元素:++```+// ✅ hover 不作用于 active 项+[data-active]:bg-muted [data-active]:text-foreground+not-data-active:hover:bg-muted/50+```++**检查方法:** 写完任何带 hover + active 状态的组件后,必须手动验证——先点击选中一项,然后鼠标移到该项上再移开,确认视觉不会"闪烁"或"降级"。++### 5.4 Pressed 状态++物理反馈感——按下按钮时有微小的位移:++```+active:not-aria-[haspopup]:translate-y-px+```++这个 1px 的下移在 shadcn button 上已全局配置。对于触发弹出菜单的按钮不添加(因为弹出即松开,位移会闪烁)。++### 5.5 Focus 状态++Focus 为键盘导航服务。所有可交互元素统一使用:++```+focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50+```++- 使用 `focus-visible`(非 `focus`),避免鼠标点击时出现 focus ring。+- ring 颜色使用 `ring` token(中灰),不跟组件颜色走——保持全局一致。++### 5.6 Disabled 状态++```+disabled:pointer-events-none disabled:opacity-50+```++简单统一。不需要为每个组件定制 disabled 样式。++### 5.7 Error / Invalid 状态++```+aria-invalid:border-destructive aria-invalid:ring-destructive/20+```++- 使用 `aria-invalid` 属性触发,与表单校验库自然对接。+- 只改变边框和 ring,不改背景。错误信息用内联文字展示,不用 toast 或 alert banner。++---++## 6. 图标规范++### 6.1 图标库++统一使用 **Lucide React**(`lucide-react`)。++禁止混用其他图标库(Heroicons、Phosphor 等),也禁止自制 SVG 图标(除非 Lucide 确实没有合适的)。++### 6.2 图标尺寸++图标尺寸与组件尺寸绑定:++| 组件尺寸 | 图标尺寸 | 示例 |+|----------|---------|------|+| xs(h-6) | `size-3` (12px) | 紧凑按钮、badge 内图标 |+| sm(h-7) | `size-3.5` (14px) | 小按钮、紧凑列表 |+| default(h-8) | `size-4` (16px) | 标准按钮、菜单项、表格操作 |+| lg(h-9) | `size-4` (16px) | 大按钮(图标不需要更大) |++**规则:**+- 独立装饰性图标(如空状态插图)最大 `size-8` (32px)。+- 所有图标默认继承父元素文字颜色。需要弱化时用 `text-muted-foreground`。+- 图标与文字的间距:`gap-1`(xs)/ `gap-1.5`(sm/default)/ `gap-2`(宽松排列)。++### 6.3 图标颜色++- **导航/操作图标:** `text-muted-foreground`,hover 时跟随文字变为 `text-foreground`+- **状态图标:** 使用对应语义色(如 `text-success`、`text-destructive`)+- **Active 状态图标:** `text-foreground`++---++## 7. 圆角规范++基于 `--radius: 0.625rem`(10px)的动态 scale:++| Token | 值 | 用途 |+|-------|-----|------|+| `rounded-sm` | 6px | Checkbox、小标签 |+| `rounded-md` | 8px | 输入框、小按钮、dropdown item |+| `rounded-lg` | 10px | 标准按钮、卡片、dialog |+| `rounded-xl` | 14px | 大卡片、sheet |+| `rounded-full` | 999px | 头像、pill badge |++**禁止** 硬编码像素值如 `rounded-[6px]`(除非 shadcn 组件内部需要响应式计算如 `rounded-[min(var(--radius-md),12px)]`)。++---++## 8. 动效规范++### 8.1 原则++- **快速、克制。** 动效是为了帮助用户理解变化,不是展示技术。+- **淡入淡出优先。** 元素出现/消失优先用 opacity 过渡,而不是滑动。+- **无弹跳。** 不使用 spring / bounce 缓动。缓动曲线统一用 `ease-out`。++### 8.2 时长++| 场景 | 时长 | 示例 |+|------|------|------|+| 颜色/透明度变化 | 150ms | hover 背景变化、文字颜色变化 |+| 展开/收起 | 200ms | accordion、collapsible |+| 弹层出入 | 150-200ms | dialog、dropdown、popover |+| 页面切换 | 无动效 | 路由跳转无过渡动画 |++### 8.3 使用的 transition++| Tailwind Class | 用途 |+|----------------|------|+| `transition-colors` | 纯颜色变化(hover、active)— 首选 |+| `transition-all` | 多属性同时变化 |+| `transition-opacity` | 元素淡入淡出 |+| `transition-transform` | 位移动画(pressed 效果) |++---++## 9. 组件使用规范++### 9.1 shadcn 优先++所有 UI 组件优先使用已安装的 shadcn 组件(55 个可用)。新增 UI 需求时:++1. 先查 shadcn 是否有对应组件 → `npx shadcn add <component>`+2. 需要变体 → 用 CVA 在现有组件上扩展+3. 确实没有 → 自建组件,但必须遵循本规范的 token / 交互状态++### 9.2 按钮层级++从最强调到最弱:++| 变体 | 视觉重量 | 使用场景 |+|------|---------|----------|+| `default`(primary) | ██████ | 页面主操作(每屏最多 1 个) |+| `outline` | ████░░ | 次要操作 |+| `secondary` | ███░░░ | 辅助操作、工具栏 |+| `ghost` | █░░░░░ | 图标按钮、内联操作、紧凑工具栏 |+| `destructive` | ████░░ | 删除、危险操作(红色调) |+| `link` | █░░░░░ | 内联文字链接 |++**规则:** 一个视图里的 primary 按钮最多 1 个。其他都用更弱的变体。如果有多个同等重要的操作,全部用 `outline` 或 `secondary`。++### 9.3 Dropdown / Popover++- 内容宽度使用 `w-auto`,**禁止** 固定宽度如 `w-52`、`w-56`(会导致文字换行)。+- 菜单项统一 `text-sm`,图标 `size-4`。+- 选中项通过 checkmark 图标或左侧指示条标记,不改变背景色。+- 危险操作项使用 `text-destructive`,放在最底部,上方用分割线隔开。++### 9.4 表单输入++- 输入框统一使用 `border-input` 边框,focus 时 `border-ring` + ring。+- Label 使用 `text-sm font-medium`。+- 描述/帮助文字使用 `text-xs text-muted-foreground`。+- 错误信息使用 `text-xs text-destructive`,放在输入框正下方。++---++## 10. 反模式清单++以下做法**禁止**出现在代码中:++| 禁止 | 原因 | 替代 |+|------|------|------|+| 硬编码颜色 `text-red-500`、`bg-gray-100` | 破坏主题一致性 | 使用 token:`text-destructive`、`bg-muted` |+| 任意像素 `text-[11px]`、`w-[137px]` | 脱离设计系统 | 使用 Tailwind 内置 scale |+| `font-bold` / `font-semibold` | 过重,破坏轻感 | `font-medium` + `text-foreground` |+| `text-lg` / `text-xl` / `text-2xl` | 信息密度型工具不需要大字 | `text-base` 已是最大 |+| `shadow-sm` / `shadow-md` / `shadow-lg` | 拟物风格,与扁平设计冲突 | 使用 `border` 分隔层级 |+| hover 时 `scale-105` | 突兀,与克制风格冲突 | `hover:bg-muted` |+| 多色 gradient 背景 | 装饰性,分散注意力 | 纯色 token |+| Skeleton loading | 与简洁风格不匹配 | Spinner(`Loader2Icon animate-spin`)或内联 loading 文字 |+| Toast 做操作确认 | 转瞬即逝,用户容易错过 | 内联状态文字或 Sonner 仅用于错误/重要提示 |+| 固定宽度 dropdown `w-52` | 文字换行不可控 | `w-auto` |+| 纯黑背景 `#000` / `oklch(0 0 0)` | LCD 上刺眼 | Dark 模式用深灰 `background` token |++---++## 11. 检查清单++在提交任何 UI 变更前,过一遍:++- [ ] 所有颜色是否使用 token?有没有硬编码?+- [ ] 字号是否只在 `text-xs` / `text-sm` / `text-base` 范围内?+- [ ] 字重是否只用了 `font-normal` 和 `font-medium`?+- [ ] Hover 状态是否比 active 状态更淡?+- [ ] Active 项被 hover 时,active 样式是否仍然可辨识(不被 hover 覆盖)?+- [ ] 图标尺寸是否与组件尺寸匹配?+- [ ] 间距是否使用 Tailwind 内置 scale(无任意值)?+- [ ] Dark 模式下是否正常?+- [ ] 有没有不必要的分割线(可以用间距替代)?+- [ ] Dropdown / Popover 是否 `w-auto`?+- [ ] 一个视图里 primary 按钮是否不超过 1 个?diff --git a/docs/docs-onboarding-optimization-plan.md b/docs/docs-onboarding-optimization-plan.mddeleted file mode 100644index f9e1a529fc..0000000000--- a/docs/docs-onboarding-optimization-plan.md+++ /dev/null@@ -1,117 +0,0 @@-# Multica 中文文档优化计划--> 状态:中文正文与目录已完成,产品截图待逐步补充。->-> 工作目录:`/Users/qingnaiyuan/Desktop/work/multica-pr-5714`--## 目标--让第一次接触 Multica 的用户能够:--1. 直接理解 Multica 是什么,以及人和智能体如何共同工作。-2. 按一条明确路径完成第一次智能体执行。-3. 明白 Multica、连接电脑、运行时和 AI 编程工具之间的关系。-4. 根据产品中的真实概念找到后续功能、集成和运维说明。--中文版本先完成并评审。英文、日文和韩文在中文结构稳定后再同步,避免四种语言反复返工。--## 当前信息架构--```text-开始使用-├─ 欢迎-├─ 快速上手-├─ Multica 是怎么工作的-└─ 自托管快速上手--工作区与团队-├─ 工作区-└─ 成员与权限--Issue 与项目-├─ Issues-├─ 项目-└─ 项目资源--智能体-├─ 智能体-├─ 创建和配置智能体-├─ Skills-└─ 小队--日常协作-├─ 把 Issue 分配给智能体-├─ 评论-├─ 通过评论调用智能体-├─ 与智能体对话-└─ 收件箱与订阅--自动化与集成-├─ 自动化-├─ 聊天集成-├─ GitHub 集成-├─ 飞书 Bot-└─ Slack Bot--运行时与执行-├─ 执行任务-├─ 守护进程与运行时-├─ 安装 AI 编程工具-└─ AI 编程工具对照--自托管与管理-├─ 环境变量-├─ 登录与注册-└─ 故障排查--客户端与 CLI-├─ 桌面应用-├─ 移动 App(iOS)-├─ 使用 CLI-└─ 认证与令牌--开发者-├─ 参与开发-├─ 项目架构-└─ 开发规范-```--目前共有 37 篇中文页面,全部进入 sidebar。旧版重复页面已经移除,并通过永久重定向保留旧链接。--## 写作原则--1. 一篇页面只解决一个主要问题。-2. 先说明用户要做什么,再补充原理和边界。-3. 使用产品中的真实概念,避免宣传性排比和抽象口号。-4. `issue`、`skill` 和 `task` 按中文术语规范使用;工作区、智能体、项目、自动化、守护进程和运行时使用中文。-5. 涉及权限、安全、失败和重试时,写清具体边界,不做绝对承诺。-6. 操作教程给出成功标志和排查入口;参考页面保留可查阅的参数、命令和状态。--## 图片计划--图片不阻塞中文正文定稿,后续按页面逐张确认。--优先补充:--1. Welcome:人和多个智能体在同一工作区协作的真实产品画面。-2. Quickstart:运行时选择、Multica Helper 入门选项、issue 执行结果。-3. 其余操作页:只有当截图能明显减少文字说明时才添加。--产品操作使用真实 UI 截图;架构和对象关系使用 React/CSS 或 SVG。图片不承担正文中没有出现的关键信息,并提供准确的 alt text。--## 已完成的验证--- 37/37 篇中文页面均在 sidebar 中。-- 所有中文站内链接和标题锚点均可解析。-- 旧版中文 URL 会重定向到对应的新页面。-- 37 个中文路由在本地开发站均返回 `200`。-- `pnpm --filter @multica/docs typecheck` 通过。-- `pnpm --filter @multica/docs test` 通过,17 个测试全部成功。-- `pnpm --filter @multica/docs build` 通过,147 个静态页面生成成功。--## 后续顺序--1. 在 `http://localhost:4000/docs/zh` 逐页评审中文文案和页面节奏。-2. 按教学价值逐张替换截图占位。-3. 检查截图的移动端、深浅色和 alt text。-4. 中文内容完全确认后,同步英文、日文和韩文。diff --git a/docs/docs-outline.md b/docs/docs-outline.mddeleted file mode 100644index a9dd4b1cfc..0000000000--- a/docs/docs-outline.md+++ /dev/null@@ -1,912 +0,0 @@-# Multica Docs 执行大纲--> 这份是**执行文档 + 协作 tracker**。每篇文档都有独立条目,委派出去的人直接在对应条目里认领、更新状态。->-> 战略思路(产品定位、读者画像、设计原则、视觉方向)保留在 [`docs-rewrite-plan.md`](./docs-rewrite-plan.md)。->-> **语言**:只写中文版。英文版暂不做。-> **V1 目标**:25 篇覆盖所有核心功能。v2 留 24 篇深度/边缘内容 pending。-------## 一、协作规则(接手任何一篇前必读)--### 1.1 写作守则(硬约束)--1. **源码优先**:每一条事实陈述必须能在源码里找到对应位置。不能从"产品宣传册"、"直觉"、"上一版本的文档"或"记忆"出发。-2. **代码里没有的功能一律不写**。即使 UI 疑似有、DB 有字段、handler 有接口但 service 层无真实读写逻辑,都视为"未实装"。遇到边界不确定的情况,标 ⚠️ 让 reviewer 再看一眼,不要硬写。-3. **下笔前先读源码验证本文件里的"写什么"清单**。这个清单是指引,不是真相。可能已过时、可能当时调研就不准。-4. **跨篇共通事实集中写**(例如 10 provider 矩阵写在 §4.3 Providers Matrix,其他篇 cross-link 过去),避免同一事实分散在多篇里。-5. **服务于产品定位**:Multica 的核心差异化是 **"BYO-agent 的 Linear—— agent 跑在你自己的机器,你掌控计算和 provider 选择"**。每篇的语气和深度都应该为这个叙事服务。-6. **为目标读者写**。不同读者期待不同深度。P0 新用户不关心 SQL 字段,P1 开发者愿意看架构图,P2 agent 读者需要命令自包含能复制。-7. **v1 认领优先**:先把 v1 的 25 篇 ship 出去,再开 v2。--### 1.2 目标读者分级--| 级别 | 读者 | 期待 |-|---|---|---|-| P0 | 新用户 / Evaluator | "这是啥?5 分钟跑起来" |-| P0 | 自托管运维 | "怎么部署?出问题怎么查?" |-| P1 | 团队管理员 / Workspace owner | "怎么配 agent?管权限?设 routines?" |-| P1 | 重度 CLI / 开发者用户 | "CLI 全集?架构细节?" |-| P2 | Agent 本身(被人类指向某页)| "每步命令要完整、可独立复制执行" |--### 1.3 状态码--- ⬜ Not started-- 🔍 Source research(正在读源码验证)-- ✍️ Drafting(正在写初稿)-- 👀 In review(待 review)-- ✅ Shipped--### 1.4 Flag(只在需要决策时填)--- 🤔 **Propose merge/drop** —— 认领后读源码发现这篇独立成页价值低,写一行理由,@ owner(Naiyuan)决策。--### 1.5 分工流程--1. **认领**:把 `Owner` 改成你的名字,`Status` 改成 🔍-2. **读源码**:用本条目的 "Source files" 作为起点,扩展看相关代码-3. **验证"写什么"清单**:发现过时/缺失/错误,直接改这个条目-4. **写初稿**:`Status` 改成 ✍️-5. **提 review**:`Status` 改成 👀,发消息 @ reviewer-6. **交付**:`Status` 改成 ✅--### 1.6 每篇目标字数--| 页面类型 | 字数范围 | 理由 |-|---|---|---|-| Concept 页(§2-§6 多数)| 800-1500 字 | 讲清一个概念 + 示例 + 关联 |-| Quickstart / Tutorial(§1.3-§1.4 / §2.1)| 500-1200 字 | 命令优先,解释从简 |-| Reference 页(§4.3 / §7-§8 多数)| 1000-2500 字 | 对照表 / env 清单 / 命令 cheatsheet,信息密度高 |-| Overview / Welcome(§1.1)| 300-600 字 | 定位 + 导航,不展开 |--**原则**:写到目标字数上限还没写完,说明该拆页或该压缩;写到下限还不够,说明内容薄,考虑合并。--### 1.7 Review Checklist(提 review 前自查)--- [ ] 每条事实陈述都能在 Source files 里找到对应代码位置-- [ ] 所有代码示例(shell / CLI)可以独立复制、独立运行(不依赖"把上面那个替换一下")-- [ ] 术语和其他页一致:workspace / agent / runtime / daemon / task / skill / routine-- [ ] 所有 cross-link 指向的目标页存在(不是死链)-- [ ] 字数在目标范围内-- [ ] 本条目"不写"清单里的字段没被写进去-- [ ] 没有从记忆或旧文档复制过来的未验证事实--### 1.8 MDX 样例模板--> 这是 §2.3 Issues 的 mdx skeleton,用来统一标题层级 / callout / code block / cross-link 风格。所有 v1 文档按这个骨架写。--```mdx-----title: Issues-description: Issue 是 Multica 的核心工作对象——人和 agent 都能被分配、评论、改状态。------# Issues--## 什么是 Issue--Issue 是 Multica 的核心工作对象……(1-2 段话说清楚"是什么")--## 关键概念--### Polymorphic Assignee--Issue 的 assignee 可以是 member(人)或 agent。这是 Multica 和传统 task manager-最重要的区别——**agent 是 first-class assignee**。--<Callout type="info">-分配给 agent 会**立即**入队一个 task。详见 [Tasks](/docs/tasks)。-</Callout>--### 状态(Status)--| Status | 含义 | 默认 |-|---|---|---|-| backlog | 还没规划 | ✓ |-| todo | 准备开工 | |-| in_progress | 正在做 | |-| ... | ... | |--**注意**:状态转换无强制约束——任意状态可以直接互转。--## 操作--### 创建 Issue(CLI)--```bash-multica issue create \- --title "Fix login bug" \- --assignee @alice-```--### 分配给 Agent(触发自动执行)--```bash-multica issue assign <issue-id> --agent <agent-slug>-```--分配给 agent 时,Multica 会立刻入队一个 task 到对应 runtime。详见-[Assigning Issues to Agents](/docs/assign-agents)。--## 删除和级联--删除 issue 会级联删除:-- 所有评论 / reactions(硬删除)-- 该 issue 上 queued / dispatched 的 task(取消)-- 附件(异步清理 S3)--## Related--- [Comments](/docs/comments)-- [Projects](/docs/projects) —— Issue 的容器-- [Assigning Issues to Agents](/docs/assign-agents)-- [Tasks](/docs/tasks)-```--**关键约定**:--- **Callout**:`<Callout type="info|warning|tip">...</Callout>`。warning 用于陷阱(如固定测试验证码),info 用于补充说明,tip 用于最佳实践-- **代码块**:shell 命令用 \`\`\`bash;配置用 \`\`\`yaml / \`\`\`env;JSON 用 \`\`\`json-- **Cross-link**:用 markdown 链接 `[显示文字](/docs/page-slug)`,不要写成 "详见 Tasks 章节"-- **表格**:有 3 行以上对照才用表格,不要 1-2 行也用-- **标题层级**:H1 只能一个(等于页面 title),H2 是主要分段,H3 是小节-------## 二、版本规划--### V1(25 篇,第一次 ship)--覆盖所有核心功能,让新用户能"5 分钟懂产品 + 10 分钟跑起来 + 30 分钟用上 agent"。--### V2(24 篇 Pending)--深度 reference / 开发者向 / 高级部署。等 v1 ship + 用户反馈后再补。--### V1 篇目清单--| 板块 | V1 篇数 | V2 推迟篇数 |-|---|---|---|-| 1. Welcome & Quickstart | 4 | 0 |-| 2. Workspace & Team | 4 | 0 |-| 3. Agents | 3 | 1(MCP)|-| 4. How Agents Run | 3 | 0 |-| 5. Working with Agents | 4 | 0 |-| 6. Staying Informed | 1 | 2(Subscriptions 合并 / Realtime)|-| 7. Administration | 3 | 5(Self-Host Overview / Docker Compose / Storage / Email / Upgrading / Signup Controls)|-| 8. Reference | 3 | 13(CLI 各子命令详细页)|-| **合计** | **25** | **24** |-------## 三、大纲概览(v1 导航)--| # | 板块 | 定位 | 篇数 |-|---|---|---|---|-| 1 | [Welcome & Quickstart](#板块-1welcome--quickstart) | 这是什么 + 5 分钟跑起来 | 4 |-| 2 | [Workspace & Team](#板块-2workspace--team) | 人能理解的部分(Linear-like) | 4 |-| 3 | [Agents](#板块-3agents) | 引入 agent 这个新物种 | 3 |-| 4 | [How Agents Run](#板块-4how-agents-run) | 执行架构(daemon / runtime / task / providers) | 3 |-| 5 | [Working with Agents](#板块-5working-with-agents) | **4 种触发方式——产品核心特色** | 4 |-| 6 | [Staying Informed](#板块-6staying-informed) | Inbox + Subscriptions | 1 |-| 7 | [Administration](#板块-7administration) | Env / Auth Setup / Troubleshooting | 3 |-| 8 | [Reference](#板块-8reference) | CLI / Tokens / Desktop | 3 |-------## 板块 1:Welcome & Quickstart--### 1.1 Welcome — 👀 In review [v1]--- **Source files**: `README.md`, `docs/docs-rewrite-plan.md`(定位段), `apps/docs/content/docs/index.mdx`(现状)-- **目标读者**: P0 新用户 / evaluator(第一次听说 Multica)-- **叙事位置**: 第一页。定义整个产品。读完应该能回答"这是啥"。-- **Punch line(推荐)**: **"Your agents, your machine, your backlog."**- > The task manager where AI teammates run on your own laptop.-- **写什么**(300-600 字):- - Punch line + 副标题- - 三段展开:- 1. Agent 是 first-class(能被分配 / 评论 / 改状态 / 作为 project lead)- 2. Agent 跑在你自己的 daemon 上——你掌控计算和 API key- 3. Provider-agnostic:支持 Claude Code / Codex / Cursor CLI / Copilot 等 10 种- - 一句借势:"Speaks MCP natively. Compatible with Anthropic Agent Skills."- - 3 种部署形态导航(Cloud / Self-Host / Desktop)-- **不写**:- - 不用 "AI-native"(已贬值)- - 不用 "autonomous"(撞 Autopilot 大军)- - 不暗示对标 Devin(分类不同)- - 架构细节(下一页)-- **写前要验证**: 产品定位文案和团队当前 positioning 是否一致-- **⚠️ 动笔前必读**:- - 不要写"human + AI agent first-class"——Linear 2026 CEO 已宣布 "issue tracking is dead",这叙事不再独特- - 真正独特点:**本地 daemon + BYO provider**(SaaS 结构性做不到)- - 不超过 600 字。这是 landing page,不是说明书-- **Owner**: Claude-- **Flag**: –-- **交付位置**: `apps/docs/content/docs/index.mdx`(v1 暂平铺,未迁 `zh/`)--### 1.2 How Multica Works — ⬜ Not started [v1]--- **Source files**: `server/cmd/multica-daemon/`, `packages/core/`, 战略 plan 的"产品定位"段-- **目标读者**: P0 新用户(想先建立心智模型再动手)-- **叙事位置**: 第二页。一张大图把 User / Issue / Agent / Runtime / Daemon / Task / Trigger 串起来。-- **写什么**(800-1200 字 + 一张架构图):- - 一张架构图(Mermaid):server ↔ 你的 daemon ↔ 你的 provider CLI- - 三段话解释:- 1. Server 维护 workspace / issue / agent 元数据- 2. Daemon 跑在你的机器上,poll server 领任务、调本地 provider CLI、汇报结果- 3. 4 种触发方式让 agent 开工(导到 §5 各篇)-- **不写**: API 细节、具体 provider 差异-- **写前要验证**: 架构图反映最新代码(有没有新组件)-- **⚠️ 动笔前必读**:- - 这页灵魂是**架构图**。图画不好等于没写- - 图里每个 box 点进去能到后续哪一篇(cross-link 要全)-- **Owner**: –--### 1.3 Quickstart (Cloud) — ⬜ Not started [v1]--- **Source files**: `apps/docs/content/docs/cloud-quickstart.mdx`(现有), `server/cmd/multica/cmd_setup.go`, `cmd_login.go`, `cmd_agent.go`, `cmd_issue.go`-- **目标读者**: P0 新用户(想 5 分钟跑起来)-- **叙事位置**: 第三页。-- **写什么**(600-1000 字):- - Signup → install CLI → `multica login` → `multica setup cloud` → 创建第一个 agent → 创建第一个 issue → 分配给 agent → 看它工作- - 每步命令可独立复制运行- - 末尾一句:"如果你想用 desktop app,参见 [Desktop App](/docs/desktop-app)"-- **不写**: self-host(下一篇)、daemon 深入配置-- **写前要验证**: `cmd_setup.go` 真实 flow;各命令最新 flag-- **⚠️ 动笔前必读**:- - 时间承诺:5 分钟。如果步骤超过 5 分钟,减步骤或老实写更长- - 每条命令要可复制运行-- **Owner**: –--### 1.4 Quickstart (Self-Host) — ⬜ Not started [v1]--- **Source files**: `Makefile`(selfhost target), `docker-compose.selfhost.yml`, `.env.example`, `server/cmd/multica/cmd_setup.go`-- **目标读者**: P0 self-host 评估者-- **叙事位置**: Cloud Quickstart 的姐妹篇。-- **写什么**(800-1200 字):- - `make selfhost` vs `make selfhost-build` 差异- - 自动生成 JWT_SECRET- - Migration 启动自动执行(**zero-touch upgrade** 是卖点)- - 第一次启动后 `multica setup self-host`- - 最小可行配置(必填 env)- - **⚠️ 提醒 `APP_ENV=production` 的陷阱**(详细讲在 §7.2)-- **不写**: 完整 env 表(§7.1)、Storage/Email 进阶配置(v2)-- **写前要验证**: `selfhost` vs `selfhost-build` 实际差异-- **⚠️ 动笔前必读**:- - 目标 10 分钟跑起来。超时就砍步骤- - 不和 §7 Administration 写重复:这里是 happy path,§7 是 reference / 排错-- **Owner**: –-------## 板块 2:Workspace & Team--> **板块叙事**:先讲"人的世界"——和 Linear 基本同构的部分。让读者在熟悉的土壤上建立心智,为板块 3 引入 agent 做铺垫。--### 2.1 Workspaces — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/workspace.go`, `server/pkg/db/queries/workspace.sql`, `server/migrations/001/006/020`, `server/internal/validation/workspace.go`(slug + reserved 列表)-- **目标读者**: P0 新用户、P1 团队管理员-- **叙事位置**: 板块 2 第一篇。定义"你在哪工作"。-- **写什么**(800-1200 字):- - Workspace = 多租户边界(所有查询按 workspace_id 过滤)- - Slug 约束(正则 `^[a-z0-9]+(?:-[a-z0-9]+)*$` + reserved 列表)- - Issue prefix(2-5 大写字符)+ issue counter per-workspace 自增- - Workspace context 字段(给 agent 读的 workspace-level 上下文)- - 硬删除级联-- **不写**: 创建 workspace 的 desktop/web UI 细节-- **写前要验证**:- - Slug 正则现值- - Reserved slug 完整列表- - Context 字段是不是真的被 agent 读(确认用途)-- **⚠️ 动笔前必读**:- - Reserved slug 列表给代码引用链接,不手写(代码会演进)- - Context 字段如果用途不明就标 ⚠️ 问清楚再写-- **Owner**: –--### 2.2 Members & Roles — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/invitation.go`, `workspace.go`(member 部分), `server/pkg/db/queries/invitation.sql`, `server/migrations/041`-- **目标读者**: P1 团队管理员-- **叙事位置**: Workspace 之后。-- **写什么**(1000-1500 字):- - 三级权限矩阵(owner / admin / member)—— 用表格- - **邀请双路径**:`CreateInvitation` vs `CreateMember`- - 邮箱自动创建(邀请不存在邮箱时)- - **至少保留 1 owner 约束**- - 角色提升约束(非 owner 不能邀请为 owner)- - 7 天邀请有效期-- **不写**: 邮件模板内容、OAuth(§7.2)-- **写前要验证**: 权限矩阵每行对应 handler;邀请有效期;邮件失败行为-- **⚠️ 动笔前必读**: 权限矩阵表 + 邀请流程图是必需的-- **Owner**: –--### 2.3 Issues & Projects — ⬜ Not started [v1]--> **合并说明**:Project 在代码里非常薄(9 字段),合并进 Issues 一页讲。用"Project 作为容器"一节处理。--- **Source files**:- - Issues: `server/internal/handler/issue.go`, `server/pkg/db/queries/issue.sql`, migrations 001/015/017/018/020/050- - Projects: `server/internal/handler/project.go`, `server/pkg/db/queries/project.sql`-- **目标读者**: P0 新用户、P1 团队管理员-- **叙事位置**: 核心工作对象。-- **写什么**(1500-2000 字):- - **Issues 部分**:- - Polymorphic assignee(member/agent/null)——第一次正式提"可以分配给 agent"- - Status 枚举(backlog/todo/in_progress/in_review/done/blocked/cancelled),**无强制 FSM**- - Priority / Label / Subscription / Reaction / Dependency / Bulk 操作- - Issue number per-workspace 自增- - Comment reply 树、@mention- - 删除级联- - **Projects 部分**(末尾一节):- - 9 字段、polymorphic lead(member/agent)- - Issue 关联(project_id 可 NULL)- - 删除 project 不删 issue(只把 project_id → NULL)-- **不写**(源码未实装):- - `acceptance_criteria` JSONB(无读写)- - `context_refs` JSONB(无读写)-- **写前要验证**:- - Status / Priority 枚举真实值- - Label color 格式- - `position` 和 `first_executed_at` 确实在用(⚠️ 旧 plan 误说未实装)-- **⚠️ 动笔前必读**:- - 字数在 1500-2000 之间;超出就拆 Projects 回独立页- - 第一次提"agent 可以是 assignee",**不要展开 agent 机制**(板块 3 讲)-- **Owner**: –--### 2.4 Comments — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/comment.go`, `server/pkg/db/queries/comment.sql`, migrations 017/018, `server/cmd/server/notification_listeners.go`(mention 解析)-- **目标读者**: P0 新用户、P1 重度用户-- **叙事位置**: 板块 2 最后一篇。用 @agent 为板块 5 铺垫。-- **写什么**(800-1200 字):- - Comment 创建 / 编辑 / 删除(作者 = member 或 agent)- - Reply 树(parent_id,CASCADE)- - @mention member 或 agent- - **⚠️ @all 展开到全 workspace member**(误用会炸 inbox)- - Emoji reaction- - Mention dedup:**单 comment 内生效**-- **不写**: @agent 触发 task 的机制(§5.2 讲)-- **写前要验证**: mention dedup 作用域-- **⚠️ 动笔前必读**:- - 板块 2 到板块 5 的桥梁,末尾预告"评论里 @agent 能触发任务,详见 [Mentioning Agents](/docs/mentioning-agents)"- - @all 警告必须醒目-- **Owner**: –-------## 板块 3:Agents--> **板块叙事**:新物种登场。读者已经理解 workspace/issue/project/comment 之后,正式引入 agent。重点:agent 是 first-class 团队成员。--### 3.1 What is an Agent — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/agent.go`, `server/pkg/db/queries/agent.sql`, migrations 001, `server/cmd/server/notification_listeners.go`("agent 不收 inbox" 过滤)-- **目标读者**: P0 新用户(第一次接触 agent 概念)-- **叙事位置**: 板块 3 首篇。用"agent 像人又不像人"建立心智。-- **写什么**(1000-1500 字):- - Agent 作为 first-class 成员(可分配 issue / 评论 / 改状态 / project lead)- - 和 human 相似点 vs 差异点(对照表):- - 相似:出现在 assignee / commenter / subscriber- - 差异:绑 provider、需要 runtime 在线、**永远不收 inbox**、有 visibility(workspace / private)、可 archive-- **不写**: provider 细节(§3.2)、skill/MCP(§3.3)、daemon 机制(§4.1)-- **写前要验证**: "agent 不收 inbox" 的过滤实现位置;visibility 默认值-- **⚠️ 动笔前必读**:- - 这页的灵魂是"和人对比"——用两列对照表最清晰- - 末尾预告:绑 provider 在 §3.2、挂 skill 在 §3.3、真的跑起来在板块 4-- **Owner**: –--### 3.2 Creating & Configuring Agents — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/agent.go`, `server/pkg/db/queries/agent.sql`, `packages/views/agents/`, `server/cmd/multica/cmd_agent.go`-- **目标读者**: P1 团队管理员-- **叙事位置**: 怎么创建一个 agent。-- **写什么**(1200-1800 字):- - Provider 选择——列主流 5 个(Claude Code / Codex / Cursor / Copilot / Gemini)+ 提示"完整对比见 [Providers Matrix](/docs/providers)"- - Model(静态 vs 动态发现)- - Instructions(系统提示词)- - **`custom_env`**:⚠️ DB 明文存储,非 owner redact;**覆盖而非合并**- - `custom_args`:pass-through- - `visibility`(workspace / private)- - `max_concurrent_tasks`(默认 1)- - Archive / restore-- **不写**: skill(§3.3)、MCP(v2 推,在 §3.3 末尾提一句)、provider 完整 matrix(§4.3)-- **写前要验证**: custom_env 明文存储;合并策略;max_concurrent_tasks 默认-- **⚠️ 动笔前必读**:- - ⚠️ `custom_env` 明文存储必须用 warning block,否则用户会把生产 token 扔进去- - Provider matrix 只列 5 个主流,完整表 cross-link 到 §4.3-- **Owner**: –--### 3.3 Skills — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/skill.go`, `server/pkg/db/queries/skill.sql`, `server/internal/daemon/execenv/context.go`(各 provider skill 注入路径), `server/cmd/multica/cmd_skill.go`-- **目标读者**: P1 重度用户、P2 agent-- **叙事位置**: 强化 agent 能力。-- **写什么**(1200-1800 字):- - **开篇借 Anthropic 比喻**:- > "Skill 是 agent 的'员工专业知识'——程序性知识模块;MCP 是 agent 的'工具通道'——外部系统连通性。" (引自 Anthropic 官方博客)- - **兼容性宣示**:- > "Multica Skill 采用 [Anthropic Agent Skills 开放标准](https://agentskills.io) 的 `SKILL.md` 格式。所有符合该规范的 skill(包括 Anthropic 官方仓库、ClawHub、skills.sh 上发布的包)都可以直接导入使用。"- - Skill 文件结构(SKILL.md + config + 任意支持文件)- - 来源:workspace skill(云端)vs local skill(daemon 扫描本机)- - 导入:新建 / GitHub / ClawHub / 本机目录- - 挂载到 agent(junction table `agent_skill`)- - **10 provider 注入路径矩阵**(或 cross-link §4.3)- - Skill 在 task dispatch 时同步- - **⚠️ ClawHavoc 警示**:2026-2 曝过 "ClawHavoc" 恶意包事件。ClawHub 已集成 VirusTotal 扫描,但安装第三方 skill 前务必检查 SKILL.md 和附带脚本。- - **末尾一段"Skills vs MCP"**(v2 再开 MCP 独立页):- > MCP(Model Context Protocol)是另一层概念——让 agent 连外部工具(数据库、文件系统、第三方 API)。Multica 支持 `mcp_config` 字段,但目前**仅 Claude Code 真实消费**,其他 provider 接收但未传递。详见 v2 的 MCP 专页(开发中)。-- **不写**: skill 内部 DSL(不存在)、MCP 深入(v2)-- **写前要验证**:- - 10 provider 路径是否还都对(execenv/context.go 最新值)- - Skill 大小限制(1 MB/file?)- - path traversal 检查-- **⚠️ 动笔前必读**:- - 开篇必须用 Anthropic 比喻 + agentskills.io 兼容声明(借势生态最大化)- - ClawHavoc 警示是必写——不警示用户可能装到恶意包-- **Owner**: –-------## 板块 4:How Agents Run--> **板块叙事**:agent 怎么真的动起来——分布式执行、用户自己跑 daemon。这是 Multica 结构上区别于 Linear/Jira 的关键部分。--### 4.1 Daemon & Runtimes — ⬜ Not started [v1]--> **合并说明**:Daemon 和 Runtime 概念耦合紧密(runtime = daemon × provider),放一页讲更连贯。--- **Source files**:- - Daemon: `server/internal/daemon/daemon.go`, `server/cmd/multica-daemon/main.go`, `server/cmd/multica/cmd_daemon.go`, `server/pkg/db/queries/daemon.sql`- - Runtime: `server/pkg/db/queries/runtime.sql`, `server/internal/handler/runtime.go`, `server/migrations/004`, `server/cmd/server/runtime_sweeper.go`-- **目标读者**: P0 运维、P1 开发者-- **叙事位置**: 板块 4 第一篇。"为什么我的 agent 不工作" 的答疑总枢。-- **写什么**(1500-2000 字):- - **Daemon 部分**:- - Daemon = 本地 worker,poll + 执行 + 汇报- - **Heartbeat 15s** / **45s offline**(⚠️ 旧 plan 写错过,必须代码核实)- - Poll 频率 3s- - max_concurrent_tasks(daemon 20 + agent 1,双层 gate)- - Recover-orphans(启动时把 dispatched/running 转 failed)- - Legacy daemon_id migration(hostname → UUID 自动迁移)- - 配置优先级(CLI flag > config file > env)- - CLI:`multica daemon install/login/start/stop/status/logs`- - **Runtime 部分**:- - Runtime = daemon × provider- - 唯一约束 `(workspace_id, daemon_id, provider)`- - 自动注册 + 重启复用- - Sweeper 每 30s 扫描,7 天 offline 自动删除-- **不写**: provider 执行细节(§4.3)、task 状态机(§4.2)-- **写前要验证**:- - ⚠️ Heartbeat 是 15s 不是 30s- - ⚠️ Offline 阈值是 45s 不是 75s- - Sweeper 间隔 + 自动删除阈值-- **⚠️ 动笔前必读**:- - 旧 plan 的 heartbeat / offline 数字是错的,认领者必须代码级核实- - 这页是 support 减压神器,写好能避免大量"agent 不工作"咨询- - Runtime 概念反直觉,建议用图:一个 daemon 可以有多个 runtime(每 provider 一个)-- **Owner**: –--### 4.2 Tasks — ⬜ Not started [v1]--> **合并说明**:原 §5.5 Rerun 合并进来作为最后一节。--- **Source files**: `server/internal/service/task.go`, `server/pkg/db/queries/task.sql`, `server/internal/handler/task.go`, `task_lifecycle.go`, `runtime_sweeper.go`(timeout)-- **目标读者**: P0 新用户、P1 开发者-- **叙事位置**: runtime 之后。一个 agent 的"一次工作" = 一个 task。-- **写什么**(1500-2200 字):- - 状态机(queued → dispatched → running → completed/failed/cancelled)- - `session_id` mid-flight pinning- - `attempt` / `max_attempts`(默认 2)- - **Retryable reasons**:runtime_offline / runtime_recovery / timeout- - **Non-retryable**:agent_error / 手动失败- - **自动重试仅对 issue-sourced 和 chat-sourced**——**Routines 任务不自动重试**- - **Dispatch timeout 5min / Running timeout 2.5h**- - Priority 来源(issue priority / chat 硬编码 2 / routine priority)- - Per-issue serialization- - **Rerun**(最后一节):- - 入口:UI / CLI- - 行为:cancel 当前 active 任务 → 新 task,继承 session_id,attempt 重置为 1- - vs auto-retry(系统自动)的区别-- **不写**: 触发入口详情(§5 每篇讲一种)、provider session resume(§4.3)-- **写前要验证**: max_attempts 默认;timeout 数值;retryable reasons 清单-- **⚠️ 动笔前必读**:- - 用状态机图(Mermaid)- - ⚠️ Routines 任务不自动重试、chat priority 硬编码 = 2,这两条容易漏- - Retryable vs non-retryable 用表格-- **Owner**: –--### 4.3 Providers Matrix — ⬜ Not started [v1]--- **Source files**: `server/pkg/agent/*.go`(10 个 provider 文件), `server/internal/daemon/execenv/context.go`(skill 路径)-- **目标读者**: P1 重度用户(选 provider)-- **叙事位置**: 板块 4 最后一篇。10 provider 能力大表。-- **写什么**(1500-2500 字):- - **分组列出**(不按字母序):- - **新手首选**:Claude Code(feature-complete)/ Codex(主流替代)- - **商业主流**:Cursor / Copilot / Gemini- - **ACP 生态**:Hermes(Nous Research)/ Kimi(Moonshot AI)- - **开源替代**:OpenCode(SST)/ Pi(minimalist)/ OpenClaw- - **大对照表**:- | Provider | 厂商 | Session Resume | MCP | Skill 注入路径 | custom_args | 备注 |- - 每个 provider 一小段(80-150 字):核心定位 + 用户画像 + 官网链接 + Multica 兼容性- - **Session resume 精确现状**:- - ✅ 真用:Antigravity / Claude / Codex / Copilot / Cursor / Hermes / Kimi / Kiro CLI / OpenCode / OpenClaw / Pi- - ❌ 不支持:Gemini-- **不写**: provider 官方使用文档(外链)、MCP 协议本身-- **写前要验证**:- - 认领者**必须逐个打开 `server/pkg/agent/*.go`** 确认- - Session resume 实现细节(flag vs thread API)- - 新 provider 加入 / 旧 provider 删除-- **⚠️ 动笔前必读**:- - ⚠️ 这是最容易过时的一页,provider 代码频繁变动- - 精确到 "代码里这个 flag 传给这个 CLI" 级别,不模糊说"支持"- - Codex fallback 语义必须明确:`thread/resume` 可用,但 stale / missing thread 会回退到 fresh thread-- **Owner**: –-------## 板块 5:Working with Agents--> **板块叙事**:这是产品最有特色的部分。4 种触发方式对应不同协作场景。->-> **板块开头必须加 intro**:4 种方式的对比表,让读者一页看懂再点进去细节。->-> | 方式 | 何时用 | 是否自动重试 | Session 复用 | Priority 来源 |-> |---|---|---|---|---|-> | [Assignment](/docs/assign-agents) | 最常见;分配 issue | ✓ | ✓ | issue priority |-> | [Mention](/docs/mentioning-agents) | "帮我看下这条" | ✓ | ✓ | issue priority |-> | [Chat](/docs/chat) | 独立对话,不绑 issue | ✗ | ✓ | hardcoded=2 |-> | [Routines](/docs/routines) | 定时 / 自动触发 | ✗ | ✓ | routine priority |--### 5.1 Assigning Issues to Agents — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/issue.go`(UpdateIssue assign), `server/internal/service/task.go`(`EnqueueTaskForIssue`)-- **目标读者**: P0 新用户-- **叙事位置**: 最常见触发方式。-- **写什么**(600-1000 字):- - UI:issue 详情页选 agent as assignee- - CLI:`multica issue assign <id> --agent <agent-slug>`- - 分配后立刻入队 task- - Private agent 仅 owner/admin 可分配- - 取消分配:**不自动取消订阅**- - Per-issue serialization-- **不写**: task 内部机制(§4.2)、subscription(§6.1)-- **写前要验证**: `EnqueueTaskForIssue` 最新逻辑-- **⚠️ 动笔前必读**: 最常见触发——尽可能简洁;旧 assignee 不自动取消订阅要说明-- **Owner**: –--### 5.2 Mentioning Agents in Comments — ⬜ Not started [v1]--- **Source files**: `server/cmd/server/notification_listeners.go`(mention 解析), `server/internal/service/task.go`(`EnqueueTaskForMention`), `subscriber_listeners.go`(防自触发)-- **目标读者**: P0 新用户、P1 重度用户-- **叙事位置**: 第二种触发。"这个 agent 帮我看一下"。-- **写什么**(800-1200 字):- - 在 comment 里 `@agent-slug`- - 触发:`EnqueueTaskForMention`,带 `trigger_comment_id`- - **Dedup 按 agent**(不同 agent 可以被并行 @)- - **防自触发 guard**(`HasAgentCommentedSince`)- - 和 assignment 的区别:不改 assignee、不改 status、task 带 trigger_comment_id-- **不写**: inbox mention 通知(§6.1)、@all(§2.4)-- **写前要验证**: 防自触发 guard 条件;dedup 作用域-- **⚠️ 动笔前必读**: 用真实场景开头("你想让 X agent 分析一下这条 issue")-- **Owner**: –--### 5.3 Chat — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/chat.go`, `server/pkg/db/queries/chat.sql`, `server/internal/service/task.go`(`EnqueueChatTask`), `packages/views/chat/`-- **目标读者**: P1 重度用户-- **叙事位置**: 第三种触发。"直接和 agent 对话,不绑 issue"。-- **写什么**(1000-1500 字):- - Chat session = agent × user × workspace 独立对话- - 发消息 → `EnqueueChatTask`(无 issue_id)- - Session 复用(session_id + work_dir COALESCE 持久化)- - **⚠️ 完全沙盒**:chat 里的 agent **不能发 comment 到 issue**- - Priority 硬编码 = 2,**不自动重试**- - Session 软删除(`status='archived'`)-- **不写**: provider 层 session 机制(§4.3)-- **写前要验证**: chat vs issue comment 隔离性;unread_since 用途-- **⚠️ 动笔前必读**:- - "沙盒"是 chat 最重要的产品语义,不说清用户会误以为 chat agent 能动 issue- - 和 §5.2 mention 的区别要对比清楚-- **Owner**: –--### 5.4 Routines — ⬜ Not started [v1]--> **改名说明**:原 Autopilot 改名 Routines。理由:GitHub Copilot 2026-04 已推 "Autopilot mode"(语义是"自主度"),两者正面撞且语义不同。Routines 更贴切(= standing orders / 定期指令)。--- **Source files**: `server/internal/handler/autopilot.go`, `server/pkg/db/queries/autopilot.sql`, `server/internal/service/autopilot.go`, `service/task.go`(`CreateAutopilotTask`)-- **目标读者**: P1 管理员-- **叙事位置**: 第四种触发。"让 agent 自己定期开工"。-- **写什么**(1200-1800 字):- - **开篇用类比**:- > "Routine 就是给 agent 的 **standing order**——像给 human teammate 设一个'每周一早上做 standup summary'的长期指令。"- - Routine = agent × schedule/trigger × 执行模式- - **两种模式**(用用户心智词,不说"run_only"):- - **Quietly run in the background**(对应代码 `run_only`):fire-and-forget,不留 issue 痕迹。适合静默维护、数据抓取- - **Create a tracked issue first**(对应代码 `create_issue`):先建 issue 再跑,留可追溯 audit trail。适合周期 audit、每周工作报告- - **Trigger**:- - `schedule`(cron + timezone)- - `api`(手动 POST 触发)- - ~~webhook~~(字段存在但**未接入路由**,不写)- - Concurrency policy 只对 "Quietly run" 模式生效- - **⚠️ Routine 任务不自动重试**- - Run 历史查看-- **不写**: webhook trigger(未接入);Label 字段(用途不明,先验证)-- **写前要验证**:- - Webhook 是否还未接入- - Label 字段用途- - Cron 格式兼容性-- **⚠️ 动笔前必读**:- - ⚠️ 全文 **用 Routines,不用 Autopilot**(避免和 GitHub Copilot Autopilot 混淆)- - 数据库/代码里还叫 `autopilot_*` —— 文档里对读者说 Routines,但引用代码位置可以括号说明"代码表名 autopilot"- - 两种模式用用户心智词,不要直接暴露 `run_only` / `create_issue`-- **Owner**: –-------## 板块 6:Staying Informed--### 6.1 Inbox & Subscriptions — ⬜ Not started [v1]--> **合并说明**:Subscription 是 Inbox 通知的前置规则,放一页讲逻辑更顺。--- **Source files**:- - Inbox: `server/cmd/server/notification_listeners.go`, `server/pkg/db/queries/inbox.sql`, `packages/core/inbox/`, `packages/views/inbox/`- - Subscriptions: `server/cmd/server/subscriber_listeners.go`, `server/pkg/db/queries/issue_subscriber.sql`, migrations 015-- **目标读者**: P0 所有用户、P1 重度用户-- **叙事位置**: 板块 6 唯一一篇。"agent 在背后干活,怎么知道发生了什么"。-- **写什么**(1500-2000 字):- - **Inbox 部分**:- - **10 种实际触发的通知**:- 1-3. issue_assigned / unassigned / assignee_changed- 4. status_changed(**唯一冒泡到 parent issue**)- 5-6. priority_changed / due_date_changed- 7-8. new_comment / mentioned- 9. reaction_added(issue + comment)- 10. task_failed- - **⚠️ @all 展开到全 workspace member**- - Mention dedup 单 comment 内- - **Agent 永远收不到 inbox**(即使在 subscriber 表)- - 操作:查看 / 已读 / 批量已读 / 归档 / 过滤- - **Subscriptions 部分**:- - 自动订阅规则(creator / assignee / commenter / @mentioned)- - 手动订阅 / 取消- - **Parent 冒泡只对 status_changed**- - **取消分配不自动取消订阅**-- **不写**:- - 4 种已定义但无触发逻辑的通知(review_requested / task_completed / agent_blocked / agent_completed)- - WebSocket event 清单(v2 Realtime 页)-- **写前要验证**:- - 通知类型清单最新值- - mention dedup 作用域- - @all 展开时机-- **⚠️ 动笔前必读**:- - 旧 plan 说 "10 种通知",代码有 14 个定义——**只讲 10 个实际触发的**,4 个 planned 可以脚注- - "agent 不收 inbox" 和 §3.1 呼应-- **Owner**: –-------## 板块 7:Administration--> **板块叙事**:给 self-host 运维 + 开发者。语气 reference 向,不讲故事。->-> **V1 砍掉**:Self-Host Overview(合并进 §1.4)/ Docker Compose 深入(简化到 §1.4)/ Storage / Email / Upgrading / Signup Controls(合并进 §7.2)/ Authentication & Tokens(拆到 §8.2)--### 7.1 Environment Variables — ⬜ Not started [v1]--- **Source files**: `.env.example`, `server/internal/config/`-- **目标读者**: self-host 运维-- **叙事位置**: self-host 部署的 reference 页。-- **写什么**(1500-2500 字):- - 按类别分组:- - **必填**:DATABASE_URL / PORT / JWT_SECRET / APP_ENV / FRONTEND_ORIGIN- - **Email**:RESEND_API_KEY(未配置→code 落 stderr)- - **OAuth**:GOOGLE_CLIENT_ID / _SECRET / _REDIRECT_URI- - **Storage**:S3_BUCKET / CloudFront 等(默认本地 `./data/uploads`)- - **Signup 控制**:ALLOW_SIGNUP / ALLOWED_EMAIL_DOMAINS / ALLOWED_EMAILS(**三级优先级**)- - 每个变量:默认值 / 来源 / 何时必填-- **不写**: Storage / Email 深入配置(v2)-- **写前要验证**: `.env.example` 里的变量穷尽吗(可能有 code-level 但没进 example 的)-- **⚠️ 动笔前必读**:- - reference 页,完整性第一- - Signup 三级优先级 EMAILS > DOMAINS > ALLOW_SIGNUP 必须说清-- **Owner**: –--### 7.2 Authentication Setup — ⬜ Not started [v1]--> **合并说明**:原 7.3 Auth Setup + 7.10 Signup Controls 合并。--- **Source files**: `server/internal/handler/auth.go`(固定测试验证码 + checkSignupAllowed), `.env.example`(auth 相关注释)-- **目标读者**: self-host 运维-- **叙事位置**: self-host 的 auth 配置。-- **写什么**(1500-2000 字):- - **🚨 超醒目 warning block**:生产环境必须保持 `MULTICA_DEV_VERIFICATION_CODE` 为空;固定测试验证码只用于非 production 私有测试- - Email + verification code 登录流程(依赖 Resend)- - Google OAuth 配置步骤(创建 OAuth client → redirect URI → 填 env)- - **Signup 白名单三层优先级决策树**:- 1. ALLOWED_EMAILS 命中 → allow- 2. ALLOWED_EMAIL_DOMAINS 命中 → allow- 3. ALLOW_SIGNUP=true → allow;false → deny- - 典型场景:开放给公司域 / 限定几个邮箱 / 完全关闭 signup- - 和邀请的关系(signup 关了也能通过邀请加人)-- **不写**: JWT 实现、token 类型(§8.2 讲)-- **写前要验证**: 固定测试验证码的 env 条件;OAuth 流程最新;Signup 优先级-- **⚠️ 动笔前必读**:- - ⚠️⚠️ **固定测试验证码风险必须最醒目**(红色 warning block),这是 self-host 最大坑- - OAuth 给外部步骤截图,别假设读者懂 GCP Console- - 决策树建议用 Mermaid 图-- **Owner**: –--### 7.3 Troubleshooting — ⬜ Not started [v1]--- **Source files**: 各 handler error / daemon log / server log-- **目标读者**: self-host 运维 + 所有遇到问题的用户-- **叙事位置**: 板块 7 最后一篇。-- **写什么**(1200-2000 字,v1 先覆盖 Top 6-8 问题):- - Daemon 连不上 server(token 过期 / network / server 挂)- - 任务一直 queued(runtime offline / max_concurrent 满 / agent 配错)- - WebSocket 连不上(cookie / CORS / proxy)- - Email 没收到(Resend 未配置 → 看 stderr)- - 固定测试验证码不工作(APP_ENV / MULTICA_DEV_VERIFICATION_CODE 检查)- - Port 冲突- - 日志位置:daemon / server / browser console-- **不写**: 深度 bug report(去 GitHub issue)-- **写前要验证**: Top 问题列表反映真实 support 记录-- **⚠️ 动笔前必读**:- - 每个问题:症状 → 可能原因 → 怎么查 → 怎么修(四段式)- - 这页应不断 append,v1 先写最高频的 6-8 个-- **Owner**: –-------## 板块 8:Reference--### 8.1 CLI Cheatsheet — ⬜ Not started [v1]--> **合并说明**:v1 不做 14 页 CLI 详细 reference,用一页 cheatsheet 覆盖核心命令 + 认证入口。V2 再按命令组拆详细页。--- **Source files**: `server/cmd/multica/main.go`(命令树), 各 `cmd_*.go`-- **目标读者**: P1 开发者、P2 agent-- **叙事位置**: Reference 板块首篇。-- **写什么**(2000-2500 字):- - **认证入口**(开头一段):- - `multica login` → 拿 PAT(`mul_` 前缀)- - PAT 存 `~/.multica/config.json`- - 详细 token 机制见 [Authentication & Tokens](/docs/auth-tokens)- - **命令总览**(按功能分组,每条一行):- - **Auth**:`login / auth status / auth logout`- - **Setup**:`setup cloud / setup self-host`- - **Workspace**:`workspace list / get / members`- - **Issue**:`issue list / get / create / update / assign / status / search / runs / rerun` + 嵌套 `issue comment` / `issue subscriber`- - **Project**:`project list / get / create / update / delete / status`- - **Agent**:`agent list / get / create / update / archive / restore / tasks` + 嵌套 `agent skills`- - **Skill**:`skill list / get / create / update / delete / import` + 嵌套 `skill files`- - **Autopilot**(命令名保留,文档里叫 Routines):`autopilot list / get / create / update / delete / runs` + 嵌套 `autopilot trigger`- - **Repo**:`repo checkout`- - **Daemon**:`daemon install / login / start / stop / status / logs`- - **Runtime**:`runtime list / usage / activity / ping / update`- - **Misc**:`config / version / update / attachment download`- - 每条命令:1 行描述 + 最常用 flag- - 末尾指引:"完整 flag / exit code / examples 见 v2 详细 CLI reference(开发中)"-- **不写**: 每条命令的深入 reference(v2)、shell completion-- **写前要验证**: 命令总数;每条最常用 flag-- **⚠️ 动笔前必读**:- - 不做 14 页详细 reference,cheatsheet 级足够- - CLI 叫 `autopilot` 但用户文档里说 Routines,加一行说明"CLI 子命令名为 `autopilot`(将在后续版本统一)"-- **Owner**: –--### 8.2 Authentication & Tokens — ⬜ Not started [v1]--- **Source files**: `server/internal/handler/auth.go`, `server/internal/middleware/auth.go`, `server/internal/middleware/daemon_auth.go`, `server/cmd/multica/cmd_auth.go`-- **目标读者**: P1 管理员、P1 开发者(用 API / CLI / daemon)-- **叙事位置**: Reference 板块。讲"三种身份证"。-- **写什么**(1200-1800 字):- - **3 种 token**:- - **JWT Cookie**(`multica_auth`,HttpOnly,30 天)—— 浏览器- - **PAT**(`mul_` 前缀)—— CLI / 脚本- - **Daemon Token**(`mdt_` 前缀)—— daemon 专用- - **Token 适用矩阵**:- | 路由 | JWT | PAT | Daemon Token |- |---|---|---|---|- | `/api/user/*` | ✓ | ✓ | ✗ |- | `/api/workspaces/:id/*` | ✓ | ✓ | ✗ |- | `/api/daemon/*` | ✗ | ✓ | ✓ |- | `WS /ws` | ✓(cookie)| ✓(首条消息)| - |- - 登录 flow(email + code / OAuth)- - PAT 创建 / 撤销 / 管理(UI 在 Settings,CLI 通过 `multica login`)- - Daemon token 生成时机(`multica daemon login`)- - Logout(删本地 token,不撤销 server session)-- **不写**: self-host 时的 auth setup(§7.2)、CLI 具体命令(§8.1)-- **写前要验证**: Daemon Token 在 WS 的行为;JWT 过期后重连-- **⚠️ 动笔前必读**:- - Token 矩阵是灵魂——一张表解决- - Daemon Token 不能命中 user-scoped 路由必须明确-- **Owner**: –--### 8.3 Desktop App — ⬜ Not started [v1]--- **Source files**: `apps/desktop/src/main/`, `apps/desktop/src/renderer/src/stores/tab-store.ts`, `stores/window-overlay-store.ts`, `apps/desktop/src/main/updater.ts`, `scripts/package.mjs`-- **目标读者**: 使用 desktop 版的用户-- **叙事位置**: Reference 最后一篇。桌面版独有能力。-- **写什么**(1000-1500 字):- - **Desktop vs Web 对比表**(开篇)- - **多 tab 系统**(per-workspace 隔离,localStorage 持久化,跨 workspace 切换时恢复上次活跃 tab)- - **自动更新**(electron-updater + GitHub Release;Windows arm64 特殊处理 `latest-arm64.yml`;app quit 时安装)- - **Daemon 不内置**:desktop 只是窗口,daemon 要单独 `multica daemon start`,desktop package 里 bundle 了 CLI- - 安装:macOS .dmg / Windows .exe / Linux .AppImage-- **不写**:- - Window Overlay(实现细节,用户无感知)- - Electron 框架本身-- **写前要验证**:- - Tab system 持久化机制- - 自动更新平台矩阵- - CLI 确实 bundle 进 desktop 包-- **⚠️ 动笔前必读**:- - 重点是"为什么选 desktop 而不是 web"- - Desktop vs Web 对比表是核心-- **Owner**: –-------## 四、V2 Pending 清单(24 篇,v1 ship 后再动)--> 这些篇不在 v1 scope,但位置已规划。等 v1 ship + 有用户反馈后再开写。--- **板块 3**: 3.4 MCP(独立页,深入 MCP 协议 + 各 provider 支持矩阵)-- **板块 6**: 6.2 Realtime(WebSocket event 完整清单、push-only 模型、41 event types、reconnection)-- **板块 7**(self-host 深度):- - 7.4 Self-Hosting Overview(决策树:Cloud / Self-Host / Hybrid)- - 7.5 Docker Compose 深入部署(镜像 / 端口 / 数据卷 / 生产参数)- - 7.6 Storage(S3 / CloudFront / 本地 disk 三模式对比)- - 7.7 Email(Resend 配置 / 邮件场景 / 未配置 fallback)- - 7.8 Upgrading(版本 tag / migration 自动执行 / 回滚策略)-- **板块 8**(CLI 详细 reference,从 8.1 cheatsheet 拆开):- - 8.4 multica auth / login 详细- - 8.5 multica setup 详细- - 8.6 multica workspace 详细- - 8.7 multica issue(+comment / subscriber)详细- - 8.8 multica project 详细- - 8.9 multica agent(+skills)详细- - 8.10 multica skill 详细- - 8.11 multica autopilot 详细- - 8.12 multica repo 详细- - 8.13 multica daemon 详细- - 8.14 multica runtime 详细- - 8.15 multica config / version / update / attachment 详细-------## 五、进度汇总(v1 25 篇)--| 板块 | 总数 | ✅ | 👀 | ✍️ | 🔍 | ⬜ |-|---|---|---|---|---|---|---|-| 1. Welcome & Quickstart | 4 | 0 | 1 | 0 | 0 | 3 |-| 2. Workspace & Team | 4 | 0 | 0 | 0 | 0 | 4 |-| 3. Agents | 3 | 0 | 0 | 0 | 0 | 3 |-| 4. How Agents Run | 3 | 0 | 0 | 0 | 0 | 3 |-| 5. Working with Agents | 4 | 0 | 0 | 0 | 0 | 4 |-| 6. Staying Informed | 1 | 0 | 0 | 0 | 0 | 1 |-| 7. Administration | 3 | 0 | 0 | 0 | 0 | 3 |-| 8. Reference | 3 | 0 | 0 | 0 | 0 | 3 |-| **V1 合计** | **25** | **0** | **1** | **0** | **0** | **24** |-------## 六、决策点记录(append-only)--- **2026-04-23** 初始大纲:49 篇,8 板块(v2 版)-- **2026-04-23** 生态调研后修正:- - Autopilot → **Routines**(避免撞 GitHub Copilot Autopilot mode)- - Welcome positioning 换成 **"Your agents, your machine, your backlog."**(不打 "human + agent first-class",Linear 自己已是)- - Skill 开篇加 Anthropic 比喻 + agentskills.io 兼容声明 + ClawHavoc 警示- - MCP 推 v2(目前仅 Claude Code 真用,v1 在 §3.3 末尾提一句)-- **2026-04-23** v1 scope 收敛到 25 篇:- - 合并:Projects → Issues / Runtime → Daemon / Rerun → Tasks / Subscriptions → Inbox / Signup → Auth Setup / CLI 14 页 → Cheatsheet- - 推 v2:MCP / Realtime / Storage / Email / Upgrading / Self-Host Overview / Docker Compose 深入 / CLI 详细 reference- - 保留独立成页:所有用户高频感知的功能(Chat / Routines / Inbox / Skills / Providers Matrix / Desktop App / Self-Host Quickstart)-- (后续更新 append 到此处)diff --git a/docs/docs-rewrite-plan.md b/docs/docs-rewrite-plan.mddeleted file mode 100644index ecc07ab1a0..0000000000--- a/docs/docs-rewrite-plan.md+++ /dev/null@@ -1,244 +0,0 @@-# Multica Docs 站重写规划(v2)--> **本规划是什么**:Multica 对外 doc 站(`apps/docs/`,Fumadocs + Next.js)的从零重写方案。它替换 v1 规划——v1 之前在代码调研之前写的,很多对概念的切分现在看是错的。->-> **v2 的数据基础**:4 份并行 subagent 的代码级调研,覆盖 Workspace/Members/Issues/Projects、Agent/Runtime/Daemon/Tasks、Skill/MCP/Autopilot/Chat、Inbox/Realtime/Auth 四大领域。每一处涉及产品行为的陈述都能在代码里找到对应位置。->-> **本文档语言**:中文(团队内部规划,你要逐篇 review)。-> **doc 站本身语言**:英文先行,中文作为 Phase 10 的 i18n。->-> **风格目标**:排版/布局对标 Anthropic docs(奶油底、serif heading、宽松行距、窄行宽、深色代码块的灵魂),但**色板继续用 Multica 自己的 tokens**(冷蓝 brand)——visual 上是"Multica 色 + Anthropic 排版语法"。-------## 一、产品定位(文档的落脚点)--Multica = **人 + AI agent 在同一个看板上协作的任务管理平台**。--这个定位决定了它的文档**和普通 SaaS 文档有三个不一样的地方**,贯穿全规划:--1. **术语负担重**。Workspace/Agent/Runtime/Daemon/Skill/Autopilot/MCP/Trigger/Session Resumption——对新用户**没有一个是 obvious** 的。**Concepts 是文档第一支柱**。-2. **分布式执行架构要讲透**。Server 不跑 agent,agent 跑在用户本地的 daemon 上——这是所有"我的 agent 怎么不工作"问题的根源。Architecture Overview 要早出现。-3. **文档也被 agent 读**。现有 `cloud-quickstart.mdx` 已经有"把这段指令给你的 agent,让它自己按文档安装"的模式——意味着文档**要能被 agent 跟着做**:每一步命令要完整、可执行、独立(不能"把上面那个替换一下")。这直接影响 code block 写法。-------## 二、读者画像(按优先级排)--| 优先级 | 读者 | 关心什么 |-|---|---|---|-| P0 | **新用户 / Evaluator** | "这是啥?5 分钟跑起来" |-| P0 | **自托管运维 (DevOps)** | "怎么部署?资源要多少?出问题怎么查?" |-| P1 | **团队管理员 / Workspace owner** | "怎么配 agent?管权限?设 autopilot?" |-| P1 | **重度 CLI / 开发者用户** | "CLI 全集?直接调 API?" |-| P2 | **Agent 本身** | "这个命令怎么用?这个概念是什么?" |-| ✗ | OSS 贡献者 | 暂不做 —— 用 `CONTRIBUTING.md` 顶着 |--> **关键**:P2 的 agent 不会逛导航,只会被人类用 `Fetch https://docs.multica.ai/...` 指向某一页。所以每一页都要**自包含**。-------## 三、设计原则--1. **Concepts First, Tasks Second**。先建立词汇表,再讲操作。-2. **每个概念独立讲透,不合并糊弄**。宁可多一页也不要把 MCP 塞进 Agents 糊弄过去。-3. **「入口」概念独立于「对象」概念**。Trigger 不是 Task 的属性——它是跨入口的共通机制,值得自己一页。-4. **每篇 < 8 分钟读完**。Concept 页可以稍长,Guide/Reference 页聚焦单一主题。-5. **命令块可独立复制运行**——不写"把上面那个改成 XXX",这对 agent 读者不友好。-6. **版本敏感的事实用代码注释标记来源**——比如"支持的 agent provider"列表,来自哪个文件,后期可以做成自动扫描。-------## 四、信息架构(v2)--**六大板块,共 56 篇。**--### 板块 1. Introduction(2 篇)--让读者用 2 分钟理解这是什么产品。--| 篇目 | 核心内容 |-|---|---|-| **Welcome** | 定位 + 核心价值 + 一张架构图 + 3 种部署形态(Cloud / Self-Host / Desktop)导航 |-| **How Multica works** | 一张大图把 User / Issue / Agent / Runtime / Daemon / Skill / Task / Trigger 之间的关系串起来——目标是建立**正确心智模型**,而不是记名词 |--### 板块 2. Getting Started(3 篇)--| 篇目 | 核心内容 |-|---|---|-| **Cloud Quickstart** | 5 分钟:signup → install CLI → `multica setup` → 第一个 agent → 第一个 issue |-| **Self-Host Quickstart** | 10 分钟:`install.sh --with-server` → `multica setup self-host` |-| **Your first task** | 从 issue 创建 → assign 给 agent → 看 agent 流式工作 → review 结果(截图 + GIF) |--### 板块 3. Concepts(17 篇 —— 灵魂)--**每页统一模板**:What · Why it exists · How it connects · Related。--| # | 篇目 | 它回答的问题 | 代码事实高光 |-|---|---|---|---|-| 1 | **Workspaces** | 多租户边界;slug / issue prefix / issue_counter 管什么 | slug 正则 `^[a-z0-9]+(?:-[a-z0-9]+)*$`;issue number **per-workspace 自增**;硬删除级联 |-| 2 | **Members & Access** | owner/admin/member 3 级权限;邀请流程;角色约束 | **邀请不存在的邮箱会自动创建 user**(用 email 当名字);每个 workspace 至少保留 1 个 owner |-| 3 | **Issues** | 最核心工作对象;polymorphic assignee(member 或 agent) | **分配给 agent 会自动入队 task**;private agent 只能被 owner/admin 分配;`acceptance_criteria`/`position`/`first_executed_at` 等字段在代码里**未实装**,不写进文档 |-| 4 | **Projects** | issue 容器;lead 可以是 agent | 非常薄(9 个字段);删除 project 只是把 issue.project_id 设 NULL |-| 5 | **Agents** | AI 工作者身份;provider/instructions/custom_env/custom_args/model 分别影响什么 | **`custom_env` 在 DB 里明文存储,无加密**——醒目警告;archive 用 `archived_at` 软删除;API 响应对非 owner 做 redact |-| 6 | **Runtimes** | 一台机器 × 一个 provider 一行;注册/在线/离线生命周期 | **唯一约束 (workspace_id, daemon_id, provider)**——同一台机器同一 provider 不会有重复 runtime;daemon 重启复用旧 runtime 行 |-| 7 | **The Daemon** | 分布式执行的灵魂;poll + heartbeat + concurrent execution | 每 30s heartbeat;75s 无心跳 → 离线;启动时调 `recover-orphans` 回收孤儿任务;max_concurrent_tasks 有双层(daemon + agent) |-| 8 | **Tasks** | 任务是什么;生命周期 queued→dispatched→running→completed/failed | **session_id mid-flight pinning**(agent 首条 system message 一到就持久化,不等完成);失败自动重试只对 issue-sourced 任务(max_attempts=3),chat 和 autopilot 不自动重试 |-| 9 | **Triggers & Entry Points** ← **独立页** | 5 种让 task 产生的入口:Assignment / Comment @mention / Chat / Autopilot / Rerun;每种的行为对比 | 每种的 FK 字段不同(trigger_comment_id / chat_session_id / autopilot_run_id);**对比表**:哪种有 session resume / 自动重试 / priority 来源 / dedup |-| 10 | **Skills** | 工作区 skill + 本地 skill;按 provider 的注入路径 | 8 种 provider 有不同 skill 根路径(Claude=`.claude/skills/`、Codex=`$CODEX_HOME/skills/`、Pi=`.pi/skills/`、etc);skill 不参与执行,只参与上下文注入 |-| 11 | **MCP** | 独立协议;怎么给 agent 配 MCP server;和 skill 的区别 | **目前只 Claude Code 真用**——其他 provider 收到 McpConfig 但 CLI 没对应 flag;JSONB 明文存储,非 owner redact |-| 12 | **Autopilots** | 让 agent 自动开工的调度器;两种执行模式;三种触发;并发策略 | **Webhook trigger 字段有但没接路由**——第一版不文档化;concurrency policy 只对 `run_only` 模式生效;`create_issue` 模式由 issue FSM 自然 gate |-| 13 | **Chat** | 和 issue comment 的区别;session 复用 | **完全沙盒**——chat 里的 agent 不能发 comment 到 issue;session_id 用 COALESCE 持久化,agent crash 不会抹掉 |-| 14 | **Inbox** | 个人通知中心;10 种通知类型 | **Agents 可以被加入 subscriber 表但永远收不到 inbox 通知**——`notifyIssueSubscribers` 显式过滤;mention dedup 只在单 event 内生效(一 comment 里 @alice 5 次 = 1 inbox) |-| 15 | **Subscriptions** | 谁会自动订阅;如何手动订阅 | **取消分配后旧 assignee 不会被取消订阅**;parent issue 冒泡只对 `status_changed` 生效 |-| 16 | **Authentication & Tokens** | 3 种凭证 + signup flow + OAuth | JWT cookie(30 天)/ PAT(`mul_` 前缀)/ Daemon Token(`mdt_` 前缀);Daemon Token **不能命中 user-scoped 路由**;PAT 几乎什么都能命中;signup 白名单优先级:`ALLOWED_EMAILS` > `ALLOWED_EMAIL_DOMAINS` > `ALLOW_SIGNUP` |-| 17 | **Realtime & Events** | WebSocket hub + room model + 事件目录 | **40+ event types**(按命名空间分:issue:* / task:* / inbox:* / chat:* 等);WS 是 **push-only**(client→server 走 HTTP);room 按 workspace;inbox:* 用 SendToUser 定向推送 |--### 板块 4. Guides(12 篇,任务导向)--| 篇目 | 核心内容 |-|---|---|-| Assign an issue to an agent | UI + CLI 两种方式 |-| Create and configure an agent | provider、instructions、custom_env、mcp、skills |-| Connect a runtime (local daemon) | daemon install → login → start → 出现在 Runtimes 页 |-| Write and share a skill | 新建 / 编辑 / 挂载到 agent |-| Import a skill from GitHub / ClawHub | import URL 的流程 |-| Import a local skill from your machine | 通过 daemon 扫描本机 skill 目录并上传 |-| Set up an autopilot | 模板起步、schedule / API trigger、run_only vs create_issue |-| Trigger an agent from comments | `@agent` 的规则、防自触发 guard |-| Use the chat interface | 何时用 chat 何时用 issue、session 复用表现 |-| Manage team members and roles | invite、角色升降、remove |-| Configure MCP servers for an agent | JSON 配置示例、常见 MCP server |-| Work from the terminal (CLI-first) | 纯 CLI 完成 create→assign→follow |--### 板块 5. Self-Hosting(8 篇)--| 篇目 | 必讲的 critical warning |-|---|---|-| Overview | 决策树(哪种部署模式适合你) |-| Docker Compose deployment | `make selfhost` vs `make selfhost-build` |-| Environment variables reference | 完整 env 表 |-| Authentication setup | **🚨 固定测试验证码必须显式设置 `MULTICA_DEV_VERIFICATION_CODE`,生产保持为空**;Google OAuth 配置;signup 白名单 |-| Storage | S3 / CloudFront / 本地磁盘 |-| Email | Resend 配置;**没配会落到 stderr** |-| Upgrading | 版本升级 + migration 策略 |-| Troubleshooting | 常见问题(日志在哪、端口冲突、daemon 连不上、等) |--### 板块 6. CLI Reference(14 篇)--按 command category 组织。每个命令页统一 schema:**Synopsis · Options · Examples · Exit codes · Related**。--Installation / Authentication / Setup / Daemon / Workspace / Issue / Comment / Agent / Skill / Autopilot / Project / Repo / Runtime / Config & Version-------## 五、代码调研发现的 12 条必写事实--这些都是 product-overview.md **没明确写清楚**、但代码里真实存在、文档里**必须呈现**的事实。每条都标了归属页面。--| # | 事实 | 归属页面 |-|---|---|---|-| 1 | `custom_env` 在 DB 里明文存储,无加密;非 owner redact 仅在 API 响应层做 | Agents |-| 2 | Agent 可被加入 subscriber 表,但永远收不到 inbox 通知 | Subscriptions / Inbox |-| 3 | Session Resumption 只有 Claude Code 真用;Codex 的 session_id 存了不读;其他不支持 | Tasks / Agents |-| 4 | MCP 目前只有 Claude Code 真用——其他 provider 忽略 mcp_config | MCP |-| 5 | Webhook autopilot trigger 字段建了但没接路由——第一版不文档化 | Autopilots |-| 6 | custom_env merge 是覆盖而非合并——不能用 custom_env"取消设置"系统 env | Agents |-| 7 | 旧 assignee 取消分配后不会被取消订阅 | Subscriptions |-| 8 | 固定本地测试验证码默认关闭;`MULTICA_DEV_VERIFICATION_CODE` 仅用于非 production 私有测试 | Self-Hosting → Auth |-| 9 | Signup 白名单优先级:ALLOWED_EMAILS > ALLOWED_EMAIL_DOMAINS > ALLOW_SIGNUP | Self-Hosting → Auth |-| 10 | One daemon ↔ many runtimes;one runtime ↔ ONE provider;同 daemon_id 重启复用旧 runtime 行 | Runtimes / Daemon |-| 11 | Inbox 10 种类型,mention dedup 只在单 event 内生效 | Inbox |-| 12 | WebSocket 是 push-only;client 写操作走 HTTP;room 按 workspace,inbox:* 用 SendToUser | Realtime & Events |-------## 六、富内容策略(不单调)--| 组件 | 用途 |-|---|---|-| Mermaid diagram | 架构图 / task 生命周期 / trigger 流向 / autopilot 调度链 |-| Tabs | Cloud / Self-Host / Desktop 并列;CLI / UI 并列 |-| Callouts(内置)| Tip / Warning / Note — **警告类密集用在 Agents 的 custom_env 和 Self-Host 的固定测试验证码** |-| Code Tabs | API 调用多语言(Shell / Node / Go) |-| Video / GIF | "Create your first agent"、"Follow an agent working" |-| DeploymentPicker(定制)| 交互式决策树:回答 3 个问题 → 推荐部署路径 |-| ConceptHero(定制)| 每个 Concept 页顶部的大图 + tagline + "also see" |-| CLIBlock(定制)| 终端样式 + copy + 期望输出 |-| APIRoute(定制)| API endpoint 统一渲染 |-| LifecycleDiagram(定制)| 任务状态机 / runtime 在线离线状态机 |-| TriggerComparison(定制)| 5 种 trigger 的对比矩阵——Triggers 页的核心组件 |-------## 七、技术基础设施--### 7.1 视觉基础(Phase 1)--- `apps/docs/app/global.css` 里 `@import "@multica/ui/styles/tokens.css"`,覆盖 Fumadocs 的 `neutral.css`-- 字体:Heading serif(**Fraunces** 或 **Source Serif 4**,`next/font` 加载)+ Body `--font-sans` + Code `--font-mono`-- 排版:主列 ~720px,段间距 1.2×,h1/h2 serif,代码块深色高对比,链接保留下划线--### 7.2 Dark/Light(已就位)--Fumadocs RootProvider 自动切换;tokens.css 已有 `.dark`,直接可用。--### 7.3 i18n(Phase 10)--Fumadocs 原生支持:`content/docs/[lang]/...`。初期只英文,中文后补。--### 7.4 CI(Phase 0)--当前 `.github/workflows/ci.yml:33` 用 `--filter='!@multica/docs'` 排除了 docs build。**在 Phase 0 做一个独立小 PR 把它加回来**——否则 MDX 语法错 CI 不拦,只有 Vercel 部署时才发现。--### 7.5 dev:docs 快捷命令(已做)--`pnpm dev:docs` 已加到 root `package.json`。-------## 八、依次开发的 Phase 分期--**约束**:Phase 3 及之后每篇 mdx 是**独立 commit**,你按 commit 一篇一篇 review。--| Phase | 产出 | review 粒度 | 预估 |-|---|---|---|---|-| **Phase 0** | CI 加 docs build;`pnpm dev:docs`(已做) | 1 个 PR | 0.5h |-| **Phase 1** | 视觉基础:tokens、serif 字体、排版规则、light/dark 验证 | 1 个 PR,看整体调性 | 1 天 |-| **Phase 2** | IA 骨架:清空 `content/docs/`,按 v2 IA 建 56 个空 mdx + `meta.json` | 1 个 PR,看导航树 | 0.5 天 |-| **Phase 3** | Introduction 2 篇 | 每篇 1 commit | 1 天 |-| **Phase 4** | Getting Started 3 篇 | 每篇 1 commit | 2 天 |-| **Phase 5** | Concepts 17 篇 | 每篇 1 commit,分 3-4 批推 | 5-7 天 |-| **Phase 6** | Guides 12 篇 | 每篇 1 commit | 3-4 天 |-| **Phase 7** | Self-Hosting 8 篇 | 每篇 1 commit | 2-3 天 |-| **Phase 8** | CLI Reference 14 篇 | 每篇 1 commit | 3-4 天 |-| **Phase 9** | 富内容组件(Mermaid / 定制组件) | 按组件分 commit | 2 天(可穿插) |-| **Phase 10** | i18n 中文 | 每篇 1 commit | 3-5 天(可延后) |--**总计约 55 篇 mdx + 基础设施**,按上述节奏单人 3-4 周可完成英文版。-------## 九、本规划**不做**的--- OSS 贡献者文档(用 `CONTRIBUTING.md` 顶着)-- API Reference 独立板块(CLI 覆盖 95% 场景,第一版不做)-- 版本化文档(`/v0.2/`、`/v0.3/`)-- Blog / Changelog UI(Changelog 先外链 `CHANGELOG.md`)-- 自动从代码生成 API reference-- 语义搜索 / 向量搜索(产品本身还没用 pgvector)-- Webhook autopilot trigger(代码未接路由)-------## 十、立即的下一步--本规划你确认后:--1. 开分支 `docs/rewrite-v1`-2. 执行 **Phase 0**(CI + 已做的 dev:docs,做成独立小 PR)-3. 执行 **Phase 1**(视觉基础)——独立 PR,你启动 dev server 看调性-4. 执行 **Phase 2**(IA 骨架)——独立 PR,你看导航-5. Phase 3 开始 **每篇一个 commit 依次推**--你按顺序 review,中间可随时 course correct。diff --git a/docs/feature-flags.md b/docs/feature-flags.mddeleted file mode 100644index abf173ecc2..0000000000--- a/docs/feature-flags.md+++ /dev/null@@ -1,237 +0,0 @@-# Feature Flags--Multica ships a framework-level feature flag implementation:--- **Backend**: `server/pkg/featureflag` — Go package.-- **Frontend**: `@multica/core/feature-flags` — TypeScript module with React hooks.--Both sides share the same vocabulary (`Decision`, `EvalContext`, `Rule`, `PercentRollout`) and the same FNV-1a percent bucketing, so a flag evaluated on the server and on the client lands in the same bucket for the same user.--The package is designed so new features can adopt feature flags without writing any infrastructure code — drop a rule into the static config, call `Service.IsEnabled` / `useFlag`, done.-------## Core concepts--```-[Toggle Point] --query--> [Service / Router] --read--> [Provider / Configuration]- business code static / env / chain-```--- A **Toggle Point** is the single `if` in business code. It always calls the Service, never the provider directly.-- The **Service** (`Service` in Go, `FeatureFlagService` in TS) is the router. Business code never depends on which provider is behind it.-- A **Provider** is the configuration backend. Today we ship `StaticProvider` (in-memory rules), `EnvProvider` (Go only — env-var override), and `ChainProvider` (composition). A future DB or LaunchDarkly provider plugs in without changing any caller.-- A **Decision** is the structured result: `{ enabled, variant, reason, source }`. `IsEnabled` is the boolean projection, `Variant` is the raw string. Use `Decision` for diagnostic endpoints.--Four flag categories (Martin Fowler):--| Category | Lifetime | Owner | Example |-|---|---|---|---|-| **Release** | Days–weeks | Engineering | Hide a half-finished page behind `flags_release_v2` |-| **Experiment** | Hours–weeks | Product / Data | A/B test `checkout_algo` between `control` and `experiment-v2` |-| **Ops** | Short or evergreen | SRE | Kill switch `billing_disable_invoice_pdf` |-| **Permission** | Years | Product | `plan_gate_enterprise_dashboard` |--Manage them in the same provider but treat them differently: Release flags get deleted; Ops flags need fast override paths (`FF_<KEY>` env var); Permission flags use `Allow` lists; Experiment flags use `PercentRollout`.-------## Backend (Go)--### Wiring at startup--The server constructs a `featureflag.Service` once in `cmd/server/main.go` via the standard helper:--```go-flags, err := featureflag.NewServiceFromEnv(featureflag.WithLogger(slog.Default()))-if err != nil {- slog.Error("feature flag configuration failed to load", "error", err)- os.Exit(1)-}-```--`NewServiceFromEnv` reads two env vars — both follow the same `MULTICA_*_FILE` / `FF_*` conventions documented in `.env.example`:--| Env var | Role |-|---|---|-| `MULTICA_FEATURE_FLAGS_FILE` | Path to the YAML rule set (optional; absent = no static rules). |-| `FF_<FLAG_KEY>` | Per-flag runtime override. `FF_BILLING_NEW_INVOICE_EMAIL=false` / `25%` / `experiment-v2`. Beats the YAML, no redeploy. |--The provider chain is `EnvProvider → YAML StaticProvider`. The server can boot with zero flag config — every `IsEnabled` call falls back to the caller's default until someone authors a rule.--### YAML schema--```yaml-# /etc/multica/feature-flags.yaml-billing_new_invoice_email:- default: true--checkout_algo:- default: false- variant: experiment-v2- percent:- percent: 25- by: user_id--ops_disable_recommendations:- default: false- allow: ["user-internal-1", "user-internal-2"]- allow_by: user_id-```--Every field except `default` is optional. `variant` is the on-variant — see the multi-arm note below. An empty file is a valid "no flags yet" state. Malformed YAML fails startup the same way `DATABASE_URL` parse errors do, so misconfig surfaces loudly.--### Attaching evaluation context to the request--```go-func middleware(flags *featureflag.Service, next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- ec := featureflag.EvalContext{- UserID: currentUserID(r),- WorkspaceID: currentWorkspaceID(r),- Attributes: map[string]string{"plan": currentPlan(r)},- }- ctx := featureflag.WithEvalContext(r.Context(), ec)- next.ServeHTTP(w, r.WithContext(ctx))- })-}-```--### Toggle point in business code--```go-if flags.IsEnabled(ctx, "billing_new_invoice_email", false) {- return s.sendNewInvoiceEmail(ctx, invoice)-}-return s.sendLegacyInvoiceEmail(ctx, invoice)-```--For multi-arm flags:--```go-switch flags.Variant(ctx, "checkout_algo", "control") {-case "experiment-v2":- return checkoutV2(ctx, order)-case "experiment-v3":- return checkoutV3(ctx, order)-default:- return checkoutControl(ctx, order)-}-```--`Rule.Variant` is the **on-variant**: it is only returned when the rule evaluates to enabled=true (allow hit, percent hit, default-on). When the rule evaluates to disabled (deny hit, percent miss, default-off) the Service returns `"off"` so callers branching on `Variant()` cannot route control users into the experiment arm. This is exercised by `TestStaticProviderVariantOnlyWhenEnabled` and is the same on the TS side.--The Service is nil-safe and missing-key-safe: `(*Service)(nil).IsEnabled(ctx, "any", true)` returns `true`. Business code never needs to guard against a missing flag.-------## Frontend (TypeScript / React)--### Mounting once at the root--```tsx-// apps/web/app/_providers.tsx (or the equivalent root)-import {- FeatureFlagsProvider,- FeatureFlagService,- StaticProvider,-} from "@multica/core/feature-flags";--const service = new FeatureFlagService(- new StaticProvider({- billing_v2_dashboard: { default: false, allow: ["user-internal"] },- checkout_algo: { default: true, variant: "experiment-v2",- percent: { percent: 25 } },- }),-);--export function Providers({ children }: { children: ReactNode }) {- const userId = useCurrentUserId();- return (- <FeatureFlagsProvider service={service} context={{ userId }}>- {children}- </FeatureFlagsProvider>- );-}-```--When the backend pushes a fresh rule set (via an API response or WebSocket), call `service.setProvider(new StaticProvider(remoteRules))` and the whole tree re-evaluates.--### Toggle point in a component--```tsx-import { useFlag, useVariant } from "@multica/core/feature-flags";--function BillingPage() {- const showV2 = useFlag("billing_v2_dashboard", false);- return showV2 ? <BillingV2 /> : <BillingV1 />;-}--function Checkout() {- const variant = useVariant("checkout_algo", "control");- switch (variant) {- case "experiment-v2": return <CheckoutV2 />;- case "experiment-v3": return <CheckoutV3 />;- default: return <CheckoutControl />;- }-}-```--Outside a `FeatureFlagsProvider` (Storybook, unit tests, error pages) `useFlag` / `useVariant` return the supplied default. You never have to mount the provider just to render a component in isolation.--### Completed v0.3.44 compatibility rollouts--Resource Labels has completed its schema-first rollout and is now always-available. Current clients always render agent- and skill-scoped labels, and-the backend no longer gates their catalog or assignment endpoints.-`/api/config` still reports `settings_resource_labels: true` so installed-desktop clients from v0.4.0 through at least v0.4.15 (every release before this-change) receive the permanently enabled behavior. Every client in that range-fails closed to `false` when the key is absent, so this compatibility decision-must remain until those clients are no longer supported; it is not an-operator-controlled flag.--The rollback prerequisite that originally justified the flag is implemented by-the down-migration chain: `174_legacy_label_index_rollback_prep.down.sql`-deletes all agent- and skill-scoped label rows before-`171_drop_legacy_label_namespace_index.down.sql` recreates the pre-162-workspace-wide unique name index. The remaining down migrations then remove-the resource-label junction tables and `resource_type` column.--Now that users can create resource-scoped labels, rollback to the pre-v0.3.44-schema is no longer supported: migration 174 would delete user data. Roll back-only to a release that understands resource-scoped labels.--Agent Builder has completed this rollout and is now always available. Current-clients always render the AI creation entry, and the backend no longer gates the-session endpoint. `/api/config` still reports `agents_agent_builder: true` so-installed desktop clients that still gate the entry on this config decision-also receive the permanently enabled behavior; this is a client-compatibility-decision, not an operator-controlled flag.--Agent skill toggles have completed this rollout and are now always available.-Current clients render the switch without a release flag, and the backend no-longer gates the write endpoint. `/api/config` still reports-`agents_skill_toggles: true` so installed v0.4.0 desktop clients also expose the-switch; this is a client-compatibility decision, not an operator-controlled-flag.--### Security note: never rely on the frontend alone--A frontend feature flag controls what the user *sees*. It does NOT enforce access. Any API route exposing the same capability MUST evaluate the matching backend flag independently. The two flags can share a key but they live in two `Service` instances and the backend value is the source of truth.-------## Best-practice checklist--Adopted from Martin Fowler, ConfigCat and Octopus.--- **Naming**: `{team}_{area}_{behavior}`, e.g. `billing_checkout_new_payment_flow`. No `enable_` / `disable_` prefixes (redundant).-- **One flag, one purpose**: never repurpose an old flag for a new feature. Add a new flag and delete the old one.-- **Plan the death of the flag at birth**: open a follow-up issue to remove the flag when the rollout completes. Release flags should live days, not quarters.-- **Convention**: `Off` is the legacy / safe state, `On` is the new behavior. Lets CI test "all-off (today)" and "all-on (tomorrow)".-- **Kill switch fast path**: ops-critical flags should be exposed via `EnvProvider` so SREs can flip them without a deploy.-- **Backend protection**: anything controlling access goes through the backend Service; the frontend flag is presentation only.-- **No secrets in flags**: variant values are not Secrets Manager / KMS. Use those for tokens, keys, and passwords.--See `docs/design.md` and `docs/timezone-architecture-rfc.md` for prior examples of how this pattern is used across the codebase.diff --git a/docs/ideation/2026-07-14-agent-list-visibility-field-ideation.html b/docs/ideation/2026-07-14-agent-list-visibility-field-ideation.htmldeleted file mode 100644index 5a9b4ec154..0000000000--- a/docs/ideation/2026-07-14-agent-list-visibility-field-ideation.html+++ /dev/null@@ -1,205 +0,0 @@-<!DOCTYPE html>-<html lang="zh-Hans">-<head>-<meta charset="utf-8">-<meta name="viewport" content="width=device-width, initial-scale=1">-<title>Ideation: Agents 列表页 · 可见性/访问范围字段</title>-<style>- :root {- --bg: #ffffff; --fg: #1a1a1a; --muted: #5b6470; --faint: #8a93a0;- --border: #e3e7ec; --surface: #f7f8fa; --accent: #2f6feb; --accent-soft: #eaf1fd;- --warn-soft: #fdf3e7; --warn-text: #9a6a1a; --good-soft: #eaf6ee; --good-text: #2a7a45;- --code-bg: #f2f4f7;- }- @media (prefers-color-scheme: dark) {- :root {- --bg: #14161a; --fg: #e7e9ee; --muted: #9aa3b0; --faint: #6b7480;- --border: #2a2f37; --surface: #1b1f25; --accent: #7aa2f7; --accent-soft: #1f2a3d;- --warn-soft: #3a2f1d; --warn-text: #d8a45a; --good-soft: #1d3a28; --good-text: #7fc594;- --code-bg: #20242b;- }- }- * { box-sizing: border-box; }- body {- margin: 0; background: var(--bg); color: var(--fg);- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;- font-size: 15.5px; line-height: 1.65; -webkit-font-smoothing: antialiased;- }- .wrap { max-width: 880px; margin: 0 auto; padding: 48px 28px 96px; }- header.eyebrow { color: var(--faint); font-size: 12px; letter-spacing: 0.14em; text-transform: uppercase; margin-bottom: 8px; }- h1 { font-size: 30px; line-height: 1.25; margin: 0 0 6px; letter-spacing: -0.01em; }- .meta { color: var(--muted); font-size: 13.5px; margin: 0 0 8px; }- .meta code { font-size: 12.5px; }- h2 { font-size: 20px; margin: 44px 0 14px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }- h3 { font-size: 17px; margin: 30px 0 4px; }- p { margin: 10px 0; }- code { background: var(--code-bg); padding: 1.5px 5px; border-radius: 4px; font-size: 13px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; }- pre { background: var(--code-bg); padding: 12px 14px; border-radius: 8px; overflow-x: auto; }- ul, ol { padding-left: 22px; }- li { margin: 4px 0; }- a { color: var(--accent); }- strong { color: inherit; }- .axis-line { font-family: ui-monospace, Menlo, monospace; font-size: 13.5px; }- article.idea { border: 1px solid var(--border); border-radius: 10px; padding: 20px 22px; margin: 18px 0; background: var(--bg); }- article.idea > h3 { margin-top: 0; display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }- .id-chip { font-family: ui-monospace, Menlo, monospace; font-size: 12px; background: var(--accent-soft); color: var(--accent); padding: 2px 8px; border-radius: 999px; }- .pill { font-family: ui-monospace, Menlo, monospace; font-size: 11.5px; padding: 2px 8px; border-radius: 999px; background: var(--surface); color: var(--muted); border: 1px solid var(--border); }- dl.fields { display: grid; grid-template-columns: 92px 1fr; gap: 4px 14px; margin: 12px 0 4px; }- dl.fields dt { color: var(--faint); font-size: 12.5px; letter-spacing: 0.04em; text-transform: uppercase; padding-top: 3px; }- dl.fields dd { margin: 0; font-size: 14.5px; }- .jumplist { display: flex; flex-wrap: wrap; gap: 8px; margin: 6px 0 2px; }- .jumplist a { font-size: 13px; }- table { border-collapse: collapse; width: 100%; font-size: 14px; margin: 8px 0; }- th, td { text-align: left; padding: 9px 12px; border-bottom: 1px solid var(--border); vertical-align: top; }- th { color: var(--muted); font-weight: 600; font-size: 12.5px; text-transform: uppercase; letter-spacing: 0.04em; }- .callout { background: var(--warn-soft); border-radius: 8px; padding: 12px 16px; margin: 14px 0; font-size: 14px; }- .callout .label { color: var(--warn-text); font-weight: 600; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase; display: block; margin-bottom: 4px; }- .diagram { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 18px; margin: 16px 0; }- .diagram svg { display: block; margin: 0 auto; max-width: 100%; height: auto; }- .diagram figcaption { text-align: center; color: var(--muted); font-size: 12.5px; margin-top: 10px; }- footer.composition-signal { margin-top: 56px; padding-top: 16px; border-top: 1px solid var(--border); color: var(--faint); font-size: 12.5px; }- footer.composition-signal code { font-size: 12px; }-</style>-</head>-<body>-<div class="wrap">-- <div class="eyebrow">Ideation · repo-grounded</div>- <h1>Agents 列表页:可见性 / 访问范围字段</h1>- <p class="meta">- <time datetime="2026-07-14">2026-07-14</time> ·- topic: <code>agent-list-visibility-field</code> ·- mode: <code>repo-grounded</code>(聚焦一轮:3 视角 / 4 存活)- </p>- <p class="meta">focus: 在 <code>agents</code> 列表页加一个"可见性范围"字段,是否更方便?</p>-- <section id="grounding">- <h2>Grounding Context(代码库上下文)</h2>- <ul>- <li><strong>页面</strong>:<code>packages/views/agents/components/agents-page.tsx</code>(1209 行)。现有列:<em>agent / status / owner / runtime / last_active / runs / model / created</em>。<strong>没有</strong>可见性/访问列。<code>visibility</code> 仅在 :319 行算成 <code>isPrivate</code>,作行内小锁标记。</li>- <li><strong>列系统</strong>:<code>AgentColumnKey</code> + <code>COLUMN_WIDTHS</code>(:108)+ <code>hiddenColumns</code>/<code>toggleColumn</code>(<code>useAgentsViewStore</code>)。<u>加一列是机械工作</u>。</li>- <li><strong>权限模型——两个独立概念(核心)</strong>:<code>visibility</code>(private|workspace,谁能<em>看见</em>,<code>canAccessPrivateAgent</code> agent_access.go:120)是<strong>派生字段</strong>,由 <code>permission_mode</code>(private|public_to)+ <code>invocation_targets</code> 派生(agent.ts:10-15)。<code>permission_mode</code>+<code>invocation_targets</code> 才是<em>触发/调用</em>的权威门槛(<code>canInvokeAgent</code> agent_access.go:48)。public_to+workspace = 任意成员/agent/system 可调用;private = 仅所有者(无 admin/A2A 旁路)。</li>- <li><strong>编辑面</strong>:<code>agent-access-settings.tsx</code> / <code>AccessPicker</code>,<strong>逐个 agent,全 UI 无任何批量入口</strong>。</li>- <li><strong>实测运营痛点(直接证据)</strong>:① 一眼看不出私有 vs 工作区 → 写原生 SQL 盘点;② 不能批量改 → 对 5 个工作区 70 个 agent 跑了 <code>UPDATE+INSERT</code>;③ 私有 agent 被 autopilot <code>run_only</code> 的 @mention <strong>静默丢弃</strong>(originator 为 NULL)—— 上游 <a href="https://github.com/multica-ai/multica/issues/5230">#5230</a>,列表页零信号。</li>- <li><strong>规模/语义</strong>:5 工作区、~81 agent;每工作区 ~14 业务 agent(工作区可调用)+ 3 内置(零号机 / Claude Code / Codex,刻意仅所有者私有)。</li>- <li><strong>已确认存在的基础设施</strong>:<code>AgentBatchToolbar</code>+<code>runBatch</code>(:646/:668,现仅用于归档/恢复);<code>AgentListFilters</code> 四维(view-store.ts:41);<code>AccessPicker</code> 可复用。</li>- </ul>- </section>-- <section id="axes">- <h2>Topic Axes</h2>- <p class="axis-line">1. what-to-show — 展示哪些权限/可见性数据</p>- <p class="axis-line">2. how-to-display — 列 vs 徽标 vs tooltip;消解 view/invoke 混淆</p>- <p class="axis-line">3. find-and-organize — 按访问范围筛选/分组/排序</p>- <p class="axis-line">4. manage-and-act — 行内/批量编辑、新 agent 默认值</p>- </section>-- <section id="ranked">- <h2>Ranked Ideas</h2>- <nav class="jumplist">- <a href="#i1">1. 有效访问列</a>- <a href="#i2">2. 批量改访问范围</a>- <a href="#i3">3. 访问筛选维度</a>- <a href="#i4">4. 新 agent 默认访问范围</a>- </nav>-- <article class="idea" id="i1">- <h3><span class="id-chip">1</span> 有效访问列(三态),而非裸 visibility <span class="pill">what-to-show + how-to-display</span></h3>- <p>加一列显示<strong>有效的调用范围</strong>——"工作区 / 指定人员 / 仅所有者",由 <code>permission_mode</code>+<code>invocation_targets</code> 合成,<strong>不</strong>读派生的 <code>visibility</code>。其中"仅所有者"这一态同时承担"自动化/autopilot 无法调用此 agent"的信号(#5230),通过 tooltip/副标说明。</p>-- <figure class="diagram">- <svg viewBox="0 0 720 230" width="720" height="230" role="img" aria-label="visibility 派生映射 vs 有效访问三态">- <defs>- <marker id="arr" markerWidth="9" markerHeight="9" refX="7" refY="4.5" orient="auto"><path d="M0,0 L9,4.5 L0,9 z" fill="#8a93a0"/></marker>- </defs>- <!-- left: effective access (3 states) -->- <text x="30" y="24" font-size="13" font-weight="700" fill="#1a1a1a">有效访问(3 态)</text>- <rect x="20" y="40" width="200" height="40" rx="6" fill="#eaf6ee" stroke="#2a7a45"/>- <text x="32" y="65" font-size="13" fill="#2a7a45">工作区 · 任意成员/agent 可调用</text>- <rect x="20" y="92" width="200" height="40" rx="6" fill="#eaf1fd" stroke="#2f6feb"/>- <text x="32" y="117" font-size="13" fill="#2f6feb">指定人员 · public_to + member</text>- <rect x="20" y="144" width="200" height="40" rx="6" fill="#fdf3e7" stroke="#9a6a1a"/>- <text x="32" y="169" font-size="13" fill="#9a6a1a">仅所有者 · 自动化无法触发</text>- <!-- arrow -->- <line x1="240" y1="112" x2="360" y2="112" stroke="#8a93a0" stroke-width="1.5" marker-end="url(#arr)"/>- <text x="252" y="104" font-size="11.5" fill="#5b6470">派生折叠(丢信息)</text>- <!-- right: raw visibility (2 states) -->- <text x="400" y="24" font-size="13" font-weight="700" fill="#1a1a1a">裸 visibility(2 态)</text>- <rect x="390" y="62" width="210" height="40" rx="6" fill="#eaf6ee" stroke="#2a7a45"/>- <text x="404" y="87" font-size="13" fill="#2a7a45">"workspace"</text>- <rect x="390" y="124" width="210" height="62" rx="6" fill="#f2f4f7" stroke="#8a93a0"/>- <text x="404" y="150" font-size="13" fill="#5b6470">"private"</text>- <text x="404" y="170" font-size="11.5" fill="#9a6a1a">↑ 指定人员 + 仅所有者 被合并</text>- </svg>- <figcaption>问题核心:<code>public_to + member</code> 目标的 agent 会被折叠成 <code>visibility:"private"</code>,与"仅所有者"无法区分。三态列保留了这个区分。</figcaption>- </figure>-- <dl class="fields">- <dt>Basis</dt><dd><code>direct:</code> <code>packages/core/types/agent.ts:10-15</code>——"<span>a public_to agent WITH a workspace target maps to visibility:'workspace'; everything else (private, or public_to scoped only to member/team targets) maps to visibility:'private'</span>"。即裸 visibility 把"仅所有者"与"指定人员"合并成同一标签。<code>agent_access.go:48-65</code> 的 <code>canInvokeAgent</code> 对 private / public_to 有截然不同的分支。</dd>- <dt>Rationale</dt><dd>用户字面诉求(加"可见性列")若照搬 <code>visibility</code> 会<strong>主动误导</strong>——一个 public_to+member 的 agent 会显示 "private",但特定成员其实能运行它。有效访问列一次建立正确心智,且"仅所有者"态把 #5230 的静默丢弃风险提前到最早可见的触点。</dd>- <dt>Downsides</dt><dd>第 8 列增加横向滚动;建议默认隐藏或同时作为排序/筛选键。标签计算是纯前端、字段已在列表 payload 里。</dd>- <dt>Confidence</dt><dd>92%</dd>- <dt>Complexity</dt><dd><span class="pill">Low–Medium</span></dd>- </dl>- </article>-- <article class="idea" id="i2">- <h3><span class="id-chip">2</span> 经现有批量工具栏批量改访问范围 <span class="pill">manage-and-act</span></h3>- <p>在 <code>AgentBatchToolbar</code>(agents-page.tsx:646,现仅归档/恢复)增加"设置访问范围…"动作,用既有 <code>runBatch</code>(:668)逐个套用 <code>AccessPicker</code> 的选择。把"筛选 → 全选 → 设为工作区"变成几秒钟的事,直接移除我们刚被逼着写的 SQL。</p>- <dl class="fields">- <dt>Basis</dt><dd><code>direct:</code> <code>agents-page.tsx:668</code> 的 <code>runBatch</code> 是带失效处理的通用顺序执行器;<code>:661</code> <code>allManageable</code> 已做行级权限门控;<code>agent-access-settings.tsx</code> 的 <code>AccessPicker</code> 发出 <code>onChange(next)</code> 补丁,逐行可复用。痛点 #2(跨 5 工作区 70 agent 的 <code>UPDATE+INSERT</code>)正是因 UI 无此路径才发生。</dd>- <dt>Rationale</dt><dd>杠杆最高。此后每次访问范围重组(团队入职、把私有 agent 开放给工作区)都从"有风险、不可重放、需管理员"的 SQL 变成 30 秒、可审计、非管理员可用的 UI 操作。基础设施 100% 复用。</dd>- <dt>Downsides</dt><dd>需确认对话框护栏(访问范围是安全敏感字段);"指定人员"批量极易出错,建议批量只开放"工作区 / 仅所有者"两档。</dd>- <dt>Confidence</dt><dd>90%</dd>- <dt>Complexity</dt><dd><span class="pill">Medium</span></dd>- </dl>- </article>-- <article class="idea" id="i3">- <h3><span class="id-chip">3</span> 访问筛选维度 <span class="pill">find-and-organize</span></h3>- <p>给 <code>AgentListFilters</code>(view-store.ts:41)加一个 <code>access</code> 多选维度,取值与列一致(工作区/指定人员/仅所有者)。一键隔离某一类,而非扫 80 行或跑 SQL。它也是想法 2 的发现机制——筛选 → 全选 → 批量改。</p>- <dl class="fields">- <dt>Basis</dt><dd><code>direct:</code> view-store.ts:41-54 已有四维(availability/runtimes/owners/models),<code>agents-page.tsx</code> 行筛选是纯前端按字段匹配,加第五维机械一致。痛点 #1("写 SQL 盘点哪些是私有")本质就是缺这个筛选。</dd>- <dt>Rationale</dt><dd>对"盘点"任务,筛选 > 列:列只能逐行扫,筛选直接隔离目标集。也是想法 2 批量流的前置发现步骤。改动极小。</dd>- <dt>Downsides</dt><dd>取值粒度(二态 vs 三态)需与列保持一致,需团队拍板。</dd>- <dt>Confidence</dt><dd>90%</dd>- <dt>Complexity</dt><dd><span class="pill">Low</span></dd>- </dl>- </article>-- <article class="idea" id="i4">- <h3><span class="id-chip">4</span> 工作区级"新 agent 默认访问范围" <span class="pill">manage-and-act / default</span></h3>- <p>工作区设置里设新建用户 agent 的默认 <code>permission_mode</code>(自动化重的工作区可默认 public_to+workspace),内置 agent 显式钉为私有。从源头消除"每个新工作区都要重做一次 70 agent 清理"的积压。</p>- <div class="callout"><span class="label">Scope-adjacent(范围相邻)</span>这是一个<strong>工作区设置</strong>,不是列表页字段;可经由列表页暴露(如横幅提示),但落地在工作区设置。用户聚焦在列表页字段,故此条标记为相邻、可选。</div>- <dl class="fields">- <dt>Basis</dt><dd><code>reasoned:</code> 批量 SQL 是症状,根因是默认值与意图不符——若每工作区 ~14 业务 agent 按意图都该是工作区可调用,则 private-by-default 迫使每个 agent 都要 opt-in。<code>external:</code> GitHub 仓库默认 public、Slack 频道默认工作区可见——协作工具默认共享、私有是 opt-out。</dd>- <dt>Rationale</dt><dd>唯一能阻止痛点<em>复发</em>的想法。想法 2 是"治理",本条是"预防"。</dd>- <dt>Downsides</dt><dd>默认值放工作区级还是所有者级需设计;内置 agent 必须豁免;离开列表页表面。</dd>- <dt>Confidence</dt><dd>70%</dd>- <dt>Complexity</dt><dd><span class="pill">Medium</span></dd>- </dl>- </article>- </section>-- <section id="rejections">- <h2>Rejection Summary</h2>- <table>- <thead><tr><th>#</th><th>想法</th><th>剔除理由</th></tr></thead>- <tbody>- <tr><td>—</td><td>裸 <code>visibility</code> 列(用户字面诉求,照搬)</td><td>会误导:<code>visibility</code> 是派生的 2 态投影(agent.ts:10-15),<code>public_to+member</code> 的 agent 会显示 "private"。被想法 1 取代。</td></tr>- <tr><td>—</td><td>独立的"自动化不可达"告警标记</td><td>并入想法 1——"仅所有者"态已承载该后果。</td></tr>- <tr><td>—</td><td>行内快切(kebab / 单元格 popover)</td><td>被想法 2(批量)+ 现有逐 agent inspector 覆盖;杠杆较低的便利项。</td></tr>- <tr><td>—</td><td>按访问范围排序</td><td>被想法 3(筛选即可分组)吸收;增量价值低。</td></tr>- <tr><td>—</td><td>访问范围分布计数 chip 条</td><td>与想法 3 及既有 <code>scopeCounts</code> 重叠;价值较低。</td></tr>- <tr><td>—</td><td>axis 覆盖</td><td>4 个存活已覆盖全部 4 个轴;无空轴。</td></tr>- </tbody>- </table>- </section>-- <footer class="composition-signal">- Composed 2026-07-14 by ce-ideate (focused pass) · repo <code>multica-ai/multica</code> · scratch <code>/tmp/compound-engineering/ce-ideate/42e47e33</code>- </footer>--</div>-</body>-</html>diff --git a/docs/onboarding-refactor-plan.md b/docs/onboarding-refactor-plan.mddeleted file mode 100644index 779179eb06..0000000000--- a/docs/onboarding-refactor-plan.md+++ /dev/null@@ -1,218 +0,0 @@-# Onboarding v3 — Thin Server, Frontend-Orchestrated Welcome--## 1. 背景--两次错位重构(MUL-2438 + da0ecb6a)叠加产出了一个味道很重的 onboarding:-- `users.onboarded_at` 在 4 个 handler 里分别 `MarkUserOnboarded`,每处副作用还不一样-- 同样的"种 install-runtime issue"在 4 个调用点重复,靠 advisory lock 在底层做去重-- Step 3 Connect 与 Skip 路径不对称(一个延迟 mark,一个立即 mark)-- 工作区 Modal 自己 query runtime 列表挑第一个,完全丢弃用户在 Step 3 的选择-- `onboarded_at` 字段同时承担"完成状态"和"Modal 触发条件"双语义--最初的 v2 方案(本 wip 分支的 PR 1-7)走"持久化字段 + 工作区 init 4 分支 dispatcher"路线 — 把 Step 3 的选择 PATCH 进 `users.onboarding_runtime_id` / `onboarding_runtime_skipped`,工作区入口读这两个字段决定弹什么。可工作,但把过去 React 内存里的瞬态意图变成了数据库的持久化字段,后端业务复杂度不降反升:多了一个 `OnboardingService`,多了一个 `WorkspaceContentService`,handler 多了一个 `EnsureOnboardingContent` endpoint,前端多了 4 分支 dispatcher 组件。--数据分析师确认生产里 0 个 mid-flow 用户(`有 workspace + onboarded_at IS NULL`),v2 加的两字段没有真实使用,可以安全删除。--v3 在 v2 之上做更激进的清理:**后端 onboarding 业务复杂度归零,Helper agent / starter issue / 中英文案全部在前端 hook 里调通用 `createAgent` / `createIssue` 完成**。--## 2. 设计 — 5 条核心原则--1. **`users.onboarded_at` 是唯一 onboarding 状态字段**(删 v2 加的两字段)-2. **Onboarding 阶段(Step 1-3)纯收集**,Step 3 按钮 = mark + welcome-store.set + navigate-3. **后端 onboarding 业务复杂度归零** — 删 `BootstrapOnboarding*` / `OnboardingService` / `WorkspaceContentService` / `EnsureOnboardingContent` 全套;后端 onboarding 只剩 mark + 问卷-4. **进工作区 hook 看 welcome-store**,有信号 → 按 runtime/skip 分两路调通用 `createAgent` / `createIssue`-5. **Helper instructions / starter prompt / install-runtime issue 描述(EN/ZH)全部在前端 TS 模块**(`packages/views/onboarding/templates/`)--外加双向路由 hard gate:`apps/web/app/[workspaceSlug]/layout.tsx` 拦未 onboarded → `/onboarding`;`apps/web/app/(auth)/onboarding/page.tsx` 拦已 onboarded → workspace。桌面端用 `App.tsx` 的 overlay 决策达成同样效果(no URL bar, no router.replace)。--## 3. 4 类用户链路--### 3.1 新用户,Step 3 选 runtime--```-Step 3 [开始探索]- → completeOnboarding("full", workspace.id) ─ 后端只 mark- → welcomeStore.set({wsId, choice:"runtime", runtimeId})- → navigate(/<slug>/issues)-workspace layout gate: onboarded_at != NULL ✓ 放行-<WelcomeAfterOnboarding /> consumes welcome-store:- phase 1: full-screen loading "Preparing your Helper…"- api.listAgents → 查重名 Multica Helper(workspace 可见的)- → 找到 → 复用- → 没找到 → api.createAgent({name, instructions: HELPER_INSTRUCTIONS[lang], runtime_id, ...})- phase 2: blocking Modal(无关闭按钮 / Escape no-op / outside-click no-op)- Helper avatar + name + description + 3 张 starter cards- phase 3: 用户挑卡 → api.createIssue({title, description: prompt,- assignee_type:"agent", assignee_id: agent.id}) → navigate(issue)-```--### 3.2 新用户,Step 3 点 Skip--```-Step 3 [跳过]- → completeOnboarding("runtime_skipped", workspace.id)- → welcomeStore.set({wsId, choice:"skip"})- → navigate(/<slug>/issues)-workspace layout gate ✓ 放行-<WelcomeAfterOnboarding /> consumes signal:- Modal 打开(可关闭)- 后台并发 api.createIssue × 2:- - Connect a runtime to start using agents- - Create your first Multica Agent- 渲染 2 张 issue 卡;点卡 → navigate;关 Modal → 留在 /issues 列表-```--### 3.3 被邀请用户--```-AcceptInvitation handler:- 事务内 qtx.CreateMember + qtx.MarkUserOnboarded(必须保留!)-navigate(/<slug>/issues) 不带 welcome-store 信号-workspace layout gate ✓ 放行-<WelcomeAfterOnboarding /> 无信号 → 渲染 null-```--### 3.4 老用户回访--```-resolvePostAuthDestination: hasOnboarded ✓ + workspace[0] → /<slug>/issues-layout gate ✓ 放行-welcome-store 无信号 → 不弹-```--## 4. 数据 / 字段终态--| 字段 | 含义 | 谁读 |-|---|---|---|-| `users.onboarded_at` | 唯一 onboarding 完成信号 | layout hard gate × 2 |-| `users.onboarding_questionnaire` | 问卷答案 | OnboardingFlow 预填 |-| (PostHog `OnboardingCompleted` event) | Skip vs Connect 历史分析 | 数据分析 |--**删掉**:`onboarding_runtime_id`、`onboarding_runtime_skipped` 列 + `user_onboarding_runtime_choice_check` CHECK 约束。Welcome 触发改用前端 Zustand transient store(`packages/core/onboarding/welcome-store.ts`),read-once-then-clear 语义。--## 5. 关键设计决策--### D1:NavigationAdapter 不支持 state → Zustand transient store--`packages/views/navigation/types.ts` 的 `push(path: string): void` 不接 state,所以不能用 `navigate(path, {state})` 模式。改用 `packages/core/onboarding/welcome-store.ts`:Step 3 完成时 `set({...})`,Welcome hook mount 时 `consume()`(一次读 + 清空)。store 非 persist → 刷新即丢 = Welcome Modal 不会被刷新重弹,符合"一次性体验"预期。--### D2:Desktop 路由 hard gate 走 overlay 而非 router.replace--桌面端 onboarding 是 `WindowOverlay`,不是 react-router 路由。`apps/desktop/src/renderer/src/App.tsx` 的 overlay 决策 effect 增加规则:`!hasOnboarded` 一律 `setCurrentWorkspace(null,null) + open onboarding overlay`(不管 wsCount)。web 端在 `layout.tsx` 用 `router.replace(paths.onboarding())` 直接跳。两套实现在效果上等价。--### D3:`resolvePostAuthDestination` 改回 onboarded-first--V2 改成了 workspace-presence-first(为了不把 mid-flow 用户踢回 onboarding),v3 还原成 onboarded-first。理由:layout hard gate 会在 `!onboarded` 时强制 redirect,resolver 直接走 workspace 只是浪费一次 navigation;mid-flow 在 v3 下概率极低(仅 Step 2 完关 app 这一窗口)。--### D4:Helper instructions / 长文案放 TS 模块,不放 i18n JSON--instructions 是 94 行 markdown,issue 描述是 60+ 行带列表 / 代码块。放在 `packages/views/onboarding/templates/` 下 3 个 TS 模块,每个导出 `{en, zh}` 字符串 const。短文案(Modal 标题 / 副标题 / 按钮 / 卡片标题)仍走 i18n JSON。--### D5:重名 Helper 防重--刷新 / StrictMode 双 mount 都可能让 hook 多次进入。前端用:-1. `useRef` 一次性锁 prevents 同 mount 内重复触发-2. Welcome 信号 `consume()` 一读即清,即使 React 多次 mount 也只第一次拿到信号-3. 进 `createAgent` 前先 `api.listAgents` 查重名 + visibility="workspace" + !archived,有则复用--### D6:失败处理--- runtime 路径:阻塞 Modal + 失败 retry UI(无关闭),用户卡死时 `onAbandon` 把信号清空恢复路由-- skip 路径:Modal 可关闭,每条 issue 失败显示 per-card retry-- `onboarded_at` 已 set,失败不阻塞 — 用户最坏情况是手动建 agent / 关 Modal 用空 workspace--## 6. 文件改动盘点(相对 main)--### 删-- `server/internal/service/onboarding.go`-- `server/internal/service/workspace_content.go`-- `server/internal/handler/onboarding.go`:`BootstrapOnboardingRuntime`、`BootstrapOnboardingNoRuntime` handler 整体 + 相关常量(`onboardingAssistantInstructions` 94 行 markdown、`onboardingAssistantName`、`onboardingIssueTitle`、`onboardingIssueDescription`、`onboardingAssistantAvatarURL`、`onboardingAssistantDescription`、`onboardingAgentTemplate`)-- `server/internal/handler/workspace.go`:`EnsureOnboardingContent` handler-- `server/cmd/server/router.go`:3 条路由(`runtime-bootstrap` / `no-runtime-bootstrap` / `ensure-onboarding-content`)-- `server/internal/handler/handler.go`:`OnboardingService` / `WorkspaceContent` 字段 + 实例化-- `server/internal/handler/onboarding_test.go`:5 个 Bootstrap* 测试 + 2 个 PatchOnboarding 测试(只留 JoinCloudWaitlist 测试)-- `packages/views/workspace/workspace-onboarding-init.tsx` + 测试-- `packages/views/workspace/onboarding-helper-modal.tsx` + 测试-- `packages/core/onboarding/store.ts`:`recordOnboardingRuntimeChoice` / `recordOnboardingRuntimeSkipped` / `bootstrapRuntimeOnboarding` / `bootstrapNoRuntimeOnboarding`-- `packages/core/api/client.ts`:`bootstrapOnboardingRuntime` / `bootstrapOnboardingNoRuntime` / `ensureOnboardingContent` + Response interfaces + EMPTY consts-- `packages/core/api/schemas.ts`:两个 Bootstrap schemas + User schema 的两字段-- `packages/core/types/workspace.ts`:User 的两个新字段-- `packages/views/locales/{en,zh-Hans}/onboarding.json`:`onboarding_helper_modal.*` 和 `workspace_init.*` keys--### 改-- `server/migrations/098_user_onboarding_runtime_choice.up.sql`:反转为 DROP CONSTRAINT/COLUMN IF EXISTS(同名文件、保留 098 序号)-- `server/migrations/098_user_onboarding_runtime_choice.down.sql`:no-op + 注释说明不可逆-- `server/pkg/db/queries/user.sql`:`PatchUserOnboarding` 回退到只接 questionnaire-- `server/internal/handler/onboarding.go`:`CompleteOnboarding` 简化为直接 `qtx.MarkUserOnboarded`(无 service 包装)+ `PatchOnboarding` 只接 questionnaire-- `server/internal/handler/invitation.go`:`AcceptInvitation` 改回直接 `qtx.MarkUserOnboarded`(保留 mark 调用 — 注释强调 layout gate 依赖)-- `server/internal/handler/workspace.go`:`CreateWorkspace` 删 `ClaimStarterContentStateIfUnset` 调用(后端不再触碰 `starter_content_state`)-- `server/internal/handler/auth.go`:`UserResponse` / `userToResponse` 删两字段-- `server/internal/handler/workspace_test.go`:测试断言保留,注释更新引用 layout gate 而非 OnboardingHelperModal-- `apps/web/app/[workspaceSlug]/layout.tsx`:加 hard gate effect + 改挂 `<WelcomeAfterOnboarding />`-- `apps/desktop/src/renderer/src/App.tsx`:overlay 决策加规则 — `!hasOnboarded` 一律开 onboarding overlay 并先 `setCurrentWorkspace(null,null)`-- `apps/desktop/src/renderer/src/components/workspace-route-layout.tsx`:`<WorkspaceOnboardingInit />` → `<WelcomeAfterOnboarding />`-- `packages/core/onboarding/index.ts`:精简 exports + 加 welcome-store exports-- `packages/core/paths/resolve.ts`:回到 onboarded-first 优先级-- `packages/core/paths/resolve.test.ts`:断言同步翻新-- `packages/views/onboarding/onboarding-flow.tsx`:`handleRuntimeNext` 改为 await `completeOnboarding` + `welcomeStore.set` + navigate-- `apps/web/test/helpers.tsx`:mockUser 删两字段-- `packages/views/package.json` exports:删 v2 两个 workspace 入口,加 `./workspace/welcome-after-onboarding`--### 加-- `packages/core/onboarding/welcome-store.ts` + 测试:Zustand transient store-- `packages/views/onboarding/templates/helper-instructions.ts`:Helper agent 系统提示词,EN/ZH 各一份-- `packages/views/onboarding/templates/install-runtime-issue.ts`:Skip 路径第 1 条 issue 文案(从 server 的 EN/ZH 双语描述完整搬过来)-- `packages/views/onboarding/templates/create-agent-guide-issue.ts`:Skip 路径第 2 条新 issue 文案(EN/ZH)-- `packages/views/onboarding/templates/index.ts`:barrel + `pickContentLang(language)`-- `packages/views/workspace/welcome-after-onboarding.tsx`:替代 v2 两个组件的统一 Welcome 体验-- `packages/views/workspace/welcome-after-onboarding.test.tsx`:5 个测试覆盖 runtime / skip / 重名复用 / navigate / 渲染门-- `packages/views/locales/{en,zh-Hans}/onboarding.json`:新增 `welcome_after_onboarding.{loading_helper,error_*,retry,dismiss_error,runtime.{title,subtitle,helper_description,cards.*},skip.{title,subtitle,open_issue,close,cards.*}}`--## 7. 老用户兼容性--生产数据(数据分析师 read-only audit):-- `users_with_workspace` = 33,172-- 其中 `onboarded_at IS NULL` = **0**--→ 没有 mid-flow 用户需要 backfill 或邮件通知。migration 098 反转 SQL 在生产里是 no-op(没有列要删,因为生产从未运行过 v2 的 add-column);在 dev 数据库上 IF EXISTS 保护让任何状态都能干净收敛到"无字段"。--老用户(`onboarded_at != NULL`)100% 安全:-- web layout hard gate `if (user.onboarded_at == null)` → 永不触发-- desktop App.tsx overlay 决策 `!hasOnboarded && wsCount > 0` → 永不触发-- welcome-store 在 onboarding-flow.tsx Step 3 之外永不 `set` → Welcome Modal 永不弹--被邀请用户(invitee)的 `AcceptInvitation` 必须保留 `qtx.MarkUserOnboarded` — 注释里强调:"DO NOT REMOVE 否则 layout gate 把 invitee 踢回 /onboarding"。--## 8. 验收 — invariant + deprecation shim--每条可用 grep 或单元测试机械验证:--1. `onboarded_at` 的写入收敛到 3 个 handler:`CompleteOnboarding`(v3 主路径)、`AcceptInvitation`(invitee 必须)、`BootstrapOnboarding*`(**shim,见 §10**)。全部直接调 `qtx.MarkUserOnboarded`,无 service 包装。`grep -rln "qtx.MarkUserOnboarded\|h.Queries.MarkUserOnboarded" server/internal/handler/ | grep -v _test.go`-2. v3 前端永不调旧 bootstrap endpoint:`grep -rn "bootstrapOnboardingRuntime\|bootstrapOnboardingNoRuntime\|ensureOnboardingContent" packages/ apps/` → 0 命中-3. v2 字段全删:`grep -rn "onboarding_runtime_id\|onboarding_runtime_skipped" packages/ apps/` → 0 命中-4. Welcome Modal 不再自查环境:`grep -rn "runtimeListOptions" packages/views/workspace/` → 0 命中-5. welcome-store 信号只来自 onboarding-flow,只被 welcome-after-onboarding 消费(`grep -rln "useWelcomeStore"` 应该只命中 4 个文件:store、welcome 组件、onboarding-flow、各自的测试)-6. 老用户登录 → 直接进工作区 → 不弹 Modal、无 loading veil(场景 4 手动验证)--## 10. Deprecation shim — `BootstrapOnboarding*`--**为什么保留**:v3 server 发布到 desktop auto-update 完成之间有 ~30 分钟真空期,期间老桌面会调旧 endpoint。删了 endpoint → 老桌面 404 → 新用户 onboarding 死循环。--**位置**:`server/internal/handler/onboarding_shim.go`(独立文件,所有 deprecated 代码都在这里;v3 主路径 `onboarding.go` 不含一行 shim 代码)。--**约束**:-- 简化版实现:handler 直接 `qtx.MarkUserOnboarded` + `qtx.CreateAgent` + `qtx.CreateIssue` + `qtx.SetStarterContentState`,不重新引入 `OnboardingService` / `WorkspaceContentService` 抽象层(那是 v2 的复杂度,已经死了)-- 文案常量完整保留(`onboardingAssistantInstructions` 94 行 markdown、`enNoRuntimeIssueDescription` 等),和前端 `packages/views/onboarding/templates/` 双轨并行,**这两份必须保持同步**直到 shim 删除-- `claimStarterContentStateIfUnset` 局部 helper 也保留,因为老桌面靠这个字段抑制 legacy starter-content dialog-- 5 个回归测试(`TestBootstrapOnboarding*`)保留,保护 shim 行为不被无意改动--**删除条件**:`X-Client-Version` telemetry 确认无任何活跃 desktop 在调这俩 endpoint(典型窗口:2-3 个 release 后)。删的时候一并删:-- `server/internal/handler/onboarding_shim.go` 整文件-- `server/cmd/server/router.go` 里 2 条 deprecated 注释 + 路由-- `server/internal/handler/onboarding_test.go` 末尾 5 个 `TestBootstrapOnboarding*`--## 9. 未来工作--- `starter_content_state` 列(老桌面端兼容)— v3 后端不再触碰,但列保留(老桌面读 NULL → 渲染 legacy 导入 dialog)。可在 desktop 0.2.x 之前的版本全部 EOL 后单独 PR 删-- `OnboardingCompletionPath` 里的 `cloud_waitlist` enum 值实际无人发送 — 可清理-- `apps/web/app/[workspaceSlug]/layout.test.tsx`(新增)+ `apps/desktop/src/renderer/src/App.test.tsx`(新增用例)覆盖两端 hard gate 的 redirect 行为 — 当前由手动 E2E 覆盖diff --git a/docs/plans/2026-07-14-001-feat-agent-list-access-scope-plan.md b/docs/plans/2026-07-14-001-feat-agent-list-access-scope-plan.mddeleted file mode 100644index 7bee08b44b..0000000000--- a/docs/plans/2026-07-14-001-feat-agent-list-access-scope-plan.md+++ /dev/null@@ -1,231 +0,0 @@-----title: Agent List Access-Scope Management - Plan-type: feat-date: 2026-07-14-topic: agent-list-access-scope-artifact_contract: ce-unified-plan/v1-artifact_readiness: implementation-ready-product_contract_source: ce-brainstorm-execution: code------# Agent List Access-Scope Management - Plan--> **Product Contract preservation:** unchanged except R7 — bulk now offers all three access scopes (Workspace / Specific people / Owner-only) via the reused AccessPicker; user override of the original two-tier limit during planning. All other R/A/F/AE IDs and scope boundaries preserved.--## Goal Capsule--- **Objective:** Make an agent's access scope a first-class, visible, and manageable dimension on the agents list page, so any access-scope question or change is answerable without raw SQL or opening many per-agent detail pages.-- **Product authority:** Product Contract from `ce-brainstorm` (this file's prior requirements-only state). Planning enriches it in place; the only product change is the R7 override noted above.-- **Stop conditions:** All four implementation units land; `pnpm typecheck`, `pnpm test`, `pnpm lint` green; a browser smoke confirms the column, filter, and bulk action on real agents.-- **Execution profile:** Pure frontend wiring in `packages/core/agents/` and `packages/views/agents/`. No backend change.-- **Open blockers:** None blocking. The structural decisions (single confirmation dialog, owner-only gate, AccessPicker wrapper) are settled here; only final dialog wording is polished during implementation.-- **Tail ownership:** The implementing agent (`ce-work` or a human) owns execution; progress is derived from git, not stored here.-------## Product Contract--### Summary--A generic, upstream-able agents-list-page feature with three connected mechanics: a three-state "effective access" column (Workspace / Specific people / Owner-only) visible by default, a matching filter dimension, and a "Set access scope" bulk action on the existing batch toolbar that offers all three scopes via the reused AccessPicker. Together they form a see → filter → change loop, computed entirely from existing permission fields with no backend change.--### Problem Frame--Operators cannot read or change agent access scope from the list page today. The list shows eight columns — agent, status, owner, runtime, last_active, runs, model, created — none of which says who can invoke an agent. The only access signal is a small lock marker derived from the `visibility` field, and `visibility` is itself a lossy two-state projection of the authoritative `permission_mode` + `invocation_targets`: a `public_to` agent scoped to specific people maps to `visibility: "private"`, indistinguishable from a truly owner-only agent.--The cost showed up directly. Inventorying which agents were private versus workspace-invocable required raw SQL because no column or filter answers it. Changing scope across many agents required a bulk `UPDATE` + `INSERT` in SQL — observed at the scale of 70 agents across 5 workspaces — because the UI edits one agent at a time. These are the workflows the list page should own, and it currently forces operators outside the product to do them.--### Requirements--**Effective-access column**--- R1. The list gains a column showing each agent's effective access scope as one of three states — Workspace, Specific people, or Owner-only — computed from `permission_mode` + `invocation_targets`, not from the derived `visibility` field.-- R2. The state mapping is deterministic: Workspace = `public_to` with a workspace target; Specific people = `public_to` scoped to member/team target(s) (or no targets); Owner-only = `private`.-- R3. The column is visible by default, not hidden behind the column toggle.-- R4. The column label is localized across all four locales (en, zh-Hans, ja, ko); Chinese copy follows the project conventions doc, keeping the product noun "agent" in English within zh-Hans.--**Access filter**--- R5. The list filter gains an `access` multi-select dimension with the same three values, isolating a class in one click independent of whether the column is visible.--**Bulk edit**--- R6. The batch toolbar offers a "Set access scope" action that applies a chosen scope to all selected agents. The action is gated by ownership (`isOwnedByMe`), not the broader manage permission, because the backend enforces owner-only writes for `permission_mode` / `invocation_targets` — agents the operator does not own are skipped (a stricter gate than archive/restore, which admit workspace admins).-- R7. Bulk offers all three access scopes — Workspace, Specific people, and Owner-only — by reusing the AccessPicker. The chosen scope, including any specific-people member targets, applies to all selected agents. (Overridden during planning from an earlier two-tier limit; the operator wants the flexibility and can reverse a wrong choice by re-running bulk edit.)-- R8. A bulk change requires a confirmation dialog that shows the target scope and the affected-agent count clearly enough that an erroneous change can be reversed by running bulk edit again.--**Uniform treatment**--- R9. All agents are treated uniformly; no built-in-agent special-casing.--### Key Decisions--- **Three-state effective access over raw `visibility`.** `visibility` is a derived two-state projection; a raw-visibility column would label a specific-people agent as "private" and mislead operators about who can run it.-- **Frontend-computed from the existing list payload.** No backend or API change. `permission_mode` and `invocation_targets` are both present in the list response (`SELECT *` carries `permission_mode`; the handler attaches `invocation_targets`).-- **Column visible by default.** At-a-glance access information is prioritized over horizontal density. Room is made by accepting horizontal scroll (mirroring the existing pattern), not by hiding another column.-- **Bulk offers all three scopes via the reused AccessPicker.** Specific-people is allowed in bulk (R7 override); the chosen member-target set applies uniformly to all selected agents.-- **Reuse existing infrastructure.** The batch toolbar, its sequential runner, the filter dimension model, the access picker, and the column system all exist; this is wiring, not new machinery.-- **Generic and upstream-able.** Uniform agent treatment and no self-host special-casing, so the change is mergeable as-is into the official repo.--### Key Flows--- F1. Bulk access-scope change- - **Trigger:** Operator selects one or more agents and chooses "Set access scope" in the batch toolbar.- - **Actors:** Owner of the selected agents (the backend rejects access-scope writes from non-owners, including workspace admins).- - **Steps:** Choose target scope (Workspace, Specific people, or Owner-only) via AccessPicker → confirmation dialog shows the scope, the owned count, and the skipped count → confirm → applied to all owned selected agents; non-owned ones are skipped → list refreshes.- - **Covered by:** R6, R7, R8.--### Acceptance Examples--- AE1.- - **Given:** an agent with `permission_mode: public_to` and a member target.- - **When:** the list renders.- - **Then:** the effective-access column shows "Specific people", not "Owner-only", even though derived `visibility` is "private".- - **Covers:** R1, R2.-- AE2.- - **Given:** a `private` agent with no invocation targets.- - **When:** the list renders.- - **Then:** the effective-access column shows "Owner-only".- - **Covers:** R1, R2.-- AE3.- - **Given:** a selection mixing owned and non-owned agents.- - **When:** the operator bulk-sets scope to Workspace and confirms.- - **Then:** the confirmation dialog shows the affected count and the skip count; only owned selected agents change; non-owned ones are skipped.- - **Covers:** R6, R8.-- AE4.- - **Given:** a workspace with private and workspace-invocable agents.- - **When:** the operator filters access = Owner-only.- - **Then:** only private agents remain.- - **Covers:** R5.-- AE5.- - **Given:** three selected agents.- - **When:** the operator bulk-sets scope to Specific people with a chosen member set and confirms.- - **Then:** all three agents receive the same `public_to` + member-target configuration.- - **Covers:** R7.--### Scope Boundaries--**Deferred for later**--- The #5230 "automation cannot trigger this agent" affordance on the Owner-only state. It is a separate upstream bug with its own fix path; keeping it out keeps this PR focused and mergeable.-- A workspace-level default access scope for newly created agents. It prevents the cleanup backlog from recurring but is a separate settings-surface concern.-- Inline (per-row popover) access editing. Per-agent inspector plus the new bulk action cover the same ground.--**Deferred to follow-up work**--- Refactoring `AccessPicker`'s internal scope logic to call the new shared effective-access helper (U1). The helper and the picker currently duplicate the same derivation; consolidating is a clean follow-up but is deliberately out of scope here to keep the PR focused.--**Outside this change**--- Backend API or schema changes. Effective access is frontend-computed from fields already in the list payload.-- Special handling of built-in agents. Uniform treatment is the generic product decision.--### Dependencies / Assumptions--- `permission_mode` and `invocation_targets` are present in the agent list payload. **Verified** — `ListAgents` is `SELECT *` (carries `permission_mode`) and the handler attaches `invocation_targets` per agent.-- The existing per-agent update path (`api.updateAgent`) can be driven per selected agent by the batch toolbar's sequential runner, mirroring archive/restore.--### Sources / Research--- Column system: `packages/core/agents/stores/view-store.ts` (`AgentColumnKey`, `AGENT_DEFAULT_HIDDEN_COLUMNS`, `toggleColumn`); `packages/views/agents/components/agents-page.tsx` (grid template, track vars, header cells, row cells, skeleton); `packages/views/agents/components/agent-list-toolbar.tsx` (column show/hide toggle).-- AccessPicker + persistence: `packages/views/agents/components/inspector/access-picker.tsx` (props, `AccessChange`, inline scope derivation); `packages/views/agents/components/agent-detail-page.tsx` → `packages/core/api/client.ts` (`api.updateAgent`).-- Filter model: `packages/core/agents/stores/view-store.ts` (`AgentListFilters`, `EMPTY_AGENT_FILTERS`, `toggleFilter`); `packages/views/agents/components/agent-list-toolbar.tsx`; row-filter predicate in `agents-page.tsx`.-- Batch toolbar: `packages/views/agents/components/agents-page.tsx` (`AgentBatchToolbar`, `runBatch`, `allManageable`, archive-with-confirm template, `selectedIds`).-- Permission semantics: `server/internal/handler/agent_access.go` (`canInvokeAgent`); derivation comment in `packages/core/types/agent.ts`.-- List payload: `server/internal/handler/agent.go` (`ListAgents` attaches `invocation_targets`); `server/pkg/db/queries/agent.sql` (`ListAgents`).-- i18n: `packages/views/locales/{en,zh-Hans,ja,ko}/agents.json`; `apps/docs/content/docs/developers/conventions.zh.mdx`.-- Tests: `packages/views/agents/components/inspector/access-picker.test.tsx`; `packages/core/agents/stores/view-store.test.ts`; `packages/views/agents/components/agent-detail-page.test.tsx`.-- Learnings: `docs/solutions/ui-bugs/skill-autocomplete-cold-cache.md`; `docs/solutions/design-patterns/adaptive-skill-import-dialog.md`; `docs/solutions/workflow-issues/run-comment-view-run-button-rollout.md`.-- Originating ideation: `docs/ideation/2026-07-14-agent-list-visibility-field-ideation.html`.-------## Planning Contract--### Key Technical Decisions--- **KTD1 — Frontend pure function, no backend change.** Effective access is a pure helper over `permission_mode` + `invocation_targets`, both verified present in the list payload. The helper lives in `packages/core/agents/` and is shared by the column (U2) and filter (U3).-- **KTD2 — Three-state mapping mirrors the authoritative gate.** Owner-only = `private`; Workspace = `public_to` + a workspace target; Specific people = `public_to` without a workspace target. This matches `canInvokeAgent`.-- **KTD3 — Bulk reuses AccessPicker and persists via `api.updateAgent`, gated by ownership.** All three scopes are offered (R7 override). The bulk action calls `api.updateAgent(id, { permission_mode, invocation_targets })` per selected agent through `runBatch`, mirroring the archive/restore pattern; the existing invalidation of `workspaceKeys.agents(wsId)` refreshes the list. The action is gated by `isOwnedByMe` (not `canManage`), matching the backend's owner-only write gate for these fields — `canManage` admits workspace admins who would receive 403s and abort the sequential batch.-- **KTD4 — Column visible by default.** The key is added to `AgentColumnKey` but not to `AGENT_DEFAULT_HIDDEN_COLUMNS`; the show/hide toggle still works.-- **KTD5 — Derive in render, never mirror to Zustand.** The three-state value is a pure function of server fields; compute it with `useMemo` at the cell/predicate. The runtime may omit either field on legacy self-host backends or stale caches, so the helper fails safe to Owner-only when `permission_mode` is absent; a `public_to` agent with absent `invocation_targets` stays Specific people (per R2/KTD2).-- **KTD6 — AccessPicker reused via a thin wrapper.** A `<BulkAccessPicker>` wrapper renders `AccessPicker` with a new optional `hideFooter` prop that suppresses its internal Save button, so the bulk dialog's own confirm button is the sole apply trigger. Only the `hideFooter` opt-in prop is added to `AccessPicker`; the adjacent refactor (consolidating the picker's internal derivation into U1's helper) remains out of scope.--### Assumptions--- The list payload carries `permission_mode` and `invocation_targets` (verified).-- `AccessPicker` is rendered inside the bulk dialog via a `<BulkAccessPicker>` wrapper that adds a `hideFooter` prop (KTD6). The wrapper initializes the picker with no scope preselected and owns the confirm-disabled logic; `ownerId` is cosmetic for the Owner-only label and `members` is the workspace member list (uniform across selected agents).--### Sequencing--U1 (shared helper) lands first. U2 (column), U3 (filter), and U4 (bulk) all depend on U1 and can proceed in parallel after it. U2 and U3 both touch the toolbar and the row layer; coordinate those edits to avoid merge friction.-------## Implementation Units--### U1. Shared effective-access helper--- **Goal:** A pure, tested function deriving an agent's effective access scope (three states) from `permission_mode` + `invocation_targets`, shared by the column and the filter.-- **Requirements:** R1, R2.-- **Dependencies:** none.-- **Files:** `packages/core/agents/effective-access.ts` (new); `packages/core/agents/effective-access.test.ts` (new).-- **Approach:** Export `AccessScope = "workspace" | "specific-people" | "owner-only"` and `effectiveAccessScope(permissionMode, invocationTargets)`. Mapping: `private` → owner-only; `public_to` with a workspace target → workspace; `public_to` without a workspace target → specific-people. Fail safe to owner-only when `permission_mode` is absent; a `public_to` agent with absent `invocation_targets` stays specific-people (the runtime may omit either field on legacy backends or stale caches). Reference the inline derivation in `packages/views/agents/components/inspector/access-picker.tsx` for the same logic; do not modify that file (KTD6).-- **Patterns to follow:** Pure helpers in `packages/core/agents/` such as `visibility-label.ts`. Respect the `packages/core` boundary (no `react-dom`, no `localStorage`, no `process.env`).-- **Test scenarios:** `private` → owner-only; `public_to` + workspace target → workspace; `public_to` + member target only → specific-people; `public_to` + team target only → specific-people; `public_to` + no targets → specific-people; missing `permission_mode` → owner-only (defensive); `public_to` with missing targets → specific-people.-- **Verification:** Unit tests pass; the helper is pure with no side effects.--### U2. Effective-access column (visible by default)--- **Goal:** A new default-visible column showing the three-state effective access label, derived via U1.-- **Requirements:** R1, R3, R4. (R2 is realized by U1.)-- **Dependencies:** U1.-- **Files:** `packages/core/agents/stores/view-store.ts` (`AgentColumnKey`; do not add to `AGENT_DEFAULT_HIDDEN_COLUMNS`); `packages/views/agents/components/agents-page.tsx` (`COLUMN_WIDTHS`, track vars, grid template, header cell, `AccessCell`, skeleton cell); `packages/views/agents/components/agent-list-toolbar.tsx` (`COLUMN_KEYS`, `COLUMN_LABELS`); `packages/views/locales/{en,zh-Hans,ja,ko}/agents.json` (new `columns.access`; reuse existing `access.*` state labels).-- **Approach:** Add `"access"` to `AgentColumnKey` and leave it out of `AGENT_DEFAULT_HIDDEN_COLUMNS` so it shows by default. Place the column immediately after `owner` (access scope is conceptually about who can use the agent, adjacent to ownership): add the width entry, the `--agc-access` track var, and the grid track in that position. Add a header cell and an `AccessCell` that renders the localized label from `effectiveAccessScope(row.agent.permission_mode, row.agent.invocation_targets)` via `useMemo`. Add the matching skeleton cell and the toolbar toggle entries. Add `columns.access` in all four locales, keeping "agent" in English within zh-Hans. Horizontal density is handled by accepting scroll, not by hiding another column. Accessibility: the `AccessCell` exposes the localized text label (not icon-only) so screen readers announce the scope.-- **Patterns to follow:** Existing cells (`OwnerCell`, `RuntimeCell`); the column show/hide toggle in `agent-list-toolbar.tsx`.-- **Test scenarios:** Renders "Workspace" for a `public_to` + workspace agent; renders "Specific people" for a `public_to` + member agent (Covers AE1); renders "Owner-only" for a `private` agent (Covers AE2); renders a safe label when fields are absent; column is visible on a fresh load; toggling hides and shows the column; the cell text is reachable to assistive tech (not icon-only).-- **Verification:** Render the page with `@multica/core/api` mocked and a callable store (per the repo test rules); assert the label per agent shape; `pnpm typecheck`.--### U3. Access filter dimension--- **Goal:** A new `access` multi-select filter that isolates a class in one click, independent of column visibility.-- **Requirements:** R5.-- **Dependencies:** U1.-- **Files:** `packages/core/agents/stores/view-store.ts` (`AgentListFilters.access`, `EMPTY_AGENT_FILTERS.access`); `packages/views/agents/components/agent-list-toolbar.tsx` (new sub-menu; bump `countActiveFilterDimensions`); `packages/views/agents/components/agents-page.tsx` (row-filter predicate); locale filter-option labels.-- **Approach:** Add `access: string[]` to `AgentListFilters` with an empty default; `toggleFilter` and rehydration are generic and need no per-key change. Add a predicate: drop a row unless `filters.access` includes its `effectiveAccessScope(...)`. Mirror the `availability` sub-menu in the toolbar and increment the active-dimension counter. Filter values share the column's three labels. Accessibility: the access sub-menu reuses the `availability` sub-menu's keyboard navigation and ARIA semantics.-- **Patterns to follow:** The `availability` dimension end-to-end (declaration, sub-menu, predicate).-- **Test scenarios:** Filtering `access = owner-only` leaves only private agents (Covers AE4); the filter combines with another dimension; clearing it restores the full list; the store persists the filter under the workspace view key; the predicate uses the same helper as the column; the sub-menu matches the `availability` sub-menu's keyboard/ARIA behavior.-- **Verification:** `view-store.test.ts` direct-manipulation pattern; a page predicate test; `pnpm typecheck`.--### U4. Bulk "Set access scope" action with confirmation--- **Goal:** A batch-toolbar action that sets access scope across selected agents via the reused AccessPicker, with a confirmation dialog showing scope and count.-- **Requirements:** R6, R7, R8, R9.-- **Dependencies:** U1.-- **Files:** `packages/views/agents/components/agents-page.tsx` (`AgentBatchToolbar` action, dialog state; `runBatch` wiring); `packages/views/agents/components/bulk-set-access-dialog.tsx` (new, embeds `AccessPicker` via the `<BulkAccessPicker>` wrapper); `packages/views/agents/components/inspector/access-picker.tsx` (adds optional `hideFooter` prop — KTD6).-- **Approach:** Add a "Set access scope…" button to `AgentBatchToolbar`, enabled when at least one selected row is `isOwnedByMe` and not busy (gated by ownership, not `canManage` — see KTD3). Use a **single dialog**: a `<BulkAccessPicker>` wrapper renders `AccessPicker` with the new `hideFooter` prop (KTD6) so the picker's internal Save is suppressed and the dialog's own confirm button is the sole apply trigger. The dialog opens with **no scope preselected** and confirm disabled until the operator picks one; when "Specific people" is chosen, confirm stays disabled until ≥1 member target is selected. A live summary line shows "Applies to N agents" (the owned subset) and updates as the selection or scope changes; non-owned selected agents are skipped and their count is surfaced in the summary and the post-action toast. On confirm, map the picker's `AccessChange` to `api.updateAgent(id, { permission_mode, invocation_targets })` and call `runBatch(fn, ownedSelectedRows)`. `runBatch` already invalidates `workspaceKeys.agents(wsId)`. Accessibility: the dialog traps focus, restores focus on close, and the affected-count text is part of the dialog's accessible name.-- **Patterns to follow:** The archive action with confirm dialog in `agents-page.tsx`; the `runBatch` usage for restore.-- **Test scenarios:** Select three owned agents, choose Workspace, confirm shows "Applies to 3", applies `updateAgent` per id, list invalidates and reflects Workspace (Covers AE3, F1); mixed owned/non-owned selection → button enabled (any-owned), summary shows owned + skipped counts, only owned agents change (Covers AE3); dialog opens with no scope preselected and confirm disabled until one is picked; choose Specific people with no member selected → confirm disabled, with ≥1 member → enabled, same member set applies to all owned selected (Covers AE5, R7); choose Owner-only → applies `private` and clears targets; cancel applies nothing; busy/disabled states; an error mid-batch toasts and invalidates; the dialog traps and restores focus and exposes the affected count in its accessible name.-- **Verification:** Page-level test mocking `@multica/core/api` (`api.updateAgent` spy) with a callable store; assert per-id calls and query invalidation; `pnpm typecheck`.-------## Verification Contract--- `pnpm typecheck` — strict-mode types across `packages/core` and `packages/views`.-- `pnpm test` — Vitest: U1 helper unit tests; `view-store.test.ts` for the new filter and column; page-level tests for the column label, the filter predicate, and the bulk action (mock `@multica/core/api` and use the callable-store pattern per the repo test rules).-- `pnpm lint` — repo lint clean.-- Browser smoke (`pnpm dev:web`, per the repo UI rule): open the agents list and confirm the column shows the correct three states for real agents, the filter isolates each class, and the bulk dialog shows scope + count, applies, and refreshes the list.-- Accessibility: the column cell text is announced (not icon-only); the access filter sub-menu matches the `availability` sub-menu's keyboard/ARIA behavior; the bulk dialog traps and restores focus and exposes the affected count in its accessible name.-------## Definition of Done--- **Global:** All four units implemented; `pnpm typecheck`, `pnpm test`, and `pnpm lint` green; browser smoke confirms column, filter, and bulk on real agents; no backend changes; `AccessPicker` reused via wrapper with only an opt-in `hideFooter` prop added (KTD6); "agent" kept in English within zh-Hans; any abandoned experimental code removed.-- **Per unit:**- - U1: helper pure and unit-tested across all three states plus the defensive cases.- - U2: column visible by default (placed after `owner`) and renders the correct state per agent.- - U3: filter isolates each class, combines with other dimensions, and persists.- - U4: bulk applies all three scopes, shows the confirmation, skips non-owned agents (surfacing the skip count), and invalidates the list.diff --git a/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.md b/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.mddeleted file mode 100644index d3003923b0..0000000000--- a/docs/plans/2026-07-17-001-feat-issue-table-server-query-plan.md+++ /dev/null@@ -1,1167 +0,0 @@-----title: Issue Table Server Query and Grouping - Plan-type: feat-date: 2026-07-17-topic: issue-table-server-query-artifact_contract: ce-unified-plan/v1-artifact_readiness: implementation-ready-product_contract_source: product-and-code-audit-execution: code------# Issue Table Server Query and Grouping - Plan--> 本文定义 Table View 的目标产品语义、前后端边界和分阶段实施方案。核心目标不是提高当前的 `1000` 上限,而是移除“前端必须拥有完整结果集才能 Group/Hierarchy”的架构前提。--> **Implementation status (2026-07-22):** 新 Table 路径的 canonical compiler、U2–U3、U5–U7,以及 U8 的 exact facets / cache invalidation 已落地;标准字段和默认 position keyset 顺序所需 concurrent indexes 已加入。Rows 先裁 page,再只为当前页解析 hierarchy;默认 position 续页额外提供可下推的 cursor range bound,避免深页从 workspace 索引起点线性过滤。Assignee 显示名在 actor 聚合后解析;无自身 active filter 的标准 facets 在批量请求中用 `GROUPING SETS` 共享一次 base scan。Legacy GET handlers 尚未迁入同一 compiler。Table 采用 hard cutover,新旧客户端仍可分别使用 additive table endpoints 与 legacy endpoints,不维护两套前端 Table truth。当前显式导出由浏览器遍历同一 rows Query Spec,并在 schema fallback、fingerprint/cursor 漂移、重复行或最终数量不等于首屏 total 时 fail closed;非默认/自定义属性排序仍可能扫描并排序完整 membership,由 query timeout 限损;server-stream / async export job、observability、100k/1m staging SLO 与 browser network smoke 属于后续收口项。--## Goal Capsule--- **Objective:** 让 Table 的 Filter、Search、Sort、Group、Hierarchy、Count 和 Export 对任意规模的结果集都保持正确,不再因结果数量改变产品行为。-- **Product authority:** 本文的 Product Contract。实现不得以“已加载窗口”“浏览器内存上限”重新定义 Group、Hierarchy 或 Count 的语义。-- **Primary user outcome:** 用户选择 Group 后,无论查询命中 10、1,001 还是 100,000 个 issue,都能立即看到准确的 Group Header 和 Count,并按需加载组内行。-- **Execution profile:** Go backend + `packages/core` 查询层 + `packages/views` Table 渲染层的跨层改造;保留现有 flat/list/board API 作为兼容路径。-- **Rollout:** 当前 Web/Desktop Table hard cutover 到 additive server Table endpoints;API 错误不得静默 fallback 到前端分组。旧客户端继续使用未删除的 legacy endpoints。-- **Stop conditions:** U1–U8 完成;后端、core、views 测试通过;1001+ issue 场景浏览器验证通过;无自动全量物化;性能与一致性验收项达标。-- **Open blockers:** 无产品决策 blocker。自定义属性 Group 的 100k 数据性能必须在 rollout 前用 `EXPLAIN (ANALYZE, BUFFERS)` 验证,但不阻塞标准字段实现。-------## 1. Executive Decision--采用一套后端权威的 `IssueTableQuerySpec`,所有需要对完整结果集求真的能力都从该 Query Spec 派生:--- 后端负责 membership、search、sort、group membership、group count、hierarchy membership、facet count 和 aggregate;当前导出由前端遍历同一 server-authoritative rows query,后续可迁到 server-stream/job。-- 前端负责 view mode、columns、column width、collapsed groups、collapsed parents、selection、density 和虚拟滚动。-- Group Header 与 Rows 分开查询:Header 返回准确 Count;Rows 按展开且进入视口的 group/parent branch 使用 cursor 加载。-- Group membership 默认取 issue 自己的字段,不再根据“是否完整加载”改用根父项字段。-- Hierarchy 只嵌套“父子都命中当前 Query Spec 且 group key 相同”的关系;跨组或父项未命中的子项作为该组根行显示。-- 第一版不支持 `multi_select` Group;仍支持它作为 Filter 和 Column。-- 现有 `TABLE_STRUCTURE_MAX_WINDOW = 1000` 及其结构暂停逻辑在新路径稳定后删除,不改成更大的数字。--目标数据流:--```text-View state- ├─ Query state: scope/filter/search/sort/group/hierarchy- │ └─ POST /api/issues/table/groups → exact group headers/counts- │ └─ POST /api/issues/table/rows → cursor-paged root/child rows- │ └─ POST /api/issues/table/facets → exact filter facets- │ └─ export replays table/rows pages → same server membership, fail closed- └─ Presentation state: columns/collapse/selection/density- └─ frontend render + virtualization-```--目标职责矩阵:--| Capability | Target owner | Reason |-|---|---|---|-| Scope / Filter / Search | Backend | 决定完整 membership、total 和 export |-| Sort / stable pagination | Backend | 必须跨 pages 保持全局顺序 |-| Group membership / order / count | Backend | 必须对完整结果集求真 |-| Hierarchy membership / child count | Backend | 父项可能不在当前客户端 window |-| Facet count / aggregate | Backend | loaded rows 不能代表全集 |-| Export | Backend membership + frontend orchestration(当前) | 显式导出逐页读取同一 rows query;fingerprint/cursor/schema 漂移或最终数量不等于首屏 total 时拒绝生成部分 CSV。server stream/job 为后续优化 |-| View mode / columns / width / density | Frontend | 只改变呈现,不改变 membership |-| Group / parent collapse | Frontend | 个人交互状态,决定哪些 branch 需要请求 |-| Selection | Frontend | 当前交互 session 状态;membership 变化时清理 |-| Saved View persistence | Backend(follow-up) | 团队共享、权限、跨设备和 URL identity |-------## 2. Product Contract--### 2.1 Problem Frame--当前 Table 从 `GET /api/issues` 获取每页 100 条平铺数据。`tableGrouping` 和 `tableHierarchy` 不进入后端请求,而是在 `TableView` 中对已加载数组执行 `buildIssueTableRows`。--为了让分组和父子树“看起来完整”,Table 在结果不超过 1000 时自动拉完所有 offset pages;超过 1000 时又把 Group 和 Hierarchy 强制改成 `none/false`。因此同一个用户动作的产品语义会随结果数量变化:--- 999 条:Group 生效,但浏览器自动下载全部数据。-- 1001 条:相同 Group 选择不生效,只显示一条弱提示。-- Filter 缩窄到 1000 以下:Group 又自动恢复。-- Hierarchy 开启时,子 issue 在窗口未完成前按自己字段归组,完成后改按根父项字段归组,行会跳组。--这不是性能优化,而是查询责任放错层级后的行为不一致。--### 2.2 Non-negotiable Invariants--- **R1 — Result-size independence.** Group/Hierarchy 是否可用不得由结果数量决定。-- **R2 — One query, one membership.** Table rows、group counts、facet counts、selection membership、export 必须使用同一个 Query Spec。-- **R3 — Server-authoritative grouping.** Group membership 和 Count 必须由后端基于完整结果集计算;前端不得用 loaded rows 推断完整 Group。-- **R4 — Bounded client window.** 首屏和滚动只加载视口需要的 pages/branches;不得因 Group、Hierarchy、Count 或 working chip 自动下载完整结果集。-- **R5 — Stable semantics.** 同一 issue 的 group key 不得因分页加载进度变化。-- **R6 — Explicit unsupported state.** 不支持的字段必须从 UI capability 中移除,或返回明确错误;不得允许用户选中后静默 no-op。-- **R7 — Exact counts.** Group Header、Filter facet 和 Aggregate 标注为精确值时,必须来自后端完整查询集。-- **R8 — No silent fallback.** 新路径请求失败时显示错误与 Retry,不得回退到 loaded-row grouping。-- **R9 — Realtime correctness.** 会改变 membership、sort、group 或 hierarchy 的写入必须使相关查询失效并重新求真。-- **R10 — Shareable query shape.** Query Spec 必须可序列化,以便后续 Saved View、URL 和 Export 复用;不得绑定 React component state。--### 2.3 Query Semantics--#### Filter--- 空数组表示该维度不过滤。-- 同一维度内 OR,不同维度间 AND。-- `include_no_assignee` / `include_no_project` 与选中值做 OR。-- Custom property filter 维持现有语义:同定义内 OR,定义间 AND。-- `working_only` 由后端通过运行中 task membership 求值;新 Query Spec 不再要求浏览器发送全部 running issue IDs。-- `include_sub_issues=false` 是 Query membership,后端使用 `parent_issue_id IS NULL`。-- Search、Filter、Scope 共同决定唯一 membership 集合。--#### Sort--- V1 UI 保持单字段 Sort;API 使用单个 `{field, direction}` 对象。-- `position` 表示 manual order,canonicalization 固定为 ascending;客户端传入的 descending 不改变语义。-- 后端自动追加稳定 tie-break:`created_at DESC, id DESC`。-- Hierarchy 开启时,Sort 应用于每一层的 siblings,而不是把所有 descendants 做一次全局排序。-- Sparse date/property 值固定 `NULLS LAST`,升降序均一致。--#### Group--V1 支持:--- `none`-- `status`-- `assignee`-- `property:<id>`,仅 active `select` / `checkbox`--V1 不支持:--- `multi_select`:一个 issue 可能属于多个值,涉及重复行、unique total、batch selection 和 export 语义。-- `text` / `url` / `number` / `date`:高基数 group 暂不作为首发能力。-- archived/unknown property:返回 `unsupported_group_field`,前端清理 stale persisted value 并提示用户。--Group membership 使用 issue 自己的值:--- Status:`issue.status`。-- Assignee:`assignee_type + assignee_id`;NULL 进入 `unassigned`。-- Select:active option ID 正常成组;缺失值进入 `no-value`;引用已删除 option 的 stale value 进入单独的 `unavailable-value` group,不能和真正未填写合并。-- Checkbox:`false`、`true`、`no-value` 是三个不同 group。--只返回非空 group。Group order:--- Status:使用 `ALL_STATUSES` 的 canonical order。-- Assignee:按 display name case-insensitive 排序,再以 actor type/id tie-break;unassigned 最后。-- Select:按 definition config option order;`unavailable-value`、`no-value` 依次排在最后。-- Checkbox:false、true、no-value。--#### Hierarchy--Hierarchy 与 Group 同时存在时使用以下稳定规则:--1. 父 issue 和子 issue 都必须命中当前 Query Spec。-2. 两者 group key 必须相同。-3. 同时满足时,子 issue 可嵌套在父 issue 下。-4. 父项未命中、父项属于另一 group、或父项不存在时,子 issue 在自己的 group 中作为 root row 渲染。-5. 不自动注入未命中的 ancestor context row;这样 total、selection 和 export 都只包含真正命中的 issue。-6. 每个 row 返回当前查询下的 `direct_child_count`;子分支在展开/进入视口时按需加载。--该规则避免“Todo 子项因为父项是 Backlog 而出现在 Backlog group”这种 group label 与 row value 冲突,也避免当前实现按加载完整度改变规则。--#### Collapse and Selection--- `collapsedGroups`、`collapsedParents` 保留为前端/个人状态。-- 折叠 group 不请求 group rows。-- 折叠 parent 不请求 child rows。-- Selection 只包含真实 issue IDs,不包含 group headers 或 loading placeholders。-- Query membership 改变时清理 selection;仅 Sort 改变时保留 selection,延续现有规则。--### 2.4 Facet Count Semantics--Filter 菜单中的数量采用 disjunctive faceting:--- 计算某个维度的候选值时,保留 scope、search 和其他 filter dimensions。-- 暂时排除当前 dimension 自身,再分别计算各 candidate count。-- 已选值即使 count=0 仍返回,以便用户看到并移除。-- Response 中的 counts 按 contract 即为精确值,不另设 `exact` 标记;超时或不可用时整个维度显示 loading/unknown,不显示 loaded-row 近似值。--### 2.5 Toolbar Information Architecture--Desktop Table header 调整为第一层能力:--```text-Filter · Sort: Title ↑ · Group: Status · Columns · Table-```--- `Sort` trigger 只承载排序,不再用 “Title” 入口承载 Group/Hierarchy/Columns。-- `Group` trigger 始终展示当前字段;`None` 时可只显示 “Group”。-- `Columns` 和 `Hierarchy` 放入 Table Display 菜单。-- Mobile 可保留合并 Display popover,但 active Group 必须在 trigger/badge 中可见。-- 新请求加载时保留上一组 headers 作为 placeholder,并显示 refreshing 状态;不闪回 ungrouped table。--### 2.6 Acceptance Examples--- **AE1 — 1001+ issues.** Given 查询命中 1,001 个 issue,When Group=Status,Then 所有非空 status headers 与准确 counts 出现,网络不会自动请求 11 个 flat pages。-- **AE2 — Large assignee cardinality.** Given 10,000 个 issue、2,000 个 assignee groups,When 打开 Table,Then group headers 自身 cursor 分页;只为展开且进入视口的 groups 获取 rows。-- **AE3 — Group count parity.** Given Filter=Priority High,When Group=Assignee,Then group counts 之和等于 Query total,且 Export 使用相同 membership。-- **AE4 — Cross-group child.** Given parent.status=Todo、child.status=Done,且两者都命中,When Group=Status + Hierarchy on,Then child 作为 Done group 的 root row,不嵌套在 Todo parent 下。-- **AE5 — Missing parent.** Given child 命中而 parent 不命中,Then child 作为自己的 group root;total 不加入 parent。-- **AE6 — Same-group hierarchy.** Given parent/child 都是 Todo 且都命中,When 展开 parent,Then child 在 parent 下出现,child page 可继续 cursor 加载。-- **AE7 — Multi-select property.** Given property type is multi_select,Then Group menu 不显示它;Filter 和 Column 仍可用。-- **AE8 — Realtime regroup.** Given issue 从 Todo 改到 Done,Then loaded row 可立即 optimistic patch,随后 Todo/Done headers、counts 和 branches 失效并重新求真。-- **AE9 — Error behavior.** Given group rows 请求失败,Then 对应 branch 显示 Retry;Table 不显示 loaded-row derived group。-- **AE10 — Stale property.** Given persisted group references archived property,Then API 返回 structured unsupported error,前端切回 Group=None 并给出一次性说明。--### 2.7 Scope Boundaries--**本计划交付:**--- Canonical Table Query Spec。-- Server-backed group headers/counts。-- Cursor-paged root/child rows。-- Status、Assignee、Select、Checkbox Group。-- Hierarchy lazy branches。-- Exact filter facets。-- Query-consistent export(当前复用 rows cursor;server stream/job 后续实现)。-- Toolbar 信息架构调整。-- Realtime cache correctness。-- Hard-cutover compatibility、observability 和 rollout 验证。--**后续能力,接口预留但不在首发:**--- Multi-select Group。-- 多字段 Group / nested Group。-- 多字段 Sort。-- text/number/date 高基数 Group。-- Group aggregate footer 的 Sum/Average/Min/Max;V1 只完成 count 和现有 calculation state 清理。-- Saved View 服务端实体、权限和团队共享。-- Web URL 编码的临时 view overrides。-- Board/List/Swimlane 全部切到同一 Query API;本计划先保证 Table。-------## 3. Current-State Code Map--### 3.1 Frontend State and Controls--- `packages/core/issues/stores/view-store.ts`- - `tableGrouping`、`tableHierarchy`、collapsed groups/parents、columns 都在 Zustand。- - `viewStorePersistOptions` 把这些状态存入 workspace-aware local storage。- - `tableHierarchy` 默认 `true`,因此当前 Table 即使不 Group 也可能触发全量自动加载。-- `packages/views/issues/components/issues-header.tsx`- - Display trigger 显示当前 Sort label,却同时容纳 Group、Hierarchy、Sort、Sub-issues 和 Columns。- - `tableGroupableProperties` 当前包含 `select`、`multi_select`、`checkbox`。- - Filter option counts 来自 `scopedIssues`;Table 未完成分页时 `facetCountsExact=false`,因此隐藏 counts。-- `packages/views/issues/surface/use-issue-surface-controller.ts`- - 将 Filter/Search/Sort 编译成 `IssueFlatFilter + IssueSortParam`。- - 不读取 `tableGrouping` 作为查询参数,因此 Group 不进入 query key/API。- - Table Search 是本地 state + 250ms debounce。-- `packages/core/issues/stores/surface-view-store.ts`- - View 状态按 surface key 存在本地 registry,不可分享。--### 3.2 Table Data and Structure--- `packages/core/issues/queries.ts`- - `ISSUE_FLAT_PAGE_SIZE = 100`。- - `issueFlatListOptions` 使用 offset infinite query。- - `fetchAllFlatPages` 用于 Export,在浏览器循环到 total。- - `scope === "all"` 时前端分别拉 assigned/created/involved,再合并去重。-- `packages/views/issues/surface/use-issue-surface-data.ts`- - Table 使用 `useInfiniteQuery(issueSurfaceFlatOptions)`,再 flatten pages。- - 后端已经执行的 Filter 又在 loaded rows 上执行一次 `applyIssueFilters`。- - working chip 为了精确 scope 又维护第二个最多 1000 的 materialized window。-- `packages/views/issues/components/table-view-model.ts`- - `TABLE_STRUCTURE_MAX_WINDOW = 1000`。- - `buildIssueTableRows` 在浏览器执行 Group/Hierarchy。- - complete hierarchy 下,group key 来自根 ancestor;incomplete window 下来自 issue 自己。-- `packages/views/issues/components/table-view.tsx`- - Group/Hierarchy wanted 时连续 `fetchNextPage()`。- - total>1000 时把有效 Group/Hierarchy 强制关闭。- - Group count 使用 loaded `group.issues.length`。--### 3.3 Backend--- `server/internal/handler/issue.go::ListIssues`- - 支持 Table 的 status/priority/actor/project/label/property/date/search/top-level/ids filters。- - 执行 server sort、`LIMIT/OFFSET` 和独立 `COUNT(*)`。- - 每页 limit clamp 到 100。-- `server/internal/handler/issue.go::QueryIssues`- - 只是 `GET /api/issues` 的 POST twin,接收 string map,解决大量 IDs 的 request-line 限制。-- `server/internal/handler/issue.go::ListGroupedIssues`- - 后端分组雏形,只接受 `group_by=assignee`。- - 使用 `COUNT(*) OVER (PARTITION BY...)` 和 `ROW_NUMBER()`,offset/limit 对每组生效。- - 只服务 Board assignee grouping,Table 不调用。-- `server/internal/handler/property.go`- - 已有 property filter compiler 和 typed property sort expression。-- Existing indexes- - Workspace、status、assignee、parent、project、title trigram、properties GIN 已存在,但 assignee/parent 缺少 workspace-leading composite index。--### 3.4 Root Cause--`tableGrouping` 和 `tableHierarchy` 不属于服务器 query contract,导致:--1. 后端只能返回平铺 pages。-2. 前端要准确 Group/Tree 就必须拥有完整 membership。-3. 完整 membership 与无限数据规模冲突。-4. 1000 上限成为防止 unbounded download 的防护栏。-5. 防护栏又被呈现成产品限制。--因此修复点是 query contract,不是 Table render function,也不是把上限改大。-------## 4. Target Query Contract--### 4.1 Canonical Type--TypeScript 形态;Go 使用等价 tagged structs:--```ts-type IssueTableScope =- | { kind: "workspace"; assignee_types?: IssueAssigneeType[] }- | { kind: "project"; project_id: string }- | { kind: "assignee"; actor: IssueActorRef }- | { kind: "creator"; actor: IssueActorRef }- | {- kind: "my";- relation: "assigned" | "created" | "involved" | "any";- };--interface IssueTableFilters {- statuses?: IssueStatus[];- priorities?: IssuePriority[];- assignees?: IssueActorRef[];- include_no_assignee?: boolean;- creators?: IssueActorRef[];- project_ids?: string[];- include_no_project?: boolean;- label_ids?: string[];- properties?: Record<string, string[]>;- date?: {- field: "created_at" | "updated_at";- start: string;- end: string;- };- working_only?: boolean;- include_sub_issues?: boolean;-}--interface IssueTableQuerySpec {- scope: IssueTableScope;- filters: IssueTableFilters;- search?: string;- sort: {- field: SortField;- direction: "asc" | "desc";- };-}--type IssueTableGroupSpec =- | { kind: "none" }- | { kind: "status" }- | { kind: "assignee" }- | { kind: "property"; property_id: string };-```--设计约束:--- `workspace_id` 继续由现有 workspace resolution/middleware 决定,不信任 body 中的任意 workspace ID。-- `scope.kind="my"` 使用当前 authenticated user;body 不接受 user ID,防止查询其他用户的 personal relation scope。-- Query Spec canonicalize 后生成 SHA-256 fingerprint;cursor 携带 version + fingerprint。-- 所有 arrays 在 fingerprint 前排序/去重;语义顺序字段(如 status order)不直接使用客户端顺序。-- 空值规范化为字段缺失,避免等价 query 产生不同 cache key/fingerprint。--### 4.2 Endpoint: Group Headers--`POST /api/issues/table/groups`--Request:--```json-{- "query": {- "scope": { "kind": "workspace" },- "filters": { "statuses": ["todo", "in_progress"] },- "sort": { "field": "title", "direction": "asc" }- },- "group": { "kind": "status" },- "page": { "limit": 100, "cursor": null }-}-```--Response:--```json-{- "query_fingerprint": "sha256:...",- "total": 18342,- "groups": [- {- "key": "status:todo",- "value": { "kind": "status", "status": "todo" },- "count": 5210- }- ],- "next_cursor": null-}-```--Group value 是 tagged union:--```ts-type IssueTableGroupValue =- | { kind: "status"; status: IssueStatus }- | { kind: "assignee"; actor: IssueActorRef | null }- | {- kind: "property";- property_id: string;- value: string | boolean | null;- value_state: "value" | "unavailable" | "unset";- };-```--`value` 仅在 `value_state="value"` 时承载 active option/checkbox value;`unset` 与 `unavailable` 使用不同 stable group key,即使 response 中 value 为 null 也不会合并。--Notes:--- `total` 是 Query membership 的 unique issue 数量。-- Group counts 之和必须等于 `total`,因为 V1 每个 issue 只属于一个 group。-- Group headers 本身 cursor 分页,limit default/max 为 100。-- Group label 由前端根据 locale/catalog 渲染;后端可在 assignee group SQL 中按 display name 排序,但不把 localized label 当 identity。--### 4.3 Endpoint: Rows and Child Branches--`POST /api/issues/table/rows`--Request:--```json-{- "query": { "...": "same IssueTableQuerySpec" },- "group": { "kind": "status" },- "group_key": "status:todo",- "hierarchy": { "enabled": true },- "parent_id": null,- "page": { "limit": 50, "cursor": null }-}-```--- `parent_id=null + hierarchy=true`:返回该 group 的 root rows。-- `parent_id=<id> + hierarchy=true`:返回该 parent 的 direct matching/same-group children。-- `hierarchy=false`:`parent_id` 必须为空,返回 group 中的平铺 rows。-- `group.kind=none`:`group_key` 必须为空,同一 endpoint 支持 ungrouped Table。--Response:--```json-{- "query_fingerprint": "sha256:...",- "group_key": "status:todo",- "parent_id": null,- "total": 0,- "rows": [- {- "issue": { "id": "...", "title": "..." },- "direct_child_count": 3- }- ],- "branch_total": 1,- "next_cursor": "opaque-cursor"-}-```--`total` 只在 `group.kind=none`、`parent_id=null` 的首页返回整个 Query membership;续页、grouped branch 和 child branch 返回 `0`,grouped header 使用 groups response 的 `total`/`count`。`branch_total` 为兼容响应结构保留,值等于当前页 `rows.length`,不是权威 branch count;这两个约束避免 rows endpoint 为每个 branch/page 额外执行全量 COUNT。--### 4.4 Cursor Design--不继续扩展 offset pagination。Cursor 使用 base64url JSON envelope:--```json-{- "v": 1,- "query": "sha256:...",- "group_key": "status:todo",- "parent_id": null,- "sort_is_null": false,- "sort_value": "Example title",- "created_at": "2026-07-17T10:00:00Z",- "id": "uuid"-}-```--- Cursor fields 全部经过类型验证并只作为 bind args,绝不拼接用户值到 SQL。-- Cursor fingerprint 与当前 canonical Query Spec 不一致时返回 `409 cursor_query_mismatch`。-- 默认 `position ASC, created_at DESC, id DESC` 保留精确的混合方向谓词,同时增加语义冗余的 `position >= cursor.position` index bound,使 PostgreSQL 可直接 seek 到深页位置;不能改成普通 row-value 比较,因为 position 不保证唯一且 tie-break 方向相反。-- Cursor 不代表跨请求数据库 snapshot。每个响应是当次 transaction/read snapshot;实时写入通过 WS invalidation 触发 refetch。-- Keyset 可避免普通 insert 下 offset shift 的重复/遗漏;如果某行的 sort/group 值在翻页期间变化,它可能跨过 cursor,WS invalidation 是最终一致性的修复机制。-- Group header cursor 使用 group order rank/display sort key/stable group key,而不是 row sort cursor。--### 4.5 Endpoint: Facets--`POST /api/issues/table/facets`--Request 复用 Query Spec,并声明需要的 facets:--```json-{- "query": { "...": "IssueTableQuerySpec" },- "facets": [{ "kind": "status" }],- "include_total": false-}-```--Response 返回 query fingerprint、query total,以及每个 facet 的 kind、可选 property ID 和 `{key,count}` values。`include_total` 省略时默认为 `true`,保留原 endpoint contract;筛选选项不消费 query total,因此前端传 `false`,跳过额外 COUNT。--Table 初始渲染不请求 facets。用户打开某个标准字段或 custom property 的筛选子菜单时,只请求该维度;关闭筛选菜单后停用查询。这样一次正常交互最多执行当前维度的聚合,不会在每次 Table mount / realtime invalidation 时依次扫描全部标准字段和工作区 properties。--API 仍支持批量 `facets[]`。对于没有自身 active filter、因而与 base query 共享同一 membership 的 status / priority / assignee / creator / project 维度,server 使用一条 `GROUP BY GROUPING SETS` 查询,并可把 base total 作为空 grouping set 同批返回。存在自身 active filter 的维度必须使用“排除自身 filter”的独立 universe;label join 与 custom-property 展开也继续独立查询,避免改变 exact disjunctive facet 语义。--前端不再用 `scopedIssues` 计算 Table facet counts;Board/List 在统一 Query API 前可保留现有行为。--### 4.6 Endpoint: Export--V1 不新增独立 export endpoint。显式导出在浏览器中使用与 Table 相同的 Query Spec,逐页调用 `POST /api/issues/table/rows`:--- 导出固定使用 `group=none`、`hierarchy=false`,因此只输出 query membership 中的真实 issue 行,不受 viewport、collapsed state 或 loaded branches 影响。-- 每一页必须保持相同的非空 `query_fingerprint`,cursor 必须前进,issue ID 不得重复;结束时唯一 issue 数必须等于首屏 `total`(续页 `total=0`)。-- Response schema fallback、fingerprint 漂移、cursor loop、重复 issue 或最终数量不一致时 fail closed,不生成可能截断或混合 snapshot 的 CSV。-- CSV formula injection protection沿用 `escapeCsvCell`。-- Server-stream / async export job 是大规模导出的后续优化;迁移时仍须复用同一 Query Spec 和上述一致性语义。--### 4.7 Error Contract--```json-{- "error": "unsupported_group",- "code": "property_type_unsupported",- "message": "This property type cannot be used for grouping."-}-```--- `400`:shape、UUID、limit、date range、cursor envelope 等非法;body 使用现有 `{ "error": "..." }` contract。-- `409`:cursor 与 query/group/parent 不匹配。-- `422 unsupported_group`:unknown/archived/unsupported property 或 group kind;机器可读原因在顶层 `code`。-- `500/504`:受控 query failure/timeout,body 沿用 handler 的顶层 error contract。--前端对 branch 错误局部展示 Retry;group header 冷启动错误展示 Table-level Retry。-------## 5. Backend Design--### 5.1 Shared Filter Compiler--新建 `server/internal/handler/issue_query_filter.go`,抽出 canonical filter representation 和 SQL builder:--```go-type issueQueryFilter struct {- Scope issueTableScope- Statuses []string- Priorities []string- Assignees []issueActorFilter- IncludeNoAssignee bool- Creators []issueActorFilter- ProjectIDs []pgtype.UUID- IncludeNoProject bool- LabelIDs []pgtype.UUID- Properties [][]json.RawMessage- Date *issueDateFilter- Search string- WorkingOnly bool- IncludeSubIssues bool-}-```--Builder 返回:--```go-type issueQuerySQL struct {- Where string- Args []any-}-```--要求:--- 新 JSON decoder、legacy GET query decoder、现有 POST twin 都编译到同一 canonical struct。-- `ListIssues` 的 ordinary paged path 和 `ListGroupedIssues` 逐步改用同一 builder,避免新旧 endpoint filter drift。-- `open_only` 和 `scheduled` 的特殊路径不强行塞进 Table contract;保留现有分支。-- `my relation=any` 在 SQL 中做 assigned OR created OR involved,不再前端三次全量请求合并。-- `working_only` 使用 `EXISTS` 查询 running tasks;不得把 WS snapshot IDs 作为 canonical membership。-- 所有动态 column/expression 只能来自枚举或后端解析过的 active property definition。--### 5.2 Group Capability Resolver--新建 `server/internal/handler/issue_table_group.go`:--```go-type resolvedIssueGroup struct {- Kind string- PropertyID *pgtype.UUID- PropertyType string- GroupExpr string- GroupPredicate func(value issueGroupValue, addArg func(any) string) string- OrderExpr string-}-```--- Static kind 使用固定 SQL expression。-- Property kind 先通过 workspace-scoped catalog 查询确认 active/type。-- UUID 重新序列化后才允许嵌入 JSONB extraction expression;group value 始终 bind。-- Group key 是后端编码的稳定 identity,不直接当 SQL fragment。-- Stale select option 单独进入 stable stale/no-value bucket;不要丢行。--### 5.3 Group Header Query--逻辑 SQL:--```sql-WITH filtered AS (- SELECT i.*, <group_expr> AS group_value- FROM issue i- WHERE <canonical_where>-), grouped AS (- SELECT group_value, COUNT(*) AS issue_count- FROM filtered- GROUP BY group_value-)-SELECT group_value, issue_count-FROM grouped-WHERE <group_cursor_predicate>-ORDER BY <semantic_group_order>, <stable_group_key>-LIMIT $limit_plus_one;-```--`total` 可由 `SUM(issue_count) OVER ()` 返回,避免第二次 count。若 group cursor 后的 page 会使 window sum 只覆盖剩余行,则在 cursor 前的 grouped CTE 上计算 total,再外层分页。--Assignee display order 需要 workspace-scoped actor name projection。优先复用现有 member/agent/squad lookup;unassigned 明确排最后。--### 5.4 Row/Hierarchy Query--逻辑分两步:--1. `filtered_group`:完整 Query membership + requested group predicate。-2. `branch`:根据 hierarchy/parent 选择 roots 或 direct children。--Root 判定:--```sql-NOT EXISTS (- SELECT 1- FROM filtered_group parent- WHERE parent.id = child.parent_issue_id-)-```--因为 `filtered_group` 已经限定同 group,父项未命中或不同 group 时 child 自动成为 root。--Direct child branch:--```sql-child.parent_issue_id = $parent_id-AND EXISTS (- SELECT 1 FROM filtered_group parent- WHERE parent.id = $parent_id-)-```--`direct_child_count` 在当前 Query/group 下批量计算,不能 N+1:--```sql-LEFT JOIN (- SELECT parent_issue_id, COUNT(*) AS child_count- FROM filtered_group- GROUP BY parent_issue_id-) cc ON cc.parent_issue_id = row.id-```--Sort/keyset 在 branch 层执行。Hierarchy off 时直接对 `filtered_group` 做 keyset pagination。--### 5.5 Index Plan--先用 production-like 数据执行 EXPLAIN,再创建必要索引。预期至少需要:--```sql-CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_assignee- ON issue (workspace_id, assignee_type, assignee_id);-```--```sql-CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_workspace_parent- ON issue (workspace_id, parent_issue_id);-```--如果 `working_only EXISTS` 计划不能稳定使用现有 issue-id index,再增加:--```sql-CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_task_running_issue- ON agent_task_queue (issue_id)- WHERE status = 'running' AND issue_id IS NOT NULL;-```--仓库规则:每个 concurrent index 单独一个、只含单 statement 的 migration;不添加 FK/cascade。--Custom property Group 使用 `i.properties -> '<definition-id>'`。现有 `jsonb_path_ops` GIN 适合 containment Filter,但不能直接加速任意 key 的 GROUP BY。Rollout gate:--- 先验证 100k issue / 20 active properties 上 select/checkbox group p95。-- 若不能达到 SLO,不通过提高客户端上限解决;后续引入无 FK 的 normalized `issue_property_value` projection,并在 property mutation transaction 中双写。-- normalized projection 是性能 contingency,不作为首发前置,除非 EXPLAIN 明确证明必须。--### 5.6 Query Limits and Safety--- Group header limit default/max 100。-- Row/child limit default 50、max 100。-- Search 长度、property filter definitions/values 复用现有 bounds。-- Query context deadline 初始 5s;超时返回 structured `query_timeout`。-- Cursor decode 后限制 envelope 大小和 field lengths。-- 所有 scope 继续经过 `RequireWorkspaceMember`,并复用 `resolveWorkspaceID`。-- Query logs 记录 kind、group kind、hierarchy、limit、duration、returned count、timeout;不记录 search text、issue title 或 raw property values。-------## 6. Frontend Design--### 6.1 Core Types and API--修改:--- `packages/core/types/api.ts`- - `IssueTableQuerySpec`- - groups/rows/facets request/response tagged unions-- `packages/core/api/schemas.ts`- - 对所有新 response 使用 Zod schema;不要 raw cast。-- `packages/core/api/client.ts`- - `listIssueTableGroups`- - `listIssueTableRows`- - `getIssueTableFacets`- - export 复用 `listIssueTableRows`-- `packages/core/issues/queries.ts`- - 新 query key prefix:`issueKeys.tableQueryAll(wsId)`。- - group headers key 包含 canonical query + group。- - row branch key 包含 query + group + groupKey + hierarchy + parentId。--Query key 中不得放 cursor;React Query infinite page param 单独管理 cursor。--### 6.2 Surface Query Compilation--在 `packages/core/issues/surface/` 新建 pure compiler:--```ts-buildIssueTableQuerySpec(- scope: IssueSurfaceScope,- viewState: IssueViewState,- search: string,-): IssueTableQuerySpec-```--职责:--- 将 `IssueSurfaceQueryPlan` 转为 typed scope,而不是散落到 flat/grouped params。-- 将 date/property filters、showSubIssues、workingOnly 编译到同一 spec。-- `my/all` 编译为 `{kind:"my", relation:"any"}`,不再调用 `fetchAllMyFlatIssues`。-- Stale property filters 在 catalog settled 后移除,延续现有 cold-catalog guard。-- Canonicalize arrays,以稳定 React Query key 和后端 fingerprint。--### 6.3 Table Query Hooks--建议新建 `packages/views/issues/surface/use-issue-table-data.ts`,避免继续扩大 `use-issue-surface-data.ts`。--提供:--- `useIssueTableGroups(spec, group)`:group headers infinite query。-- `useIssueTableBranch(spec, group, groupKey, hierarchy, parentId)`:单 branch infinite query。-- `useIssueTableFacets(spec)`:按打开的 filter submenu 懒加载。-- export controller:使用 `group=none` / `hierarchy=false` 遍历 rows cursor,并执行完整性校验。--加载规则:--- Group=None:只加载 root/flat top branch。-- Group!=None:先加载 group headers。-- Collapsed group:不 mount branch query。-- Expanded group:仅当 header/loading placeholder 接近 viewport 时 enable root branch。-- Expanded parent:仅当 parent 可见且未 collapsed 时 enable child branch。-- 不存在任何“为了 count/structure 自动 while(hasNextPage) fetch”的 effect。--### 6.4 Render Model--替换当前 `buildIssueTableRows(issues)` 的全数组模型,改为由 server branches 组装 display rows:--```ts-type IssueTableDisplayRow =- | { kind: "group"; descriptor: IssueTableGroupDescriptor }- | { kind: "issue"; issue: Issue; depth: number; childCount: number }- | { kind: "branch-loading"; key: string; depth: number }- | { kind: "branch-error"; key: string; depth: number };-```--- Frontend只做 flatten 已加载 branch tree,不重新计算 group key/membership/count。-- Group count 始终取 descriptor.count。-- `depth` 由 branch parent 链计算,不依赖后端返回全树。-- DataTable 继续 virtualization;动态 branch 插入后由 virtualizer remeasure。-- Shift range selection 只覆盖当前可见且已加载 issue rows,行为在 UI copy/测试中明确。-- “Loaded X / Total” 改为 “Visible X · Total Y”;X 是当前已加载真实 issue 数,不暗示完整加载。--### 6.5 View State--保留前端:--- `viewMode`-- `tableColumns` / width / order-- `tableCollapsedGroups`-- `tableCollapsedParents`-- selection-- density(未来)--进入 Query Spec:--- filters-- search-- sort-- `tableGrouping`-- `tableHierarchy`-- showSubIssues--`tableCalculation` 当前没有生产消费者:本计划中从 persist state 和 dead helper 清理,或在 Aggregate 单独立项前保持 hidden 但不得展示不准确结果。--Web 后续通过 app-level NavigationAdapter 把 query state 编码到 URL;`packages/views` 不引入 `next/*`。--### 6.6 Cache and Realtime--新 query prefix:--```ts-issueKeys.tableQueryAll(wsId)-```--第一版采用 correctness-first invalidation:--- Issue create/delete:invalidate workspace table query prefix。-- Issue update:先 patch 所有 loaded row branches 中的 issue snapshot。-- 如果 changed dimensions 影响任何 query 的 filter/sort/group/hierarchy,invalidate 对应 table query keys。-- Assignee/status/property/parent/project/label/title/date 改动均可能改变至少一个 Table query;利用 query key 中的 spec 做 predicate,无法证明安全时失效。-- Group header counts 永远通过 refetch 修正,不在客户端猜 source/destination count delta。-- Mutation optimistic update 失败时 rollback row snapshots;现有 `cache-coordinator` 模式继续复用。--后续可优化为只 invalid source/destination group,但首发不以复杂 delta logic 换取少一次 refetch。--### 6.7 Deployment Strategy--本次不引入 frontend-public release flag,也不在同一客户端保留双 Table 数据路径:--- 新 Table endpoints 是 additive API;老 Web/Desktop 客户端继续使用 legacy endpoints。-- 新客户端的 Table membership/structure 始终使用新 API;API error 显示 Retry,不 fallback 到 loaded-row Group。-- 回滚以回滚 Web/Desktop build 为单位,后端 additive endpoints 和 indexes 可保留,不涉及数据回迁。-- Board/List 仍使用原有 API;它们不在本次 hard cutover 范围内。-------## 7. Implementation Units--### U1. Canonical Query Spec and Shared Filter Compiler--- **Goal:** 所有 Table endpoint 和 legacy list path 可复用同一 membership compiler。-- **Requirements:** R2、R5、R10。-- **Dependencies:** none。-- **Files:**- - `server/internal/handler/issue_query_filter.go`(new)- - `server/internal/handler/issue.go`- - `server/internal/handler/issue_table_filters_test.go`- - `server/internal/handler/issue_involves_test.go`-- **Approach:** 定义 Go Query Spec、canonicalization、scope/filter validation、where/args builder;把 ordinary `ListIssues` 和 `ListGroupedIssues` 的重复 filter fragments 接到 builder。保留 `open_only/scheduled` 特殊路径。-- **Critical test scenarios:** legacy GET 与新 canonical spec 在所有现有 Table filters 上返回相同 membership;my relation any 去重;workspace isolation;empty/no-value semantics;property/date/search parity。-- **Verification:** 现有 handler issue tests 全绿;新增 compiler table tests 覆盖每个 dimension。--### U2. Group Resolver and Group Headers API--- **Goal:** 后端返回准确、可分页的 group headers/counts。-- **Requirements:** R1、R3、R6、R7。-- **Dependencies:** U1。-- **Files:**- - `server/internal/handler/issue_table_group.go`(new)- - `server/internal/handler/issue_table_query.go`(new)- - `server/internal/handler/issue_table_query_test.go`(new)- - `server/cmd/server/router.go`- - `server/internal/featureflags/keys.go`-- **Approach:** 实现 status/assignee/select/checkbox resolver;group semantic order;group header keyset cursor;structured errors;flag gate。-- **Critical test scenarios:** 1,001 seeded issues;count sum=total;unassigned/no-value;select option order;checkbox false/true/null;archived/unknown/multi-select rejection;2-page group cursor 无重无漏。-- **Verification:** Go integration tests;EXPLAIN standard groups on 100k fixture。--### U3. Cursor-paged Rows and Lazy Hierarchy API--- **Goal:** 支持 ungrouped/grouped flat rows、root rows 和 direct child branches。-- **Requirements:** R1、R4、R5。-- **Dependencies:** U1、U2。-- **Files:**- - `server/internal/handler/issue_table_query.go`- - `server/internal/handler/issue_table_cursor.go`(new)- - `server/internal/handler/issue_table_query_test.go`-- **Approach:** 实现 typed cursor、query fingerprint、stable keyset、same-query same-group hierarchy、page row counts/direct child counts。-- **Critical test scenarios:** title/date/property/position asc+desc;NULLS LAST;created_at ties;cursor mismatch;same-group child;cross-group child;filtered-out parent;deep tree branch loading;parent moved between groups。-- **Verification:** 反复分页结果与一次性 SQL baseline ID set 相同;race/update scenario 通过 invalidation contract 测试。--### U4. Indexes and Performance Gate--- **Goal:** 标准字段 group/rows/hierarchy 达到 rollout SLO。-- **Requirements:** R4。-- **Dependencies:** U2、U3 query shape settled。-- **Files:**- - next available single-statement migrations for workspace-assignee/workspace-parent- - optional running-task partial index migration- - EXPLAIN notes appended to this plan or linked benchmark artifact-- **Approach:** production-like 100k/1m fixtures EXPLAIN;只为证明确有收益的 indexes 建 migration;每个 index 单文件 `CREATE INDEX CONCURRENTLY`。-- **Verification:** 无 sequential global scan;workspace predicate 生效;group header p95<500ms、rows p95<300ms 的 staging 指标目标。--### U5. Core API, Schemas, Query Keys and Surface Compiler--- **Goal:** 提供类型安全、可缓存的新 Table repository。-- **Requirements:** R2、R10。-- **Dependencies:** U2、U3 contract stable。-- **Files:**- - `packages/core/types/api.ts`- - `packages/core/api/schemas.ts`- - `packages/core/api/client.ts`- - `packages/core/issues/queries.ts`- - `packages/core/issues/surface/query-plan.ts`- - `packages/core/issues/surface/repository.ts`- - new compiler/tests under `packages/core/issues/surface/`-- **Approach:** typed union + Zod parse;canonical key builder;group/branch infinite query options;my any scope 不再走三次 full fetch。-- **Critical test scenarios:** schema defaults不得把 malformed group value 伪装成 empty success;query keys 隔离 group/parent/hierarchy;canonical array order;POST body exactness;response enum 向前兼容。-- **Verification:** core unit tests、API schema tests、typecheck。--### U6. Table Data Hook and Server-backed Renderer--- **Goal:** Table 不再物化完整 window,也不再前端求 Group/Hierarchy truth。-- **Requirements:** R1–R5、R8。-- **Dependencies:** U3、U5。-- **Files:**- - `packages/views/issues/surface/use-issue-table-data.ts`(new)- - `packages/views/issues/surface/use-issue-surface-controller.ts`- - `packages/views/issues/surface/use-issue-surface-data.ts`- - `packages/views/issues/surface/issue-surface.tsx`- - `packages/views/issues/components/table-view.tsx`- - `packages/views/issues/components/table-view-model.ts`- - related tests-- **Approach:** group headers + viewport-enabled branch hooks;display row flatten;per-branch error/loading;visible/total copy;保留 TanStack virtualization。-- **Removal:** 新路径删除 `TABLE_STRUCTURE_MAX_WINDOW`、`shouldAutoLoadNextWindowPage`、structure suspension copy/effects;不再对 Group/Hierarchy 调 `fetchNextFlatPage`。-- **Critical test scenarios:** total=1001 group 仍生效;collapsed group zero row requests;expand visible parent只发对应 branch;branch retry;selection忽略 placeholders;switch group保留 placeholder但不显示旧 group 为新 group。-- **Verification:** views tests、typecheck、browser network trace 无 auto-materialization。--### U7. Header Controls and Capability UX--- **Goal:** Group、Sort、Columns 的产品入口与实际能力一致。-- **Requirements:** R6 及 Toolbar contract。-- **Dependencies:** U5、U6。-- **Files:**- - `packages/views/issues/components/issues-header.tsx`- - `packages/core/issues/stores/view-store.ts`- - `packages/views/locales/{en,zh-Hans,ja,ko}/issues.json`- - header/surface tests-- **Approach:** desktop 拆分 Sort/Group/Columns;移除 multi-select group option;active group持续可见;stale property清理提示;修复 Filter trigger 内嵌不可键盘操作的 clear control。-- **Critical test scenarios:** group trigger label;keyboard navigation;mobile merged display;archived property fallback;all four locales;sort icon accessible label。-- **Verification:** component tests + browser keyboard/accessibility smoke。--### U8. Facets, Export, Realtime and Compatibility--- **Goal:** 所有 Table 衍生能力复用相同 Query Spec,并安全发布。-- **Requirements:** R2、R7–R10。-- **Dependencies:** U5、U6。-- **Files:**- - backend facets handler and tests- - `packages/core/issues/cache-coordinator.ts`- - `packages/core/issues/ws-updaters.ts`- - `packages/views/issues/surface/use-issue-table-data.ts`- - analytics/observability touchpoints-- **Approach:** exact disjunctive facets;rows-based fail-closed export;table query prefix invalidation;row optimistic patch;additive endpoint compatibility。-- **Critical test scenarios:** group/facet/export membership parity;export cursor/fingerprint/schema drift 与 final-total mismatch;create/delete/update invalidation;property edit regroup;offline/5xx retry;old desktop client继续使用旧 endpoints。-- **Verification:** core WS/cache tests、integration tests、staging rollout dashboards。--### Sequencing--```text-U1- └─ U2- ├─ U3- │ └─ U4- └─ U5- └─ U6- ├─ U7- └─ U8-```--U2/U3/U4 可由 backend owner 连续完成;U5 可在 API schema freeze 后与 U3 并行;U6 只有在 hierarchy contract 和 cursor tests 稳定后切换。-------## 8. Rollout and Compatibility--### 8.1 Compatibility--- 保留 `GET /api/issues`、`POST /api/issues/query`、`GET /api/issues/grouped`。-- 老 Web/Desktop 客户端继续使用旧 API,不受新 response 影响。-- 新前端的 Table 直接使用新 endpoints;Board/List 以及老客户端保持原有 API。-- 新 endpoint 不改变数据库 schema,除性能 indexes 外无数据 migration。--### 8.2 Validation Cohorts--1. Local/dev:功能与测试完成。-2. Internal workspace:收集 group/rows query duration、error、timeout、branch request fan-out。-3. 10% cloud workspaces:重点观察大 workspace、自定义 property group。-4. 100% cloud:发布新 Web/Desktop build。-5. 至少一个 desktop release 周期后,再评估 legacy endpoint 和旧 client grouping 的退休窗口。--### 8.3 Rollback--- 回滚 Web/Desktop build 即回到旧 Table 数据路径;旧 endpoints 全程保留。-- Rollback 不删除 index;concurrent indexes 可在后续独立 migration 决定是否移除。-- 新 Table API 的单次请求失败只显示 Retry,不按请求级别自动 fallback,避免同一 session 同时存在两套 Group truth。--### 8.4 Observability--Backend structured fields:--- endpoint: groups/rows/facets-- group_kind-- hierarchy-- scope_kind-- duration_ms-- db_rows_returned-- group_count/branch_count-- timeout/error_code-- cursor_present--Frontend events:--- table_group_changed-- table_group_headers_loaded/failed-- table_branch_loaded/failed-- table_export_started/completed/failed--不得记录 search text、issue title、raw property values、assignee display name。-------## 9. Test and Verification Matrix--### Backend Integration--- 每种 filter dimension 与 group 组合。-- `my relation=any` 的 assigned/created/involved OR + dedupe。-- status/assignee/select/checkbox group identity/order/count。-- 1001、10k、100k fixture 的 counts 和 pages。-- group header cursor、row cursor、child cursor。-- asc/desc/null/tie cases。-- hierarchy same-group/cross-group/missing-parent/deep tree。-- workspace isolation 与 actor/property stale input。-- malformed cursor、query mismatch、limit clamp、timeout。-- running_only membership。--### Core Unit--- Query Spec canonicalization。-- Scope compiler。-- Query key separation。-- Zod parse/fallback failure behavior。-- API request serialization。-- Cache invalidation predicate。-- WS create/update/delete handling。--### Views Unit--- Group header exact count display。-- No auto-fetch of all groups/pages。-- Collapse/expand query enablement。-- Branch flatten depth。-- Loading/error placeholders。-- Selection range over visible issue rows only。-- Group/Sort/Columns controls and keyboard semantics。-- Stale property fallback。-- Four locales。--### Browser Smoke--1. Seed/prepare a workspace with >1000 issues。-2. 打开 Network panel,进入 Table。-3. 切换 Group=Status、Assignee、Select、Checkbox。-4. 验证首屏只请求 headers 与可见 branches,不出现连续 offset page loop。-5. 折叠/展开 group 与 parent,验证 branch requests。-6. 修改 status/assignee/property,验证 row optimistic update 后 counts/refetch 正确。-7. Filter/Search/Sort 后验证 group totals 与 Export parity。-8. Keyboard 操作 Filter/Sort/Group/Columns/Table controls。--### Performance SLO--在 staging production-like Postgres 数据上:--- Standard group headers p95 < 500ms,p99 < 1s。-- Row/child page p95 < 300ms,p99 < 800ms。-- Table first interactive 不随 total 线性增长。-- 浏览器自动加载 issue rows 上限为当前可见 branch pages,不超过 2 pages/branch prefetch。-- Group header request memory 不随 issue count在应用层线性增长;聚合发生在数据库。-- Custom property group 若不达标,flag cohort 不扩大,触发 normalized projection contingency。--不要在 CI 以 wall-clock assertion 执行 SLO;CI 验证逻辑正确性,SLO 由可重复 benchmark/staging telemetry 验证。-------## 10. Risks and Mitigations--### Risk A — Shared filter compiler refactor causes legacy drift--- **Mitigation:** 先建立 legacy GET 与 canonical spec 的 golden parity tests,再逐段替换;保留特殊 open/scheduled 分支。--### Risk B — Dynamic property group scans large JSONB windows--- **Mitigation:** flag cohort、query deadline、EXPLAIN gate;必要时 normalized property-value projection,不回退客户端 materialization。--### Risk C — Hierarchy branch queries重复评估完整 filtered set--- **Mitigation:** workspace-leading parent index;用 CTE/derived query 让 planner复用;对可见 parent 才请求;观察 branch fan-out;必要时批量 children endpoint。--### Risk D — Realtime updates cause count flicker或跨 cursor遗漏--- **Mitigation:** optimistic patch只改善单元格即时性;任何 shape-changing field 都 invalidate server queries;不猜 count delta。--### Risk E — 高基数 Assignee groups 产生过多 HTTP requests--- **Mitigation:** headers cursor;collapsed/viewport enablement;首发监测 fan-out。若 p95 session fan-out过高,增加 batched branch request,而不改变 Query Spec。--### Risk F — Old persisted multi-select grouping--- **Mitigation:** catalog settled 后 capability validation;一次性降级为 none + toast;不要把 multi-select组合值继续发送到 API。--### Risk G — Feature flag造成双路径维护时间过长--- **Mitigation:** 在 rollout 中写明 retirement milestone;100% 后一个 desktop release 周期内删除旧 client structure path。-------## 11. Definition of Done--- [x] Result >1000 时 Group/Hierarchy 不暂停、不消失。-- [x] Group counts 来自后端完整 Query membership。-- [x] Group/row/child headers 和 rows 均使用 cursor pagination。-- [x] Table 不存在自动 materialize entire window 的 effect。-- [x] Multi-select property 不在 Group capability 中出现。-- [x] Filter、Search、Sort、Group、Hierarchy、Facet、Export 使用同一 Query Spec。-- [x] `my/all` 不再前端三次全量获取合并。-- [x] Working-only 不再通过浏览器发送全部 running IDs。-- [x] Cross-group hierarchy semantics 与本文一致并有 integration tests。-- [x] Realtime shape changes invalidate server group truth。-- [x] Toolbar 独立显示 Sort/Group/Columns/View,active Group 可见。-- [x] 新 API 有 structured errors、query deadlines 和 safe cursors。-- [x] 必要 indexes 以单 statement concurrent migrations 落地。-- [ ] Go、core、views tests 与 typecheck 通过。-- [ ] 1001+ issue browser smoke 和 network trace 通过。-- [ ] Staging SLO 和 custom-property EXPLAIN gate 通过。-- [ ] Rollout/rollback/flag retirement owner 明确。-------## 12. Primary Source Map--- Frontend view state: `packages/core/issues/stores/view-store.ts`-- Per-surface persistence: `packages/core/issues/stores/surface-view-store.ts`-- Query keys and flat pagination: `packages/core/issues/queries.ts`-- Surface repository: `packages/core/issues/surface/repository.ts`-- Surface query compilation: `packages/views/issues/surface/use-issue-surface-controller.ts`-- Surface data selection: `packages/views/issues/surface/use-issue-surface-data.ts`-- Table structure/render: `packages/views/issues/components/table-view-model.ts`, `table-view.tsx`-- Header controls/facet counts: `packages/views/issues/components/issues-header.tsx`-- API types/schemas/client: `packages/core/types/api.ts`, `packages/core/api/schemas.ts`, `packages/core/api/client.ts`-- Backend flat/grouped handlers: `server/internal/handler/issue.go`-- Property filter/sort compiler: `server/internal/handler/property.go`-- Routes: `server/cmd/server/router.go`-- Cache/realtime: `packages/core/issues/cache-coordinator.ts`, `packages/core/issues/ws-updaters.ts`-- Backend tests: `server/internal/handler/issue_table_filters_test.go`, `issue_grouped_test.go`, `issue_sort_test.go`, `issue_involves_test.go`-- Frontend tests: `packages/views/issues/components/table-view-model.test.ts`, `table-group-row.test.tsx`, `packages/views/issues/surface/use-issue-surface-controller.test.tsx`, `issue-surface.test.tsx`diff --git a/docs/product-overview.md b/docs/product-overview.mddeleted file mode 100644index 85b0def184..0000000000--- a/docs/product-overview.md+++ /dev/null@@ -1,983 +0,0 @@-# Multica 产品全景文档--> **文档说明**->-> 这份文档的目的是:**让任何没有写过代码的新同事,在 30 分钟内完全理解 Multica 这个产品到底有哪些功能、每个功能在整体中处于什么位置、一个功能和另一个功能如何协同**。->-> 它的受众包括:->-> - **新加入的工程师 / 产品 / 设计 / 运营**——用它做 onboarding 的第一份材料-> - **产品介绍工作**——需要对外讲解 Multica 时的事实基础-> - **文案工作者**——写交互文案、营销文案、帮助文档时,需要知道某个词(比如 "Skill"、"Runtime"、"Autopilot")在产品体系里代表什么-> - **任何需要在修改某个局部前,先理解它与整体关系的人**->-> 它**不是**:开发者文档、架构决策记录(ADR)、或者销售话术。它是**功能事实的汇总**——每一条描述都能在代码、schema 或 API 里找到对应。->-> 文档基于对整个 monorepo(server、apps、packages、migrations、daemon、CLI)的系统性调研生成,数据截止日期 2026-04-21。-------## 目录--1. [Multica 是什么](#1-multica-是什么)-2. [核心概念词典](#2-核心概念词典)-3. [功能全景(按模块)](#3-功能全景按模块)- - 3.1 [Workspace 工作区](#31-workspace-工作区)- - 3.2 [Issue 议题管理](#32-issue-议题管理)- - 3.3 [Project 项目](#33-project-项目)- - 3.4 [Agent 智能体](#34-agent-智能体)- - 3.5 [Runtime 运行时 & Daemon 守护进程](#35-runtime-运行时--daemon-守护进程)- - 3.6 [Skill 技能](#36-skill-技能)- - 3.7 [Autopilot 自动驾驶](#37-autopilot-自动驾驶)- - 3.8 [Chat 对话](#38-chat-对话)- - 3.9 [Inbox 收件箱与通知](#39-inbox-收件箱与通知)- - 3.10 [成员、邀请与权限](#310-成员邀请与权限)- - 3.11 [搜索与命令面板](#311-搜索与命令面板)- - 3.12 [认证、登录与 Onboarding](#312-认证登录与-onboarding)- - 3.13 [设置与个人资料](#313-设置与个人资料)- - 3.14 [CLI 命令行工具](#314-cli-命令行工具)-4. [系统架构全景](#4-系统架构全景)-5. [产品地图(全部路由)](#5-产品地图全部路由)-6. [跨平台差异:Web vs 桌面](#6-跨平台差异web-vs-桌面)-7. [附录:关键数据表速查](#7-附录关键数据表速查)-------## 1. Multica 是什么--### 一句话定位--**Multica 把编码智能体变成真正的团队成员。**--像给同事分配任务一样,把一个 issue 指派给一个 agent,它会自己认领、写代码、汇报进度、更新状态——不需要你一直守着。--### 解决的问题--传统方式用 AI coding agent 的痛点:--- 每次都要复制粘贴 prompt-- 必须盯着终端,看它跑不跑得完-- 没有跨任务的记忆,每次都从零开始-- 多个 agent 同时工作时,没有一个"看板"能看到全局--Multica 做的事:--- Agent 和人**共用同一个任务看板**(issue board)-- Agent **有 profile**,会出现在 assignee 下拉里、会在评论区发言、会自己创建 issue-- 同一个 (agent, issue) 的多轮对话**自动恢复会话**——上一次的上下文、工作目录都保留-- **Skill 系统**让历史上解决过的问题沉淀成可复用的能力-- **Autopilot** 让 agent 按定时规则自动开工(比如每天早上 9 点做 bug triage)--### 定位一句话版本--> Multica 不是一个 AI 工具,而是一个**人 + AI 协作的任务管理平台**。agent 是一等公民,和人在同一个工作流里。--### 部署形态--- **云版本(Multica Cloud)**:官方托管服务,agent 通过你本地跑的 daemon 执行-- **自托管(Self-Host)**:完整后端可以部署在自己的服务器-- **客户端**:Next.js web 版 + Electron 桌面版(两端体验基本一致,桌面独有:多标签、原生托盘、自动更新)--### 支持的 Coding Agent--Multica **不自己训模型**,也不锁定某一家厂商。它是调度器,本地 daemon 会自动探测以下 CLI 工具并接入:--Claude Code · Codex · OpenClaw · OpenCode · Hermes · Gemini · Pi · Cursor Agent · Kimi · Kiro CLI · Qoder CLI--每个 agent 可以配置自己的模型、API Key、环境变量、MCP 服务器。-------## 2. 核心概念词典--**理解这些名词是理解产品的前提。每个概念的定义都严格对应数据库表。**--| 概念 | 定义 | 映射的数据表 |-|------|------|-------------|-| **User 用户** | 一个人类账号,可以登录,属于多个 workspace | `user` |-| **Workspace 工作区** | 一切资源的容器。issue、agent、project、skill 全部隔离在 workspace 里。就是 Linear/Notion 里的 workspace/team 概念 | `workspace` |-| **Member 成员** | 用户在某个 workspace 里的身份。一个用户在不同 workspace 可以有不同角色(owner/admin/member) | `member` |-| **Agent 智能体** | 可被指派任务的 AI 工作者。有 profile(名字、头像、说明)、会指定 runtime 和 provider、可以配自定义 prompt 和技能 | `agent` |-| **Runtime 运行时** | Agent 实际跑在哪里的**执行环境**。可以是用户本地机器(通过 daemon)或云端实例。**一个 runtime = 一台可以跑 agent 的机器** | `agent_runtime` |-| **Daemon 守护进程** | 用户本地运行的后台程序,自动发现已安装的 coding CLI 并注册为 runtime,然后不停轮询 server 认领任务 | (进程,不是表) |-| **Issue 议题** | 一个工作单元——任务、bug、feature。最核心的产品对象。可以分配给人或 agent | `issue` |-| **Comment 评论** | Issue 下的讨论回复。人和 agent 都能发。在评论里 `@某个 agent` 会自动触发这个 agent 的新任务 | `comment` |-| **Task 任务** | Agent 执行一次 issue 所产生的一次运行。本质是"一次 agent 跑起来的会话"。队列化执行 | `agent_task_queue` |-| **Skill 技能** | 工作区级别的可复用说明文档。作用是给 agent 提供"怎么做某件事"的上下文。Agent 开跑时会把挂载的 skill 内容注入到工作目录让 CLI 能读到 | `skill`, `skill_file`, `agent_skill` |-| **Project 项目** | 议题的高层归属,类似"里程碑"或"版本"。issue 可以归属到 project | `project` |-| **Autopilot 自动驾驶** | 定时或被触发的自动化规则。按 cron 或 webhook 触发,自动创建 issue 并分配给 agent | `autopilot`, `autopilot_trigger`, `autopilot_run` |-| **Chat 对话** | 用户和 agent 的持久化多轮对话。不依附于 issue | `chat_session`, `chat_message` |-| **Inbox 收件箱** | 个人通知中心。被 @、被分配、订阅的 issue 有更新都会进这里 | `inbox_item` |-| **Subscriber 订阅者** | 谁关注某个 issue。被分配、被 @、评论过都会自动订阅。订阅者会收到 inbox 通知 | `issue_subscriber` |-| **Activity 活动 / Timeline 时间线** | 所有关键动作的审计记录。issue 详情页的"时间线"就是这个表的数据 | `activity_log` |-| **Pin 固定** | 个人侧边栏快捷方式,把常用的 issue/project 置顶 | `pinned_item` |-| **Reaction 反应** | Issue 或评论上的 emoji 反应,跟 GitHub/Slack 一样 | `issue_reaction`, `comment_reaction` |-| **Attachment 附件** | Issue 或评论的文件上传,支持 S3/CloudFront 或本地存储 | `attachment` |-| **Personal Access Token (PAT)** | 用户级 API token,CLI 和自动化用。`mul_` 前缀 | `personal_access_token` |-| **Daemon Token** | 单 workspace 单 daemon 的 token。`mdt_` 前缀,比 PAT 权限范围更小 | `daemon_token` |-| **Session Resumption 会话恢复** | 同一对 (agent, issue) 的下一次任务会自动复用上次 Claude Code 的 `session_id` 和工作目录——历史对话、文件状态都保留 | `agent_task_queue.session_id`, `.work_dir` |-| **MCP (Model Context Protocol)** | Anthropic 提出的协议,让 agent 通过标准接口调用外部工具。每个 agent 可配自己的 MCP server 列表 | `agent.mcp_config` (JSONB) |-| **Workspace Context 工作区上下文** | 工作区级别的 agent 系统提示词。所有该工作区的 agent 都会感知到它 | `workspace.context` |-| **Polymorphic Actor 多态行动者** | 设计范式:几乎所有"谁做了什么"的字段都是 `actor_type` (`member`/`agent`) + `actor_id`。这就是为什么 agent 能像人一样创建 issue、发评论、被订阅 | 贯穿所有表 |-------## 3. 功能全景(按模块)--### 3.1 Workspace 工作区--> **角色**:一切的容器。Multica 的多租户边界。--#### 功能--- **多工作区**:一个用户可以属于多个 workspace,每个 workspace 完全隔离(issue、agent、skill、成员都独立)。-- **创建工作区**:只需要一个名字;自动生成 slug(URL 中使用的短 ID)。-- **切换工作区**:侧边栏下拉;桌面端每个工作区有独立的标签组。-- **离开工作区**:非 owner 成员可自行离开。-- **删除工作区**:只有 owner 可以,硬删除+级联。-- **Workspace 设置**:名称、slug、描述、**Workspace Context**(给该工作区所有 agent 的统一系统提示)、**仓库列表**(workspace 允许 agent 访问的 Git 仓库 URL 白名单)。-- **Workspace 头像 / issue 前缀**:每个工作区可以有自己的 issue 编号前缀(如 `ACME-42`)。--#### 产品里的位置--Workspace 不是一个功能,而是**所有功能的坐标系**。URL 的形态永远是 `/{workspace-slug}/...`,API 请求永远带 `X-Workspace-Slug` 头。一个 issue、一个 agent、一个 skill,脱离了 workspace 就没有意义。--#### 对应表--`workspace`, `member`, `workspace_invitation`-------### 3.2 Issue 议题管理--> **角色**:Multica 的核心工作对象。--Issue 对应的概念在 Linear 叫 Issue、在 Jira 叫 Ticket、在 GitHub 叫 Issue——就是一个任务单元。Multica 的特色在于**issue 可以分配给 agent,和分配给人完全对等**。--#### 核心字段--- 标题、描述(Tiptap 富文本)、状态、优先级-- 编号(自动递增,带 workspace 前缀)-- **Assignee(可以是 member 或 agent)**-- **Creator(可以是 member 或 agent)**——agent 也能创建 issue-- Parent issue(用来做子任务)-- Project(归属的项目)-- Due date(截止日期)-- Labels(多对多标签)-- Dependencies(依赖/阻塞关系)-- Acceptance criteria(验收标准,JSONB)-- Origin(如果是 autopilot 创建的,会记录来源 autopilot run)--#### 视图--- **List 列表视图**:表格形式,可按 status/priority/assignee/creator/project 过滤、按名称/优先级/截止日/手动位置排序;支持开放和已完成分页。-- **Board 看板视图**:Kanban,按状态分列;支持拖拽(拖动会自动切到"手动排序"模式)。-- **My Issues 我的议题**:专属视图,三个 scope:分配给我 / 我创建的 / 我的 agent 负责的。--#### 交互--- **快速创建**:侧边栏单行快速创建、或弹窗富文本创建(支持草稿本地持久化)-- **批量操作**:多选后批量改 status/priority/assignee/删除-- **子 issue**:父 issue 显示子任务完成比例圆环-- **订阅(subscribe)**:默认 creator、assignee、被 @ 的人会自动订阅-- **Reaction**:issue 和评论都能加 emoji 反应-- **Pin 固定**:把 issue 置顶到侧边栏快捷栏-- **复制链接 / 快捷键跳转(Cmd+K)**-- **Timeline 时间线**:所有关键动作(状态变更、指派变更、评论)按时间顺序展示,混合 `activity_log` + `comment` 两类记录--#### 评论与讨论--- Tiptap 富文本编辑器,支持 `@` 提到 member 或 agent-- 嵌套回复(一层)-- emoji 反应-- **@agent 触发任务**:在评论里提到某个 agent,会自动生成一个新的 agent task,让它来回复/处理--#### 附件--- 拖拽上传或按钮上传-- 图片内联预览-- 存储后端:S3/CloudFront 或本地磁盘(自托管)--#### 产品里的位置--Issue 是**所有工作流的载体**:-- Agent 通过"被分配到 issue"获得任务-- Autopilot 通过"创建 issue"来触发 agent-- 评论通过"@agent" 追加任务-- Inbox 通知围绕 issue 生成--#### 对应表--`issue`, `comment`, `issue_label`, `issue_to_label`, `issue_dependency`, `issue_subscriber`, `issue_reaction`, `comment_reaction`, `attachment`, `activity_log`, `pinned_item`-------### 3.3 Project 项目--> **角色**:多个 issue 的高层容器,类似 Linear 的 Project、Jira 的 Epic。--#### 功能--- 标题、描述、图标(emoji 或标识符)-- 状态:`planned` / `in_progress` / `paused` / `completed` / `cancelled`-- 优先级:urgent / high / medium / low / none-- **Lead 负责人**:可以是 member 或 agent(跟 issue 的 assignee 一样是多态)-- 详情页展示项目内的所有 issue-- 支持搜索项目--#### 产品里的位置--Project 相比 Issue 是更高层的组织单元。一个 issue 可以不属于任何 project,但如果属于,会在列表页的筛选、侧边栏导航、面包屑里集中展示。--#### 对应表--`project`-------### 3.4 Agent 智能体--> **角色**:AI 工作者。Multica 最独特的对象。--一个 Agent 不是一个"AI 模型",而是一个**带配置的工作者身份**。它有名字、头像、个人描述、说明书(系统提示词)、绑定的运行时、挂载的技能。在 UI 上它和人一样会出现在 assignee 下拉、评论作者、订阅者列表里。--#### 配置字段--- **基本信息**:名字、描述、头像(自动生成)-- **Provider**:选择底层是 Claude / Codex / OpenClaw / OpenCode / Hermes / Gemini / Pi / Cursor / Kimi / Kiro / Qoder 中的哪一个-- **Runtime**:绑定到哪个运行时(即在哪台机器上跑)-- **Instructions 说明书**:agent 的系统提示词("你是一个资深工程师...")-- **Custom Env**:要注入到 CLI 进程的环境变量(如 `ANTHROPIC_API_KEY`、`ANTHROPIC_BASE_URL`、`CLAUDE_CODE_USE_BEDROCK`)-- **Custom Args**:附加给 CLI 的启动参数(如 `--model`, `--thinking`)-- **MCP Config**:Model Context Protocol 服务器列表(让 agent 有额外工具能力)-- **Max Concurrent Tasks**:同时最多跑几个任务-- **Skills**:关联多个 skill(见 3.6)-- **Visibility**:`workspace`(工作区可见)或 `private`(仅创建者可见)--#### 状态--- `idle` / `working` / `blocked` / `error` / `offline`——由 runtime heartbeat 决定-- 可以被 archive(软删除)--#### 交互--- 在 **Settings → Agents** 页面创建、编辑、归档-- 在 issue 的 assignee 下拉里选择-- 在评论里 `@agent` 触发-- 在 chat 面板里直接聊--#### 产品里的位置--Agent 是 Multica 的灵魂。几乎所有功能都围绕"如何让一个 agent 干活"展开:-- Issue 通过分配触发 agent-- Skill 通过挂载赋能 agent-- Runtime 提供 agent 的运行环境-- Autopilot 调度 agent 自动开工-- Chat 提供 agent 的对话界面--#### 对应表--`agent`, `agent_skill`-------### 3.5 Runtime 运行时 & Daemon 守护进程--> **角色**:Agent 真正跑起来的物理/虚拟机器。--这是 Multica **分布式执行架构**的核心设计:**agent 不在 server 上运行,而在用户自己的机器上运行**。Server 只做任务调度、状态同步、数据存储。--#### Daemon 是什么--`multica` CLI 在用户的机器上启动一个后台进程(macOS launchd / Linux systemd / Windows 服务风格),它:--1. **自动探测** `$PATH` 上安装的 coding CLI(`claude`, `codex`, `opencode`, `openclaw`, `hermes`, `pi`, `cursor-agent`, `kimi`, `kiro-cli`, `qodercli`, `qoderclicn`, `traecli`, `grok`)-2. 向 server **注册** 为一组 runtime(一个 CLI = 一个 runtime)-3. 每 3 秒 **轮询** 一次 server,有任务就认领-4. 每 15 秒 **心跳**(keepalive),报告自己还活着-5. 认领任务后,在本机的隔离工作目录里**启动 agent CLI**,把 agent 的输出流**实时推回 server**-6. 任务完成后上报结果、token 用量、session id 和工作目录(用于下次恢复)--#### Runtime 展示--在 **Settings → Runtimes** 页面可以看到:--- 每个 runtime 的名字、提供方(图标)、owner(谁的机器)、状态指示(在线/离线)、last seen 时间-- Ping 诊断:手动戳一下看响应-- Usage 用量:近期的 token 消耗统计-- Activity:任务活动情况-- CLI 安装指引(自托管模式下)-- 桌面端独有:**本地 daemon 卡片**,显示本机 daemon 状态、可一键重启--#### Runtime 的生命周期--- **注册**:daemon 启动时 POST `/api/daemon/register` 得到 runtime ID-- **在线**:15 秒一次心跳-- **离线**:如果 server 45 秒没收到心跳,把 runtime 标记为离线(server 后台 sweeper 每 30 秒巡检)-- **孤儿任务回收**:超过 5 分钟还在 dispatched 或超过 2.5 小时还在 running 的任务,sweeper 会把它标记为失败-- **长期离线 GC**:7 天没心跳且没活跃 agent 的 runtime 会被回收--#### CLI 与 Daemon 的关系--| 命令 | 说明 |-|------|------|-| `multica setup` | 一键配置:填 URL + 登录 + 启动 daemon |-| `multica login` | 浏览器打开 OAuth 登录,保存 90 天 PAT 到 `~/.multica/config.json` |-| `multica login --token <pat>` | 无头登录(SSH/CI) |-| `multica daemon start` | 后台启动 daemon(写 PID 到 `~/.multica/daemon.pid`,日志到 `~/.multica/daemon.log`) |-| `multica daemon stop` | 发 SIGTERM,优雅关闭(等待进行中的任务完成,超时 30s) |-| `multica daemon status` | 打印 daemon 状态、探测到的 agent、watch 中的 workspace |-| `multica daemon logs -f` | 实时跟随日志 |-| `multica daemon start --profile <name>` | 启动独立配置的 daemon(用于多环境,比如同时连 staging 和生产) |--#### 安全边界--- 每个任务一个**独立工作目录** `~/multica_workspaces/{ws}/{task_short_id}/workdir/`-- 环境变量**过滤**:阻止 agent 覆盖 daemon 的认证变量(`MULTICA_TOKEN` 等)-- 仓库访问**白名单**:agent 只能 checkout workspace 配置的仓库-- Codex 有**版本相关的 sandbox 策略**--#### 产品里的位置--Runtime 是让"给 agent 分配任务"这件事**能真正发生**的基础设施。没有 runtime,所有 agent 就是空壳。用户第一次 onboarding 时必须至少有一个 runtime 在线,否则 agent 没法干活。--#### 对应表--`agent_runtime`, `daemon_token`, `daemon_pairing_session`(弃用中), `daemon_connection`(弃用中), `runtime_usage`-------### 3.6 Skill 技能--> **角色**:让 agent "学会"某种工作方式的可复用说明文档。--Skill 是一组 Markdown 文档 + 配套文件。它**不是代码**,**不是 prompt 模板**,而是**给 agent CLI 读的说明**。--#### 数据形态--```-skill- ├─ name: "react-patterns"- ├─ description: "Common React patterns and best practices"- ├─ content: "## Overview\n..." # 主要说明文档- └─ files:- ├─ examples/hooks.md- └─ examples/useState.jsx-```--#### 它怎么工作--1. **创建**:在 **Settings → Skills** 页面创建或从 URL 导入(如 clawhub.ai、skills.sh)-2. **挂载**:给某个 agent 勾选要用的 skill-3. **注入**:当 agent 认领任务时,daemon 把挂载的 skill 内容写到任务工作目录的 **provider 原生位置**:- - Claude Code → `.claude/skills/{name}/SKILL.md`- - Codex → `CODEX_HOME/skills/{name}/`- - OpenCode → `.opencode/skills/{name}/SKILL.md`- - Pi → `.pi/skills/{name}/SKILL.md`- - Cursor → `.cursor/skills/{name}/SKILL.md`- - GitHub Copilot → `.github/skills/{name}/SKILL.md`- - 其他 → `.agent_context/skills/{name}/SKILL.md`-4. **使用**:agent CLI 自己按照 provider 约定发现并读取这些文件--> 💡 **Skill 是静态的**——不是 AI 生成的,也不会随执行变化。它是人写的经验文档。未来可能扩展成"AI 从历史任务中沉淀技能",但当前版本不是。--#### CLI 对应命令--```bash-multica skill list-multica skill get <id>-multica skill create --title ...-multica skill import --url https://...-multica skill files upsert <skill-id> --path ...-```--#### 产品里的位置--Skill 是 Multica 区别于"每次都要写长 prompt"的关键机制。它让团队的专业知识**沉淀成可复用的组件**,绑在 agent 上就生效——就像给员工写的 SOP/playbook。--从架构角度:skill 不参与执行逻辑,只参与**上下文注入**。它在整个任务生命周期里只出现一次——在 daemon 启动 CLI 之前的环境准备阶段。--#### 对应表--`skill`, `skill_file`, `agent_skill`-------### 3.7 Autopilot 自动驾驶--> **角色**:让 agent 在没人触发的时候也能自己开工的调度器。--Autopilot 解决的问题:很多工作是**周期性**的——每天早上的 bug triage、每周的依赖审计、每月的安全扫描。人手动触发太烦,Autopilot 是规则化自动触发。--#### 数据形态--```-autopilot- ├─ title, description- ├─ assignee: <agent_id> # 指定哪个 agent 跑- ├─ execution_mode: create_issue | run_only- ├─ issue_title_template: "Daily triage - {{date}}"- ├─ concurrency_policy: skip | queue | replace- └─ triggers (多个):- ├─ kind: schedule | webhook | api- ├─ cron_expression- ├─ timezone- └─ webhook_token-```--#### 两种执行模式--- **`create_issue`(默认)**:触发时先创建一个新 issue(标题用 `issue_title_template` 渲染),再把 issue 分配给 agent,走正常 agent 任务流程-- **`run_only`**:直接创建 task,不关联 issue(适合"只执行不留下 ticket"的场景,比如每小时检查某状态)--#### 三种触发方式--- **Schedule(cron)**:server 后台每 30 秒扫一次 `autopilot_trigger`,到点的触发出去-- **Webhook**:给出一个带 `webhook_token` 的 URL,外部 POST 即可触发-- **API / Manual**:UI 上点"立即运行"按钮,或用 CLI `multica autopilot trigger <id>`--#### 并发策略--- `skip`:同一个 autopilot 上一次还没跑完,跳过这次(去重)-- `queue`:排队等上一次跑完-- `replace`:中止上一次,换成这次--#### 运行记录--每次触发都在 `autopilot_run` 里留一条记录:`pending → issue_created → running → completed/failed/skipped`。在 UI 的 autopilot 详情页可以看全部历史。--#### 内置模板--产品提供一些现成的 autopilot 模板,一键创建:--- Daily news digest(每天 9:00)-- PR review reminder(工作日 10:00)-- Bug triage(工作日 9:00)-- Weekly progress report(每周 17:00)-- Dependency audit(每周 10:00)-- Security scan(每周 02:00)--#### 产品里的位置--Autopilot 让 Multica 从"你分配 → agent 做"升级到"agent 自己发起工作"。配合 `run_only` 模式,甚至可以在没有 issue 的前提下跑定时任务。Issue 上的 `origin_type=autopilot` + `origin_id` 字段留下了"这个 issue 是哪个 autopilot run 创建的"的追溯链。--#### 对应表--`autopilot`, `autopilot_trigger`, `autopilot_run`-------### 3.8 Chat 对话--> **角色**:用户和 agent 的持久多轮对话界面,不依附于 issue。--有时候你不想为了和 agent 说一句话就开一个 issue。Chat 就是为这种"轻量对话"准备的——像 ChatGPT 的对话界面,但是你在和你工作区的某个 agent 对话。--#### 功能--- **创建会话**:选一个 agent 开始-- **消息列表**:支持 Markdown 渲染、代码块高亮-- **发送消息**:消息会被 queue 成一个 task,agent 执行后把响应作为消息写回-- **流式响应**:通过 WebSocket 实时推送-- **未读跟踪**:`unread_since` 字段记录第一条未读消息的时间戳-- **归档**:把旧会话移出活跃列表-- **Session 复用**:同一个 chat session 下的多轮消息会复用底层 CLI 的 `session_id`(Claude Code 能保留对话上下文)--#### 和 Issue 评论的区别--| | Chat | Issue 评论 |-|---|---|---|-| 上下文载体 | 独立 session(chat_session) | 某个 issue |-| 是否公开 | 个人和 agent 对话(私有) | 工作区所有成员可见 |-| 触发 agent | 每条 user 消息都触发 | 需要 `@agent` |-| 用途 | 探索、提问、一次性任务 | 和 issue 强绑定的工作推进 |--#### 产品里的位置--Chat 填补了"不够正式到需要开 issue、但又需要持久化"的对话空白。同时也是体验上更像常规聊天软件的入口。--#### 对应表--`chat_session`, `chat_message`;底层执行仍走 `agent_task_queue`(`chat_session_id` 字段区分)-------### 3.9 Inbox 收件箱与通知--> **角色**:每个人的个人通知中心。--#### 数据形态--`inbox_item` 是推给特定"recipient"的条目:--- recipient_type = `member` 或 `agent`(agent 也能有 inbox!)-- type(e.g. `issue_assigned`, `comment_mention`, `task_completed`, `invitation_created`)-- severity(`action_required` / `attention` / `info`)-- 关联的 issue(如果有)-- read / archived 状态--#### 通知触发场景--- Issue 被分配给你-- 被 @ 提到-- 订阅的 issue 状态变化-- 订阅的 issue 有新评论-- 工作区邀请-- 你的 agent 任务完成/失败--#### 订阅机制(自动)--Server 的 subscriber listener 自动把以下人加入 `issue_subscriber`:--- issue creator-- 当前 assignee(变更会同步更新)-- 评论里被 @ 的人-- 手动订阅的人--#### UI--- **Inbox 页面**:两栏布局,左边列表 + 右边 issue 详情-- **批量操作**:全部标记已读 / 仅归档已读 / 归档已完成 issue 的通知-- **徽标**:侧边栏导航上显示未读数-- **WebSocket 推送**:新 inbox 条目实时到达(`inbox:new` 事件只发给目标用户)--#### 产品里的位置--Inbox 是"主动注意力系统",让用户不必一直盯着看板也知道哪些事要自己处理。--#### 对应表--`inbox_item`, `issue_subscriber`-------### 3.10 成员、邀请与权限--#### 角色体系--| 角色 | 权限 |-|------|------|-| **Owner** | 全部;唯一能删除工作区的角色 |-| **Admin** | 管理成员、管理设置;不能删工作区,不能移除其他 admin |-| **Member** | 创建 issue、评论、自我分配、使用 agent |--#### 邀请流程--- Admin 在 **Settings → Members** 输入邮箱邀请-- Server 生成 `workspace_invitation` 记录(7 天过期)-- 发送邮件(Resend 集成,未配置时打到 stderr)-- 被邀请人收到邀请:如果已有账号,会出现在个人 Inbox;如果没账号,邮件里有注册链接-- 接受 / 拒绝 / 过期--#### UI--- 成员列表:头像、邮箱、角色徽章、操作菜单(改角色、移除)-- 待处理邀请列表:可 resend、revoke-- Invite 接受页面(`/invite/[id]`):展示工作区信息、接受/拒绝按钮--#### 邀请接受的桌面特殊处理--桌面端的 `multica://invite/{id}` 深链接**不是走路由**,而是触发 `WindowOverlay`——共享视图组件 `InvitePage` 装在原生窗口覆盖层里,保证拖拽移动窗口等原生体验。--#### 产品里的位置--成员管理是**一切协作的前提**。但在 Multica 里它有一个独特之处:成员系统也管 agent。之所以要有 `assignee_type` 区分 member 和 agent,就是为了让两者在同一套 API 里表达"谁可以被分配"。--#### 对应表--`member`, `workspace_invitation`-------### 3.11 搜索与命令面板--#### 命令面板(Cmd+K)--全局搜索入口,覆盖:--- **Issues**(按标题、编号匹配)-- **Projects**(按名称匹配)-- **Workspaces**(按名称匹配,用于快速切换)-- **Navigation**(跳转到设置、runtimes、skills 等)-- **Actions**(新建 issue、新建 project、切换主题)-- **Recent Issues**(最近访问过的,自动记录)--#### 列表过滤--Issue 列表、project 列表、inbox 等都有本地 filter chips 和 search input。--#### 全文搜索--`GET /api/issues/search` 支持对 issue 的标题、描述、评论内容做全文搜索,返回命中片段。--> **当前没有基于向量的语义搜索**——产品宣传是 AI-native,但没有用 pgvector。Schema 里也没启用向量扩展。未来可能扩展。--#### 产品里的位置--Cmd+K 是 keyboard-first 用户(Linear-style)的主要导航方式,比点击侧边栏更快。-------### 3.12 认证、登录与 Onboarding--#### 登录方式--- **邮箱验证码(Magic Link 风格)**:输入邮箱 → 收 6 位验证码 → 输入验证码登录-- **Google OAuth**:一键 Google 登录-- **PAT(CLI)**:用户在 Settings → API Tokens 里生成的 token,CLI/脚本场景--#### Onboarding 流程(正在重设计中)--位于 `packages/views/onboarding/` 和 `apps/web/app/(auth)/onboarding/`。--经典 5 步:--1. **Welcome** — 欢迎页-2. **Workspace** — 创建工作区(或跳过,如果已有)-3. **Runtime** — 展示可用的 runtime 和 CLI 安装指引-4. **Agent** — 创建第一个 agent(需要有 runtime)-5. **Complete** — 展示创建好的 workspace 和 agent,跳转到 dashboard--#### 邀请接受(Zero-workspace)--如果新用户是被邀请进来的(还没有自己的 workspace),接受邀请后直接进入该工作区,跳过 onboarding。--#### 认证后的跳转规则--- 已登录且有至少一个 workspace:跳到 `/{slug}/issues`-- 已登录但没有 workspace:进入 `/workspaces/new` 或 onboarding-- 未登录:跳到 `/login`--#### Signup 限流--Server 支持:-- `ALLOW_SIGNUP=false` 关闭注册-- `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS` 白名单--#### 产品里的位置--Onboarding 是新用户能不能成功把 agent 跑起来的关键漏斗。任何一步没完成(尤其是 runtime 没连上),后续功能都是空壳。--#### 对应表--`user`, `verification_code`, `personal_access_token`-------### 3.13 设置与个人资料--#### My Account 标签--- **Profile**:名字、头像(不可上传,系统生成)、邮箱(只读)-- **Appearance**:主题(light / dark / system)-- **API Tokens**:创建/查看/撤销 PAT;创建时一次性展示完整 token-- **Daemon**(桌面独有):本机 daemon 状态、重启、开机自启开关-- **Updates**(桌面独有):当前版本、检查更新、自动更新开关--#### Workspace 标签--- **General**:名字、描述、**Workspace Context**(agent 系统级提示)-- **Members**:见 3.10-- **Repositories**:GitHub 集成,连接仓库列表,agent 白名单-- **Agents / Runtimes / Skills / Autopilots**:各自独立页面(实际上这些在侧边栏直接有入口,settings 里也有对应管理 tab)--#### 产品里的位置--Settings 是所有"配置即工作"动作的汇总:agent 的 prompt、workspace 的 context、仓库白名单、skill 的内容——都在这里。**对运营和文案来说最重要的一句话**:用户在 Multica 的 settings 页面做的配置,每一项都会影响 agent 实际执行时读到的上下文。-------### 3.14 CLI 命令行工具--`multica` 不只是启动 daemon 的工具,也是完整的命令行操作层。很多用户喜欢在终端里推进工作而不是开 UI。--#### 工作区 / 议题--```bash-multica workspace list | get | watch | unwatch-multica issue list | get | create | update | assign | status-multica issue comment list | add | delete-multica issue runs <id> # 查看任务执行历史-multica issue run-messages <task-id> # 查看某次执行的消息-```--#### Agent / Skill / Autopilot / Project / Repo--```bash-multica agent list | get | create | update | archive-multica skill list | get | create | update | delete | import | files upsert-multica autopilot list | get | create | update | trigger-multica autopilot trigger-add --cron "0 9 * * 1-5"-multica project list | get | create | update-multica repo list | add | update | delete-```--#### Runtime--```bash-multica runtime list | usage | activity | update-```--#### 配置 / 更新--```bash-multica config show | set server_url ...-multica auth status | logout-multica version | update-```--#### 产品里的位置--CLI 是 Multica 对开发者友好度的体现。对于 agent 自己来说,也同等重要——**agent 在执行任务时能调用 `multica` 命令读写 issue、评论、查文档**,这正是 CLI 在 "agent 作为一等公民"架构里的作用。-------## 4. 系统架构全景--```-┌─────────────────────┐ ┌────────────────────┐ ┌──────────────────┐-│ Next.js Web App │ │ Electron Desktop │ │ multica CLI │-│ apps/web │ │ apps/desktop │ │ server/cmd/ │-└──────────┬──────────┘ └──────────┬─────────┘ └────────┬─────────┘- │ HTTP + WebSocket │ │ HTTP- │ │ │- └──────────────┬────────────────┴───────────────┬───────────┘- │ │- ▼ ▼- ┌─────────────────────────────────────────────────┐- │ Go Backend (server/) │- │ • Chi HTTP router • gorilla/websocket hub │- │ • sqlc generated queries │- │ • In-process event bus │- │ • Background workers (sweeper / scheduler) │- └──────────────────┬──────────────────────────────┘- │- ▼- ┌──────────────────────┐- │ PostgreSQL 17 │- │ + pgcrypto │- │ (28 tables) │- └──────────────────────┘-- ▲- │ HTTPS poll + heartbeat- │- ┌─────────────────────────────────────────────────┐- │ Local Daemon (用户机器上运行) │- │ • 每 3s 认领任务 • 每 15s 心跳 │- │ • 探测并启动 agent CLI 子进程 │- │ • 为任务准备隔离工作目录 │- └───────────────┬─────────────────────────────────┘- │ spawns- ┌───────────────┼─────────────────────────────────┐- ▼ ▼ ▼ ▼- Claude Code Codex OpenCode …其他 CLI- (子进程) (子进程) (子进程)-```--### 分层职责--| 层 | 负责什么 | 不负责什么 |-|---|---|---|-| **Web / Desktop 客户端** | UI、本地客户端状态(Zustand)、服务器状态缓存(TanStack Query)、WebSocket 订阅 | 业务规则、AI 调用 |-| **Server** | 持久化、权限、任务编排、事件广播、Autopilot 调度、Runtime 健康监测 | 不直接执行 agent、不调 LLM |-| **Daemon** | 探测并启动本地 CLI、管理任务工作目录、流式上报消息、session 恢复 | 不做业务决策、只认 server 给它的任务 |-| **Agent CLI(Claude Code 等)** | 实际调用 LLM、执行工具调用、写文件、跑测试 | 不感知 Multica 的数据模型(所有上下文通过 `multica` CLI 命令读回) |--### 实时层(WebSocket)--Server 启动一个 WebSocket hub:--- **鉴权**:URL 参数里的 JWT 或 PAT + workspace_slug-- **房间模型**:按 workspace 分房间,一个 workspace 的事件只广播给该房间的连接-- **个人定向推送**:`inbox:new`, `invitation:created` 等个人事件用 `SendToUser`-- **心跳**:server 每 54 秒 ping,客户端 60 秒内必须 pong--**全部事件类型(供文案参考,共约 60+ 个)**:-- `issue:created` / `issue:updated` / `issue:deleted`-- `comment:created` / `comment:updated` / `comment:deleted` / `reaction:added` / `issue_reaction:added`-- `agent:created` / `agent:status` / `agent:archived`-- `task:dispatch` / `task:progress` / `task:message` / `task:completed` / `task:failed` / `task:cancelled`-- `inbox:new` / `inbox:read` / `inbox:archived` / `inbox:batch-*`-- `workspace:updated` / `workspace:deleted` / `member:added` / `member:updated` / `member:removed`-- `invitation:created` / `invitation:accepted` / `invitation:declined` / `invitation:revoked`-- `chat:message` / `chat:done` / `chat:session_read`-- `skill:created` / `skill:updated` / `skill:deleted`-- `project:created` / `project:updated` / `project:deleted`-- `autopilot:created` / `autopilot:updated` / `autopilot:run_start` / `autopilot:run_done`-- `subscriber:added` / `activity:created`-- `daemon:heartbeat` / `daemon:register`--客户端收到事件后的模式:要么直接 patch 本地缓存(issue / comment / task 这类需要即时更新的),要么触发对应 query 的失效重拉(less-critical 数据)。--### AI / LLM 在哪里--**Multica 本身不直接调 LLM API**。所有 LLM 调用都在 agent CLI 子进程里发生(Claude Code 调 Anthropic API、Codex 调 OpenAI API 等)。--Server 和 daemon 做的事情是:--1. 准备 prompt(见 `server/internal/daemon/prompt.go`)-2. 准备环境变量(agent.custom_env 注入)-3. 准备工作目录(注入 CLAUDE.md / AGENTS.md / skills / issue context)-4. 启动 CLI 子进程-5. 流式读 CLI 的 stdout,把消息分类并转发--**所以看不到大段的 prompt 工程代码**——prompt 只有几个模板(task prompt、chat prompt、comment-triggered prompt),核心内容是 agent instructions + issue context + skill files,真正的 LLM 对话由 CLI 自己管理。--### 后台任务--Server 启动三个 goroutine:--1. **Runtime Sweeper**(每 30s):标记离线 runtime、回收孤儿任务、GC 长期离线 runtime-2. **Autopilot Scheduler**(每 30s):扫 cron 触发器,到点就 dispatch-3. **DB Stats Logger**:周期性打印 pgxpool 连接池状态-------## 5. 产品地图(全部路由)--### 公共 / 认证--- `/` — 首页-- `/login` — 登录-- `/auth/callback` — OAuth 回调-- `/workspaces/new` — 创建工作区-- `/invite/[id]` — 接受邀请-- `/onboarding` — 首次引导--### 工作区内(`/{slug}/...`)--- `/issues` — Issue 列表(board / list 视图)-- `/issues/[id]` — Issue 详情-- `/my-issues` — 我的 issue(三 scope)-- `/projects` — 项目列表-- `/projects/[id]` — 项目详情-- `/autopilots` — Autopilot 列表-- `/autopilots/[id]` — Autopilot 详情-- `/agents` — Agent 列表-- `/runtimes` — Runtime 列表-- `/skills` — Skill 库-- `/inbox` — 收件箱-- `/settings` — 设置(包含多个 tab:profile / appearance / tokens / workspace / members / repos / daemon / updates)--### 桌面端特有(不是路由,是 WindowOverlay)--- **Create workspace overlay**-- **Invite accept overlay**(来自 `multica://invite/{id}` 深链接)-- **Onboarding overlay**(首次或零工作区时)-------## 6. 跨平台差异:Web vs 桌面--### 共享(绝大部分功能)--所有业务页面(issues / projects / autopilots / agents / runtimes / skills / inbox / settings / chat / login / onboarding)的实际 UI 都在 `packages/views/` 里,web 和桌面共用同一套组件。--### Web 特有--- 地址栏 + 浏览器前进后退-- 服务端渲染(SSR)-- `/login` 的 OAuth 回调处理 localhost 端口(方便 CLI 登录)--### 桌面特有--- **多标签**:每个 workspace 独立标签组,可以拖拽重排-- **WindowOverlay**:邀请接受、创建工作区、onboarding 不走路由,而是原生窗口层-- **Daemon 集成**:设置里能直接重启本机 daemon、看状态-- **本地 daemon runtime 卡片**:在 Runtimes 页面自动显示本机 daemon-- **自动更新**:`Settings → Updates` 检查/下载/安装新版本-- **Immersive mode**:全屏模式,隐藏侧边栏-- **深链接**:`multica://auth/callback?token=...` 和 `multica://invite/{id}`-- **拖动区**:macOS 的红绿灯 + 顶部 48px 拖拽条(`h-12`)用来移动窗口-- **Workspace 单例守护**:`setCurrentWorkspace()` 管理当前活跃工作区的全局身份--### 为什么两端要做差异--Web 有 URL 栏——错误状态(比如"你没有访问这个 workspace 的权限")作为一个可分享的 URL 页面是有意义的。桌面没有 URL 栏——同样的状态只会把用户困住,所以桌面选择**静默自愈**:把失效的 tab 从 store 里移除即可。这个差异直接影响多个细节:--- Web 有 `NoAccessPage`,桌面没有-- Web 有 `/workspaces/new` 页面,桌面把它做成 overlay-- Web 的 deep link 直接路由,桌面的深链接转 WindowOverlay-------## 7. 附录:关键数据表速查--共 **28 张表**,覆盖 10 个产品域。以下按域列出最重要的字段,供文案/产品查询"某个功能背后到底存了什么"。--### 身份 / 认证--- `user` — 基础账号(id, email, name, avatar_url)-- `verification_code` — 邮箱验证码(code, expires_at, attempts)-- `personal_access_token` — 用户 API token(token_hash, token_prefix, revoked)--### 工作区 / 成员--- `workspace` — 容器(name, slug, description, context, settings, repos, issue_prefix, issue_counter)-- `member` — 成员身份(role: owner/admin/member)-- `workspace_invitation` — 邀请(invitee_email, status: pending/accepted/declined/expired)--### Agent / Runtime / Skill--- `agent` — Agent 主表(instructions, custom_env, custom_args, mcp_config, runtime_mode, visibility, status)-- `agent_runtime` — 运行时(daemon_id, provider, status: online/offline, last_seen_at)-- `agent_skill` — agent 挂载 skill 的 n-n 关联-- `skill` — 技能主文档(name, description, content)-- `skill_file` — 技能附带文件(path, content)-- `daemon_token` — 守护进程级 token-- `daemon_connection` / `daemon_pairing_session` — 早期设计(弃用中)--### Issue / 协作--- `issue` — 议题(status, priority, assignee_type+assignee_id, creator_type+creator_id, parent_issue_id, project_id, origin_type, origin_id, acceptance_criteria, due_date, position)-- `issue_label` / `issue_to_label` — 标签-- `issue_dependency` — 依赖关系(blocks / blocked_by / related)-- `issue_subscriber` — 订阅者(reason: creator/assignee/commenter/mentioned/manual)-- `issue_reaction` / `comment_reaction` — emoji 反应-- `comment` — 评论(type: comment/status_change/progress_update/system, parent_id for threading)-- `attachment` — 附件--### 任务执行--- `agent_task_queue` — 任务主表(status: queued/dispatched/running/completed/failed/cancelled, context, result, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id)-- `task_message` — 每次执行的消息流水(seq, type, tool, input, output)-- `task_usage` — Token 用量(input/output/cache_read/cache_write tokens)--### 对话--- `chat_session` — 聊天会话(unread_since, session_id, work_dir)-- `chat_message` — 消息(role: user/assistant)--### 项目与组织--- `project` — 项目(status, priority, lead_type+lead_id, icon)-- `pinned_item` — 侧边栏置顶(item_type, item_id, position)--### 自动化--- `autopilot` — 规则(assignee_id, execution_mode: create_issue/run_only, issue_title_template, concurrency_policy)-- `autopilot_trigger` — 触发器(kind: schedule/webhook/api, cron_expression, timezone, next_run_at, webhook_token)-- `autopilot_run` — 执行记录(status: pending/issue_created/running/skipped/completed/failed)--### 通知与审计--- `inbox_item` — 收件箱条目(recipient_type, type, severity, read, archived)-- `activity_log` — 审计日志(actor_type: member/agent/system, action, details)-- `runtime_usage` — 运行时按日聚合 token 用量(给计费/容量规划用)-------## 尾声--Multica 的设计可以归结为一句话:**把"人在一个看板上协作"这件事,扩展到了"人 + AI agent 在同一个看板上协作"**。--所有功能都是围绕这个核心展开:-- 为了让 agent 能像人一样被分配任务 → polymorphic actor(`assignee_type`)-- 为了让 agent 能自己开工 → Autopilot-- 为了让 agent 的工作方式能沉淀复用 → Skill-- 为了让 agent 执行在用户控制的环境里 → Runtime + Daemon-- 为了让人不被通知淹没 → Inbox + 自动订阅-- 为了让一次会话有连续性 → Session Resumption--当你读到某段文案、某个 UI 模块、某张表时,请把它放回这个"人 + AI 协作"的坐标系里去理解它的位置。diff --git a/docs/timezone-architecture-rfc.md b/docs/timezone-architecture-rfc.mddeleted file mode 100644index 544cfc9904..0000000000--- a/docs/timezone-architecture-rfc.md+++ /dev/null@@ -1,374 +0,0 @@-# Timezone 架构重构 — Scheduling / Viewing 两层模型--> Status: Implemented-> Last updated: 2026-05-20--## TL;DR--- **问题**:当前代码里 timezone 被三种语义混用,导致 workspace usage 页 picker 在 #2822 review 中被移除(前后端 tz 不一致会把跨 UTC 午夜的行算到错的 calendar week),同时 runtime detail 页的 timezone editor 又承担了"既是物理 tz 又是报表 tz"的双重职责。-- **方案**:把 timezone 收敛成两个独立的 product 概念——**Scheduling**(trigger 规则里写的"9 点"是哪个 9 点,由 `autopilot_trigger.timezone` 承载)和 **Viewing**(用户报表 tz,由新字段 `user.timezone` 承载)。原先混在 `runtime.timezone` 上的"物理位置"语义(Operational)经盘查无真实消费者,整列移除。-- **数据层**:把 `task_usage_daily` (per-runtime, 物化在 runtime tz) 和 `task_usage_dashboard_daily` (workspace 级, 物化在 UTC) **合并成一张 `task_usage_hourly` (UTC, hourly grain)**,所有报表查询按调用方 tz 在查询时切日界。-- **新增字段**:`user.timezone`(默认 = browser detected,可在 Preferences 覆盖)。-- **不引入** `workspace.timezone`——viewing tz 是查看者属性,不是 workspace 属性。-- **性能**:hourly rollup 在密集工况(16 active hours/day)下单 ws 90d 窗口 ~15k 行、~15ms,和现有 daily rollup 同档。-- **副产品**:Migration 082 的"改 runtime tz → 重灌整张 rollup"逻辑可以删除;跨 region 团队自动支持各看各的"今天";未来要做 hourly heatmap / 时段分析无需再动 schema。-------## 1. 背景--### 1.1 现状盘点--代码里"timezone"出现在四个地方:--| # | 位置 | 字段 | 实际语义 |-|---|---|---|---|-| 1 | `agent_runtime.timezone` | TEXT, daemon 探测或 UI 覆盖 | 报表 + 物理位置(混淆) |-| 2 | `autopilot_trigger.timezone` | TEXT, 用户写规则时选 | Scheduling(正确) |-| 3 | Workspace Usage 页面 | 无字段,曾在前端用 `useState(browserTimezone())` | Viewing(被 #2822 删除) |-| 4 | 各种 list / log 时间戳显示 | 浏览器 tz | Viewing(隐式) |--### 1.2 问题--**问题 A — Runtime tz 同时承担两个不同的角色:**--`runtime.timezone` 在 migration 082 之后决定了 `task_usage_daily.bucket_date` 的物化口径,等于"报表 tz";同时 daemon 启动时 `detectLocalTimezone()` 写入这个字段,又当成"机器物理 tz"用。结果:--- 改这个字段会触发整张 rollup 重新物化(migration 082 backfill 逻辑),代价不小。-- 一个 SF 的 dev 把 daemon 跑在 PST 的机器上,但 PM 在上海希望按 CST 出报表——这一个字段没法同时满足两个需求。-- daemon 自动探测的"客观真值"和用户手动想换的"我想看的报表 tz"被同一个 PATCH 接口覆盖,互相打架。--**问题 B — Workspace usage 页面没有正确的"报表 tz"概念:**--PR #2822 删除了 workspace usage 页的 TimezonePicker,原因是:--> 后端 dashboard rollup 把数据按 UTC `bucket_date` 聚合,但前端却驱动 Weekly 边界用用户在 picker 里选的 tz。靠近 UTC 午夜的行会被放进错的 calendar week。Lock workspace Weekly to UTC and remove the timezone picker。--这个修复是对的——前后端 tz 不一致就是 bug。但它**没解决根本问题**:用户确实需要按自己的 tz 看 workspace 报表,只是当前数据层没法支持。--**问题 C — Viewing tz 没有持久化:**--即使 picker 还在,它也只是 `useState(browserTimezone())`——刷新页面、换设备、跨 session 都会丢。用户每次都得手动切。--**问题 D — 没有"跨 region 团队"的支持位:**--把"报表 tz"放在 workspace 上是常见的诱惑,但 workspace 里两个成员一个在 SF 一个在 Beijing,他们想看到的"今天"本来就不同。任何"workspace 级 tz 设置"都强制其中一个人看错位的报表。--### 1.3 目标--1. **架构上清晰**:每个 timezone 字段只回答一个问题。-2. **性能上不退步**:所有现有报表查询保持 <15ms 量级。-3. **正确性优先**:前后端 tz 物化口径必须一致,没有"前端切了但后端没跟"的 UI 谎言。-4. **跨 region 友好**:同一 workspace 不同成员可以各看各的"今天"。-------## 2. 两个 timezone 概念--| 概念 | 在回答什么 | 谁是真值 | 承载字段 |-|---|---|---|---|-| **Scheduling** | "9 点跑"的 9 点是哪个 9 点 | 用户写规则那一刻的意图 | `autopilot_trigger.timezone` |-| **Viewing** | 我想看的"今天"是哪个日历日 | 当前查看者的偏好 | `user.timezone`(新增) |--**关键论断**:之前代码把"物理位置"和"报表口径"混在 `runtime.timezone` 一个字段上。重构后:--- Scheduling 不动,`autopilot_trigger.timezone` 已经正确。-- Viewing 由新字段 `user.timezone` 承载。-- 数据层不再按任何固定 tz 物化 bucket,而是以 UTC 为唯一存储口径,所有报表查询在 read time 按调用方传入的 tz 切日界。-- `runtime.timezone` 整列删除——见 §2.1。--### 2.1 为什么不要 Operational 层--最初设计有第三个概念 **Operational**(机器物理在哪)。落地盘查后砍掉,两条理由:--**理由一 —— 就算需要 operational tz,`runtime` 也是错的层级。** Operational tz 是**物理机器**的属性,不是 runtime 的属性。同一台机器可以跑多个 runtime,它们共用同一个 OS 时钟,operational tz 必然相同。把 tz 放在 `agent_runtime` 上,等于把一个 machine 级事实复制到同机每一行 runtime——天然的冗余与 drift 风险(同机两个 runtime 的 tz 被改得不一致是无意义的非法状态)。要建模 operational tz,正确归属是 machine 层;而当前 schema 里根本没有 machine 实体,强行放 runtime 层只是把错误固化。--**理由二 —— 它的消费者都不需要 operational 语义。** `runtime.timezone` 今天承担"既是物理 tz 又是报表 tz"的双重职责,但盘查后没有一个读取者真正要"机器物理 tz":--- runtime detail 页的 Daily / Weekly 趋势图、KPI 卡片,通过 `task_usage_daily` 的物化口径间接吃这个 tz——这是**报表口径**语义,不是 operational。而且这些成本/token 数字要和 workspace dashboard 跨页对账,dashboard 下挂多 runtime、多时区,根本不存在"workspace 的 operational tz",可对账量只能统一走 Viewing tz。-- hour-of-day heatmap(`GetRuntimeUsageByHour` / `GetRuntimeTaskActivity`)看似要"机器作息"属性,但若只让它一个图表走 operational,用户在同一张卡里切 "Daily" ↔ "Heatmap" 会看到同一个"昨天"两个数。它也只能跟 Viewing tz。--autopilot 调度走 `trigger.timezone` 不碰它,daemon 要时钟直接读 OS clock,`TimezoneEditor` 只是编辑它自己。换句话说,凡是真读它的地方都应当是 Viewing tz——operational 语义在整个系统里没有一个真实需求点。--结论:Operational 作为服务端持久化、用户可编辑的字段没有立足点。机器有物理时钟这个**事实**永远存在,但那是 daemon 进程内部的事,不必上 server。`runtime.timezone` 整列由 migration 104 删除。--代价已知且接受:跨 region 团队看一台 SF runtime 的 hour-of-day heatmap 时,按查看者自己的 tz(如 Asia/Shanghai)显示活跃时段,而非机器本地的 9-to-5。对单 region 团队零影响。-------## 3. 字段定义与 UI 文案--### 3.1 `runtime.timezone` — 已移除--由 migration `104_drop_runtime_timezone` 删除整列。daemon 注册不再上报 host tz(`detectLocalTimezone()` 删除),`PATCH /api/runtimes/:id` 不再接受 `timezone`(只剩 `visibility`),Runtime Detail 页的 timezone editor 删除。理由见 §2.1。--### 3.2 `autopilot_trigger.timezone` — 不动--已经正确。--### 3.3 `user.timezone` — 新增 Viewing 字段--实现见 migration `100_user_timezone`。表名是 `"user"`(单数、保留字需加引号):--```sql-ALTER TABLE "user"- ADD COLUMN timezone TEXT NULL;--COMMENT ON COLUMN "user".timezone IS- 'User-preferred IANA timezone for report rendering (Viewing tz). '- 'NULL means "use the browser-detected tz at render time". Affects '- 'dashboards, charts, and any "today" label shown to this user. Does '- 'not affect data materialisation — all rollups remain in UTC.';-```--`NULL` 是默认值——前端在 NULL 时 fallback 到 `browserTimezone()`。这样新用户零配置就有合理行为。--UI:-- **Settings → Preferences → Timezone**:dropdown,可选 `(browser)` 或具体 IANA name。-- Hint:`"Used for dashboards, charts, and any 'today' label shown to you. Other users in your workspaces will see their own timezone."`--### 3.4 不引入 `workspace.timezone`--理由见 §1.2 问题 D。如果未来真有"workspace 默认报表 tz"的需求(例如新成员加入时给一个建议默认值),可以在那时再加,与本 RFC 兼容——`user.timezone` 可作为 `workspace.timezone` 的 override。--### 3.5 Viewing tz 如何到达后端--报表 handler 通过 `Handler.resolveViewingTZ(r)` 解析当前请求该用哪个 tz 渲染,优先级:--1. `?tz=` query param —— 浏览器端 `useViewingTimezone()` 解析后随每个报表请求显式带上。-2. 已认证用户的 `user.timezone`(query param 缺失时的 cold fallback,会多查一次 `GetUser`)。-3. `"UTC"` —— 兜底。--非法 IANA 名直接跳过该级、不报错(tz 是显示问题)。浏览器走 (1) 显式 query param 这条热路径,旧客户端 / API client 漏传时由 (2) 服务端读 `user.timezone` 兜底。Handler 拿到 tz 后用 `parseSinceParamInTZ` 把 `days=N` 折算成"查看者本地第 N 天零点"对应的 UTC 瞬间,再连同 `@tz` 一起传给 SQL。-------## 4. 数据层设计--### 4.1 新表 `task_usage_hourly`--实现见 migration `101_task_usage_hourly_schema`(建表):--```sql-CREATE TABLE task_usage_hourly (- bucket_hour TIMESTAMPTZ NOT NULL, -- UTC, truncated to hour boundary- workspace_id UUID NOT NULL,- runtime_id UUID NOT NULL,- agent_id UUID NOT NULL,- project_id UUID, -- nullable- provider TEXT NOT NULL,- model TEXT NOT NULL,- input_tokens BIGINT NOT NULL DEFAULT 0,- output_tokens BIGINT NOT NULL DEFAULT 0,- cache_read_tokens BIGINT NOT NULL DEFAULT 0,- cache_write_tokens BIGINT NOT NULL DEFAULT 0,- task_count BIGINT NOT NULL DEFAULT 0, -- COUNT(DISTINCT task_id)- event_count BIGINT NOT NULL DEFAULT 0, -- COUNT(*) of task_usage rows- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),- CONSTRAINT uq_task_usage_hourly_key- UNIQUE NULLS NOT DISTINCT- (bucket_hour, workspace_id, runtime_id, agent_id, project_id, provider, model)-);--CREATE INDEX idx_task_usage_hourly_workspace_time- ON task_usage_hourly (workspace_id, bucket_hour DESC);-CREATE INDEX idx_task_usage_hourly_runtime_time- ON task_usage_hourly (runtime_id, bucket_hour DESC);-CREATE INDEX idx_task_usage_hourly_workspace_agent_time- ON task_usage_hourly (workspace_id, agent_id, bucket_hour DESC);-CREATE INDEX idx_task_usage_hourly_workspace_project_time- ON task_usage_hourly (workspace_id, project_id, bucket_hour DESC)- WHERE project_id IS NOT NULL;-```--**关于字段的几个落地决定**:--- **没有 `cost_micros` 列**。成本不在数据层物化——`task_usage_hourly` 只存 token 计数,PK 里带 `provider`+`model`,客户端按 per-model 定价表算成本。这样定价表更新无需重灌 rollup。-- **`task_count` 与 `event_count` 两个计数**:`task_count` 是 `COUNT(DISTINCT task_id)`,`event_count` 是 `COUNT(*)`(同一 task 多次 usage 事件)。注意 task 跨多个 hour bucket 时 `task_count` 会按小时重复计——面向用户的"任务数"列优先用 `agent_task_queue` 派生的查询(见 §4.2),hourly 表的 `task_count` 仅作信息参考。-- **`runtime_id` 为 `NOT NULL`**:`agent_task_queue.runtime_id` 本身带 `NOT NULL` 约束(migration 004),所有建队列的写入路径(含 quick-create)都会带上 runtime,所以 rollup 永远不会产生 no-runtime 的 bucket。`project_id` 可空是因为任务确实可以不挂 project。--migration 101 同时建了两张配套表:--- `task_usage_hourly_rollup_state` —— 单行 watermark 状态表(与 073/084 的 rollup_state 同形)。-- `task_usage_hourly_dirty` —— 失效队列,承载 `updated_at` watermark 看不到的失效(`task_usage` 的 DELETE、级联 DELETE、`issue.project_id` / `agent_task_queue.runtime_id` 改动导致的重新归属)。**必须配 TTL**,见 §4.4。--**这一张表替换两张现有表**:-- `task_usage_daily` (migration 073, 082) — 含 runtime_id,物化在 runtime tz-- `task_usage_dashboard_daily` (migration 084) — 含 agent_id/project_id,物化在 UTC--合并后 PK 同时包含 runtime / agent / project 三个维度,可以从同一张表派生出所有现有视图。--### 4.2 查询模式--Token 类报表查询从 `task_usage_hourly` 派生,按调用方传入的 `@tz` 在查询时折算日界。**成本不在 SQL 里算**——查询只 `SUM` token 列并保留 `model` 维度,成本由客户端按 per-model 定价表折算(所以按日期分组的查询会保留 `model`,按 agent 分组的也是)。--```sql--- Workspace dashboard 趋势图 ListDashboardUsageDaily(按 viewer tz 切日,保留 model)-SELECT DATE(bucket_hour AT TIME ZONE @tz::text) AS date,- model,- SUM(input_tokens)::bigint AS input_tokens,- SUM(output_tokens)::bigint AS output_tokens,- SUM(cache_read_tokens)::bigint AS cache_read_tokens,- SUM(cache_write_tokens)::bigint AS cache_write_tokens,- SUM(task_count)::int AS task_count-FROM task_usage_hourly-WHERE workspace_id = $1- AND bucket_hour >= @since::timestamptz- AND (@project_id::uuid IS NULL OR project_id = @project_id)-GROUP BY DATE(bucket_hour AT TIME ZONE @tz::text), model-ORDER BY DATE(bucket_hour AT TIME ZONE @tz::text) DESC, model;---- Runtime detail 趋势图 ListRuntimeUsage(按 viewer tz 切日,tz 来自 user 不是 runtime)-SELECT DATE(bucket_hour AT TIME ZONE @tz::text) AS date,- provider, model,- SUM(input_tokens)::bigint AS input_tokens,- ...-FROM task_usage_hourly-WHERE runtime_id = $1- AND bucket_hour >= @since::timestamptz-GROUP BY DATE(bucket_hour AT TIME ZONE @tz::text), provider, model-ORDER BY DATE(bucket_hour AT TIME ZONE @tz::text) DESC, provider, model;---- Per-agent 视图 ListDashboardUsageByAgent / ListRuntimeUsageByAgent--- 不按日期分组 → 不需要 @tz,只用 @since 截断(@since 已是 viewer tz 折算后的 UTC 瞬间)。-SELECT agent_id, model,- SUM(input_tokens)::bigint AS input_tokens,- ...-FROM task_usage_hourly-WHERE workspace_id = $1- AND bucket_hour >= @since::timestamptz-GROUP BY agent_id, model-ORDER BY agent_id, model;-```--**两类查询不走 `task_usage_hourly`**:--- **Time / Tasks 指标**(dashboard 的"时长 / 任务数"标签页)由独立查询 `ListDashboardRunTimeDaily` / `ListDashboardAgentRunTime` 直接打 `agent_task_queue`,按 `completed_at AT TIME ZONE @tz` 切日——任务时长来自队列的 `started_at`/`completed_at`,不是 token rollup 能表达的。它们同样吃 `@tz`,保证 Tokens/Cost/Time/Tasks 四个标签页的日界一致。-- **Runtime hour-of-day Heatmap**(`GetRuntimeUsageByHour` / `GetRuntimeTaskActivity`)仍直接扫原始 `task_usage` / `agent_task_queue`,按 **viewer tz**(`resolveViewingTZ` 解析出的 `@tz`)做 `EXTRACT(HOUR FROM ... AT TIME ZONE @tz)`。Heatmap 窗口小(单 runtime、近 30/90d),raw 扫描足够快,没有必要从 hourly 表派生。--### 4.3 性能预估--单 workspace 90d 窗口的 `task_usage_hourly` 行数:--| 工况 | 行数估算 | 趋势图查询代价 |-|---|---|---|-| 小(5 agent × 2 model × 2 active hour × 90d) | ~1.8k | <5ms |-| 中(5 agent × 2 model × 8 active hour × 90d) | ~7.2k | <10ms |-| 大(5 agent × 2 model × 16 active hour × 90d) | ~14.4k | ~15ms |-| 巨大(20 agent × 5 model × 16 active hour × 90d) | ~144k | ~50ms |--和现有 daily rollup 在同一档。Leaderboard / per-agent / per-project 视图同样指标。--### 4.4 Rollup worker 改造--现有两张 rollup 表的写入逻辑合并成一条管线,实现见 migration `102_task_usage_hourly_pipeline`(触发器 + 窗口函数 + 失效队列 TTL + pg_cron 调度):--- 源数据扫描不变(仍然扫 `task_usage` 增量 + 失效队列)。`bucket_hour` 用 `task_usage_hour_bucket(tu.created_at)`(UTC 整点截断)。-- Upsert 目标从两张 daily 表改为一张 `task_usage_hourly`。-- 失效队列维度由 `(bucket_date, …)` 改为 `(bucket_hour, …)`(`task_usage_hourly_dirty`),由 `task_usage` / `agent_task_queue` / `issue` 上的触发器写入。**必须配 TTL(保留 7 天)**,否则脏行在密集工况下无界增长——这是整个设计最容易漏的正确性要求(hourly 粒度把脏面比 daily 放大了 ~24×)。-- 调度入口 `rollup_task_usage_hourly()` 由 pg_cron 周期触发:取 advisory lock → 从 `task_usage_hourly_rollup_state` 读 watermark → 调 `rollup_task_usage_hourly_window(from, to)` 重算脏 bucket → 推进 watermark → 释放锁后跑 `prune_task_usage_hourly_dirty()`。单 tick 窗口上限 1 天,watermark 落后时分多次 tick 追平,不会一条语句锁表重算多周。--源表扫描是 worker 的主要开销,目标表换粒度只让单 tick 多几十 ms upsert,不会成倍增长。--### 4.5 Migration 082 的副作用消除--当前 `runtime.timezone` 的 PATCH 处理(migration 082 + 现有 handler)会触发该 runtime 的整张 `task_usage_daily` 重新物化——因为 `bucket_date` 含了 tz。--新方案下 `bucket_hour` 永远是 UTC,**`runtime.timezone` 改变不再触发任何数据层操作**。改 tz 立即生效,零 backfill。这同时修掉了:--- 改 tz 期间的 race condition(旧 bucket 还没重灌完,新查询已经按新 tz 渲染)。-- daemon 第一次注册时探测到非 UTC 的 tz 但历史 rollup 还是 UTC 的尴尬过渡期。-------## 5. UI / UX 影响--### 5.1 Runtime Detail 页--| 组件 | 重构前 tz 来源 | 重构后 tz 来源 |-|---|---|---|-| Daily / Weekly 趋势图 | `runtime.timezone` | `user.timezone ?? browserTimezone()` |-| KPI 卡片 | `runtime.timezone`(隐式) | `user.timezone ?? browserTimezone()` |-| 日历活跃热力图 | `runtime.timezone` 锚点 + viewer-tz 数据(不一致 bug) | `user.timezone ?? browserTimezone()`(锚点与数据统一) |-| Hour-of-day Heatmap | `runtime.timezone` | `user.timezone ?? browserTimezone()` |-| Timezone editor | 写 `runtime.timezone` | **删除** |--**用户可感知的行为变化**:--- Runtime Detail 页所有图表统一跟随 viewer 自己的 tz;页面上不再有任何 runtime 级 tz 控件。-- 想换报表 tz 的用户去 Settings → Preferences 改一次,所有 workspace / runtime 的报表立刻全跟着变。-- 跨 region 团队:hour-of-day heatmap 按查看者 tz 显示活跃时段(已知且接受的取舍,见 §2.1)。--### 5.2 Workspace Usage 页--恢复"按 viewing tz 渲染"的能力,但**不放页面级 picker**。理由:--- Picker 当年被加上去就是因为没有持久化的 viewing tz 概念。现在有了 `user.timezone`,picker 的诉求被 Preferences 替代。-- 页面级 picker 容易让用户误以为"这是一个 view-state",但 viewing tz 是全应用属性,不是单页设置。-- 减少 UI 控件 = 减少认知负担。--`packages/views/dashboard/components/dashboard-page.tsx` 里的 `WEEK_TZ = "UTC"` 改成 `useViewingTimezone()`(hook 见 `packages/views/common/use-viewing-timezone.ts`),相应的解释性注释删除。--### 5.3 Preferences 页--新增一个 Timezone setting,和现有的语言 / 主题等并列。-------## 6. 实施--> 产品尚未上线,无存量用户需保护,全部变更作为一组迁移一次性交付——旧的 daily 管线在同一分支里直接拆除,不保留共存期。--整套变更落在分支 `feat/timezone-architecture`,migration 100–104:--| Migration | 内容 |-|---|---|-| `100_user_timezone` | 加 `"user".timezone` 列(nullable) |-| `101_task_usage_hourly_schema` | 建 `task_usage_hourly` + `task_usage_hourly_rollup_state` + `task_usage_hourly_dirty` + 索引 |-| `102_task_usage_hourly_pipeline` | 失效触发器、`rollup_task_usage_hourly_window` 窗口函数、`prune_task_usage_hourly_dirty()` 失效队列 TTL、带单日 cap 与 prune 的 `rollup_task_usage_hourly()` cron 入口、pg_cron 调度 |-| `103_drop_legacy_daily_rollups` | 拆掉 `task_usage_daily` / `task_usage_dashboard_daily` 两条旧管线(表、函数、触发器、pg_cron 任务) |-| `104_drop_runtime_timezone` | 删除 `agent_runtime.timezone` 列(Operational 层移除,见 §2.1) |--配套的代码侧改动:--- **数据回填**:一次性命令 `cmd/backfill_task_usage_hourly`,按 workspace 切片把历史 `task_usage` 灌进新表。旧的 `cmd/backfill_task_usage_daily` / `cmd/backfill_task_usage_dashboard_daily` 已删除。-- **查询切换**:后端所有报表查询迁到 `task_usage_hourly`(或 Time/Tasks 的 `agent_task_queue` 查询),统一接受 `@tz`;`UseDailyRollupForDashboard` / `UseDailyRollupForRuntimeUsage` 等 feature flag 与旧的 raw-scan / daily-rollup 双查询路径一并删除。-- **前端打通**:`useViewingTimezone()` hook 解析 viewer tz,报表组件随请求带 `?tz=`;`dashboard-page.tsx` 的 `WEEK_TZ = "UTC"` 改为 `useViewingTimezone()`,原 UTC-lock 解释性注释删除。-- **UI 文案**:Preferences 新增 Timezone setting。Runtime Detail 页的 timezone editor 整体删除。-- **runtime tz 移除**:`PATCH /api/runtimes/:id` 的 `timezone` 字段删除,该端点只剩 `visibility`;daemon 注册不再上报 host tz;`agent_runtime.timezone` 列由 migration 104 删除。-------## 7. Open questions / Risks--### 7.1 Risks--- **Invalidation queue TTL 是必做**。如果忘记加,密集工况下 queue 会无界增长。-- **Hourly rollup backfill 期间的源表 read pressure**。按 workspace 切片、低峰期跑,预期 OK,但需要提前给 DB 团队打招呼。-- **DST 当天的 23h/25h "日"**。`DATE(bucket_hour AT TIME ZONE @tz)` 会正确处理,但前端任何"一天 = 24 小时"的硬编码偏移逻辑要测一遍 DST 边界。-- **现有 `runtime.timezone` 的 PATCH endpoint 行为变了**。改完不再触发 backfill——这是好事,但 API 文档和 changelog 要写清楚,避免下游集成误判。--### 7.2 Open question--- **Trigger 的 timezone 默认值**?目前用户必须手动选;可以默认 `user.timezone`,但用户写 trigger 时的 viewing tz 和 trigger 实际跑的 tz 是两件事,需要产品决策。--### 7.3 非目标--- **不做** workspace 级 tz 设置:跨 region 团队两个成员各自正确的"今天"不同,workspace 级 tz 必让其中一方看错位报表。-- **不做** 预物化多 tz rollup:IANA tz 列表有 ~600 个无法穷举、DST 需逐 tz 维护,而 hourly rollup 已经够快。-- **不做** issue / comment / inbox 等列表的 tz 切换——它们已经隐式用浏览器 tz,本 RFC 不动。后续如果要让这些也跟 `user.timezone`,是独立的 follow-up。-------## 8. 决策汇总--| 决策点 | 选择 |-|---|---|-| Timezone 概念分层 | Scheduling / Viewing 两层(Operational 经盘查后移除) |-| `runtime.timezone` 角色 | ❌ 整列删除(migration 104) |-| `user.timezone` 是否新增 | ✅ 新增,nullable,默认 fallback 到 browser |-| `workspace.timezone` 是否新增 | ❌ 不引入 |-| 数据层物化口径 | 统一 UTC, hourly grain |-| Rollup 表合并 | `task_usage_daily` + `task_usage_dashboard_daily` → `task_usage_hourly` |-| 报表 tz 切换粒度 | 全局 per-user(Preferences),不做 per-view picker |-| hour-of-day heatmap tz | viewer tz(不再用机器物理 tz) |diff --git a/docs/ui-consistency-audit.md b/docs/ui-consistency-audit.mddeleted file mode 100644index 430caff265..0000000000--- a/docs/ui-consistency-audit.md+++ /dev/null@@ -1,363 +0,0 @@-# Multica UI 一致性问题与页面模式层治理--> Status: Draft-> Owner: TBD-> Last updated: 2026-07-11-> Related implementation: [PR #5263](https://github.com/multica-ai/multica/pull/5263)--## TL;DR--Multica 当前的主要 UI 问题不是缺少颜色 token、Button 或 Card,而是缺少一层被明确命名、文档化和持续执行的 **Page Pattern Layer(页面模式层)**。--现有基础大致分成三层:--1. `packages/ui/styles/` 已经提供颜色、surface、间距等设计 token。-2. `packages/ui/components/` 已经提供 Button、Input、Card、Tabs、Empty 等基础组件。-3. `packages/views/` 中也已经出现 `CollectionPageHeader`、`CollectionPageState`、`SettingsTab`、`SettingsSection`、`SettingsCard`、`SettingsRow` 等页面模式的早期实现。--但第三层仍然是局部的、未完成的:没有覆盖所有主要页面类型,没有清晰的使用边界,也没有 review checklist 或迁移计划。因此业务页面仍然会自行决定标题、导航、卡片、分割线、表单、空状态和保存反馈,最终形成“基础组件相同,但页面体验不同”的局面。--Agent 详情页重构是页面模式层的一次试点,不应停留在单页优化。下一步应该把其中可复用的结构提炼为明确的页面模式,再逐步迁移其他页面。-------## 1. 文档目的--本文档用于:--- 记录本轮 UI review 中发现的问题,避免问题只存在于对话和截图中。-- 明确 UI 不一致的架构根因,而不是继续逐页修补 CSS。-- 区分 Design Token、基础组件、页面模式和业务页面各自的职责。-- 记录 Agent 详情页试点中已经处理或仍需验证的事项。-- 给出下一阶段 UI 治理的优先级、验收标准和开放问题。--本文档不是新的视觉规范。颜色、字体、surface、间距和基础交互仍以 [`docs/design.md`](./design.md) 为准。-------## 2. 核心判断:缺失的是页面模式层--### 2.1 当前 UI 分层--| 层级 | 回答的问题 | 当前载体 | 当前状态 |-| --- | --- | --- | --- |-| Design Token | 颜色、间距、圆角、阴影应该是什么 | `packages/ui/styles/`、`docs/design.md` | 基本完整 |-| UI Primitive | Button、Input、Card、Tabs 如何表现 | `packages/ui/components/` | 基本完整 |-| Page Pattern | 页面标题、分区、导航、列表、设置表单、状态页如何组合 | `packages/views/layout/`、`packages/views/settings/components/settings-layout.tsx` 等 | **局部存在,但未固化** |-| Business Page | Agent、Issue、Runtime 等具体业务如何呈现 | `packages/views/<domain>/` | 大量自行组合 |--Token 和 Primitive 只能保证局部视觉相似,不能自动保证页面一致。它们不会回答以下问题:--- 列表页标题、数量、描述和主操作应该放在哪里?-- 设置页应该用卡片还是平铺?一行可以放几个设置?-- 二级导航应该横向还是纵向?什么时候需要 URL 深链?-- Detail 页面如何区分状态概览、工作记录和配置?-- Empty、Loading、Error、Not Found 是否共享尺寸和文案结构?-- 可编辑列表是持续显示多个 Input,还是列表 + 单个 composer?-- 保存状态、未保存提醒和离开保护如何统一?--如果这些问题没有标准答案,每个业务页面就会重新设计一次。--### 2.2 根因--当前问题可以概括为:--> 底层 token 和基础组件已经比较完整,但中间的“页面模式层”没有被明确固化,也没有被持续执行。--具体表现为:--1. **模式没有被命名。** 开发者知道有 Card、Tabs 和 Empty,但不知道当前页面属于 Collection、Settings 还是 Workbench Detail。-2. **模式没有完整覆盖。** Collection 和 Settings 已经有早期抽象,Detail、Editable List、Inspector、Split Pane 等仍主要由页面自行实现。-3. **模式没有使用边界。** 什么时候用 Card、什么时候只用 spacing、什么时候允许 divider,仍依赖个人判断。-4. **模式没有持续执行。** 缺少新页面 checklist、视觉回归样例和跨页面 review,局部 PR 很容易重新引入平行实现。-5. **复用多停留在 JSX。** 相似页面会复制布局 class,而不是复用带语义的页面组件;一旦规范变化,需要逐页修改。-------## 3. 已发现的问题--### 3.1 全局问题--| 类别 | 当前问题 | 影响 |-| --- | --- | --- |-| 页面 Header | 标题高度、左右 padding、数量、描述和操作区组合不一致 | 页面切换时节奏跳变 |-| 二级导航 | 同类配置有的横向、有的纵向,有的只存在本地 state | 信息架构和深链行为不稳定 |-| Section 分组 | Card、divider、背景色和纯 spacing 混用,缺少明确优先级 | 页面过重或分组不清 |-| 表单布局 | 单行单项、双列设置、label/value 比例和保存区位置不一致 | 扫读和操作成本增加 |-| 列表编辑 | 有的持续显示 Input,有的用 dialog,有的就地编辑 | 同类操作需要重新学习 |-| 状态页面 | Empty、Loading、Error、Not Found 各自实现 | 图标、留白、文案和操作不一致 |-| 保存反馈 | Toast、inline status、disabled button、dirty guard 组合不统一 | 用户无法稳定判断是否已保存 |-| 内容约束 | 长描述、代码、ID 和用户输入的换行/截断策略不统一 | 容易溢出或出现密集文本墙 |-| 响应式与无障碍 | icon-only action、focus、移动端折叠依赖页面自行处理 | 容易产生不可访问或小屏失效的页面 |--### 3.2 Agent 详情页问题记录--状态说明:--- **已实现**:当前 Agent 详情页重构分支已有对应实现。-- **试点中**:已在 Agent 页面采用,但尚未抽象或推广为全局模式。-- **待验证**:需要在合并前进行完整视觉或交互回归。-- **开放**:仍需要产品或架构决策。--| 区域 | 问题 | 处理方向 | 状态 |-| --- | --- | --- | --- |-| 整体信息架构 | 原详情页更像后端字段检查器,观察、工作和配置混在一起 | 重组为 Overview、Work、Capabilities、Settings | 试点中 |-| 二级导航 | Capabilities 与 Settings 的二级选项使用横向菜单,扩展后拥挤 | 桌面端采用稳定的纵向 section nav,并保持 URL 深链 | 已实现 |-| Integrations | 本地 feature flag 默认关闭,Capabilities 中缺少 Integrations | 根据系统配置显示 Integrations,并纳入 Capabilities | 已实现 |-| Overview / Attention | “Tasks Need Attention”价值不明确、优先级过高 | 无明确干预价值时移除,不制造伪告警 | 已实现 |-| Overview / Recent Work | 条目过少;Issue 维度还是 Session 维度没有明确 | 增加可见条目;产品语义见开放问题 §8.1 | 试点中 |-| Overview / Skills | 多个 skill 时 divider 与下方横线粘连 | 优先用 spacing 分组,避免连续 divider | 待验证 |-| Instructions | System Prompt 被设计成单行 Input | 使用支持长文本、Markdown 和合理高度的 Textarea | 已实现 |-| MCP | 描述过长,缺少换行和信息层级,呈现为密集文本墙 | 缩短主文案,把说明拆成辅助信息并约束宽度 | 已实现 |-| General | 信息展示感强,不像配置页;Visibility 等交互不顺手 | 使用标准 Settings section/row,明确 label、description、control | 试点中 |-| Settings 分组 | 页面缺少稳定分组,或使用不符合 surface 规范的 Card | 独立设置组使用白色 SettingsCard;组间使用 section spacing | 已实现 |-| Settings 行布局 | 一行放两个 setting,扫读和响应式表现差 | 默认单行单项;除非字段天然组成一个原子输入 | 已实现 |-| Access | Shared 等权限不是简单 toggle,现有交互不能表达复杂规则 | Access 独立为 Settings 子 Tab,使用专门权限模型 | 试点中 |-| Details | Owner、Created、Updated 等只读元数据被放进 Settings | 从可编辑设置中移出,放到 Overview 或 inspector | 已实现 |-| Environment | 当前结构可暂时保留 | 后续迁移到统一 editable key-value pattern | 开放 |-| Custom Args | 横线过多;每个参数永久显示为 Input;新增一项就增加一个输入框和 divider | 改为有序 token 列表;只有新增/编辑项进入 composer;独立命令预览 | 已实现 |--### 3.3 Custom Args 暴露出的通用模式问题--Custom Args 并不只是一个局部样式问题,它暴露了 “Editable List” 页面模式缺失:--- 数据在静止状态下应该首先是列表,不是表单。-- 编辑态应该是临时状态,不应该让所有条目永久显示为 Input。-- 新增操作应该把内容加入列表,而不是无限扩张表单结构。-- 参数顺序有语义,应明确显示顺序。-- 每个列表项对应一个 argv token;包含空格的 token 不应被前端自行拆分。-- 命令预览属于结果反馈,应和编辑列表分开呈现。--这个模式未来可以复用于:Custom Args、Environment Variables、Webhook Headers、Repository Rules、Token/Secret 列表等,但不同数据类型需要保留各自的验证和敏感信息策略。-------## 4. 建议固化的页面模式--### 4.1 Collection Page--适用于 Agents、Projects、Skills、Runtimes、Squads、Autopilots 等实体集合。--应统一:--- Header 的 icon、title、count、description 和 actions。-- 列表/网格容器的 page padding 和滚动策略。-- Empty、Loading、Error、No Results 状态。-- 主操作在小屏下的收缩方式。-- 筛选、搜索和视图切换的位置。--现有基础:--- `packages/views/layout/collection-page.tsx`-- `CollectionPageHeader`-- `CollectionPageHeaderAction`-- `CollectionPageState`--下一步不是再造一套组件,而是补齐使用文档、样例和迁移覆盖。--### 4.2 Settings Page--适用于 Workspace Settings、Account Settings、Agent Settings 和其他配置型页面。--应统一:--- `SettingsTab → SettingsSection → SettingsCard → SettingsRow` 的层级。-- 默认单行单项;复杂 compound control 必须说明原因。-- label、description 和 control 的宽度与对齐。-- auto-save 与 explicit save 两种模式的反馈。-- dirty state、离开保护、error 和 success 状态。-- 权限不足时的只读表现。--现有基础:--- `packages/views/settings/components/settings-layout.tsx`-- `SettingsTab`-- `SettingsSection`-- `SettingsCard`-- `SettingsRow`-- `SettingsSaveState`--需要决定这些组件是否继续归属于 Settings domain,还是迁移到更通用的 `packages/views/layout/`。--### 4.3 Workbench Detail Page--适用于 Agent、Runtime、Squad、Member 等同时包含身份、状态、历史和配置的详情页。--应统一:--- Identity header:名称、状态、关键 metadata 和主操作。-- 一级导航:Overview、Work/Activity、Capabilities、Settings。-- 二级导航:当选项超过 2–3 个或文案较长时使用纵向 section nav。-- Overview 只呈现判断和行动所需的信息,不复制全部字段。-- Settings 只放可编辑配置;只读 metadata 不混入设置。-- URL 必须反映 tab/section 状态,支持刷新和分享。-- 不为不存在的健康度或进度制造伪指标。--Agent 详情页是此模式的第一个试点,但不能直接把 Agent 业务组件当作全局抽象。应先识别 Runtime、Squad、Member 的共同结构,再定义最小公共 API。--### 4.4 Editable List--适用于用户维护一个有序或无序的小型配置集合。--默认交互:--1. 静止状态显示列表项。-2. 点击 Add 后只出现一个 composer。-3. 点击 Edit 后只让目标项进入编辑态。-4. Enter 提交,Escape 取消;新增/编辑时焦点进入输入区。-5. 删除先更新本地 draft;外部持久化由统一 Save 或 auto-save 策略负责。-6. 空状态仍保留清晰的主操作。-7. 长值必须支持截断、换行或展开查看。--不应把所有 Editable List 都抽成一个万能业务组件。可以共享布局、状态和 action slot,但验证、字段结构和安全策略留在 domain 层。--### 4.5 Page State--所有页面至少需要明确以下状态:--- Initial loading-- Background refreshing-- Empty-- No search results-- Permission denied-- Not found-- Recoverable error-- Fatal error--这些状态应复用一致的尺寸、语气和 action 位置,但不能用同一条空状态文案覆盖不同原因。-------## 5. 组件归属原则--| 内容 | 推荐位置 | 约束 |-| --- | --- | --- |-| 无业务语义的原子组件 | `packages/ui/` | 不得依赖 `@multica/core` |-| 跨 domain 的页面模式 | `packages/views/layout/` | 只定义布局、slot 和交互契约 |-| 某类页面的共享模式 | `packages/views/<domain-or-pattern>/` | 允许有限业务语义,但不得绑定平台路由 |-| 具体业务页面 | `packages/views/<domain>/` | 组合模式并负责数据、权限和文案 |-| Next.js / Electron 接线 | app platform layer | 不进入 shared views |--判断一个结构是否应该抽取时,优先问:--1. 它表达的是视觉细节,还是稳定的页面语义?-2. 第二个真实使用者是谁?-3. 抽取后能否减少业务页面对 spacing、divider、responsive class 的重复决策?-4. 是否能通过 slot 保持业务差异,而不是制造大量 boolean prop?-------## 6. 下一步实施计划--### Phase 0:建立基线--- [ ] 为 Collection、Settings、Workbench Detail、Editable List、Page State 各补一个 canonical example。-- [ ] 建立页面清单,标记每个页面当前采用的模式和偏差。-- [x] 给 `docs/design.md` 增加本文件入口。-- [ ] 确认 Agent 详情页试点的视觉和交互验收结果。--### Phase 1:固化现有模式--- [ ] 补齐 Collection Page 的 loading、filter toolbar 和 responsive 规范。-- [ ] 明确 Settings explicit-save / auto-save 两套状态契约。-- [ ] 从 Agent 详情页提炼最小 Workbench Detail shell,而不是复制整页。-- [ ] 提炼 Editable List 的布局契约,并用第二个真实页面验证抽象。-- [ ] 为 pattern components 增加结构和无障碍测试。--### Phase 2:迁移高频页面--建议优先级:--1. Agents / Skills / Runtimes / Projects 等 collection 页面。-2. Workspace Settings 与 Agent Settings。-3. Runtime / Squad / Member detail 页面。-4. Environment、Custom Args 和其他 editable configuration lists。--每次迁移应是小 PR,不在同一 PR 中同时改变业务行为和全局视觉规范。--### Phase 3:持续执行--- [ ] 在 PR template 中加入 Page Pattern checklist。-- [ ] 新页面必须声明采用的 page pattern;偏离时说明原因。-- [ ] 给 canonical examples 增加 light/dark、中文/英文和窄屏视觉回归。-- [ ] 定期删除迁移后遗留的平行组件和重复 class 组合。-- [ ] 将审计从一次性项目变成每个季度的 UI consistency review。-------## 7. 验收标准--页面模式层达到可用状态,需要同时满足:--1. 新页面可以先选择页面模式,再填充业务内容,而不是从空白 `<div>` 开始。-2. 同类页面的 header、导航、section、empty/error 和 action 位置一致。-3. 业务页面不再重复决定基础 padding、divider、card 和保存反馈。-4. 模式组件支持 keyboard、focus、overflow、responsive 和 i18n 长文案。-5. light/dark、中文/英文、desktop/web 至少有 canonical visual coverage。-6. 模式允许业务差异,但偏差是显式决定,不是无意复制。-7. 新抽象至少由两个真实页面验证,避免只为单页包装 JSX。-------## 8. 开放问题--### 8.1 Agent Recent Work 使用 Issue 还是 Session 维度--需要先确认该区块回答的问题:--- 如果回答“这个 Agent 最近交付了什么”,Issue/Task 是更接近用户心智的单位。-- 如果回答“这个 Agent 最近每次执行发生了什么”,Session 是更准确的诊断单位。--建议不要在同一个平铺列表中混合两个粒度。可以默认使用 Issue/Task 维度,把最新 Session 状态作为行内 metadata;完整 Session 历史留在 Work 页面。--### 8.2 Settings pattern 的归属--当前实现位于 `packages/views/settings/components/settings-layout.tsx`,但 Agent Settings 已经复用它。需要决定:--- 保持当前位置,把 Settings 当作共享 pattern package;或-- 迁移到 `packages/views/layout/settings-*`,让归属与实际用途一致。--在迁移前不要再创建第二套 Settings layout。--### 8.3 Card 与 flat section 的边界--默认遵循 `docs/design.md` 的容器优先级:spacing → 单条 divider → 背景变化 → Card。--建议补充的判断是:--- 独立设置组、可整体操作的信息块可以使用 Card。-- 连续阅读内容、元数据清单和普通列表不应每项一张 Card。-- Card 内不要再通过多层 border 制造“卡片套卡片”。--### 8.4 Detail pattern 的最小公共部分--Agent、Runtime、Squad 和 Member 的详情页并不完全相同。抽象前需要确认真正共享的是 shell、header、navigation 和 section layout,还是还包括 inspector。原则上优先抽取稳定外壳,业务内容通过 slot 注入。-------## 9. 新页面 Review Checklist--- [ ] 这个页面属于哪一种 page pattern?-- [ ] 是否复用了现有 Header、Section、State 和 Action 模式?-- [ ] 是否出现了业务页面自定义的 Card、divider 或 empty state?为什么?-- [ ] 设置是否默认单行单项?复合字段是否真的是一个原子输入?-- [ ] URL 是否反映 tab、filter、pagination 或 section 等可分享状态?-- [ ] Loading、Empty、Error、Permission 和 Not Found 是否被分别处理?-- [ ] 长文案、长 ID、用户输入和窄屏是否不会溢出?-- [ ] icon-only button 是否有 accessible name?键盘 focus 是否可见?-- [ ] light/dark 和至少一种 CJK locale 是否完成视觉检查?-- [ ] 是否新增了一个只服务当前页面、但其实表达通用模式的本地组件?-------## 10. 相关文件--- [`docs/design.md`](./design.md)-- `packages/ui/styles/tokens.css`-- `packages/ui/components/`-- `packages/views/layout/collection-page.tsx`-- `packages/views/layout/page-header.tsx`-- `packages/views/settings/components/settings-layout.tsx`-- `packages/views/agents/components/agent-detail-page.tsx`-- `packages/views/agents/components/agent-overview-pane.tsx`-- `packages/views/agents/components/tabs/custom-args-tab.tsx`diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.tsindex a4abdb03dc..d318df6962 100644--- a/packages/core/analytics/index.ts+++ b/packages/core/analytics/index.ts@@ -1,6 +1,6 @@// Frontend analytics glue. Thin wrapper over posthog-js.//-// The source-of-truth event catalog is `docs/analytics.md`. This module only+// The source-of-truth event catalog is `server/internal/analytics/events.go`. This module only// handles the two things the backend can't do itself: attribution capture on// first anonymous pageview, and person-identity merge on login. Every funnel// event (signup, workspace_created, runtime_registered, issue_executed,@@ -117,7 +117,7 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole// our funnel is set up: signup is the first real funnel step.person_profiles: "identified_only",// Turn off every on-by-default auto-capture surface. Our funnel is- // narrow and explicit (the events in docs/analytics.md + a manual+ // narrow and explicit (the events in server/internal/analytics/events.go + a manual// $pageview). Autocapture floods the Activity view with anonymous// "clicked button" / "clicked link" noise, burns the billed event// budget, and risks capturing user-typed content in input values.diff --git a/server/cmd/backfill_task_usage_hourly/main.go b/server/cmd/backfill_task_usage_hourly/main.goindex 004d16af73..fe7ec38b76 100644--- a/server/cmd/backfill_task_usage_hourly/main.go+++ b/server/cmd/backfill_task_usage_hourly/main.go@@ -31,7 +31,7 @@// / issue. On a database with years of history that is sustained heavy// load. Use --sleep-between-slices to throttle on a busy production DB,// and coordinate a maintenance window with the DB team before a-// full-history run (see docs/timezone-architecture-rfc.md §7.1).+// full-history run.//// Operator note: this command does NOT call prune_task_usage_hourly_dirty.// The dirty queue starts empty during backfill (triggers fire only ondiff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 1b6dd1bbed..13bf20b7c2 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -198,7 +198,7 @@ func main() {// Feature flags: loaded once at startup from MULTICA_FEATURE_FLAGS_FILE// (a YAML rule set) with FF_<KEY> env overrides layered on top.- // See docs/feature-flags.md for the schema and lifecycle rules.+ // See server/pkg/featureflag for the schema and lifecycle rules.//// Booting the server without any flag config is intentional: when the// env var is unset, every IsEnabled call falls through to the caller's@@ -211,7 +211,7 @@ func main() {slog.Error("feature flag configuration failed to load", "error", err)os.Exit(1)}- _ = flags // adopted by the router (opts.FeatureFlags) and server-side toggle points; see docs/feature-flags.md+ _ = flags // adopted by the router (opts.FeatureFlags) and server-side toggle points; see server/pkg/featureflagdbURL := os.Getenv("DATABASE_URL")if dbURL == "" {diff --git a/server/internal/agenttmpl/loader.go b/server/internal/agenttmpl/loader.goindex dc19ab34d4..41c923daf1 100644--- a/server/internal/agenttmpl/loader.go+++ b/server/internal/agenttmpl/loader.go@@ -101,9 +101,8 @@ func validate(t Template, filename string) error {return fmt.Errorf("missing instructions")}// 0-skill templates are legitimate — most starter templates are- // prompt-only (instructions alone, no skill fan-out). See- // docs/agent-quick-create-plan.md and the picker UI's "Prompt only"- // rendering for zero-length skill arrays.+ // prompt-only (instructions alone, no skill fan-out). See the picker+ // UI's "Prompt only" rendering for zero-length skill arrays.for i, s := range t.Skills {if strings.TrimSpace(s.SourceURL) == "" {return fmt.Errorf("skill[%d]: missing source_url", i)diff --git a/server/internal/analytics/client.go b/server/internal/analytics/client.goindex de0a5dfb15..7e011c65d2 100644--- a/server/internal/analytics/client.go+++ b/server/internal/analytics/client.go@@ -1,6 +1,6 @@// Package analytics ships product telemetry events to an external analytics// backend (PostHog). Events feed the acquisition → activation → expansion-// funnel — see docs/analytics.md for the event contract.+// funnel — see events.go for the event contract.//// Design:// - Capture is non-blocking. Request handlers must never wait on analyticsdiff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex 4f25f06bb7..7b191bddde 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -2,7 +2,8 @@ package analyticsimport "strings"-// Event names. Keep in sync with docs/analytics.md.+// Event names. This file is the source-of-truth catalog; keep+// packages/core/analytics in sync with it.const (EventSignup = "signup"EventWorkspaceCreated = "workspace_created"@@ -44,7 +45,7 @@ const EventSchemaVersion = 2// events metrics-only — both the product-behaviour group and the original// high-volume runtime/autopilot telemetry are Prometheus-only. PostHog now only// receives frontend error/crash telemetry ($exception, client_crash,-// client_unresponsive); see packages/core/analytics and docs/analytics.md.+// client_unresponsive); see packages/core/analytics.//// Note: agent_task_* lifecycle events are also Prometheus-only, but their// Prometheus side is handled by typed BusinessMetrics.RecordTask* methods, so@@ -117,7 +118,7 @@ type CoreProperties struct {type TaskContext = CoreProperties-// Onboarding completion paths. Keep in sync with docs/analytics.md.+// Onboarding completion paths. Keep in sync with packages/core/analytics.const (OnboardingPathFull = "full" // reached first_issue end of flowOnboardingPathRuntimeSkipped = "runtime_skipped" // completed without connecting a runtimediff --git a/server/migrations/100_user_timezone.up.sql b/server/migrations/100_user_timezone.up.sqlindex 5226c7cdbb..1d2b6b91c3 100644--- a/server/migrations/100_user_timezone.up.sql+++ b/server/migrations/100_user_timezone.up.sql@@ -1,5 +1,5 @@-- Per-user IANA timezone for *viewing* reports — the third leg of the--- Operational / Scheduling / Viewing trio (see docs/timezone-architecture-rfc.md).+-- Operational / Scheduling / Viewing trio.---- Distinct from:-- * agent_runtime.timezone (Operational): where a runtime physically runs.diff --git a/server/migrations/101_task_usage_hourly_schema.up.sql b/server/migrations/101_task_usage_hourly_schema.up.sqlindex 04f3cb9b20..1c2fa20784 100644--- a/server/migrations/101_task_usage_hourly_schema.up.sql+++ b/server/migrations/101_task_usage_hourly_schema.up.sql@@ -1,7 +1,7 @@-- Hourly rollup table for `task_usage`, materialised in **UTC**. Replaces-- both per-runtime `task_usage_daily` (073, 082) and per-workspace-- `task_usage_dashboard_daily` (084) as the single source of truth for--- all token-usage reports. See docs/timezone-architecture-rfc.md §4.+-- all token-usage reports.---- WHY HOURLY + UTC:-- The two existing rollups materialise on a `DATE` bucket — one in thediff --git a/server/migrations/103_drop_legacy_daily_rollups.up.sql b/server/migrations/103_drop_legacy_daily_rollups.up.sqlindex f3263234d2..b8c6cc1384 100644--- a/server/migrations/103_drop_legacy_daily_rollups.up.sql+++ b/server/migrations/103_drop_legacy_daily_rollups.up.sql@@ -1,6 +1,5 @@-- Drop the two legacy daily rollup pipelines now that `task_usage_hourly`--- is the only read path (see docs/timezone-architecture-rfc.md §6,--- Phase 3). Forward-only: there is no down migration that would put the+-- is the only read path. Forward-only: there is no down migration that would put the-- data back, since by the time this ships:---- * The hourly rollup has been live and writing every bucket since@@ -27,8 +26,7 @@-- per-version stop), so a self-host operator who skips the documented-- backfill step would otherwise silently land in a state where dashboards-- show zeros (see SELF-HOST UPGRADE ORDER in--- cmd/backfill_task_usage_hourly/main.go and--- docs/timezone-architecture-rfc.md §6 / §7.1). Failing loud here is the+-- cmd/backfill_task_usage_hourly/main.go). Failing loud here is the-- only thing that turns an undetected outage into a clear migration error.---- The completion signal we trust is task_usage_hourly_rollup_state.watermark_at:diff --git a/server/migrations/104_drop_runtime_timezone.up.sql b/server/migrations/104_drop_runtime_timezone.up.sqlindex 5f232b90fe..8e2f86a798 100644--- a/server/migrations/104_drop_runtime_timezone.up.sql+++ b/server/migrations/104_drop_runtime_timezone.up.sql@@ -2,5 +2,5 @@-- collapsed from 3 layers to 2: Scheduling (autopilot_trigger.timezone) and-- Viewing (user.timezone). The runtime's physical tz had exactly one-- consumer -- the hour-of-day heatmap -- which now renders in the viewer's--- tz like every other report. See docs/timezone-architecture-rfc.md.+-- tz like every other report.ALTER TABLE agent_runtime DROP COLUMN timezone;diff --git a/server/pkg/featureflag/doc.go b/server/pkg/featureflag/doc.goindex f84bb09e14..782ea1859c 100644--- a/server/pkg/featureflag/doc.go+++ b/server/pkg/featureflag/doc.go@@ -33,5 +33,5 @@// which is already a server-level dependency.//// See server/pkg/featureflag/service.go for the public Service API and-// docs/feature-flags.md for end-to-end usage examples.+// the package tests for end-to-end usage examples.package featureflag