router
AGENTS.md5.6k starsChanged 2 months agoApache-2.0View on GitHub
Mirror notice. Generated from CLAUDE.md. Edit CLAUDE.md, then run make generate-agent-guides; CI rejects drift. Root guide for AI agents in the router/ subproject. Start here, then read the guide for the affected package. The README covers product setup, not required incident context. For a router repair, establish a synthetic failing regression before changing behavior and run it unchanged against the fix. For diagnosis-only requests, investigate without editing. Identify the incident-time serving revision and configuration before applying current source assumptions. A…
Trending
More talk lately.thin dataabout the whole repository
Who's talking about weave-os/router
- sudosubin/agents.nix“agent-skills.github.weave-os.router: 0.2.23 → 0.2.28”GitHub · Oct 4, 2026
- sudosubin/agents.nix“agent-skills.github.weave-os.router: init at 0.2.23”GitHub · Oct 3, 2026
- PyTorchKR/landscape“[Add] Weave Router (weave-os/router)”GitHub · Oct 3, 2026
- datarelay-labs/datarelay-atlas“[Roadmap] Adaptive Model Routing — Weave Router reference / cache-aware switching”GitHub · Oct 2, 2026
The biggest 4 of 4 mentions linking to the repository that our crawl found. Each line is their own headline.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository10 other files it gives its agents.
- cmd/AGENTS.mdAGENTS.md
- db/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- cmd/CLAUDE.mdCLAUDE.md
- db/CLAUDE.mdCLAUDE.md
- debug-claude-sessionSkill
- debug-codex-sessionSkill
- pr-merge-readySkill
- test-claude-locallySkill
- test-codex-locallySkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
19 rules. About 0 are common, 6 are distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Very specific: line 23
Run python3 scripts/agent_checks.py doctor and plan --base origin/main from this root for read-only prerequisite and suite discovery.
- Distinctive: line 161
If wanting to import something that violates these rules, design is wrong — surface as interface in appropriate inner-ring package and …
- Very specific: line 165
Every inference or adjacent operation has a typed purpose and reviewed policy in internal/router/policy/inference_registry.go.
- Very specific: line 169
Run make generate-inference-policy after registry changes and make inference-boundary before broader tests.
- Very specific: line 170
Read docs/INFERENCE_BOUNDARY.md before moving a call site.
- Very specific: line 199
Default rule: put logic in the package that uses it.
- Distinctive: line 203
Don't, unless same logic needed in 3+ places and no plausible existing home.
- Distinctive: line 211
If new helper doesn't fit, justify new package in code comment before creating.
- Distinctive: line 218
Keep files small. Split distinct logic into separate files, especially when shared between multiple places.
- Distinctive: line 219
Avoid unnecessary nesting — flatten conditionals with early returns + combined conditions.
- Very specific: line 220
All exported symbols carry godoc starting with symbol name (Foo does X or // Foo is …).
- Very specific: line 222
Use errors.Is / errors.As, never == or != on errors.
- Very specific: line 231
Use testify/assert + testify/require.
- Very specific: line 233
No DB-backed integration tests in internal/.
- Distinctive: line 239
Keep log statements on single line with all args inline.
- Very specific: line 240
Use log.With("key", value) to attach repeated context once, rather than repeating same key-value on every call.
- Very specific: line 243
Never log raw bearer tokens or hashes.
- Very specific: line 279
When adding new endpoint, put inside selfhosted block in server.Register unless part of product surface (/v1/*, /v1beta/*, /health, …
- Very specific: line 299
"How do I add new OpenAI-compatible upstream?": Add *BaseURL constant to internal/providers/openaicompat, provider-name constant + env-var …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
router — AGENTS
Mirror notice. Generated from CLAUDE.md. Edit CLAUDE.md, then run
make generate-agent-guides; CI rejects drift.
Root guide for AI agents in the router/ subproject. Start here, then read the guide for the affected package. The README covers product setup, not required incident context.
Production incident entrypoint
For a router repair, establish a synthetic failing regression before changing behavior and run it unchanged against the fix. For diagnosis-only requests, investigate without editing. Identify the incident-time serving revision and configuration before applying current source assumptions. A local repair does not authorize production mutation or establish production recovery.
| Symptom | Owning code and context | Initial regression boundary |
| Tool/schema rejection | translation, providers, internal/proxy/dispatch_error.go | Translation unit test, then provider conformance |
| Retry, fallback, truncated stream | proxy, internal/dispatch, internal/sse, inference boundary | Dispatch/SSE behavior, stream-commit and cancellation invariants |
| Wrong model or session pin | routing, Go HMM selection, session pins | Eligibility, policy selection and pin transitions |
| Authentication or charges | auth, internal/billing, composition | Credential isolation, entitlement and exactly-once accounting |
| Admission or release | internal/gateway, internal/policyregistry, serving control | Admission and immutable identity checks |
| Client setup or UI | install/, frontend/, contributing | Offline installer tests or frontend checks |
Run python3 scripts/agent_checks.py doctor and plan --base origin/main from this
root for read-only prerequisite and suite discovery. Missing required checks remain
blocked; do not report local checks as complete CI. Keep private incident notes in
ignored .context/; only authored, synthetic reproductions belong in public fixtures.
Engineering principles
- Patterns of Enterprise Application Architecture (Fowler)
- Designing Data-Intensive Applications (Kleppmann)
- Design Patterns (GoF)
- CLEAN architecture (Martin) — especially dependency inversion
- DRY
- Small expert team — explicit composition, readable wiring; reject DI containers, reflection, framework magic
- Concise comments, sparingly — default to none. Only when why is non-obvious (hidden constraint, subtle invariant, workaround, surprising behavior). Never rehash code, never reference current task/PR/caller, no multi-paragraph. If removing wouldn't confuse, don't write.
- Non-tautological tests — every test must assert behavior that breaks if prod code deleted.
Layer model and import rules
Three concentric layers. Imports flow inward only.
+-------------------------------------------------------------------+
| cmd/router/main.go (composition root — wires all) |
| |
| +-------------------------------------------------------------+ |
| | internal/api/admin (presentation: /health, /validate,| |
| | /admin/v1/*) | |
| | internal/api/anthropic (/v1/messages, passthrough, | |
| | /v1/route) | |
| | internal/api/openai (/v1/chat/completions) | |
| | internal/api/gemini (/v1beta/models/:modelAction) | |
| | internal/api/feedback (/f/<token> no-login feedback | |
| | page; deliberately no auth | |
| | middleware) | |
| | internal/api/analytics (/v1/analytics/* read-only | |
| | routing-decision export; | |
| | ra_ keys only) | |
| | internal/server (route registration) | |
| | internal/server/middleware (auth, timeout, cluster/embed | |
| | overrides, OTel timing) | |
| | internal/postgres (adapter: SQLC over pgx; also | |
| | session-pin store + billing repo | |
| | impls) | |
| | internal/sqlc (generated; regenerate via | |
| | `make generate`) | |
| | internal/router/cluster (Router impl: AvengersPro, | |
| | Multiversion) | |
| | internal/providers/* (Client impls: anthropic, openai, | |
| | google native, openaicompat, | |
| | httputil) | |
| | internal/observability/otel (span emitter; adapter) | |
| | internal/observability/apm (second OTel/SigNoz adapter: | |
| | gin HTTP spans + Go runtime | |
| | metrics; independent of otel's | |
| | per-decision span emitter) | |
| | internal/pubsub (adapter: GCP Pub/Sub cache- | |
| | invalidation + recharge-needed | |
| | notify) | |
| | | |
| | +-------------------------------------------------------+ | |
| | | internal/auth (identity domain: types, | | |
| | | repos, Service.VerifyAPIKey, | | |
| | | APIKeyCache, id/hashing, Tink | | |
| | | encryptor) | | |
| | | internal/billing (balance checks + inference | | |
| | | debits: Service + Repo iface; | | |
| | | Postgres impl in | | |
| | | internal/postgres) | | |
| | | internal/feedback (pure HMAC signer for the | | |
| | | no-login feedback-link token; | | |
| | | no I/O) | | |
| | | internal/analytics (routing-decision export domain: | | |
| | | Decision row shape, keyset | | |
| | | cursor, schema + price book; | | |
| | | Service + Repository iface, | | |
| | | Postgres impl in | | |
| | | internal/postgres) | | |
| | | internal/proxy (routing/dispatch service: | | |
| | | Route, ProxyMessages, | | |
| | | ProxyOpenAIChatCompletion, | | |
| | | ProxyGemini; action loop, | | |
| | | handover adapter, cache writer, | | |
| | | session-key derivation) | | |
| | | internal/proxy/usage (Anthropic unified-limit | | |
| | | observer for usage-bypass) | | |
| | | internal/router (Router iface + Request/Decision | | |
| | | + ModelSpec/ModelRegistry) | | |
| | | internal/router/cache (semantic response cache) | | |
| | | internal/router/catalog (single source of truth | | |
| | | for per-model data: | | |
| | | tier, provider bindings, | | |
| | | pricing, cost math) | | |
| | | internal/router/handover (Summarizer iface + | | |
| | | envelope rewrite) | | |
| | | internal/router/planner (cache-aware EV policy) | | |
| | | internal/router/sessionpin (Pin types + Store iface) | | |
| | | internal/router/turntype (turn-type detector) | | |
| | | internal/router/banditexplore (Router decorator: | | |
| | | bounded quality-tie-band | | |
| | | exploration, env-flag | | |
| | | gated) | | |
| | | internal/providers (Client iface + types + canonical | | |
| | | Provider* name constants) | | |
| | | internal/translate (cross-format wire-format | | |
| | | conversion: OpenAI <-> Anthropic | | |
| | | <-> Gemini; pure, no I/O) | | |
| | | internal/sse (zero-alloc SSE framing helpers) | | |
| | | internal/websearch (Anthropic native web-search | | |
| | | server tool: detection, result | | |
| | | synthesis, Executor iface; pure) | | |
| | | internal/timing (Timing value type: per-request | | |
| | | latency stamps, no otel dep) | | |
| | | internal/requestcontext (request-scoped creds, | | |
| | | identity, forwarded headers; | | |
| | | read by provider adapters) | | |
| | | internal/dispatch (inference execution boundary: | | |
| | | provider-client registry, plan | | |
| | | walk with retry/failover, wire- | | |
| | | target check, attempt events) | | |
| | +-------------------------------------------------------+ | |
| +-------------------------------------------------------------+ |
| |
| internal/config (env helpers: MustGet, GetOr) |
| internal/observability (slog logger + gin middleware) |
+-------------------------------------------------------------------+Hard rules
- Layering is load-bearing. Imports flow inward only. Inner-ring packages must not import adapter or presentation packages; adapters never import each other; only
cmd/router/main.goconstructs concrete things. Inner-ring packages may import each other (e.g.proxy.Service.Routereturnsrouter.Decision;proxy.Servicecallstranslate,sessionpin,planner,handover,cache,catalog,turntype,usage,billingto compose an action). - Request compatibility is Go-owned. Policy sidecars may extract generic features, classify complexity, and publish their configured roster/group ranking. They must never recognize native-tool request shapes or use provider/model identity to enforce request-level compatibility, eligibility, pass-through, session pins, fallbacks, or dispatch. Put native search detection in
internal/websearch, semantic requirements ininternal/translate, and routing enforcement ininternal/proxy/internal/router. The Go router must filter candidates before a sidecar call or bypass the sidecar entirely. - Small utility third-party libs allowed at every layer. Layering = about where I/O and behavior live, not banning go.mod entries. Reach for vetted small lib (
golang-lru,uuid, error helpers) before rolling own. Reject heavyweight frameworks (DI containers, ORMs, metaprogramming kits). - Inner-ring packages are I/O-free.
internal/inference,internal/router,internal/providers,internal/translate,internal/sse,internal/timing,internal/requestcontext,internal/feedback,internal/router/{cache,catalog,handover,planner,policy,sessionpin,turntype,banditexplore},internal/proxy/usagedefine interfaces, value types, pure functions only. Adding I/O method (HTTP, DB, queue, FS) = layering violation; put onauth.Service/proxy.Service/billing.Serviceor adapter subpackage. Pure-Go utility libs fine. - Adapters depend only on inner ring.
internal/postgresmay also importinternal/sqlc. Adapters never import each other —internal/postgresdoesn't knowinternal/api/adminetc. Provider adapters (internal/providers/<name>/) read request-scoped credentials, effective base URL / model alias, caller identity, and forwarded headers from the inner-ringinternal/requestcontextpackage — never frominternal/proxy(enforced byinternal/architecture).internal/dispatchis the only inner-ring package that dereferencesproviders.Client:proxy.Serviceholds adispatch.Clientsregistry and runs policy-resolved operations throughdispatch.Executor(wired incmd/router/main.go), which validates the prepared wire model against the plan target before any upstream I/O and emits ordered attempt events. Upstream response headers are reported throughproviders.ObserveUpstreamHeaders, whose observer is attached by proxy.internal/server/middlewareandinternal/providers/httputil(both adapters) stamp/read request latency viainternal/timing'sTimingvalue type instead of importinginternal/observability/oteldirectly —Timingused to live inoteland was pulled out specifically so these adapters (andinternal/providers/{anthropic,openai,google,openaicompat}) don't need a concrete dependency on the OTel exporter adapter just to stamp a timestamp.internal/proxyalso importsinternal/timing(an inner-ring package importing another inner-ring package, which is allowed) to read timing back into span attributes. internal/api/*andinternal/serverdepend oninternal/auth(Service handle + middleware-context types),internal/proxy(routing/dispatch service handle), andinternal/router(Routerinterface +Request/Decisiontypes —internal/server/middleware/auth.goandrouting_knobs_override.goconstruct/readrouter.Request/router.Decisionfor header-driven overrides). May importinternal/observabilityfor logging,internal/providersfor shared sentinel errors,internal/router/clusterforErrClusterUnavailablesentinel +DeployedModelsSourceinterface (API handlers map sentinel → HTTP 503). Must not importinternal/postgres, any concreteinternal/providers/*adapter, orinternal/translatedirectly. Concrete instances reach presentation only via constructor params from composition root.internal/configandinternal/observabilityare leaf utilities — must not import any other package underinternal/. Third-party utility deps fine; today pull only stdlib + gin (request-scoped logger middleware).internal/observability/otelsubpackage is an adapter (builds real OTLP exporter) and can import other internal packages; parentinternal/observabilitystays a leaf.- Worker composition happens in
cmd/router/main.go; gateway composition incmd/router-gateway/main.go. The gateway wires identity/admission and a streaming hop only, never providers, ONNX or billing. Seecmd/CLAUDE.md.
If wanting to import something that violates these rules, design is wrong — surface as interface in appropriate inner-ring package and implement in adapter subpackage.
Inference policy boundary
- Every inference or adjacent operation has a typed purpose and reviewed policy in
internal/router/policy/inference_registry.go; generated review projections live indocs/POLICY_INFERENCE.{md,json}. - Feature orchestration describes an operation with
inference.InvocationRequest;policy.PlanResolveris the only constructor for immutablepolicy.ResolvedPlanexecution authorization. Invalid target or budget overrides fail closed instead of falling through to another model. - New feature code must not own a provider client/map, call
providers.Client.Proxy/Passthrough, construct a provider/modelrouter.Decisionfor execution, or add a fixed catalog target. Current migration exceptions are enumerated with owner, rationale, operation class, and removal phase ininternal/architecture/inference_boundary_baseline.json. router.Decisionremains a compatibility/result DTO during migration; it is not provider-call authorization. New selection behavior starts as a policy entry and later resolves to the executor contract.- Run
make generate-inference-policyafter registry changes andmake inference-boundarybefore broader tests. The latter is type-aware and rejects baseline growth, concrete-provider imports outside adapters/composition, raw HTTP calls to known inference routes, and unregistered purposes. - Read
docs/INFERENCE_BOUNDARY.mdbefore moving a call site. It records the operation taxonomy, current owners, pending PR sequencing, and behavior-regression suites.
Where to put new code
Pick by responsibility, then read that package's CLAUDE.md:
| Responsibility | Package | Guide |
| HTTP endpoint (handler + route) | internal/api/<group>/ | internal/api/CLAUDE.md |
| Identity / API-key logic | internal/auth (method on *Service) | internal/auth/CLAUDE.md |
| Per-action orchestration | internal/proxy (method on *Service) | internal/proxy/CLAUDE.md |
| Execution authorization / provider attempts | internal/router/policy / internal/dispatch | docs/INFERENCE_BOUNDARY.md |
| Managed admission / release identity | internal/gateway / internal/policyregistry | docs/SERVING_CONTROL.md |
| Balance check / inference debit | internal/billing (method on *Service) | — |
| Feedback-link token signing (no I/O) | internal/feedback | — |
| Routing-decision export row shape / cursor / schema | internal/analytics | — |
| Cross-format wire conversion (no I/O) | internal/translate | internal/translate/CLAUDE.md |
| Native web-search server tool (no I/O) | internal/websearch | — |
| New upstream provider | internal/providers/<name>/ | internal/providers/CLAUDE.md |
New Router implementation | internal/router/<name>/ | internal/router/CLAUDE.md |
| Cluster scorer / artifacts | internal/router/cluster/ | internal/router/cluster/CLAUDE.md |
| New model / per-model pricing data | internal/router/catalog/ | internal/router/catalog/CLAUDE.md |
| Cache-aware action routing internals | internal/router/{planner,handover,cache,sessionpin,turntype}/ | each has its own CLAUDE.md |
| Bounded quality-tie-band exploration | internal/router/banditexplore/ | — |
| Anthropic usage-bypass gate | internal/proxy/usage | internal/proxy/usage/CLAUDE.md |
| New column / SQL query | db/queries/ + internal/postgres/ | db/CLAUDE.md, internal/postgres/CLAUDE.md |
| Cross-instance cache invalidation / recharge notify | internal/pubsub | — |
Doc under docs/ | docs/ | docs/CONFIGURATION.md |
Default rule: put logic in the package that uses it. Only promote to a shared home (auth, proxy, translate, config, observability, sse, timing) when 3+ packages need the same logic.
Adding a new helper
Don't, unless same logic needed in 3+ places and no plausible existing home. Canonical homes:
- Auth helpers (token prefix, ID gen, hashing, encryption) →
internal/authalongside types they support. - Env parsing →
internal/config. - Logging / tracing →
internal/observability(OTel exporter inotelsubpackage). - SSE framing →
internal/sse. - Per-request latency stamps →
internal/timing— pure value type shared by adapters (server/middleware,providers/*) andproxy.Service; deliberately has zero otel dependency so those adapters don't need one just to stamp a timestamp.
If new helper doesn't fit, justify new package in code comment before creating.
Conventions
Go style
- No magic strings for provider/model names. Use named constants from
internal/providers(providers.ProviderAnthropic,providers.ProviderOpenAI,providers.ProviderGoogle,providers.ProviderOpenRouter,providers.ProviderFireworks) everywhere provider names appear as values — map keys, switch cases,router.Decision.Providerliterals, log fields, test fixtures. For new model name constants, add to appropriate package before use. Bare string literals = review-blocking. - Keep files small. Split distinct logic into separate files, especially when shared between multiple places.
- Avoid unnecessary nesting — flatten conditionals with early returns + combined conditions.
- All exported symbols carry godoc starting with symbol name (
Foo does Xor// Foo is …). - Errors flow up. Don't swallow; don't log-and-continue on request path. The one documented exception is a best-effort, off-request-path fire-and-forget — always wrapped in
observability.SafeGo(bounded timeout, panic-recovering, logs its own failure), never a rawgo func(){}(). Current call sites:fireMarkUsed(auth/service.go),fireTelemetry+reportHMMOutcome(proxy/service.go),NotifyInstallationChanged+NotifyRechargeNeeded(pubsub). - Use
errors.Is/errors.As, never==or!=on errors. For no-rows checks:errors.Is(err, sql.ErrNoRows). - Use
slog, notfmt.Printlnorlog.Print*. On the request path, acquire the logger from the context —observability.FromContext(ctx), orobservability.FromGin(c)in a handler. Both inherit the correlation fieldsobservability.Middlewarebinds at first touch (request_id, plussession_key/client_session_idoncebindRequestLoggerruns), which is what makes one session's logs filterable end to end.observability.Get()returns the global logger with no request correlation, so a request-path line emitted through it cannot be found when filtering by session — reserve it for genuinely off-request-path code (startup, background listeners,SafeGofire-and-forget). Enforced byTestGlobalLoggerBudget; fix a failure by threading ctx, not by raising the budget. - Sentinel errors typed (
var ErrFoo = errors.New(...)) + live in same package as function that returns them. HTTP layer maps to status codes; do not export HTTP semantics from inner-ring packages. - Constructor injection over package-level singletons. Inject clock (
auth.Clock = func() time.Time), logger, HTTP client, etc.
Tests
- Tests live next to code (
foo_test.gonext tofoo.go). Prefer<pkg>_testexternal test packages so public API exercised; use internal package only when test needs unexported state (*_internal_test.gofiles ininternal/proxyare canonical). - Real assertions only. Compare value code-under-test produced to value test author chose. Tautological assertions (
x == x, "constructor returns instance", "mock called with X") rejected. - Use
testify/assert+testify/require. Userequire.Eventuallyfor async (see service_test.gofireMarkUsedassertion). - In-memory fakes for repos/routers/provider clients are cheap + far better than mocks for unit testing Service.
- No DB-backed integration tests in
internal/. If need real Postgres,docker composestack is runtime fixture; write scripts underscripts/rather than*_test.go. - Pre-merge end-to-end smoke suite (
smoke/,smokebuild tag) boots an isolated real router behind a record/replay MITM proxy. Local and PR runs replay recorded synthetic provider responses without provider keys; only explicit recording checks live provider acceptance. The shared selector inscripts/agent_checks.pyincludes request-path packages, dispatch/policy/SSE, gateway and build inputs. Add a scenario for stack-level wire/stream/cache behavior not already established by a smaller test. See docs/SMOKE.md for isolation, scenario creation, recording and privacy constraints.
Logging
- Log message explains in plain English what happened. Include
err+ relevant context (IDs, counts, status codes). - Keep log statements on single line with all args inline.
- Use
log.With("key", value)to attach repeated context once, rather than repeating same key-value on every call. - snake_case for log attribute keys (
api_key_id, notapiKeyID). - Log
Debugfor routine ops (auth checks, repo calls);Infofor major business events (server start, key issuance). ReserveErrorfor genuine failures needing on-call attention; auth-401 isDebug, notError. - Never log raw bearer tokens or hashes. 8-char prefix + 4-char suffix (
KeyPrefix/KeySuffixcolumns onauth.APIKey) are safe; full token is not.
Every line must be findable. Correlation tags are what let an operator pull one session's full log trail; a line without them is effectively lost even though it was written. The tags are attached in two layers, and both are automatic — inherit them, never re-add by hand:
| Field | Bound by | Present from |
name | initLogger (from NAME, else OTEL_SERVICE_NAME, else router) | process start — every line |
request_id | observability.Middleware | first touch, before the body is read |
session_key, api_key_id, ingress | bindRequestLogger | after the envelope parses |
client_session_id | bindRequestLogger | after the envelope parses, when the client sent one |
request_id is bound before parsing on purpose: pre-parse failures ("Failed to parse Anthropic request") used to be untagged, which made exactly the errors you go hunting for the ones you could not find. It is echoed as the X-Request-Id response header. An inbound X-Request-Id is not adopted — it lands in upstream_request_id (sanitized, length-bounded) instead, so one client reusing a value can't make request_id stop identifying a single request.
A helper that logs on the request path takes ctx and calls observability.FromContext(ctx). Do not add a msg-only log helper that reaches for observability.Get() internally — that silently drops every tag (this is what made upstream 4xx/5xx error bodies unfindable by session; see httputil.LogUpstreamStatus, which now takes ctx for that reason).
Never pass a bound key as a call-site attribute. slog does not dedupe: re-passing request_id, session_key, client_session_id, api_key_id, ingress, or name emits the key twice and JSON consumers keep the last value, overwriting the bound one — so the line goes missing from exactly the search that should find it. A different-meaning value gets a distinct key (upstream_request_id, rated_request_id, tool_name); an identical value is simply dropped. Enforced by TestNoReservedLogKeyShadowing.
Things to NEVER do
- Never put customer/company/org names or private identifiers in anything committed here. This repo is public — commit messages, branch names, PR titles/descriptions, code comments, tests, and fixtures are world-readable. This holds even when a change is motivated by one customer's investigation (e.g. a loop-break or spiral fix found from a specific org's agentic session): describe the trigger generically ("a customer", "a large agentic session", "an org's monorepo"). No org names, org IDs, account emails, internal ticket/Linear links, or verbatim private Slack/support excerpts — those stay in the private Weave repo + Linear.
- Never import code from outside this subproject. Router is standalone Go module (
module weave-os/router) with no cross-project deps. If need utility from elsewhere in monorepo, copy into appropriateinternal/package with own godoc. - Never write raw SQL outside
db/queries/or callpgx.Pooldirectly from anywhere exceptinternal/postgres/. SQLC is only data mapper. - Never reach across layers. Handler in
internal/api/calling*sqlc.Queriesdirectly = layering violation; surface Service method instead. Repo calling another repo = layering violation; put orchestration inauth.Service/proxy.Service. - Never add FKs to tables outside router's own schema. Such tables don't exist in this project.
organization_id+created_by= opaque external strings, not FKs. - Never panic on request path. Reserve
panicfor startup-time fail-fast (config.MustGet, cluster-scorer boot failure, invalidROUTER_DEPLOYMENT_MODE) where misconfiguration must abort process. - Never introduce DI container, reflection-based wiring, or service locator. Composition = plain Go function calls in
cmd/router/main.go. - Never log secrets, raw API keys, or full request bodies. First 8 + last 4 chars on
auth.APIKeyare safe form. BYOK secrets at rest go throughauth.Encryptor(Tink AES-256-GCM); plaintext only in memory for request lifetime. - Never edit generated files under
internal/sqlc/. Regenerate withmake generate. SQLC's "DO NOT EDIT" header is load-bearing.
Deployment modes
ROUTER_DEPLOYMENT_MODE read at boot in cmd/router/main.go:
selfhosted(default): full dashboard at/ui/*,/admin/v1/*API (auth, metrics, keys, provider-keys, config, excluded-models), dashboard cookie auth all mounted. Provider keys read from env vars; missing keys keep providers registered for client-passthrough but exclude from hard-pin resolution.managed: dashboard +/admin/v1/*not mounted; the control plane is separate. Billing is enabled when its tables exist (a transient billing health-check error also keeps billing enabled). With billing, deployment keys are loaded and platform requests are balance-gated. Only a managed deployment without billing stays BYOK-only and registers empty deployment keys. Inspectcmd/router/main.goand the incident's boot configuration rather than inferring credentials from the mode alone. Any other mode value panics at boot. BYOK remains opt-in per installation (byok_enabled):withAPIKeystrips external keys until enabled; opted-in BYOK debits no inference cost, thoughBYOK_FEE_RATEmay add a separate platform-fee ledger row.
When adding new endpoint, put inside selfhosted block in server.Register unless part of product surface (/v1/*, /v1beta/*, /health, /validate). Do not re-expose admin surface in managed mode.
Eval harness (sibling router-internal/eval/)
The eval harness is a sibling uv project, not in this repo — lives at router-internal/eval/ in the Weave monorepo and runs as a Modal app. It exercises the router via staging headers; see that package's README.
Per-request router selection (server side):
internal/server/middleware.WithClusterVersionOverridereadsx-weave-cluster-version: v0.Xheader + stashes version on request context.cluster.Multiversion.Routereads viacluster.VersionFromContext+ dispatches to matchingScorer. Customer traffic (no header) always serves deployment's default version (ROUTER_CLUSTER_VERSION→artifacts/latest).WithEmbedOnlyUserMessageOverridehonorsx-weave-embed-only-user-message: true|falseheader, flipping proxy between embedding user-role text only (default) + concatenated action stream.
What to NOT do:
- Do NOT re-introduce heuristic-vs-cluster A/B switch. Heuristic retired because silent-fallback behavior masked cluster regressions. If need to compare strategies, ship alternate strategy as another
internal/router/Xpackage + promote on own merits, not as runtime fallback. - Do NOT add runtime override that picks specific model directly. Whole point is comparing router strategies, not per-request model overrides.
Quick reference
- "Should I commit
internal/sqlc/?" Yes. Dockerfile + CI builds depend on generated code being present. Runmake generatebefore committing migration or query changes. - "How do I run one-off query against local DB?"
docker compose exec postgres psql -U router -d router. Migrate step has already applied schema. (Router lives inrouterschema; pool'sAfterConnecthook pinssearch_pathso accidental writes topublic.*are impossible.) - "How do I add new OpenAI-compatible upstream?" Add
*BaseURLconstant tointernal/providers/openaicompat, provider-name constant + env-var entry tointernal/providers/provider.go, registration block incmd/router/main.go. No new adapter package. See internal/providers/CLAUDE.md.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

