Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(server): funnel/community/commercial business metrics + PostHog pairing (MUL-2949) (#3698)
LinYushende900b2ba69d
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 60205e673a..b398b38b1b 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -270,6 +270,11 @@ func main() {})httpMetrics = metricsRegistry.HTTPbusinessMetrics = metricsRegistry.Business+ // Forward inbound daemon WS frames into the per-kind counter so+ // dashboards can split heartbeat / unknown / invalid traffic.+ if daemonHub != nil {+ daemonHub.SetMessageKindRecorder(businessMetrics)+ }metricsServer = obsmetrics.NewServer(metricsConfig.Addr, metricsRegistry.Gatherer)if !obsmetrics.IsLoopbackAddr(metricsConfig.Addr) {slog.Warn(diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f4a1861c7c..e655a6c068 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -18,6 +18,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"@@ -142,7 +143,16 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusCloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)+ h.Metrics = opts.BusinessMetricsh.TaskService.Metrics = opts.BusinessMetrics+ if opts.BusinessMetrics != nil {+ // Wire the BusinessMetrics receiver into the cloud runtime client+ // so every outbound Fleet/Gateway request feeds the+ // multica_cloudruntime_request_* histograms.+ if client, ok := h.CloudRuntime.(*cloudruntime.Client); ok {+ client.SetRecorder(opts.BusinessMetrics)+ }+ }if opts.DaemonWakeup != nil {h.TaskService.Wakeup = opts.DaemonWakeup}diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 5ba26eb1ea..282b169777 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -9,6 +9,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/handler"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -118,7 +119,7 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handl}if taskSvc != nil && taskSvc.Analytics != nil {for _, row := range staleRows {- taskSvc.Analytics.Capture(analytics.RuntimeOffline(+ obsmetrics.RecordEvent(taskSvc.Analytics, taskSvc.Metrics, analytics.RuntimeOffline(util.UUIDToString(row.OwnerID),util.UUIDToString(row.WorkspaceID),util.UUIDToString(row.ID),diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.goindex fc9f596852..fdc42fd7cf 100644--- a/server/internal/analytics/events.go+++ b/server/internal/analytics/events.go@@ -31,6 +31,8 @@ const (EventCloudWaitlistJoined = "cloud_waitlist_joined"EventFeedbackSubmitted = "feedback_submitted"EventContactSalesSubmitted = "contact_sales_submitted"+ EventSquadCreated = "squad_created"+ EventAutopilotCreated = "autopilot_created")const EventSchemaVersion = 2@@ -261,12 +263,16 @@ func IssueExecuted(actorID, workspaceID, issueID, taskID, agentID, source, runti}}-func IssueCreated(actorID, workspaceID, issueID, agentID, taskID, autopilotRunID, source string) Event {+func IssueCreated(actorID, workspaceID, issueID, agentID, taskID, autopilotRunID, source, platform string) Event {+ props := map[string]any{}+ if platform != "" {+ props["platform"] = platform+ }return Event{Name: EventIssueCreated,DistinctID: actorID,WorkspaceID: workspaceID,- Properties: withCoreProperties(nil, CoreProperties{+ Properties: withCoreProperties(props, CoreProperties{UserID: nonAgentUserID(actorID),WorkspaceID: workspaceID,AgentID: agentID,@@ -278,12 +284,16 @@ func IssueCreated(actorID, workspaceID, issueID, agentID, taskID, autopilotRunID}}-func ChatMessageSent(userID, workspaceID, chatSessionID, taskID, agentID, runtimeMode, provider string) Event {+func ChatMessageSent(userID, workspaceID, chatSessionID, taskID, agentID, runtimeMode, provider, platform string) Event {+ props := map[string]any{}+ if platform != "" {+ props["platform"] = platform+ }return Event{Name: EventChatMessageSent,DistinctID: userID,WorkspaceID: workspaceID,- Properties: withCoreProperties(nil, CoreProperties{+ Properties: withCoreProperties(props, CoreProperties{UserID: userID,WorkspaceID: workspaceID,AgentID: agentID,@@ -340,18 +350,18 @@ type AutopilotAssignee struct {SquadID string // empty when AssigneeType != "squad"}-func AutopilotRunStarted(actorID, workspaceID, autopilotID, runID string, assignee AutopilotAssignee, triggerSource string) Event {- return autopilotRunEvent(EventAutopilotRunStarted, actorID, workspaceID, autopilotID, runID, assignee, triggerSource, nil)+func AutopilotRunStarted(actorID, workspaceID, autopilotID, runID, cadence string, assignee AutopilotAssignee, triggerSource string) Event {+ return autopilotRunEvent(EventAutopilotRunStarted, actorID, workspaceID, autopilotID, runID, cadence, assignee, triggerSource, nil)}-func AutopilotRunCompleted(actorID, workspaceID, autopilotID, runID string, assignee AutopilotAssignee, triggerSource string, durationMS int64) Event {- return autopilotRunEvent(EventAutopilotRunCompleted, actorID, workspaceID, autopilotID, runID, assignee, triggerSource, map[string]any{+func AutopilotRunCompleted(actorID, workspaceID, autopilotID, runID, cadence string, assignee AutopilotAssignee, triggerSource string, durationMS int64) Event {+ return autopilotRunEvent(EventAutopilotRunCompleted, actorID, workspaceID, autopilotID, runID, cadence, assignee, triggerSource, map[string]any{"duration_ms": durationMS,})}-func AutopilotRunFailed(actorID, workspaceID, autopilotID, runID string, assignee AutopilotAssignee, triggerSource, failureReason, errorType string, willRetry bool, durationMS int64) Event {- return autopilotRunEvent(EventAutopilotRunFailed, actorID, workspaceID, autopilotID, runID, assignee, triggerSource, map[string]any{+func AutopilotRunFailed(actorID, workspaceID, autopilotID, runID, cadence string, assignee AutopilotAssignee, triggerSource, failureReason, errorType string, willRetry bool, durationMS int64) Event {+ return autopilotRunEvent(EventAutopilotRunFailed, actorID, workspaceID, autopilotID, runID, cadence, assignee, triggerSource, map[string]any{"duration_ms": durationMS,"failure_reason": failureReason,"error_type": errorType,@@ -410,6 +420,32 @@ func TeamInviteAccepted(inviteeID, workspaceID string, daysSinceInvite int64) Ev// are presence booleans for the free-text "other" override; the// free-text content is kept in the DB for product research but not// broadcast via analytics (PII risk + low cardinality ask).+// OnboardingStarted fires from the server side the first time a user's+// onboarding state transitions from untouched (no questionnaire payload+// recorded) to any non-empty patch. Frontends emit their own+// onboarding_started on first page open; the server emission is what+// lights up the Prometheus counter so Grafana can be cross-checked+// against the PostHog funnel without depending on the SDK roundtrip.+//+// platform is the X-Client-Platform header value at the time of the+// first onboarding interaction, fed into the+// `multica_onboarding_started_total{platform=...}` label via the fixed+// allow-list in metrics.NormalizePlatform.+func OnboardingStarted(userID, platform string) Event {+ props := map[string]any{}+ if platform != "" {+ props["platform"] = platform+ }+ return Event{+ Name: EventOnboardingStarted,+ DistinctID: userID,+ Properties: withCoreProperties(props, CoreProperties{+ UserID: userID,+ Source: SourceOnboarding,+ }),+ }+}+func OnboardingQuestionnaireSubmitted(userID string, source []string, role string, useCase []string, sourceSkipped, roleSkipped, useCaseSkipped, sourceHasOther, roleHasOther, useCaseHasOther bool) Event {// Normalize nil slices to [] so PostHog property values are stable// (avoids null vs [] mixing in property type inference).@@ -520,13 +556,17 @@ func CloudWaitlistJoined(userID string, hasReason bool) Event {// FeedbackSubmitted fires after a feedback row is successfully inserted.// The raw message is stored in the DB and never broadcast — we only emit a-// coarse length bucket, an image-presence flag, and the client platform /-// version so support can segment without leaking content.-func FeedbackSubmitted(userID, workspaceID string, messageLen int, hasImages bool, platform, appVersion string) Event {+// coarse length bucket, an image-presence flag, the kind picker selection,+// and the client platform / version so support can segment without leaking+// content.+func FeedbackSubmitted(userID, workspaceID, kind string, messageLen int, hasImages bool, platform, appVersion string) Event {props := map[string]any{"message_length_bucket": feedbackLengthBucket(messageLen),"has_images": hasImages,}+ if kind != "" {+ props["kind"] = kind+ }if platform != "" {props["platform"] = platform}@@ -548,9 +588,15 @@ func FeedbackSubmitted(userID, workspaceID string, messageLen int, hasImages boo// ContactSalesSubmitted fires after a contact-sales inquiry is recorded.// The form is public and unauthenticated, so DistinctID is empty (PostHog// will treat it as an anonymous event). We carry the coarse company size,-// country, and intended use case so sales / marketing can split inbound-// volume without having to query the operational DB.-func ContactSalesSubmitted(inquiryID, companySize, countryRegion, useCase string, hasGoals bool) Event {+// country, intended use case, and the form-location bucket (page /+// onboarding / agents_page) so sales / marketing can split inbound volume+// without having to query the operational DB.+//+// formSource is the page-context bucket; the CoreProperties Source stays+// "marketing_contact_sales" so PostHog dashboards keep the funnel join+// against other marketing events. The Prometheus side reads form_source+// directly via the metrics.NormalizeContactSalesSource allow-list.+func ContactSalesSubmitted(inquiryID, companySize, countryRegion, useCase, formSource string, hasGoals bool) Event {props := map[string]any{"inquiry_id": inquiryID,"company_size": companySize,@@ -558,6 +604,9 @@ func ContactSalesSubmitted(inquiryID, companySize, countryRegion, useCase string"use_case": useCase,"has_goals": hasGoals,}+ if formSource != "" {+ props["form_source"] = formSource+ }return Event{Name: EventContactSalesSubmitted,DistinctID: inquiryID,@@ -567,6 +616,47 @@ func ContactSalesSubmitted(inquiryID, companySize, countryRegion, useCase string}}+// SquadCreated fires when a workspace member or admin creates a new squad.+// `memberCount` is the number of members the squad was seeded with at+// creation time (frontend can pre-populate via the picker).+func SquadCreated(actorID, workspaceID, squadID string, memberCount int) Event {+ return Event{+ Name: EventSquadCreated,+ DistinctID: actorID,+ WorkspaceID: workspaceID,+ Properties: withCoreProperties(map[string]any{+ "squad_id": squadID,+ "member_count": int64(memberCount),+ }, CoreProperties{+ UserID: nonAgentUserID(actorID),+ WorkspaceID: workspaceID,+ Source: SourceManual,+ }),+ }+}++// AutopilotCreated fires when a workspace member creates a new autopilot.+// `cadence` matches the autopilot.cadence enum (hourly/daily/weekly/...+// /webhook). triggerKind is the initial trigger type (schedule / webhook /+// manual) — when both schedule and webhook triggers are seeded, we report+// the dominant one (schedule wins).+func AutopilotCreated(actorID, workspaceID, autopilotID, cadence, triggerKind string) Event {+ return Event{+ Name: EventAutopilotCreated,+ DistinctID: actorID,+ WorkspaceID: workspaceID,+ Properties: withCoreProperties(map[string]any{+ "autopilot_id": autopilotID,+ "cadence": cadence,+ "trigger_kind": triggerKind,+ }, CoreProperties{+ UserID: nonAgentUserID(actorID),+ WorkspaceID: workspaceID,+ Source: SourceManual,+ }),+ }+}+func agentTaskEvent(name string, ctx TaskContext, extra map[string]any) Event {props := withCoreProperties(extra, CoreProperties(ctx))return Event{@@ -577,11 +667,15 @@ func agentTaskEvent(name string, ctx TaskContext, extra map[string]any) Event {}}-func autopilotRunEvent(name, actorID, workspaceID, autopilotID, runID string, assignee AutopilotAssignee, triggerSource string, extra map[string]any) Event {+func autopilotRunEvent(name, actorID, workspaceID, autopilotID, runID, cadence string, assignee AutopilotAssignee, triggerSource string, extra map[string]any) Event {if extra == nil {extra = map[string]any{}}extra["trigger_source"] = triggerSource+ extra["trigger_kind"] = triggerSource+ if cadence != "" {+ extra["cadence"] = cadence+ }props := withCoreProperties(extra, CoreProperties{UserID: nonAgentUserID(actorID),WorkspaceID: workspaceID,diff --git a/server/internal/analytics/events_test.go b/server/internal/analytics/events_test.goindex 16abe0815e..3f352cd8ba 100644--- a/server/internal/analytics/events_test.go+++ b/server/internal/analytics/events_test.go@@ -30,7 +30,7 @@ func TestFailedEventsUseWillRetry(t *testing.T) {t.Fatalf("task failure should not emit recoverable")}- runEv := AutopilotRunFailed("user-1", "workspace-1", "autopilot-1", "run-1", AutopilotAssignee{AgentID: "agent-1", AssigneeType: "agent"}, "manual", "task failed", "task_error", false, 10)+ runEv := AutopilotRunFailed("user-1", "workspace-1", "autopilot-1", "run-1", "manual", AutopilotAssignee{AgentID: "agent-1", AssigneeType: "agent"}, "manual", "task failed", "task_error", false, 10)if got := runEv.Properties["will_retry"]; got != false {t.Fatalf("autopilot will_retry = %v, want false", got)}diff --git a/server/internal/cloudruntime/client.go b/server/internal/cloudruntime/client.goindex 8b97f1448d..11423d29d6 100644--- a/server/internal/cloudruntime/client.go+++ b/server/internal/cloudruntime/client.go@@ -22,10 +22,21 @@ var (ErrInvalidBaseURL = errors.New("cloud runtime fleet URL is invalid"))+// RequestRecorder is the small interface the client uses to instrument every+// outbound request without taking a hard dependency on the metrics package.+// A nil recorder is safely no-op'd.+type RequestRecorder interface {+ RecordCloudRuntimeRequest(op, status string, durationSeconds float64)+}+type Config struct {BaseURL stringTimeout time.DurationHTTPClient *http.Client+ // Recorder, when non-nil, receives one observation per Do() call with+ // the inferred op, status bucket, and elapsed time. Production wires+ // this to the BusinessMetrics collector; tests leave it nil.+ Recorder RequestRecorder}type Request struct {@@ -36,6 +47,12 @@ type Request struct {UserID stringRequestID string+ // Op is the high-level operation label fed to the request metric (e.g.+ // "provision", "terminate", "status", "gateway"). Empty defaults to a+ // path-derived bucket — useful for ad-hoc proxy calls that don't have+ // an obvious symbolic name.+ Op string+// Headers carries arbitrary outbound headers that the caller wants// forwarded verbatim. They are applied AFTER the client's defaults// (Accept, Content-Type, X-User-ID, X-Request-ID) so a caller@@ -58,6 +75,7 @@ type Response struct {type Client struct {baseURL stringhttpClient *http.Client+ recorder RequestRecorder}func NewClient(cfg Config) *Client {@@ -72,7 +90,18 @@ func NewClient(cfg Config) *Client {return &Client{baseURL: strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/"),httpClient: httpClient,+ recorder: cfg.Recorder,+ }+}++// SetRecorder lets callers attach a metrics recorder after construction —+// useful for handler.New which builds the cloudruntime client before main.go+// has decided whether the metrics listener is enabled.+func (c *Client) SetRecorder(r RequestRecorder) {+ if c == nil {+ return}+ c.recorder = r}func (c *Client) Enabled() bool {@@ -84,6 +113,17 @@ func (c *Client) Do(ctx context.Context, req Request) (*Response, error) {return nil, ErrDisabled}+ op := inferCloudRuntimeOp(req.Op, req.Method, req.Path)+ start := time.Now()+ resp, err := c.doInner(ctx, req)+ if c.recorder != nil {+ status := requestStatusBucket(resp, err)+ c.recorder.RecordCloudRuntimeRequest(op, status, time.Since(start).Seconds())+ }+ return resp, err+}++func (c *Client) doInner(ctx context.Context, req Request) (*Response, error) {base, err := url.Parse(c.baseURL)if err != nil || base.Scheme == "" || base.Host == "" {return nil, fmt.Errorf("%w: %s", ErrInvalidBaseURL, c.baseURL)@@ -153,3 +193,63 @@ func (c *Client) Do(ctx context.Context, req Request) (*Response, error) {Body: data,}, nil}++// inferCloudRuntimeOp returns the symbolic op label for the request metric.+// Callers may pin Request.Op explicitly; otherwise the bucket is derived+// from the path so existing call sites don't need to change.+func inferCloudRuntimeOp(op, method, path string) string {+ op = strings.ToLower(strings.TrimSpace(op))+ if op != "" {+ return op+ }+ switch {+ case strings.Contains(path, "/billing"):+ return "billing"+ case strings.Contains(path, "/gateway") || strings.Contains(path, "/proxy"):+ return "gateway"+ case strings.Contains(path, "/exec"):+ return "gateway"+ case strings.Contains(path, "/start") || strings.Contains(path, "/provision") || strings.Contains(path, "/nodes/create"):+ return "provision"+ case strings.Contains(path, "/stop") || strings.Contains(path, "/terminate") || strings.Contains(path, "/reboot"):+ return "terminate"+ case strings.Contains(path, "/status") || strings.Contains(path, "/health") || strings.Contains(path, "/ready"):+ return "status"+ case strings.Contains(path, "/nodes"):+ switch strings.ToUpper(strings.TrimSpace(method)) {+ case "POST":+ return "provision"+ case "DELETE":+ return "terminate"+ default:+ return "status"+ }+ }+ return "fleet"+}++// requestStatusBucket maps the (response, error) pair into the fixed metric+// status enum {ok, 4xx, 5xx, timeout, error}.+func requestStatusBucket(resp *Response, err error) string {+ if err != nil {+ // context.DeadlineExceeded surfaces as net.Error.Timeout(); we+ // keep the substring check loose so wrapped timeouts still bucket.+ msg := strings.ToLower(err.Error())+ if strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline exceeded") {+ return "timeout"+ }+ return "error"+ }+ if resp == nil {+ return "error"+ }+ switch {+ case resp.StatusCode >= 200 && resp.StatusCode < 400:+ return "ok"+ case resp.StatusCode >= 400 && resp.StatusCode < 500:+ return "4xx"+ case resp.StatusCode >= 500 && resp.StatusCode < 600:+ return "5xx"+ }+ return "error"+}diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.goindex 7690298ed4..0c639c22c4 100644--- a/server/internal/daemonws/hub.go+++ b/server/internal/daemonws/hub.go@@ -5,6 +5,7 @@ import ("encoding/json""log/slog""net/http"+ "strings""sync""time"@@ -71,6 +72,14 @@ func (c *client) markSeen(eventID string) bool {// the ack and is logged at debug level.type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error)+// MessageKindRecorder is the optional metric hook called once per inbound+// daemon WebSocket frame. kind is the protocol message type with the+// "daemon:" prefix stripped (e.g. "heartbeat") or the literal "unknown" for+// types we don't model. A nil recorder is safely no-op'd.+type MessageKindRecorder interface {+ RecordDaemonWSMessageReceived(kind string)+}+// Hub keeps daemon WebSocket connections indexed by runtime ID. Messages are// best-effort wakeup hints; the daemon still uses HTTP claim for correctness.type Hub struct {@@ -82,6 +91,9 @@ type Hub struct {hbMu sync.RWMutexonHeartbeat HeartbeatHandler++ kindMu sync.RWMutex+ kindRecorder MessageKindRecorder}func NewHub() *Hub {@@ -119,6 +131,27 @@ func (h *Hub) heartbeatHandler() HeartbeatHandler {return h.onHeartbeat}+// SetMessageKindRecorder installs an optional callback fired exactly once per+// inbound daemon WebSocket frame. Used by the metrics layer to count traffic+// by handler kind without hard-coupling the hub to any specific collector.+func (h *Hub) SetMessageKindRecorder(rec MessageKindRecorder) {+ if h == nil {+ return+ }+ h.kindMu.Lock()+ h.kindRecorder = rec+ h.kindMu.Unlock()+}++func (h *Hub) messageKindRecorder() MessageKindRecorder {+ if h == nil {+ return nil+ }+ h.kindMu.RLock()+ defer h.kindMu.RUnlock()+ return h.kindRecorder+}+func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request, identity ClientIdentity) {if len(identity.RuntimeIDs) == 0 {http.Error(w, `{"error":"runtime_ids required"}`, http.StatusBadRequest)@@ -343,8 +376,18 @@ func (c *client) handleFrame(raw []byte) {var msg protocol.Messageif err := json.Unmarshal(raw, &msg); err != nil {slog.Debug("daemon websocket invalid frame", "error", err, "daemon_id", c.identity.DaemonID)+ if rec := c.hub.messageKindRecorder(); rec != nil {+ rec.RecordDaemonWSMessageReceived("invalid")+ }return}+ kind := strings.TrimPrefix(msg.Type, "daemon:")+ if kind == "" {+ kind = "unknown"+ }+ if rec := c.hub.messageKindRecorder(); rec != nil {+ rec.RecordDaemonWSMessageReceived(kind)+ }switch msg.Type {case protocol.EventDaemonHeartbeat:c.handleHeartbeatFrame(msg.Payload)diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex d8be7e5c21..fbf3f9c3b2 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -18,6 +18,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -166,27 +167,27 @@ type AgentTaskResponse struct {// as `## Workspace Context` so every agent running in this workspace —// regardless of issue / chat / autopilot / quick-create — sees the same// shared context. Empty when the workspace owner hasn't set it.- WorkspaceContext string `json:"workspace_context,omitempty"`- Status string `json:"status"`- Priority int32 `json:"priority"`- DispatchedAt *string `json:"dispatched_at"`- StartedAt *string `json:"started_at"`- CompletedAt *string `json:"completed_at"`- Result any `json:"result"`- Error *string `json:"error"`- FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask- Attempt int32 `json:"attempt"`- MaxAttempts int32 `json:"max_attempts"`- ParentTaskID *string `json:"parent_task_id,omitempty"`- Agent *TaskAgentData `json:"agent,omitempty"`- Repos []RepoData `json:"repos,omitempty"`- ProjectID string `json:"project_id,omitempty"` // issue's project, when present- ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context- ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project- CreatedAt string `json:"created_at"`- PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue- PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue- WorkDir string `json:"work_dir,omitempty"` // local working directory pinned for this task; populated once the daemon reports it+ WorkspaceContext string `json:"workspace_context,omitempty"`+ Status string `json:"status"`+ Priority int32 `json:"priority"`+ DispatchedAt *string `json:"dispatched_at"`+ StartedAt *string `json:"started_at"`+ CompletedAt *string `json:"completed_at"`+ Result any `json:"result"`+ Error *string `json:"error"`+ FailureReason string `json:"failure_reason,omitempty"` // see TaskService.MaybeRetryFailedTask+ Attempt int32 `json:"attempt"`+ MaxAttempts int32 `json:"max_attempts"`+ ParentTaskID *string `json:"parent_task_id,omitempty"`+ Agent *TaskAgentData `json:"agent,omitempty"`+ Repos []RepoData `json:"repos,omitempty"`+ ProjectID string `json:"project_id,omitempty"` // issue's project, when present+ ProjectTitle string `json:"project_title,omitempty"` // for surfacing in agent context+ ProjectResources []ProjectResourceData `json:"project_resources,omitempty"` // resources attached to the project+ CreatedAt string `json:"created_at"`+ PriorSessionID string `json:"prior_session_id,omitempty"` // session ID from a previous task on same issue+ PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue+ WorkDir string `json:"work_dir,omitempty"` // local working directory pinned for this task; populated once the daemon reports it// RelativeWorkDir is a privacy-safe display form of WorkDir intended for// the UI. For standard tasks it strips the daemon's workspaces root so// the user sees `<wsUUID>/<taskShort>/workdir`; for local_directory@@ -197,28 +198,28 @@ type AgentTaskResponse struct {// when WorkDir is empty, or when stripping leaves nothing. See// relativeWorkDir() for the full rules. Older clients can still read// WorkDir directly; newer UIs should prefer RelativeWorkDir.- RelativeWorkDir string `json:"relative_work_dir,omitempty"`- TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task- TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment- TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes- TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment- TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author- NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it- NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it- ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks- ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks- ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry- AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks- AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task- AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context- AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt- AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api- AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs- QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks- SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader- SquadName string `json:"squad_name,omitempty"` // display name for the picker squad- ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under- ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context+ RelativeWorkDir string `json:"relative_work_dir,omitempty"`+ TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task+ TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment+ TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes+ TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment+ TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author+ NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it+ NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it+ ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks+ ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks+ ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry+ AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks+ AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task+ AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context+ AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt+ AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api+ AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs+ QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks+ SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader+ SquadName string `json:"squad_name,omitempty"` // display name for the picker squad+ ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context// RequestingUserName + RequestingUserProfileDescription mirror the user// the agent is acting on behalf of (see daemon/types.go). v1 sources them// from the runtime owner so they're populated for daemon runtimes and@@ -746,7 +747,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {actorType, actorID := h.resolveActor(r, ownerID, workspaceID)h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})- h.Analytics.Capture(analytics.AgentCreated(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(ownerID,workspaceID,uuidToString(created.ID),diff --git a/server/internal/handler/agent_template.go b/server/internal/handler/agent_template.goindex 5743ae07f6..5976f31f6f 100644--- a/server/internal/handler/agent_template.go+++ b/server/internal/handler/agent_template.go@@ -17,6 +17,7 @@ import ("github.com/multica-ai/multica/server/internal/agenttmpl""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -126,9 +127,9 @@ type CreateAgentFromTemplateRequest struct {// Optional overrides — let the picker UI customise the template before// creation without forcing a second round-trip to the detail page.// When nil/empty, the template's own values are used.- Description *string `json:"description,omitempty"`- Instructions *string `json:"instructions,omitempty"`- AvatarURL *string `json:"avatar_url,omitempty"`+ Description *string `json:"description,omitempty"`+ Instructions *string `json:"instructions,omitempty"`+ AvatarURL *string `json:"avatar_url,omitempty"`// Workspace skill IDs to attach **in addition to** the template's// skills. The merge dedupes against template skills automatically// (agent_skill INSERT uses ON CONFLICT DO NOTHING).@@ -553,7 +554,7 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.RequestactorType, actorID := h.resolveActor(r, ownerID, workspaceID)h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": resp})- h.Analytics.Capture(analytics.AgentCreated(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(ownerID,workspaceID,uuidToString(agent.ID),@@ -660,4 +661,3 @@ func fetchSkillFromURL(client *http.Client, rawURL string) (*importedSkill, erro}return nil, fmt.Errorf("unknown import source for %s", rawURL)}-diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.goindex f484aff16d..45cb3a6120 100644--- a/server/internal/handler/auth.go+++ b/server/internal/handler/auth.go@@ -22,6 +22,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -51,11 +52,11 @@ var supportedLanguages = map[string]struct{}{}type UserResponse struct {- ID string `json:"id"`- Name string `json:"name"`- Email string `json:"email"`- AvatarURL *string `json:"avatar_url"`- Language *string `json:"language"`+ ID string `json:"id"`+ Name string `json:"name"`+ Email string `json:"email"`+ AvatarURL *string `json:"avatar_url"`+ Language *string `json:"language"`// Pinned IANA tz; nil = no preference (use browser-detected tz).Timezone *string `json:"timezone"`OnboardedAt *string `json:"onboarded_at"`@@ -390,7 +391,7 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {return}if isNew {- h.Analytics.Capture(analytics.Signup(uuidToString(user.ID), user.Email, signupSourceFromRequest(r)))+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.Signup(uuidToString(user.ID), user.Email, signupSourceFromRequest(r)))}tokenString, err := h.issueJWT(user)@@ -560,7 +561,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {if isNew {evt := analytics.Signup(uuidToString(user.ID), user.Email, signupSourceFromRequest(r))evt.Properties["auth_method"] = "google"- h.Analytics.Capture(evt)+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, evt)}// Update name and avatar from Google profile if the user was just createddiff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 242c6b18e9..59d9d6956a 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -11,6 +11,8 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/analytics"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -458,6 +460,13 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {resp := autopilotToResponse(autopilot)h.publish(protocol.EventAutopilotCreated, workspaceID, "member", userID, map[string]any{"autopilot": resp})+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AutopilotCreated(+ userID,+ workspaceID,+ uuidToString(autopilot.ID),+ "manual",+ "manual",+ ))writeJSON(w, http.StatusCreated, resp)}diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.goindex 57db8230df..ce3f0dde4d 100644--- a/server/internal/handler/autopilot_webhook.go+++ b/server/internal/handler/autopilot_webhook.go@@ -1,6 +1,7 @@package handlerimport (+ "context""crypto/hmac""crypto/rand""crypto/sha256"@@ -852,6 +853,7 @@ func (h *Handler) finaliseDeliveryTerminal("error", err,)}+ h.Metrics.RecordWebhookDelivery(h.deliveryProvider(r.Context(), id), status)}// finaliseDeliveryWithRun records a delivery that produced (or was admission-@@ -879,6 +881,23 @@ func (h *Handler) finaliseDeliveryWithRun("error", err,)}+ h.Metrics.RecordWebhookDelivery(h.deliveryProvider(r.Context(), id), status)+}++// deliveryProvider best-effort reads the provider for a delivery id so the+// webhook delivery metric carries useful provenance. On lookup failure we+// fall back to "generic" — the metric must always be incremented exactly+// once per finalise call so the dashboard counts line up with autopilot_run+// volume.+func (h *Handler) deliveryProvider(ctx context.Context, id pgtype.UUID) string {+ if h.Queries == nil {+ return "generic"+ }+ row, err := h.Queries.GetWebhookDelivery(ctx, id)+ if err != nil || row.Provider == "" {+ return "generic"+ }+ return row.Provider}// ── Rate-limit / IP plumbing ────────────────────────────────────────────────diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 5ca59b3f67..e5543bbea4 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -13,6 +13,8 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -475,7 +477,8 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {slog.Warn("failed to touch chat session", "session_id", sessionID, "error", err)}taskContext := h.TaskService.AnalyticsContextForTask(r.Context(), task)- h.Analytics.Capture(analytics.ChatMessageSent(+ platform, _, _ := middleware.ClientMetadataFromContext(r.Context())+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.ChatMessageSent(userID,workspaceID,uuidToString(session.ID),@@ -483,6 +486,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {uuidToString(session.AgentID),taskContext.RuntimeMode,taskContext.Provider,+ platform,))// Broadcast the user message.diff --git a/server/internal/handler/contact_sales.go b/server/internal/handler/contact_sales.goindex d1ba76b982..c6d3ca8807 100644--- a/server/internal/handler/contact_sales.go+++ b/server/internal/handler/contact_sales.go@@ -12,6 +12,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -26,13 +27,13 @@ import (// request body itself is bounded so an attacker can't POST megabytes of// junk into the JSONB-free TEXT columns.const (- contactSalesMaxFirstName = 80- contactSalesMaxLastName = 80- contactSalesMaxEmail = 254- contactSalesMaxCompanyName = 200- contactSalesMaxGoals = 2000- contactSalesHourlyEmailCap = 3- contactSalesBodyLimit = 16 * 1024+ contactSalesMaxFirstName = 80+ contactSalesMaxLastName = 80+ contactSalesMaxEmail = 254+ contactSalesMaxCompanyName = 200+ contactSalesMaxGoals = 2000+ contactSalesHourlyEmailCap = 3+ contactSalesBodyLimit = 16 * 1024)// contactSalesAllowedCompanySize is the closed enum the frontend dropdown@@ -92,14 +93,21 @@ var freeEmailDomains = map[string]struct{}{}type CreateContactSalesRequest struct {- FirstName string `json:"first_name"`- LastName string `json:"last_name"`- BusinessEmail string `json:"business_email"`- CompanyName string `json:"company_name"`- CompanySize string `json:"company_size"`- CountryRegion string `json:"country_region"`- UseCase string `json:"use_case"`- Goals string `json:"goals"`+ FirstName string `json:"first_name"`+ LastName string `json:"last_name"`+ BusinessEmail string `json:"business_email"`+ CompanyName string `json:"company_name"`+ CompanySize string `json:"company_size"`+ CountryRegion string `json:"country_region"`+ UseCase string `json:"use_case"`+ Goals string `json:"goals"`+ // Source identifies where the form was opened from. Frontend+ // enumerates {page, onboarding, agents_page}; the metric label+ // `multica_contact_sales_submitted_total{source=...}` reads it+ // via the metrics.NormalizeContactSalesSource allow-list, anything+ // else collapses to "other". Empty falls back to "page" so legacy+ // clients that don't send the field don't blackhole the metric.+ Source string `json:"source"`ConsentOutreach bool `json:"consent_outreach"`ConsentUpdates bool `json:"consent_updates"`}@@ -219,11 +227,17 @@ func (h *Handler) CreateContactSales(w http.ResponseWriter, r *http.Request) {"use_case", useCase,)...)- h.Analytics.Capture(analytics.ContactSalesSubmitted(+ formSource := strings.TrimSpace(req.Source)+ if formSource == "" {+ formSource = "page"+ }++ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.ContactSalesSubmitted(inquiryID,companySize,countryRegion,useCase,+ formSource,goals != "",))diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 1ab1293c8c..f98062dc4f 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -19,6 +19,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/daemonws"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"@@ -343,7 +344,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {OwnerID: ownerID,})if err != nil {- h.Analytics.Capture(analytics.RuntimeFailed(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(uuidToString(ownerID),req.WorkspaceID,req.DaemonID,@@ -376,7 +377,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {// Inserted is false for normal daemon reconnects/upserts, so// runtime_ready is a first-ready-per-runtime-row signal.if row.Inserted {- h.Analytics.Capture(analytics.RuntimeRegistered(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeRegistered(uuidToString(ownerID),req.WorkspaceID,uuidToString(registered.ID),@@ -386,7 +387,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {req.CLIVersion,))if registered.Status == "online" {- h.Analytics.Capture(analytics.RuntimeReady(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeReady(uuidToString(ownerID),req.WorkspaceID,uuidToString(registered.ID),@@ -560,7 +561,7 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {slog.Warn("deregister: failed to set offline", "runtime_id", rid, "error", err)continue}- h.Analytics.Capture(analytics.RuntimeOffline(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeOffline(uuidToString(rt.OwnerID),wsID,uuidToString(rt.ID),@@ -1832,7 +1833,7 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.Aif marked.CreatorType == "agent" {distinct = "agent:" + distinct}- h.Analytics.Capture(analytics.IssueExecuted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueExecuted(distinct,uuidToString(marked.WorkspaceID),uuidToString(marked.ID),diff --git a/server/internal/handler/feedback.go b/server/internal/handler/feedback.goindex 45c8b9dd95..04360f6215 100644--- a/server/internal/handler/feedback.go+++ b/server/internal/handler/feedback.go@@ -10,6 +10,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -31,8 +32,15 @@ const ()type CreateFeedbackRequest struct {- Message string `json:"message"`- URL string `json:"url"`+ Message string `json:"message"`+ URL string `json:"url"`+ // Kind is the coarse category the feedback picker stamps. The metric+ // label `multica_feedback_submitted_total{kind=...}` reads it via the+ // fixed allow-list in metrics.NormalizeFeedbackKind ("bug", "feature",+ // "general", "praise"); anything outside collapses to "other". Empty /+ // missing falls back to "general" so legacy clients that don't send the+ // field don't blackhole the metric.+ Kind string `json:"kind"`WorkspaceID *string `json:"workspace_id,omitempty"`}@@ -117,9 +125,15 @@ func (h *Handler) CreateFeedback(w http.ResponseWriter, r *http.Request) {slog.Info("feedback submitted", append(logger.RequestAttrs(r), "feedback_id", uuidToString(fb.ID))...)- h.Analytics.Capture(analytics.FeedbackSubmitted(+ kind := strings.TrimSpace(req.Kind)+ if kind == "" {+ kind = "general"+ }++ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.FeedbackSubmitted(userID,uuidToString(fb.WorkspaceID),+ kind,len(message),feedbackImageRegex.MatchString(message),platform,diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 679a050178..f124b428d5 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -525,6 +525,8 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {return}event := r.Header.Get("X-GitHub-Event")+ action := extractGitHubAction(body)+ h.Metrics.RecordGithubEventReceived(event, action)ctx := r.Context()switch event {case "ping":@@ -543,6 +545,19 @@ func (h *Handler) HandleGitHubWebhook(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusAccepted)}+// extractGitHubAction sniffs the top-level "action" field from a webhook+// body without committing to a typed struct (each event has its own shape;+// we just need the verb for the metric label).+func extractGitHubAction(body []byte) string {+ var probe struct {+ Action string `json:"action"`+ }+ if err := json.Unmarshal(body, &probe); err != nil {+ return ""+ }+ return probe.Action+}+func verifyWebhookSignature(secret, header string, body []byte) bool {const prefix = "sha256="if !strings.HasPrefix(header, prefix) {@@ -709,6 +724,12 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {return}+ if state == "merged" {+ if openSeconds := pullRequestMergeSeconds(p.PullRequest.CreatedAt, p.PullRequest.MergedAt); openSeconds > 0 {+ h.Metrics.ObserveGithubPRMergeSeconds(openSeconds)+ }+ }+workspaceID := uuidToString(inst.WorkspaceID)resp := githubPullRequestToResponse(pr)@@ -1023,6 +1044,25 @@ func parseGHTimeRequired(s string) pgtype.Timestamptz {return t}+// pullRequestMergeSeconds returns the open-to-merge latency in seconds, or+// 0 (caller skips) when either timestamp is missing or the merge happened+// before the create timestamp (clock skew safety).+func pullRequestMergeSeconds(createdAt, mergedAt string) float64 {+ created, err := time.Parse(time.RFC3339, createdAt)+ if err != nil {+ return 0+ }+ merged, err := time.Parse(time.RFC3339, mergedAt)+ if err != nil {+ return 0+ }+ delta := merged.Sub(created).Seconds()+ if delta <= 0 {+ return 0+ }+ return delta+}+// extractIdentifiers pulls every "PREFIX-NUMBER" match across the supplied// fields, deduplicating in input order.func extractIdentifiers(parts ...string) []string {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex c788aed6d9..59579697f3 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -20,6 +20,7 @@ import ("github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/internal/service"@@ -106,13 +107,18 @@ type Handler struct {Storage storage.StorageCFSigner *auth.CloudFrontSignerAnalytics analytics.Client- PATCache *auth.PATCache- DaemonTokenCache *auth.DaemonTokenCache- MembershipCache *auth.MembershipCache- WebhookRateLimiter WebhookRateLimiter- WebhookIPRateLimiter WebhookRateLimiter- CloudRuntime cloudRuntimeProxy- cfg Config+ // Metrics is the shared business-metrics collector built by main.go.+ // May be nil in tests / self-hosted with the metrics listener disabled;+ // every Record* method is nil-safe and obsmetrics.RecordEvent treats a+ // nil Metrics as "PostHog only".+ Metrics *obsmetrics.BusinessMetrics+ PATCache *auth.PATCache+ DaemonTokenCache *auth.DaemonTokenCache+ MembershipCache *auth.MembershipCache+ WebhookRateLimiter WebhookRateLimiter+ WebhookIPRateLimiter WebhookRateLimiter+ CloudRuntime cloudRuntimeProxy+ cfg Config}func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config, daemonHubs ...*daemonws.Hub) *Handler {diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex 30427469b7..aaa13518ae 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -11,6 +11,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -154,7 +155,7 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {}h.publish(protocol.EventInvitationCreated, uuidToString(requester.WorkspaceID), "member", userID, eventPayload)- h.Analytics.Capture(analytics.TeamInviteSent(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.TeamInviteSent(uuidToString(requester.UserID),uuidToString(requester.WorkspaceID),email,@@ -472,7 +473,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {if inv.CreatedAt.Valid {daysSinceInvite = int64(time.Since(inv.CreatedAt.Time).Hours() / 24)}- h.Analytics.Capture(analytics.TeamInviteAccepted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.TeamInviteAccepted(userID,wsID,daysSinceInvite,@@ -482,7 +483,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {if onboardedUser.OnboardedAt.Valid {onboardedAt = onboardedUser.OnboardedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00")}- h.Analytics.Capture(analytics.OnboardingCompleted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingCompleted(userID,wsID,analytics.OnboardingPathInviteAccept,diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex e28301f871..cc73ea3184 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -19,6 +19,8 @@ import ("github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -2247,7 +2249,8 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {)}}- h.Analytics.Capture(analytics.IssueCreated(+ platform, _, _ := middleware.ClientMetadataFromContext(r.Context())+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(analyticsActorID,workspaceID,uuidToString(issue.ID),@@ -2255,6 +2258,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {analyticsTaskID,analyticsAutopilotRunID,analyticsSource,+ platform,))// Enqueue agent task when an agent-assigned issue is created.diff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.goindex 3966aec5f2..b05f820edf 100644--- a/server/internal/handler/onboarding.go+++ b/server/internal/handler/onboarding.go@@ -11,6 +11,8 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -113,7 +115,7 @@ func (h *Handler) CompleteOnboarding(w http.ResponseWriter, r *http.Request) {if user.OnboardedAt.Valid {onboardedAt = user.OnboardedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00")}- h.Analytics.Capture(analytics.OnboardingCompleted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingCompleted(userID,req.WorkspaceID,path,@@ -231,9 +233,15 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {// is treated as "incomplete" — worst case we emit once more than// we should, never twice for the same transition.var before questionnaireAnswers+ beforeRaw := []byte("{}")if beforeUser, err := h.Queries.GetUser(r.Context(), parseUUID(userID)); err == nil {- _ = json.Unmarshal(beforeUser.OnboardingQuestionnaire, &before)+ beforeRaw = beforeUser.OnboardingQuestionnaire+ _ = json.Unmarshal(beforeRaw, &before)}+ // firstTouch is true when the user has never written any+ // onboarding state on the server before this PATCH. Used to fire+ // onboarding_started exactly once per user from the server side.+ firstTouch := len(beforeRaw) == 0 || string(beforeRaw) == "null" || string(beforeRaw) == "{}"params := db.PatchUserOnboardingParams{ID: parseUUID(userID)}if req.Questionnaire != nil {@@ -246,10 +254,19 @@ func (h *Handler) PatchOnboarding(w http.ResponseWriter, r *http.Request) {return}+ // Server-side onboarding_started: fire on the first PATCH that+ // actually carries a questionnaire payload. The frontend also+ // emits its own onboarding_started on page open; the two together+ // let Grafana cross-check the funnel against PostHog.+ if firstTouch && req.Questionnaire != nil && len(*req.Questionnaire) > 0 && string(*req.Questionnaire) != "{}" {+ platform, _, _ := middleware.ClientMetadataFromContext(r.Context())+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingStarted(userID, platform))+ }+var after questionnaireAnswers_ = json.Unmarshal(user.OnboardingQuestionnaire, &after)if after.complete() && !before.complete() {- h.Analytics.Capture(analytics.OnboardingQuestionnaireSubmitted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingQuestionnaireSubmitted(userID,[]string(after.Source),after.Role,@@ -323,7 +340,7 @@ func (h *Handler) JoinCloudWaitlist(w http.ResponseWriter, r *http.Request) {return}- h.Analytics.Capture(analytics.CloudWaitlistJoined(userID, reason != ""))+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.CloudWaitlistJoined(userID, reason != ""))writeJSON(w, http.StatusOK, userToResponse(user))}diff --git a/server/internal/handler/onboarding_shim.go b/server/internal/handler/onboarding_shim.goindex fc075bf978..f460cc6b57 100644--- a/server/internal/handler/onboarding_shim.go+++ b/server/internal/handler/onboarding_shim.go@@ -33,6 +33,8 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -308,7 +310,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requif assistantCreated {resp := agentToResponse(assistant)h.publish(protocol.EventAgentCreated, req.WorkspaceID, "member", userID, map[string]any{"agent": resp})- h.Analytics.Capture(analytics.AgentCreated(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.AgentCreated(userID, req.WorkspaceID, uuidToString(assistant.ID),runtime.Provider, runtime.RuntimeMode, onboardingAgentTemplate, isFirstAgent,))@@ -317,9 +319,11 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requprefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)resp := issueToResponse(issue, prefix)h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": resp})- h.Analytics.Capture(analytics.IssueCreated(+ platform, _, _ := middleware.ClientMetadataFromContext(r.Context())+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(userID, req.WorkspaceID, uuidToString(issue.ID),uuidToString(assistant.ID), "", "", analytics.SourceOnboarding,+ platform,))if h.shouldEnqueueAgentTask(r.Context(), issue) {h.TaskService.EnqueueTaskForIssue(r.Context(), issue)@@ -330,7 +334,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requif updatedUser.OnboardedAt.Valid {onboardedAt = updatedUser.OnboardedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00")}- h.Analytics.Capture(analytics.OnboardingCompleted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingCompleted(userID, req.WorkspaceID, analytics.OnboardingPathFull,onboardedAt, updatedUser.CloudWaitlistEmail.Valid,))@@ -455,9 +459,11 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Reprefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)resp := issueToResponse(issue, prefix)h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": resp})- h.Analytics.Capture(analytics.IssueCreated(+ platform2, _, _ := middleware.ClientMetadataFromContext(r.Context())+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(userID, req.WorkspaceID, uuidToString(issue.ID),"", "", "", analytics.SourceOnboarding,+ platform2,))}if firstCompletion {@@ -465,7 +471,7 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Reif updatedUser.OnboardedAt.Valid {onboardedAt = updatedUser.OnboardedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00")}- h.Analytics.Capture(analytics.OnboardingCompleted(+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.OnboardingCompleted(userID, req.WorkspaceID, analytics.OnboardingPathRuntimeSkipped,onboardedAt, updatedUser.CloudWaitlistEmail.Valid,))diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 315a05dc43..719e98b173 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -10,6 +10,8 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/analytics"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -268,6 +270,12 @@ func (h *Handler) CreateSquad(w http.ResponseWriter, r *http.Request) {return}h.publish(protocol.EventSquadCreated, workspaceID, "member", uuidToString(member.UserID), map[string]any{"squad": resp})+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.SquadCreated(+ uuidToString(member.UserID),+ workspaceID,+ uuidToString(squad.ID),+ 1,+ ))writeJSON(w, http.StatusCreated, resp)}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 30988bbb2f..3b4fc3ccbd 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -11,6 +11,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -232,7 +233,7 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {// at whether they have a prior workspace_created event, not stamped at// emit time. Stamping here would race under concurrent creates without// a schema change, and the event stream answers the question exactly.- h.Analytics.Capture(analytics.WorkspaceCreated(userID, wsID))+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.WorkspaceCreated(userID, wsID))slog.Info("workspace created", append(logger.RequestAttrs(r), "workspace_id", wsID, "name", ws.Name, "slug", ws.Slug)...)writeJSON(w, http.StatusCreated, workspaceToResponse(ws))diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex ab1d2db474..548bfae45f 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -36,6 +36,10 @@ type BusinessMetrics struct {activeMu sync.MutexactiveTasks map[string]activeTaskLabels++ // PR3 funnel / community / commercial counters. See business_events.go+ // for the field-level docs and labels.+ events *businessEventMetrics}func NewBusinessMetrics() *BusinessMetrics {@@ -142,13 +146,14 @@ func NewBusinessMetrics() *BusinessMetrics {Help: "Total dispatched or running task leases expired by the scheduler.",}, metricLabels("multica_task_lease_expired_total")),activeTasks: map[string]activeTaskLabels{},+ events: newBusinessEventMetrics(),}m.prewarmFailureReasons()return m}func (m *BusinessMetrics) Collectors() []prometheus.Collector {- return []prometheus.Collector{+ return append([]prometheus.Collector{m.taskEnqueued,m.taskDispatched,m.taskStarted,@@ -165,7 +170,7 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.llmRequests,m.taskQueuedExpired,m.taskLeaseExpired,- }+ }, m.events.collectors()...)}func (m *BusinessMetrics) RecordTaskEnqueued(source, runtimeMode string) {diff --git a/server/internal/metrics/business_events.go b/server/internal/metrics/business_events.gonew file mode 100644index 0000000000..6cd7d95e7d--- /dev/null+++ b/server/internal/metrics/business_events.go@@ -0,0 +1,485 @@+package metrics++import (+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/prometheus/client_golang/prometheus"+)++// PR3: funnel / commercial / community counters paired with PostHog events.+//+// Every PostHog Capture(...) call site goes through metrics.RecordEvent(...)+// (see event_recorder.go) so the two sides cannot drift. Lint test in+// business_pairing_test.go enforces that.++// runtimeReadyBuckets covers cold-start runtime readiness from <1s to ~5min.+// Most provider boots land in 5–60s; the long tail catches stuck pulls.+var runtimeReadyBuckets = []float64{1, 2.5, 5, 10, 30, 60, 120, 300, 600}++// cloudRuntimeRequestBuckets covers outbound Fleet/Gateway calls from sub-100ms+// (status pings) to ~30s (provision). Aligns with cloudruntime.defaultTimeout.+var cloudRuntimeRequestBuckets = []float64{0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30}++// prMergeSecondsBuckets covers PR-open → PR-merged latency from minutes to weeks.+var prMergeSecondsBuckets = []float64{+ 300, 900, 1800,+ 3600, 2 * 3600, 6 * 3600, 12 * 3600,+ 24 * 3600, 2 * 24 * 3600, 7 * 24 * 3600, 30 * 24 * 3600,+}++// businessEventMetrics holds the PR3 collectors. Kept in a separate struct+// so business.go (PR2 task lifecycle / LLM) stays focused; both are exposed+// through the same BusinessMetrics receiver and the same Collectors() slice.+type businessEventMetrics struct {+ signup *prometheus.CounterVec+ workspaceCreated *prometheus.CounterVec+ teamInviteSent *prometheus.CounterVec+ teamInviteAccepted *prometheus.CounterVec+ onboardingStarted *prometheus.CounterVec+ onboardingQuestionnaireSubmit *prometheus.CounterVec+ onboardingCompleted *prometheus.CounterVec+ cloudWaitlistJoined *prometheus.CounterVec+ issueCreated *prometheus.CounterVec+ chatMessageSent *prometheus.CounterVec+ agentCreated *prometheus.CounterVec+ squadCreated *prometheus.CounterVec+ autopilotCreated *prometheus.CounterVec+ issueExecuted *prometheus.CounterVec+ runtimeRegistered *prometheus.CounterVec+ runtimeReady *prometheus.CounterVec+ runtimeReadySeconds *prometheus.HistogramVec+ runtimeFailed *prometheus.CounterVec+ runtimeOffline *prometheus.CounterVec+ daemonWSMessageReceived *prometheus.CounterVec+ autopilotRunStarted *prometheus.CounterVec+ autopilotRunTerminal *prometheus.CounterVec+ autopilotRunSkipped *prometheus.CounterVec+ webhookDelivery *prometheus.CounterVec+ githubEventReceived *prometheus.CounterVec+ githubPRReview *prometheus.CounterVec+ githubPRMergeSeconds prometheus.Histogram+ cloudRuntimeRequest *prometheus.CounterVec+ cloudRuntimeRequestDurationSecs *prometheus.HistogramVec+ feedbackSubmitted *prometheus.CounterVec+ contactSalesSubmitted *prometheus.CounterVec+}++func newBusinessEventMetrics() *businessEventMetrics {+ return &businessEventMetrics{+ signup: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_signup_total",+ Help: "Total user signups (account creations).",+ }, metricLabels("multica_signup_total")),+ workspaceCreated: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_workspace_created_total",+ Help: "Total workspaces created.",+ }, metricLabels("multica_workspace_created_total")),+ teamInviteSent: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_team_invite_sent_total",+ Help: "Total workspace invitations sent.",+ }, metricLabels("multica_team_invite_sent_total")),+ teamInviteAccepted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_team_invite_accepted_total",+ Help: "Total workspace invitations accepted.",+ }, metricLabels("multica_team_invite_accepted_total")),+ onboardingStarted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_onboarding_started_total",+ Help: "Total onboarding flows started.",+ }, metricLabels("multica_onboarding_started_total")),+ onboardingQuestionnaireSubmit: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_onboarding_questionnaire_submitted_total",+ Help: "Total onboarding questionnaires submitted.",+ }, metricLabels("multica_onboarding_questionnaire_submitted_total")),+ onboardingCompleted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_onboarding_completed_total",+ Help: "Total onboarding flows completed.",+ }, metricLabels("multica_onboarding_completed_total")),+ cloudWaitlistJoined: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_cloud_waitlist_joined_total",+ Help: "Total users that joined the cloud waitlist.",+ }, metricLabels("multica_cloud_waitlist_joined_total")),+ issueCreated: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_issue_created_total",+ Help: "Total issues created (any source).",+ }, metricLabels("multica_issue_created_total")),+ chatMessageSent: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_chat_message_sent_total",+ Help: "Total user chat messages sent (excludes agent replies).",+ }, metricLabels("multica_chat_message_sent_total")),+ agentCreated: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_agent_created_total",+ Help: "Total agents created.",+ }, metricLabels("multica_agent_created_total")),+ squadCreated: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_squad_created_total",+ Help: "Total squads created.",+ }, metricLabels("multica_squad_created_total")),+ autopilotCreated: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_autopilot_created_total",+ Help: "Total autopilots created.",+ }, metricLabels("multica_autopilot_created_total")),+ issueExecuted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_issue_executed_total",+ Help: "First task completion per issue (per-issue exactly-once activation keystone).",+ }, metricLabels("multica_issue_executed_total")),+ runtimeRegistered: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_runtime_registered_total",+ Help: "Total first-time runtime registrations.",+ }, metricLabels("multica_runtime_registered_total")),+ runtimeReady: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_runtime_ready_total",+ Help: "Total runtimes that reached ready state.",+ }, metricLabels("multica_runtime_ready_total")),+ runtimeReadySeconds: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Name: "multica_runtime_ready_seconds",+ Help: "Time from runtime registration to ready (seconds).",+ Buckets: runtimeReadyBuckets,+ }, metricLabels("multica_runtime_ready_seconds")),+ runtimeFailed: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_runtime_failed_total",+ Help: "Total runtime failures by canonical reason.",+ }, metricLabels("multica_runtime_failed_total")),+ runtimeOffline: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_runtime_offline_total",+ Help: "Total runtime offline transitions.",+ }, metricLabels("multica_runtime_offline_total")),+ daemonWSMessageReceived: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_daemon_ws_message_received_total",+ Help: "Total daemon WebSocket inbound messages by handler kind.",+ }, metricLabels("multica_daemon_ws_message_received_total")),+ autopilotRunStarted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_autopilot_run_started_total",+ Help: "Total autopilot runs started.",+ }, metricLabels("multica_autopilot_run_started_total")),+ autopilotRunTerminal: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_autopilot_run_terminal_total",+ Help: "Total autopilot runs that reached a terminal status.",+ }, metricLabels("multica_autopilot_run_terminal_total")),+ autopilotRunSkipped: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_autopilot_run_skipped_total",+ Help: "Total autopilot runs that admission-skipped (concurrency / cooldown / other).",+ }, metricLabels("multica_autopilot_run_skipped_total")),+ webhookDelivery: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_webhook_delivery_total",+ Help: "Total inbound webhook deliveries by provider and outcome.",+ }, metricLabels("multica_webhook_delivery_total")),+ githubEventReceived: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_github_event_received_total",+ Help: "Total GitHub webhook events received by event kind and action.",+ }, metricLabels("multica_github_event_received_total")),+ githubPRReview: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_github_pr_review_total",+ Help: "Total GitHub pull request reviews observed by result.",+ }, metricLabels("multica_github_pr_review_total")),+ githubPRMergeSeconds: prometheus.NewHistogram(prometheus.HistogramOpts{+ Name: "multica_github_pr_merge_seconds",+ Help: "Time from PR opened to merged (seconds).",+ Buckets: prMergeSecondsBuckets,+ }),+ cloudRuntimeRequest: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_cloudruntime_request_total",+ Help: "Total outbound cloud runtime requests by op and status bucket.",+ }, metricLabels("multica_cloudruntime_request_total")),+ cloudRuntimeRequestDurationSecs: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Name: "multica_cloudruntime_request_duration_seconds",+ Help: "Outbound cloud runtime request duration (seconds).",+ Buckets: cloudRuntimeRequestBuckets,+ }, metricLabels("multica_cloudruntime_request_duration_seconds")),+ feedbackSubmitted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_feedback_submitted_total",+ Help: "Total in-app feedback submissions.",+ }, metricLabels("multica_feedback_submitted_total")),+ contactSalesSubmitted: prometheus.NewCounterVec(prometheus.CounterOpts{+ Name: "multica_contact_sales_submitted_total",+ Help: "Total contact-sales inquiries submitted.",+ }, metricLabels("multica_contact_sales_submitted_total")),+ }+}++func (e *businessEventMetrics) collectors() []prometheus.Collector {+ if e == nil {+ return nil+ }+ return []prometheus.Collector{+ e.signup,+ e.workspaceCreated,+ e.teamInviteSent,+ e.teamInviteAccepted,+ e.onboardingStarted,+ e.onboardingQuestionnaireSubmit,+ e.onboardingCompleted,+ e.cloudWaitlistJoined,+ e.issueCreated,+ e.chatMessageSent,+ e.agentCreated,+ e.squadCreated,+ e.autopilotCreated,+ e.issueExecuted,+ e.runtimeRegistered,+ e.runtimeReady,+ e.runtimeReadySeconds,+ e.runtimeFailed,+ e.runtimeOffline,+ e.daemonWSMessageReceived,+ e.autopilotRunStarted,+ e.autopilotRunTerminal,+ e.autopilotRunSkipped,+ e.webhookDelivery,+ e.githubEventReceived,+ e.githubPRReview,+ e.githubPRMergeSeconds,+ e.cloudRuntimeRequest,+ e.cloudRuntimeRequestDurationSecs,+ e.feedbackSubmitted,+ e.contactSalesSubmitted,+ }+}++// RecordEvent enqueues a PostHog event AND increments the matching Prometheus+// counter so the two cannot drift. Pass `client = nil` (no PostHog) or+// `m = nil` (no metrics) safely; both sides are best-effort and never block+// the request path.+//+// This is the canonical way to emit any of the funnel / community / commercial+// PostHog events from server code. Direct analytics.Client.Capture(...) with+// an event constructed from analytics.* is rejected by the lint test in+// business_pairing_test.go — see that test for the allow-list of events whose+// Prometheus side is handled by typed BusinessMetrics methods (multica_agent_task_*).+func RecordEvent(client analytics.Client, m *BusinessMetrics, ev analytics.Event) {+ if client != nil {+ client.Capture(ev)+ }+ if m != nil {+ m.IncForEvent(ev)+ }+}++// IncForEvent dispatches an analytics.Event to the matching Prometheus counter.+// Unknown event names are silently ignored — the lint test in+// business_pairing_test.go is responsible for catching missing dispatch entries.+func (m *BusinessMetrics) IncForEvent(ev analytics.Event) {+ if m == nil || m.events == nil {+ return+ }+ switch ev.Name {+ case analytics.EventSignup:+ m.events.signup.WithLabelValues(NormalizeSignupSource(stringProp(ev.Properties, "signup_source"))).Inc()+ case analytics.EventWorkspaceCreated:+ m.events.workspaceCreated.WithLabelValues(NormalizeTaskSource(stringProp(ev.Properties, "source"))).Inc()+ case analytics.EventTeamInviteSent:+ m.events.teamInviteSent.WithLabelValues().Inc()+ case analytics.EventTeamInviteAccepted:+ m.events.teamInviteAccepted.WithLabelValues().Inc()+ case analytics.EventOnboardingStarted:+ m.events.onboardingStarted.WithLabelValues(NormalizePlatform(stringProp(ev.Properties, "platform"))).Inc()+ case analytics.EventOnboardingQuestionnaireSubmit:+ m.events.onboardingQuestionnaireSubmit.WithLabelValues().Inc()+ case analytics.EventOnboardingCompleted:+ m.events.onboardingCompleted.WithLabelValues(NormalizeOnboardingPath(stringProp(ev.Properties, "completion_path"))).Inc()+ case analytics.EventCloudWaitlistJoined:+ m.events.cloudWaitlistJoined.WithLabelValues().Inc()+ case analytics.EventIssueCreated:+ m.events.issueCreated.WithLabelValues(+ NormalizeTaskSource(stringProp(ev.Properties, "source")),+ NormalizePlatform(stringProp(ev.Properties, "platform")),+ ).Inc()+ case analytics.EventChatMessageSent:+ m.events.chatMessageSent.WithLabelValues(NormalizePlatform(stringProp(ev.Properties, "platform"))).Inc()+ case analytics.EventAgentCreated:+ m.events.agentCreated.WithLabelValues(+ NormalizeRuntimeMode(stringProp(ev.Properties, "runtime_mode")),+ NormalizeTaskSource(stringProp(ev.Properties, "source")),+ ).Inc()+ case analytics.EventSquadCreated:+ m.events.squadCreated.WithLabelValues().Inc()+ case analytics.EventAutopilotCreated:+ m.events.autopilotCreated.WithLabelValues(NormalizeAutopilotCadence(stringProp(ev.Properties, "cadence"))).Inc()+ case analytics.EventIssueExecuted:+ m.events.issueExecuted.WithLabelValues(NormalizeTaskSource(stringProp(ev.Properties, "source"))).Inc()+ case analytics.EventRuntimeRegistered:+ m.events.runtimeRegistered.WithLabelValues(+ NormalizeRuntimeMode(stringProp(ev.Properties, "runtime_mode")),+ NormalizeRuntimeProvider(stringProp(ev.Properties, "provider")),+ ).Inc()+ case analytics.EventRuntimeReady:+ runtimeMode := NormalizeRuntimeMode(stringProp(ev.Properties, "runtime_mode"))+ provider := NormalizeRuntimeProvider(stringProp(ev.Properties, "provider"))+ m.events.runtimeReady.WithLabelValues(runtimeMode, provider).Inc()+ if d := int64Prop(ev.Properties, "ready_duration_ms"); d > 0 {+ m.events.runtimeReadySeconds.WithLabelValues(runtimeMode, provider).Observe(float64(d) / 1000.0)+ }+ case analytics.EventRuntimeFailed:+ m.events.runtimeFailed.WithLabelValues(+ NormalizeRuntimeMode(stringProp(ev.Properties, "runtime_mode")),+ NormalizeRuntimeProvider(stringProp(ev.Properties, "provider")),+ NormalizeFailureReason(stringProp(ev.Properties, "failure_reason")),+ boolLabel(boolProp(ev.Properties, "recoverable")),+ ).Inc()+ case analytics.EventRuntimeOffline:+ m.events.runtimeOffline.WithLabelValues(+ NormalizeRuntimeMode(stringProp(ev.Properties, "runtime_mode")),+ NormalizeRuntimeProvider(stringProp(ev.Properties, "provider")),+ ).Inc()+ case analytics.EventAutopilotRunStarted:+ m.events.autopilotRunStarted.WithLabelValues(+ NormalizeAutopilotCadence(stringProp(ev.Properties, "cadence")),+ NormalizeAutopilotTrigger(stringProp(ev.Properties, "trigger_kind")),+ ).Inc()+ case analytics.EventAutopilotRunCompleted:+ m.events.autopilotRunTerminal.WithLabelValues(+ NormalizeAutopilotCadence(stringProp(ev.Properties, "cadence")),+ NormalizeAutopilotTrigger(stringProp(ev.Properties, "trigger_kind")),+ "completed",+ ).Inc()+ case analytics.EventAutopilotRunFailed:+ m.events.autopilotRunTerminal.WithLabelValues(+ NormalizeAutopilotCadence(stringProp(ev.Properties, "cadence")),+ NormalizeAutopilotTrigger(stringProp(ev.Properties, "trigger_kind")),+ "failed",+ ).Inc()+ case analytics.EventFeedbackSubmitted:+ m.events.feedbackSubmitted.WithLabelValues(+ NormalizeFeedbackKind(stringProp(ev.Properties, "kind")),+ NormalizePlatform(stringProp(ev.Properties, "platform")),+ ).Inc()+ case analytics.EventContactSalesSubmitted:+ m.events.contactSalesSubmitted.WithLabelValues(NormalizeContactSalesSource(stringProp(ev.Properties, "form_source"))).Inc()+ default:+ // AgentTask* events are intentionally not dispatched here — their+ // Prometheus side is handled by typed BusinessMetrics.RecordTask*+ // methods that take queue/run/total seconds the analytics event+ // does not carry. The lint test allow-lists those names.+ // Anything else is a missing case and the lint test will fail CI.+ }+}++// ---- non-PostHog Record* helpers (typed; no analytics.Event source) -------++// RecordAutopilotRunSkipped counts an autopilot admission-skip with reason.+func (m *BusinessMetrics) RecordAutopilotRunSkipped(cadence, reason string) {+ if m == nil || m.events == nil {+ return+ }+ m.events.autopilotRunSkipped.WithLabelValues(+ NormalizeAutopilotCadence(cadence),+ NormalizeAutopilotSkipReason(reason),+ ).Inc()+}++// RecordWebhookDelivery counts an inbound webhook outcome.+func (m *BusinessMetrics) RecordWebhookDelivery(provider, status string) {+ if m == nil || m.events == nil {+ return+ }+ m.events.webhookDelivery.WithLabelValues(+ NormalizeWebhookProvider(provider),+ NormalizeWebhookDeliveryStatus(status),+ ).Inc()+}++// RecordGithubEventReceived counts a GitHub webhook event by event kind / action.+func (m *BusinessMetrics) RecordGithubEventReceived(eventKind, action string) {+ if m == nil || m.events == nil {+ return+ }+ m.events.githubEventReceived.WithLabelValues(+ NormalizeGithubEventKind(eventKind),+ NormalizeGithubAction(action),+ ).Inc()+}++// RecordGithubPRReview counts a PR review observation by result.+func (m *BusinessMetrics) RecordGithubPRReview(result string) {+ if m == nil || m.events == nil {+ return+ }+ m.events.githubPRReview.WithLabelValues(NormalizeGithubPRReviewResult(result)).Inc()+}++// ObserveGithubPRMergeSeconds records open→merge latency in seconds.+// Negative or zero values are ignored.+func (m *BusinessMetrics) ObserveGithubPRMergeSeconds(seconds float64) {+ if m == nil || m.events == nil || seconds <= 0 {+ return+ }+ m.events.githubPRMergeSeconds.Observe(seconds)+}++// RecordCloudRuntimeRequest counts an outbound Fleet/Gateway call by op ++// status bucket and observes its duration.+func (m *BusinessMetrics) RecordCloudRuntimeRequest(op, status string, durationSeconds float64) {+ if m == nil || m.events == nil {+ return+ }+ op = NormalizeCloudRuntimeOp(op)+ status = NormalizeCloudRuntimeStatus(status)+ m.events.cloudRuntimeRequest.WithLabelValues(op, status).Inc()+ if durationSeconds >= 0 {+ m.events.cloudRuntimeRequestDurationSecs.WithLabelValues(op).Observe(durationSeconds)+ }+}++// RecordDaemonWSMessageReceived counts an inbound daemon WS message by handler kind.+func (m *BusinessMetrics) RecordDaemonWSMessageReceived(kind string) {+ if m == nil || m.events == nil {+ return+ }+ m.events.daemonWSMessageReceived.WithLabelValues(NormalizeDaemonWSKind(kind)).Inc()+}++// ---- property accessors ---------------------------------------------------++func stringProp(props map[string]any, key string) string {+ if props == nil {+ return ""+ }+ v, ok := props[key]+ if !ok || v == nil {+ return ""+ }+ if s, ok := v.(string); ok {+ return s+ }+ return ""+}++func int64Prop(props map[string]any, key string) int64 {+ if props == nil {+ return 0+ }+ v, ok := props[key]+ if !ok || v == nil {+ return 0+ }+ switch x := v.(type) {+ case int64:+ return x+ case int32:+ return int64(x)+ case int:+ return int64(x)+ case float64:+ return int64(x)+ }+ return 0+}++func boolProp(props map[string]any, key string) bool {+ if props == nil {+ return false+ }+ v, ok := props[key]+ if !ok || v == nil {+ return false+ }+ if b, ok := v.(bool); ok {+ return b+ }+ return false+}++func boolLabel(b bool) string {+ if b {+ return "true"+ }+ return "false"+}diff --git a/server/internal/metrics/business_pairing_test.go b/server/internal/metrics/business_pairing_test.gonew file mode 100644index 0000000000..6f1156a522--- /dev/null+++ b/server/internal/metrics/business_pairing_test.go@@ -0,0 +1,463 @@+package metrics_test++// PR3 lint test: enforces that every PostHog event constant declared in+// server/internal/analytics/events.go has a paired Prometheus counter+// reachable through metrics.RecordEvent — and that every+// h.Analytics.Capture(analytics.<Helper>(...)) call site goes through+// metrics.RecordEvent (no naked Capture allowed except for the AgentTask*+// allow-list whose Prometheus side is handled by typed PR2 methods).++import (+ "go/ast"+ "go/parser"+ "go/token"+ "path/filepath"+ "runtime"+ "sort"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/metrics"+)++// taskMetricEvents are emitted via the typed PR2 methods (RecordTaskEnqueued,+// RecordTaskDispatched, RecordTaskStarted, RecordTaskTerminal, RecordTaskFailed)+// instead of the generic RecordEvent dispatcher because their Prometheus side+// needs queue/run/total seconds that the analytics event does not carry.+//+// These names are still required to be paired — the lint test verifies they+// have a typed RecordTask* hit in service/task.go.+var taskMetricEvents = map[string]string{+ analytics.EventAgentTaskQueued: "RecordTaskEnqueued",+ analytics.EventAgentTaskDispatched: "RecordTaskDispatched",+ analytics.EventAgentTaskStarted: "RecordTaskStarted",+ analytics.EventAgentTaskCompleted: "RecordTaskTerminal",+ analytics.EventAgentTaskFailed: "RecordTaskFailed",+ analytics.EventAgentTaskCancelled: "RecordTaskTerminal",+}++// frontendOnlyEvents are declared in events.go but emitted from the frontend,+// not from server code. They still need a Prometheus counter (so a future+// server-side emission point lights up the same label set) but the server+// has no Capture call site to lint.+var frontendOnlyEvents = map[string]bool{+ analytics.EventOnboardingStarted: true,+}++// TestEveryAnalyticsEventHasPrometheusCounter asserts that every Event*+// constant declared in analytics/events.go either:+// - is dispatched by metrics.IncForEvent (verified by sending a synthetic+// event through RecordEvent and observing a counter delta), or+// - is in the typed taskMetricEvents allow-list.+func TestEveryAnalyticsEventHasPrometheusCounter(t *testing.T) {+ t.Parallel()++ declared := analyticsEventNames(t)++ m := metrics.NewBusinessMetrics()+ for name := range declared {+ if _, allowed := taskMetricEvents[name]; allowed {+ continue+ }+ // Build a minimal event with the required label properties that the+ // dispatcher reads. Since IncForEvent reads via stringProp helpers,+ // a nil Properties map is acceptable for events with empty label+ // sets and is normalised by the helpers for the others.+ ev := analytics.Event{+ Name: name,+ DistinctID: "test",+ Properties: defaultPropsForEvent(name),+ }+ ok := dispatchIncrementsCounter(m, ev)+ if !ok {+ t.Errorf("analytics.%s (%q) is not paired with a Prometheus counter via metrics.IncForEvent — add a case in business_events.go", constantNameForEvent(name), name)+ }+ }+}++// TestNoNakedAnalyticsCaptureInHandlersOrServices walks every Go file under+// server/internal/handler and server/internal/service and asserts that every+// `<x>.Analytics.Capture(analytics.<Helper>(...))` call has been migrated to+// metrics.RecordEvent. The only exception is the body of+// `service/task.go`'s captureTaskEvent function — a function-granular+// allow-list, not a whole-file one, so any new naked Capture added to the+// same file fails CI.+func TestNoNakedAnalyticsCaptureInHandlersOrServices(t *testing.T) {+ t.Parallel()++ roots := []string{+ filepath.Join(repoRoot(t), "internal", "handler"),+ filepath.Join(repoRoot(t), "internal", "service"),+ filepath.Join(repoRoot(t), "cmd", "server"),+ }+ // allowedFunctions is keyed by absolute file path, valued by the set of+ // function names whose bodies are allowed to call Analytics.Capture+ // directly. Granularity is per-function, not per-file: anything else+ // in the same file still trips the check.+ allowedFunctions := map[string]map[string]struct{}{+ filepath.Join(repoRoot(t), "internal", "service", "task.go"): {+ "captureTaskEvent": {},+ },+ }++ var offenders []string+ fset := token.NewFileSet()+ for _, root := range roots {+ matches, err := filepath.Glob(filepath.Join(root, "*.go"))+ if err != nil {+ t.Fatalf("glob %s: %v", root, err)+ }+ for _, file := range matches {+ if strings.HasSuffix(file, "_test.go") {+ continue+ }+ f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution)+ if err != nil {+ t.Fatalf("parse %s: %v", file, err)+ }+ fileAllowedFns := allowedFunctions[file]+ for _, decl := range f.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok {+ continue+ }+ if _, allowed := fileAllowedFns[fn.Name.Name]; allowed {+ continue+ }+ if fn.Body == nil {+ continue+ }+ ast.Inspect(fn.Body, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ if !isAnalyticsCapture(call) {+ return true+ }+ offenders = append(offenders, fset.Position(call.Pos()).String()+" (in "+fn.Name.Name+")")+ return true+ })+ }+ }+ }++ if len(offenders) > 0 {+ sort.Strings(offenders)+ t.Errorf("found %d naked Analytics.Capture(...) calls — wrap them in metrics.RecordEvent so the Prometheus and PostHog sides cannot drift:\n %s", len(offenders), strings.Join(offenders, "\n "))+ }+}++// TestEveryAnalyticsRecordEventTakesAnalyticsHelper enforces the inverse of+// TestNoNakedAnalyticsCaptureInHandlersOrServices: every call site that+// DOES go through metrics.RecordEvent must take an analytics.* event helper+// as its third argument. Local idents are accepted only when def-use+// tracking inside the same function body proves the value originated from+// an `analytics.<Helper>(...)` call — bare strings or unresolved values+// fail CI.+func TestEveryAnalyticsRecordEventTakesAnalyticsHelper(t *testing.T) {+ t.Parallel()++ roots := []string{+ filepath.Join(repoRoot(t), "internal", "handler"),+ filepath.Join(repoRoot(t), "internal", "service"),+ filepath.Join(repoRoot(t), "cmd", "server"),+ }++ var offenders []string+ fset := token.NewFileSet()+ for _, root := range roots {+ matches, err := filepath.Glob(filepath.Join(root, "*.go"))+ if err != nil {+ t.Fatalf("glob %s: %v", root, err)+ }+ for _, file := range matches {+ if strings.HasSuffix(file, "_test.go") {+ continue+ }+ f, err := parser.ParseFile(fset, file, nil, parser.SkipObjectResolution)+ if err != nil {+ t.Fatalf("parse %s: %v", file, err)+ }+ for _, decl := range f.Decls {+ fn, ok := decl.(*ast.FuncDecl)+ if !ok || fn.Body == nil {+ continue+ }+ analyticsLocals := analyticsBackedIdents(fn.Body)+ ast.Inspect(fn.Body, func(n ast.Node) bool {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ if !isMetricsRecordEvent(call) {+ return true+ }+ if len(call.Args) < 3 {+ offenders = append(offenders, fset.Position(call.Pos()).String()+" (RecordEvent must be called with 3 args: client, metrics, event)")+ return true+ }+ ev := call.Args[2]+ if analyticsHelperCall(ev) {+ return true+ }+ if id, ok := ev.(*ast.Ident); ok {+ if _, traced := analyticsLocals[id.Name]; traced {+ return true+ }+ offenders = append(offenders, fset.Position(call.Pos()).String()+" (third arg "+id.Name+" was not assigned from an analytics.* helper in this function)")+ return true+ }+ offenders = append(offenders, fset.Position(call.Pos()).String()+" (third arg must be an analytics.* helper call or a local assigned from one)")+ return true+ })+ }+ }+ }++ if len(offenders) > 0 {+ sort.Strings(offenders)+ t.Errorf("metrics.RecordEvent call sites must take an analytics.* event:\n %s", strings.Join(offenders, "\n "))+ }+}++// analyticsBackedIdents walks a function body and returns the set of local+// identifiers whose initial value came from an analytics.<Helper>(...) call.+// Both `:=` short declarations and `=` assignments at any nesting depth are+// recognised. The set is conservative — re-assignments to non-analytics+// values keep the ident in the set (we only track the originating+// definition); call sites that cared could rewrite to use the helper inline.+//+// KNOWN LIMITATION (tracked as PR3 follow-up; see PR description):+// matching is by ident NAME, not by SSA def-use. A pathological function+// that shadows an analytics-backed name with a non-analytics binding in a+// nested scope (e.g. an `if`/`for` re-declaration via `:=`) would still+// pass this check, because the outer-scope name is in the allow-set. This+// is rare in practice — every current call site assigns once at the same+// scope as the RecordEvent call — but a future hardening pass should+// switch to a real go/types or go/ssa walk so the lint is type-aware+// rather than name-aware.+func analyticsBackedIdents(body *ast.BlockStmt) map[string]struct{} {+ out := map[string]struct{}{}+ if body == nil {+ return out+ }+ ast.Inspect(body, func(n ast.Node) bool {+ switch stmt := n.(type) {+ case *ast.AssignStmt:+ // Match either lhs[i] = analytics.X(...) or lhs[i], _ := analytics.X(...).+ if len(stmt.Rhs) == 0 {+ return true+ }+ for i, lhs := range stmt.Lhs {+ if i >= len(stmt.Rhs) {+ // Multi-return-from-single-call shape (e.g. a, b := f())+ // — there is exactly one Rhs and we can't tell which+ // returned position the ident binds without type info.+ // Fall back to checking the single Rhs.+ if len(stmt.Rhs) == 1 && analyticsHelperCall(stmt.Rhs[0]) {+ if id, ok := lhs.(*ast.Ident); ok {+ out[id.Name] = struct{}{}+ }+ }+ continue+ }+ if id, ok := lhs.(*ast.Ident); ok && analyticsHelperCall(stmt.Rhs[i]) {+ out[id.Name] = struct{}{}+ }+ }+ case *ast.ValueSpec:+ // `var x = analytics.X(...)` and the like.+ for i, name := range stmt.Names {+ if i < len(stmt.Values) && analyticsHelperCall(stmt.Values[i]) {+ out[name.Name] = struct{}{}+ }+ }+ }+ return true+ })+ return out+}++// ---- helpers --------------------------------------------------------------++// repoRoot returns the absolute path to server/. The test sources live in+// server/internal/metrics/ so two parents up is the server root.+func repoRoot(t *testing.T) string {+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatalf("runtime.Caller failed")+ }+ // .../server/internal/metrics/business_pairing_test.go → .../server+ return filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))+}++// analyticsEventNames parses analytics/events.go and returns every Event*+// constant value (the literal string passed to PostHog).+func analyticsEventNames(t *testing.T) map[string]struct{} {+ t.Helper()++ path := filepath.Join(repoRoot(t), "internal", "analytics", "events.go")+ fset := token.NewFileSet()+ f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)+ if err != nil {+ t.Fatalf("parse %s: %v", path, err)+ }++ out := map[string]struct{}{}+ for _, decl := range f.Decls {+ gen, ok := decl.(*ast.GenDecl)+ if !ok || gen.Tok != token.CONST {+ continue+ }+ for _, spec := range gen.Specs {+ vs, ok := spec.(*ast.ValueSpec)+ if !ok || len(vs.Values) == 0 {+ continue+ }+ for i, name := range vs.Names {+ if !strings.HasPrefix(name.Name, "Event") {+ continue+ }+ lit, ok := vs.Values[i].(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING {+ continue+ }+ out[strings.Trim(lit.Value, "\"")] = struct{}{}+ }+ }+ }+ if len(out) == 0 {+ t.Fatalf("no Event* constants found in %s", path)+ }+ return out+}++// constantNameForEvent reverse-maps an event string to its Go constant name+// for nicer error messages. Stable for the constants we ship.+func constantNameForEvent(name string) string {+ parts := strings.Split(name, "_")+ for i, p := range parts {+ if len(p) == 0 {+ continue+ }+ parts[i] = strings.ToUpper(p[:1]) + p[1:]+ }+ return "Event" + strings.Join(parts, "")+}++// dispatchIncrementsCounter sends ev through RecordEvent (with a noop+// PostHog client) and returns true when at least one Prometheus counter+// receives a non-zero increment. We use a fresh BusinessMetrics per event+// so a leftover prewarm value from another counter cannot mask a missing+// dispatch case.+func dispatchIncrementsCounter(m *metrics.BusinessMetrics, ev analytics.Event) bool {+ before := metrics.SumAllCounters(m)+ metrics.RecordEvent(analytics.NoopClient{}, m, ev)+ after := metrics.SumAllCounters(m)+ return after > before+}++// defaultPropsForEvent returns a properties map populated with the label+// values the dispatcher reads, so the synthetic test event lights up its+// matching counter without relying on the analytics helper plumbing.+func defaultPropsForEvent(name string) map[string]any {+ switch name {+ case analytics.EventSignup:+ return map[string]any{"signup_source": "test"}+ case analytics.EventWorkspaceCreated:+ return map[string]any{"source": "manual"}+ case analytics.EventOnboardingStarted:+ return map[string]any{"platform": "web"}+ case analytics.EventOnboardingCompleted:+ return map[string]any{"completion_path": "full"}+ case analytics.EventIssueCreated:+ return map[string]any{"source": "manual", "platform": "web"}+ case analytics.EventChatMessageSent:+ return map[string]any{"platform": "web"}+ case analytics.EventAgentCreated:+ return map[string]any{"runtime_mode": "local", "source": "manual"}+ case analytics.EventAutopilotCreated:+ return map[string]any{"cadence": "manual"}+ case analytics.EventIssueExecuted:+ return map[string]any{"source": "manual"}+ case analytics.EventRuntimeRegistered, analytics.EventRuntimeReady, analytics.EventRuntimeOffline:+ return map[string]any{"runtime_mode": "local", "provider": "claude"}+ case analytics.EventRuntimeFailed:+ return map[string]any{"runtime_mode": "local", "provider": "claude", "failure_reason": "unknown", "recoverable": false}+ case analytics.EventAutopilotRunStarted, analytics.EventAutopilotRunCompleted, analytics.EventAutopilotRunFailed:+ return map[string]any{"cadence": "manual", "trigger_kind": "manual"}+ case analytics.EventFeedbackSubmitted:+ return map[string]any{"kind": "general", "platform": "web"}+ case analytics.EventContactSalesSubmitted:+ return map[string]any{"form_source": "page"}+ }+ return map[string]any{}+}++func isAnalyticsCapture(call *ast.CallExpr) bool {+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return false+ }+ if sel.Sel == nil || sel.Sel.Name != "Capture" {+ return false+ }+ // Receiver must be a selector ending in `.Analytics`.+ rec, ok := sel.X.(*ast.SelectorExpr)+ if !ok {+ return false+ }+ if rec.Sel == nil || rec.Sel.Name != "Analytics" {+ return false+ }+ // Must be passing an analytics helper or a local built from one — but+ // the lint principle is "no direct Capture", so any shape fails.+ return true+}++// isMetricsRecordEvent reports whether call is a metrics.RecordEvent+// invocation. Recognises the two import aliases used in this codebase:+// `obsmetrics` (everywhere outside the metrics package itself) and the+// natural package name `metrics`.+//+// KNOWN LIMITATION (tracked as PR3 follow-up; see PR description):+// the alias set is HARD-CODED. A future caller that imports the metrics+// package under a third alias (`mx "..."`, etc.) would slip past this+// check. The follow-up plan is to walk the file's import declarations+// and resolve the alias for `server/internal/metrics` per-file, so any+// alias works as long as the canonical import path matches. We leave it+// hard-coded here because every current import in handler/, service/,+// and cmd/server/ uses one of the two names, and goimports/`gofmt`+// guidance keeps it that way.+func isMetricsRecordEvent(call *ast.CallExpr) bool {+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return false+ }+ if sel.Sel == nil || sel.Sel.Name != "RecordEvent" {+ return false+ }+ pkg, ok := sel.X.(*ast.Ident)+ if !ok {+ return false+ }+ return pkg.Name == "obsmetrics" || pkg.Name == "metrics"+}++func analyticsHelperCall(expr ast.Expr) bool {+ call, ok := expr.(*ast.CallExpr)+ if !ok {+ return false+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok {+ return false+ }+ pkg, ok := sel.X.(*ast.Ident)+ if !ok {+ return false+ }+ return pkg.Name == "analytics" && sel.Sel != nil && len(sel.Sel.Name) > 0+}diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex c1c560efe0..73aab0bfb6 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -7,6 +7,7 @@ import ("github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/testutil"+ "github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/pkg/taskfailure")@@ -109,6 +110,41 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordLLMUsage("issue", "local", "codex", "gpt-5.4", 1, 1, 1, 1)m.RecordLLMUsage("issue", "local", "custom-provider", "custom-model", 1, 0, 0, 0)+ // PR3 funnel / community / commercial events. Drive every counter+ // with one synthetic value so the gather loop below sees the family.+ exerciseEvent(m, analytics.EventSignup, map[string]any{"signup_source": "test"})+ exerciseEvent(m, analytics.EventWorkspaceCreated, map[string]any{"source": "manual"})+ exerciseEvent(m, analytics.EventTeamInviteSent, nil)+ exerciseEvent(m, analytics.EventTeamInviteAccepted, nil)+ exerciseEvent(m, analytics.EventOnboardingStarted, map[string]any{"platform": "web"})+ exerciseEvent(m, analytics.EventOnboardingQuestionnaireSubmit, nil)+ exerciseEvent(m, analytics.EventOnboardingCompleted, map[string]any{"completion_path": "full"})+ exerciseEvent(m, analytics.EventCloudWaitlistJoined, nil)+ exerciseEvent(m, analytics.EventIssueCreated, map[string]any{"source": "manual", "platform": "web"})+ exerciseEvent(m, analytics.EventChatMessageSent, map[string]any{"platform": "web"})+ exerciseEvent(m, analytics.EventAgentCreated, map[string]any{"runtime_mode": "local", "source": "manual"})+ exerciseEvent(m, analytics.EventSquadCreated, nil)+ exerciseEvent(m, analytics.EventAutopilotCreated, map[string]any{"cadence": "manual"})+ exerciseEvent(m, analytics.EventIssueExecuted, map[string]any{"source": "manual"})+ exerciseEvent(m, analytics.EventRuntimeRegistered, map[string]any{"runtime_mode": "local", "provider": "claude"})+ exerciseEvent(m, analytics.EventRuntimeReady, map[string]any{"runtime_mode": "local", "provider": "claude", "ready_duration_ms": int64(1000)})+ exerciseEvent(m, analytics.EventRuntimeFailed, map[string]any{"runtime_mode": "local", "provider": "claude", "failure_reason": "timeout", "recoverable": true})+ exerciseEvent(m, analytics.EventRuntimeOffline, map[string]any{"runtime_mode": "local", "provider": "claude"})+ exerciseEvent(m, analytics.EventAutopilotRunStarted, map[string]any{"cadence": "manual", "trigger_kind": "manual"})+ exerciseEvent(m, analytics.EventAutopilotRunCompleted, map[string]any{"cadence": "manual", "trigger_kind": "manual"})+ exerciseEvent(m, analytics.EventAutopilotRunFailed, map[string]any{"cadence": "manual", "trigger_kind": "manual"})+ exerciseEvent(m, analytics.EventFeedbackSubmitted, map[string]any{"kind": "general", "platform": "web"})+ exerciseEvent(m, analytics.EventContactSalesSubmitted, map[string]any{"form_source": "page"})++ // Direct Record* helpers (no PostHog event source).+ m.RecordAutopilotRunSkipped("manual", "throttled")+ m.RecordWebhookDelivery("github", "dispatched")+ m.RecordGithubEventReceived("pull_request", "opened")+ m.RecordGithubPRReview("approved")+ m.ObserveGithubPRMergeSeconds(120)+ m.RecordCloudRuntimeRequest("provision", "ok", 0.5)+ m.RecordDaemonWSMessageReceived("heartbeat")+families, err := registry.Gather()if err != nil {t.Fatalf("gather: %v", err)@@ -123,3 +159,10 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {}}}++func exerciseEvent(m *BusinessMetrics, name string, props map[string]any) {+ if props == nil {+ props = map[string]any{}+ }+ m.IncForEvent(analytics.Event{Name: name, Properties: props})+}diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 6a0ce1721e..04d185b582 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -16,6 +16,21 @@ const (labelTokenType = "token_type"labelModel = "model"labelModelAlias = "model_alias"++ // PR3 labels (funnel / community / commercial).+ labelSignupSource = "signup_source"+ labelPlatform = "platform"+ labelPath = "path"+ labelCadence = "cadence"+ labelTriggerKind = "trigger_kind"+ labelReason = "reason"+ labelRecoverable = "recoverable"+ labelKind = "kind"+ labelStatus = "status"+ labelEventKind = "event_kind"+ labelAction = "action"+ labelResult = "result"+ labelOp = "op")var businessMetricLabels = map[string][]string{@@ -35,6 +50,38 @@ var businessMetricLabels = map[string][]string{"multica_llm_request_total": {labelProvider, labelModel, labelRuntimeMode},"multica_task_queued_expired_total": {labelSource, labelRuntimeMode},"multica_task_lease_expired_total": {labelSource},++ // PR3 funnel / community / commercial.+ "multica_signup_total": {labelSignupSource},+ "multica_workspace_created_total": {labelSource},+ "multica_team_invite_sent_total": {},+ "multica_team_invite_accepted_total": {},+ "multica_onboarding_started_total": {labelPlatform},+ "multica_onboarding_questionnaire_submitted_total": {},+ "multica_onboarding_completed_total": {labelPath},+ "multica_cloud_waitlist_joined_total": {},+ "multica_issue_created_total": {labelSource, labelPlatform},+ "multica_chat_message_sent_total": {labelPlatform},+ "multica_agent_created_total": {labelRuntimeMode, labelSource},+ "multica_squad_created_total": {},+ "multica_autopilot_created_total": {labelCadence},+ "multica_issue_executed_total": {labelSource},+ "multica_runtime_registered_total": {labelRuntimeMode, labelProvider},+ "multica_runtime_ready_total": {labelRuntimeMode, labelProvider},+ "multica_runtime_ready_seconds": {labelRuntimeMode, labelProvider},+ "multica_runtime_failed_total": {labelRuntimeMode, labelProvider, labelFailureReason, labelRecoverable},+ "multica_runtime_offline_total": {labelRuntimeMode, labelProvider},+ "multica_daemon_ws_message_received_total": {labelKind},+ "multica_autopilot_run_started_total": {labelCadence, labelTriggerKind},+ "multica_autopilot_run_terminal_total": {labelCadence, labelTriggerKind, labelTerminalStatus},+ "multica_autopilot_run_skipped_total": {labelCadence, labelReason},+ "multica_webhook_delivery_total": {labelProvider, labelStatus},+ "multica_github_event_received_total": {labelEventKind, labelAction},+ "multica_github_pr_review_total": {labelResult},+ "multica_cloudruntime_request_total": {labelOp, labelStatus},+ "multica_cloudruntime_request_duration_seconds": {labelOp},+ "multica_feedback_submitted_total": {labelKind, labelPlatform},+ "multica_contact_sales_submitted_total": {labelSource},}var forbiddenMetricLabels = map[string]struct{}{diff --git a/server/internal/metrics/labels_pr3.go b/server/internal/metrics/labels_pr3.gonew file mode 100644index 0000000000..2e086534a2--- /dev/null+++ b/server/internal/metrics/labels_pr3.go@@ -0,0 +1,396 @@+package metrics++import (+ "encoding/json"+ "strings"+)++// PR3 normalizers. All inputs go through fixed allow-lists so a misbehaving+// caller cannot inflate metric cardinality. Every "unknown" / "other" bucket+// keeps the series count bounded even under enum drift.++var (+ knownPlatforms = map[string]string{+ "server": "server",+ "web": "web",+ "desktop": "desktop",+ "cli": "cli",+ "mobile": "mobile",+ "ios": "ios",+ "unknown": "unknown",+ }++ // knownSignupSources is the fixed bucket set for the signup_source+ // metric label. The PostHog event still ships the raw cookie value+ // so analytics keeps the long tail; the Prometheus side gets the+ // bucketed version so cardinality stays bounded even if a misbehaving+ // frontend writes a unique-per-visitor cookie. Empty cookie collapses+ // to "direct" (no attribution = direct visit), unknown channels to+ // "other".+ knownSignupSources = map[string]string{+ "direct": "direct",+ "google": "google",+ "bing": "bing",+ "duckduckgo": "duckduckgo",+ "twitter": "twitter",+ "x": "twitter",+ "linkedin": "linkedin",+ "facebook": "facebook",+ "instagram": "instagram",+ "github": "github",+ "gitlab": "gitlab",+ "hacker_news": "hacker_news",+ "hackernews": "hacker_news",+ "reddit": "reddit",+ "youtube": "youtube",+ "discord": "discord",+ "slack": "slack",+ "product_hunt": "product_hunt",+ "producthunt": "product_hunt",+ "medium": "medium",+ "dev_to": "dev_to",+ "devto": "dev_to",+ "email": "email",+ "newsletter": "email",+ "organic": "organic",+ "referral": "referral",+ "partner": "partner",+ "affiliate": "affiliate",+ "ad": "paid",+ "ads": "paid",+ "paid": "paid",+ "cpc": "paid",+ "sem": "paid",+ "other": "other",+ }++ knownOnboardingPaths = map[string]string{+ "full": "full",+ "runtime_skipped": "runtime_skipped",+ "cloud_waitlist": "cloud_waitlist",+ "skip_existing": "skip_existing",+ "invite_accept": "invite_accept",+ "unknown": "unknown",+ }++ knownAutopilotCadences = map[string]string{+ "hourly": "hourly",+ "daily": "daily",+ "weekly": "weekly",+ "monthly": "monthly",+ "manual": "manual",+ "webhook": "webhook",+ "unknown": "unknown",+ }++ knownAutopilotTriggers = map[string]string{+ "schedule": "schedule",+ "webhook": "webhook",+ "manual": "manual",+ "unknown": "unknown",+ }++ knownAutopilotSkipReasons = map[string]string{+ "already_running": "already_running",+ "recent_run": "recent_run",+ "runtime_offline": "runtime_offline",+ "throttled": "throttled",+ "max_concurrency": "max_concurrency",+ "trigger_disabled": "trigger_disabled",+ "signature_invalid": "signature_invalid",+ "unknown": "unknown",+ "other": "other",+ }++ knownWebhookProviders = map[string]string{+ "github": "github",+ "generic": "generic",+ "gitlab": "gitlab",+ "stripe": "stripe",+ "other": "other",+ }++ knownWebhookDeliveryStatuses = map[string]string{+ "queued": "queued",+ "dispatched": "dispatched",+ "failed": "failed",+ "rejected": "rejected",+ "ignored": "ignored",+ "duplicate": "duplicate",+ "other": "other",+ }++ knownGithubEventKinds = map[string]string{+ "pull_request": "pull_request",+ "pull_request_review": "pull_request_review",+ "issues": "issues",+ "issue_comment": "issue_comment",+ "push": "push",+ "installation": "installation",+ "installation_repositories": "installation_repositories",+ "check_run": "check_run",+ "check_suite": "check_suite",+ "ping": "ping",+ "other": "other",+ }++ knownGithubActions = map[string]string{+ "opened": "opened",+ "closed": "closed",+ "reopened": "reopened",+ "merged": "merged",+ "synchronize": "synchronize",+ "edited": "edited",+ "submitted": "submitted",+ "created": "created",+ "deleted": "deleted",+ "labeled": "labeled",+ "unlabeled": "unlabeled",+ "assigned": "assigned",+ "unassigned": "unassigned",+ "requested": "requested",+ "completed": "completed",+ "none": "none",+ "other": "other",+ }++ knownGithubPRReviewResults = map[string]string{+ "approved": "approved",+ "changes_requested": "changes_requested",+ "commented": "commented",+ "dismissed": "dismissed",+ "other": "other",+ }++ knownCloudRuntimeOps = map[string]string{+ "provision": "provision",+ "terminate": "terminate",+ "status": "status",+ "gateway": "gateway",+ "billing": "billing",+ "fleet": "fleet",+ "other": "other",+ }++ knownCloudRuntimeStatuses = map[string]string{+ "ok": "ok",+ "4xx": "4xx",+ "5xx": "5xx",+ "timeout": "timeout",+ "error": "error",+ }++ knownDaemonWSKinds = map[string]string{+ "heartbeat": "heartbeat",+ "task_claim": "task_claim",+ "task_complete": "task_complete",+ "task_usage": "task_usage",+ "task_progress": "task_progress",+ "task_messages": "task_messages",+ "log": "log",+ "other": "other",+ }++ knownFeedbackKinds = map[string]string{+ "bug": "bug",+ "feature": "feature",+ "general": "general",+ "praise": "praise",+ "other": "other",+ }++ knownContactSalesSources = map[string]string{+ "page": "page",+ "onboarding": "onboarding",+ "agents_page": "agents_page",+ "unknown": "unknown",+ "other": "other",+ }+)++func normalizeFromAllowList(value string, allowList map[string]string, fallback string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ if normalized, ok := allowList[value]; ok {+ return normalized+ }+ return fallback+}++func NormalizePlatform(value string) string {+ return normalizeFromAllowList(value, knownPlatforms, "unknown")+}++// NormalizeSignupSource buckets the raw multica_signup_source cookie payload+// into the fixed signup channel allow-list. The cookie carries free-form+// JSON (utm_source / utm_medium / referrer) on the PostHog side; here we+// only need a bounded label, so we look at utm_source / source / referrer+// fields when present, otherwise the bare string. Empty -> "direct".+// Anything not in the allow-list -> "other".+func NormalizeSignupSource(value string) string {+ value = strings.TrimSpace(value)+ if value == "" {+ return "direct"+ }+ // JSON shape: {"utm_source":"...","utm_medium":"...","referrer":"..."}+ if strings.HasPrefix(value, "{") {+ var parsed map[string]any+ if err := json.Unmarshal([]byte(value), &parsed); err == nil {+ for _, key := range []string{"utm_source", "source", "referrer", "ref"} {+ if raw, ok := parsed[key]; ok {+ if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" {+ value = s+ break+ }+ }+ }+ }+ }+ return normalizeFromAllowList(canonicaliseSignupChannel(value), knownSignupSources, "other")+}++// canonicaliseSignupChannel collapses the raw signup-source string into a+// shape the allow-list can match: lowercase, trimmed, host-only for URL-ish+// values, and with a few obvious aliases unified ("twitter.com" -> "twitter").+// We deliberately keep this defensive — the cookie is set client-side, so any+// shape is possible.+func canonicaliseSignupChannel(value string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ if value == "" {+ return ""+ }+ // Strip an optional URL scheme so "https://twitter.com/foo" -> "twitter.com/foo".+ for _, scheme := range []string{"https://", "http://", "//"} {+ if strings.HasPrefix(value, scheme) {+ value = strings.TrimPrefix(value, scheme)+ break+ }+ }+ // Take just the host segment.+ if i := strings.IndexAny(value, "/?#"); i >= 0 {+ value = value[:i]+ }+ value = strings.TrimPrefix(value, "www.")+ // Map well-known hostnames to their channel bucket.+ hostAliases := map[string]string{+ "google.com": "google",+ "google.co.uk": "google",+ "bing.com": "bing",+ "duckduckgo.com": "duckduckgo",+ "twitter.com": "twitter",+ "x.com": "twitter",+ "t.co": "twitter",+ "linkedin.com": "linkedin",+ "lnkd.in": "linkedin",+ "facebook.com": "facebook",+ "fb.com": "facebook",+ "instagram.com": "instagram",+ "github.com": "github",+ "gitlab.com": "gitlab",+ "news.ycombinator.com": "hacker_news",+ "reddit.com": "reddit",+ "old.reddit.com": "reddit",+ "youtube.com": "youtube",+ "youtu.be": "youtube",+ "discord.com": "discord",+ "discord.gg": "discord",+ "slack.com": "slack",+ "producthunt.com": "product_hunt",+ "medium.com": "medium",+ "dev.to": "dev_to",+ }+ if mapped, ok := hostAliases[value]; ok {+ return mapped+ }+ return value+}++func NormalizeOnboardingPath(value string) string {+ return normalizeFromAllowList(value, knownOnboardingPaths, "unknown")+}++func NormalizeAutopilotCadence(value string) string {+ return normalizeFromAllowList(value, knownAutopilotCadences, "unknown")+}++func NormalizeAutopilotTrigger(value string) string {+ return normalizeFromAllowList(value, knownAutopilotTriggers, "unknown")+}++func NormalizeAutopilotSkipReason(value string) string {+ return normalizeFromAllowList(value, knownAutopilotSkipReasons, "other")+}++func NormalizeWebhookProvider(value string) string {+ return normalizeFromAllowList(value, knownWebhookProviders, "other")+}++func NormalizeWebhookDeliveryStatus(value string) string {+ return normalizeFromAllowList(value, knownWebhookDeliveryStatuses, "other")+}++func NormalizeGithubEventKind(value string) string {+ return normalizeFromAllowList(value, knownGithubEventKinds, "other")+}++func NormalizeGithubAction(value string) string {+ if strings.TrimSpace(value) == "" {+ return "none"+ }+ return normalizeFromAllowList(value, knownGithubActions, "other")+}++func NormalizeGithubPRReviewResult(value string) string {+ return normalizeFromAllowList(value, knownGithubPRReviewResults, "other")+}++func NormalizeCloudRuntimeOp(value string) string {+ return normalizeFromAllowList(value, knownCloudRuntimeOps, "other")+}++// NormalizeCloudRuntimeStatus collapses an HTTP status code or symbolic+// outcome string into the fixed bucket set {ok, 4xx, 5xx, timeout, error}.+// Empty / unknown collapses to "error".+func NormalizeCloudRuntimeStatus(value string) string {+ value = strings.ToLower(strings.TrimSpace(value))+ if normalized, ok := knownCloudRuntimeStatuses[value]; ok {+ return normalized+ }+ if len(value) == 3 {+ switch value[0] {+ case '2':+ return "ok"+ case '4':+ return "4xx"+ case '5':+ return "5xx"+ }+ }+ return "error"+}++// CloudRuntimeStatusForCode maps an HTTP status code to its bucket label.+// Used by cloudruntime client instrumentation.+func CloudRuntimeStatusForCode(code int) string {+ switch {+ case code >= 200 && code < 400:+ return "ok"+ case code >= 400 && code < 500:+ return "4xx"+ case code >= 500 && code < 600:+ return "5xx"+ default:+ return "error"+ }+}++func NormalizeDaemonWSKind(value string) string {+ return normalizeFromAllowList(value, knownDaemonWSKinds, "other")+}++func NormalizeFeedbackKind(value string) string {+ return normalizeFromAllowList(value, knownFeedbackKinds, "other")+}++func NormalizeContactSalesSource(value string) string {+ return normalizeFromAllowList(value, knownContactSalesSources, "other")+}diff --git a/server/internal/metrics/labels_pr3_test.go b/server/internal/metrics/labels_pr3_test.gonew file mode 100644index 0000000000..3f759e5b08--- /dev/null+++ b/server/internal/metrics/labels_pr3_test.go@@ -0,0 +1,119 @@+package metrics_test++// PR3 normalizer regression coverage. Exercises every PR3-side label+// normalizer with both a happy-path value and an unknown value, asserting+// the unknown value collapses to the documented fallback bucket. Lives in+// the *_test package so a future contributor can't accidentally widen the+// allow-list internals without also widening these expectations.++import (+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/metrics"+)++func TestNormalizePR3LabelsCollapseUnknownValues(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ fn func(string) string+ input string+ want string+ fallback string+ }{+ {"platform_unknown", metrics.NormalizePlatform, "iphone-internal-build-9", "unknown", "unknown"},+ {"platform_known_web", metrics.NormalizePlatform, "web", "web", "unknown"},+ {"signup_source_unknown", metrics.NormalizeSignupSource, "rakuten-affiliate-program", "other", "other"},+ {"signup_source_empty", metrics.NormalizeSignupSource, "", "direct", "direct"},+ {"signup_source_json_utm", metrics.NormalizeSignupSource, `{"utm_source":"twitter","utm_medium":"social"}`, "twitter", "other"},+ {"signup_source_url_host", metrics.NormalizeSignupSource, "https://news.ycombinator.com/item?id=42", "hacker_news", "other"},+ {"onboarding_path_unknown", metrics.NormalizeOnboardingPath, "ab-experiment-123", "unknown", "unknown"},+ {"autopilot_cadence_unknown", metrics.NormalizeAutopilotCadence, "every_5_min", "unknown", "unknown"},+ {"autopilot_trigger_unknown", metrics.NormalizeAutopilotTrigger, "future_kind", "unknown", "unknown"},+ {"autopilot_skip_reason_unknown", metrics.NormalizeAutopilotSkipReason, "lunar_phase", "other", "other"},+ {"webhook_provider_unknown", metrics.NormalizeWebhookProvider, "internal-billing", "other", "other"},+ {"webhook_status_unknown", metrics.NormalizeWebhookDeliveryStatus, "exotic", "other", "other"},+ {"github_event_unknown", metrics.NormalizeGithubEventKind, "deploy_status", "other", "other"},+ {"github_action_empty", metrics.NormalizeGithubAction, "", "none", "none"},+ {"github_action_unknown", metrics.NormalizeGithubAction, "rerequested_by_user", "other", "other"},+ {"github_pr_review_unknown", metrics.NormalizeGithubPRReviewResult, "skipped", "other", "other"},+ {"cloudruntime_op_unknown", metrics.NormalizeCloudRuntimeOp, "lifecycle_audit", "other", "other"},+ {"cloudruntime_status_2xx_string", metrics.NormalizeCloudRuntimeStatus, "200", "ok", "error"},+ {"cloudruntime_status_5xx_string", metrics.NormalizeCloudRuntimeStatus, "503", "5xx", "error"},+ {"cloudruntime_status_garbage", metrics.NormalizeCloudRuntimeStatus, "lol", "error", "error"},+ {"daemon_ws_kind_unknown", metrics.NormalizeDaemonWSKind, "future_event", "other", "other"},+ {"feedback_kind_unknown", metrics.NormalizeFeedbackKind, "rant", "other", "other"},+ {"contact_sales_source_unknown", metrics.NormalizeContactSalesSource, "homepage_modal", "other", "other"},+ }++ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ got := tt.fn(tt.input)+ if got != tt.want {+ t.Fatalf("normalize(%q) = %q, want %q (fallback bucket %q)", tt.input, got, tt.want, tt.fallback)+ }+ })+ }+}++// TestOnboardingStartedUnknownPlatformCollapses pins the specific+// regression that motivated this test file: a misbehaving frontend that+// sends an unrecognised X-Client-Platform header must NOT leak that raw+// value into the metric label. The dispatcher in IncForEvent runs the+// platform property through NormalizePlatform, so anything outside the+// fixed allow-list collapses to "unknown". A future change that drops the+// normalize wrapper will fail this test.+func TestOnboardingStartedUnknownPlatformCollapses(t *testing.T) {+ t.Parallel()++ m := metrics.NewBusinessMetrics()++ // First fire: a known platform — sanity check the happy path.+ metrics.RecordEvent(analytics.NoopClient{}, m, analytics.OnboardingStarted("user-1", "web"))++ // Second fire: an attacker-shaped unknown platform that, without+ // NormalizePlatform, would inflate the label cardinality.+ metrics.RecordEvent(analytics.NoopClient{}, m, analytics.OnboardingStarted("user-2", "iphone-build-1234567890-abcdef"))++ // Read /metrics-style output and assert exactly two label values are+ // present: web and unknown. Anything else means the raw header+ // leaked into the label.+ families := metrics.GatherForTest(t, m)+ famName := "multica_onboarding_started_total"+ fam, ok := families[famName]+ if !ok {+ t.Fatalf("metric family %s not present in registry output", famName)+ }+ seen := map[string]float64{}+ for _, child := range fam.GetMetric() {+ for _, lbl := range child.GetLabel() {+ if lbl.GetName() == "platform" {+ seen[lbl.GetValue()] += child.GetCounter().GetValue()+ }+ }+ }+ if seen["web"] != 1 {+ t.Errorf("expected platform=web count 1, got %v", seen["web"])+ }+ if seen["unknown"] != 1 {+ t.Errorf("expected platform=unknown count 1 (collapsed from raw header), got %v", seen["unknown"])+ }+ for v, count := range seen {+ if v == "web" || v == "unknown" {+ continue+ }+ t.Errorf("found unexpected platform label value %q (count=%v) — NormalizePlatform should have collapsed it", v, count)+ }+ // Defensive check: no label value should look like a raw header (anything+ // over the longest allow-list entry is almost certainly a leak).+ for v := range seen {+ if len(v) > len("desktop") && !strings.EqualFold(v, "unknown") {+ t.Errorf("platform label %q is suspiciously long — likely raw header bleed", v)+ }+ }+}diff --git a/server/internal/metrics/testutil.go b/server/internal/metrics/testutil.gonew file mode 100644index 0000000000..8ba01e5521--- /dev/null+++ b/server/internal/metrics/testutil.go@@ -0,0 +1,68 @@+package metrics++import (+ "testing"++ "github.com/prometheus/client_golang/prometheus"+ dto "github.com/prometheus/client_model/go"+)++// SumAllCounters returns the running sum across every counter sample+// currently registered with this BusinessMetrics receiver. Used by the lint+// test in business_pairing_test.go to confirm that a synthetic event causes+// AT LEAST ONE counter to advance — i.e. that the IncForEvent dispatch+// covered the case. Production code never calls this.+//+// Histograms and gauges are deliberately excluded so prewarmed buckets+// (e.g. failure_reason 0-counts) don't make every event "pass" trivially.+func SumAllCounters(m *BusinessMetrics) float64 {+ if m == nil {+ return 0+ }+ reg := prometheus.NewPedanticRegistry()+ for _, c := range m.Collectors() {+ // MustRegister panics on duplicate; we use a fresh registry each call.+ reg.MustRegister(c)+ }+ families, err := reg.Gather()+ if err != nil {+ return 0+ }+ var total float64+ for _, fam := range families {+ if fam.GetType() != dto.MetricType_COUNTER {+ continue+ }+ for _, mtr := range fam.GetMetric() {+ if c := mtr.GetCounter(); c != nil {+ total += c.GetValue()+ }+ }+ }+ return total+}++// GatherForTest registers every collector on a fresh registry and returns+// the resulting metric families keyed by name. Test-only — the production+// /metrics endpoint reads from the shared registry constructed in+// NewRegistry. Any Gather error is reported via t.Fatalf so callers can+// dereference the result without nil checks.+func GatherForTest(t *testing.T, m *BusinessMetrics) map[string]*dto.MetricFamily {+ t.Helper()+ if m == nil {+ t.Fatalf("GatherForTest: nil BusinessMetrics")+ }+ reg := prometheus.NewPedanticRegistry()+ for _, c := range m.Collectors() {+ reg.MustRegister(c)+ }+ families, err := reg.Gather()+ if err != nil {+ t.Fatalf("GatherForTest: gather failed: %v", err)+ }+ out := make(map[string]*dto.MetricFamily, len(families))+ for _, fam := range families {+ out[fam.GetName()] = fam+ }+ return out+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 8570ec1a1f..20d8b7a975 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -15,6 +15,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueposition"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -735,7 +736,7 @@ func (s *AutopilotService) captureIssueCreatedFromAutopilot(ap db.Autopilot, run// For PostHog the agent_id should be the agent that will actually run// the work (the resolved leader for squad autopilots) so per-agent task// counts line up with what daemons report.- s.TaskSvc.Analytics.Capture(analytics.IssueCreated(+ obsmetrics.RecordEvent(s.TaskSvc.Analytics, s.TaskSvc.Metrics, analytics.IssueCreated(autopilotActorID(ap),util.UUIDToString(ap.WorkspaceID),util.UUIDToString(issue.ID),@@ -743,6 +744,7 @@ func (s *AutopilotService) captureIssueCreatedFromAutopilot(ap db.Autopilot, run"",util.UUIDToString(run.ID),analytics.SourceAutopilot,+ analytics.PlatformServer,))}@@ -750,11 +752,12 @@ func (s *AutopilotService) captureAutopilotRunStarted(ap db.Autopilot, run db.Auif s.TaskSvc == nil || s.TaskSvc.Analytics == nil {return}- s.TaskSvc.Analytics.Capture(analytics.AutopilotRunStarted(+ obsmetrics.RecordEvent(s.TaskSvc.Analytics, s.TaskSvc.Metrics, analytics.AutopilotRunStarted(autopilotActorID(ap),util.UUIDToString(ap.WorkspaceID),util.UUIDToString(ap.ID),util.UUIDToString(run.ID),+ triggerSource, // cadence proxy: see autopilot cadence note in metrics/labels_pr3.gos.autopilotAssigneeAnalytics(ap),triggerSource,))@@ -764,11 +767,12 @@ func (s *AutopilotService) captureAutopilotRunCompleted(ap db.Autopilot, run db.if s.TaskSvc == nil || s.TaskSvc.Analytics == nil {return}- s.TaskSvc.Analytics.Capture(analytics.AutopilotRunCompleted(+ obsmetrics.RecordEvent(s.TaskSvc.Analytics, s.TaskSvc.Metrics, analytics.AutopilotRunCompleted(autopilotActorID(ap),util.UUIDToString(ap.WorkspaceID),util.UUIDToString(ap.ID),util.UUIDToString(run.ID),+ run.Source,s.autopilotAssigneeAnalytics(ap),run.Source,autopilotRunDurationMS(run),@@ -782,11 +786,12 @@ func (s *AutopilotService) captureAutopilotRunFailed(ap db.Autopilot, run db.Autif reason == "" {reason = "unknown"}- s.TaskSvc.Analytics.Capture(analytics.AutopilotRunFailed(+ obsmetrics.RecordEvent(s.TaskSvc.Analytics, s.TaskSvc.Metrics, analytics.AutopilotRunFailed(autopilotActorID(ap),util.UUIDToString(ap.WorkspaceID),util.UUIDToString(ap.ID),util.UUIDToString(run.ID),+ triggerSource,s.autopilotAssigneeAnalytics(ap),triggerSource,reason,