Files
multica/server/internal/analytics/client.go
Jiayuan Zhang c1ec1f4646 docs: cut docs/ to design + product-overview, English by default (MUL-5698) (#6364)
* docs: delete completed plan docs and fix stale repo documentation (MUL-5698)

Ten repo docs were verifiably out of date against the code. Completed
plans are deleted outright rather than archived — they are dead weight in
every agent's context and their decisions already live in the code.

Deleted (all describe work that has shipped):
- docs/agent-quick-create-plan.md — marked "未动工", but agenttmpl
  templates (Phase 1) and the AI-create-agent page (Phase 3) are live
- docs/docs-outline.md — tracker planning "Chinese only, 25 pages"; the
  doc site is 39 pages x 4 languages
- docs/docs-rewrite-plan.md — plans 55 mdx, lists webhook autopilot
  triggers as unrouted; both superseded by what shipped
- docs/docs-onboarding-optimization-plan.md — work log for #5714, which
  landed the four languages and screenshots it lists as pending
- docs/onboarding-refactor-plan.md — v3 shipped (welcome-store,
  welcome-after-onboarding, onboarding_shim)
- apps/mobile/docs/project-v1-{plan,gap-audit}.md — marked
  "pre-implementation"; the picker files they scope no longer exist
- docs/plans/* + docs/ideation/* — implementation plans for agent
  access-scope (agent.visibility) and issue-table server query
  (/api/issues/grouped), both shipped

Fixed:
- docs/codex-sandbox-troubleshooting.md — the decision matrix claimed
  non-darwin gets workspace-write. Linux is danger-full-access (MUL-5578)
  and Windows is danger-full-access (MUL-4957); Windows had no row at all
- apps/mobile/docs/rnr-migration.md — Phase 1 is complete, not "not
  started"; every checklist item is in the tree
- AGENTS.md — architecture list was missing apps/mobile, apps/docs,
  packages/eslint-config
- docs/ui-consistency-audit.md — §3.2 status column is a mid-PR snapshot;
  #5263 and #5258 have merged
- server/internal/agenttmpl/loader.go — drop reference to a deleted doc

Co-authored-by: multica-agent <github@multica.ai>

* docs: reduce docs/ to design + product-overview, English by default (MUL-5698)

docs/ now holds two documents, each with an English default and a .zh.md
translation. Everything else was engineering scratch that agents load as
context on every run without ever being read by a human.

Deleted:
- docs/analytics.md, docs/feature-flags.md, docs/timezone-architecture-rfc.md,
  docs/codex-sandbox-troubleshooting.md, docs/codex-usage-cache-backfill.md,
  docs/custom-runtimes.md, docs/ui-consistency-audit.md

Language convention — English is the default filename, translations carry
a language suffix:
- docs/design.md (new English) + docs/design.zh.md (was design.md)
- docs/product-overview.md (new English) + docs/product-overview.zh.md
  (was product-overview.md)

While translating product-overview, three facts were corrected against the
code rather than carried over from the 2026-04-21 survey: the provider list
now matches README, onboarding is the shipped three-step
about_you/workspace/runtime sequence with Helper creation moved after exit
(packages/core/onboarding/step-order.ts), and the stale "28 tables" total
was dropped.

Reference cleanup so no comment points at a deleted file — .env.example,
server/internal/analytics/{client,events}.go, packages/core/analytics/index.ts,
server/cmd/server/main.go, server/pkg/featureflag/doc.go,
server/cmd/backfill_task_usage_hourly/main.go, and the doc pointers in
migrations 100/101/103/104. Migration edits are comment-only; the runner
tracks applied versions by filename, not by checksum.

docs/assets/ is kept — README.md and README.zh-CN.md embed those images.

Co-authored-by: multica-agent <github@multica.ai>

* docs: drop product-overview, fix rnr body and CLAUDE/AGENTS drift (MUL-5698)

Addresses all four blockers from review.

1+2. Delete docs/product-overview.md and docs/product-overview.zh.md.
The review found the doc carried facts that would make an agent do the
wrong thing — skill injection claimed a .agent_context/skills fallback for
providers that now have native paths in execenv/context.go, and it
documented `multica skill create --title` when the CLI only registers
--name. Rather than chase those, the document goes: it is derived from
code and can be regenerated from code when it is actually wanted. That
also removes the zh-as-historical-snapshot problem, since neither
language survives.

docs/ is now design.md + design.zh.md + assets/. design.zh.md is a
faithful translation of the English, not a snapshot, so blocker 1 does
not apply to it.

3. apps/mobile/docs/rnr-migration.md: the body contradicted its own
status line. §1 asserted in present tense that there is no theming
infrastructure, hardcoded tailwind hex, and a three-line global.css;
§5.2 said the same. Both are now marked as the pre-Phase-1 baseline with
the shipped state noted, §6's Phase 0/1 checklists are backfilled as
complete, and Phase 2 is labelled not started.

4. CLAUDE.md gains apps/docs/ and packages/eslint-config/, so the
authoritative Project Shape list matches the pointer list in AGENTS.md.
The two lists are now identical.

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Lambda <lambda@multica.ai>
Co-authored-by: multica-agent <github@multica.ai>
2026-08-04 17:31:45 +08:00

129 lines
4.3 KiB
Go

// Package analytics ships product telemetry events to an external analytics
// backend (PostHog). Events feed the acquisition → activation → expansion
// funnel — see events.go for the event contract.
//
// Design:
// - Capture is non-blocking. Request handlers must never wait on analytics
// network I/O, so we enqueue into a bounded channel and a background
// worker flushes to PostHog in batches.
// - When the queue is full events are dropped (and counted). A broken
// analytics backend must never degrade the product.
// - When POSTHOG_API_KEY is empty the package runs a no-op client, which
// keeps local dev and self-hosted instances friction-free.
package analytics
import (
"log/slog"
"os"
"strings"
"time"
)
// Event is a single analytics capture. Fields mirror PostHog's /capture/ shape
// but are framework-agnostic so alternate backends can plug in later.
type Event struct {
// Name of the event (e.g. "signup", "workspace_created").
Name string
// DistinctID identifies the person this event belongs to. For logged-in
// users this is user.id; for anonymous events it should be the anon_id
// that was previously used on the frontend so identity merging works.
DistinctID string
// WorkspaceID scopes the event to a workspace. Required when the event is
// about a workspace-level action (workspace_created, issue_executed, ...).
// Empty is allowed for pre-workspace events (signup).
WorkspaceID string
// Properties is the free-form bag of event attributes. Only serialisable
// values (string, number, bool, nested maps/slices of the same) should
// go here. Never put raw PII like full emails here — use email_domain.
Properties map[string]any
// SetOnce properties attach to the person record and are only written the
// first time they appear. Use this for acquisition attribution
// (initial_utm_source, etc.) so later events don't overwrite the origin.
SetOnce map[string]any
// Set properties attach to the person record and overwrite on every write.
// Use this for mutable cohort signals (role, use_case, platform_preference)
// that users can legitimately change during onboarding.
Set map[string]any
// Timestamp is optional; when zero the client fills in time.Now().
Timestamp time.Time
}
// Client is the narrow surface the rest of the codebase depends on. Handlers
// call Capture and move on; the implementation is responsible for buffering,
// batching, and shipping.
type Client interface {
Capture(e Event)
// Close drains pending events. Call once during graceful shutdown.
Close()
}
// NewFromEnv returns a Client configured from environment variables:
//
// - POSTHOG_API_KEY: project API key. Empty → no-op client.
// - POSTHOG_HOST: API host (default https://us.i.posthog.com).
// - ANALYTICS_ENVIRONMENT: production/staging/dev. Defaults from APP_ENV.
// - ANALYTICS_DISABLED: set to "true"/"1" to force a no-op client even
// when POSTHOG_API_KEY is set (useful for CI and self-hosted opt-out).
func NewFromEnv() Client {
if isDisabled() {
slog.Info("analytics disabled via ANALYTICS_DISABLED")
return NoopClient{}
}
key := os.Getenv("POSTHOG_API_KEY")
if key == "" {
slog.Info("analytics: POSTHOG_API_KEY not set, using noop client")
return NoopClient{}
}
host := os.Getenv("POSTHOG_HOST")
if host == "" {
host = "https://us.i.posthog.com"
}
slog.Info("analytics: posthog client enabled", "host", host)
return NewPostHogClient(PostHogConfig{
APIKey: key,
Host: host,
Environment: EnvironmentFromEnv(),
})
}
func isDisabled() bool {
v := os.Getenv("ANALYTICS_DISABLED")
return v == "true" || v == "1"
}
func EnvironmentFromEnv() string {
if v := normalizeEnvironment(os.Getenv("ANALYTICS_ENVIRONMENT")); v != "" {
return v
}
if v := normalizeEnvironment(os.Getenv("APP_ENV")); v != "" {
return v
}
return "dev"
}
func normalizeEnvironment(v string) string {
switch strings.ToLower(strings.TrimSpace(v)) {
case "production", "prod":
return "production"
case "staging", "stage":
return "staging"
case "development", "dev", "test", "local":
return "dev"
default:
return ""
}
}
// NoopClient silently drops all events. Used in tests, in local dev when
// POSTHOG_API_KEY is unset, and in self-hosted instances that opt out.
type NoopClient struct{}
func (NoopClient) Capture(Event) {}
func (NoopClient) Close() {}