Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

docs(agents): lighten shared agent guidance (#14000)

Max Deichmanna1884e7c0cf2
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md
index c2e4f7b671..009aeaac25 100644
--- a/.agents/AGENTS.md
+++ b/.agents/AGENTS.md
@@ -1,99 +1,30 @@
# Agent Guidelines for Langfuse
-This is the canonical root agent guide for the repo. The root `AGENTS.md`
-should remain only as a discovery symlink so tools that require that filename
-continue to work while `.agents/` stays the source of truth.
-
Langfuse is an open source LLM engineering platform for developing, monitoring,
evaluating, and debugging AI applications.
-## Maintenance Contract
-
-- `AGENTS.md` is a living document.
-- Keep this file concise and router-like. Push narrow or conditional workflows
- into package-local `AGENTS.md` files or shared skills under `.agents/skills/`.
-- Update this file in the same PR when monorepo-level architecture, workflows,
- dependency boundaries, mandatory verification commands, or release/security
- processes materially change.
-- Treat developer interactions as a learning loop: when work reveals a durable
- repo convention, recurring pitfall, reusable workflow, or verification pattern,
- update the smallest relevant context surface in the same PR. Use package
- `AGENTS.md` files for package-local guidance and `.agents/skills/**` for
- reusable workflows. Do not edit this file for one-off task preferences.
-- For package-local material changes, update the nearest package `AGENTS.md` in
- the same PR.
-
-## Start Here By Task
-
-- Architecture principles for high-scale observability and wide event data:
- `.agents/ARCHITECTURE_PRINCIPLES.md`
-- Langfuse org navigation, cross-repo context, or when context/skills from
- other Langfuse codebases may be required:
- use the `langfuse-codebase-navigator` skill.
-- Repo-wide agent setup, `.agents/**`, provider shims, or MCP/bootstrap config:
- `.agents/README.md`,
- `.agents/skills/agent-setup-maintenance/SKILL.md`
-- Creating, editing, or refining shared skills under `.agents/skills/**`:
- `.agents/skills/skill-creator/SKILL.md`, then
- `.agents/skills/agent-setup-maintenance/SKILL.md` for repo sync/check
- requirements.
-- Langfuse Cloud cost structure, infra spend, AWS/ClickHouse cost splits, or
- Metabase cost marts:
- `.agents/skills/analyze-cloud-costs/SKILL.md`
-- Production telemetry research, Datadog query recipes, tenant/public API usage
- audits, or queue consumer telemetry:
- `.agents/skills/datadog-query-recipes/SKILL.md`
-- Backend/API work in `web/src/server/**`, `web/src/pages/api/public/**`,
- `worker/src/**`, or `packages/shared/src/**`:
- `.agents/skills/backend-dev-guidelines/SKILL.md`
-- Model pricing work in `worker/src/constants/default-model-prices.json`,
- `packages/shared/src/server/llm/types.ts`, or related pricing files:
- `.agents/skills/add-model-price/SKILL.md`
-- Code review tasks:
- `.agents/skills/code-review/SKILL.md`
-- Debugging a Linear issue, GitHub issue, or incident report using Datadog
- (APM, logs, metrics) to establish a root cause:
- `.agents/skills/debug-issue-with-datadog/SKILL.md`
-- Measured bug or regression evidence that needs Linear deduplication, evidence
- comments, or Triage bug issue creation:
- `.agents/skills/linear-bug-triage/SKILL.md`
-- Weekly production reviews of what broke, fixed/open `bug`-labeled Linear
- tickets, Datadog alert/page signals, and status-page or incident.io incidents:
- `.agents/skills/weekly-production-review/SKILL.md`
-- Changelog drafting for completed feature branches:
- `.agents/skills/changelog-writing/SKILL.md`
-- ClickHouse schema/query review:
- `.agents/skills/clickhouse-best-practices/SKILL.md`
-- Monorepo/Turbo task graph changes:
- `.agents/skills/turborepo/SKILL.md`
-- pnpm dependency upgrades, package-version bumps, or `minimumReleaseAgeExclude`
- decisions in `pnpm-workspace.yaml`:
- `.agents/skills/pnpm-upgrade-package/SKILL.md`
-- User-visible frontend changes, Playwright review, or browser signoff:
- `.agents/skills/frontend-browser-review/SKILL.md`
-- Web UI and frontend entry points:
- `web/AGENTS.md`
-- Worker queues and processors:
- `worker/AGENTS.md`
-- Shared contracts, exports, schema, and migrations:
- `packages/shared/AGENTS.md`
-- EE-only work:
- `ee/AGENTS.md`
-
-Read the minimal set required for the task. More-specific package guides and
-shared skills take precedence over this root file for their scoped areas.
+## How To Work
+
+- Read the minimal local context required for the task.
+- Keep changes scoped and avoid unrelated refactors.
+- For bug fixes, write the failing test first, confirm it fails, then fix the
+ bug.
+- For user-visible frontend changes in `web/**`, review the affected flow in a
+ real browser before signoff.
+- Never commit secrets or credentials. Keep `.env*.example` files in
+ sync with required env vars.
## Project Structure
```text
langfuse/
-β”œβ”€ web/ # Next.js app (UI + tRPC + public REST)
-β”œβ”€ worker/ # Queue consumers and background processing
-β”œβ”€ packages/shared/ # Shared domain, DB, queue contracts, repositories
-β”œβ”€ ee/ # Enterprise package consumed by web
-β”œβ”€ generated/ # Generated API clients (do not hand-edit)
-β”œβ”€ fern/ # API definition sources
-└─ scripts/ # Repo scripts
+|- web/ # Next.js app (UI + tRPC + public REST)
+|- worker/ # Queue consumers and background processing
+|- packages/shared/ # Shared domain, DB, queue contracts, repositories
+|- ee/ # Enterprise package consumed by web
+|- generated/ # Generated API clients (do not hand-edit)
+|- fern/ # API definition sources
+`- scripts/ # Repo scripts
```
- Dependency direction:
@@ -108,10 +39,7 @@ langfuse/
- Postgres schema: `packages/shared/prisma/schema.prisma`
- ClickHouse migrations:
`packages/shared/clickhouse/migrations/{clustered,unclustered}/*.sql`
-- Architecture handbook:
- [langfuse.com/handbook/product-engineering/architecture](https://langfuse.com/handbook/product-engineering/architecture)
- with source markdown in the sibling docs checkout at
- `../langfuse-docs/content/handbook/product-engineering/architecture.mdx`
+- Architecture principles live in `.agents/ARCHITECTURE_PRINCIPLES.md`.
## Core Commands
@@ -123,88 +51,48 @@ langfuse/
- Typecheck all: `pnpm run typecheck` / `pnpm tc`
- Build check: `pnpm run build:check`
- Full build: `pnpm run build`
-- Full reset/bootstrap (destructive): `pnpm run dx`
-- Environment/worktree bootstrap: `bash scripts/codex/setup.sh`
-- Environment/worktree maintenance: `bash scripts/codex/maintenance.sh`
-- Install Playwright Chromium for agent browser review: `pnpm run playwright:install`
-
-Minimum verification matrix:
-
-| Change scope | Minimum verification |
-| --- | --- |
-| `web/**` only | `pnpm --filter web run lint` + targeted web tests |
-| `worker/**` only | `pnpm --filter worker run lint` + targeted worker tests |
-| `packages/shared/**` (non-schema) | `pnpm --filter @langfuse/shared run lint` + one targeted web check + one targeted worker check |
-| `packages/shared/prisma/**` or `packages/shared/clickhouse/**` | `pnpm --filter @langfuse/shared run lint` + `pnpm run db:generate` + targeted web/worker regressions |
-| Public API contract (`web/src/pages/api/public/**`, `web/src/features/public-api/types/**`, `fern/apis/**`) | web lint + targeted server API tests + Fern update/regeneration; never hand-edit `generated/**` |
-| Cross-package refactor (`web` + `worker` + `shared`) | `pnpm run lint` + `pnpm run typecheck` + targeted tests per impacted package |
-
-## Repo Rules
-
-- Keep changes scoped; avoid unrelated refactors.
-- Prefer package-local implementation details in package `AGENTS.md` files.
-- Do not hand-edit generated/build artifacts:
- - `generated/*`
- - `web/.next/*`
- - `web/.next-check/*`
- - `*/dist/*`
- - `packages/shared/prisma/generated/*`
-- Public API contract changes must update Fern sources in `fern/apis/**` and
- regenerated outputs. Never hand-edit `generated/**`.
-- Before adding constants, value lists, or display mappings, search for an
- existing owner and reuse or extend that source of truth.
-- Keep tests independent and parallel-safe.
-- For bug fixes, write the failing test first, confirm it fails, then fix the
- bug.
-- For user-visible frontend changes in `web/**`, review the affected flow in a
- real browser with the Playwright MCP server before signoff. Use
- `.agents/skills/frontend-browser-review/SKILL.md` and `web/AGENTS.md` for the
- browser-review loop.
-- Never commit secrets or credentials. Keep `.env*.example` files in sync with
- required env vars.
+- Worktree bootstrap: `bash scripts/codex/setup.sh`
+- Worktree maintenance: `bash scripts/codex/maintenance.sh`
+- Install Playwright Chromium: `pnpm run playwright:install`
+
+## Verification
+
+- `web/**`: `pnpm run lint` plus targeted web tests.
+- `worker/**`: `pnpm run lint` plus targeted worker tests.
+- `packages/shared/**` non-schema changes:
+ `pnpm run lint` plus one targeted web check and one targeted worker check.
+- `packages/shared/prisma/**` or `packages/shared/clickhouse/**`:
+ `pnpm run lint`, `pnpm run db:generate`, and targeted web/worker
+ regressions.
+- Public API contracts in `web/src/pages/api/public/**`,
+ `web/src/features/public-api/types/**`, or `fern/apis/**`: `pnpm run lint`,
+ targeted server API tests, and Fern update/regeneration.
+- Cross-package refactors: `pnpm run lint`, `pnpm run typecheck`, and targeted
+ tests for impacted packages.
+
+## Generated Files
+
+Do not hand-edit generated or build artifacts:
+
+- `generated/*`
+- `web/.next/*`
+- `web/.next-check/*`
+- `*/dist/*`
+- `packages/shared/prisma/generated/*`
+
+Public API contract changes must update Fern sources in `fern/apis/**` and
+regenerated outputs. Never hand-edit `generated/**`.
## Shared Agent Setup
- `.agents/AGENTS.md` is the canonical root guide.
- Root `AGENTS.md` is a symlink to `.agents/AGENTS.md`.
- Root `CLAUDE.md` is a compatibility symlink to `AGENTS.md`.
-- Shared agent/tool config lives in `.agents/config.json` and shared skills
- live in `.agents/skills/`.
- When creating or editing `.agents/skills/**`, use
`.agents/skills/skill-creator/SKILL.md`; keep skills concise with
- progressive disclosure, update
- `.agents/skills/README.md`, and run the shared agent verification below.
-- Project-scoped provider discovery files are generated local artifacts. Edit
- the canonical files under `.agents/` instead of editing generated tool
- directories by hand.
-- If you change `.agents/config.json`, `.agents/skills/**`, or the
- shim-generation workflow, run:
- - `pnpm run agents:sync`
- - `pnpm run agents:check`
-- Do not commit generated provider config or shim outputs under `.claude/`,
- `.cursor/`, `.codex/`, `.vscode/`, or `.mcp.json`.
-- Durable cross-tool guidance belongs in root/package `AGENTS.md` files or
- `.agents/skills/**`, not only in tool-specific config directories.
-
-## Commit, PR, and Release Rules
-
-- Commit messages and PR titles must follow Conventional Commits:
- `type(scope): description` or `type: description`.
-- PR titles are validated by `.github/workflows/validate-pr-title.yml`.
-- In PR descriptions, list impacted packages and executed verification commands.
-- Release workflow is managed at root with `pnpm run release`.
-- Promote `main` to `production` via
- `.github/workflows/promote-main-to-production.yml` or
- `pnpm run release:cloud`.
-- Do not change release/versioning flow without updating this file and impacted
- package guides.
-
-## Git and Tooling Notes
-
-- Use `gh search issues` for GitHub issue search.
-- Do not use destructive git commands such as `reset --hard` unless explicitly
- requested.
-- Do not revert unrelated working-tree changes.
-- Keep commits focused and atomic.
-- Remaining `.cursor/rules/*.mdc` files should stay thin wrappers around shared
- docs or skills rather than owning durable repo guidance directly.
+ progressive disclosure.
+- After changing shared agent setup, run `pnpm run agents:sync` and
+ `pnpm run agents:check`.
+- Generated provider config and shim outputs under `.claude/`, `.cursor/`,
+ `.codex/`, `.vscode/`, or `.mcp.json` are local artifacts, not source of
+ truth files.
diff --git a/.agents/README.md b/.agents/README.md
index 49b36d7cbe..37732263a1 100644
--- a/.agents/README.md
+++ b/.agents/README.md
@@ -207,5 +207,3 @@ Do not use skills for one-off task notes or tool runtime configuration.
Use `skills/skill-creator/SKILL.md` when creating or editing shared skills.
`pnpm run agents:sync` projects the shared skills into `.claude/skills/` so
Claude can discover the same repo-owned skills.
-
-For the skill authoring workflow, see [skills/README.md](skills/README.md).
diff --git a/.agents/skills/README.md b/.agents/skills/README.md
deleted file mode 100644
index 7100e73496..0000000000
--- a/.agents/skills/README.md
+++ /dev/null
@@ -1,223 +0,0 @@
-# Shared Skills
-
-Shared repo skills for any coding agent working in Langfuse.
-
-Use these from `AGENTS.md`. Claude Code reaches the same shared instructions via
-the root `CLAUDE.md` compatibility symlink. Shared skills should stay focused on
-reusable implementation guidance rather than runtime automation.
-
-For the shared agent config and generated shim model, start with
-[`../README.md`](../README.md).
-
-When Codex creates or edits a shared skill, first use
-`skill-creator/SKILL.md`, then apply the repo-specific rules in this file and
-`agent-setup-maintenance/SKILL.md`.
-
-Claude discovers these shared skills through symlinks under `.claude/skills/`.
-Those discovery links are created and verified by `pnpm run agents:sync` and
-`pnpm run agents:check`.
-
-Shared skills should use progressive disclosure:
-
-- `SKILL.md` is the short entrypoint with trigger guidance and navigation.
-- `AGENTS.md` is optional and should stay concise when it exists.
-- `references/` holds focused prose references that agents should open only
- when the task needs them.
-- `scripts/` holds deterministic helpers for repetitive or fragile steps.
-
-## Learning Loop
-
-- Treat feature work and developer feedback as a source of durable agent
- guidance.
-- When a task reveals a reusable repo workflow, recurring pitfall, missing
- verification step, or package convention, update the smallest relevant context
- surface in the same PR when practical.
-- Use root `.agents/AGENTS.md` for repo-wide defaults, package `AGENTS.md` files
- for package-local guidance, and shared skills for reusable workflows that need
- more than a short rule.
-- Do not codify one-off preferences, task-local decisions, or temporary
- debugging notes.
-
-## Available Skills
-
-### agent-setup-maintenance
-
-Use for:
-- `.agents/config.json`, `.agents/AGENTS.md`, or `.agents/README.md`
-- shared skill additions or shared skill routing changes
-- generated shim behavior in `scripts/agents/sync-agent-shims.mjs`
-- install-time agent sync behavior and provider discovery paths
-
-Open: [agent-setup-maintenance/SKILL.md](agent-setup-maintenance/SKILL.md)
-
-### skill-creator
-
-Use for:
-- creating new shared skills under `.agents/skills/`
-- editing or refining existing shared skills
-- choosing when to use `SKILL.md`, `references/`, `scripts/`, `assets/`, and
- `agents/openai.yaml`
-- validating skills with `scripts/quick_validate.py`
-
-Open: [skill-creator/SKILL.md](skill-creator/SKILL.md)
-
-### analyze-cloud-costs
-
-Use for:
-- Langfuse Cloud infrastructure cost structure
-- AWS versus ClickHouse cost splits and cost drivers
-- Metabase infra cost dashboard and cost marts
-- daily cost per tracing event and cost regression analysis
-
-Open: [analyze-cloud-costs/SKILL.md](analyze-cloud-costs/SKILL.md)
-
-### datadog-query-recipes
-
-Use for:
-- production telemetry research across `prod-us`, `prod-eu`, `prod-hipaa`,
- and `prod-jp`
-- Datadog query recipes for spans, logs, metrics, tenants, public API usage,
- and queue consumers
-- ad hoc measured questions where the task is not yet an incident root-cause
- analysis
-
-Open: [datadog-query-recipes/SKILL.md](datadog-query-recipes/SKILL.md)
-
-### frontend-browser-review
-
-Use for:
-- user-visible changes in `web/**`
-- Playwright MCP browser review before signoff
-- checking visible regressions in layout, styling, navigation, or responsive behavior
-
-Open: [frontend-browser-review/SKILL.md](frontend-browser-review/SKILL.md)
-
-### backend-dev-guidelines
-
-Use for:
-- tRPC routers and procedures
-- public API endpoints
-- worker queue processors
-- Prisma and ClickHouse backed services
-- backend auth, validation, observability, and tests
-
-Open: [backend-dev-guidelines/SKILL.md](backend-dev-guidelines/SKILL.md)
-
-### add-model-price
-
-Use for:
-- `worker/src/constants/default-model-prices.json`
-- `packages/shared/src/server/llm/types.ts`
-- pricing tiers, tokenizer IDs, and model `matchPattern` changes
-
-Open: [add-model-price/SKILL.md](add-model-price/SKILL.md)
-
-### code-review
-
-Use for:
-- PR or branch review
-- correctness, regression, and risk-focused review tasks
-- applying the repo-specific review policy in
- `code-review/references/review-checklist.md`
-
-Open: [code-review/SKILL.md](code-review/SKILL.md)
-
-### weekly-production-review
-
-Use for:
-- weekly engineering reviews of what broke in production
-- combining Linear `bug`-labeled tickets, Datadog alert/page signals, and
- status-page or incident.io incidents
-- fixed/open production bug summaries with title, summary, owner, evidence, and
- classification
-- event-centric reporting that separates source evidence from the engineering
- narrative
-
-Open: [weekly-production-review/SKILL.md](weekly-production-review/SKILL.md)
-
-### linear-bug-triage
-
-Use for:
-- deduplicating measured bug or regression evidence against Linear
-- creating new Linear bug issues in `Triage` with `bug` and related labels
-- adding concise evidence comments to related existing Linear issues
-
-Open: [linear-bug-triage/SKILL.md](linear-bug-triage/SKILL.md)
-
-### changelog-writing
-
-Use for:
-- changelog entries for completed features
-- drafting user-facing release notes
-- checking related docs links for changelog posts
-
-Open: [changelog-writing/SKILL.md](changelog-writing/SKILL.md)
-
-### clickhouse-best-practices
-
-Use for:
-- ClickHouse schema, query, or configuration review
-- ClickHouse migrations under `packages/shared/clickhouse/**`
-- applying the repo-specific ClickHouse rules layered on top of upstream best practices
-
-Open: [clickhouse-best-practices/SKILL.md](clickhouse-best-practices/SKILL.md)
-
-### debug-issue-with-datadog
-
-Use for:
-- root-causing Linear, GitHub, or incident reports with Datadog evidence
-- production debugging across APM spans, logs, metrics, and monitors
-- mapping observed error clusters back to Langfuse code paths
-
-Open: [debug-issue-with-datadog/SKILL.md](debug-issue-with-datadog/SKILL.md)
-
-### pnpm-upgrade-package
-
-Use for:
-- pnpm dependency bumps that need a specific target version
-- interactive upgrades where the package name or version may be missing
-- transitive lockfile bumps that may need temporary overrides, then a
- remove/install/dedupe check before deciding whether the override should stay
-- checking whether `pnpm-workspace.yaml` `minimumReleaseAgeExclude` must change
-- comparing registry latest with the latest version installable under the
- current release-age gate
-
-Open: [pnpm-upgrade-package/SKILL.md](pnpm-upgrade-package/SKILL.md)
-
-### turborepo
-
-Use for:
-- `turbo.json` task graph, caching, filtering, or affected-run changes
-- root/package script organization for Turborepo workflows
-- monorepo package boundaries and shared-code layout decisions
-
-Open: [turborepo/SKILL.md](turborepo/SKILL.md)
-
-## Adding a New Shared Skill
-
-1. Codex may create or refine shared skills under `.agents/skills/` when a
- repo-specific workflow becomes repeated enough to justify durable guidance.
-2. Start with [skill-creator/SKILL.md](skill-creator/SKILL.md); if it is not
- available, follow these rules and the shape of nearby skills.
-3. Create a concise `.agents/skills/<skill-name>/SKILL.md`.
-4. Add `.agents/skills/<skill-name>/AGENTS.md` only when the skill benefits
- from a short router or checklist on top of `SKILL.md`.
-5. Prefer `references/` for detailed prose and `scripts/` for deterministic
- execution helpers.
-6. Keep the skill tightly scoped to one domain or workflow.
-7. Link the skill from `AGENTS.md` if it is relevant across the repo.
-8. Run `pnpm run agents:sync` and `pnpm run agents:check` so Claude's projected
- `.claude/skills/` view stays in sync.
-9. Update `AGENTS.md` or package-local `AGENTS.md` if the new skill changes the
- default reusable workflow for future agents.
-10. Run the relevant verification for the package or workflow the skill affects.
-
-## Skill Design Rules
-
-- Keep the skill tool-neutral.
-- Use `SKILL.md` as the short entrypoint, not the full knowledge dump.
-- Prefer `references/` for deeper docs and `scripts/` for deterministic helpers.
-- Avoid copying large sections of repo docs into the skill when a stable link is
- enough.
-- If the skill is web- or package-specific, link the nearest package
- `AGENTS.md` or package docs instead of restating them.
diff --git a/.agents/skills/add-model-price/AGENTS.md b/.agents/skills/add-model-price/AGENTS.md
deleted file mode 100644
index 658edcd696..0000000000
--- a/.agents/skills/add-model-price/AGENTS.md
+++ /dev/null
@@ -1,544 +0,0 @@
-# Add Model Price
-
-Guide for adding or updating model pricing entries in Langfuse. Use this when
-editing `worker/src/constants/default-model-prices.json`,
-`packages/shared/src/server/llm/types.ts`, model `matchPattern` values,
-tokenizer IDs, or pricing tiers.
-
-## Purpose
-
-This guide keeps model pricing changes consistent across providers and runtime
-surfaces so Langfuse can calculate token costs accurately.
-
-## How to Use This Skill
-
-1. Read [references/schema-and-tiers.md](references/schema-and-tiers.md) for
- the JSON shape and pricing-tier rules.
-2. Read
- [references/provider-sources-and-price-keys.md](references/provider-sources-and-price-keys.md)
- for official pricing URLs, per-token conversion, and provider-specific usage
- keys.
-3. Read [references/match-patterns.md](references/match-patterns.md) when you
- need to add or expand regex coverage.
-4. Read
- [references/workflow-and-validation.md](references/workflow-and-validation.md)
- for the end-to-end edit workflow, validation rules, and common mistakes.
-
-## Deterministic Helpers
-
-- Validate the pricing file:
- `node .agents/skills/add-model-price/scripts/validate-pricing-file.mjs`
-- Test a regex directly:
- `node .agents/skills/add-model-price/scripts/test-match-pattern.mjs --pattern '(?i)^(openai/)?(gpt-4o)$' --accept gpt-4o openai/gpt-4o --reject gpt-4o-mini`
-- Test the regex for an existing model entry:
- `node .agents/skills/add-model-price/scripts/test-match-pattern.mjs --model gpt-4o --accept gpt-4o openai/gpt-4o --reject gpt-4o-mini`
-
-## Quick Start Checklist
-
-### Adding a New Model
-
-- [ ] Gather official pricing from the provider documentation
-- [ ] Generate a lowercase UUID for the model entry
-- [ ] Create a `matchPattern` that covers supported provider formats
-- [ ] Add at least one default pricing tier
-- [ ] Insert the pricing entry into
- `worker/src/constants/default-model-prices.json`
-- [ ] Update `packages/shared/src/server/llm/types.ts` if the model should be
- selectable in playground or evaluation flows
-- [ ] Validate the JSON after editing
-
-### Updating an Existing Model
-
-- [ ] Update the relevant prices, keys, tiers, or regexes
-- [ ] Refresh `updatedAt` to today's ISO-8601 timestamp
-- [ ] Validate the JSON after editing
-
-## Target Files
-
-- Pricing data:
- `worker/src/constants/default-model-prices.json`
-- Shared model types:
- `packages/shared/src/server/llm/types.ts`
-- Validation logic:
- `packages/shared/src/features/model-pricing/validation.ts`
-- Matching logic:
- `packages/shared/src/server/pricing-tiers/matcher.ts`
-- Tests:
- `worker/src/__tests__/pricing-tier-matcher.test.ts`
-
-## Data Structure
-
-### Complete Model Entry Schema
-
-```json
-{
- "id": "uuid-generated-with-uuidgen",
- "modelName": "model-name-identifier",
- "matchPattern": "(?i)^regex-pattern$",
- "createdAt": "ISO-8601-timestamp",
- "updatedAt": "ISO-8601-timestamp",
- "tokenizerConfig": null,
- "tokenizerId": "claude|openai|null",
- "pricingTiers": [
- {
- "id": "model-uuid_tier_default",
- "name": "Standard",
- "isDefault": true,
- "priority": 0,
- "conditions": [],
- "prices": {
- "input": 0.000005,
- "output": 0.000025
- }
- }
- ]
-}
-```
-
-### Required Fields
-
-| Field | Type | Description |
-| --- | --- | --- |
-| `id` | string | Unique lowercase UUID |
-| `modelName` | string | Primary model identifier |
-| `matchPattern` | string | Regex for matching model names |
-| `createdAt` | string | ISO-8601 timestamp set on creation |
-| `updatedAt` | string | ISO-8601 timestamp refreshed whenever the entry changes |
-| `pricingTiers` | array | At least one pricing tier |
-
-### Optional Fields
-
-| Field | Type | Default | Description |
-| --- | --- | --- | --- |
-| `tokenizerId` | string | `null` | `"claude"`, `"openai"`, or `null` |
-| `tokenizerConfig` | object | `null` | Custom tokenizer settings |
-
-## Pricing Tier Structure
-
-### Default Tier
-
-Every model must have exactly one default tier:
-
-```json
-{
- "id": "{model-id}_tier_default",
- "name": "Standard",
- "isDefault": true,
- "priority": 0,
- "conditions": [],
- "prices": {}
-}
-```
-
-Rules for the default tier:
-
-- `isDefault` must be `true`
-- `priority` must be `0`
-- `conditions` must be `[]`
-
-### Additional Tiers
-
-Use extra tiers for context-window or usage-based pricing:
-
-```json
-{
- "id": "uuid-for-tier",
- "name": "Large Context (>200K)",
- "isDefault": false,
- "priority": 1,
- "conditions": [
- {
- "usageDetailPattern": "(input|prompt|cached)",
- "operator": "gt",
- "value": 200000,
- "caseSensitive": false
- }
- ],
- "prices": {}
-}
-```
-
-Supported condition operators: `gt`, `gte`, `lt`, `lte`, `eq`, `neq`
-
-## Official Pricing Sources
-
-Always fetch pricing from the provider's official docs before editing. Do not
-infer or estimate missing values.
-
-| Provider | Source |
-| --- | --- |
-| Anthropic Claude | `https://platform.claude.com/docs/en/about-claude/pricing` |
-| OpenAI | `https://openai.com/api/pricing/` |
-| Google Gemini | `https://ai.google.dev/pricing` |
-| AWS Bedrock | `https://aws.amazon.com/bedrock/pricing/` |
-| Azure OpenAI | `https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/` |
-
-Gather:
-
-1. Base input token price per million tokens
-2. Output token price per million tokens
-3. Cache write price when supported
-4. Cache read price when supported
-5. Any long-context pricing tiers
-6. All model ID formats that Langfuse should match
-
-## Price Conversion
-
-Values in `default-model-prices.json` are per token, not per million tokens.
-
-| Provider Price | JSON Value |
-| --- | --- |
-| `$5 / MTok` | `5e-6` |
-| `$25 / MTok` | `25e-6` |
-| `$0.50 / MTok` | `0.5e-6` |
-| `$6.25 / MTok` | `6.25e-6` |
-
-Formula:
-
-```text
-price_per_token = price_per_mtok / 1_000_000
-```
-
-## Common Price Keys by Provider
-
-### Anthropic Claude Models
-
-```json
-{
- "input": "<base_input_price>",
- "input_tokens": "<base_input_price>",
- "output": "<output_price>",
- "output_tokens": "<output_price>",
- "cache_creation_input_tokens": "<cache_write_price>",
- "input_cache_creation": "<cache_write_price>",
- "cache_read_input_tokens": "<cache_read_price>",
- "input_cache_read": "<cache_read_price>"
-}
-```
-
-### OpenAI Models
-
-```json
-{
- "input": "<input_price>",
- "input_cached_tokens": "<cached_input_price>",
- "input_cache_read": "<cached_input_price>",
- "output": "<output_price>"
-}
-```
-
-### Google Gemini Models
-
-```json
-{
- "input": "<input_price>",
- "input_modality_1": "<input_price>",
- "prompt_token_count": "<input_price>",
- "promptTokenCount": "<input_price>",
- "input_cached_tokens": "<cached_price>",
- "cached_content_token_count": "<cached_price>",
- "output": "<output_price>",
- "output_modality_1": "<output_price>",
- "candidates_token_count": "<output_price>",
- "candidatesTokenCount": "<output_price>"
-}
-```
-
-## Match Pattern Examples
-
-### Anthropic Claude: API + Bedrock + Vertex
-
-```regex
-(?i)^(anthropic\/)?(claude-opus-4-6|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-6-v1(:0)?|claude-opus-4-6)$
-```
-
-Matches:
-
-- `claude-opus-4-6`
-- `anthropic/claude-opus-4-6`
-- `anthropic.claude-opus-4-6-v1:0`
-- `us.anthropic.claude-opus-4-6-v1:0`
-- `claude-opus-4-6`
-
-### With Version Date
-
-```regex
-(?i)^(anthropic\/)?(claude-opus-4-5-20251101|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-5-20251101-v1:0|claude-opus-4-5@20251101)$
-```
-
-### OpenAI
-
-```regex
-(?i)^(openai\/)?(gpt-4o)$
-```
-
-### Google Gemini
-
-```regex
-(?i)^(google\/)?(gemini-2.5-pro)$
-```
-
-### Pattern Components
-
-| Component | Purpose | Example |
-| --- | --- | --- |
-| `(?i)` | Case-insensitive match | `gpt-4o` and `GPT-4O` |
-| `^...$` | Full-string match | Avoids partial matches |
-| `(provider\/)?` | Optional provider prefix | `openai/gpt-4o` |
-| `(eu\\.|us\\.|apac\\.)?` | Optional AWS region prefix | `us.anthropic.model` |
-| `(:0)?` | Optional version suffix | Bedrock model versions |
-| `@date` | Vertex AI version format | `claude-3-5-sonnet@20240620` |
-
-## Step-by-Step Workflow
-
-### 1. Fetch Official Pricing
-
-Open the official provider pricing page and capture the model's input, output,
-cache write, and cache read prices.
-
-### 2. Generate a Lowercase UUID
-
-```bash
-uuidgen
-```
-
-Convert the output to lowercase before using it.
-
-### 3. Create the JSON Entry
-
-Example for a model with $5 input, $25 output, $6.25 cache write, and
-$0.50 cache read:
-
-```json
-{
- "id": "13458bc0-1c20-44c2-8753-172f54b67647",
- "modelName": "claude-opus-4-6",
- "matchPattern": "(?i)^(anthropic\/)?(claude-opus-4-6|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-6-v1(:0)?|claude-opus-4-6)$",
- "createdAt": "2026-03-09T00:00:00.000Z",
- "updatedAt": "2026-03-09T00:00:00.000Z",
- "tokenizerConfig": null,
- "tokenizerId": "claude",
- "pricingTiers": [
- {
- "id": "13458bc0-1c20-44c2-8753-172f54b67647_tier_default",
- "name": "Standard",
- "isDefault": true,
- "priority": 0,
- "conditions": [],
- "prices": {
- "input": 5e-6,
- "input_tokens": 5e-6,
- "output": 25e-6,
- "output_tokens": 25e-6,
- "cache_creation_input_tokens": 6.25e-6,
- "input_cache_creation": 6.25e-6,
- "cache_read_input_tokens": 0.5e-6,
- "input_cache_read": 0.5e-6
- }
- }
- ]
-}
-```
-
-### 4. Insert the Entry
-
-Add the entry to the JSON array in
-`worker/src/constants/default-model-prices.json`. Keep related models grouped
-together.
-
-### 5. Update Shared Model Types When Needed
-
-If the model should be available in the playground or LLM-as-judge flows, add
-it to the correct array in `packages/shared/src/server/llm/types.ts`.
-
-Model arrays include:
-
-- `anthropicModels`
-- `openAIModels`
-- `vertexAIModels`
-- `googleAIStudioModels`
-
-Do not add a new model as the first entry in one of these arrays. The first
-entry is used as a default model in some test or evaluation paths and newer
-models may not be available to all users yet.
-
-### 6. Validate the Change
-
-```bash
-jq . worker/src/constants/default-model-prices.json > /dev/null
-```
-
-You can also inspect a specific entry:
-
-```bash
-jq '.[] | select(.modelName == "claude-opus-4-6")' worker/src/constants/default-model-prices.json
-```
-
-## Multi-Tier Example
-
-For models with long-context pricing:
-
-```json
-{
- "id": "uuid-here",
- "modelName": "model-name",
- "matchPattern": "...",
- "pricingTiers": [
- {
- "id": "uuid-here_tier_default",
- "name": "Standard",
- "isDefault": true,
- "priority": 0,
- "conditions": [],
- "prices": {
- "input": 5e-6,
- "output": 25e-6
- }
- },
- {
- "id": "uuid-for-large-context-tier",
- "name": "Large Context (>200K)",
- "isDefault": false,
- "priority": 1,
- "conditions": [
- {
- "usageDetailPattern": "(input|prompt|cached)",
- "operator": "gt",
- "value": 200000,
- "caseSensitive": false
- }
- ],
- "prices": {
- "input": 10e-6,
- "output": 37.5e-6
- }
- }
- ]
-}
-```
-
-## Validation Rules
-
-1. Exactly one default tier must have `isDefault: true`
-2. The default tier must have `priority: 0`
-3. The default tier must have `conditions: []`
-4. Non-default tiers must have `priority > 0`
-5. Non-default tiers must have at least one condition
-6. Priorities must be unique within a model
-7. Tier names must be unique within a model
-8. Each tier must contain at least one price
-9. All tiers must expose the same usage-type keys
-10. Regex patterns must be valid and safe
-
-## Common Mistakes
-
-### Guessing Instead of Using Official Pricing
-
-Wrong:
-
-```json
-{
- "cache_creation_input_tokens": "input_price * 1.25"
-}
-```
-
-Correct:
-
-```json
-{
- "cache_creation_input_tokens": 6.25e-6
-}
-```
-
-### Using MTok Values Directly
-
-Wrong:
-
-```json
-{
- "input": 5
-}
-```
-
-Correct:
-
-```json
-{
- "input": 5e-6
-}
-```
-
-### Missing the Default Tier Suffix
-
-Wrong:
-
-```json
-{
- "id": "some-uuid"
-}
-```
-
-Correct:
-
-```json
-{
- "id": "model-uuid_tier_default"
-}
-```
-
-### Invalid Regex Escaping
-
-Wrong:
-
-```json
-{
- "matchPattern": "anthropic.claude"
-}
-```
-
-Correct:
-
-```json
-{
- "matchPattern": "anthropic\\.claude"
-}
-```
-
-### Forgetting to Update `updatedAt`
-
-Wrong:
-
-```json
-{
- "updatedAt": "2025-12-12T15:00:06.513Z"
-}
-```
-
-Correct:
-
-```json
-{
- "updatedAt": "2026-03-09T00:00:00.000Z"
-}
-```
-
-## Testing Model Matching
-
-After adding a model, verify that the regex matches the intended provider
-variants:
-
-```javascript
-const pattern = new RegExp(matchPattern);
-console.log(pattern.test("claude-opus-4-6")); // true
-console.log(pattern.test("anthropic/claude-opus-4-6")); // true
-console.log(pattern.test("anthropic.claude-opus-4-6-v1:0")); // true
-console.log(pattern.test("us.anthropic.claude-opus-4-6-v1:0")); // true
-```
-
-## Existing Model Templates
-
-Use nearby entries as templates:
-
-- `claude-opus-4-5-20251101` for Anthropic multi-provider patterns
-- `gpt-4o` for a simple OpenAI pattern
-- `gemini-2.5-pro` for a multi-tier Gemini entry
diff --git a/.agents/skills/add-model-price/SKILL.md b/.agents/skills/add-model-price/SKILL.md
index 091cda3163..4f0c0e6ace 100644
--- a/.agents/skills/add-model-price/SKILL.md
+++ b/.agents/skills/add-model-price/SKILL.md
@@ -19,18 +19,36 @@ updates in `packages/shared/`.
## How to Read This Skill
-- Start with [AGENTS.md](AGENTS.md) for the high-level workflow and helper
- scripts.
-- Then open only the specific reference file that matches the task.
+- Use this `SKILL.md` as the high-level workflow and helper index.
+- Open only the specific reference file that matches the task.
+
+## Quick Start Checklist
+
+### Adding a New Model
+
+- Gather official pricing from the provider documentation.
+- Generate a lowercase UUID for the model entry.
+- Create a `matchPattern` that covers supported provider formats.
+- Add at least one default pricing tier.
+- Insert the pricing entry into `worker/src/constants/default-model-prices.json`.
+- Update `packages/shared/src/server/llm/types.ts` if the model should be
+ selectable in playground or evaluation flows.
+- Validate the JSON after editing.
+
+### Updating an Existing Model
+
+- Update the relevant prices, keys, tiers, or regexes.
+- Refresh `updatedAt` to today's ISO-8601 timestamp.
+- Validate the JSON after editing.
## Reference Map
-| Topic | Read this when | File |
-| --- | --- | --- |
-| Schema and tier rules | You need the entry shape or pricing-tier invariants | [references/schema-and-tiers.md](references/schema-and-tiers.md) |
+| Topic | Read this when | File |
+| ------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| Schema and tier rules | You need the entry shape or pricing-tier invariants | [references/schema-and-tiers.md](references/schema-and-tiers.md) |
| Provider sources and price keys | You need official pricing URLs, per-token conversion, or provider-specific usage keys | [references/provider-sources-and-price-keys.md](references/provider-sources-and-price-keys.md) |
-| Match patterns | You are editing `matchPattern` regexes or provider coverage | [references/match-patterns.md](references/match-patterns.md) |
-| Workflow and validation | You are applying the end-to-end edit process or checking common mistakes | [references/workflow-and-validation.md](references/workflow-and-validation.md) |
+| Match patterns | You are editing `matchPattern` regexes or provider coverage | [references/match-patterns.md](references/match-patterns.md) |
+| Workflow and validation | You are applying the end-to-end edit process or checking common mistakes | [references/workflow-and-validation.md](references/workflow-and-validation.md) |
## Deterministic Helpers
@@ -38,3 +56,5 @@ updates in `packages/shared/`.
`node .agents/skills/add-model-price/scripts/validate-pricing-file.mjs`
- Match-pattern tester:
`node .agents/skills/add-model-price/scripts/test-match-pattern.mjs --model <modelName> --accept <sample...> --reject <sample...>`
+- Direct regex tester:
+ `node .agents/skills/add-model-price/scripts/test-match-pattern.mjs --pattern '(?i)^(openai/)?(gpt-4o)$' --accept gpt-4o openai/gpt-4o --reject gpt-4o-mini`
diff --git a/.agents/skills/add-model-price/references/schema-and-tiers.md b/.agents/skills/add-model-price/references/schema-and-tiers.md
index b4bb1ee182..b2c9456812 100644
--- a/.agents/skills/add-model-price/references/schema-and-tiers.md
+++ b/.agents/skills/add-model-price/references/schema-and-tiers.md
@@ -94,3 +94,45 @@ Use extra tiers for context-window or usage-based pricing:
```
Supported operators: `gt`, `gte`, `lt`, `lte`, `eq`, `neq`
+
+## Multi-Tier Example
+
+Use multiple tiers when a provider changes pricing by context window or usage
+class. Keep exactly one default tier and assign higher priorities to conditional
+tiers:
+
+```json
+{
+ "pricingTiers": [
+ {
+ "id": "{model-id}_tier_default",
+ "name": "Standard",
+ "isDefault": true,
+ "priority": 0,
+ "conditions": [],
+ "prices": {
+ "input": 0.000001,
+ "output": 0.000002
+ }
+ },
+ {
+ "id": "uuid-for-large-context-tier",
+ "name": "Large Context (>200K)",
+ "isDefault": false,
+ "priority": 1,
+ "conditions": [
+ {
+ "usageDetailPattern": "(input|prompt|cached)",
+ "operator": "gt",
+ "value": 200000,
+ "caseSensitive": false
+ }
+ ],
+ "prices": {
+ "input": 0.000002,
+ "output": 0.000004
+ }
+ }
+ ]
+}
+```
diff --git a/.agents/skills/add-model-price/references/workflow-and-validation.md b/.agents/skills/add-model-price/references/workflow-and-validation.md
index 735dcbf05c..24e345f06c 100644
--- a/.agents/skills/add-model-price/references/workflow-and-validation.md
+++ b/.agents/skills/add-model-price/references/workflow-and-validation.md
@@ -22,10 +22,58 @@ template, then:
- add the new entry near related models
- refresh `updatedAt` when editing an existing entry
-- update `packages/shared/src/server/llm/types.ts` when the model should be
- selectable in product flows
-### 4. Validate the Result
+Example for a model with `$5` input, `$25` output, `$6.25` cache write, and
+`$0.50` cache read per million tokens:
+
+```json
+{
+ "id": "13458bc0-1c20-44c2-8753-172f54b67647",
+ "modelName": "claude-opus-4-6",
+ "matchPattern": "(?i)^(anthropic\/)?(claude-opus-4-6|(eu\\.|us\\.|apac\\.)?anthropic\\.claude-opus-4-6-v1(:0)?)$",
+ "createdAt": "2026-03-09T00:00:00.000Z",
+ "updatedAt": "2026-03-09T00:00:00.000Z",
+ "tokenizerConfig": null,
+ "tokenizerId": "claude",
+ "pricingTiers": [
+ {
+ "id": "13458bc0-1c20-44c2-8753-172f54b67647_tier_default",
+ "name": "Standard",
+ "isDefault": true,
+ "priority": 0,
+ "conditions": [],
+ "prices": {
+ "input": 5e-6,
+ "input_tokens": 5e-6,
+ "output": 25e-6,
+ "output_tokens": 25e-6,
+ "cache_creation_input_tokens": 6.25e-6,
+ "input_cache_creation": 6.25e-6,
+ "cache_read_input_tokens": 0.5e-6,
+ "input_cache_read": 0.5e-6
+ }
+ }
+ ]
+}
+```
+
+### 4. Update Shared Model Types When Needed
+
+If the model should be available in playground or LLM-as-judge flows, add it to
+the correct array in `packages/shared/src/server/llm/types.ts`.
+
+Common arrays include:
+
+- `anthropicModels`
+- `openAIModels`
+- `vertexAIModels`
+- `googleAIStudioModels`
+
+Do not add a new model as the first entry in one of these arrays. The first
+entry is used as a default model in some test or evaluation paths, and newer
+models may not be available to all users yet.
+
+### 5. Validate the Result
Run the bundled validator:
@@ -33,6 +81,12 @@ Run the bundled validator:
node .agents/skills/add-model-price/scripts/validate-pricing-file.mjs
```
+For quick manual inspection, use `jq`:
+
+```bash
+jq '.[] | select(.modelName == "claude-opus-4-6")' worker/src/constants/default-model-prices.json
+```
+
## Validation Rules
1. Exactly one default tier must have `isDefault: true`
@@ -46,6 +100,17 @@ node .agents/skills/add-model-price/scripts/validate-pricing-file.mjs
9. All tiers must expose the same usage-type keys
10. Regex patterns must be valid
+## Testing Model Matching
+
+Use the bundled tester before finishing any `matchPattern` change:
+
+```bash
+node .agents/skills/add-model-price/scripts/test-match-pattern.mjs --model <modelName> --accept <sample...> --reject <sample...>
+```
+
+Use representative accepted and rejected model IDs for every provider format the
+regex is intended to cover.
+
## Common Mistakes
- Guessing prices instead of using official provider docs
diff --git a/.agents/skills/agent-setup-maintenance/SKILL.md b/.agents/skills/agent-setup-maintenance/SKILL.md
index 5dc8229e8d..cffa70bfcc 100644
--- a/.agents/skills/agent-setup-maintenance/SKILL.md
+++ b/.agents/skills/agent-setup-maintenance/SKILL.md
@@ -31,13 +31,13 @@ Use this skill when changing the shared agent setup for the repository.
3. Treat tool-specific directories such as `.claude/`, `.cursor/`, `.codex/`,
`.vscode/`, and `.mcp.json` as generated discovery surfaces unless the tool
requires a truly tool-specific feature.
-4. Keep root `AGENTS.md` concise and router-like. Move detailed or conditional
- workflows into shared skills or package `AGENTS.md` files.
+4. Keep root `AGENTS.md` concise. Move detailed or conditional workflows into
+ shared skills or package `AGENTS.md` files.
5. Treat developer feedback as a learning loop: when a task reveals a durable
repo convention, recurring pitfall, reusable workflow, or verification
pattern, update the smallest relevant `AGENTS.md` or shared skill.
-6. When adding or changing a shared skill, update `skills/README.md` and link
- it from root `AGENTS.md` if it changes the default reusable workflow.
+6. When adding or changing a shared skill, keep `SKILL.md` as the entrypoint; do
+ not add skill-by-skill links to root `AGENTS.md`.
7. When shared setup behavior changes materially, update `README.md` and
contributor-facing docs in the same PR.
diff --git a/.agents/skills/backend-dev-guidelines/AGENTS.md b/.agents/skills/backend-dev-guidelines/AGENTS.md
deleted file mode 100644
index 5e5586e723..0000000000
--- a/.agents/skills/backend-dev-guidelines/AGENTS.md
+++ /dev/null
@@ -1,320 +0,0 @@
-# Backend Development Guidelines
-
-## Purpose
-
-Establish consistency and best practices across Langfuse's backend packages
-(`web`, `worker`, `packages/shared`) using Next.js, tRPC, BullMQ, and TypeScript
-patterns. Check package manifests such as `web/package.json` for current
-framework versions before version-sensitive work.
-Keep this file as an entrypoint; open reference files only when the task needs
-their details.
-
-## When to Use This Skill
-
-Use this guide when working on:
-
-- Creating or modifying tRPC routers and procedures
-- Creating or modifying public API endpoints (REST)
-- Creating or modifying BullMQ queue consumers and producers
-- Building services with business logic
-- Authenticating API requests
-- Accessing resources based on entitlements
-- Implementing middleware (tRPC, NextAuth, public API)
-- Database operations with Prisma (PostgreSQL) or ClickHouse
-- Observability with OpenTelemetry, DataDog, logger, and traceException
-- Input validation with Zod v4
-- Environment configuration from env variables
-- Backend testing and refactoring
-
----
-
-## Quick Start
-
-### UI: New tRPC Feature Checklist (Web)
-
-- [ ] **Router**: Define in `features/[feature]/server/*Router.ts`
-- [ ] **Procedures**: Use appropriate procedure type (protected, public)
-- [ ] **Authentication**: Use JWT authorization via middlewares.
-- [ ] **Entitlement check**: Access resources based on resource and role
-- [ ] **Validation**: Zod v4 schema for input
-- [ ] **Service**: Business logic in service file
-- [ ] **Error handling**: Use traceException wrapper
-- [ ] **Tests**: Unit + integration tests in `__tests__/`
-- [ ] **Config**: Access via env.mjs
-
-### SDKs: New Public API Endpoint Checklist (Web)
-
-- [ ] **Route file**: Create in `pages/api/public/`
-- [ ] **Wrapper**: Use `withMiddlewares` + `createAuthedProjectAPIRoute`
-- [ ] **Types**: Define in `features/public-api/types/`
-- [ ] **Authentication**: Authorization via basic auth
-- [ ] **Validation**: Zod schemas for query/body/response
-- [ ] **Versioning**: Versioning in API path and Zod schemas for query/body/response
-- [ ] **Fern API Docs**: Update `fern/apis/server/definition/` to match TypeScript types
-- [ ] **Tests**: Add end-to-end test in `__tests__/async/`
-
-### New Queue Processor Checklist (Worker)
-
-- [ ] **Processor**: Create in `worker/src/queues/`
-- [ ] **Queue types**: Create queue types in `packages/shared/src/server/queues`
-- [ ] **Service**: Business logic in `features/` or `worker/src/features/`
-- [ ] **Error handling**: Distinguish between errors which should fail queue processing and errors which should result in a succeeded event.
-- [ ] **Queue registration**: Add to WorkerManager in app.ts
-- [ ] **Tests**: Add vitest tests in worker
-
----
-
-## Architecture Overview
-
-### Layered Architecture
-
-```
-# Web Package (Next.js)
-
-β”Œβ”€ tRPC API ──────────────────┐ β”Œβ”€β”€ Public REST API ──────────┐
-β”‚ β”‚ β”‚ β”‚
-β”‚ HTTP Request β”‚ β”‚ HTTP Request β”‚
-β”‚ ↓ β”‚ β”‚ ↓ β”‚
-β”‚ tRPC Procedure β”‚ β”‚ withMiddlewares + β”‚
-β”‚ (protectedProjectProcedure)β”‚ β”‚ createAuthedProjectAPIRouteβ”‚
-β”‚ ↓ β”‚ β”‚ ↓ β”‚
-β”‚ Service (business logic) β”‚ β”‚ Service (business logic) β”‚
-β”‚ ↓ β”‚ β”‚ ↓ β”‚
-β”‚ Prisma / ClickHouse β”‚ β”‚ Prisma / ClickHouse β”‚
-β”‚ β”‚ β”‚ β”‚
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
- ↓
- [optional]: Publish to Redis BullMQ queue
- ↓
-β”Œβ”€ Worker Package (Express) ──────────────────────────────────┐
-β”‚ β”‚
-β”‚ BullMQ Queue Job β”‚
-β”‚ ↓ β”‚
-β”‚ Queue Processor (handles job) β”‚
-β”‚ ↓ β”‚
-β”‚ Service (business logic) β”‚
-β”‚ ↓ β”‚
-β”‚ Prisma / ClickHouse β”‚
-β”‚ β”‚
-β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
-```
-
-**Key Principles:**
-
-- **Web**: tRPC procedures for UI OR public API routes for SDKs β†’ Services β†’ Database
-- **Worker**: Queue processors β†’ Services β†’ Database
-- **packages/shared**: Shared code for Web and Worker
-
-See [references/architecture-overview.md](references/architecture-overview.md)
-for complete details.
-
----
-
-## Core Principles
-
-### 1. tRPC Procedures Delegate to Services
-
-```typescript
-// ❌ NEVER: Business logic in procedures
-export const traceRouter = createTRPCRouter({
- byId: protectedProjectProcedure
- .input(z.object({ traceId: z.string() }))
- .query(async ({ input, ctx }) => {
- // 200 lines of logic here
- }),
-});
-
-// βœ… ALWAYS: Delegate to service
-export const traceRouter = createTRPCRouter({
- byId: protectedProjectProcedure
- .input(z.object({ traceId: z.string() }))
- .query(async ({ input, ctx }) => {
- return await getTraceById(input.traceId);
- }),
-});
-```
-
-### 2. Access Config via env.mjs, NEVER process.env
-
-```typescript
-// ❌ NEVER (except in env.mjs itself)
-const dbUrl = process.env.DATABASE_URL;
-
-// βœ… ALWAYS
-import { env } from "@/src/env.mjs";
-const dbUrl = env.DATABASE_URL;
-```
-
-### 3. Validate ALL Input with Zod v4
-
-```typescript
-import { z } from "zod/v4";
-
-const schema = z.object({
- email: z.string().email(),
- projectId: z.string(),
-});
-const validated = schema.parse(input);
-```
-
-### 4. Services Use Prisma Directly for Simple CRUD or Repositories for Complex Queries
-
-```typescript
-// Services use Prisma directly for simple CRUD
-import { prisma } from "@langfuse/shared/src/db";
-
-const dataset = await prisma.dataset.findUnique({
- where: { id: datasetId, projectId }, // Always filter by projectId for tenant isolation
-});
-
-// Or use repositories for complex queries (traces, observations, scores)
-import { getTracesTable } from "@langfuse/shared/src/server";
-
-const traces = await getTracesTable({
- projectId,
- filter: [...],
- limit: 1000,
-});
-```
-
-### 6. Observability: OpenTelemetry + DataDog (Not Sentry for Backend)
-
-**Langfuse uses OpenTelemetry for backend observability, with traces and logs sent to DataDog.**
-
-```typescript
-// Import observability utilities
-import {
- logger, // Winston logger with OpenTelemetry/DataDog context
- traceException, // Record exceptions to OpenTelemetry spans
- instrumentAsync, // Create instrumented spans
-} from "@langfuse/shared/src/server";
-
-// Structured logging (includes trace_id, span_id, dd.trace_id)
-logger.info("Processing dataset", { datasetId, projectId });
-logger.error("Failed to create dataset", { error: err.message });
-
-// Record exceptions to OpenTelemetry (sent to DataDog)
-try {
- await operation();
-} catch (error) {
- traceException(error); // Records to current span
- throw error;
-}
-
-// Instrument critical operations (all API routes auto-instrumented)
-const result = await instrumentAsync(
- { name: "dataset.create" },
- async (span) => {
- span.setAttributes({ datasetId, projectId });
- // Operation here
- return dataset;
- },
-);
-```
-
-**Note**: Frontend uses Sentry, but backend (tRPC, API routes, services, worker) uses OpenTelemetry + DataDog.
-
-### 7. Comprehensive Testing Required
-
-Add targeted tests for new backend behavior and bug fixes. Keep tests
-independent and parallel-safe. See
-[testing-guide.md](references/testing-guide.md) for tRPC, public API, service,
-repository, and worker examples.
-
-### 8. Always Filter by projectId for Tenant Isolation
-
-```typescript
-// βœ… CORRECT: Filter by projectId for tenant isolation
-const trace = await prisma.trace.findUnique({
- where: { id: traceId, projectId }, // Required for multi-tenant data isolation
-});
-
-// βœ… CORRECT: ClickHouse queries also require projectId
-const traces = await queryClickhouse({
- query: `
- SELECT * FROM traces
- WHERE project_id = {projectId: String}
- AND timestamp >= {startTime: DateTime64(3)}
- `,
- params: { projectId, startTime },
-});
-```
-
-### 9. Keep Fern API Definitions in Sync with TypeScript Types
-
-When modifying public API types in `web/src/features/public-api/types/`, the corresponding Fern API definitions in `fern/apis/server/definition/` must be updated to match.
-
-**Zod to Fern Type Mapping:**
-
-| Zod Type | Fern Type | Example |
-| -------- | --------- | ------- |
-| `.nullish()` | `optional<nullable<T>>` | `z.string().nullish()` β†’ `optional<nullable<string>>` |
-| `.nullable()` | `nullable<T>` | `z.string().nullable()` β†’ `nullable<string>` |
-| `.optional()` | `optional<T>` | `z.string().optional()` β†’ `optional<string>` |
-| Always present | `T` | `z.string()` β†’ `string` |
-
-**Source References:**
-
-Add a comment at the top of each Fern type referencing the TypeScript source file:
-
-```yaml
-# Source: web/src/features/public-api/types/traces.ts - APITrace
-Trace:
- properties:
- id: string
- name:
- type: nullable<string>
-```
-
----
-
-## Live Examples
-
-Reference existing Langfuse features for implementation patterns:
-- tRPC router with project auth and Zod input:
- `web/src/features/events/server/eventsRouter.ts`
-- Public API route with middleware and typed request/response schemas:
- `web/src/pages/api/public/datasets/index.ts`
-- Worker queue processor with typed jobs, logging, and retry behavior:
- `worker/src/queues/evalQueue.ts`
-- Tenant filters for Prisma and ClickHouse:
- `references/database-patterns.md`
-
----
-
-## Naming Conventions
-
-- tRPC routers: `camelCaseRouter.ts`, e.g. `datasetRouter.ts`
-- Services: `service.ts` in the feature server directory
-- Queue processors: `camelCaseQueue.ts`, e.g. `evalQueue.ts`
-- Public API routes: kebab-case filenames, e.g. `dataset-items.ts`
-
----
-
-## Anti-Patterns to Avoid
-
-❌ Business logic in routes/procedures
-❌ Direct process.env usage (always use env.mjs/env.ts)
-❌ Missing error handling
-❌ No input validation (always use Zod v4)
-❌ Missing projectId filter on tenant-scoped queries
-❌ console.log instead of logger/traceException (OpenTelemetry)
-
----
-
-## Navigation Guide
-
-Keep detailed backend guidance in these focused reference files and open only
-the one that matches the task.
-
-| Need to... | Read this |
-| ------------------------- | ------------------------------------------------------------ |
-| Understand architecture | [architecture-overview.md](references/architecture-overview.md) |
-| Create routes/controllers | [routing-and-controllers.md](references/routing-and-controllers.md) |
-| Organize business logic | [services-and-repositories.md](references/services-and-repositories.md) |
-| Create middleware | [middleware-guide.md](references/middleware-guide.md) |
-| Database access | [database-patterns.md](references/database-patterns.md) |
-| Manage config | [configuration.md](references/configuration.md) |
-| Write tests | [testing-guide.md](references/testing-guide.md) |
-
----
diff --git a/.agents/skills/backend-dev-guidelines/SKILL.md b/.agents/skills/backend-dev-guidelines/SKILL.md
index 3e8b98ffef..74861ec589 100644
--- a/.agents/skills/backend-dev-guidelines/SKILL.md
+++ b/.agents/skills/backend-dev-guidelines/SKILL.md
@@ -20,24 +20,93 @@ Use this skill for backend and API work across `web/`, `worker/`, and
## How to Read This Skill
-- Start with [AGENTS.md](AGENTS.md) when the task spans multiple backend areas
- or you need the end-to-end checklists.
+- Use this `SKILL.md` when the task spans multiple backend areas or you need the
+ end-to-end reference map.
- Read only the specific reference file that matches the work when the scope is
narrower.
-## Reference Map
+## Quick Start Checklists
+
+### UI: New tRPC Feature
+
+- Define the router in `features/[feature]/server/*Router.ts`.
+- Use the appropriate protected or public procedure.
+- Authenticate with JWT-aware middleware.
+- Check project/resource access and entitlements.
+- Validate input with Zod v4.
+- Put business logic in a service file.
+- Use `traceException` for error handling where relevant.
+- Add unit or integration tests in `__tests__/`.
+- Access config via `env.mjs`.
+
+### SDKs: New Public API Endpoint
+
+- Create the route in `pages/api/public/`.
+- Wrap it with `withMiddlewares` and `createAuthedProjectAPIRoute`.
+- Define types in `features/public-api/types/`.
+- Authenticate with basic auth.
+- Validate query, body, and response with Zod schemas.
+- Include API versioning in paths and schemas.
+- Update Fern API definitions to match TypeScript types.
+- Add end-to-end tests in `__tests__/async/`.
+
+### Worker: New Queue Processor
+
+- Create the processor in `worker/src/queues/`.
+- Define queue types in `packages/shared/src/server/queues`.
+- Place business logic in `features/` or `worker/src/features/`.
+- Distinguish failed jobs from jobs that should succeed with a recorded error.
+- Register the queue in `WorkerManager` in `app.ts`.
+- Add worker vitest coverage.
+
+## Core Principles
-| Topic | Read this when | File |
-| --- | --- | --- |
-| Architecture and package boundaries | You need the web/worker/shared split, request flow, or queue lifecycle | [references/architecture-overview.md](references/architecture-overview.md) |
-| Routing and controllers | You are writing tRPC procedures, public API routes, or queue entrypoints | [references/routing-and-controllers.md](references/routing-and-controllers.md) |
-| Middleware and auth | You are changing request auth, permissions, or middleware composition | [references/middleware-guide.md](references/middleware-guide.md) |
-| Services and repositories | You are placing business logic, repository code, or DI patterns | [references/services-and-repositories.md](references/services-and-repositories.md) |
-| Database access | You are touching Prisma, ClickHouse, tenant filters, or query patterns | [references/database-patterns.md](references/database-patterns.md) |
-| Configuration | You are adding env vars, startup config, or runtime toggles | [references/configuration.md](references/configuration.md) |
-| Testing | You are adding or updating backend tests | [references/testing-guide.md](references/testing-guide.md) |
+- tRPC procedures, public API routes, and queue processors delegate business
+ logic to services.
+- Access configuration through `env.mjs`; do not read `process.env` directly
+ outside env setup.
+- Validate all external input with Zod v4.
+- Use Prisma directly for simple CRUD and repositories for complex query access.
+- Use OpenTelemetry and DataDog for backend observability.
+- Always filter project-scoped database queries by `projectId`.
+- Keep Fern API definitions in sync with public TypeScript API contracts.
+- Keep backend tests independent and parallel-safe.
-## Full Compiled Guide
+## Live Examples
+
+- tRPC router with project auth and Zod input:
+ `web/src/features/events/server/eventsRouter.ts`.
+- Public API route with middleware and typed request/response schemas:
+ `web/src/pages/api/public/datasets/index.ts`.
+- Worker queue processor with typed jobs, logging, and retry behavior:
+ `worker/src/queues/evalQueue.ts`.
+- Tenant filters for Prisma and ClickHouse:
+ `references/database-patterns.md`.
+
+## Naming Conventions
+
+- tRPC routers: `camelCaseRouter.ts`, for example `datasetRouter.ts`.
+- Services: `service.ts` in the feature server directory.
+- Queue processors: `camelCaseQueue.ts`, for example `evalQueue.ts`.
+- Public API routes: kebab-case filenames, for example `dataset-items.ts`.
+
+## Anti-Patterns to Avoid
+
+- Business logic in routes or procedures.
+- Direct `process.env` usage instead of `env.mjs` / `env.ts`.
+- Missing error handling.
+- Missing input validation.
+- Missing `projectId` filters on tenant-scoped queries.
+- `console.log` instead of `logger` / `traceException`.
+
+## Reference Map
-Read [AGENTS.md](AGENTS.md) for the complete backend guide with checklists,
-directory conventions, imports, architecture, and cross-cutting practices.
+| Topic | Read this when | File |
+| ----------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
+| Architecture and package boundaries | You need the web/worker/shared split, request flow, or queue lifecycle | [references/architecture-overview.md](references/architecture-overview.md) |
+| Routing and controllers | You are writing tRPC procedures, public API routes, or queue entrypoints | [references/routing-and-controllers.md](references/routing-and-controllers.md) |
+| Middleware and auth | You are changing request auth, permissions, or middleware composition | [references/middleware-guide.md](references/middleware-guide.md) |
+| Services and repositories | You are placing business logic, repository code, or DI patterns | [references/services-and-repositories.md](references/services-and-repositories.md) |
+| Database access | You are touching Prisma, ClickHouse, tenant filters, or query patterns | [references/database-patterns.md](references/database-patterns.md) |
+| Configuration | You are adding env vars, startup config, or runtime toggles | [references/configuration.md](references/configuration.md) |
+| Testing | You are adding or updating backend tests | [references/testing-guide.md](references/testing-guide.md) |
diff --git a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
index 4fca1a8dec..593935a0fa 100644
--- a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
+++ b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
@@ -864,7 +864,7 @@ const validated = bodySchema.parse(req.body);
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main guide
+- [../SKILL.md](../SKILL.md) - Main guide
- [routing-and-controllers.md](routing-and-controllers.md) - tRPC and Public API details
- [services-and-repositories.md](services-and-repositories.md) - Service patterns
- [testing-guide.md](testing-guide.md) - Testing strategies
diff --git a/.agents/skills/backend-dev-guidelines/references/configuration.md b/.agents/skills/backend-dev-guidelines/references/configuration.md
index 19475714f8..714af9c1b8 100644
--- a/.agents/skills/backend-dev-guidelines/references/configuration.md
+++ b/.agents/skills/backend-dev-guidelines/references/configuration.md
@@ -286,7 +286,7 @@ const licenseKey = env.LANGFUSE_EE_LICENSE_KEY;
**When Set:**
| Environment | Value | Purpose |
-|--------------------------|------------------------|------------------------------------------------|
+| ------------------------ | ---------------------- | ---------------------------------------------- |
| **Developer Laptop** | `"DEV"` or `"STAGING"` | Local development against cloud infrastructure |
| **Langfuse Cloud US** | `"US"` | Production US region |
| **Langfuse Cloud EU** | `"EU"` | Production EU region |
@@ -559,5 +559,5 @@ langfuse/
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main guide
+- [../SKILL.md](../SKILL.md) - Main guide
- [architecture-overview.md](architecture-overview.md) - Architecture patterns
diff --git a/.agents/skills/backend-dev-guidelines/references/database-patterns.md b/.agents/skills/backend-dev-guidelines/references/database-patterns.md
index 18abe06da3..5582679077 100644
--- a/.agents/skills/backend-dev-guidelines/references/database-patterns.md
+++ b/.agents/skills/backend-dev-guidelines/references/database-patterns.md
@@ -57,7 +57,7 @@ const project = await prisma.project.create({
// βœ… GOOD: Read with projectId filter
const trace = await prisma.trace.findUnique({
- where: { id: traceId, projectId }, // ← Always include projectId for tenant isolation
+ where: { id: traceId, projectId }, // ← Always include projectId for tenant isolation
include: {
scores: true,
project: { select: { id: true, name: true } },
@@ -77,12 +77,12 @@ await prisma.user.update({
// βœ… GOOD: Delete with projectId
await prisma.apiKey.delete({
- where: { id: apiKeyId, projectId }, // ← Always include projectId
+ where: { id: apiKeyId, projectId }, // ← Always include projectId
});
// βœ… GOOD: Count with projectId
const traceCount = await prisma.trace.count({
- where: { projectId, userId }, // ← Always include projectId
+ where: { projectId, userId }, // ← Always include projectId
});
```
@@ -225,7 +225,7 @@ const rows = await queryClickhouse<{ id: string; name: string }>({
LIMIT {limit: UInt32}
`,
params: {
- projectId, // ← Required for tenant isolation
+ projectId, // ← Required for tenant isolation
startTime: convertDateToClickhouseDateTime(startDate),
limit: 100,
},
@@ -341,6 +341,7 @@ const query = `
```
**Why this is important:**
+
- Langfuse is multi-tenant - each project's data must be isolated
- The `project_id` filter ensures queries only access data from the intended tenant
- All queries on project-scoped tables (traces, observations, scores, sessions, etc.) must filter by `project_id`
@@ -548,6 +549,7 @@ export const getScoresByTraceId = async (
### Project-Scoped vs Global Tables
**Project-scoped tables (MUST filter by `project_id`):**
+
- `traces` - All trace queries require `project_id`
- `observations` - All observation queries require `project_id`
- `scores` - All score queries require `project_id`
@@ -555,6 +557,7 @@ export const getScoresByTraceId = async (
- `dataset_run_items_rmt` - All dataset run queries require `project_id`
**Global tables (no `project_id` filter needed):**
+
- `users` - User management (use `id` for filtering)
- `organizations` - Organization data (use `id` for filtering)
- System configuration tables
@@ -627,12 +630,12 @@ try {
**Common Prisma error codes:**
-| Code | Meaning | Typical Cause |
-| -------- | ---------------------------- | ------------------------------------- |
-| `P2002` | Unique constraint violation | Duplicate email, API key, etc. |
-| `P2003` | Foreign key constraint | Referenced record doesn't exist |
-| `P2025` | Record not found | Update/delete of non-existent record |
-| `P2018` | Required relation not found | Connect to non-existent related record |
+| Code | Meaning | Typical Cause |
+| ------- | --------------------------- | -------------------------------------- |
+| `P2002` | Unique constraint violation | Duplicate email, API key, etc. |
+| `P2003` | Foreign key constraint | Referenced record doesn't exist |
+| `P2025` | Record not found | Update/delete of non-existent record |
+| `P2018` | Required relation not found | Connect to non-existent related record |
### ClickHouse Errors
@@ -664,11 +667,11 @@ try {
**ClickHouse error types:**
-| Error Type | Discriminator | Meaning | Solution |
-| --------------- | ----------------------- | ---------------------------- | -------------------------------------------------- |
-| `MEMORY_LIMIT` | "memory limit exceeded" | Query used too much memory | Use more specific filters or shorter time range |
-| `OVERCOMMIT` | "OvercommitTracker" | Memory overcommit limit hit | Reduce query complexity or result set size |
-| `TIMEOUT` | "Timeout", "timed out" | Query took too long | Add filters, reduce time range, or optimize query |
+| Error Type | Discriminator | Meaning | Solution |
+| -------------- | ----------------------- | --------------------------- | ------------------------------------------------- |
+| `MEMORY_LIMIT` | "memory limit exceeded" | Query used too much memory | Use more specific filters or shorter time range |
+| `OVERCOMMIT` | "OvercommitTracker" | Memory overcommit limit hit | Reduce query complexity or result set size |
+| `TIMEOUT` | "Timeout", "timed out" | Query took too long | Add filters, reduce time range, or optimize query |
**ClickHouse retries:**
@@ -676,13 +679,13 @@ ClickHouse queries automatically retry network errors (socket hang up) with expo
```typescript
// In packages/shared/src/env.ts
-LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS: z.coerce.number().positive().default(3)
+LANGFUSE_CLICKHOUSE_QUERY_MAX_ATTEMPTS: z.coerce.number().positive().default(3);
```
---
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main backend development guidelines
+- [../SKILL.md](../SKILL.md) - Main backend development guidelines
- [architecture-overview.md](architecture-overview.md) - System architecture
- [configuration.md](configuration.md) - Environment variable configuration
diff --git a/.agents/skills/backend-dev-guidelines/references/middleware-guide.md b/.agents/skills/backend-dev-guidelines/references/middleware-guide.md
index d4664ce7e8..830da19d95 100644
--- a/.agents/skills/backend-dev-guidelines/references/middleware-guide.md
+++ b/.agents/skills/backend-dev-guidelines/references/middleware-guide.md
@@ -116,7 +116,9 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(async (opts) => {
const projectId = parsedInput.data.projectId;
const sessionProject = ctx.session.user.organizations
- .flatMap((org) => org.projects.map((project) => ({ ...project, organization: org })))
+ .flatMap((org) =>
+ org.projects.map((project) => ({ ...project, organization: org })),
+ )
.find((project) => project.id === projectId);
if (!sessionProject) {
@@ -164,7 +166,9 @@ const enforceIsAuthedAndOrgMember = t.middleware(async (opts) => {
}
const orgId = result.data.orgId;
- const sessionOrg = ctx.session.user.organizations.find((org) => org.id === orgId);
+ const sessionOrg = ctx.session.user.organizations.find(
+ (org) => org.id === orgId,
+ );
if (!sessionOrg && ctx.session.user.admin !== true) {
throw new TRPCError({
@@ -179,7 +183,8 @@ const enforceIsAuthedAndOrgMember = t.middleware(async (opts) => {
...ctx.session,
user: ctx.session.user,
orgId: orgId,
- orgRole: ctx.session.user.admin === true ? Role.OWNER : sessionOrg!.role,
+ orgRole:
+ ctx.session.user.admin === true ? Role.OWNER : sessionOrg!.role,
},
},
});
@@ -221,7 +226,8 @@ const enforceTraceAccess = t.middleware(async (opts) => {
if (!trace.public && !sessionProject && ctx.session?.user?.admin !== true) {
throw new TRPCError({
code: "UNAUTHORIZED",
- message: "User is not a member of this project and this trace is not public",
+ message:
+ "User is not a member of this project and this trace is not public",
});
}
@@ -348,6 +354,7 @@ export default withMiddlewares({
### createAuthedProjectAPIRoute Pattern
Factory function for authenticated public API routes with:
+
- Authentication (Basic auth or Admin API key)
- Rate limiting
- Input/output validation (Zod)
@@ -355,17 +362,21 @@ Factory function for authenticated public API routes with:
```typescript
export const createAuthedProjectAPIRoute = <TQuery, TBody, TResponse>(
- routeConfig: RouteConfig<TQuery, TBody, TResponse>
+ routeConfig: RouteConfig<TQuery, TBody, TResponse>,
) => {
return async (req: NextApiRequest, res: NextApiResponse) => {
// 1. Authentication (verifyAuth)
- const auth = await verifyAuth(req, routeConfig.isAdminApiKeyAuthAllowed || false);
+ const auth = await verifyAuth(
+ req,
+ routeConfig.isAdminApiKeyAuthAllowed || false,
+ );
// 2. Rate limiting
- const rateLimitResponse = await RateLimitService.getInstance().rateLimitRequest(
- auth.scope,
- routeConfig.rateLimitResource || "public-api"
- );
+ const rateLimitResponse =
+ await RateLimitService.getInstance().rateLimitRequest(
+ auth.scope,
+ routeConfig.rateLimitResource || "public-api",
+ );
if (rateLimitResponse?.isRateLimited()) {
return rateLimitResponse.sendRestResponseIfLimited(res);
@@ -474,15 +485,20 @@ Public APIs use **Basic Auth** with API keys:
```typescript
async function verifyBasicAuth(authHeader: string | undefined) {
- const regularAuth = await new ApiAuthService(prisma, redis)
- .verifyAuthHeaderAndReturnScope(authHeader);
+ const regularAuth = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(authHeader);
if (!regularAuth.validKey) {
throw { status: 401, message: regularAuth.error };
}
if (regularAuth.scope.accessLevel !== "project") {
- throw { status: 401, message: "Access denied - need basic auth with secret key" };
+ throw {
+ status: 401,
+ message: "Access denied - need basic auth with secret key",
+ };
}
return regularAuth;
@@ -499,7 +515,10 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest) {
// 3. x-langfuse-project-id: <project-id>
if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- throw { status: 403, message: "Admin API key auth not available on Langfuse Cloud" };
+ throw {
+ status: 403,
+ message: "Admin API key auth not available on Langfuse Cloud",
+ };
}
const adminApiKey = env.ADMIN_API_KEY;
@@ -508,8 +527,14 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest) {
// Timing-safe comparison
const isValid =
- crypto.timingSafeEqual(Buffer.from(bearerToken), Buffer.from(adminApiKey)) &&
- crypto.timingSafeEqual(Buffer.from(adminApiKeyHeader), Buffer.from(adminApiKey));
+ crypto.timingSafeEqual(
+ Buffer.from(bearerToken),
+ Buffer.from(adminApiKey),
+ ) &&
+ crypto.timingSafeEqual(
+ Buffer.from(adminApiKeyHeader),
+ Buffer.from(adminApiKey),
+ );
if (!isValid) throw { status: 401, message: "Invalid admin API key" };
@@ -635,6 +660,7 @@ return opentelemetry.context.with(ctx, async () => {
```
**Baggage includes:**
+
- `userId` - User ID from session
- `projectId` - Project ID from input
- `headers` - Request headers for trace propagation
@@ -676,7 +702,9 @@ const baseProcedure = withOtelTracingProcedure.use(withErrorHandling);
const authedProcedure = baseProcedure.use(enforceUserIsAuthed);
// Add project scoping
-const projectProcedure = authedProcedure.use(enforceUserIsAuthedAndProjectMember);
+const projectProcedure = authedProcedure.use(
+ enforceUserIsAuthedAndProjectMember,
+);
```
### Using Procedures in Routers
@@ -692,7 +720,7 @@ export const tracesRouter = createTRPCRouter({
projectId: z.string(),
page: z.number().optional(),
limit: z.number().optional(),
- })
+ }),
)
.query(async ({ input, ctx }) => {
// ctx.session.projectId is guaranteed to exist
@@ -713,7 +741,7 @@ export const tracesRouter = createTRPCRouter({
traceId: z.string(),
projectId: z.string(),
timestamp: z.date().nullish(),
- })
+ }),
)
.query(async ({ input, ctx }) => {
// ctx.trace is guaranteed to exist (fetched by middleware)
@@ -729,11 +757,12 @@ Middleware executes in the order it's chained:
```typescript
protectedProjectProcedure
- .use(withErrorHandling) // 1. Wraps entire execution
- .use(enforceUserIsAuthed) // 2. Validates session exists
- .use(enforceUserIsAuthedAndProjectMember) // 3. Validates project membership
- .input(schema) // 4. Validates input
- .query(async ({ input, ctx }) => { // 5. Executes query
+ .use(withErrorHandling) // 1. Wraps entire execution
+ .use(enforceUserIsAuthed) // 2. Validates session exists
+ .use(enforceUserIsAuthedAndProjectMember) // 3. Validates project membership
+ .input(schema) // 4. Validates input
+ .query(async ({ input, ctx }) => {
+ // 5. Executes query
// ...
});
```
@@ -744,22 +773,21 @@ Each middleware can enrich the context:
```typescript
// After enforceUserIsAuthed:
-ctx.session.user // NonNullable<User>
+ctx.session.user; // NonNullable<User>
// After enforceUserIsAuthedAndProjectMember:
-ctx.session.projectId // string
-ctx.session.projectRole // Role (OWNER | ADMIN | MEMBER | VIEWER)
-ctx.session.orgId // string
-ctx.session.orgRole // Role
+ctx.session.projectId; // string
+ctx.session.projectRole; // Role (OWNER | ADMIN | MEMBER | VIEWER)
+ctx.session.orgId; // string
+ctx.session.orgRole; // Role
// After enforceTraceAccess:
-ctx.trace // TraceRecord (pre-fetched)
+ctx.trace; // TraceRecord (pre-fetched)
```
---
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main backend development guidelines
+- [../SKILL.md](../SKILL.md) - Main backend development guidelines
- [architecture-overview.md](architecture-overview.md) - System architecture
-- [../AGENTS.md](../AGENTS.md) - Error handling patterns and traceException guidance
diff --git a/.agents/skills/backend-dev-guidelines/references/routing-and-controllers.md b/.agents/skills/backend-dev-guidelines/references/routing-and-controllers.md
index 745ebe21c9..139fe511b8 100644
--- a/.agents/skills/backend-dev-guidelines/references/routing-and-controllers.md
+++ b/.agents/skills/backend-dev-guidelines/references/routing-and-controllers.md
@@ -7,6 +7,7 @@ Complete guide to routing and separation of concerns in Langfuse's Next.js + tRP
- [Architecture Overview](#architecture-overview)
- [tRPC Routers](#trpc-routers)
- [Public REST API Routes](#public-rest-api-routes)
+- [Fern API Definitions](#fern-api-definitions)
- [Service Layer](#service-layer)
- [Repository Layer](#repository-layer)
- [Separation of Concerns](#separation-of-concerns)
@@ -48,6 +49,7 @@ Langfuse uses a **layered architecture** with clear separation of concerns:
### Key Principles
**Entry Points (Routes/Procedures):**
+
- βœ… Define routing and procedure signatures
- βœ… Handle authentication/authorization (via middleware)
- βœ… Validate input (Zod schemas)
@@ -55,12 +57,14 @@ Langfuse uses a **layered architecture** with clear separation of concerns:
- βœ… Return responses
**Entry Points should NEVER:**
+
- ❌ Contain business logic
- ❌ Access database directly
- ❌ Perform complex data transformations
- ❌ Make direct repository calls (use services)
**Services:**
+
- βœ… Contain business logic
- βœ… Orchestrate multiple operations
- βœ… Call repositories or Prisma/ClickHouse
@@ -68,6 +72,7 @@ Langfuse uses a **layered architecture** with clear separation of concerns:
- ❌ Should NOT know about HTTP, tRPC, or request/response objects
**Repositories:**
+
- βœ… Complex database queries
- βœ… Data transformation (DB β†’ domain models)
- βœ… ClickHouse query builders
@@ -88,7 +93,10 @@ tRPC routers define type-safe procedures for the internal UI. Each router groups
```typescript
import { z } from "zod/v4";
-import { createTRPCRouter, protectedProjectProcedure } from "@/src/server/api/trpc";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
import { paginationZod, singleFilter, orderBy } from "@langfuse/shared";
import {
getScoresUiTable,
@@ -187,6 +195,7 @@ export const scoresRouter = createTRPCRouter({
```
**Key Points:**
+
- Use appropriate procedure type (`protectedProjectProcedure`, `authenticatedProcedure`, etc.)
- Define input schema with Zod (`.input()`)
- Use `.query()` for reads, `.mutation()` for writes
@@ -255,6 +264,7 @@ web/src/pages/api/public/
```
**Dynamic routes:**
+
- `[param].ts` β†’ Single dynamic segment (e.g., `/api/public/scores/[scoreId].ts`)
- `[...param].ts` β†’ Catch-all route (e.g., `/api/public/[...path].ts`)
@@ -345,12 +355,39 @@ export default withMiddlewares({
```
**Key Points:**
+
- Use `withMiddlewares` for all public API routes (provides CORS, error handling, OpenTelemetry)
- Use `createAuthedProjectAPIRoute` for authenticated endpoints (handles auth, rate limiting, validation)
- Define separate handlers for each HTTP method
- Input/output validated with Zod schemas
- Delegate to services for business logic
+### Fern API Definitions
+
+When modifying public API types in `web/src/features/public-api/types/`, update
+the matching Fern API definitions in `fern/apis/server/definition/`.
+
+**Zod to Fern Type Mapping:**
+
+| Zod Type | Fern Type | Example |
+| -------------- | ----------------------- | --------------------------------------------------------- |
+| `.nullish()` | `optional<nullable<T>>` | `z.string().nullish()` -> `optional<nullable<string>>` |
+| `.nullable()` | `nullable<T>` | `z.string().nullable()` -> `nullable<string>` |
+| `.optional()` | `optional<T>` | `z.string().optional()` -> `optional<string>` |
+| Always present | `T` | `z.string()` -> `string` |
+
+Add a source comment at the top of each Fern type that references the
+TypeScript source:
+
+```yaml
+# Source: web/src/features/public-api/types/traces.ts - APITrace
+Trace:
+ properties:
+ id: string
+ name:
+ type: nullable<string>
+```
+
### Simple Public Routes
For routes that don't need authentication:
@@ -433,6 +470,7 @@ export class ScoresApiService {
```
**Key Points:**
+
- Services contain business logic, not routing logic
- Services should NOT import tRPC or Next.js types
- Services can call repositories, Prisma, ClickHouse directly
@@ -442,6 +480,7 @@ export class ScoresApiService {
### Where to Put Services
**Feature-specific services:**
+
```
web/src/features/
β”œβ”€β”€ datasets/
@@ -456,6 +495,7 @@ web/src/features/
```
**Shared services:**
+
```
packages/shared/src/server/services/
β”œβ”€β”€ SlackService.ts
@@ -497,7 +537,7 @@ import { convertClickhouseToDomain } from "./traces_converters";
*/
export const getTracesByIds = async (
projectId: string,
- traceIds: string[]
+ traceIds: string[],
): Promise<TraceRecordReadType[]> => {
const rows = await queryClickhouse<TraceRecordReadType>({
query: `
@@ -519,7 +559,7 @@ export const getTracesByIds = async (
* Upsert trace to ClickHouse
*/
export const upsertTrace = async (
- trace: TraceRecordInsertType
+ trace: TraceRecordInsertType,
): Promise<void> => {
await upsertClickhouse({
table: "traces",
@@ -536,6 +576,7 @@ export const upsertTrace = async (
```
**Key Points:**
+
- Use `queryClickhouse` for SELECT queries
- Use `upsertClickhouse` for INSERT/UPDATE
- Use `commandClickhouse` for DDL (ALTER TABLE, etc.)
@@ -546,12 +587,14 @@ export const upsertTrace = async (
### When to Use Repositories
βœ… **Use repositories for:**
+
- Complex ClickHouse queries with CTEs, joins, aggregations
- Queries used in multiple places (DRY principle)
- Data transformation from DB types to domain models
- Streaming large result sets
❌ **Use direct Prisma/ClickHouse for:**
+
- Simple CRUD operations
- One-off queries
- Prototyping (can refactor to repository later)
@@ -645,9 +688,7 @@ export async function createScoreWithValidation({
```typescript
// packages/shared/src/server/repositories/scores.ts
-export const upsertScore = async (
- score: ScoreInsertType
-): Promise<void> => {
+export const upsertScore = async (score: ScoreInsertType): Promise<void> => {
// βœ… Pure data access - no business logic
await upsertClickhouse({
table: "scores",
@@ -719,6 +760,7 @@ export const scoresRouter = createTRPCRouter({
```
**Why it's bad:**
+
- Business logic tied to tRPC (can't reuse in public API)
- Hard to test (need to mock tRPC context)
- No separation of concerns
@@ -817,9 +859,7 @@ export const upsertScore = async (
```typescript
// βœ… GOOD: Pure data access, no business logic
-export const upsertScore = async (
- score: ScoreInsertType
-): Promise<void> => {
+export const upsertScore = async (score: ScoreInsertType): Promise<void> => {
await upsertClickhouse({
table: "scores",
records: [score],
@@ -838,7 +878,7 @@ export const upsertScore = async (
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main backend development guidelines
+- [../SKILL.md](../SKILL.md) - Main backend development guidelines
- [architecture-overview.md](architecture-overview.md) - System architecture
- [middleware-guide.md](middleware-guide.md) - Middleware patterns
- [database-patterns.md](database-patterns.md) - Database access patterns
diff --git a/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md b/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
index 2eb73ed9f9..0dda4610be 100644
--- a/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
+++ b/.agents/skills/backend-dev-guidelines/references/services-and-repositories.md
@@ -644,7 +644,7 @@ over invented examples:
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main guide
+- [../SKILL.md](../SKILL.md) - Main guide
- [routing-and-controllers.md](routing-and-controllers.md) - Controllers that use services
- [database-patterns.md](database-patterns.md) - Prisma and repository patterns
- [testing-guide.md](testing-guide.md) - Testing service and repository code
diff --git a/.agents/skills/backend-dev-guidelines/references/testing-guide.md b/.agents/skills/backend-dev-guidelines/references/testing-guide.md
index 3802ddde54..238568324c 100644
--- a/.agents/skills/backend-dev-guidelines/references/testing-guide.md
+++ b/.agents/skills/backend-dev-guidelines/references/testing-guide.md
@@ -26,12 +26,12 @@ Complete guide to testing Langfuse backend services across web, worker, and shar
### By Test Type
-| Test Type | Key Principles |
-|-----------|----------------|
-| **Integration** | Test HTTP endpoints, validate status codes and response shapes |
-| **tRPC** | Use `createInnerTRPCContext` and `appRouter.createCaller`, test auth/permissions |
-| **Service** | Test individual functions with isolated data, always cleanup |
-| **Worker** | Use vitest, test streams with async iteration, test filtering logic |
+| Test Type | Key Principles |
+| --------------- | -------------------------------------------------------------------------------- |
+| **Integration** | Test HTTP endpoints, validate status codes and response shapes |
+| **tRPC** | Use `createInnerTRPCContext` and `appRouter.createCaller`, test auth/permissions |
+| **Service** | Test individual functions with isolated data, always cleanup |
+| **Worker** | Use vitest, test streams with async iteration, test filtering logic |
### Test Data Management
@@ -58,12 +58,12 @@ const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
Langfuse uses multiple testing strategies for different layers:
-| Test Type | Framework | Location | Purpose |
-|-----------|-----------|----------|---------|
-| Integration | Vitest | `web/src/__tests__/server/` | Full API endpoint testing |
-| tRPC | Vitest | `web/src/__tests__/server/` | tRPC procedure testing with auth |
-| Service | Vitest | `web/src/__tests__/server/repositories/` | Repository/service function testing |
-| Worker | Vitest | `worker/src/__tests__/` | Queue processors and streams |
+| Test Type | Framework | Location | Purpose |
+| ----------- | --------- | ---------------------------------------- | ----------------------------------- |
+| Integration | Vitest | `web/src/__tests__/server/` | Full API endpoint testing |
+| tRPC | Vitest | `web/src/__tests__/server/` | tRPC procedure testing with auth |
+| Service | Vitest | `web/src/__tests__/server/repositories/` | Repository/service function testing |
+| Worker | Vitest | `worker/src/__tests__/` | Queue processors and streams |
---
@@ -103,6 +103,7 @@ describe("Dataset API", () => {
```
**Key Points:**
+
- Uses `makeZodVerifiedAPICall` for type-safe API testing
- Tests HTTP status codes and response validation
- Tests both success and error cases
@@ -163,7 +164,9 @@ describe("Event Repository Tests", () => {
// Test the service function
const result = await getObservationsWithModelDataFromEventsTable({
projectId,
- filter: [{ type: "string", column: "id", operator: "=", value: generationId }],
+ filter: [
+ { type: "string", column: "id", operator: "=", value: generationId },
+ ],
limit: 1000,
offset: 0,
});
@@ -203,18 +206,24 @@ describe("Event Repository Tests", () => {
const result = await getObservationsWithModelDataFromEventsTable({
projectId,
filter: [
- { type: "stringOptions", column: "type", operator: "any of", value: ["GENERATION"] }
+ {
+ type: "stringOptions",
+ column: "type",
+ operator: "any of",
+ value: ["GENERATION"],
+ },
],
limit: 1000,
offset: 0,
});
- expect(result.every(o => o.type === "GENERATION")).toBe(true);
+ expect(result.every((o) => o.type === "GENERATION")).toBe(true);
});
});
```
**Key Points:**
+
- Tests service/repository functions directly
- Uses ClickHouse and Prisma test data
- Always cleanup test data after tests
@@ -245,16 +254,20 @@ async function prepare() {
user: {
id: "user-1",
name: "Demo User",
- organizations: [{
- id: org.id,
- name: org.name,
- role: "OWNER",
- projects: [{
- id: project.id,
- role: "ADMIN",
- name: project.name,
- }],
- }],
+ organizations: [
+ {
+ id: org.id,
+ name: org.name,
+ role: "OWNER",
+ projects: [
+ {
+ id: project.id,
+ role: "ADMIN",
+ name: project.name,
+ },
+ ],
+ },
+ ],
},
};
@@ -327,13 +340,17 @@ describe("automations trpc", () => {
...session,
user: {
...session.user!,
- organizations: [{
- ...session.user!.organizations[0],
- projects: [{
- ...session.user!.organizations[0].projects[0],
- role: "VIEWER", // VIEWER can't create automations
- }],
- }],
+ organizations: [
+ {
+ ...session.user!.organizations[0],
+ projects: [
+ {
+ ...session.user!.organizations[0].projects[0],
+ role: "VIEWER", // VIEWER can't create automations
+ },
+ ],
+ },
+ ],
},
};
@@ -365,6 +382,7 @@ describe("automations trpc", () => {
```
**Key Points:**
+
- Uses `prepare()` helper to set up test context
- Creates authenticated caller with `appRouter.createCaller`
- Tests both success and permission error cases
@@ -497,6 +515,7 @@ describe("batch export test suite", () => {
```
**Key Points:**
+
- Uses vitest (not Jest) for worker tests
- Tests stream functions with async iteration
- Creates isolated test data per test
@@ -510,6 +529,7 @@ Use the nearest package `AGENTS.md` as the source of truth for current test
commands.
Common targeted forms:
+
- Web server tests: `pnpm --filter web run test <file-or-pattern>`
- Web client tests: `pnpm --filter web run test-client <file-or-pattern>`
- Worker tests: `pnpm --filter worker run test <file-or-pattern>`
@@ -517,6 +537,7 @@ Common targeted forms:
---
**Related Files:**
-- [../AGENTS.md](../AGENTS.md) - Main backend guidelines
+
+- [../SKILL.md](../SKILL.md) - Main backend guidelines
- [architecture-overview.md](architecture-overview.md) - Architecture patterns
- [services-and-repositories.md](services-and-repositories.md) - Service and repository examples
diff --git a/.agents/skills/clickhouse-best-practices/AGENTS.md b/.agents/skills/clickhouse-best-practices/AGENTS.md
deleted file mode 100644
index a973c02e03..0000000000
--- a/.agents/skills/clickhouse-best-practices/AGENTS.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# ClickHouse Best Practices
-
-Start with `SKILL.md` for the ClickHouse review workflow, rule-selection
-process, and response format. This file exists as a concise compatibility
-entrypoint for agents that open `AGENTS.md` directly.
-
-Detailed rules live in `rules/`. Read only the rule files that match the schema,
-query, or ingestion issue under review, and cite the specific rule names in
-responses.
-
-## Langfuse-Specific Rules
-
-- Use `packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts`
- for queries against the `events` table. Do not hand-roll `events` SQL unless
- you first confirm the query builder cannot express the query.
-- Never use `FINAL` on the `events` table; it is designed so `FINAL` is not
- required and the keyword hurts performance.
-- Any migration in `packages/shared/clickhouse/migrations/clustered/**` with
- more than one `ALTER` on the same table must end every metadata `ALTER`
- (`ADD/DROP/MODIFY COLUMN`, `ADD/DROP INDEX`) with `SETTINGS alter_sync = 2`,
- and every mutation-creating `ALTER` (`MATERIALIZE …`, `UPDATE`, `DELETE`)
- with `SETTINGS mutations_sync = 2`. The `unclustered/` mirror runs against
- plain `MergeTree` and does not need (and should not duplicate) these
- settings.
-
-## Rule Index
-
-### Schema Design
-
-- `rules/schema-pk-plan-before-creation.md`
-- `rules/schema-pk-cardinality-order.md`
-- `rules/schema-pk-prioritize-filters.md`
-- `rules/schema-pk-filter-on-orderby.md`
-- `rules/schema-types-native-types.md`
-- `rules/schema-types-minimize-bitwidth.md`
-- `rules/schema-types-lowcardinality.md`
-- `rules/schema-types-enum.md`
-- `rules/schema-types-avoid-nullable.md`
-- `rules/schema-partition-start-without.md`
-- `rules/schema-partition-low-cardinality.md`
-- `rules/schema-partition-query-tradeoffs.md`
-- `rules/schema-partition-lifecycle.md`
-- `rules/schema-json-when-to-use.md`
-
-### Query Optimization
-
-- `rules/query-join-choose-algorithm.md`
-- `rules/query-join-consider-alternatives.md`
-- `rules/query-join-filter-before.md`
-- `rules/query-join-null-handling.md`
-- `rules/query-join-use-any.md`
-- `rules/query-index-skipping-indices.md`
-- `rules/query-mv-incremental.md`
-- `rules/query-mv-refreshable.md`
-
-### Insert Strategy
-
-- `rules/insert-batch-size.md`
-- `rules/insert-async-small-batches.md`
-- `rules/insert-format-native.md`
-- `rules/insert-mutation-avoid-delete.md`
-- `rules/insert-mutation-avoid-update.md`
-- `rules/insert-optimize-avoid-final.md`
diff --git a/.agents/skills/clickhouse-best-practices/README.md b/.agents/skills/clickhouse-best-practices/README.md
index 47d0840444..81b3837310 100644
--- a/.agents/skills/clickhouse-best-practices/README.md
+++ b/.agents/skills/clickhouse-best-practices/README.md
@@ -12,23 +12,24 @@ npx skills add ClickHouse/clickhouse-agent-skills
**28 atomic rules** organized by prefix:
-| Prefix | Count | Coverage |
-|--------|-------|----------|
-| `schema-pk-*` | 4 | PRIMARY KEY selection, cardinality ordering |
-| `schema-types-*` | 5 | Data types, LowCardinality, Nullable |
-| `schema-partition-*` | 4 | Partitioning strategy, lifecycle management |
-| `schema-json-*` | 1 | JSON type usage |
-| `query-join-*` | 5 | JOIN algorithms, filtering, alternatives |
-| `query-index-*` | 1 | Data skipping indices |
-| `query-mv-*` | 2 | Incremental and refreshable MVs |
-| `insert-batch-*` | 1 | Batch sizing (10K-100K rows) |
-| `insert-async-*` | 2 | Async inserts, data formats |
-| `insert-mutation-*` | 2 | Mutation avoidance |
-| `insert-optimize-*` | 1 | OPTIMIZE FINAL avoidance |
+| Prefix | Count | Coverage |
+| -------------------- | ----- | ------------------------------------------- |
+| `schema-pk-*` | 4 | PRIMARY KEY selection, cardinality ordering |
+| `schema-types-*` | 5 | Data types, LowCardinality, Nullable |
+| `schema-partition-*` | 4 | Partitioning strategy, lifecycle management |
+| `schema-json-*` | 1 | JSON type usage |
+| `query-join-*` | 5 | JOIN algorithms, filtering, alternatives |
+| `query-index-*` | 1 | Data skipping indices |
+| `query-mv-*` | 2 | Incremental and refreshable MVs |
+| `insert-batch-*` | 1 | Batch sizing (10K-100K rows) |
+| `insert-async-*` | 2 | Async inserts, data formats |
+| `insert-mutation-*` | 2 | Mutation avoidance |
+| `insert-optimize-*` | 1 | OPTIMIZE FINAL avoidance |
## Trigger Phrases
This skill activates when you:
+
- "Create a table for..."
- "Optimize this query..."
- "Design a schema for..."
@@ -38,13 +39,13 @@ This skill activates when you:
## Files
-| File | Purpose |
-|------|---------|
-| `SKILL.md` | Quick reference and decision frameworks |
-| `AGENTS.md` | Complete rule reference (auto-generated) |
-| `rules/*.md` | Individual rule definitions |
+| File | Purpose |
+| ------------ | -------------------------------------------------------- |
+| `SKILL.md` | Review workflow, quick reference, and rule-selection entrypoint |
+| `rules/*.md` | Individual rule definitions |
## Related Documentation
All rules link to official ClickHouse documentation:
+
- [ClickHouse Best Practices](https://clickhouse.com/docs/best-practices)
diff --git a/.agents/skills/clickhouse-best-practices/SKILL.md b/.agents/skills/clickhouse-best-practices/SKILL.md
index 7c86b4607c..f700889df4 100644
--- a/.agents/skills/clickhouse-best-practices/SKILL.md
+++ b/.agents/skills/clickhouse-best-practices/SKILL.md
@@ -59,6 +59,7 @@ Comprehensive guidance for ClickHouse covering schema design, query optimization
9. `rules/schema-partition-lifecycle.md` - Partitioning purpose
**Check for:**
+
- [ ] PRIMARY KEY / ORDER BY column order (low-to-high cardinality)
- [ ] Data types match actual data ranges
- [ ] LowCardinality applied to appropriate string columns
@@ -77,6 +78,7 @@ Comprehensive guidance for ClickHouse covering schema design, query optimization
5. `rules/schema-pk-filter-on-orderby.md` - Filter alignment with ORDER BY
**Check for:**
+
- [ ] Filters use ORDER BY prefix columns
- [ ] JOINs filter tables before joining (not after)
- [ ] Correct JOIN algorithm for table sizes
@@ -93,6 +95,7 @@ Comprehensive guidance for ClickHouse covering schema design, query optimization
5. `rules/insert-optimize-avoid-final.md` - OPTIMIZE TABLE risks
**Check for:**
+
- [ ] Batch size 10K-100K rows per INSERT
- [ ] No ALTER TABLE UPDATE for frequent changes
- [ ] ReplacingMergeTree or CollapsingMergeTree for update patterns
@@ -129,19 +132,19 @@ Structure your response as follows:
## Rule Categories by Priority
-| Priority | Category | Impact | Prefix | Rule Count |
-|----------|----------|--------|--------|------------|
-| 1 | Primary Key Selection | CRITICAL | `schema-pk-` | 4 |
-| 2 | Data Type Selection | CRITICAL | `schema-types-` | 5 |
-| 3 | JOIN Optimization | CRITICAL | `query-join-` | 5 |
-| 4 | Insert Batching | CRITICAL | `insert-batch-` | 1 |
-| 5 | Mutation Avoidance | CRITICAL | `insert-mutation-` | 2 |
-| 6 | Partitioning Strategy | HIGH | `schema-partition-` | 4 |
-| 7 | Skipping Indices | HIGH | `query-index-` | 1 |
-| 8 | Materialized Views | HIGH | `query-mv-` | 2 |
-| 9 | Async Inserts | HIGH | `insert-async-` | 2 |
-| 10 | OPTIMIZE Avoidance | HIGH | `insert-optimize-` | 1 |
-| 11 | JSON Usage | MEDIUM | `schema-json-` | 1 |
+| Priority | Category | Impact | Prefix | Rule Count |
+| -------- | --------------------- | -------- | ------------------- | ---------- |
+| 1 | Primary Key Selection | CRITICAL | `schema-pk-` | 4 |
+| 2 | Data Type Selection | CRITICAL | `schema-types-` | 5 |
+| 3 | JOIN Optimization | CRITICAL | `query-join-` | 5 |
+| 4 | Insert Batching | CRITICAL | `insert-batch-` | 1 |
+| 5 | Mutation Avoidance | CRITICAL | `insert-mutation-` | 2 |
+| 6 | Partitioning Strategy | HIGH | `schema-partition-` | 4 |
+| 7 | Skipping Indices | HIGH | `query-index-` | 1 |
+| 8 | Materialized Views | HIGH | `query-mv-` | 2 |
+| 9 | Async Inserts | HIGH | `insert-async-` | 2 |
+| 10 | OPTIMIZE Avoidance | HIGH | `insert-optimize-` | 1 |
+| 11 | JSON Usage | MEDIUM | `schema-json-` | 1 |
---
@@ -236,11 +239,3 @@ Each rule file in `rules/` contains:
- **Incorrect example**: Anti-pattern with explanation
- **Correct example**: Best practice with explanation
- **Additional context**: Trade-offs, when to apply, references
-
----
-
-## Compatibility Entrypoint
-
-`AGENTS.md` is a short compatibility index for agents that open that file
-directly. The authoritative workflow lives in this `SKILL.md`, and detailed rule
-bodies live in `rules/`.
diff --git a/.agents/skills/git-workflow/SKILL.md b/.agents/skills/git-workflow/SKILL.md
new file mode 100644
index 0000000000..730a803724
--- /dev/null
+++ b/.agents/skills/git-workflow/SKILL.md
@@ -0,0 +1,51 @@
+---
+name: git-workflow
+description: |
+ Langfuse repo Git, GitHub, commit, branch, pull request, issue search,
+ release, and production-promotion workflow. Use when staging, committing,
+ pushing, opening PRs, searching GitHub issues, or changing release/promotion
+ behavior.
+---
+
+# Git Workflow
+
+Use this skill for repo-specific Git, GitHub, pull request, and release
+operations.
+
+## Safety
+
+- Inspect `git status` before staging or committing.
+- Do not stage unrelated working-tree changes.
+- Do not revert unrelated working-tree changes.
+- Do not use destructive commands such as `git reset --hard` or
+ `git checkout --` unless explicitly requested.
+- Keep commits focused and atomic.
+- Never add secrets or credentials to the repo.
+
+## Commits and Pull Requests
+
+- Commit messages and PR titles must follow Conventional Commits:
+ `type(scope): description` or `type: description`.
+- Use `feat` for new features and `fix` for bug fixes.
+- Use a scope when it clarifies the affected area, for example
+ `fix(api): handle missing trace id`.
+- Mark breaking changes with `!` in the type/scope or a `BREAKING CHANGE:`
+ footer.
+- PR titles are validated by `.github/workflows/validate-pr-title.yml`.
+- In PR descriptions, list impacted packages and executed verification
+ commands.
+
+## GitHub
+
+- Use `gh search issues` for GitHub issue search.
+- Prefer non-interactive Git and GitHub commands where possible.
+- Keep PRs narrow enough to review without unrelated refactors.
+
+## Release
+
+- Release workflow is managed at root with `pnpm run release`.
+- Promote `main` to `production` via
+ `.github/workflows/promote-main-to-production.yml` or
+ `pnpm run release:cloud`.
+- Do not change release/versioning flow without updating this skill and the
+ impacted package guides.
diff --git a/.agents/skills/pnpm-upgrade-package/AGENTS.md b/.agents/skills/pnpm-upgrade-package/AGENTS.md
deleted file mode 100644
index d45f58ead5..0000000000
--- a/.agents/skills/pnpm-upgrade-package/AGENTS.md
+++ /dev/null
@@ -1,82 +0,0 @@
-# PNPM Upgrade Package
-
-Use this workflow when a user wants to upgrade a dependency in the Langfuse
-pnpm workspace.
-
-## Workflow
-
-1. Collect missing inputs.
- - Ask for the package if missing.
- - Ask for the target version if missing.
- - If the user says `latest`, resolve the real registry latest first.
-
-2. Run the main helper once.
- - Run
- `node .agents/skills/pnpm-upgrade-package/scripts/check-release-age-window.mjs <package> <targetVersion>`.
- - Treat this as the single source of truth for:
- - direct workspace references
- - root `pnpm-workspace.yaml` `overrides` / `patchedDependencies`
- - latest registry version
- - latest version installable under the current release-age rules
- - existing matching `minimumReleaseAgeExclude` entries
- - exact dependency companions from `dependencies` and `optionalDependencies`
- - exact peer dependencies that are actually installed in the workspace
-
-3. Handle the transitive-only case before editing anything.
- - If the helper shows no direct workspace references, run `pnpm why -r <package>`.
- - Identify the current top-level parent that pulls the package in.
- - Check whether that parent's current dependency range already permits the
- requested transitive version.
- - If the current parent range already covers the requested version, prefer a
- lock refresh / reinstall path before changing `package.json`.
- - If the current parent range does not cover the requested version, upgrade
- the direct parent dependency that pulls the package in.
- - Do not add the transitive package directly unless the user explicitly asks.
-
-4. Ask before changing `minimumReleaseAgeExclude`.
- - Prefer `package@version` entries.
- - Only use bare `package` entries after explicit approval.
- - Ask about exact companion packages only when the helper says they still
- need a new exclusion.
- - Treat range-based dependency or peer entries as manual review.
-
-5. Bump at the narrowest useful scope.
- - `pnpm -w up <package>@<version>` for root-only changes.
- - `pnpm --filter <workspace> up <package>@<version>` for one workspace.
- - `pnpm -r up <package>@<version>` only when every current reference should move.
- - For an already-allowed transitive bump that pnpm refuses to move, use the
- narrowest temporary `overrides` entry only to force resolution.
- - After a temporary override moves the lockfile, remove that override and run
- `pnpm install`, then `pnpm dedupe` when permitted. If the lockfile remains
- at the target without the override, keep the lockfile-only result and do
- not keep the override.
- - Do not hand-edit `pnpm-lock.yaml`.
-
-6. Validate.
- - Use the nearest package `AGENTS.md` plus the root verification matrix.
- - Finish with `pnpm why -r <package>`.
- - If companions moved too, run `pnpm why -r <companion-package>` for them as well.
- - Run `pnpm dedupe` when validating temporary override removal or when the
- user permits it; otherwise suggest it as optional cleanup. Review the diff
- afterward because dedupe may move unrelated lockfile state.
-
-## Quick Commands
-
-- Run the single analysis pass:
- `node .agents/skills/pnpm-upgrade-package/scripts/check-release-age-window.mjs <package> <targetVersion>`
-- Transitive provenance check:
- `pnpm why -r <package>`
-- Inspect the current parent manifest on the registry:
- `npm view <parent>@<installedVersion> dependencies peerDependencies optionalDependencies --json`
-- Final graph verification:
- `pnpm why -r <package>`
-- Optional lockfile cleanup for the user to run after the fix:
- `pnpm dedupe`
-- Bump in the root workspace:
- `pnpm -w up <package>@<version>`
-- Bump in one workspace:
- `pnpm --filter web up <package>@<version>`
-- Bump everywhere that should move together:
- `pnpm -r up <package>@<version>`
-- Verify temporary override removal:
- remove the override, then run `pnpm install` and `pnpm dedupe`
diff --git a/.agents/skills/pnpm-upgrade-package/SKILL.md b/.agents/skills/pnpm-upgrade-package/SKILL.md
index ab1dc35fa3..6b1ac65c7c 100644
--- a/.agents/skills/pnpm-upgrade-package/SKILL.md
+++ b/.agents/skills/pnpm-upgrade-package/SKILL.md
@@ -12,7 +12,7 @@ Use this skill for interactive dependency bumps in Langfuse.
## Read Order
-- Start with [AGENTS.md](AGENTS.md) for the end-to-end workflow.
+- Use this `SKILL.md` for the end-to-end workflow.
- Run the main helper once at the start of the upgrade:
`node .agents/skills/pnpm-upgrade-package/scripts/check-release-age-window.mjs <package> [targetVersion]`
@@ -53,3 +53,22 @@ Use this skill for interactive dependency bumps in Langfuse.
locally installed exact peer dependencies.
- Finish with `pnpm why -r <package>` to confirm that only the intended version
remains in the workspace.
+
+## Quick Commands
+
+- Analysis pass:
+ `node .agents/skills/pnpm-upgrade-package/scripts/check-release-age-window.mjs <package> <targetVersion>`
+- Transitive provenance / final graph verification:
+ `pnpm why -r <package>`
+- Inspect a current parent manifest on the registry:
+ `npm view <parent>@<installedVersion> dependencies peerDependencies optionalDependencies --json`
+- Optional lockfile cleanup:
+ `pnpm dedupe`
+- Bump in the root workspace:
+ `pnpm -w up <package>@<version>`
+- Bump in one workspace:
+ `pnpm --filter web up <package>@<version>`
+- Bump everywhere that should move together:
+ `pnpm -r up <package>@<version>`
+- Verify temporary override removal:
+ remove the override, then run `pnpm install` and `pnpm dedupe`