Layering rules (enforced, not aspirational)
- Transport layers (REST routes, MCP tools) contain zero business logic — they parse (schema), call
packages/core, format. Oversized router files are the anti-pattern to avoid. packages/corenever imports express/MCP/Next types.packages/dbenforces two-layer tenant isolation: every tenant-scoped query runs insidewithTenant()(RLS) and carries an explicit caller-bounduser_idpredicate — defense in depth, perdocs/concepts/data-model.mdx.- 50-line function / 500-line file budget. Target, not a lint rule — same as AGENTS.md hard rule 5. Oversized files in core paths are the failure mode the budget is there to prevent.
- Dependency direction is package.json + review +
scripts/check-db-access.sh. CI does not run a dedicated dependency-direction linter.
Server topology note
API and MCP ship as one express app / one service in v1 (a shared service layer makes a separate process split unnecessary at this scale). Split into separate deployables only when load profiles demonstrably diverge — the code structure (thin adapters overcore) keeps that a deploy-config change, not a refactor.
Resource-limit composition contract
The public server exposes two optional, billing-neutral resource limits through the injectedLimits resolver:
maxLiveMemoriescaps rows wherestatus = 'active' AND valid_to IS NULL.maxActiveMcpClientscaps distinct client IDs with at least one non-revoked, unexpired OAuth token.
valid_to is already set do not. A revision is allowed at the cap because it closes one live row and appends its successor in the same transaction, leaving the live count unchanged.
OAuth admission is serialized with account credential lifecycle changes. A first grant for a new distinct client is refused at the cap, while reauthorization of an already-active client remains possible when usage is at or below the cap. If a limit is lowered below current usage, issuance converges without deleting credentials: only the newest allowed client IDs (ordered by their latest live token creation time, then client_id ascending) may reauthorize or rotate. Losing clients cannot leapfrog the retained set with a fresh authorization-code flow, and their current access tokens expire naturally. Dynamic registration and CIMD resolution remain unrestricted; the limit is enforced when a client first receives tokens.
Transport contracts are explicit:
- REST memory creation returns
409 {"error":"resource_limit_exceeded"}. - MCP tools return an
isErrorresult with reason coderesource_limit_exceeded. - The onboarding welcome-seed endpoint returns the same HTTP 409 reason. On success it returns
200 { outcome }, wherecreatedmeans a new seed andalready_existsmeans deduplication found an existing copy, including archived copies; it never restores an archived memory. GET /auth/onboardingis read-only and returns connection history plususerMemoryCount: live memories excluding the welcome seed by content hash and system creation provenance. A user-authored note with the same title or content still counts.- OAuth token issuance returns RFC-compatible HTTP 400
invalid_grantwith the safe descriptionActive MCP client limit reached.
@3ngram/server/app exports the literal RESOURCE_LIMITS_ENFORCED = true. Downstream composition roots can require this sentinel before booting, preventing an older public server from silently ignoring the optional fields. It is a runtime compatibility marker, not commercial policy.
LLM gateway
packages/llm owns every model call; scripts/check-no-direct-provider.sh fails the build on a provider host or SDK import anywhere else in apps/ or packages/. Core and the apps see one Gateway interface with three methods:
embed(texts, operation): vectors from the OpenAI-compatible gateway (LLM_GATEWAY_URL+LLM_GATEWAY_API_KEY).complete(prompt, operation, options): text generation from the same gateway.decide(request, operation): typed judgments (issue #225). A request carries one boundedstateand named questions (noulyes/no,choice,score). Each answer comes back typed, with a probability or confidence in [0, 1], under the name of the question it answers. Anything else fails the call: a missing or extra answer, an unknown label, a probability map that does not cover exactly the question’s labels or levels, or an out-of-range number. Only the Jev gateway (packages/llm/src/jev.ts, raw fetch, one attempt, no retries) implements it. The OpenAI gateway throwsNotImplementedError, and Jev’sembed/completethrow it too.
composeGateway. embed/complete go to the OpenAI-compatible gateway, and decide goes to Jev when JEV_API_KEY and JEV_MODEL are both set. Without them decide rejects with NotImplementedError, so callers can tell “not configured” apart from a failed call. Judgment also needs the base gateway: with no LLM_GATEWAY_* there is no gateway at all. JEV_MODEL must name a pinned model. A floating alias such as jev-latest or latest is refused at env load and again by the gateway factory, and setting a key without a model is a boot error. The last pin verified wire-compatible is jev-1.14.0 (2026-10-25). That is a contract check, not a quality evaluation. On that date /v1/models listed only the aliases jev-latest and jev-preview, so the version to pin is read from the model field of a /v1/systemone response, and the API accepts that version as the request model. An unknown pin is answered 400, which decide() surfaces as a status-only GatewayRequestError. packages/llm/test/__fixtures__/jev-systemone-recorded.json holds one recorded response for that pin, and the wire guards are tested against it. JEV_API_URL defaults to the vendor’s API root. It must be https, with no credentials, query or /v1 path. Setting JEV_* without the LLM_GATEWAY_* pair logs one boot warning and leaves decide() unavailable. Every call is a registered metered operation (packages/llm/src/operations.ts); judgments use the generation capability class because they are billed model inference, the same thing the llm_generation plan capability gates.
Subprocessor. With JEV_* configured, the state of a decide() call goes to TypeSafe AI (Jev). Nothing in the shipped code calls decide() yet. Any caller must first check the tenant’s judgment opt-in before it sends tenant-derived text. The opt-in is isJudgmentEnabled in packages/core, backed by user_judgment_policy and set through PUT /api/v1/settings/judgment. It defaults to off, and account erasure resets it to off. The check must run immediately before the send, never at enqueue time, so an opt-out that lands in between still stops it. Every change is recorded as a content-free audit_log row (settings.judgment.set, mode only) as the consent record. Self-hosters who never set JEV_* send nothing.