/loxihart-engineering:instrumenting-production-stackfrom loxihart-engineering
Sets up observability for the Vercel + Supabase + n8n + Anthropic stack. Live operational path runs through PostHog (MCP connected). Datadog is NOT connected — all Datadog steps are static setup references only, clearly labeled, and not executable via MCP. Use when the user mentions: PostHog instrumentation, production monitoring, health dashboard, alert setup, stack observability, what to monitor, are things working in production. Not for cost tracking or budget alerts (use governing-stack-costs) and not for agent behavioral telemetry (use instrumenting-agent-telemetry).
Ships in loxihart-engineering. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Use when — "set up observability for my production stack." "I don't know what's happening in production." "Wire PostHog to track Vercel errors and Anthropic costs."
Do NOT use when — "why is my Anthropic bill so high" → governing-stack-costs. "Set up telemetry for my AI agent's behavior" → instrumenting-agent-telemetry.
Covers: Vercel (frontend), Cloudflare Workers (edge), Supabase (database + auth), n8n (workflows), Anthropic API (AI).
Live operational path: PostHog MCP ✅ Datadog: ❌ NOT connected — sections marked [STATIC REFERENCE] are manual setup guides only.
| Tool | Status | Operational Path | Notes |
|---|---|---|---|
| PostHog | MCP ✅ CONNECTED | Live event queries, insight creation, alert configuration | Primary observability path |
| Supabase | MCP ✅ CONNECTED | Schema queries, log table creation and querying | Ask before write ops |
| n8n | MCP ✅ CONNECTED | Execution status, workflow health check | Read-only preferred |
| Vercel | MCP ✅ CONNECTED | Deployment status | Limited log access |
| Datadog | ❌ NOT_CONNECTED | Static reference only — no MCP execution possible | All Datadog steps require manual setup |
Rule: Any step in a [STATIC REFERENCE] section cannot be executed via MCP. Do not attempt Datadog API calls, dashboard creation, or monitor creation in a Claude session — Datadog is not connected. Any result would be fabricated.
"Just do it" override: proceed with the PostHog-only live path and label Datadog items as manual follow-ups if the user requests immediate action.
Should trigger:
Should NOT trigger:
Service → What it produces → LIVE PATH (MCP ✅) → [STATIC REF] Datadog
─────────────────────────────────────────────────────────────────────────────────────────────
Vercel → Function logs, → PostHog (web vitals, → Log drain to Datadog
web vitals error events)
Cloudflare → Worker logs, → PostHog (custom events → Datadog Cloudflare
edge metrics via fetch) integration
Supabase → Query logs, → Supabase built-in dash → Datadog Postgres
auth events, + PostHog custom events integration
API latency
n8n → Execution logs, → n8n MCP + Error → Datadog log
credential errors Trigger → Slack shipping
Anthropic API → Token usage, → PostHog wrapper → [STATIC] statsd
cost, latency (server-side) custom metric
Add to your Next.js _app.tsx or layout.tsx:
import posthog from 'posthog-js'
import { useReportWebVitals } from 'next/web-vitals'
export function reportWebVitals(metric) {
posthog.capture('web_vital', {
name: metric.name, // LCP, FID, CLS, TTFB, FCP
value: metric.value,
rating: metric.rating, // good / needs-improvement / poor
page: window.location.pathname
// Do NOT include: auth tokens, user IDs, email addresses
})
}
PostHog insight to build: filter event = 'web_vital', breakdown by name, trend value over time.
// Add to error boundary or _app.tsx — client-side only (posthog-js)
window.addEventListener('unhandledrejection', (event) => {
posthog.capture('js_error', {
error_message: event.reason?.message ?? 'unknown',
error_type: 'unhandled_rejection',
page: window.location.pathname
// Do NOT include: event.reason stack trace if it may contain secrets or PII
})
})
PostHog Insights → Alerts:
js_error count exceeds threshold per hour → alertweb_vital where name = LCP and value rolling average exceeds 2500ms → alert⚠️ Datadog is NOT connected via MCP. Execute these steps manually in Vercel and Datadog dashboards.
source:vercel and confirm events appearEdge Function logs are retained 7 days on the free plan. For longer retention:
CREATE TABLE function_logs (
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
function_name text NOT NULL,
status_code int,
duration_ms int,
error text,
created_at timestamptz DEFAULT now()
);
-- Restrict to service role only — blocks anon and authenticated reads
ALTER TABLE function_logs ENABLE ROW LEVEL SECURITY;
CREATE POLICY "deny_all_non_service" ON function_logs
FOR ALL USING (false);
-- Service role bypasses RLS automatically
// server-side only — posthog-node, not posthog-js
import { PostHog } from 'posthog-node'
// Key loaded from environment variable — never hardcoded
const ph = new PostHog(process.env.POSTHOG_SERVER_KEY!)
supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') {
ph.capture({
distinctId: session?.user?.id ?? 'anonymous', // UUID only — not email
event: 'auth_signed_in',
properties: {
method: session?.user?.app_metadata?.provider ?? 'email'
// Do NOT include: session.access_token, user.email, user.phone
}
})
}
if (event === 'SIGNED_OUT') {
ph.capture({ distinctId: 'anonymous', event: 'auth_signed_out', properties: {} })
}
})
| Metric | Alert threshold | Where to see it |
|---|---|---|
| Active connections | >80% of connection limit | Supabase Dashboard |
| Query P95 latency | >500ms on indexed queries | Query Performance tab |
| DB size growth | >20% week-over-week | Supabase Dashboard |
| Failed auth attempts | >50 in 10 minutes | Logs Explorer → Auth |
| RLS policy errors | Any spike | Logs Explorer → level = error |
⚠️ Datadog is NOT connected via MCP. Execute these steps manually in Datadog.
service_role keyCREATE ROLE datadog_monitor WITH LOGIN PASSWORD '[set in Bitwarden]';
GRANT SELECT ON pg_stat_activity TO datadog_monitor;
GRANT SELECT ON pg_stat_database TO datadog_monitor;
Anthropic provides no webhook-based cost alerts. Instrument a server-side wrapper:
// server-side only — never import posthog-node in client bundles
import { PostHog } from 'posthog-node'
// All keys loaded from environment variables
const ph = new PostHog(process.env.POSTHOG_SERVER_KEY!)
async function callClaude(
params: MessageParams,
context: string,
sessionId: string // anonymized session UUID — not email, not user name
): Promise<Anthropic.Message> {
const start = Date.now()
const response = await anthropic.messages.create(params)
const inputTokens = response.usage.input_tokens
const outputTokens = response.usage.output_tokens
const model = params.model
// Pricing reference — update when Anthropic publishes rate changes
const costs: Record<string, { input: number; output: number }> = {
'claude-sonnet-4-20250514': { input: 3.00, output: 15.00 },
'claude-haiku-4-5-20251001': { input: 0.80, output: 4.00 },
}
const rate = costs[model] ?? costs['claude-sonnet-4-20250514']
const costUsd = (inputTokens / 1e6 * rate.input) + (outputTokens / 1e6 * rate.output)
ph.capture({
distinctId: sessionId,
event: 'anthropic_api_call',
properties: {
context,
model,
input_tokens: inputTokens,
output_tokens: outputTokens,
cost_usd: costUsd,
latency_ms: Date.now() - start,
// Do NOT include: prompt content, response content, user data
}
})
return response
}
PostHog insights to build:
anthropic_api_call → sum cost_usd by day, breakdown by contextinput_tokens + output_tokens over timelatency_ms by modelPostHog alerts:
sum(cost_usd) exceeds budget threshold → alertinput_tokens value exceeds 50,000 (runaway context indicator)⚠️ Datadog is NOT connected via MCP. This is a reference pattern for when you manually connect Datadog.
Replace the PostHog ph.capture() block above with the following when Datadog agent is running:
// Requires hot-shots (StatsD client) — install: npm install hot-shots
// DD_AGENT_HOST set via environment variable — never hardcoded
import StatsD from 'hot-shots'
const statsd = new StatsD({ host: process.env.DD_AGENT_HOST })
statsd.gauge('anthropic.cost_usd', costUsd, [`context:${context}`, `model:${model}`])
statsd.gauge('anthropic.latency_ms', Date.now() - start, [`context:${context}`])
statsd.increment('anthropic.requests.total', [`context:${context}`, `model:${model}`])
DD_AGENT_HOST and any Datadog API key belong in environment variables only. Do not include them in source code.
Real-time failure alerts: use the Error Trigger node in n8n → sends to Slack webhook on any workflow failure. See operating-n8n-production for the Error Trigger pattern.
Health check via n8n MCP or REST API:
GET /api/v1/executions?status=error&limit=50
Write error counts to a Supabase n8n_metrics table. Query via PostHog connected source or Supabase SQL.
n8n MCP query to run in session:
"Pull the last 20 failed executions from n8n and list the workflow names and error messages"
⚠️ Datadog is NOT connected via MCP. Execute these steps manually.
DD_API_KEY (from Bitwarden)GET /api/v1/executions and ship results to Datadog HTTP log intake via HTTP Request nodeCreate one PostHog dashboard with four sections:
Section 1: User-Facing Health
web_vital avg value by metric name (trend)js_error count per dayauth_signed_in and auth_signed_out per daySection 2: AI Costs
anthropic_api_call sum cost_usd by daycontextinput_tokens trend over timeSection 3: Automation Health
n8n_metrics Supabase table, if wired)agent_session_completed events are flowing)Section 4: Auth & Funnel
pageview → auth_signed_in → key action event⚠️ Datadog is NOT connected. This is a reference for when you manually configure Datadog.
Build one Datadog dashboard with four sections: (1) Vercel error rate and P95 latency, (2) Supabase active connections and query latency, (3) Anthropic daily cost and token volume, (4) n8n execution error count. Set as Datadog account default landing page.
reportWebVitals function added to Next.js app and web_vital events visible in PostHog Live Events — FAIL if no events appear after a page loadjs_error PostHog events captured — FAIL if unhandled rejections produce no telemetryanthropic_api_call PostHog events visible after at least one API call — FAIL if events are missingfunction_logs table created (if using Edge Functions) — FAIL if Edge Functions have no retention beyond 7 dayscost_usd threshold existsCLAIMS
COUNTEREXAMPLE
CONTRADICTIONS
statsd calls as live operational steps. Datadog is NOT connected — those steps cannot execute via MCP. PostHog is the live path. All Datadog content is now clearly labeled [STATIC REFERENCE].fetch to emit events to the PostHog /capture endpoint from within a Worker. This pattern is not covered here — extend when needed.POSTHOG_SERVER_KEY rotation. Must be rotated per managing-credential-lifecycle schedule. No auto-rotation is in place.function_logs table pattern is not implemented and the plan is not upgraded, log data beyond 7 days is unrecoverable.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub krosebrook/loxihart-skills --plugin loxihart-engineering22 skills in this plugin
/administering-supabaseManages Supabase database operations for FlashFusion's production stack — schema design, Row Level Security policies, migrations, Edge Functions, and debugging. Active project: flashnframe-app (etctmappdhpjuwptdbeb). Use when the user mentions: Supabase, RLS, row level security, migration, schema, database, table, Edge Function, auth, policies, Postgres, supabase query, database admin, add a column, create a table, why is my query blocked, or any task involving the Supabase project or database structure.
/auditing-logicAudits code for logical errors before they become bugs — control flow gaps, data contract violations, schema/type drift, business logic inconsistencies, and silent failure paths. Produces a severity-rated issue list with a one-line diagnosis and one-line fix per finding. Use this skill whenever code is pasted with a review request, or when the user says "audit this", "check the logic", "does this make sense", "any issues with this", "logic audit", "what's wrong here", "review this function", "is this correct", or hands you any code file and wants a critical eye. Even if the user does not say "logic" — if code is present and they want feedback, use this skill. Also triggers on: "find the bug", "something feels off", "is this right", "sanity check this", "does this hold", "validate my logic", "code review", "PR review", "review this PR".
/code-auditorPerforms comprehensive codebase analysis covering architecture, code quality, security, performance, testing, and maintainability. Use when user wants to audit code quality, identify technical debt, find security issues, assess test coverage, or get a codebase health check./code-transferTransfer code between files with line-based precision. Use when users request copying code from one location to another, moving functions or classes between files, extracting code blocks, or inserting code at specific line numbers./debug-like-expertDeep analysis debugging mode for complex issues. Activates methodical investigation protocol with evidence gathering, hypothesis testing, and rigorous verification. Use when standard troubleshooting fails or when issues require systematic root cause analysis. Triggers on: debug this, root cause analysis, systematic debugging, why is this failing, trace this bug, diagnose this issue, investigation protocol, hypothesis testing./engineering-patternsProduction engineering pattern library spanning 11 phases — Foundation, Resilience, Performance, Data Integrity, Observability, Deployment, Scalability, Edge Cases, Security Deep, Compliance/DR/FinOps, and AI/HITL. Use when auditing code for production readiness, applying hardening patterns, reviewing system design, pattern audit, apply phase, harden this, production-ready, resilience patterns, observability gaps, security review, DR plan, FinOps, or AI guardrails. Use alongside engineering-staff-workflows for execution. Not for writing the implementation itself — that is engineering-staff-workflows.