Skip to content

Error codes

Every error Karni raises starts with a code and ends with a link to its entry on this page:

E104: EventViewSet: Owned('organiser') does not lead from Event to the user model
(Event has no field 'organiser'). Name a relation path ending at the user, e.g.
Owned("organizer") or Owned("event__organizer"). See …/errors/#e104

The message names your class, field or setting. The entry below says why Karni objects and how to fix it in general. Offline, without a browser:

karni explain E104      # any code on this page: E, W, C, PAY, K

Codes are permanent: a code never changes meaning and is never reused, so match on the code, not on the wording, which improves between releases.

Prefix Comes from
E / W Karni itself: exceptions, system checks (W = warning), API errors, test failures
PAY the karni-payments module (each module has its own prefix)
SUG suggestions from code, printed by karni check and karni doctor, never a failure
C the karni command
K agent rules, enforced by karni check and the architecture tests
karni/… the ESLint plugin shipped with @karni/ui

System checks run on runserver, migrate, check and every management command, so problems surface on boot rather than on the first request. Their ids are karni.<code>. Silence a warning on purpose with SILENCED_SYSTEM_CHECKS = ["karni.W001"]. karni_settings() starts that list empty, so SILENCED_SYSTEM_CHECKS += ["karni.W001"] works in a project.

End-user outcomes are not on this page: wrong credentials, expired or used tokens, an invalid 2FA code, a declined payment, a 404 for a row outside your access. Those are ordinary API responses (see accounts and api), not mistakes in your code.

Karni (E, W)

0xx · Models, managers and scopes

E001: A soft-delete model's default manager shows deleted rows

system check (error) · from karni.checks.check_soft_delete_managers

Why Karni objects. The model inherits SoftDeleteModel, but its default manager does not run Karni's scope pipeline, usually because another mixin listed first supplied a plain objects. Deleted rows then appear in every query, relation and API response, and the model misses every future scope such as tenant.

Fix. Inherit karni.models.BaseModel, or list SoftDeleteModel first among the Karni mixins, or declare objects = SoftDeleteManager() (any manager built on karni.managers.ScopedManagerMixin) with class Meta(SoftDeleteModel.Meta).

W001: A registered scope is switched off by KARNI_SCOPES

system check (warning) · from karni.checks.check_scopes

Why Karni objects. KARNI_SCOPES lists the scopes that run. A registered scope it leaves out filters nothing, which is usually an accident after installing a module.

Fix. Add the scope's name to KARNI_SCOPES (or unset KARNI_SCOPES to run every scope). If switching it off is deliberate, add 'karni.W001' to SILENCED_SYSTEM_CHECKS.

E002: A scope or the KARNI_SCOPES setting is invalid

system check (error) · from karni.scopes registry; karni.checks.check_scopes

Why Karni objects. Every query of a scoped model runs the registered scopes in order. A scope that fails to load, has a bad name or order, or a KARNI_SCOPES list that names unknown or duplicate scopes would silently change which rows every query returns.

Fix. Fix the scope class or the KARNI_SCOPES entry the message names. A Scope subclass needs an identifier name and an int order. KARNI_SCOPES is a list of registered names in pipeline order (or unset to run all of them).

E003: objects.without() names no scope, or an unknown one

exception · from karni.scopes; Model.objects.without()

Why Karni objects. without() lifts a scope by name for one query. An unknown name would lift nothing while the code reads as if it did.

Fix. Pass a registered scope name, e.g. Model.objects.without("soft_delete", reason="..."). The message lists the registered scopes.

E004: objects.without() needs a reason

exception · from karni.scopes; Model.objects.without()

Why Karni objects. Lifting a scope shows rows the scope exists to hide (deleted rows, another tenant's rows). The reason is logged so every such query can be audited.

Fix. Pass reason="<why this query must see rows the scope hides>", e.g. Model.objects.without("soft_delete", reason="admin: deleted filter").

E005: without() was called on a queryset

exception · from karni.managers.ScopedQuerySet.without

Why Karni objects. Scopes are applied when the manager builds the queryset, so a queryset has already filtered by every scope. Lifting one there cannot bring rows back.

Fix. Start from the manager: Model.objects.without("<scope>", reason="...").filter(...).

E006: A scope's context is not bound

exception · from karni.scopes.ScopeContextMissing (raised by a scope, e.g. tenant)

Why Karni objects. A scope that needs context (the current tenant) has none, typically in a Celery task, management command or test. Karni fails closed instead of returning every tenant's rows.

Fix. Bind the context before querying, as the message says (e.g. wrap the task body in the module's context manager), or lift the scope deliberately with Model.objects.without("<scope>", reason="...").

E007: Karni.audit or Karni.sensitive is malformed

exception · from karni.audit.capture

Why Karni objects. A model opts into change history with True or a list of its field names, and names its sensitive fields the same way. A name the model does not have would silently audit or redact nothing.

Fix. Write class Karni: audit = True (or a list of field names) and sensitive = [...] with field names of the model.

E008: unrecorded() has no reason

exception · from karni.audit.capture.unrecorded

Why Karni objects. A block of saves that leaves no change-history entry hides writes from the history, so it says why: what it writes that no person makes, as a lifted scope says why it lifts.

Fix. Pass the reason: with unrecorded("the template's default, stored on its first render"):.

1xx · API: access, viewsets, serializers, pagination, budgets, expand

E101: A viewset declares no access

system check (error) · from karni.checks.check_viewsets; karni.api.access.KarniAccessPermission

Why Karni objects. Access is mandatory (ADR 0001 Q2.1): without a declaration Karni cannot know which rows a user may see or change, so the viewset denies every request.

Fix. Declare access = Granted() on the viewset (the roles' grants for its model, row-scoped), or a custom Access(read=..., write=...) (e.g. Access(read=Authenticated(), write=Owned('owner'))), or opt out explicitly with access = Unscoped(reason='...').

W101: A hand-written serializer duplicates the one Karni generates

system check (warning) · from karni.checks.check_viewsets

Why Karni objects. Karni generates the serializer from the model (APIMeta tunes it). A copy that declares nothing of its own drifts from the model and from the schema the frontend is generated from.

Fix. Delete the serializer and its serializer_class line, and tune the generated one with APIMeta on the model. Keep serializer_class only for a serializer with custom fields or validation. When the copy is deliberate, say why on the line above the class: # karni: allow(redundant-serializer): <reason> (karni make serializer --reason writes it).

E102: access is not an Access(...) or Unscoped(...) declaration

exception · from karni.api.access.validate_access

Why Karni objects. The access declaration compiles into both the request gate and the row filter. Anything else would leave one of them undefined.

Fix. Write access = Access(read=..., write=..., create=...) with predicates, or access = Unscoped(reason='...'). A bare predicate goes inside Access(read=...).

W102: Any self-registered user may change and delete every row of a resource

system check (warning) · from karni.checks.check_open_writes

Why Karni objects. The viewset's write predicate is Authenticated() or Public(), not narrowed with & by HasRole, Granted, Owned or Can, while KARNI_ACCOUNTS_REGISTRATION is True. Anyone who opens an account through register/ can then update and delete every row the viewset routes. A test that acts as any signed-in user passes and confirms it. Karni 0.4.0's --access public-read preset generated this declaration.

Fix. Tighten write: HasRole("staff") (what --access public-read now writes), Granted() (the roles' grants) or Owned("<field>"). create=Authenticated() with an Owned() write is the user-generated-content pattern and is not flagged. If nobody may self-register, set KARNI_ACCOUNTS_REGISTRATION = False. If every signed-in user is trusted, add 'karni.W102' to SILENCED_SYSTEM_CHECKS.

E103: A predicate was expected but something else was given

exception · from karni.api.access: Access(...), Owned(bypass=...), @action(access=...)

Why Karni objects. Access slots, Owned(bypass=...) and @action(access=...) take predicate instances so they can be evaluated per request and per row.

Fix. Pass a predicate instance: Owned('field'), HasRole('staff'), Authenticated(), Public(), Where(fn), combined with | and &. Write HasRole('staff'), not HasRole.

E104: Owned() does not name a path to the user

exception · from karni.api.access.Owned; karni.api.access.validate_access

Why Karni objects. Owned('path') filters rows to those whose path leads to request.user, and stamps the owner on create. A path that does not end at the user model would match nothing or the wrong rows.

Fix. Name the owner relation as a string, following relations with __ and ending at the user model: Owned('organizer') or Owned('event__organizer').

E105: HasRole() names no roles

exception · from karni.api.access.HasRole

Why Karni objects. Roles are Django group names. A HasRole without names would grant nobody.

Fix. Pass one or more group names: HasRole('staff') or HasRole('organizer', 'staff').

E106: A Where() function is invalid

exception · from karni.api.access.Where

Why Karni objects. Where(fn) calls fn(request) for the request gate and as the row filter. The function must be callable and return a Q (rows) or a bool (everything or nothing).

Fix. Pass a function of the request returning a Q or a bool, e.g. Where(lambda request: Q(published=True)).

E107: Unscoped() needs a reason

exception · from karni.api.access.Unscoped

Why Karni objects. Opting a viewset out of access control is sometimes right (a public catalogue), but it must be deliberate and reviewable. The reason is published in karni context and the schema.

Fix. Write access = Unscoped(reason='public catalogue') with a non-empty reason.

E109: Access predicates were combined with and / or / not

exception · from karni.api.access.Predicate.__bool__

Why Karni objects. Python's and/or/not evaluate truthiness, so one side of the expression would be silently dropped.

Fix. Combine predicates with | and &: Owned('user') | HasRole('staff').

E110: A viewset has neither model nor queryset

exception · from karni.api.viewsets.BaseViewSet

Why Karni objects. Karni generates the queryset, serializer, filters and expansion from the model.

Fix. Set model = YourModel on the viewset (or queryset = ...), or override get_queryset() and get_serializer_class().

E111: Pagination was switched off without Unpaginated(...)

exception · from karni.pagination.check_pagination_class; BaseViewSet

Why Karni objects. An unpaginated list grows with the table until it times out (ADR 0001 Q3.5), so every list must be bounded.

Fix. Keep the default paginator, or declare pagination = Unpaginated(max_rows=N, reason='...') to return a bounded plain list.

E112: pagination_class is not a Karni paginator

exception · from karni.pagination.check_pagination_class

Why Karni objects. Karni's paginators enforce KARNI_MAX_PAGE_SIZE. Another paginator would let a client request unbounded pages.

Fix. Subclass karni.pagination.KarniPageNumberPagination or KarniCursorPagination.

E113: Unpaginated(...) is invalid

exception · from karni.pagination.Unpaginated; BaseViewSet.pagination

Why Karni objects. Unpaginated lists still need a hard row limit and a reviewable reason.

Fix. Write pagination = Unpaginated(max_rows=500, reason='CSV export') with a positive max_rows and a non-empty reason. To change the paginator, set pagination_class instead.

E114: Both pagination and pagination_class are declared

exception · from karni.api.viewsets.BaseViewSet

Why Karni objects. The two declarations contradict each other.

Fix. Keep one: pagination = Unpaginated(...) for a plain bounded list, or pagination_class for another Karni paginator.

E115: A query Budget(...) is invalid

exception · from karni.performance.Budget; BaseViewSet.query_budget

Why Karni objects. A query budget caps SQL statements per request to catch N+1 regressions. Raising it must be a measured, explained decision.

Fix. Write query_budget = Budget(list=25, reason='...'): name at least one action, use positive integers (None stops checking an action) and give a non-empty reason.

E116: query_budget names unknown actions

exception · from karni.api.viewsets.BaseViewSet

Why Karni objects. A budget for an action the viewset does not have would never apply.

Fix. Use the viewset's action names (list, retrieve, create, update, partial_update, destroy, or an @action's name), or default= for every other action.

E117: A request ran more SQL queries than its budget

exception · from karni.api.viewsets.BaseViewSet; karni.testing.query_budget

Why Karni objects. Repeated statements are almost always an N+1: a relation loaded once per row. Budgets turn that into a failing test instead of a slow production page.

Fix. Read the repeated statements in the message and load that relation up front (select_related / prefetch_related, or let the optimizer see it through the serializer). If the work is real, raise the limit: query_budget = Budget(list=N, reason='...').

E118: KARNI_QUERY_BUDGET_MODE is invalid

exception · from karni.performance.budget_mode; karni.testing.pytest_plugin

Why Karni objects. The mode decides whether an exceeded budget is ignored, logged or raised.

Fix. Set KARNI_QUERY_BUDGET_MODE (or the pytest ini option karni_query_budget_mode) to 'off', 'warn' or 'raise'.

E119: Cache(...) or Uncached(...) is invalid

exception · from karni.api.caching; BaseViewSet.cache

Why Karni objects. Response caching must have a positive lifetime, and opting a viewset out must be explained.

Fix. Write cache = Cache(ttl=300) with a positive integer, or cache = Uncached(reason='balances change on every request').

E120: Query hints are invalid

exception · from karni.api.optimizer.validate_hints

Why Karni objects. select_related / prefetch_related / select hints are merged into the optimizer's plan, so they must be lookups it can apply.

Fix. Give a list of lookup strings (e.g. select_related = ["venue"]) or Prefetch objects for prefetch_related.

E121: optimize must be True or False

exception · from karni.api.viewsets.BaseViewSet

Why Karni objects. optimize switches the automatic query optimizer for the viewset.

Fix. Set optimize = True (default) or optimize = False.

E122: APIMeta declares both fields and exclude

exception · from karni.api.serializers (generated serializers)

Why Karni objects. The generated serializer can take an allow-list or a deny-list, not both.

Fix. Keep APIMeta.fields or APIMeta.exclude on the model.

E123: APIMeta names fields the serializer does not have

exception · from karni.api.serializers (generated serializers)

Why Karni objects. read_only_fields, write_only_fields and expand entries must name fields that the generated serializer exposes, or they would silently do nothing.

Fix. Fix the spelling, or add the field to APIMeta.fields (or remove it from exclude).

E124: A field is both read-only and write-only

exception · from karni.api.serializers (generated serializers)

Why Karni objects. A field cannot be both returned-only and accepted-only.

Fix. Remove the field from APIMeta.read_only_fields or APIMeta.write_only_fields.

E125: An expandable field is not a relation

exception · from karni.api.serializers.expanded_field

Why Karni objects. ?expand= replaces a foreign key's id with the related object, so only relations can be expanded.

Fix. Name a ForeignKey, OneToOneField or ManyToManyField (or a reverse relation) of the model.

E126: The ?expand= parameter names an unknown or invalid path

API 400 response · from karni.api.expansion

Why Karni objects. Expansion is validated against the model so a typo returns a 400 instead of a silently unexpanded response.

Fix. Use the keys the error lists (comma-separated, nested with dots: ?expand=venue,tiers.event). Each segment must be a relation.

E127: The ?expand= path is too deep

API 400 response · from karni.api.expansion

Why Karni objects. Each level of expansion multiplies the work per row, so KARNI_API_MAX_EXPAND_DEPTH caps the depth.

Fix. Request fewer levels, or raise KARNI_API_MAX_EXPAND_DEPTH in settings if the client really needs them.

E128: KARNI_API_ROUTER cannot be imported

system check (error) · from karni.checks.check_viewsets

Why Karni objects. The router factory builds every API route. Without it the API serves nothing.

Fix. Point KARNI_API_ROUTER at an importable zero-argument factory returning a router (default 'karni.api.routers.get_default_router').

E129: List or retrieve queries grow with the number of rows (N+1)

test failure · from karni.testing.performance (pytest --pyargs karni.testing.performance)

Why Karni objects. The scaling check runs list and retrieve with few and many rows. More rows must not mean more queries, or the page slows down as the table grows.

Fix. Let the optimiser see the relation through the serializer, or add select_related / prefetch_related hints (or APIMeta.select/prefetch) for a SerializerMethodField or property. Opt out only with # karni: allow(query-scaling): <reason> above the viewset class.

E130: An opt-out marker has no reason

test failure · from karni.testing (# karni: allow(<rule>) markers)

Why Karni objects. Opting out of a check must be deliberate and reviewable. The reason is what gets reviewed.

Fix. Write the reason after the colon: # karni: allow(<rule>): <why>.

E131: search_fields names a write-only field

system check (error) · from karni.checks.check_viewsets

Why Karni objects. A field in APIMeta.write_only never appears in a response, but ?search= over it answers whether a row contains a value. That makes search a membership oracle on a hidden column.

Fix. Remove the field from search_fields, or take it out of APIMeta.write_only if it may be read.

E132: Throttle(...) is invalid

exception · from karni.api.throttling.Throttle; BaseViewSet.throttle

Why Karni objects. A viewset's throttle declaration names actions of that viewset and gives each a DRF rate, '<number>/<period>' with the period s, sec, second, m, min, minute, h, hour, d or day.

Fix. Write throttle = Throttle(create='10/hour'), naming only actions the viewset has (the standard ones, or a custom @action by its method name).

E133: Karni.dashboard is malformed or names a field the model does not have

system check (error) · from karni.dashboard.dashboard_spec; karni.checks.check_dashboards

Why Karni objects. The dashboard declaration is published in the OpenAPI schema and @karni/ui's <Dashboard> counts rows with the list endpoint's filters. A field name with a typo, a value the field does not have or a count without filters would show a wrong number, so the declaration is refused at boot.

Fix. Write dashboard = True, or a dict with the keys label, order, total, new_days, by, values, counts, recent, columns and date_field, naming fields of the model: e.g. dashboard = {'by': 'status', 'counts': {'Due today': {'due_on': 'today'}}, 'recent': 5}.

E134: The written row is outside the caller's write scope

exception · from karni.api.viewsets.BaseViewSet.check_written_row (perform_create / perform_update)

Why Karni objects. An access rule such as Owned('seller__user') limits the rows a caller may change. A create or an update that leaves the row outside that rule (a listing in someone else's shop, a lesson in another instructor's course) would let the caller write rows that are not theirs, so it is refused with a 403 and nothing is saved.

Fix. Point the row at something of yours (your shop, your course), or give the caller a role the rule admits.

E135: Only some roles may set the owner of a row

exception · from karni.api.viewsets.BaseViewSet.perform_create / perform_update (Access(assign=...))

Why Karni objects. The owner field of a row (the member of a booking) is the caller. Access(assign=...) names who may set it to someone else (staff booking for a member, a manager reassigning a deal). Anyone else who sends another user is refused with a 403.

Fix. Leave the owner field out (it becomes you), or ask someone the assign rule admits.

E136: A row action is declared wrongly

exception · from karni.api.actions (RowAction, row_actions)

Why Karni objects. row_actions maps action names to RowAction(...), whose by= is an access predicate, and the states it names belong to the model's one StateField unless field= names another.

Fix. Write row_actions = {'ship': RowAction(from_='paid', to='shipped', by=Owned(...))}, and name the StateField with field= when the model has two.

W136: A row action has nothing to run yet

system check (warning) · from karni.api.actions.missing_methods; karni.checks.check_viewsets

Why Karni objects. A row action without to= is the viewset's own @action method of that name (pay opens a payment): Karni checks the state and who may, then runs it. Until the method exists no route answers the action. It is a warning so a project built from karni.yaml migrates and runs while the method is being written.

Fix. Write the @action(detail=True, methods=['post']) method of that name in the project's viewset (<app>/viewsets.py), or give the action a to= state.

2xx · Accounts

E201: KARNI_ACCOUNTS_EMAIL_BACKEND is not an accounts email backend

exception · from karni.accounts.emails.get_backend

Why Karni objects. Account emails (verification, password reset) are sent through this backend.

Fix. Point the setting at a subclass of karni.accounts.emails.AccountsEmailBackend, e.g. 'karni.accounts.emails.DjangoEmailBackend'.

E202: No KARNI_ACCOUNTS_LINKS entry for a token purpose

exception · from karni.accounts.emails

Why Karni objects. Emails link to your frontend, so Karni needs the URL template for each purpose (verify_email, reset_password, ...).

Fix. Add the purpose to KARNI_ACCOUNTS_LINKS, e.g. {'reset_password': '{frontend}/reset-password?token={token}'}.

E203: create_user() or create_superuser() was called with invalid arguments

exception · from karni.accounts.managers.UserManager

Why Karni objects. Karni users log in by email, and a superuser must be staff and superuser.

Fix. Pass email= (and password=). For create_superuser(), leave is_staff and is_superuser unset or True.

E204: Unknown one-time token purpose

exception · from karni.accounts.tokens

Why Karni objects. One-time tokens are issued per purpose so a reset token cannot verify an email.

Fix. Use one of the purposes the message lists.

E205: KARNI_ROLES is malformed

exception · from karni.accounts.roles.declared_roles

Why Karni objects. The role declaration is the single source of what each role may do. A malformed entry cannot be reconciled into the role tables.

Fix. Write KARNI_ROLES = {'<slug>': {'name': ..., 'description': ..., 'system': bool, 'grants': {'app_label.model:action': '<scope>'}}}. A pattern may use '' for the model or the action (or '' alone). A scope is 'all', 'own', 'related:<key>', 'custom:<name>' or 'tree:<path>'.

E206: A grant in KARNI_ROLES cannot be resolved

exception · from karni.accounts.roles.sync_roles

Why Karni objects. A pattern that matches no permission, an 'own' scope on a model with no owner field, a 'related' scope on a model without that scope path, or a 'custom' scope nobody registered would silently grant nothing. Karni refuses it instead.

Fix. Fix the key (permissions look like 'events.event:view', and extra actions come from class Karni: actions), declare owner_field / scope_paths in the model's class Karni, or register the custom scope with karni.accounts.roles.register_scope.

E207: user.can() was given an action without a model

exception · from karni.accounts.roles.user_can

Why Karni objects. A permission is a (model, action) pair, so a bare action name cannot be looked up.

Fix. Pass the full key, user.can('shop.order:approve'), or name the model: user.can('approve', obj=order) or user.can('approve', model=Order).

E208: The request lacks the permission @requires names

API 400 response · from karni.accounts.roles.requires

Why Karni objects. A view or service guarded with @requires('app.model:action') was called by a user whose roles hold no grant for it (a 403).

Fix. Grant the permission to one of the user's roles in KARNI_ROLES and run karni sync-roles, or assign the user a role that has it.

E209: Can() was given a bad permission, or one for another model

exception · from karni.api.access.Can

Why Karni objects. Can() names permissions as 'app_label.model:action', and its row filter is built against that model, so a viewset's declaration can only use its own model's permissions.

Fix. Write Can('events.event:approve'). On EventViewSet it must be an events.event permission. To gate on another model's permission, use HasRole(...).

E210: scope_exempt = True without a reason

exception · from karni.api.access.validate_access

Why Karni objects. A viewset or admin that shows every row its gate admits is the one place row scoping is off. Without a reason it looks like an oversight, and karni check lists every exemption by its reason.

Fix. Add scope_exempt_reason = '...' next to scope_exempt = True (e.g. 'public catalogue'), or remove the exemption and let Granted() / the roles' grants scope the rows.

E211: Granted() has no permission for this action or viewset

exception · from karni.api.access.Granted

Why Karni objects. Granted() resolves to the viewset's model and the current action. An unsafe custom @action the model never declared has no permission to check, and a viewset without a model has nothing to resolve against. Evaluating it outside a viewset is the same error.

Fix. Add the action to class Karni: actions = [...] on the model and grant 'app.model:<action>' in KARNI_ROLES, give the action its own @action(access=...), set model = ... on the viewset, or evaluate through action_predicate(view, access).

E212: Karni.field_roles is malformed, names a missing field or an undeclared role

system check (error) · from karni.meta.field_roles; karni.checks.check_field_roles

Why Karni objects. Field-level visibility is declared once on the model as field -> roles. A typo in a field name hides nothing, and a role nobody holds hides the field from everyone, so both are refused at boot.

Fix. Write field_roles = {'phone': {'read': ['staff', 'support'], 'write': ['staff']}} (or 'phone': ['staff'] for read and write) with field names of the model and role slugs declared in KARNI_ROLES.

E213: The permission matrix refused a change

API 400 response · from karni.accounts.matrix.apply_changes

Why Karni objects. A guard rail stopped the request and nothing was written: a system role's declared grant is locked, the operator does not hold the permission (or holds it at a narrower scope than the one granted), the change would remove the operator's own last permission to change permissions, or the role, permission or scope is unknown.

Fix. Change KARNI_ROLES for a system role's grants, ask someone who holds the permission at that scope, keep one of your roles able to change permissions, or check the role slug, the 'app.model:action' key and the scope value against GET permissions/matrix/.

E214: A role's scope names a path the model does not have

system check (error) · from karni.checks.check_role_scope_paths

Why Karni objects. A grant's scope becomes a database filter on every request: own follows Karni.owner_field, related:<key> follows Karni.scope_paths[key], and a custom:<name> scope builds its own. A path the model does not have would answer 500 to every user holding the grant. This typically happens after a new model joins a wildcard grant written for its siblings.

Fix. Give the model the path the scope expects (class Karni: owner_field = 'workspace__members', or the scope path), teach the custom scope the new model, or narrow the grant's pattern so it does not cover the model.

E215: The ID token is not valid

API 400 response · from karni.accounts.social_token.verify_id_token (POST <auth>/social/<provider>/)

Why Karni objects. Karni verifies an ID token offline: a JWT signed with one of the provider's published keys, with the algorithm the provider uses, carrying exp, iat, iss, aud and sub. A token that is malformed, signed with another key or algorithm, missing one of those claims, or issued in the future (iat or nbf past the leeway) proves nothing, so the answer is a 401.

Fix. Send the ID token itself (not the access token, and not the authorization code) exactly as the provider's SDK returned it, and get a fresh one. A token issued in the future means the server's clock is off: fix the clock, or raise KARNI_SOCIAL_TOKEN_LEEWAY.

E216: The ID token was issued for another application

API 400 response · from karni.accounts.social_token.verify_id_token

Why Karni objects. A token's aud claim names the client id it was issued to. Accepting a token issued to another application would let any app that signs its users in with the same provider sign them in here too, so aud must be one of the configured client ids (401).

Fix. Add the client id the app uses to KARNI_SOCIAL_TOKEN_PROVIDERS[<provider>]['client_ids']: the web client id, and each iOS and Android client id (for Apple, the service id and the bundle id). An empty list means the provider is not configured: signing in with it answers 503 with this code, and every other command and request still works. The settings block karni build writes reads the ids from KARNI_SOCIAL_<PROVIDER>_CLIENT_IDS.

E217: The ID token comes from another issuer or tenant

API 400 response · from karni.accounts.social_token.verify_id_token

Why Karni objects. Each provider has its own issuer: accounts.google.com, https://appleid.apple.com, or for Microsoft https://login.microsoftonline.com/<tenant id>/v2.0 with the token's own tid. A Microsoft token from a tenant the 'tenants' setting does not allow is refused the same way (401).

Fix. Check that the token comes from the provider of the URL it was posted to. For Microsoft, request a v2.0 token and list its tenant (or 'common', 'organizations' or 'consumers') in KARNI_SOCIAL_TOKEN_PROVIDERS['microsoft']['tenants'].

E218: The ID token has expired

API 400 response · from karni.accounts.social_token.verify_id_token

Why Karni objects. ID tokens live minutes to an hour. Karni accepts one up to its exp claim plus KARNI_SOCIAL_TOKEN_LEEWAY seconds (401 after that).

Fix. Get a fresh token from the provider's SDK right before posting it. Do not store ID tokens for later.

E219: The ID token's signing key is unknown

API 400 response · from karni.accounts.social_token.signing_key

Why Karni objects. Karni looks the token's kid up in the provider's key set (JWKS), cached for KARNI_SOCIAL_TOKEN_JWKS_TTL seconds. An unknown kid fetches the key set again, at most once a minute per provider, so a rotated key works within a minute. A kid that is still missing answers 401. A key set that cannot be fetched answers 503.

Fix. Send a token the provider issued recently. A 503 means the server cannot reach the provider's JWKS URL: check its outbound network, or the fetcher named in KARNI_SOCIAL_TOKEN_JWKS_FETCHER.

E220: The ID token's nonce does not match

API 400 response · from karni.accounts.social_token.verify_id_token

Why Karni objects. A nonce binds the token to one sign-in attempt, so a stolen token cannot be replayed. When the request sends a nonce, the token's nonce claim must equal it, or its SHA-256 hex digest (Apple's convention: the app passes the hash to Apple and the raw value to Karni). A provider with 'require_nonce' refuses a request without one (401).

Fix. Post the nonce the app generated for this sign-in, the raw value. Generate a new one for every attempt.

E221: The ID token carries no email address

API 400 response · from karni.accounts.social_token.sign_in

Why Karni objects. A token whose identity is not linked yet is matched to an account by its email. Without an email claim (for Microsoft, email or an email-shaped preferred_username) there is nothing to match or create (400).

Fix. Request the email scope. Apple sends the email only on the first sign-in of a user, so that first answer must reach Karni.

E222: The provider did not verify the email address

API 400 response · from karni.accounts.social_token.sign_in

Why Karni objects. Karni creates an account from a token, or links a token to the account with the same email, only when the provider says it verified the address. Otherwise anyone could put someone else's address in a token and take over their account. Microsoft tokens count as verified only with the xms_edov claim true or a tenant listed in 'trusted_tenants' (400). An identity already linked signs in without this check.

Fix. For Microsoft, add the xms_edov optional claim to the app registration, or list your organisation's tenant id in KARNI_SOCIAL_TOKEN_PROVIDERS['microsoft']['trusted_tenants']. Otherwise the user signs in with a password, or with a provider that verified the address.

E223: Sign-up with an ID token is closed

API 400 response · from karni.accounts.social_token.sign_in

Why Karni objects. KARNI_SOCIAL_TOKEN_SIGNUP is 'existing' (the default while KARNI_ACCOUNTS_REGISTRATION is False): only an identity already linked, or an account with the token's email, may sign in. Nobody else gets an account (400).

Fix. Create the account first (in the admin, or let staff invite the user), then sign in with the token. To let anyone in, set KARNI_SOCIAL_TOKEN_SIGNUP = 'open', or 'approval' to create accounts an administrator activates.

E224: The account awaits an administrator's approval

API 400 response · from karni.accounts.social_token.sign_in; karni.accounts.otp.verify_code

Why Karni objects. With KARNI_SOCIAL_TOKEN_SIGNUP = 'approval', a token without an account creates an inactive one. The answer is a 202 with this code and no credentials, again on each sign-in until an administrator activates the account. With KARNI_EMAIL_OTP_SIGNUP = 'approval', the code that creates the account answers the same 202. A later code for the inactive account answers E226.

Fix. An administrator ticks 'Active' on the user's page in the admin. The next sign-in then succeeds.

E225: This sign-in provider is not configured

API 400 response · from karni.accounts.api.views.SocialTokenLoginView

Why Karni objects. Each provider named in KARNI_SOCIAL_TOKEN_PROVIDERS gets its own social/<provider>/ route. A provider the setting does not name answers 404.

Fix. Add the provider with its client ids to KARNI_SOCIAL_TOKEN_PROVIDERS, or post to the route of a configured one.

E226: The account is inactive

API 400 response · from karni.accounts.social_token.sign_in; karni.accounts.otp.verify_code

Why Karni objects. An inactive user never signs in, by password, by token or by a code sent by email (401). Sign-in by code says so only after a right code, so the answer tells nothing to someone who does not read that mailbox.

Fix. An administrator activates the account in the admin, if it should sign in.

E227: An account with this email exists and is not linked

API 400 response · from karni.accounts.social_token.sign_in

Why Karni objects. KARNI_SOCIAL_TOKEN_LINK_VERIFIED is False, so a token is never linked to an existing account that has a password, even when the provider verified the email (400).

Fix. Sign in with the password. Linking a provider from a signed-in session is not built yet. To link on a verified email, set KARNI_SOCIAL_TOKEN_LINK_VERIFIED = True (the default).

E235: The sign-in code is wrong or has expired

API 400 response · from karni.accounts.otp.verify_code (POST <auth>/otp/verify/)

Why Karni objects. One answer covers every failure of a code, so it tells nobody whether an address has an account: a wrong code, one past KARNI_EMAIL_OTP_TTL, one already used, one replaced by a newer code, one locked after KARNI_EMAIL_OTP_MAX_ATTEMPTS wrong guesses, an address no code was sent to, and an address that may not sign up (KARNI_EMAIL_OTP_SIGNUP = 'existing'). The precise reason is only in the accounts.otp.refused log event (401).

Fix. Ask for a new code with POST otp/send/ and type the newest one. Only the latest code of an address works. Check the reason in the log when one user keeps failing.

E236: Sign-in with a code is turned off

API 400 response · from karni.accounts.api.views.OtpSendView; karni.accounts.api.views.OtpVerifyView

Why Karni objects. otp/send/ and otp/verify/ are mounted only while KARNI_EMAIL_OTP is True. A URLconf built while it was True answers 404 with this code once the setting is False.

Fix. Set KARNI_EMAIL_OTP = True (or KARNI_EMAIL_OTP=True in the environment) to offer sign-in with a code, or sign in with login/.

E245: The signed-in user has not accepted the current terms

API 400 response · from karni.accounts.terms.TermsGateMiddleware

Why Karni objects. KARNI_TERMS requires every signed-in user to accept its current version before using the API. The gate answers 403 with this code, the version and the terms url to a signed-in user who has not accepted that version, on every request under KARNI_TERMS['paths'] (default ['/api/']) outside the auth mount and KARNI_TERMS['exempt']. Staff and superusers are gated like everyone. A new version makes everyone accept again.

Fix. Show the terms at the url in the answer, then POST <auth mount>/terms/accept/ with {"version": "<the version in the answer>"}. @karni/ui's TermsGate does both. To keep a path open before acceptance, add its prefix to KARNI_TERMS['exempt'].

E246: The accepted terms version is not the current one

API 400 response · from karni.accounts.terms.accept (POST <auth>/terms/accept/)

Why Karni objects. terms/accept/ records acceptance of KARNI_TERMS['version'] only. A client that sends another version showed the user other terms (an old copy, or the version changed after the page loaded), so nothing is recorded (400). The answer carries the current version and url.

Fix. Show the terms at the url in the answer and send the version in the answer. GET terms/ returns the current version too.

E247: A terms acceptance is a permanent record

exception · from karni.accounts.models.TermsAcceptance

Why Karni objects. Each TermsAcceptance row records that a user accepted a version of the terms, when, from which IP and with which client. The table is append-only: saving an existing row, deleting one (soft or hard) and update() or delete() on a queryset of them would rewrite that record, so each one raises.

Fix. Record a new acceptance with karni.accounts.terms.accept(), or POST terms/accept/. To make everyone accept again, change KARNI_TERMS['version']. A user's rows go only with the user: user.hard_delete() deletes them.

E248: The terms gate is not in MIDDLEWARE, or runs before authentication

system check (error) · from karni.checks.check_terms_middleware

Why Karni objects. KARNI_TERMS requires acceptance, but karni.accounts.terms.TermsGateMiddleware (or a subclass) is missing from MIDDLEWARE, so nothing is gated, or it comes before django.contrib.auth's AuthenticationMiddleware, so it cannot see the session user. karni_settings() lists it, so this happens when MIDDLEWARE is replaced after the call.

Fix. Add 'karni.accounts.terms.TermsGateMiddleware' to MIDDLEWARE after 'django.contrib.auth.middleware.AuthenticationMiddleware', or extend MIDDLEWARE instead of replacing it.

E249: Terms acceptance is turned off

API 400 response · from karni.accounts.api.views.TermsView; karni.accounts.api.views.TermsAcceptView

Why Karni objects. terms/ and terms/accept/ are mounted only while KARNI_TERMS is set. A URLconf built while it was set answers 404 with this code once it is unset.

Fix. Set KARNI_TERMS = {"version": "<version>", "url": "<where the terms are>"} to ask users to accept terms, or remove the client's call.

E250: A merge of two people who both have an account

exception · from karni.people.merge (MergeRefused, HTTP 409)

Why Karni objects. A person is linked to at most one account. Merging two people who each have one would have to merge the accounts too: their passwords, roles and sign-ins, which only a person can decide.

Fix. Merge the accounts first, by hand: deactivate or delete one account (or unlink it from its person), then merge the people.

E251: A merge clash that only a merge hook can resolve

exception · from karni.people.merge (MergeRefused, HTTP 409), karni.people.merge_plan

Why Karni objects. Both records have a one-to-one row of the same model (two CRM profiles), or moving the dropped record's rows breaks a unique rule of their model (two bookings for one slot). Karni cannot know which row wins, so it refuses instead of guessing.

Fix. Register a merge hook for the model named in the message, in its app's people.py: @people.merge_hook(Model) def merge(keep, drop): fold the dropped record's row into the kept one and delete it. Or skip the model with KARNI_PEOPLE_MERGE_SKIP.

E252: A merge or an erase of records it does not take

exception · from karni.people.merge, karni.people.merge_plan, karni.people.erase

Why Karni objects. A merge takes two live records of the same kind (two people or two organisations) that are not the same row, and an erase takes a person. A deleted or already merged record has nothing left to merge.

Fix. Pass two different live people (or organisations). To merge into a record that was merged already, merge into the record it points at (merged_into).

E253: people.resolve() cannot run

exception · from karni.people.resolve, karni.people.get_resolver (KARNI_PEOPLE_RESOLVER)

Why Karni objects. One email is one person, so a person is found or created by an account or an email, never by a name alone. The resolver itself comes from KARNI_PEOPLE_RESOLVER.

Fix. Pass user= (a signed-in user) or email=. Point KARNI_PEOPLE_RESOLVER at karni.people.services.Resolver or a subclass of it.

E254: Another person has this email

API 400 response · from karni.people.models.Person.clean (the API and the admin)

Why Karni objects. Email is the identity of a person: one live person per email, kept in lower case, so every part finds the same person for the same address.

Fix. Open the person who has the email instead, or merge the two people (people.merge, POST /api/people/<id>/merge/).

E255: The email of a person with an account changes through the account

API 400 response · from karni.people.models.Person.clean (the API and the admin)

Why Karni objects. A person linked to an account has the account's verified email. Changing it on the person alone would let anyone with write access point the person at an address nobody verified.

Fix. Change the email through the account (the email change flow verifies the new address), or unlink the account first.

E256: A value the people tables do not take

API 400 response · from karni.people.models (clean of Person, Address, Membership)

Why Karni objects. A person's time zone is an IANA name and its language a language tag, an address belongs to exactly one owner (a person or an organisation), and a person is a member of an organisation once.

Fix. Use a time zone such as Europe/Paris and a language such as en or pt-BR; set exactly one of person and organisation on an address; change the existing membership instead of adding a second one.

E257: A person fact, merge hook, erase hook or duplicate rule cannot be registered

exception · from karni.people.registry (register_fact, merge_hook, erase_hook, register_duplicate_rule, annotate_facts, duplicates)

Why Karni objects. Facts become annotations, filters and orderings on Person, so a fact's name must be an identifier that is not a Person field, and every contribution has one owner: a second registration under a taken name would silently replace the first.

Fix. Name the fact after what it measures (orders, total_spent), give a second contribution its own name, or pass replace=True to swap one on purpose. Ask only for registered facts and rules (people.facts(), people.duplicate_rules()).

E258: An account cannot be linked to this person

exception · from karni.people.link_account

Why Karni objects. An account is linked to a person only after its email is verified, only to the person with that email, and a person has one account. Otherwise anyone could take over a guest's orders by signing up with their address.

Fix. Verify the account's email first (the verification link, a sign-in code or a provider that verified it), link it to the person with the same email, and merge the accounts by hand when the person has another one.

E259: A people event that is not declared

exception · from karni.people.events.publish, karni.people.events.signal_for

Why Karni objects. The people contract's events are declared with their fields (karni.people.events.EVENTS), so every subscriber gets the same payload.

Fix. Publish one of the declared events (people.person.created, linked, merged, erased, people.organisation.created, merged) with exactly its declared fields.

E260: A database alias is not configured

exception · from karni_schema (--database)

Why Karni objects. A command was given a database alias that DATABASES does not define, so there is no connection to read.

Fix. Pass an alias from settings.DATABASES ('default' unless the project declares more), or add the database to DATABASES.

E270: An external model is managed by Django

system check (error) · from karni.db.checks.check_database_options

Why Karni objects. class Karni: external = True says another system owns the table or view, so Karni must never create, change or drop it. Django still migrates a model unless Meta.managed = False, so migrate would try to create or alter that table. The two declarations go together.

Fix. Add managed = False to the model's class Meta, or remove external = True if Django should own the table.

E271: Karni.database names a database that is not in DATABASES

system check (error) · from karni.db.checks.check_database_options

Why Karni objects. class Karni: database = '<alias>' sends the model's reads, writes and migrations to that alias of the DATABASES setting. An alias Django does not know fails on the first query.

Fix. Add the alias to DATABASES (for example DATABASES['warehouse'] = env.db_url('WAREHOUSE_DATABASE_URL')), or fix the name in class Karni.

E272: The table or view of an external model does not exist

system check (error) · from karni.db.checks.check_external_tables (karni check)

Why Karni objects. An external model reads a table or view another system owns, and Karni never creates it. karni check connected to the model's database and found no table or view with the model's Meta.db_table, so every query on the model would fail.

Fix. Create the table or view in that database (a SQL view the project owns can come from a RunSQL migration), or fix Meta.db_table. A PostgreSQL table in another schema is written db_table = 'schema"."table'. Where the table cannot exist (a CI database), add 'karni.E272' to SILENCED_SYSTEM_CHECKS in that environment's settings.

E273: An external model has a column its table or view lacks

system check (error) · from karni.db.checks.check_external_tables (karni check)

Why Karni objects. Every concrete field of an external model is a column Karni selects. A field whose column (its name, or db_column) is missing from the table or view makes every query on the model fail.

Fix. Fix the field's name or db_column to match the column, remove the field, or regenerate the model from the table with karni make model <Name> --external --table <table> and keep what you need.

E274: An external model's field type does not match its column

system check (error) · from karni.db.checks.check_external_tables (karni check)

Why Karni objects. The database reports a column type that cannot hold the field's values, for example a DateTimeField over a text column or an IntegerField over a date. Karni compares broad kinds only (numbers, text, dates, times, booleans, UUIDs, JSON, binary), and skips columns whose type the database does not report, so a reported mismatch is a real one.

Fix. Change the field to the column's type (karni make model <Name> --external --table <table> --dry-run shows the type Django infers), or cast the column in the view.

E275: class Karni: external, writable or database has a value of the wrong type

system check (error) · from karni.db.checks.check_database_options

Why Karni objects. external and writable are True or False, and database is the name of a DATABASES alias. Another value would be read in a way the code does not say.

Fix. Write external = True, writable = True or database = '<alias>' (a non-empty string).

E276: A relation joins models on different databases

system check (error) · from karni.db.checks.check_database_options

Why Karni objects. A foreign key, one-to-one or many-to-many field needs both tables in one database: Django joins them in SQL, and Karni's router refuses to relate rows across databases. A model on another database that inherits BaseModel has this problem too, because AuditedModel's created_by and updated_by point at the user table.

Fix. Keep related models on the same database (the same Karni.database), or store the other row's key in a plain field. For a model Karni manages on another database, compose UUIDModel, TimestampedModel and SoftDeleteModel instead of BaseModel.

E280: Karni.label_field names a field the model does not have

system check (error) · from karni.meta.label_field; karni.checks.check_aggregations (karni check)

Why Karni objects. Karni.label_field is the field that shows a row to people where only its key would show otherwise: the groups of an aggregate on a relation (chart legends and axes, comparison headers). A name the model does not have can show nothing.

Fix. Name a field of the model: class Karni: label_field = 'name'. Leave it out to use the first text field named name, title or label, else Karni.natural_key.

E290: Karni.explicit_actions names an action the model does not have

system check (error) · from karni.meta.explicit_actions; karni.checks.check_explicit_actions (karni check)

Why Karni objects. Karni.explicit_actions lists the actions a wildcard grant never reaches: only a grant that writes the action out gives it. A name that is not one of the model's actions protects nothing, so a typo would leave the real action open to every wildcard role.

Fix. List actions of the model: the standard view, add, change, delete, or a name in Karni.actions (class Karni: actions = ['refund']; explicit_actions = ['refund']). Then grant the action by name: KARNI_ROLES = {'finance': {'grants': {'shop.order:refund': 'all'}}}.

E291: Karni.natural_key or import_key is not one field of the model

system check (error) · from karni.meta.natural_key; karni.meta.import_options; karni.checks.check_key_fields (karni check)

Why Karni objects. natural_key names the one field that names a row to people: an import's relation cell carries its value and an export writes it. import_key names the column an import matches rows on. Each carries one value per cell, so a list of fields has no form in a file, and a name the model does not have would fail every request that reads the model.

Fix. Write one field name as a string: class Karni: natural_key = 'name' (not ['name']). For a row that only several fields name together, add one unique field that names it (a SlugField built from them), or leave natural_key out to use the primary key.

3xx · Admin

E301: KARNI_ADMIN_BASE is not a ModelAdmin class

exception · from karni.admin.base

Why Karni objects. Every auto-registered admin is built on this base class.

Fix. Point KARNI_ADMIN_BASE at an importable django.contrib.admin.ModelAdmin subclass (default 'unfold.admin.ModelAdmin').

E302: AdminMeta.inline_on is invalid

exception · from karni.admin.inlines

Why Karni objects. inline_on names the foreign key under whose parent the model is shown inline.

Fix. Name a ForeignKey field of the model: class AdminMeta: inline_on = 'event'.

E303: KARNI_ADMIN_LOGO is not a logo declaration

exception · from karni.conf.admin_logo.unfold_logo_entries

Why Karni objects. The admin logo is wired into UNFOLD from this one setting, so it must name static files unfold can serve.

Fix. Set KARNI_ADMIN_LOGO = 'karni' for Karni's mark, or {'light': '<static path>', 'dark': ..., 'icon': ...} with at least 'light'. Leave it unset for a text header.

E304: karni_makemigrations --renames is not a rename list

exception · from karni.management.commands.karni_makemigrations

Why Karni objects. karni build passes the renames of the plan as JSON: {"models": [[app, old, new]], "fields": [[app, model, old, new]]}. Anything else cannot be written as a migration.

Fix. Pass a JSON object with models and fields lists, or run karni build, which writes it.

E305: An app has more than one latest migration, so the renames have no place

exception · from karni.management.commands.karni_makemigrations.write_renames

Why Karni objects. A rename migration follows the app's latest migration. Two migrations that both claim to be latest (two branches) leave no single one to follow.

Fix. Run manage.py makemigrations --merge for the app, then karni build again.

E310: A module's manifest does not match the module

test failure · from karni.testing.assert_module_manifest

Why Karni objects. karni.module.toml is what karni modules, karni add, karni remove and the app spec read about a module. assert_module_manifest checks it parses, that the karni.modules entry point names the package, that its settings are the DEFAULTS fragment's, and that its models are the app's. Each listed line is one mismatch.

Fix. Fix the manifest or the module as the line says: list every KARNI_<NAME>* setting of conf.DEFAULTS under [provides.settings] with its type, list the app's models under provides.models, and add [project.entry-points."karni.modules"] <name> = "karni<name>" to pyproject.toml, then reinstall the module. docs/modules.md lists every key.

E320: A preferences lock or default names nothing, or a value its field refuses

system check (error) · from karni.preferences.checks.check_preferences

Why Karni objects. KARNI_PREFERENCES_LOCKED and KARNI_PREFERENCES_DEFAULTS map a group (details, a section's key, connections, emails) to names and values. A name nobody declared is most likely a typo, and a value its field refuses would be refused on the Settings page too.

Fix. Write {'details': {'name': ...}, '<section>': {'<field>': ...}, 'connections': {'<name>': True}, 'emails': {'<kind>': False}} with the names the message lists, and values each field takes.

E321: A settings section cannot be registered

exception · from karni.preferences.section

Why Karni objects. A section is a subclass of karni.preferences.Section registered under its part's prefix, once. Every field needs a valid default, so a project that never opens Settings still works. details, connections and emails are kept for the Settings page.

Fix. Subclass preferences.Section, give every field a default its constraints accept, and register it as @preferences.section('<prefix>') once.

E322: A connection or an email kind cannot be declared

exception · from karni.preferences.connection; karni.preferences.email

Why Karni objects. A connection is named '<prefix>.<what>', needs at least one contract or module, has a default of True or False and says in one sentence what it does. An email kind is named '<prefix>.<message>'. Each name is declared once.

Fix. Correct the name, needs=, default= or describe= the message names, or pass replace=True to replace a declaration on purpose.

E323: A preferences change has a field or a value it cannot take

API 400 response · from karni.preferences.save_details; karni.preferences.save_section; PATCH /api/preferences/

Why Karni objects. Details and sections take their declared fields only, and each value must pass its field's checks (a time zone name, an ISO currency code, a number in range, one of the choices).

Fix. Send the fields the Settings page lists, with values the errors per field describe. null puts a section's field back to its default.

E324: A preferences value is fixed by the deployment

API 400 response · from karni.preferences.save_details; karni.preferences.save_section; karni.preferences.switch

Why Karni objects. KARNI_PREFERENCES_LOCKED fixes this value for the deployment. Every read answers the lock, so a change would not hold. The API answers 409.

Fix. Change KARNI_PREFERENCES_LOCKED in the deployment's settings, or leave the value as it is.

E325: No such section, connection or email kind

exception · from karni.preferences.get; karni.preferences.switch; /api/preferences/

Why Karni objects. The name is not registered: the part that declares it is not installed, its preferences.py or connections.py was not imported, or the name is misspelt. preferences.value() never raises it: it returns the default it is given.

Fix. Use a name GET /api/preferences/ lists, install the part, or read the value with preferences.value('<section>.<field>', default).

E340: A tree node's new parent is the node itself or a node below it

exception · from karni.models.TreeModel.check_parent (save, clean, move_to); the API answers 400

Why Karni objects. A parent below the node would make the branch its own ancestor: a cycle. Every walk stays safe on such data, but the nodes on the cycle drop out of the tree, so Karni refuses the write before any SQL.

Fix. Choose a parent outside the node's branch (or None for a root). To swap two nodes, move the lower one out of the branch first. In the API, POST <id>/move/ with another parent.

E341: A tree node with live children cannot be deleted alone

exception · from karni.models.TreeModel.delete; the API answers 409

Why Karni objects. A soft-deleted node hides its whole branch. Deleting a node that still has live children would hide them too, without anyone deciding that, so delete() refuses and the answer counts the children.

Fix. Move the children to another parent first, or delete the whole branch on purpose: node.delete_branch(), or DELETE <id>/?branch=true in the API (write access to every node of the branch).

E342: A tree endpoint got a parameter it cannot use

API 400 response · from karni.api.tree (tree/, move/, ?parent=, ?descendants_of=, ?branch=)

Why Karni objects. The tree endpoints take keys of the model (?root=, ?parent=, ?descendants_of=, the parent of move/), a whole number of levels (?depth=, from 1 to the viewset's tree_max_depth) and true or false (?branch=). A key must name a node the requester may read.

Fix. Send a key of the model (or null for ?parent= and move/'s parent), a depth within the limit the message names, and branch=true or branch=false.

E343: A tree method got an argument it cannot use

exception · from karni.managers.TreeQuerySet (walk, descendants, ancestors, subtree_ids); karni.models.TreeModel.move_to

Why Karni objects. A walk starts from rows of the model, their keys or a queryset of the model. A row of another model, an unsaved row or a malformed key names no node. move_to() takes a position only on an OrderedTreeModel, as a whole number from 0.

Fix. Pass saved rows of the model or their keys. Drop the position on a TreeModel, or inherit OrderedTreeModel to order siblings.

E344: A tree model's default manager has no tree walks

system check (error) · from karni.checks.check_tree_models

Why Karni objects. TreeModel's manager (karni.managers.TreeManager) carries roots(), children(), ancestors(), descendants() and subtree_ids(), and the tree endpoints use them. A base listed before TreeModel (class Region(BaseModel, TreeModel)) supplies its own objects first, so the walks are missing.

Fix. List TreeModel first: class Region(TreeModel, BaseModel). A custom manager must be built on karni.managers.TreeQuerySet, the way TreeManager is.

E345: A tree model's parent is not a foreign key to the model itself

system check (error) · from karni.checks.check_tree_models

Why Karni objects. Every walk joins a node to its parent through the parent column, so parent must stay a nullable ForeignKey to the same model.

Fix. Remove the redeclared parent field, or declare it as models.ForeignKey('self', null=True, blank=True, on_delete=models.PROTECT, related_name='children').

E360: A user grant's permission pattern matches no permission

exception · from karni.accounts.grants.check

Why Karni objects. A user grant names its permission as a KARNI_ROLES grant does: 'app_label.model:action', with '' for either part, or '' alone. A pattern that is malformed or matches no permission of the project would grant nothing, so it is refused when the grant is written (the API, the admin, karni.accounts.grants.grant or full_clean()).

Fix. Write the key as karni context or GET permissions/matrix/ lists it (e.g. 'shop.order:view'), and declare a model's extra actions in class Karni: actions = [...] before granting them.

E361: A user grant's scope does not fit the permissions it covers

exception · from karni.accounts.grants.check

Why Karni objects. The scope is one a role grant takes: 'all', 'own', 'related:<key>', 'custom:<name>' or 'tree:<path>'. 'own' needs the model's owner field, 'related:<key>' its Karni.scope_paths[key], 'custom:<name>' a scope registered with register_scope() and 'tree:<path>' a path from the model to a tree model. An explicit key whose model lacks it is refused, and a wildcard pattern must keep at least one model that has it.

Fix. Pick a scope from the model's options in GET permissions/matrix/, declare the owner field or scope path in class Karni, or register the custom scope at startup.

E362: A user grant's targets are invalid

exception · from karni.accounts.grants.check

Why Karni objects. targets lists the row ids a scope that points at rows reaches: a 'related:<key>' grant with targets reaches the rows whose Karni.scope_paths[key] is one of them, and a 'tree:<path>' grant the rows under those nodes of the tree. Targets are a list of ids (text, integers or UUIDs), only for such a scope, and each must be a value the scope path's field takes.

Fix. Pass a list of ids of the related model, e.g. targets=[3, 7] for an integer key, drop targets for an 'all', 'own' or 'custom:' grant, or grant 'related:<key>' instead.

E363: The operator may not give this user grant

API 400 response · from karni.accounts.grants.refusals

Why Karni objects. Nobody grants what they do not hold, as in the permission matrix: the operator must hold every permission the pattern reaches, at scope 'all' or at the same scope, and for a grant with targets their own targets under that scope must include each one. Nothing was written. Superusers and code that passes operator=None are not checked.

Fix. Ask someone who holds the permission at that scope (or 'all') to give the grant, narrow the pattern, the scope or the targets to what you hold, or grant it from code with operator=None.

E364: Per-user grants are turned off

API 400 response · from karni.accounts.api.grants

Why Karni objects. permissions/grants/ and its routes are mounted only while KARNI_USER_GRANTS is True. A URLconf built while it was True answers 404 with this code once it is False. While it is False, user grants are not read and grant nothing.

Fix. Set KARNI_USER_GRANTS = True (or features: user_grants: true in karni.yaml, then karni build) to use per-user grants.

E365: karni.accounts.grants.change() was given a field it does not set

exception · from karni.accounts.grants.change

Why Karni objects. change() sets a grant's permission, scope, targets, expires_at and reason. The user a grant belongs to, granted_by and the timestamps are not changed this way: a grant for another user is a new grant, and granted_by follows the operator.

Fix. Pass only permission, scope, targets, expires_at or reason. To move access to another user, revoke() this grant and grant() a new one.

E380: An aggregation declaration is not valid

system check (error) · from karni.aggregation.Aggregation (karni.checks.check_aggregations)

Why Karni objects. class Karni: aggregate on a model, or aggregation on a viewset, says what GET <resource>/aggregate/ may group by and sum. Each name must be a field, a relation path or a declared expression of the model, a bucket (:year, :quarter, :month) needs a date field, and the metrics are count, sum, avg, min, max and distinct_count.

Fix. Fix the name the message quotes: {'group_by': ['category', 'launched_on:year'], 'values': ['price'], 'metrics': ['count', 'sum'], 'expressions': {'revenue': TextNumber('revenue_text')}}. Every key but group_by is optional.

E381: The resource declares no aggregation

API 400 response · from karni.api.viewsets.BaseViewSet.aggregate

Why Karni objects. Nothing is aggregatable unless declared, so GET <resource>/aggregate/ answers 404 for a model without class Karni: aggregate (and a viewset without aggregation).

Fix. Declare what may be grouped and summed on the model: class Karni: aggregate = {'group_by': ['region'], 'values': ['price']}.

E382: group_by, stack or series names something not declared

API 400 response · from karni.aggregation.parse_query

Why Karni objects. A request may group only by the fields, relation paths and expressions the declaration lists, and never by a field hidden from the requester (Karni.field_roles, APIMeta.write_only). group_by is required.

Fix. Use one of the values the message lists (the OpenAPI document lists them too, in x-karni-aggregate), or add the field to the declaration's group_by.

E383: The metric is not allowed

API 400 response · from karni.aggregation.parse_query

Why Karni objects. The declaration's metrics list what may be computed: count, sum, avg, min, max, distinct_count, or fewer.

Fix. Send one of the metrics the message lists, or add it to the declaration's metrics.

E384: The value is missing, not declared, or not a number

API 400 response · from karni.aggregation.parse_query

Why Karni objects. Every metric but count reads a value, which must be in the declaration's values and visible to the requester. sum, avg, min and max need a number field or a numeric expression.

Fix. Send value=<one of the declared values>. For a number stored as text, declare an expression: 'expressions': {'revenue': TextNumber('revenue_text')}.

E385: The date bucket does not fit

API 400 response · from karni.aggregation.parse_query

Why Karni objects. A bucket (:year, :quarter, :month) groups a date or datetime field. Another bucket, or a bucket on another kind of field, cannot be computed.

Fix. Send group_by=<date field>:year, :quarter or :month, or group by the field without a bucket.

E386: An aggregate parameter is not valid

API 400 response · from karni.aggregation.parse_query

Why Karni objects. top must be a whole number from 1 to KARNI_AGGREGATE_MAX_GROUPS, only one of stack and series names the second dimension, and it must differ from group_by.

Fix. Fix the parameter the message names.

E387: The aggregate makes too many groups

API 400 response · from karni.aggregation.run_aggregate

Why Karni objects. A response holds at most KARNI_AGGREGATE_MAX_GROUPS groups (default 1000), so grouping by a field with a value per row cannot fill a chart or the server's memory.

Fix. Send top=<n> to keep the largest groups and put the rest in Other, narrow the rows with filters, group by a coarser bucket, or raise KARNI_AGGREGATE_MAX_GROUPS.

4xx · Events, listeners, schedules and Celery

E401: A queued listener is not a module-level function

exception · from karni.events.queued

Why Karni objects. A queued listener runs on a Celery worker, which finds it by its dotted name. Nested functions and lambdas have none.

Fix. Define the listener at the top level of <app>/listeners.py, or queue an existing task with queued('app.tasks.task_name').

E402: A listener registration is invalid

exception · from karni.events

Why Karni objects. Listeners connect to model events (on_created(Model), ...) and must be callables.

Fix. Decorate a function, and pass a model class or an 'app_label.ModelName' string: @on_created(Event) or @on_created('events.Event').

E403: A Celery task cannot be found

exception · from karni.celery.resolve_task

Why Karni objects. Tasks are found by dotted name, and Celery autodiscovers only @shared_task functions in installed apps' tasks.py.

Fix. Check the dotted name, and that the function is decorated with @shared_task in an installed app's tasks.py.

E404: A schedule declaration is invalid

exception · from karni.schedule (every, cron)

Why Karni objects. Schedules are stored by django-celery-beat: the task must be a task or its dotted name, and name/args/kwargs/options must be plain JSON-serializable values.

Fix. Pass a @shared_task or 'app.tasks.task_name', a non-empty name, args as a list, kwargs and options as dicts of plain values (ids, not objects).

E405: A schedule's interval or cron expression is invalid

exception · from karni.schedule (every, cron)

Why Karni objects. Intervals are whole positive seconds, and cron expressions have five fields.

Fix. Use every('15m') / every(minutes=15) (s, m, h, d units), or cron('0 3 * * *') ('minute hour day-of-month month day-of-week').

E406: Two schedules share a name

system check (error) · from karni.schedule; karni.checks.check_schedules

Why Karni objects. Schedule names become django-celery-beat PeriodicTask names, so they must be unique across the project.

Fix. Pass a distinct name=... to one of the two declarations the message names.

E407: No schedule has that name

exception · from karni.schedule.run_now; karni schedule run

Why Karni objects. Schedules are looked up by name.

Fix. List them with karni schedule list and use one of the names shown.

E408: A scheduled task failed when run by hand

exception · from karni_schedules management command; karni schedule run

Why Karni objects. karni schedule run executes the task in-process so failures show immediately.

Fix. Read the task's own error in the message and fix the task. Then re-run it with karni schedule run <name>.

E410: A cached viewset reads a model Karni sees no write to

system check (error) · from karni.checks.check_api_cache

Why Karni objects. With KARNI_API_CACHE on, a cached response is invalidated when a model it reads is written. An external or unmanaged model, or one on another database, is written by another system, so no signal reaches Karni and the response would stay stale for the whole KARNI_API_CACHE_TTL.

Fix. Bound the staleness with cache = Cache(ttl=60) on the viewset (any explicit ttl), or opt it out with cache = Uncached(reason='reads the warehouse tables'). After a write you can see, call karni.api.caching.invalidate(Model).

E411: KARNI_API_CACHE_FLUSH is not a time of day

exception · from karni.conf.validation; karni.api.caching.parse_flush

Why Karni objects. The scheduled flush of the response cache runs once a day at the time this setting names, in its timezone or Celery's.

Fix. Write 'HH:MM' (24-hour), optionally followed by an IANA timezone: '03:30' or '03:30 Europe/Paris'. Leave it unset (None) for no scheduled flush.

E430: Karni.search is malformed or names a field the model does not have

system check (error) · from karni.global_search.search_declaration; karni.checks.check_global_search

Why Karni objects. GET /api/search/ matches the query against the declared fields, shows each hit's title and subtitle, and makemigrations adds a trigram index per field. A field that is not text, a title that is not a column or a weight that is not a positive number would fail at query time, so the declaration is refused at boot.

Fix. Write search = {'fields': [...], 'title': ..., 'subtitle': ..., 'weight': ...}: fields lists text fields of the model (CharField, TextField), title and subtitle name a field or a path through foreign keys (title defaults to the first field), weight is a number above 0 (default 1). For example search = {'fields': ['name', 'sku'], 'title': 'name'}.

E431: ?models= names a resource cross-model search does not cover

API 400 response · from karni.api.global_search.GlobalSearchView

Why Karni objects. GET /api/search/?models= picks the resources to search by their router prefix. A name that is not one of them is a typo or a model without class Karni: search, and searching nothing for it would hide the mistake, so the request answers 400 with the resources it covers.

Fix. Name resources from the response's resources list (the router prefixes, e.g. products), or declare class Karni: search on the model and route a BaseViewSet for it.

E440: A message is sent as a kind nobody declared

exception · from karni.notify.send

Why Karni objects. A message kind is what Settings, Emails lists, what a person switches off and what a business edits. notify.send() sends declared kinds only, so every message the project sends can be found, switched and edited. karni.mail.send_templated() with an undeclared kind still sends its email, as it always did.

Fix. Declare the kind in the part's messages.py with karni.mail.register_kind('<prefix>.<message>', title=..., template='<app>/email/<stem>', fields={...}), or correct the name to one GET /api/email-templates/ lists.

W440: A message kind is declared on channels the project does not send on

system check (warning) · from karni.notify.checks.check_notify

Why Karni objects. KARNI_NOTIFY_CHANNELS lists the channels the project sends on. A kind whose channels are all left out of it goes nowhere, so its moment passes without a message.

Fix. Add the channel to KARNI_NOTIFY_CHANNELS, or declare the kind with a channel the project sends on, or silence karni.W440 when that is what the project wants.

E441: A person cannot switch or unsubscribe from this message kind

API 400 response · from karni.notify.choose; karni.notify.unsubscribe; PATCH /api/inbox/choices/<kind>/

Why Karni objects. A person's own switches cover the declared kinds that are switchable. A kind declared switchable=False (a sign-in code) always goes out. Unsubscribing is for marketing kinds (transactional=False): a receipt is switched off in the person's own switches, never by a link.

Fix. Use a kind GET /api/inbox/choices/ lists, or switch a transactional kind off with notify.choose(user, kind, email=False) instead of notify.unsubscribe().

API 400 response · from karni.notify.read_token; /api/notify/unsubscribe/

Why Karni objects. The link in a marketing email carries a token signed with the project's SECRET_KEY, naming the address and the kind. A changed or cut token, or one signed under another secret, would let anyone unsubscribe anyone.

Fix. Open the link from the email as it is. After a SECRET_KEY rotation, old links stop working: the person unsubscribes from a newer email or in their own switches.

E443: A message is sent to something that is not a recipient

exception · from karni.notify.send; karni.notify.recipients

Why Karni objects. A message goes to a user (its email and its inbox), a person of karni.people (its email, and its account when it has one), an email address, or a list of them. Anything else has no address and no inbox.

Fix. Pass to=[user], to=[person], to='someone@example.com' or a list of those.

E444: An inbox request asks for a page that does not exist

API 400 response · from karni.notify.api.InboxView

Why Karni objects. GET /api/inbox/ pages the signed-in person's notifications from page 1. A page past the last one, or one that is not a number, has nothing to show.

Fix. Ask for ?page= from 1 up to the page the previous answer's next named, or leave it out for the first page.

E445: A message kind names a channel Karni does not send on

exception · from karni.mail.register_kind

Why Karni objects. A message kind goes to an email, the recipient's inbox in the app (karni.notify), or both. A misspelt channel would send the message nowhere.

Fix. Pass channels=('email',), ('inbox',) or ('email', 'inbox').

E446: Edited emails would be lost: karni.notify is not installed

exception · from karni.notify.adopt.adopt_edited_emails (karni-commerce's migration 0008)

Why Karni objects. The emails a business edits moved to the notifications contract. A part that kept them in its own table (karni-commerce did) copies each one to notify.EmailTemplate before it drops its table, and without karni.notify there is no table to copy to.

Fix. Add 'karni.notify' to INSTALLED_APPS (features: {notify: true} in karni.yaml, or a recipe that requires notify>=1) and run migrate again.

E450: An event is published that is not declared

exception · from karni.events.publish

Why Karni objects. A family event is an API between parts: subscribers read its declared fields and karni check lists it. An event published without a declaration, or with a version nobody declared, would reach subscribers with a payload no one agreed on.

Fix. Declare it in the publishing app's events.py with declare('<prefix>.<record>.<moment>', version=1, fields={...}) before publishing it, or publish a declared version.

W450: A subscriber reads a version its event does not have

system check (warning) · from karni.outbox.checks.check_event_bus

Why Karni objects. Subscribers name the payload version they read. When the installed publisher declares other versions only, nothing is ever delivered to this subscriber.

Fix. Move the subscriber to a declared version (@subscribe(name, version=N)) and adapt it to that payload, or keep the publisher publishing the old version too.

E451: Family events need the karni.outbox app

system check (error) · from karni.outbox.checks.check_event_bus; karni.events.publish; karni.events.once

Why Karni objects. Subscribers are delivered from the outbox tables, written in the publisher's transaction. Without the app there is nowhere to write the event, so the subscribers would never be called.

Fix. Add 'karni.outbox' to INSTALLED_APPS and run migrate.

E452: An event declaration is malformed

exception · from karni.events.declare

Why Karni objects. A name is <prefix>.<record>.<moment> in lower case, a version is a whole number from 1, fields are lower case names with a description each, and one part owns each name and version.

Fix. Fix what the message names: declare('shop.order.paid', version=1, fields={'order': 'the order id', 'total': 'a decimal string'}). Declare a changed shape as the next version, next to the old one.

E453: A published event's fields do not match its declaration

exception · from karni.events.publish; karni.events.once

Why Karni objects. Subscribers rely on the declared fields being there, and on plain JSON values: ids, states and amounts, never model instances, so no subscriber depends on another part's models.

Fix. Pass exactly the declared fields (None for a value you do not have), ids instead of model instances (str(obj.pk)), and a person when the declaration names one.

E454: A subscriber is malformed

exception · from karni.events.subscribe

Why Karni objects. A delivery row names its subscriber, and every process (web, worker) finds it by that name. A nested function or a lambda has no stable name, and two subscribers cannot share one.

Fix. Define the subscriber at the top level of <app>/listeners.py and decorate it with @subscribe('<event name>', version=1), or pass a distinct name='...'.

E455: KARNI_EVENTS_DISPATCHER cannot be used

system check (error) · from karni.outbox.checks.check_event_bus; karni.outbox.dispatch.load

Why Karni objects. After a commit, Karni calls the dispatcher with each event's id to hand it to a worker. A path that does not import, or names something that cannot be called, would leave every event waiting for the sweep.

Fix. Name a function taking (event_id, *, countdown=0), as 'package.module.function', or remove the setting for the default (karni.outbox.dispatch.celery).

E456: An assertion about family events failed

test failure · from karni.testing.events (capture_events, assert_events_declared)

Why Karni objects. The test expected an event to be published with given values, or an app's published events to be declared, and the code did otherwise.

Fix. Read the events the message lists: publish the expected event inside the action's transaction, with the expected fields, and declare every event an app publishes.

E460: A timeline= option of an event declaration is not valid

system check (error) · from karni.timeline.checks.check_timeline; karni.timeline.parse_option

Why Karni objects. An event's timeline= option writes the title of every entry the event makes. A template that reads attributes or fields the event does not declare would show more than the payload holds, or nothing.

Fix. Write a title template with {field} for declared fields only (no attribute, index, conversion or format), or a mapping with the keys title, body, subjects ({field: 'app_label.model'}) and kind.

W460: Events declare a timeline title and the outbox is not installed

system check (warning) · from karni.timeline.checks.check_timeline

Why Karni objects. Entries from family events are written by a subscriber, and subscribers are delivered through karni.outbox. Without it, no entry is written from events.

Fix. Add 'karni.outbox' to INSTALLED_APPS and run migrate, or set KARNI_TIMELINE_FROM_EVENTS = False and write entries with timeline.record().

E461: The timeline needs the people contract

system check (error) · from karni.timeline.checks.check_timeline

Why Karni objects. Every timeline entry may point at a person (people.Person), so karni.timeline cannot work without karni.people.

Fix. Set KARNI_PEOPLE = True above karni_settings(globals()), or add 'karni.people' to INSTALLED_APPS, and run migrate.

E462: timeline.record() was given an argument it cannot use

exception · from karni.timeline.record

Why Karni objects. An entry needs a kind (lower-case words joined by dots), a title, and a person or a subject to show on. A person is a people.Person, a subject a saved record, and data holds JSON values only.

Fix. Pass kind='part.what', a title, person=<Person or id> and/or subjects=[record or ('app_label.model', id)], and ids instead of model instances in data.

E463: A timeline request names no record, or a malformed one

API 400 response · from karni.timeline.api.TimelineView

Why Karni objects. GET /api/timeline/ lists the timeline of exactly one person, organisation or record, and pages with the cursor it gave.

Fix. Name exactly one of ?person=<id>, ?organisation=<id> or ?subject=<app_label.model>:<id>, and pass ?cursor= as the previous page's next.

E470: A context slice names no app or model

exception · from karni.introspect.resolve_apps; karni.introspect.resolve_models; karni context

Why Karni objects. karni context --app and --model print one area of the project. The label or name matched no app with models and no model.

Fix. Use a name the message lists, or run karni context --summary to see every app and its models. A model is Name or app_label.Name.

E471: A context slice names a model two apps share

exception · from karni.introspect.resolve_models; karni context --model

Why Karni objects. Two apps have a model of that name, so the bare name could mean either.

Fix. Write app_label.Name, one of the labels the message lists.

E473: A volume seed refused tables that hold rows no seed run left

exception · from manage.py karni_seed --volume; karni.bulk_seeding.Ledger

Why Karni objects. A seed run records how many rows each table holds when it is done (.karni/local/seeded.json). A table that holds another number of rows was written by someone else, and volume rows would mix with that content.

Fix. Pass --reset to wipe the project's tables first, --force to add rows anyway, or --model to seed only the tables seed runs filled. Real content belongs in karni load.

E475: karni seed --volume or --batch-size is not a positive number

exception · from manage.py karni_seed

Why Karni objects. A volume and a batch size are numbers of rows.

Fix. Pass 1 or more, e.g. karni seed --volume 100000 --batch-size 2000.

E476: An endpoint is slower than its time budget at the large row count

test failure · from karni.testing.performance (the scaling check); query_scaling = Scaling(seconds=...)

Why Karni objects. The viewset declares a time budget: the request at the scaling check's large row count (the faster of two runs) must take no longer. It took longer.

Fix. Read the statements in the message. karni queries <endpoint> --explain shows each plan on PostgreSQL and names the index a sequential scan wants. Raise Scaling(seconds=...) only when the work is real.

E477: A scaling declaration or KARNI_SCALING_ROWS is not valid

exception · from karni.performance.Scaling; karni.performance.scaling_rows

Why Karni objects. The scaling check compares two row counts, small then large, and a time budget is a number of seconds.

Fix. Write rows=(small, large) with 1 <= small < large, e.g. Scaling(rows=(2, 50), seconds=0.5), and the same pair in KARNI_SCALING_ROWS.

E490: A tree:<path> scope does not end at a tree model

system check (error) · from karni.accounts.tree_scope.resolve_path; karni.checks.check_tree_scopes (KARNI_ROLES); tree_scope() in a Where

Why Karni objects. tree:<path> reaches the rows whose <path> is a node the user holds or a node below it, so each step of the path must be a relation of the model before it (a foreign key, a one-to-one, a many-to-many or a reverse relation) and the last one must point at a model on karni.models.TreeModel. A path that does not resolve could only ever reach no row, so Karni refuses it at startup, in KARNI_ROLES and wherever tree_scope() names it.

Fix. Name the row's relation to the tree model, through relations when needed: tree:region, tree:product__categories. Make the target a tree model (class Region(TreeModel, BaseModel)), or grant another scope.

E491: The access/ endpoint of a tree resource got a parameter it cannot use

API 400 response · from karni.api.tree (GET <resource>/access/?permission=)

Why Karni objects. ?permission= keeps the grants of the permissions it matches, written as a KARNI_ROLES pattern: 'app_label.model:action' with '' for either part, or '' alone. Anything else would match no grant and answer an empty forest without saying why.

Fix. Send a permission key such as ?permission=shop.order:view (or a pattern such as shop.order:*), or leave the parameter out to count every tree grant.

5xx · Settings and optional dependencies

E501: An optional dependency is not installed

exception · from karni.conf.sentry, karni.storage, karni.accounts.twofa, karni.api.search.postgres, karni.testing.assert_crud

Why Karni objects. Optional features (Sentry, S3 storage, thumbnails, 2FA, PostgreSQL search, image uploads in assert_crud) need extra packages that a minimal install leaves out.

Fix. Install the extra the message names, e.g. pip install 'karni[sentry]', 'karni[s3]', 'karni[images]', 'karni[2fa]' or 'psycopg[binary]'.

W501: The throttle cache is private to each process

system check (warning) · from karni.checks.check_throttle_cache

Why Karni objects. DRF keeps rate-limit counters in CACHES['default']. With DEBUG off, a locmem or dummy backend gives every worker its own counters, so the login, registration and password-reset limits are multiplied by the worker count.

Fix. Point CACHES['default'] at a backend every worker shares (Redis, which Karni uses by default, or the database cache). A deployment of one process declares it with KARNI_SINGLE_PROCESS=True and WEB_CONCURRENCY=1, which quiets the check.

E502: Unknown settings profile

exception · from karni.conf.karni_settings

Why Karni objects. karni_settings() picks dev or prod defaults from DJANGO_ENV.

Fix. Set DJANGO_ENV to one of the profiles the message lists, or pass env_name= to karni_settings().

E503: A module's settings fragment is invalid

exception · from karni.conf (karni.settings entry points)

Why Karni objects. Installed modules contribute default settings. A fragment may only add new top-level names, so installing a module never changes a setting you rely on.

Fix. Fix or upgrade the module the message names. Module authors: export a dict of new names only.

E504: Karni settings failed validation

exception · from karni.conf.validation.validate_settings (at startup)

Why Karni objects. Settings are validated once at boot so a bad value fails the deploy, not the first request that reads it.

Fix. Fix every setting the message lists. KARNI_VALIDATE = False skips validation (not recommended).

E505: The welcome page is reachable with DEBUG off

system check (error) · from karni.checks.check_welcome_route

Why Karni objects. The welcome page (karni.welcome) introspects the project at request time (models, modules, status checks, the agent context) for first boot in development. Served in production, it would describe the deployment to anyone who opens the site.

Fix. Mount it only through *karni.welcome.welcome_urls() at the end of urlpatterns (it returns no route when DEBUG is False) and remove any hand-written path('', WelcomeView.as_view()).

E506: A setting names a dotted path that cannot be imported

exception · from karni.imports.import_setting (KARNI_SEARCH_PROVIDER, KARNI_API_ROUTER, KARNI_ADMIN_SITE, KARNI_THUMBNAILER, ...)

Why Karni objects. Settings that name a class or function by dotted path are resolved when first used. A typo or a package missing from the environment would otherwise surface as a bare ModuleNotFoundError far from the setting.

Fix. Fix the path the message names ('package.module.Object') or install the package that provides it.

E507: KARNI_CACHE names an unknown cache backend

exception · from karni.conf (KARNI_CACHE)

Why Karni objects. The default cache (throttle counters, response cache, locks) is Redis at REDIS_URL. locmem is the in-process alternative for a host run without Redis.

Fix. Set KARNI_CACHE to redis (the default) or locmem. For anything else, define CACHES yourself in settings.py.

E508: A setting is assigned where it cannot take effect

system check (error) · from karni.checks.check_call_time_settings

Why Karni objects. karni_settings() reads a few settings during the call to compute others: KARNI_AUTH_MODE, KARNI_2FA, KARNI_SOCIAL_AUTH and KARNI_SOCIAL_PROVIDERS decide INSTALLED_APPS and MIDDLEWARE, KARNI_FRONTEND_URL feeds CSRF_TRUSTED_ORIGINS, KARNI_AUTH_THROTTLE_RATES the throttle rates, KARNI_JSON_LOGS builds LOGGING, KARNI_CACHE builds CACHES, KARNI_STORAGE builds STORAGES and KARNI_SINGLE_PROCESS sets the cache, Celery's eager mode and the probes. Assigned after the call, such a setting changes none of them, and the project would run with the settings computed from the old value. A KARNI_ADMIN_LOGO with no SITE_LOGO entry in UNFOLD (UNFOLD replaced after the call) shows no logo either.

Fix. Move the assignment above the karni_settings(globals()) line, pass it as a keyword (karni_settings(globals(), KARNI_AUTH_MODE='session')) or set its environment variable in .env. For the logo, change UNFOLD in place instead of replacing it.

E509: Sign-in with an ID token needs the cryptography package

exception · from karni.conf.validation (at startup), karni.accounts.social_token

Why Karni objects. Google, Microsoft and Apple sign their ID tokens with RS256 (an EC key uses ES256). PyJWT verifies those only with the cryptography package, which a plain install of Karni leaves out.

Fix. Run pip install 'karni[social-token]', or empty KARNI_SOCIAL_TOKEN_PROVIDERS.

E510: KARNI_STATIC_STORAGE names an unknown storage

exception · from karni.conf (KARNI_STATIC_STORAGE)

Why Karni objects. The static files' storage is chosen by name: plain keeps the names as written, manifest gives each file a name with a hash of its content, which a browser may keep for a year. Any other word names nothing.

Fix. Set KARNI_STATIC_STORAGE to plain (the default), manifest or the dotted path of a storage class, or define STORAGES yourself in settings.py.

W510: DEBUG is on in a deployment

system check (warning) · from karni.security.checks.check_debug (deploy)

Why Karni objects. With DEBUG on, an error page shows the settings, the source code around the error and the request to whoever triggers it. Django also keeps every query in memory, and the content security policy only reports instead of blocking.

Fix. Run production with DJANGO_ENV=prod, which turns DEBUG off, or set DEBUG=False in the environment.

E511: A front end cannot be published at that path

exception · from karni.deploy.web.front_path; manage.py karni_publish_web --front

Why Karni objects. karni_publish_web --front PATH=DIR publishes another built front end, a game's build for one, at a folder of the web root. PATH must be folder names of letters, digits, - and _ joined by / (play/sky-dash), outside the folders the staff app and the published files take, and the option needs both PATH and DIR.

Fix. Give --front play/<slug>=game/<slug>/dist, as the release step does for each game. The message names the paths that are taken.

W511: SECRET_KEY is weak or a development key

system check (warning) · from karni.security.checks.check_secret_key (deploy)

Why Karni objects. SECRET_KEY signs sessions, password-reset and verification tokens and every signed value. The scaffold's karni-insecure-dev-key is public, and a short or plain key can be guessed. Either way anyone could forge them.

Fix. Set SECRET_KEY in the production environment to a random value of at least 50 characters, for example the output of python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())". Never commit it.

W512: ALLOWED_HOSTS is empty or allows every host

system check (warning) · from karni.security.checks.check_allowed_hosts (deploy)

Why Karni objects. Django builds absolute links, including password-reset and verification links, from the request's Host header. With '*' an attacker picks the host those links point at. An empty list answers no host at all once DEBUG is off.

Fix. Set ALLOWED_HOSTS in the environment to the site's host names, comma-separated, e.g. ALLOWED_HOSTS=example.com,www.example.com.

W513: CSRF_TRUSTED_ORIGINS is missing, a wildcard or plain http

system check (warning) · from karni.security.checks.check_csrf_trusted_origins (deploy)

Why Karni objects. Django accepts a form or a session-mode API call only from a trusted origin. Behind a proxy, and for a frontend on another host, that origin must be listed. A wildcard or an http:// origin trusts more than the site, and session mode adds KARNI_FRONTEND_URL, whose default is http://localhost:5173.

Fix. Set CSRF_TRUSTED_ORIGINS in the environment to the site's https origins, comma-separated, e.g. CSRF_TRUSTED_ORIGINS=https://example.com. In session mode also set KARNI_FRONTEND_URL to the frontend's https URL.

W514: HSTS is off

system check (warning) · from karni.security.checks.check_hsts (deploy)

Why Karni objects. Without Strict-Transport-Security a browser may still try plain http, for example from a typed address or an old link, and a network attacker can read or change that traffic before the redirect to https.

Fix. Run production with DJANGO_ENV=prod, which sets SECURE_HSTS_SECONDS to one year with subdomains and preload. To try a new domain first, set SECURE_HSTS_SECONDS=3600 in the environment and raise it once https works.

system check (warning) · from karni.security.checks.check_secure_cookies (deploy)

Why Karni objects. A cookie without the Secure flag is also sent over plain http, where anyone on the network can read it and take over the session.

Fix. Run production with DJANGO_ENV=prod, which sets SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to True. If you define them in settings.py, set both to True.

W516: The admin is at /admin/

system check (warning) · from karni.security.checks.check_admin_path (deploy)

Why Karni objects. Scanners try /admin/ on every site, so a login form there receives password guesses all day. Another path keeps it off their lists. It is not a substitute for strong passwords, it only removes the noise.

Fix. Set KARNI_ADMIN_PATH in the environment to a path nobody guesses, with a trailing slash, e.g. KARNI_ADMIN_PATH=staff-7f3a9c/. The scaffold's urls.py mounts the admin at that setting.

W517: CORS allows every origin

system check (warning) · from karni.security.checks.check_cors (deploy)

Why Karni objects. CORS decides which other sites may call the API from a visitor's browser. Allowing every origin lets any site read what the visitor can read, and with CORS_ALLOW_CREDENTIALS (on in session mode) it does so with the visitor's cookies. The development profile allows every origin, so a deployment that runs with DJANGO_ENV=dev does too.

Fix. Run production with DJANGO_ENV=prod and list the frontend's origins in CORS_ALLOWED_ORIGINS, e.g. CORS_ALLOWED_ORIGINS=https://app.example.com. Remove CORS_ALLOW_ALL_ORIGINS and any regex that matches every origin.

W518: No enforced Content-Security-Policy

system check (warning) · from karni.security.checks.check_csp_present (deploy)

Why Karni objects. The Content-Security-Policy tells the browser which scripts may run, so an injected script does not. Karni's SecurityHeadersMiddleware sends it, but not when it is missing from MIDDLEWARE or KARNI_CSP is None, and it only reports while DEBUG or KARNI_CSP_REPORT_ONLY is on.

Fix. Keep karni.security.SecurityHeadersMiddleware in MIDDLEWARE (karni_settings() adds it), leave KARNI_CSP a dict, and run with DEBUG off and KARNI_CSP_REPORT_ONLY unset. If a proxy sends the policy instead, add 'karni.W518' to SILENCED_SYSTEM_CHECKS.

W519: The Content-Security-Policy lets any script run

system check (warning) · from karni.security.checks.check_csp_scripts (deploy)

Why Karni objects. A script-src with *, http:, https:, data:, 'unsafe-eval' or 'unsafe-inline' (without a nonce or hash) lets an injected script run, which defeats the policy. The admin and the API docs pages get the extra sources they need on their own pages only.

Fix. Remove those sources from KARNI_CSP['script-src']. Allow a script host by its origin, e.g. https://js.example.com, and an inline script by its hash with karni.security.script_hash() on the one view that needs it (@csp_extend).

W520: Production email is not set up

system check (warning) · from karni.security.checks.check_email (deploy)

Why Karni objects. Password resets, account emails and the notifications of a site's forms go out by email. The console, locmem, dummy and file backends deliver nothing, and a sender at localhost (Django's default, webmaster@localhost) is refused by mail servers, so every email is lost without an error.

Fix. Set EMAIL_URL to the mail server (smtp+tls://user:password@smtp.example.com:587, smtps:// for SSL) and DEFAULT_FROM_EMAIL to an address of the site's domain ("Example Site <noreply@example.com>") in the production environment (.env.prod). .env.prod.example lists them. A project that sends no email adds 'karni.W520' to SILENCED_SYSTEM_CHECKS.

E520: The deploy checks failed when the container started

exception · from karni.deploy.entrypoint (the production image's ENTRYPOINT)

Why Karni objects. The production image runs karni check --deploy before its command, so a container with DEBUG on, the scaffold's SECRET_KEY, open hosts or another unsafe value never serves a request. Each finding printed before the E520 line has its own code (karni.W510 to karni.W520, a Django security warning, or a karni check hook).

Fix. Set the production values in the environment the container gets (.env.prod for docker-compose.prod.yml) and start it again: karni explain W511 and the others say what each value must be. In an emergency KARNI_SKIP_DEPLOY_CHECK=1 starts it without the checks, logged on every start. Remove it once the values are fixed.

E521: A backup failed

exception · from karni.deploy.backup (the backup service, karni-backup)

Why Karni objects. A backup that fails quietly is found missing on the day it is needed, so the backup service reports the failure in its log, and its health check turns unhealthy until a backup succeeds.

Fix. Read the line after E521: it names the step (pg_dump, pg_restore, psql, the media archive, S3) and its error. Check DATABASE_URL, that the client tools match the database's major version (the backup image's POSTGRES_VERSION), the free space in KARNI_BACKUP_DIR and, with KARNI_BACKUP_S3_BUCKET, the AWS_* credentials. Then run docker compose -f docker-compose.prod.yml exec backup karni-backup run.

W530: Anyone may read a resource whose ids can be guessed

system check (warning) · from karni.checks.check_public_integer_keys

Why Karni objects. The model has an integer primary key (BigIntBaseModel or an AutoField), its detail route looks rows up by that key, and its read access admits anonymous callers. Integer ids are sequential, so a visitor learns how many rows there are and can walk the detail URLs one id after the other, including rows no list links to.

Fix. Give the model a UUID key (inherit BaseModel) or look rows up by a slug (lookup_field = "slug" on the viewset). When the ids may be public, write # karni: allow(public-integer-key): <reason> above the viewset class, or add 'karni.W530' to SILENCED_SYSTEM_CHECKS for the whole project.

E530: KARNI_NAVIGATION is not valid

exception · from karni.navigation.settings_problems (startup validation), karni.navigation.models.NavItem

Why Karni objects. KARNI_NAVIGATION is a list of items and groups, 'db' or None. An item is a dict with a label and a route (an app path that starts with /), and may have an icon name, an integer order and what it requires. A group is a dict with a label and children, and no route. A menu Karni cannot read would answer every request with an error.

Fix. Fix the entry the message names, e.g. {'label': 'Products', 'route': '/products', 'icon': 'box', 'requires': 'catalog.product:view'}, or {'label': 'Catalog', 'children': [...]} for a group.

E531: KARNI_NAVIGATION = 'db' without the karni.navigation app

exception · from karni.navigation.settings_problems (startup validation)

Why Karni objects. The database menu lives in the NavItem table, which comes with the karni.navigation app. Karni does not install the app for every project, so a project that keeps its menu in the settings gains no table.

Fix. Add 'karni.navigation' to INSTALLED_APPS and run migrate, or set KARNI_NAVIGATION to a list of items.

E532: A navigation entry's requirement is not valid

exception · from karni.navigation.requirement_problem (startup validation, NavItem.requires)

Why Karni objects. An entry requires 'public' (everyone), 'authenticated' (every signed-in user) or a permission pattern written as in KARNI_ROLES grants, so role grants and per-user grants open it the way they open the API.

Fix. Write 'public', 'authenticated', or a pattern such as 'catalog.product:view', 'catalog.:view' or ''.

system check (error) · from karni.navigation.checks.check_navigation (karni check)

Why Karni objects. karni check compares each item's route with the pages of the frontend: the path: entries of the KARNI_NAVIGATION_PAGES files (frontend/src/routes.tsx, where karni make page and karni build register each page). A menu entry that leads to no page is a dead link for every user who sees it.

Fix. Fix the route (the message names the closest one), add the page with karni make page, or remove the item. Add 'karni.E533' to SILENCED_SYSTEM_CHECKS if the page is registered somewhere karni check does not read, or list that file in KARNI_NAVIGATION_PAGES.

E534: A navigation entry requires a permission the project does not have

system check (error) · from karni.navigation.checks.check_navigation (karni check)

Why Karni objects. A permission pattern opens an entry for users who hold a grant for a permission it names. A pattern that names no permission of the project (a typo, a model that was renamed) opens it for nobody but a superuser.

Fix. Name an existing permission as karni context or GET permissions/matrix/ lists it (app_label.model:action, lowercase), or write 'authenticated' or 'public'.

E535: Navigation is turned off

API 400 response · from karni.navigation.api.NavigationView

Why Karni objects. GET /api/navigation/ is mounted only while KARNI_NAVIGATION is set. A URLconf built while it was set answers 404 with this code once it is unset.

Fix. Set KARNI_NAVIGATION to a list of items, or to 'db' with the karni.navigation app installed (or navigation: in karni.yaml, then karni build).

E536: A navigation entry has both a route and entries

exception · from karni.navigation.models.NavItem.clean (the admin form)

Why Karni objects. An entry with a route is a link. A group is an entry without a route that holds other entries. One entry cannot be both: the menu shows a link with no entries under it.

Fix. Give the group no route and put the link inside it as an entry of its own, or choose a group as the parent.

W540: The database of an external model cannot be reached

system check (warning) · from karni.db.checks.check_external_tables (karni check)

Why Karni objects. karni check compares each external model with its table or view when the model's database answers. This one did not, so nothing was compared for it. That is not an error: the database may be outside this machine's reach (CI, a laptop).

Fix. Check the alias in DATABASES (host, port, credentials, network) and run karni check again where the database is reachable. Add 'karni.W540' to SILENCED_SYSTEM_CHECKS where it never is.

W541: Karni.writable on a model that is not external

system check (warning) · from karni.db.checks.check_database_options

Why Karni objects. writable = True only lifts the read-only default of an external model. Every other model is writable already, so the declaration does nothing.

Fix. Remove writable = True, or add external = True (with Meta.managed = False) if another system owns the table.

W542: Karni.database is declared but Karni's database router is not installed

system check (warning) · from karni.db.checks.check_database_router

Why Karni objects. A model declares class Karni: database, but DATABASE_ROUTERS does not list karni.db.DatabaseRouter (or a subclass), so Django sends the model to the default database. karni_settings() lists the router, so this happens when DATABASE_ROUTERS is replaced after the call.

Fix. Add 'karni.db.DatabaseRouter' to DATABASE_ROUTERS, after your own routers (the first router with an answer wins). If your own router routes these models, add 'karni.W542' to SILENCED_SYSTEM_CHECKS.

E550: Karni.field_groups or Karni.field_group_layout is malformed

system check (error) · from karni.layout.field_groups; karni.checks.check_layouts

Why Karni objects. The groups are published in the OpenAPI schema as x-karni-field-groups and lay out @karni/ui's ResourceForm and ResourceDetail and the admin's change form. A group without a title or without fields cannot be shown, so the declaration is refused at boot.

Fix. Map each group's title to a list of field names, e.g. field_groups = {'Overview': ['name', 'summary'], 'Financials': ['price', 'cost']}, and write field_group_layout = 'sections' (the default) or 'tabs'.

E551: A field group or a column set names a field the model does not have

system check (error) · from karni.layout.field_groups; karni.layout.column_sets; karni.checks.check_layouts

Why Karni objects. A name with a typo would leave its field out of every form section, or show an empty column, without an error anywhere, so a group or column set must name the model's own fields.

Fix. Correct the name to a field of the model (the message names the model, the group or set, and the field), or remove it from the group or set.

E552: A field is in two field groups

system check (error) · from karni.layout.field_groups; karni.checks.check_layouts

Why Karni objects. A form shows each field once, in one group. A field listed in two groups would be edited in two places at once, so each field belongs to one group.

Fix. Keep the field in one group and remove it from the other (the message names both).

E553: Karni.column_sets is malformed

system check (error) · from karni.layout.column_sets; karni.checks.check_layouts

Why Karni objects. The column sets are published as x-karni-column-sets and ResourceTable offers them in a selector. A set without a name or without columns, or one that lists a column twice, cannot be shown.

Fix. Map each set's name to a list of field names, each once, e.g. column_sets = {'default': ['name', 'price'], 'financial': ['name', 'price', 'cost']}.

E570: class Karni: taxonomies is malformed

exception · from karni.taxonomy.declared_taxonomies (raised when the model class is built)

Why Karni objects. taxonomies maps each key to a tree model. The key becomes a many-to-many field of that name and the list parameters ?<key>= and ?<key>_descendants=, so it must be a field name: no leading underscore, no double underscore, not ending in _descendants. The value names the tree model as 'app_label.Model' or the model class.

Fix. Write taxonomies = {"region": "geo.Region", "category": "catalog.Category"}, with keys that are field names and values that name tree models.

W570: An aggregation expression is never used

system check (warning) · from karni.checks.check_aggregations

Why Karni objects. An expression in the declaration's expressions is only reachable through group_by or values. One that neither lists does nothing.

Fix. Add its name to group_by or values, or remove it.

E571: A taxonomy points at a model that is not a tree model

system check (error) · from karni.checks.check_taxonomies (karni check)

Why Karni objects. A taxonomy tags rows with the nodes of a hierarchy: ?<key>_descendants=, the facets rolled up to the ancestors, the node counts and the tree:<key> scope all walk the tree from a node to the nodes below it. A model that is not on karni.models.TreeModel has no parent to walk.

Fix. Make the target a tree model (class Region(TreeModel, BaseModel), or tree: true in karni.yaml), or point the key at the tree model you meant. For tags without a hierarchy, declare a plain many-to-many instead of a taxonomy.

E572: The field a taxonomy adopts is not a many-to-many to its tree

system check (error) · from karni.checks.check_taxonomies (karni check); karni.taxonomy.Taxonomy.field

Why Karni objects. When the model already has an attribute named after a taxonomy key, Karni adopts it instead of generating the many-to-many. Adopting works only for a ManyToManyField to the tree model the key names: the filters, the facets and the scope read its through table.

Fix. Declare the field as models.ManyToManyField(<the tree model>, blank=True, ...) under the key's name, rename the other attribute, or remove the field and let Karni generate it.

E573: A taxonomy filter or endpoint got a parameter it cannot use

API 400 response · from karni.api.taxonomy (?<key>=, ?<key>_descendants=, facets/, <key>/tagged/)

Why Karni objects. ?<key>= takes keys of the tree's nodes separated by commas. ?<key>_descendants=, ?rollup= and ?descendants= take true or false. facets/ counts one taxonomy: ?taxonomy= names it, and may be left out only when the model has one.

Fix. Send node keys (?region=3,7), true or false for the flags, and one of the keys the message lists as ?taxonomy=.

W580: Cached responses live in a cache private to each process

system check (warning) · from karni.checks.check_api_cache_backend

Why Karni objects. KARNI_API_CACHE keeps responses and their version tokens in KARNI_API_CACHE_ALIAS. A per-process backend (LocMemCache) keeps them in each worker, so a write handled by one worker leaves the other workers serving the old response until the TTL ends.

Fix. Point KARNI_API_CACHE_ALIAS at a cache every process shares (Redis, the database cache) in production, or silence karni.W580 for a single-process deployment.

E590: The API version settings cannot work

system check (error) · from karni.checks.check_api_versions

Why Karni objects. KARNI_API_VERSION is a URL segment (lower case letters, digits and -, at most 16 characters), and KARNI_API_VERSIONS is a dict of version name to a dict with the keys router, deprecated, sunset and notes. A sunset or deprecated date is written 'YYYY-MM-DD', and a router is a dotted path to a zero-argument factory. One of them is not, so the versions cannot be mounted.

Fix. Fix the setting the message names. Example: KARNI_API_VERSION = 'v1' and KARNI_API_VERSIONS = {'v0': {'deprecated': '2026-06-01', 'sunset': '2027-01-31'}}.

W590: A field cross-model search searches has no trigram index

system check (warning) · from karni.global_search.check_search_indexes (karni check)

Why Karni objects. On PostgreSQL every searched field needs a GIN trigram index, or each search reads the whole table. Karni adds the index to the model's Meta.indexes, so it exists once the migration that creates it is written and applied.

Fix. Run python manage.py makemigrations <app> and python manage.py migrate (karni build writes the migration for an app built from karni.yaml). For a table another system owns, run the CREATE INDEX the message prints in its database. For a table small enough to scan, silence it: SILENCED_SYSTEM_CHECKS = ["karni.W590"].

E591: KARNI_API_UNVERSIONED is not usable

system check (error) · from karni.checks.check_api_versions

Why Karni objects. KARNI_API_UNVERSIONED says what /api/ without a version does once versions exist: 'keep', 'redirect' or 'remove'. 'redirect' sends clients to the current version, so it needs KARNI_API_VERSION.

Fix. Use 'keep', 'redirect' or 'remove', and set KARNI_API_VERSION when you redirect.

W591: A model declares Karni.search but no routed viewset serves it

system check (warning) · from karni.checks.check_global_search_routes

Why Karni objects. Cross-model search reads each model through its list endpoint, so the access rules hold, and links each hit to the resource's page. A model no routed BaseViewSet serves has neither, so search never finds it.

Fix. Declare a BaseViewSet for the model in the app's viewsets.py (karni make viewset), or remove search from its class Karni.

6xx · Testing and seeding

E601: The resource under test is not routed

test failure · from karni.testing.assert_crud / assert_isolated

Why Karni objects. assert_crud tests a resource through its URLs, exactly as clients reach it.

Fix. Route the viewset (karni make viewset <Model>, or auto_register), or pass the viewset class or its route name.

E602: The API does not behave as its access declaration promises

test failure · from karni.testing.assert_crud

Why Karni objects. assert_crud derives every expected outcome (allowed actions, 403/404 denials, pagination, filtering, owner stamping, response schema) from the viewset's access and the OpenAPI schema. Each listed failure is a real difference.

Fix. Fix each failure in the report: usually the access declaration, a custom get_queryset, or a serializer that does not match the schema. skip=[...] excludes a check that genuinely does not apply.

E603: checks=/skip= names unknown checks

exception · from karni.testing.assert_crud; assert_row_hidden; assert_admin_row_hidden

Why Karni objects. Skipping (or selecting) a check that does not exist would hide nothing and mislead the reader.

Fix. Use the check names the message lists.

E604: A request raised an exception during assert_crud

test failure · from karni.testing.assert_crud

Why Karni objects. The API raised instead of answering, so the check could not run.

Fix. Read the exception in the message and fix the view, serializer or data it names.

E605: assert_isolated cannot isolate this resource

exception · from karni.testing.assert_isolated; karni.testing.isolation

Why Karni objects. Isolation is proved along a dimension (owner, tenant, ...) that the resource's access actually filters by.

Fix. Give the resource an Owned(...) access (or install the module providing the dimension), and name only registered dimensions.

E606: Rows leak to a user who must not see them

test failure · from karni.testing.assert_isolated; assert_row_hidden; assert_admin_row_hidden

Why Karni objects. One owner (or tenant) could read or change another's rows, or learn that a row outside their scope exists (a 403 where a missing row gets 404, a count, an expanded or exported related row): a data leak.

Fix. Fix what each listed line names: usually the viewset's access (Owned('<owner path>'), a scoped grant, the tenant scope), or custom get_queryset / get_object / serializer / @action code that bypasses it.

E607: There is no OpenAPI schema snapshot yet

test failure · from karni.testing.assert_schema_snapshot

Why Karni objects. CI compares the API schema with a committed snapshot, so an accidental breaking change fails the build. CI never writes snapshots.

Fix. Generate it locally with the command in the message and commit the file.

E608: The OpenAPI schema changed

test failure · from karni.testing.assert_schema_snapshot

Why Karni objects. Clients (and the generated frontend types) depend on the schema, so this change would reach them.

Fix. If the change is intended, accept it with the command in the message and commit the snapshot. Otherwise, revert the change that caused it.

E609: No factory can be built for this model

exception · from karni.testing.factories

Why Karni objects. Factories create rows of concrete models.

Fix. Pass a concrete model class or an 'app_label.Model' string.

W610: karni queries --explain analyses plans on PostgreSQL only

system check (warning) · from karni.api.diagnose; karni queries --explain

Why Karni objects. EXPLAIN ANALYZE with a plan Karni reads, and the sequential scans it flags, need PostgreSQL. On another database --explain prints that database's plain EXPLAIN of the slowest statements.

Fix. Run karni queries --explain against PostgreSQL, with data at a realistic volume (karni seed --volume N).

E610: A factory cannot generate a value for a field

exception · from karni.testing.factories

Why Karni objects. Values are inferred from field types and names, and some custom fields have no safe default.

Fix. Pass the value (create(Model, field=...)) or define an explicit factory in <app>/factories.py.

W611: A query reads a large table from start to end

system check (warning) · from karni.api.explain; karni queries --explain

Why Karni objects. The plan has a sequential scan on a table of KARNI_EXPLAIN_SEQ_SCAN_ROWS rows or more (default 1000). It reads every row, so it slows down as the table grows.

Fix. Add the index the finding names to the model's Meta.indexes and make a migration. When the finding says the filter keeps most rows, narrow the filter or paginate instead: an index would not help.

E611: Required relations form a loop

exception · from karni.testing.factories; karni.seeding

Why Karni objects. Each row needs its required relation to exist first. In a loop, no order works.

Fix. Make one of the foreign keys nullable, pass an existing row for that field, or seed one model yourself in a Seeder.seed() override.

E612: Seeding keeps hitting a database constraint

exception · from karni.seeding

Why Karni objects. Generated values collided with a unique or check constraint on every attempt.

Fix. Give the clashing fields distinct values in a seeder (karni make seeder <Model>), e.g. with factory.Sequence.

E613: Seeding a row failed

exception · from karni.seeding

Why Karni objects. The model rejected a generated row (model validation or save() logic).

Fix. Override Seeder.seed() for the model (karni make seeder <Model>) and create the rows yourself with context.create(..., field=value).

E614: karni seed was given invalid arguments

exception · from karni seed; manage.py karni_seed

Why Karni objects. --model takes app_label.Model names and --count a non-negative number.

Fix. Fix the argument the message names, e.g. karni seed --model events.Event --count 20.

E615: karni seed refuses to run with DEBUG = False

exception · from karni seed; manage.py karni_seed

Why Karni objects. DEBUG = False usually means a production database, and seeding creates a demo superuser with a known password.

Fix. Seed a development database. If you really mean it, pass --force.

E616: A hidden-row check has nothing to prove against

test failure · from karni.testing.assert_row_hidden; assert_admin_row_hidden

Why Karni objects. A row-scope check only means something when the client can list the resource and sees some row (the positive control). A role-level refusal or an empty list hides every row alike, so every check would pass vacuously.

Fix. Pass a client (or staff user) that can list the resource, and a row it does see as visible=. Test role-level refusals with assert_crud's denials instead.

E617: karni seed refuses to add demo rows to a table that already has rows

exception · from karni seed; manage.py karni_seed

Why Karni objects. Seeded rows carry no mark, so seed cannot tell its own rows from real content. Adding random demo rows to a table that holds content mixes the two for good. Any row in a table the run would write to counts (the user table is left out: users are matched by login and never deleted).

Fix. Pass --reset to wipe the project's tables first, --force to add demo rows on top, --model to narrow the run to empty tables, or load real content with karni load.

E618: A public page fails the page checks

test failure · from karni.testing.assert_pages

Why Karni objects. assert_pages requests each page of a site and checks what visitors and search engines get: a 200, a title, a meta description, alt text on every image, same-site links that answer, and a 404 for a URL the site does not have. Each listed line is a page and a problem a visitor or a crawler would meet.

Fix. Fix what each line names: usually the page's {% block title %} or {% block description %}, an img element without an alt attribute (alt="" for a decorative image), a link or {% static %} path to a URL that does not exist, or a catch-all route that should raise Http404. Turn a check off with require_title=False, require_description=False, require_alt=False, check_links=False or not_found_url=None, or leave links out with ignore=[...].

E619: assert_pages was given no URLs

exception · from karni.testing.assert_pages

Why Karni objects. With no page to request, every check would pass without checking anything.

Fix. Pass the site's pages, for example assert_pages(client, ["/", "/about/"]).

W620: A role grant of a tree scope gives its members no node

system check (warning) · from karni.checks.check_tree_scopes (karni check)

Why Karni objects. A role grant of tree:<path> reaches the rows under the node the user holds in the attribute named after the path's last step (tree:region and tree:store__region read user.region), as related:<key> compares user.<key>. The user model has no such attribute, so the role gives each member no node and no row. A tree grant never falls back to every row.

Fix. Give the user model the attribute (a field or a property holding a node of the tree, e.g. region), or give each user their nodes with user grants of the same scope (features: user_grants, then karni.accounts.grants.grant(..., targets=[...])). The check is silent while KARNI_USER_GRANTS is on, since the nodes come from the grants. Silence it with SILENCED_SYSTEM_CHECKS = ['karni.W620'] otherwise when something else gives the nodes on purpose.

E620: cycled() was given an empty list of names

exception · from karni.seeding.cycled

Why Karni objects. cycled() picks a row's name from a fixed list and repeats the list with a number once it runs out. An empty list has no name to give.

Fix. Pass at least one name, for example cycled(["Oak Table", "Pine Shelf"], index).

W630: The database menu could not be read

system check (warning) · from karni.navigation.checks.check_navigation (karni check)

Why Karni objects. With KARNI_NAVIGATION = 'db', karni check reads the NavItem rows to compare their routes and requirements. The database did not answer, or the karni.navigation migration has not run, so nothing was compared. That is not an error: the database may be outside this machine's reach.

Fix. Run migrate, check DATABASES, and run karni check again where the database answers. Add 'karni.W630' to SILENCED_SYSTEM_CHECKS where it never does.

W631: No frontend pages file to compare the menu with

system check (warning) · from karni.navigation.checks.check_navigation (karni check)

Why Karni objects. karni check reads the pages from the KARNI_NAVIGATION_PAGES files (default frontend/src/routes.tsx). None of them exists, so the menu's routes were not compared.

Fix. List the file that registers the frontend's routes in KARNI_NAVIGATION_PAGES, or set it to [] when the menu serves a client whose pages Karni cannot read (a mobile app).

W660: An API version is past its sunset date

system check (warning) · from karni.checks.check_api_versions (karni check)

Why Karni objects. A version's Sunset header promised the day it would go. That day has passed and the version is still mounted, so clients that read the header were told something untrue.

Fix. Remove the version from KARNI_API_VERSIONS once its clients have moved, or move its sunset date. Add 'karni.W660' to SILENCED_SYSTEM_CHECKS to keep it mounted.

W661: API versions are set, but the URLconf does not mount them

system check (warning) · from karni.checks.check_api_versions (karni check)

Why Karni objects. KARNI_API_VERSION or KARNI_API_VERSIONS names versions, and the API is mounted at /api/<version>/ only by karni.api.versions.api_urls(). The URLconf still includes karni.api.urls at api/, so every /api/<version>/ answers 404.

Fix. In config/urls.py, import api_urls from karni.api.versions and use *api_urls() in place of path("api/", include("karni.api.urls")). A new project already does.

7xx · Agent tooling: karni check, karni.rules.py, changelog

E701: karni.rules.py is invalid

exception · from karni.agent.overrides

Why Karni objects. karni.rules.py adjusts the agent rules. It is read statically (never executed), so only literal values are allowed.

Fix. Fix the line the message names. ADD/OVERRIDE/DISABLE/ADAPTERS take literal values. ADD uses codes like P001 with a non-empty 'rule'. OVERRIDE/DISABLE name only Karni K codes.

E702: karni check found violations

exception · from karni check; manage.py karni_check

Why Karni objects. The architecture checks enforce the K rules (generated code is not hand-written, access is declared, and so on).

Fix. Fix each listed violation (each names its K code, and karni explain K106 explains one), or suppress a deliberate exception the way the violation describes.

E703: A source file cannot be parsed

exception · from karni.agent.check

Why Karni objects. karni check reads your code statically, so a syntax error stops it.

Fix. Fix the syntax error at the file and line in the message.

E704: Karni's changelog is invalid

exception · from karni.changelog

Why Karni objects. karni upgrade reads the changelog to find and apply every breaking change.

Fix. Maintainers: fix the entries the message lists (schema in karni/changelog/init.py). Users: reinstall karni-cli.

8xx · Import and export

E801: An import cannot proceed as asked

API 400 response · from karni.transfer

Why Karni objects. The mapping names a column the file lacks or a field the role may not write, the file has no header row, a commit was requested before the mandatory preview, or the model's import metadata (Karni.natural_key / import_key / import_lookup / import_transform / after_import) is malformed.

Fix. Map columns to importable fields only (GET /<resource>/import/ lists them), preview before committing, and check the names in class Karni against the model.

E802: The file format is not supported

API 400 response · from karni.transfer.formats

Why Karni objects. Import and export speak CSV and XLSX. Anything else is refused, and so is an upload whose format cannot be told from its name or content type.

Fix. Upload a .csv or .xlsx file, or pass ?format=csv|xlsx. XLSX needs openpyxl (a core dependency).

E803: Too many rows for one import or export

API 400 response · from karni.transfer

Why Karni objects. KARNI_IMPORT_MAX_ROWS caps an upload and KARNI_EXPORT_MAX_ROWS an export so one request cannot pin a worker or build an unbounded file.

Fix. Split the upload, narrow the export's filters, or raise the setting for a project that needs more.

E804: A content file cannot be loaded

exception · from karni load; manage.py karni_load; karni.transfer.loading

Why Karni objects. The file is missing, is not valid JSON or YAML, does not map model labels to lists of rows, names a model that is not installed, nests rows under a model with no key to match them on, or --as names no user. Nothing was written.

Fix. The message names the file and the problem. Keys are model labels (events.Event), each holding a list of rows. A nested child needs a Karni.natural_key or a unique constraint with its parent. YAML needs PyYAML, or write the file as JSON.

E805: A content file holds rows that cannot be loaded

exception · from karni load; manage.py karni_load; karni.transfer.loading

Why Karni objects. A row failed the validation the API runs (a missing required field, a bad choice, clean(), uniqueness), names a field the model does not have or a file cannot set, names a relation target that does not exist, lacks its key, or points at a file that is not there. The whole load runs in one transaction, so every row was rolled back.

Fix. Each problem names the model, the row's key, the field and what is wrong. Fix the rows (relations are named by the target's natural key, paths are relative to the content file) and run again. karni load --dry-run checks a file without writing.

9xx · Debugging: karni queries, karni explain

E901: karni why: no API resource by that name

exception · from karni.why.resolve.resolve_resource; karni why

Why Karni objects. karni why explains the decisions of a routed BaseViewSet, so it needs the resource as the API routes it.

Fix. Name the resource by its route prefix (events), router basename (events-event) or model label (events.Event). The message lists the routed resources, and karni routes lists every URL.

E902: karni why: no such user

exception · from karni.why.resolve.resolve_user; karni why --as

Why Karni objects. A decision is always for one user. --as looks the user up by primary key, login field, email or username. A recorded request names its user by primary key.

Fix. Pass --as with an email, username or primary key that exists, or --as anonymous for a request that is not signed in.

E903: karni why: no request record for that id

exception · from karni.why.resolve.load_record; karni why <status> <request-id>

Why Karni objects. The dev server records each request as .karni/requests/<request id>.json, and only while DEBUG is on. Without the record there is nothing to replay.

Fix. Reproduce the request with the dev server running (karni serve) and use its request id, or ask about the row directly: karni why <resource>/<id> --as <user> [--action ...].

E904: karni why: the request record cannot be read

exception · from karni.why.resolve.load_record

Why Karni objects. The record is not JSON, or its version or fields are not what this karni reads (version 1: request_id, method, path, status, user, ...).

Fix. Delete the file and reproduce the request. If it keeps happening, upgrade karni so the writer and the reader agree.

E905: karni why: the resource has no such field

exception · from karni.why.verdict.explain_field; karni why <resource>.<field>

Why Karni objects. A field question names a model field or a field of the resource's serializer.

Fix. Use a field name the message lists (the resource's API fields).

E906: karni why: the resource routes no such action or method

exception · from karni.why.resolve.resolve_action; karni why --action/--method

Why Karni objects. --action names a routed viewset action (or the plain words view, update, delete, create, list). --method must be one that action answers.

Fix. Use an action the message lists, or drop --method.

E907: karni why: not a Karni BaseViewSet route

exception · from karni.why.resolve.resolve_resource; karni.why.verdict.explain_record

Why Karni objects. karni why explains the decisions of Karni's access layer, which only BaseViewSet routes have. Another view's permission_classes decide on their own.

Fix. Read that view's permission_classes and get_queryset(), or move the endpoint onto a BaseViewSet with an access declaration.

E908: karni why: the question is incomplete

exception · from manage.py karni_why

Why Karni objects. A question names what (a request id after its status, <resource>/<id>, <resource>.<field> or <resource>) and, except for a recorded request, who (--as).

Fix. Follow the form the message shows, e.g. karni why events/42 --as alice@example.com, karni why 403 <request-id>, or karni why-empty events --as alice@example.com.

E920: karni replay needs DEBUG on

exception · from karni.debug.replay; manage.py karni_replay

Why Karni objects. A replay re-sends a captured request, force-authenticated as a captured user, against the configured database. That is a development tool. With DEBUG off it could act as any user on a production database, so Karni refuses.

Fix. Run it in development, where DEBUG is on (DEBUG=true in the environment or .env). To check a fix in production, add a test instead.

W920: RequestIdMiddleware runs after django-structlog's RequestMiddleware

system check (warning) · from karni.checks.check_request_id_middleware

Why Karni objects. django-structlog logs request_started with the X-Request-ID it finds. Karni's RequestIdMiddleware decides that id (a client's value is accepted only in development or from a trusted proxy). When it runs later, the first log lines carry a different, possibly client-chosen id than the response, tasks and history.

Fix. Move 'karni.tracing.RequestIdMiddleware' above 'django_structlog.middlewares.RequestMiddleware' in MIDDLEWARE (Karni's defaults put it first).

E921: Nothing was captured for this request id

exception · from karni.debug.trace; manage.py karni_trace, karni_replay

Why Karni objects. karni trace and karni replay read what the development capture wrote under .karni/ (requests/, trace/) plus change log entries with the id. Capture runs only with DEBUG on and KARNI_DEBUG_CAPTURE not False, keeps the newest KARNI_DEBUG_CAPTURE_KEEP records and KARNI_DEBUG_TRACE_DAYS of trace. Ids are 1-128 letters, digits, '_' and '-'.

Fix. Turn DEBUG on, repeat the request, and pass the id from its X-Request-ID response header (or last for the newest capture). Check the id has no typo.

E922: No failure snapshot with this id

exception · from karni.debug.brief; karni explain --failure; manage.py karni_failure

Why Karni objects. A failure snapshot is written to .karni/failures/ when a request or a Celery task raises an unhandled exception with DEBUG on. The newest KARNI_DEBUG_CAPTURE_KEEP are kept. A request that answered an error status without raising has none.

Fix. Use the failure id from the request record or karni trace <request-id>, a failed request's id, or last. Reproduce the failure with DEBUG on if nothing was captured.

E923: A redacted value cannot be replayed

exception · from karni.debug.replay; karni replay --set

Why Karni objects. Capture never stores passwords, tokens or other secrets: they are recorded as '[redacted]'. Replaying that literal could, for example, set a password to it, so the replay stops until the value is supplied.

Fix. Pass each value the message lists: --set <field>=<value> (a dotted path into the body, or query:<name> for a query parameter), or leave them out with --drop-redacted.

E924: The user to replay as cannot be found

exception · from karni.debug.replay; karni replay --as

Why Karni objects. A replay runs as the captured user, or the user --as names (a primary key, an email or a username). That user must exist in the database the replay uses, and the captured id must still belong to the captured email: after a reset, integer ids are reused by other users.

Fix. Pass --as with an existing user's email, username or primary key, or pass --anonymous. Do not pass both.

E940: karni queries cannot find the endpoint

exception · from karni.api.diagnose.resolve_endpoint (manage.py karni_queries)

Why Karni objects. karni queries requests the endpoint in-process, so it must resolve to a URL the project serves: a path, a routed resource (events, events/<id>) or a routed viewset (EventViewSet.list). A detail action named by its viewset needs a row the user can read.

Fix. Pass a path that karni routes lists (/api/events/), a resource prefix it shows, or resource/<id>. The message lists the routed resources or viewsets.

E941: karni queries cannot find the user (--as)

exception · from karni.api.diagnose.resolve_user (manage.py karni_queries --as)

Why Karni objects. The request runs force-authenticated as one user, named by primary key, email or username. The value matched none (or several).

Fix. Pass a user that exists in this database (the message shows a few), seed some with karni seed, or drop --as for an anonymous request.

E942: karni queries cannot build the request

exception · from karni.api.diagnose.run (manage.py karni_queries --method / --data)

Why Karni objects. --method must be an HTTP method the view answers at that URL, and --data a JSON body.

Fix. Use a method the message lists for that URL, and pass --data as JSON (--data '{"title": "Launch"}').

E943: The view raised while karni queries requested it

exception · from manage.py karni_queries

Why Karni objects. There is no query report for a request that raised. The message shows the traceback and what karni explain recognises in it.

Fix. Fix the exception the traceback names (karni explain - explains a pasted traceback), then run karni queries again.

E950: KARNI_DEMO_ACCOUNTS is invalid

system check (error) · from karni.demo.conf.accounts; karni.demo.checks.check_demo_mode

Why Karni objects. Each demo account is a dict with a login and optional label, can, roles, staff, superuser and password. Roles are a list of role names or 'all'. A login can be listed only once.

Fix. Fix the entry the message names. Example: KARNI_DEMO_ACCOUNTS = [{'login': 'customer@example.com', 'label': 'Customer', 'roles': ['customer'], 'can': 'Place orders.'}].

E951: karni_demo_boot refuses to run outside demo mode

exception · from manage.py karni_demo_boot

Why Karni objects. The boot command seeds the database with accounts that have a known password. That is right for a public demo and wrong for anything else, so it refuses while KARNI_DEMO_MODE is off and DEBUG is off.

Fix. Set KARNI_DEMO_MODE=True (the environment variable DEMO_MODE=True works too) for the public demo. Do not run it against real data.

E952: A demo setting names a function that cannot be imported

exception · from karni.demo.guard.check_request; karni.demo.reset.reseed

Why Karni objects. KARNI_DEMO_WRITE_RULE and KARNI_DEMO_SEEDER are dotted paths to a function. The path could not be imported.

Fix. Fix the dotted path (module.function), or unset the setting to use Karni's own rule.

E953: Demo mode is on and the write guard is not installed

system check (error) · from karni.demo.checks.check_demo_mode

Why Karni objects. KARNI_DEMO_MODE only changes behaviour through DemoWriteGuardMiddleware. Without it every visitor can write to the demo and to its accounts.

Fix. Add 'karni.demo.middleware.DemoWriteGuardMiddleware' (and DemoResetMiddleware) to MIDDLEWARE after Karni's stack, and 'karni.demo' to INSTALLED_APPS.

E954: Demo mode is turned off

API 400 response · from karni.demo.views.DemoInfoView

Why Karni objects. GET /api/demo/ answers only while KARNI_DEMO_MODE is on.

Fix. Set KARNI_DEMO_MODE=True for the public demo, or remove the route from urls.py.

E960: A FloatField holds money

system check (error) · from karni.fields.checks.check_money_floats

Why Karni objects. A field named like money (price, amount, total, cost, fee, subtotal, tax, balance, ...) is a FloatField. Binary floats cannot represent most cent values, so sums drift (0.1 + 0.2 != 0.3) and totals stop reconciling. No test with round numbers notices.

Fix. Use MoneyField(currency="EUR") (or currency_field="currency") from karni.fields, a PercentField for a rate, then karni make migration. If the field is not money, declare class Karni: not_money = {"field": "<what it is>"}.

E961: A MoneyField's currency is not declared

exception · from karni.fields.MoneyField; karni.fields.checks.check_field_declarations

Why Karni objects. An amount without a currency is ambiguous: 10.00 could be any currency. MoneyField needs exactly one declaration: a fixed ISO 4217 code, or the CurrencyField on the same model that holds each row's currency.

Fix. Write MoneyField(currency="EUR"), or MoneyField(currency_field="currency") with currency = CurrencyField() on the model.

E962: A float reached a MoneyField

exception · from karni.fields.MoneyField; karni.fields.quantize / allocate / split

Why Karni objects. Money is stored and computed as Decimal. A float has already lost the exact value before Karni sees it (Decimal(0.1) is 0.1000000000000000055...), so assigning one or using one in a lookup is refused rather than silently rounded.

Fix. Pass a Decimal (Decimal("9.99")), an int, or a string. Parse user input with Decimal(str), never float(str).

E963: A typed field declaration cannot work

exception · from karni.fields (PercentField, SlugField, SearchField, CountryField, CurrencyField, MoneyField); karni.fields.checks.check_field_declarations

Why Karni objects. The arguments contradict each other or name something the model lacks: bounds that do not fit max_digits, a populate_from or SearchField source that is not a field, a code outside the ISO list, an unknown rounding mode or text search configuration.

Fix. Fix the argument the message names. docs/fields.md lists every field's arguments.

E964: A field cannot work on the configured database

system check (error) · from karni.fields.checks.check_backends

Why Karni objects. The field needs PostgreSQL (an ArrayField: array columns exist nowhere else), but a database in DATABASES that migrates this model is another backend. migrate would fail with a syntax error. The check says which field instead.

Fix. Point that database at PostgreSQL, or replace the field with the portable one the message names (a JSONField holding a list instead of an ArrayField).

W964: A PostgreSQL guarantee is missing on the configured database

system check (warning) · from karni.fields.checks.check_backends

Why Karni objects. The model works on this database but without something PostgreSQL provides: exact NUMERIC storage (SQLite keeps NUMERIC as a binary float), a GIN index, the tsvector column, the E.164 CHECK, or partial unique indexes.

Fix. This is fine for tests and local development on SQLite. Run production on PostgreSQL. Silence karni.W964 where the difference is deliberate.

W965: A foreign key on a financial or audited model cascades

system check (warning) · from karni.fields.checks.check_cascades

Why Karni objects. on_delete=CASCADE on a model that holds money (a MoneyField, a money-named decimal, a payments-like model) or keeps history (Karni.audit) means hard-deleting the referenced row silently deletes those rows too: payments, refunds or audit trails vanish.

Fix. Choose on_delete deliberately: models.PROTECT (refuse while rows exist) or SET_NULL (null=True), then karni make migration. If the cascade is intended, declare it with the reason: class Karni: cascade = {"<field>": "<why>"}.

E966: A PostgreSQL extension could not be created

exception · from karni.fields.extensions.ensure_extension / CreateExtension (karni.accounts 0005)

Why Karni objects. A migration needs an extension (btree_gist, pg_trgm, ...) and the database role may not create it. Trusted extensions (PostgreSQL 13+) need CREATE on the database, and the others need a superuser.

Fix. Run the SQL the message prints: CREATE EXTENSION IF NOT EXISTS <name>; as a superuser in the project's database, or, for a trusted extension, GRANT CREATE ON DATABASE "<db>" TO "<role>";. Then migrate again.

W967: A searched, filtered or ordered column has no index

system check (warning) · from karni.fields.checks.check_usage_indexes; karni schema

Why Karni objects. A routed viewset declares search_fields, filterset_fields, ordering_fields or an ordering on a column no index covers, so every such list request reads the whole table. Fast with seed data, slow in production. Only the project's own models are checked: a module indexes its own.

Fix. Add the index the message names to Meta.indexes (a SearchField for search), then run karni make migration. karni schema <app> shows what serves each column. For a table small enough to scan, silence it instead: SILENCED_SYSTEM_CHECKS = ["karni.W967"].

E968: LiveUniqueConstraint on a model without soft delete

system check (error) · from karni.fields.checks.check_field_declarations

Why Karni objects. LiveUniqueConstraint limits uniqueness to rows whose deleted_at is NULL. A model without soft delete has no deleted_at, so the constraint cannot be created.

Fix. Use models.UniqueConstraint, or inherit karni.models.BaseModel (or SoftDeleteModel).

E969: karni schema was given an unknown app or model

exception · from manage.py karni_schema (karni schema)

Why Karni objects. karni schema reports the models you name, by app label or app.Model.

Fix. Pass labels karni context lists (events, events.Event), or none for every model of your own apps.

E970: A field-layer Karni option is malformed

system check (error) · from karni.fields.checks (Karni.not_money, Karni.cascade, Karni.append_only)

Why Karni objects. Opt-outs need a reason per field so the next reader knows the choice was deliberate. append_only names columns that only grow.

Fix. Write not_money = {"field": "<what it is>"}, cascade = {"field": "<why>"}, append_only = True or a list of existing timestamp columns.

E980: A StateField change the declared lifecycle does not allow

exception · from karni.lifecycle (save(), transition(), StateField.validate, the generated serializer)

Why Karni objects. A StateField declares its states and the transitions between them. Moving a row along an undeclared transition (out of a terminal state, backwards, or to a value that is not a state) is refused before any SQL: from the ORM, the admin (a form error), the API (a 400 on the field), commands and tasks alike. The column's CHECK constraint refuses an undeclared value from raw SQL too.

Fix. Move the row to one of the legal states the message lists (instance.transition('<field>', '<state>'), or allowed_transitions('<field>') to ask), or add the transition to the field's transitions= if the lifecycle should allow it.

W980: no_overlap is not enforced on this database

system check (warning) · from karni.checks.check_guarded_models

Why Karni objects. Only PostgreSQL has EXCLUDE constraints. On SQLite (or any other backend) the NoOverlap constraint creates nothing, so overlapping rows are accepted. The StateField and CapacityField CHECK constraints do work on SQLite.

Fix. Use PostgreSQL wherever overlaps matter (production, CI). Silence karni.W980 only for a development database where accepting overlaps is fine.

E981: The row's state changed since it was loaded

exception · from karni.models.GuardedModel._do_update (karni.lifecycle.StateConflict)

Why Karni objects. A save that writes a StateField updates the row only if it still holds the state it was loaded with (UPDATE ... WHERE status = '<loaded>'). Another transaction changed it first, so nothing was written. Two concurrent transitions from one state can never both succeed. The API answers 409.

Fix. Reload the row (refresh_from_db()) and decide again from the state the message names. In a UI, show the new state and let the user retry.

E982: A new row starts in a state that is not an initial state

exception · from karni.lifecycle (save() of a new row, the generated serializer's create)

Why Karni objects. A StateField row is created in one of its initial states (default: the default state) and reaches the others through transitions, so a client cannot create an order that is already 'paid'. Karni's factories and seeders may create any state (karni.lifecycle.any_initial_state).

Fix. Create the row in an initial state and call .transition(...), list the state in initial= if rows may legitimately start there, or wrap data loading in any_initial_state(reason='...').

E983: A StateField is declared or named wrongly

exception · from karni.fields.StateField; karni.lifecycle.transition

Why Karni objects. The lifecycle must be complete and unambiguous: every state named in transitions or initial is declared, states use letters, digits, _ and - (they go into a CHECK constraint), every state is reachable, and transition() names a StateField.

Fix. Fix the declaration the message names: declare the missing state, drop the self-transition, add a transition into an unreachable state, or name the right field.

E984: The slot overlaps an existing row

exception · from karni.constraints.NoOverlap (class Karni: no_overlap)

Why Karni objects. PostgreSQL's EXCLUDE constraint refused the row because another live row of the same resource overlaps its range. The check runs in the database, so it holds under concurrency and against raw SQL. Soft-deleted rows and the states listed in ignore= never block. The API answers 409 naming the existing row.

Fix. Pick a free slot, or cancel or delete the row the message names first. Touching ranges ([10:00, 11:00) and [11:00, 12:00)) do not overlap.

E985: Not enough capacity left

exception · from karni.capacity.reserve; the CapacityField CHECK constraint

Why Karni objects. A CapacityField counts what is left of a limited resource and its CHECK keeps it at or above zero. reserve() locks the row and refuses when fewer units remain than were asked for. Lowering the total below what is already reserved is refused the same way. The API answers 409 with the resource and the remaining count.

Fix. Ask for at most the remaining count the message gives, offer another resource or a waiting list, or release reservations before lowering the total.

E986: A capacity counter is used the wrong way

exception · from karni.capacity.reserve / release; CapacityField; karni.checks

Why Karni objects. Capacity is consumed only through reserve() and release(), inside transaction.atomic() together with the write that uses it, by a positive quantity. Assigning the counter directly would let a stale instance overwrite reservations, and releasing more than was reserved means a double release.

Fix. Call reserve(resource, quantity) / release(...) inside transaction.atomic(). Change the total field to resize. Point CapacityField(total=...) at an integer field of the same model.

E987: A no_overlap declaration is invalid

system check (error) · from karni.constraints.NoOverlap; karni.checks.check_guarded_models

Why Karni objects. NoOverlap takes the resource field(s) and then the range: a range field (DateTimeRangeField, DateRangeField) or a (start, end) pair of date, date-time or number fields. ignore= must name model fields and, for a StateField, declared states.

Fix. Fix the declaration the message names, e.g. no_overlap = NoOverlap('room', 'during', ignore={'status': ['cancelled']}).

E988: A guarded field on a model without GuardedModel

system check (error) · from karni.checks.check_guarded_models

Why Karni objects. StateField, CapacityField and NoOverlap rely on karni.models.GuardedModel for the loaded-state tracking, the conditional UPDATE, the transition history and the named conflicts. Without it saves would skip all of that silently.

Fix. Inherit karni.models.BaseModel (which includes GuardedModel), or add karni.models.GuardedModel to the model's bases.

E990: A value is outside the bounds of its field

exception · from karni.rules (class Karni: bounds); the API's serializer limits

Why Karni objects. class Karni: bounds gives a number, date or datetime field its lowest and highest value ($now and $today for dates). A value written new or changed outside them is refused before any SQL: from the API (a 400 on the field), the admin (a form error) and the ORM. A value that was stored before the rule existed is not checked again until it changes.

Fix. Send a value inside the bounds the message names, or change the bound in class Karni (karni.yaml: bounds) if the rule is wrong.

E991: A row with the same values already exists

exception · from karni.rules (class Karni: unique); karni.rules.UniqueRule

Why Karni objects. class Karni: unique makes the fields unique among the live rows (and, with where, among the rows that match it), with a partial unique index PostgreSQL and SQLite enforce. Karni checks it before the write (a 400 on the first field), and the index refuses a duplicate that two requests write at the same moment (a 409).

Fix. Change one of the values, or cancel or delete the row that holds them first.

E993: A relation points at a row its rule does not allow

exception · from karni.rules (class Karni: targets)

Why Karni objects. class Karni: targets says which rows a foreign key may point at: a row filter on the target, with $me (the signed-in user), $now, $today and $<field> (a field of the row being written, so two relations agree). A key that points elsewhere is refused with a 400 on the field.

Fix. Point the field at a row that matches the filter the message names (an active listing, a course of yours, a contact of the deal's company).

E994: A field cannot change

exception · from karni.rules (class Karni: frozen)

Why Karni objects. class Karni: frozen names fields that are set on create and never change (true), or that cannot change while the stored row matches a row filter (a won deal's value). Changing one would break what was decided from it (a reserved place, a paid amount).

Fix. Leave the field as it is, or create a new row (a new booking for another slot).

E995: The row cannot be deleted now

exception · from karni.rules (class Karni: delete)

Why Karni objects. class Karni: delete keeps a row while related rows point at it (blocked_by) or while it is not in a deletable state (when). Deleting it would leave orphans or erase a record that money or people depend on. The API answers 409.

Fix. Delete or move the related rows the message counts first, or move the row to a state where it may be deleted (cancel it).

E996: A move into a state misses what it needs

exception · from karni.rules (class Karni: moves)

Why Karni objects. class Karni: moves says what a move into a state (or a boolean becoming true) requires: fields that must hold a value (a lost reason) and related rows that must exist (a lesson before publishing). The move is refused with a 400 naming the field.

Fix. Send the field the message names with the move, or add the related row first.

exception · from karni.api.actions (RowAction, the viewset's row_actions; karni.yaml: actions)

Why Karni objects. A row action (pay, cancel, ship) declares the states it may run from. Called in another state it is refused with a 409 naming the state and the legal ones. An action that moves the row (to=) and finds it already there answers 200 and changes nothing, so calling it twice is safe.

Fix. Reload the row and offer only the actions x-karni-actions lists for its state.

E998: A rule of class Karni is declared wrongly

system check (error) · from karni.rules.rules_of; karni.checks.check_rules

Why Karni objects. bounds, unique, targets, frozen, delete and moves must name fields and relations the model has, with values of the right kind, so a rule never silently checks nothing.

Fix. Fix the declaration the message names (karni.yaml: the entity's key of that name).

Suggestions (SUG)

karni check, karni doctor and karni suggest print these after the errors and warnings. A suggestion never fails a run or changes an exit code. Each one names the file and line and the exact change. Silence one with # karni: allow(<rule>): <reason>, or all of them with KARNI_SUGGESTIONS = False. See suggestions.

SUG001: A foreign key to itself, named like a parent, is a hand-written tree

suggestion · from karni.suggestions.suggest_tree_models

Why Karni objects. A model with a foreign key to itself named like a parent (category_parent, parent_category) is a tree written by hand: it has no cycle-safe queries, no tree endpoints and no tree UI. The hand-written-tree architecture rule fails on the names parent and parent_*, so this suggestion covers the other names.

Fix. Inherit karni.models.TreeModel first (class Category(TreeModel, BaseModel)), drop the field and run karni makemigrations. Silence it with a comment on the field line: # karni: allow(suggest-tree-model): <reason>.

SUG002: A text field that holds markdown is not a MarkdownField

suggestion · from karni.suggestions.suggest_markdown_fields

Why Karni objects. A TextField named *_markdown or *_md, or whose help text says markdown, holds markdown. The API publishes it as plain text, so @karni/ui shows the raw markup.

Fix. Use karni.fields.MarkdownField in its place and run karni makemigrations: it is a TextField in the database, so no data changes. Silence it with # karni: allow(suggest-markdown): <reason>.

SUG003: Raw SQL with GROUP BY, opted out of the raw-sql rule, is an aggregate

suggestion · from karni.suggestions.suggest_aggregate

Why Karni objects. Two or more raw SQL queries with GROUP BY carry a karni: allow(raw-sql) opt-out. Grouped counts and sums are what a model's aggregate declaration gives a resource, under the list's filters and access.

Fix. Declare class Karni: aggregate = {'group_by': [...], 'values': [...]} on the model and call GET <resource>/aggregate/?group_by=... (docs/aggregations.md). Silence one query with # karni: allow(suggest-aggregate): <reason> on its line.

SUG004: Three models with a many-to-many to one tree model need a taxonomy

suggestion · from karni.suggestions.suggest_taxonomies

Why Karni objects. Each model tagged to the same tree model (a region tree, a category tree) needs the same filters, facet counts, import columns and access rule, written once per model.

Fix. Declare class Karni: taxonomies = {'region': 'geo.Region'} on each model and drop its many-to-many (a many-to-many you keep is adopted). Silence a model with # karni: allow(suggest-taxonomy): <reason> on its field line.

SUG005: An added module nothing in the project uses

suggestion · from karni.suggestions.suggest_unused_modules

Why Karni objects. The module is in INSTALLED_APPS, and no project file imports it or renders its templates, no URL beyond the one karni add wrote refers to it, and none of its settings differs from its default. It costs a dependency and, for some, a service.

Fix. Run karni remove <name>. It never drops data: it counts each table's rows and stops until you pass --keep-tables or migrate the app to zero. Silence it with # karni: allow(suggest-unused-module): <reason> on its line in config/settings.py.

SUG006: A module the spec or the README describes is not added

suggestion · from karni_cli.suggest.module_suggestions

Why Karni objects. A phrase of a module's use_when list (payments, PDF reports, a public website) appears in karni.yaml or the README, and the module is not added. In the README only a phrase of two words or more counts, because single words (checkout, payments) mean other things there.

Fix. Run karni modules show <name> to read what it does, then karni add <name>. Silence it with # karni: allow(suggest-add-module): <reason> on the line (in the README inside <!-- ... -->).

SUG007: The project drifted from karni.yaml

suggestion · from karni_cli.suggest.drift_suggestions

Why Karni objects. karni plan is not empty: the project and the spec say different things, so the next karni build would change the project, or the spec is out of date.

Fix. Read karni plan. Run karni build to bring the project to the spec, or karni spec export -o karni.yaml to take the code's side. Silence it with # karni: allow(suggest-sync-spec): <reason> on the first line of karni.yaml.

AI (AI)

AI001: KARNI_AI_PROVIDER is not set

system check (error) · from karni_ai.checks (and providers.base.get_provider)

Why Karni objects. karni-ai has no default provider: every extraction goes through the one the project names.

Fix. Set KARNI_AI_PROVIDER to 'anthropic', 'openai' or 'test' (in .env, or in karni.yaml as modules: ai: provider), or to the dotted path of a karni_ai.providers.base.Provider subclass.

AI002: KARNI_AI_PROVIDER cannot be loaded

exception · from karni_ai.providers.base.get_provider

Why Karni objects. The setting names something that is not a shortcut and does not import as a Provider subclass.

Fix. Use 'anthropic', 'openai' or 'test', or the dotted path of a karni_ai.providers.base.Provider subclass.

AI003: The provider's SDK is not installed

system check (error) · from karni_ai.providers (anthropic, openai)

Why Karni objects. Provider SDKs are optional extras, so a project installs only the one it uses.

Fix. Install the extra: pip install 'karni-ai[anthropic]' or 'karni-ai[openai]'.

AI004: The provider's API key is not set

system check (error) · from karni_ai.providers (anthropic, openai)

Why Karni objects. The provider cannot answer without its key. The key comes from the environment only, never from code or karni.yaml.

Fix. Set ANTHROPIC_API_KEY or OPENAI_API_KEY in the environment (.env in development). Use the 'test' provider for local work and CI without a key.

AI005: The provider's model name is not set

system check (error) · from karni_ai.providers (anthropic, openai)

Why Karni objects. karni-ai has no default model: model names change, and the choice of one is a cost and quality decision for the project.

Fix. Set ANTHROPIC_MODEL or OPENAI_MODEL in the environment to the model the provider should use.

AI006: The provider call failed

API 400 response · from karni_ai.providers (answered with HTTP 502)

Why Karni objects. The provider refused the request, timed out or could not be reached. The call is logged with this code and nothing is previewed.

Fix. Read the message for the provider's own reason (a rate limit, a bad key, an unknown model). Raise KARNI_AI_TIMEOUT for slow answers.

AI007: The model's answer cannot be used

API 400 response · from karni_ai.providers (answered with HTTP 502)

Why Karni objects. The model declined, its answer was cut off at KARNI_AI_MAX_OUTPUT_TOKENS, or it was not the JSON the schema asks for.

Fix. Send a shorter source, raise KARNI_AI_MAX_OUTPUT_TOKENS, or try another model.

AI008: The resource cannot be extracted into

API 400 response · from karni_ai.extraction (answered with HTTP 400)

Why Karni objects. Extraction ends in the resource's import preview, so it needs a routed BaseViewSet whose import is on and whose model is writable.

Fix. Name the resource by its router prefix (products, not Product), and keep its viewset's import_data on.

AI009: You may not create rows of this resource

API 400 response · from karni_ai.extraction (answered with HTTP 403)

Why Karni objects. Only a user the resource's access declaration lets create may extract into it, so nobody spends tokens on rows they could never save.

Fix. Ask for a role the resource's create access admits.

AI010: The source cannot be read

API 400 response · from karni_ai.sources (answered with HTTP 400)

Why Karni objects. Give exactly one of text, url or file. The text has a size limit (KARNI_AI_MAX_SOURCE_CHARS), and a file must be a PDF with text in it, within KARNI_AI_MAX_UPLOAD_BYTES and KARNI_AI_MAX_PDF_PAGES.

Fix. Send one source within the limits. A scanned PDF needs text recognition first.

AI011: The URL is refused

API 400 response · from karni_ai.services.fetch (answered with HTTP 400)

Why Karni objects. A URL the server fetches must not reach the server's own network: only http and https, no user name or password, a port of KARNI_AI_FETCH_PORTS, a public address, and every redirect checked the same way, at most KARNI_AI_FETCH_MAX_REDIRECTS of them.

Fix. Use a public http or https address. Paste the text instead for a page on a private network.

AI012: The URL's response is refused

API 400 response · from karni_ai.services.fetch (answered with HTTP 400)

Why Karni objects. The response was larger than KARNI_AI_FETCH_MAX_BYTES, slower than KARNI_AI_FETCH_TIMEOUT, an HTTP error, or not HTML, plain text or a PDF.

Fix. Download the document and send it as a file, or paste its text.

AI013: Your monthly token budget is spent

API 400 response · from karni_ai.usage (answered with HTTP 429)

Why Karni objects. KARNI_AI_MONTHLY_TOKENS_PER_USER caps the tokens one user spends in a calendar month.

Fix. Wait for the next month, or ask for the budget to be raised.

AI014: The project's monthly token budget is spent

API 400 response · from karni_ai.usage (answered with HTTP 429)

Why Karni objects. KARNI_AI_MONTHLY_TOKENS caps the tokens the whole project spends in a calendar month.

Fix. Wait for the next month, or raise KARNI_AI_MONTHLY_TOKENS.

AI015: The resource has no field extraction can fill

API 400 response · from karni_ai.schema (answered with HTTP 400)

Why Karni objects. Extraction fills text, number, date, choice and boolean fields, and relations to a model with a natural key. Files, JSON and relations without a natural key are left out.

Fix. Give the related model a natural key (class Karni: natural_key = 'name'), or import the resource from a file.

AI016: KARNI_AI_EXTRACTOR or KARNI_AI_FETCHER cannot be loaded

exception · from karni_ai.extraction.get_extractor, karni_ai.sources

Why Karni objects. Both settings are escape hatches: dotted paths to a subclass of the class they replace.

Fix. Point KARNI_AI_EXTRACTOR at a karni_ai.extraction.Extractor subclass and KARNI_AI_FETCHER at a karni_ai.services.fetch.Fetcher subclass, or remove the setting.

APR (APR)

APR001: The change was sent for approval instead of being written

API 400 response · from karni_approvals.interception

Why Karni objects. The model declares requires_approval and the change touches a guarded field, so a pending change holds it until a second person approves. The API answers 202 with the pending change, the admin says so, and code gets KarniWriteDeferred.

Fix. Nothing is wrong. Have a checker approve it (the admin queue, /api/pending-changes/, <ApprovalsQueue/>). Trusted code may write inside karni_approvals.interception.bypass(reason=...).

APR002: The maker cannot be the checker

API 400 response · from karni_approvals.services.decide

Why Karni objects. Second-person approval means a second person: the user who proposed a change may never approve or reject it, through the API, the admin or a direct call.

Fix. Ask another holder of the approve permission to decide it.

APR003: This user may not decide this pending change

API 400 response · from karni_approvals.services.decide

Why Karni objects. Deciding needs the karni_approvals.pendingchange:approve (or :reject) grant, the model's approver_roles when it declares them, and the row inside the checker's own scope.

Fix. Grant the permission in KARNI_ROLES (or the permission matrix), assign the approver role, or have someone whose scope covers the row decide.

APR004: This checker has already decided this change

API 400 response · from karni_approvals.services.decide

Why Karni objects. One decision per person per change. A second one would count twice.

Fix. Another checker must supply the remaining approvals.

APR005: The pending change is no longer pending

API 400 response · from karni_approvals.services.decide

Why Karni objects. It was already approved, rejected, expired or failed, and decisions are final.

Fix. Propose the change again if it is still wanted.

APR006: The change could not be applied: the row changed since it was proposed

API 400 response · from karni_approvals.services.apply

Why Karni objects. Every recorded old value must still be current when the change is applied, or an approval would overwrite something nobody reviewed.

Fix. Propose the change again against the row as it is now.

APR007: The model's approval policy is malformed

system check (error) · from karni_approvals.meta.approval_policy

Why Karni objects. requires_approval, approvals_required, approver_roles, approval_timeout and approval_on_timeout are read at boot. A typo would silently hold or release changes.

Fix. Set requires_approval to True or a list of field names, approvals_required to a positive int, approver_roles / approval_escalation_roles to lists of KARNI_ROLES slugs, approval_timeout to a timedelta or hours, and approval_on_timeout to 'expire' or 'escalate'.

CHART (CHART)

CHART001: The chart's source is not a resource with an aggregation

exception · from karni_charts.services.source_viewset

Why Karni objects. A chart reads its data through the source resource's aggregate action, so the source must be a routed resource whose model declares class Karni: aggregate (or whose viewset declares aggregation).

Fix. Pick one of the sources the admin offers, or declare an aggregation on the model the chart should read: class Karni: aggregate = {'group_by': [...], 'values': [...]}.

CHART002: A filter the chart does not allow

API 400 response · from karni_charts.services.chart_filters

Why Karni objects. A viewer may narrow a saved chart only with the filters its allowed_filters lists. The default_filters always apply.

Fix. Send only the filters the chart allows, or add the filter's name to the chart's allowed_filters in the admin.

CHART003: The chart's filters are not valid

exception · from karni_charts.models.Chart.clean

Why Karni objects. default_filters maps a list filter to a value or a list of values, and allowed_filters lists the names of list filters. The aggregate's own parameters (group_by, metric, value, top, stack, series) are the chart's axes, never filters.

Fix. Write default_filters as {"channel": "online"} and allowed_filters as ["channel", "launched_on__gte"].

CHART004: The chart's axes do not fit the source's aggregation

exception · from karni_charts.models.Chart.clean

Why Karni objects. The x axis, the metric and value of the y axis and the z axis must be ones the source's aggregation declares (karni.aggregation). The message quotes the source's own refusal, with its E38x code.

Fix. Choose a group, metric and value the source declares, or add them to the source model's class Karni: aggregate.

COM (COM)

COM001: karni-commerce is installed without the people contract

system check (error) · from karni_commerce.checks.people_installed (karni.COM001)

Why Karni objects. Every order names the person who bought it (Order.person, found or made by karni.people.resolve at checkout), so the customers list, the person facts and the timeline are the same person in every part. Without karni.people the order table cannot be created.

Fix. Set KARNI_PEOPLE = True above karni_settings(globals()) in config/settings.py (karni build writes it when karni.yaml lists the commerce module, or features: {people: true}), then run migrate.

COM002: A sellable adapter does not keep the commerce contract

test failure · from karni_commerce.testing.assert_sellable

Why Karni objects. Commerce calls the adapter of every kind the same way: it holds a line at checkout, lets it go when the order is not paid, takes it when paid and gives it back on a refund. An adapter that prices, holds or releases wrongly sells the same seat twice or loses stock.

Fix. Read the message: it names the hook and what it saw. Fix that hook of the adapter (docs/commerce.md, Selling something), then run the test again.

COM003: A sellable's hold is not a positive number of minutes

exception · from karni_commerce.sellables.hold_of (Sellable.hold_minutes)

Why Karni objects. Checkout keeps an order's items for the shortest hold of its lines, and an order not paid by then is cancelled. Zero or a negative number would cancel it before the buyer could pay.

Fix. Return None (the project's KARNI_COMMERCE_HOLD_MINUTES) or a whole number of minutes from 1 from the adapter's hold_minutes(item, options).

COM004: A sellable adapter is registered wrongly

exception · from karni_commerce.sellables.register

Why Karni objects. Commerce finds an adapter by its kind, and a cart line and an order line store that kind as a short name. register() takes a Sellable subclass whose kind is letters, digits and _.

Fix. Decorate a subclass of karni_commerce.sellables.Sellable with @register and set kind = "booking" (a short name, unique in the project).

GAME (GAME)

GAME001: karni-game is installed without the people contract

system check (error) · from karni_game.checks.people_installed (karni.GAME001)

Why Karni objects. A player is the game profile of a person (karni.people), so a guest who signs in keeps their progress and the person page, the merge and the erase see the player. Without karni.people the player table cannot be created.

Fix. Set KARNI_PEOPLE = True above karni_settings(globals()) in config/settings.py (karni build writes it when karni.yaml lists the game module), then run migrate.

GAME002: The request names no player

exception · from karni_game.api (HTTP 401)

Why Karni objects. Every save, score, wallet and progress call belongs to one player, found from the request alone: a signed-in account, or a guest's token. No endpoint takes a player's id from the client, so another player's progress is never reachable.

Fix. Sign in, or call POST /api/game/guest/ once and send its token in the X-Player-Token header (KARNI_GAME_TOKEN_HEADER).

GAME003: The guest token is unknown or revoked

exception · from karni_game.players.player_for_token (HTTP 401)

Why Karni objects. A guest token is issued once and kept as a hash. It is revoked when the guest is upgraded to an account (its progress is the account's then) and when staff revoke it.

Fix. Drop the stored token. Sign in to the account it was upgraded to, or issue a new guest with POST /api/game/guest/.

GAME004: The account has no person yet: its email is not verified

exception · from karni_game.players.player_for_user (HTTP 403)

Why Karni objects. An account is linked to a person only once its email is verified (the people contract), so nobody takes over another person's progress by signing up with their address. A player belongs to a person.

Fix. Verify the account's email (the verification link or a sign-in with an email code), then call again. Until then the game can keep playing as a guest.

GAME005: Guest play is off

exception · from karni_game.api.GuestView (HTTP 403)

Why Karni objects. The project's Settings, Games section has allow_guests off, so only signed-in accounts play.

Fix. Sign in first, or turn allow_guests on (preferences game.allow_guests).

GAME006: No active game has this slug

exception · from karni_game.api (HTTP 404)

Why Karni objects. Each path under /api/game/<game>/ names a Game row by its slug. A game that is not active answers as if it did not exist.

Fix. Use the slug of a game in the admin (Karni games, Games), or turn it active. karni load puts a game declared in a content file in the database.

GAME007: The save is larger than the game allows

exception · from karni_game.saves.write (HTTP 413)

Why Karni objects. A save is read and written whole on every sync, so each game caps its size (max_save_bytes in its settings, at most KARNI_GAME_MAX_SAVE_BYTES).

Fix. Keep less in the save (derive what can be derived), or raise the game's max_save_bytes in its settings.

GAME008: The save changed on the server: a stale write

exception · from karni_game.saves (HTTP 409)

Why Karni objects. Every write names the version it started from (base_version). Another device wrote since, so this write would lose that one's progress. The server's version counter decides, not a device's clock.

Fix. Read the server's copy in the answer's save, choose or combine, and write again with base_version set to its version.

GAME009: The save's schema version is not one the server knows

exception · from karni_game.saves.migrate (HTTP 400)

Why Karni objects. schema_version is the shape of the save's data. The server migrates an older save up to the game's save_schema_version, and cannot read a newer one: the client is ahead of the server.

Fix. Raise the game's save_schema_version (and register the migration to it) before shipping a client that writes the new shape.

GAME010: A save migration is missing

exception · from karni_game.saves.migrate

Why Karni objects. The game saves a newer schema than a stored save, and each step from one schema version to the next is a function the project registers. A missing step would hand the client data of a shape it does not read.

Fix. Register the step in <app>/game.py: @hooks.save_migration("<game>", n) on a function that takes the data of version n and returns the data of n + 1.

GAME011: Not a slot name, or no free slot

exception · from karni_game.saves (HTTP 400)

Why Karni objects. A slot is named in the path (a lowercase letter or digit, then up to 39 more, _ or -), and each game keeps at most max_slots slots per player.

Fix. Use a slot name such as main or slot-2, or write to a slot the player has.

GAME012: No active board has this key in the game

exception · from karni_game.scores.find_board (HTTP 404)

Why Karni objects. A score goes to one board of one game, named by its key in the path. A board that is not active answers as if it did not exist.

Fix. Use the key of one of the game's boards (GET /api/game/<game>/ lists them), or turn the board active in the admin.

GAME013: The score is outside the board's plausible range

exception · from karni_game.scores.submit (HTTP 400)

Why Karni objects. A client can send any number, so each board names the lowest and the highest score a real run can make (min_value, max_value), and refuses the rest.

Fix. Send the score the run made. When real runs go beyond the range, widen the board's min_value or max_value.

GAME014: The run is missing, too large, or does not check out

exception · from karni_game.scores.submit (HTTP 400)

Why Karni objects. A board may ask every score for its run (the seed and the input log a deterministic game replays), a daily board for a run on the day's seed, and the project's run check may refuse a run.

Fix. Send run: {seed, inputs, duration_ms} with the score, use today's seed (GET /api/game/<game>/daily/) on a daily board, and keep the run under KARNI_GAME_MAX_RUN_BYTES.

GAME015: Too many requests of this kind

exception · from karni_game.throttling.PlayerRateThrottle (HTTP 429)

Why Karni objects. Writes are limited per player (KARNI_GAME_RATES), so a script cannot flood the boards, the wallet or the events.

Fix. Wait retry_after seconds (the Retry-After header) and send it again, or raise the scope's rate in KARNI_GAME_RATES.

GAME016: Not enough of the currency

exception · from karni_game.wallet.change (HTTP 409)

Why Karni objects. A balance never goes below 0. The wallet row is locked and written with a conditional update, so two purchases at once never spend the same coins.

Fix. Earn more first: the answer has balance and needed.

GAME017: The reward is not available now

exception · from karni_game.rewards (HTTP 409)

Why Karni objects. Each reward says how often a player may have it: once a day for a daily reward, per_day claims in one of the game's days, and cooldown seconds between two.

Fix. Ask again at next_at (the answer has it), or raise the reward's per_day or lower its cooldown.

GAME018: The client does not claim this reward

exception · from karni_game.rewards (HTTP 403)

Why Karni objects. Only an ad reward of trust client is claimed by the client. A daily reward comes with the check-in, a mission's and an achievement's with their progress, a match's with the realtime server's report, and an ad reward of trust callback only when the portal's server calls back, signed.

Fix. Use the path the reward's kind has (docs/game-api.md, Rewards). For an ad reward of trust callback: POST rewards/<key>/intent/ and hand the intent to the portal.

GAME019: A server-to-server request does not verify

exception · from karni_game.signatures.HmacVerifier (HTTP 403)

Why Karni objects. A portal's callback and a realtime server's report change balances and boards, so each is signed with a shared secret over its exact body, with a timestamp that stops a replay.

Fix. Sign the raw body: X-Karni-Timestamp and X-Karni-Signature: sha256=<HMAC-SHA256 of '<timestamp>.' + body> with the secret in KARNI_GAME_PORTALS or KARNI_GAME_SERVER_SECRET, and keep the clocks within KARNI_GAME_SIGNATURE_TOLERANCE seconds.

GAME020: The intent token is not valid

exception · from karni_game.rewards.from_callback (HTTP 400)

Why Karni objects. An ad reward's callback names the player and the reward by the intent this server signed (POST rewards/<key>/intent/), valid for KARNI_GAME_AD_INTENT_SECONDS.

Fix. Hand the portal a fresh intent before each ad, and send it back unchanged.

GAME021: No such item for sale

exception · from karni_game.shop (HTTP 404)

Why Karni objects. The shop sells the game's active items that have a currency and a price.

Fix. Use the key of an item GET shop/ lists with a price, or give the item a currency and a price in the admin.

GAME022: The player owns the item already

exception · from karni_game.shop (HTTP 409)

Why Karni objects. A cosmetic is owned once, so a second purchase would take currency for nothing.

Fix. Equip it instead (POST items/<item>/equip/).

GAME023: The player does not own the item

exception · from karni_game.shop (HTTP 409)

Why Karni objects. Only an item the player owns is worn.

Fix. Buy it first (POST shop/<item>/buy/), or earn it.

GAME024: A progress event the game does not count

exception · from karni_game.progress.report (HTTP 400)

Why Karni objects. Progress is counters the game reports, and the server unlocks from them. A counter no active achievement or mission counts, or an amount past the game's max_progress_step, would let a client invent progress or jump to a goal.

Fix. Report the counters the game's achievements and missions name (GET achievements/ and missions/ list them), in amounts from 1 to max_progress_step. The answer's index names the event.

GAME025: An analytics event the game does not declare

exception · from karni_game.config.track (HTTP 400, or 202 with rejected)

Why Karni objects. Analytics events go through the family events to the project's own analytics, so each game declares the events it sends and their props (analytics in its settings). An undeclared event or prop, a wrong type or a long text is refused, so a client cannot fill the analytics with anything.

Fix. Declare the event in the game's settings: analytics: {"level_done": {"level": "int"}}, and send at most 10 props of those types.

GAME026: A game's settings do not validate

exception · from karni_game.models.Game.clean (karni_game.settings.GameSettings)

Why Karni objects. A game's settings (its time zone, save limits, streak grace, analytics schema) are read on every call. A value the server cannot use is refused when it is saved, not when a player meets it.

Fix. Read the message: it names each field and what it takes (docs/game.md, Game settings).

GAME027: Multiplayer is not set up

exception · from karni_game.multiplayer.secret (HTTP 503)

Why Karni objects. A realtime server verifies the player token and signs its reports with the secret it shares with the project. Without one, no token could be trusted.

Fix. Set KARNI_GAME_SERVER_SECRET in the environment (a long random string) and give the same value to the realtime server.

GAME028: The guest cannot be upgraded to this account

exception · from karni_game.players.upgrade (HTTP 409)

Why Karni objects. An upgrade merges a guest's person into the account's person, and the guest's progress into the account's player. It needs a guest token, a guest (not an account already), and two people the people contract can merge.

Fix. Send the guest's token in X-Player-Token (or guest_token) with a signed-in, verified account. The message names the reason a merge was refused.

GAME029: The player is banned from the boards

exception · from karni_game.scores.submit, karni_game.multiplayer (HTTP 403)

Why Karni objects. Staff banned the player (Game moderator, ban): their scores no longer count, they are on no board and get no realtime token. Their saves and wallet stay theirs.

Fix. Staff unban the player in the admin or with POST /api/game-players/<id>/unban/.

GAME030: karni_game.urls is not included

system check (error) · from karni_game.checks.run_checks

Why Karni objects. The game API (guest tokens, saves, scores, the wallet) is mounted by one include line. Without it the client's calls answer 404.

Fix. Add path("api/game/", include("karni_game.urls")) to config/urls.py, before path("api/", include("karni.api.urls")).

GAME031: A real-money item is sold through the cart

exception · from karni_game.shop.buy (HTTP 400)

Why Karni objects. Real money goes through karni-commerce (the sellable kind game_item), with its checkout, payments and refunds. A soft currency never buys it.

Fix. Add it to the cart: POST /api/carts/current/lines/ with kind game_item and the item's id, signed in. The item is the player's once the order is paid.

GAME032: A game hook is registered wrongly

exception · from karni_game.hooks (save_migration, run_check)

Why Karni objects. A save migration is one step from a schema version (a whole number from 1) to the next, and each game has one step per version and one run check per board, so the server knows which code runs.

Fix. Register one function per step (@hooks.save_migration("<game>", 1)) and per board (@hooks.run_check("<game>", "<board>")), or pass replace=True to swap one.

GAME033: The intent was used already with another request

exception · from karni_game.intents.once (HTTP 409)

Why Karni objects. An intent names one action, so a retry of a score, a claim or a purchase never counts twice. A second action under the same intent would be lost.

Fix. Make a new intent (a UUID) for each new action, and send the same body when you retry one.

GAME035: A match report names what the game does not have

exception · from karni_game.multiplayer.report (HTTP 400)

Why Karni objects. A report is recorded whole or not at all, so each row must name a player the server knows (the token's sub), an active board of the game with a whole-number value, and active rewards of kind match.

Fix. Read index in the answer: it is the row. Send the player's id from the token, and the keys of the game's boards and match rewards.

GAME036: A score's played_at is outside the window the server trusts

exception · from karni_game.scores.played_time (HTTP 400)

Why Karni objects. A score played offline names when it was played, so it lands on that day's and week's boards and a daily board takes that day's seed. The device's clock is trusted only that far back (KARNI_GAME_PLAYED_AT_WINDOW) and a minute ahead, so a changed clock cannot reach an old or a future board.

Fix. Send queued scores sooner, send this one without played_at (it counts now), or widen KARNI_GAME_PLAYED_AT_WINDOW.

GAME037: The player has no save in this slot

exception · from karni_game.saves.empty (HTTP 404)

Why Karni objects. A slot the player never wrote, or deleted, has no save. The code tells it from a path that does not exist, so a client knows to start the slot (base_version 0).

Fix. Write the slot with base_version 0, or read GET saves/ for the slots the player has.

GAME038: Other origins may call the game API, and the browser cannot send its token

system check (error) · from karni_game.checks.run_checks

Why Karni objects. A portal build of a game runs on the portal's domain and calls the game API with a token (X-Player-Token, or an account's JWT), never cookies. The browser sends the token's header only when CORS_ALLOW_HEADERS names it. Cookies never sign in across origins: the game views drop the session for such a call.

Fix. Set CORS_ALLOW_HEADERS = (*default_headers, "x-player-token") (from corsheaders.defaults), or empty KARNI_GAME_CORS_ORIGINS.

IMP (IMP)

IMP001: Impersonation needs the explicit impersonate permission

API 400 response · from karni_impersonation.services.start

Why Karni objects. Staff or admin status never implies the right to act as someone else. Only a role granted karni_impersonation.impersonationsession:impersonate may start a session.

Fix. Grant the permission to the support role in KARNI_ROLES (or the permission matrix).

IMP002: The target holds something the impersonator does not

API 400 response · from karni_impersonation.services.privilege_gap

Why Karni objects. Impersonation must never escalate privileges: a target who is a superuser, is staff, or holds any grant or Django permission the impersonator lacks cannot be impersonated.

Fix. Impersonate from an account that holds at least everything the target holds, or ask such a person to.

IMP003: A reason is required to impersonate

API 400 response · from karni_impersonation.services.start

Why Karni objects. KARNI_IMPERSONATION_REQUIRE_REASON is on (the default for customer data): the reason is recorded with the session and sent to the impersonated user.

Fix. Give a reason, or set KARNI_IMPERSONATION_REQUIRE_REASON = False for a project that does not need one.

IMP004: This user cannot be impersonated now

API 400 response · from karni_impersonation.services.start

Why Karni objects. You cannot impersonate yourself or an inactive account, or start a second session while one is running.

Fix. Stop the current session first, or pick another user.

IMP005: This request is not part of an impersonated session

API 400 response · from karni_impersonation.viewsets.ImpersonationSessionViewSet.stop

Why Karni objects. stop/ ends the session the request belongs to, and there is none (it ended, expired or never started).

Fix. Nothing to do: you are yourself.

IMP006: This action is blocked while impersonating

API 400 response · from karni_impersonation.vetoes, karni_impersonation.middleware

Why Karni objects. KARNI_IMPERSONATION_BLOCKED names what an impersonator may never do (deleting, exporting, payment changes, credential changes by default), whatever the target may.

Fix. Stop impersonating and do it as yourself, or ask the user to. A project narrows the list in KARNI_IMPERSONATION_BLOCKED.

IMP007: karni-impersonation is installed but not wired

system check (error) · from karni_impersonation.checks

Why Karni objects. The middleware resolves the impersonated session, enforces the limit and injects the banner. The URL include serves the banner's exit. Without them sessions start but nothing acts on them.

Fix. Add 'karni_impersonation.middleware.ImpersonationMiddleware' after AuthenticationMiddleware in MIDDLEWARE and path('impersonation/', include('karni_impersonation.urls')) to config/urls.py.

IMP008: KARNI_IMPERSONATION_BLOCKED is malformed

system check (error) · from karni_impersonation.checks

Why Karni objects. The blocked list is matched on every gate, so a non-string entry would silently match nothing.

Fix. Use strings: action names, 'app.model', 'app.model:action' patterns, or '/path/*'.

karni-payments (PAY)

PAY001: KARNI_PAYMENTS_PROVIDER cannot be loaded

exception · from karni_payments.providers.base.get_provider

Why Karni objects. Every checkout, refund and webhook goes through the configured provider class.

Fix. Set KARNI_PAYMENTS_PROVIDER to a shortcut ('stripe', 'razorpay', 'test') or the dotted path of a karni_payments.providers.base.PaymentProvider subclass.

PAY002: No payment provider has that name

exception · from karni_payments.providers.base.get_provider_by_name

Why Karni objects. Webhooks and stored payments name the provider that handled them.

Fix. Use the configured provider's name or a shortcut: stripe, razorpay, test.

PAY003: The payment provider's SDK is not installed

exception · from karni_payments.providers (stripe, razorpay)

Why Karni objects. Provider SDKs are optional extras so a project installs only the one it uses.

Fix. Install the extra: pip install 'karni-payments[stripe]' or 'karni-payments[razorpay]'.

PAY004: The payment provider's API credentials are not set

exception · from karni_payments.providers (stripe, razorpay)

Why Karni objects. The provider cannot create checkouts or refunds without its API keys.

Fix. Set STRIPE_SECRET_KEY (Stripe) or RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET (Razorpay) in the environment (.env in development). Use the 'test' provider for local work without keys.

PAY005: The webhook signing secret is not set

exception · from karni_payments.providers (stripe, razorpay)

Why Karni objects. Unverified webhooks could mark any payment as paid, so Karni refuses them.

Fix. Set STRIPE_WEBHOOK_SECRET or RAZORPAY_WEBHOOK_SECRET to the secret shown in the provider's dashboard for this webhook endpoint.

PAY006: A webhook failed signature verification

exception · from karni_payments.webhooks (answered with HTTP 400, never stored)

Why Karni objects. The payload was not signed with this endpoint's secret: a forged request, or a secret that does not match the provider's dashboard.

Fix. If the webhook is genuine, copy the endpoint's signing secret from the provider's dashboard into the *_WEBHOOK_SECRET setting. Otherwise nothing to do: the request was rejected.

PAY007: The currency or amount cannot be charged exactly

exception · from karni_payments.providers.base.to_minor_units

Why Karni objects. Providers charge integer minor units (cents). Karni never rounds money silently, and 3-decimal currencies are not supported yet.

Fix. Round the amount to the currency's minor unit before charging (e.g. Decimal('10.50')), and charge in a 0- or 2-decimal currency.

PAY008: A checkout redirect URL points at an origin that is not allowed

API 400 response · from karni_payments.services.create_checkout

Why Karni objects. An open redirect after payment would let attackers send customers anywhere.

Fix. Redirect to your frontend (KARNI_FRONTEND_URL), or add the origin to KARNI_PAYMENTS_ALLOWED_REDIRECTS.

PAY009: A webhook event matches no local payment

exception · from karni_payments.services (webhook processing task)

Why Karni objects. Providers can deliver a webhook before the checkout that created the payment is committed. The task retries instead of dropping the event.

Fix. Usually nothing: the retry succeeds. If it keeps failing, the payment was created outside Karni (or in another environment sharing the webhook): check the provider ids in the message.

REPORT (REPORT)

REPORT001: No report has that name

exception · from karni_reports.registry.get_report (the endpoints answer it with HTTP 404)

Why Karni objects. A report is requested by the name its class declares, and none is registered under this one.

Fix. Use a name manage.py karni_pregenerate --list prints, or declare the report in <app>/reports.py with @register.

REPORT002: A report declaration is incomplete

exception · from karni_reports.registry.register

Why Karni objects. A report prints rows of one model through one template, so both must be named.

Fix. Set model to a model class and template to a template name on the Report subclass, and give it a name of lowercase letters, digits, - and _.

REPORT003: Two reports have the same name

exception · from karni_reports.registry.register

Why Karni objects. The name is the report's address in the API, so it must be unique.

Fix. Give one of them another name.

REPORT004: No viewset serves the report's model

system check (error) · from karni_reports.report.Report.get_viewset and karni check

Why Karni objects. Who may see a row's report is decided by who may retrieve the row through its model's viewset. Without one, nobody can be checked, so the report is refused.

Fix. Add a BaseViewSet for the model (karni make viewset <Model>), or set viewset on the Report to the viewset class or its dotted path.

REPORT005: KARNI_REPORTS_RENDERER cannot be loaded

exception · from karni_reports.rendering.get_renderer

Why Karni objects. Every report goes through the configured renderer to become a PDF.

Fix. Set KARNI_REPORTS_RENDERER to 'weasyprint', 'fake' (tests) or the dotted path of a karni_reports.rendering.Renderer subclass.

REPORT006: WeasyPrint or the system libraries it needs are missing

exception · from karni_reports.rendering.WeasyPrintRenderer

Why Karni objects. WeasyPrint draws the PDF with Pango, which is a system library, not a Python package.

Fix. Install Pango: apt-get install libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b fonts-dejavu-core (Debian, Ubuntu), apk add pango font-dejavu (Alpine) or brew install pango (macOS). Set KARNI_REPORTS_RENDERER = 'fake' in tests.

REPORT007: A report failed to render

exception · from karni_reports.services.render (stored on the GeneratedReport row)

Why Karni objects. The template, the report's get_context or the renderer raised. The row keeps the error and the API answers status 'failed'.

Fix. Read the error on the row in the admin (Generated reports, filter by status failed), fix the template or get_context, then use the Regenerate action or request the report again.

REPORT008: No file is ready for this report and row yet

exception · from karni_reports.viewsets.GeneratedReportViewSet.download_report (answered with HTTP 404)

Why Karni objects. The download serves a rendered file. This row's report was never requested, or is still rendering, or failed.

Fix. POST /api/reports/<report>/<id>/ to request it, poll its status/ until it says ready, then download.

REPORT009: A template referenced a URL the renderer does not fetch

exception · from karni_reports.rendering.WeasyPrintRenderer (logged as a warning, the URL is left out of the PDF)

Why Karni objects. Fetching any URL while rendering would let a value in a row make the server call another host. The renderer reads only data: URLs and files under STATIC_URL and MEDIA_URL, and leaves the rest out of the PDF.

Fix. Serve the image or stylesheet from your static or media files, or subclass WeasyPrintRenderer with allow_network = True and name it in KARNI_REPORTS_RENDERER.

REPORT010: A report's template does not exist

system check (error) · from karni_reports.checks.run_checks

Why Karni objects. Every render loads the template, so a missing one fails every request.

Fix. Create the template the report names, or correct its template.

REPORT011: A report's context holds a value with no stable text

exception · from karni_reports.versions.encode

Why Karni objects. The data version is a hash of the context. A value whose text changes on every run (an object without str) would make every request render again.

Fix. Put plain data in the context (dicts, lists, model instances, querysets), give the class a str, or override Report.get_data_version.

SITE (SITE)

SITE001: Templates do not get the request

system check (error) · from karni_site.checks

Why Karni objects. {% ifactive %} reads the current page from the request, and {% csp_hash %} and {% csp_allow %} add to the request's Content-Security-Policy. Without django.template.context_processors.request in the template engine's context_processors, no menu item is ever current and the design's inline scripts are blocked in production.

Fix. Add 'django.template.context_processors.request' to TEMPLATES[0]['OPTIONS']['context_processors'] in config/settings.py (karni_settings() includes it unless the project replaced TEMPLATES).

SITE002: {% ifactive %} names a URL the project does not have

system check (error) · from karni_site.checks

Why Karni objects. A menu item marks itself current when the request resolved to one of the URL names in its {% ifactive %}. A name that no URL pattern has, after a view was renamed or removed, never matches, so the item is never marked and nothing fails.

Fix. Use the name karni routes lists for that page (<app>:<name>), or remove the name from the tag.

SITE003: A karni_site template tag is written wrongly

exception · from karni_site.templatetags.karni_site

Why Karni objects. {% ifactive %} needs at least one URL name or path. {% csp_hash %} takes nothing, or attribute. {% csp_allow %} takes arguments like "font-src https://fonts.gstatic.com". {% editable %} and {% editable_image %} take a block key ("home.intro": lowercase words joined by dots, the page first), {% site_image %} a file field of the site's settings, {% site_defaults %} name="value" pairs, and {% get_menu %} a name and as <variable>. The template does not compile otherwise. The highlight filter takes a tag with optional classes ("span.accent", "em", or "" for none) and fails the render otherwise.

Fix. Write the tag as the message shows. The karni-site README has an example of each.

SITE004: Templates do not get site

system check (error) · from karni_site.checks

Why Karni objects. site (the site's name, logo, contact details, opening hours and social links, edited in the admin) reaches templates through the context processor karni_site.context_processors.site. Without it every {{ site.<field> }} renders empty and nothing fails.

Fix. Add 'karni_site.context_processors.site' to TEMPLATES[0]['OPTIONS']['context_processors'] in config/settings.py. karni make site <app> adds it.

SITE005: The redirect middleware is not installed

system check (error) · from karni_site.checks

Why Karni objects. Redirects a client adds in the admin are answered by karni_site.middleware.RedirectMiddleware. Without it they are stored and never used, and the old addresses answer 404.

Fix. Add 'karni_site.middleware.RedirectMiddleware' to the # karni:middleware block of config/settings.py. karni make site <app> adds it.

SITE006: A redirect would send visitors in a circle

exception · from karni_site.redirects

Why Karni objects. The new address of a redirect is itself redirected, through one redirect or several, back to the old address. A browser would follow the chain until it gives up, so the page could never be reached.

Fix. Point the redirect at the page's final address, or remove the redirect that leads back. The message lists the chain.

SITE007: A menu item does not point at a page

exception · from karni_site.menus

Why Karni objects. A menu item goes to exactly one place: one of the site's pages by URL name, a row's own page (its get_absolute_url), or an address. An item with none of them (and no children from a model), with a URL name no route has, with a row that no longer exists, with an address such as javascript:, or under itself, would render a broken link.

Fix. Choose where the item goes in the admin (or set route, content_type and object_id, or url), and pick a parent from the same menu.

SITE008: One block key has two different defaults

system check (error) · from karni_site.checks

Why Karni objects. A block is stored once per key. While nobody has edited it, it follows its template's default, so a key written with one default in one template and another default elsewhere (or used for text in one place and an image in another) would be stored again on every render and show the other place's text.

Fix. Give each place its own key (karni import design --editable does), or the same default in both when the text is meant to be shared.

SITE009: KARNI_SITE_SETTINGS_MODEL names no installed model

exception · from karni_site.sitesettings

Why Karni objects. site, the admin's site settings and the editor role read the model KARNI_SITE_SETTINGS_MODEL names. A label that is not an installed model (a typo, an app missing from INSTALLED_APPS) leaves them nothing to read.

Fix. Set it to 'app_label.ModelName' of a model that subclasses karni_site.models.AbstractSiteSettings and whose app is installed, or remove it for karni_site.SiteSettings.

SITE010: A page has no title

system check (error) · from karni_site.checks_seo

Why Karni objects. Search results and browser tabs show a page's <title>. A page without one, or with an empty one, is listed under its address or a title the search engine makes up.

Fix. Give the page a title: {% block title %} in its template, the title of its row (class Karni: seo), or its entry in the admin's Page titles and descriptions. base.html needs {% karni_seo %} around its <title>.

SITE011: Two pages have the same title

system check (error) · from karni_site.checks_seo

Why Karni objects. Search engines treat pages with the same title as copies of one another and may show only one. Visitors cannot tell the results apart either. It usually means a template's title was written once for every page of a kind.

Fix. Give each page its own title. For pages of one view, let the row name it (class Karni: seo = {"title": "name"}, or {% block title %}{{ object.title }}{% endblock %}), or set it per page in the admin.

SITE012: A page has no description

system check (error) · from karni_site.checks_seo

Why Karni objects. Search results show the <meta name="description"> under the title. Without one the search engine picks a fragment of the page, often the menu or a cookie notice. The placeholder karni make site and karni make view write ("One sentence that search engines show under this page's title.") counts as none.

Fix. Write one sentence about the page: {% block description %} in its template, the description of its row (class Karni: seo = {"description": "summary"}), its entry in the admin, or the site's tagline as the last default.

SITE013: Two pages have the same description

system check (error) · from karni_site.checks_seo

Why Karni objects. A description shared by several pages says nothing about any one of them, and search engines may ignore it. A detail page that repeats its card's text, or a layout's default left in place, is the usual cause.

Fix. Write a description per page, or let each row give its own (class Karni: seo = {"description": "intro"}).

SITE014: An image has no alt text

system check (error) · from karni_site.checks_seo

Why Karni objects. Screen readers read an image's alt text, and search engines index it. An <img> without an alt attribute is announced by its file name.

Fix. Describe the image in alt="...", or write alt="" when it only decorates. {% image %} requires alt, and an image a client uploads takes its alt text in the admin.

SITE015: An image has no width and height

system check (error) · from karni_site.checks_seo

Why Karni objects. Without width and height the browser does not know how much room an image takes until it loads, so the text below it jumps when it does (layout shift, which search engines measure).

Fix. Render uploaded images with {% image %}, which writes both. For a design's own image, write its pixel width and height (karni import design does). CSS still sizes it: {% karni_seo %} keeps such images in proportion.

SITE016: An image is much larger than the page shows it

system check (error) · from karni_site.checks_seo

Why Karni objects. A visitor downloads every pixel of an image, however small the page shows it. A photo thousands of pixels wide in a small card makes the page slow on a phone, and page speed counts in search rankings.

Fix. Give it smaller copies: {% image %} for uploads (with Pillow installed, pip install karni-site[images], and a Celery worker running), a srcset for a design's image (karni import design writes one when Pillow is installed where karni runs), or a smaller file. KARNI_SITE_SEO_IMAGE_BYTES and KARNI_SITE_SEO_PIXEL_RATIO set the limits.

system check (error) · from karni_site.checks_seo

Why Karni objects. A link, image, stylesheet or script on one of the site's own pages points at an address that answers an error. Visitors land on a dead end, and search engines count broken links against the site.

Fix. Point it at a page that exists ({% url %} for the site's pages, {% static %} for its files), add a redirect for an address that moved, or remove it.

SITE018: The sitemap and the site's pages disagree

system check (error) · from karni_site.checks_seo

Why Karni objects. sitemap.xml tells search engines which pages exist. A page the site links to that the sitemap leaves out is found late or not at all, and an address in the sitemap that does not answer 200 (or asks not to be indexed) wastes the crawl.

Fix. Include karni_site's URLs (path("", include("karni_site.urls")) in config/urls.py, which karni make site writes). Give a model's rows get_absolute_url() and the public filter they need (class Karni: sitemap), and leave out an address that is not a page with KARNI_SITE_SITEMAP_EXCLUDE.

SITE019: An SEO tag or declaration is written wrongly

exception · from karni_site.seo_tags

Why Karni objects. {% karni_seo %} takes nothing and ends with {% endkarni_seo %}. {% image %} takes the image, then name=value pairs, alt among them. class Karni: sitemap is True, False or a dict of filter, exclude, lastmod, changefreq and priority, on a model with get_absolute_url(). class Karni: seo maps title, description, image and type to fields. @pages on a view gives the captures of each of its addresses.

Fix. Write it as the message shows. The karni-site README has an example of each.

SITE020: {% karni_form %} names a form Karni cannot find

system check (error) · from karni_site.forms.resolve_form; karni_site.form_checks

Why Karni objects. The tag finds a form by the name of its model ("enquiry" for Enquiry, "booking_request" for BookingRequest, or "app_label.model"), served by the viewset the API router registered for it, or by an entry in KARNI_SITE_FORMS. A name that matches no model, a model no viewset serves, or several models leaves the page without its form. karni check reports it before a visitor does.

Fix. Create the form with karni make form <name> <field:type> ..., use the name of a model a viewset serves, write app_label.model when several apps have the name, or map the name in KARNI_SITE_FORMS = {"<name>": "app.viewsets.SomeViewSet"}.

SITE021: {% karni_form %} is written wrongly

exception · from karni_site.templatetags.karni_forms

Why Karni objects. The tag takes the form's name and then option="value" pairs it knows: fields, rows, labels, placeholders, widgets, next, id, classes, template, the texts (button, success, invalid, throttled, refused, failed, choose) and a <part>_class per part of the markup. labels, placeholders and widgets are "field: text | field: text", and every field they name must be one a visitor fills.

Fix. Write it like {% karni_form "contact" fields="name,email,message" labels="name: Your name" classes="bootstrap" %}. The karni-site README lists every option.

SITE022: The form view is not routed

exception · from karni_site.forms.SiteForm.action

Why Karni objects. Every {% karni_form %} posts to karni_site's form view (karni_site:form), which saves the submission through the form's viewset and works without JavaScript. Without the include in config/urls.py the form has nowhere to post.

Fix. Add path("", include("karni_site.urls")) to urlpatterns in config/urls.py, before the site's own include. karni make form adds it.

SITE023: A notification does not say who to email

exception · from karni_site.notify.recipients; karni_site.notify.notify_recipients

Why Karni objects. karni_site.notify.notify_recipients(row, setting="NAME", ...) emails the addresses in settings.NAME, and to=[...] emails fixed addresses. It needs exactly one of the two. A setting that does not exist is a typo or a missing line, and the email would never go out. An empty list only logs a warning.

Fix. Pass setting= or to=. For a setting, add NAME = env.list("NAME", default=[]) to config/settings.py and NAME=team@example.com to .env (karni make form --notify NAME writes both).

SITE024: A page fails while karni_site_seed renders it

exception · from karni_site.management.commands.karni_site_seed

Why Karni objects. manage.py karni_site_seed renders every page of the site once, in a deploy, so the blocks, menus and site details its templates give are stored before the first visitor. A page that answers a server error (500) with the new code and the migrated database would fail for every visitor too, and its defaults are not stored.

Fix. Open the page the message names with karni serve (or read the error the command printed) and fix the view or the template. --keep-going reports the failing pages without failing the run.

STORE (STORE)

STORE001: KARNI_STORAGE_PROVIDER names no preset

system check (error) · from karni_storage.presets

Why Karni objects. The preset gives core's S3 backend the endpoint, region and addressing style of the service. Without one, protected files have nowhere to go.

Fix. Set KARNI_STORAGE_PROVIDER to aws, r2, minio, spaces, b2 or gcs-interop (in karni.yaml: modules: {storage: {provider: r2}}). A service no preset knows is minio with its endpoint in AWS_S3_ENDPOINT_URL.

STORE002: The storage provider has no credentials

system check (error) · from karni_storage.presets

Why Karni objects. With KARNI_STORAGE=s3 every upload and every signed download URL is signed with the access key. Without it each one fails in production.

Fix. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in the environment (.env), with the access key of the provider's account (R2, Spaces, B2 and GCS HMAC keys use the same two names). On AWS with an instance or task role, set KARNI_STORAGE_CREDENTIALS=chain instead. Credentials never go in karni.yaml.

STORE003: The storage preset needs a value it does not have

system check (error) · from karni_storage.presets

Why Karni objects. A preset builds the endpoint from the bucket's region (aws, spaces, b2), the account id (r2) or your server's URL (minio). Without it the backend talks to the wrong host.

Fix. Set what the message names in the environment: AWS_STORAGE_BUCKET_NAME (or KARNI_STORAGE_BUCKET), AWS_S3_REGION_NAME, R2_ACCOUNT_ID or AWS_S3_ENDPOINT_URL.

STORE004: karni_storage.urls is not included

system check (error) · from karni_storage.checks

Why Karni objects. The API gives each protected file as its download path, <resource>/<id>/files/<field>/. Without the include those paths answer 404 and nothing can be uploaded.

Fix. Add path("api/", include("karni_storage.urls")) to config/urls.py, next to path("api/", include("karni.api.urls")).

STORE005: A karni-storage setting has a value it does not take

system check (error) · from karni_storage.checks

Why Karni objects. The module would fail on the first upload or the first thumbnail.

Fix. KARNI_STORAGE_UPLOAD_METHOD takes post, put or nothing. KARNI_STORAGE_CREDENTIALS takes keys or chain. KARNI_STORAGE_THUMBNAIL_SIZES maps a name to [width, height] in pixels, e.g. {"small": [160, 160]}. KARNI_STORAGE_THROTTLE_RATES maps download, upload or confirm to a rate such as "120/hour", or None.

STORE006: A model with protected files has no viewset on the API

system check (error) · from karni_storage.checks

Why Karni objects. A protected file is served only after its row is retrieved through the model's own viewset. A model the API does not serve has files nobody can download.

Fix. Declare a BaseViewSet for the model (karni make viewset), or use a plain FileField if the files are not meant to be downloaded through the API.

STORE010: No protected file field there

API 400 response · from karni_storage.access (answered with HTTP 404)

Why Karni objects. The path names a resource the API does not route, or a field that is not one of its model's protected fields, or one Karni.field_roles hides from you.

Fix. Use the download path the API returned for the field, or the field's own name.

STORE011: The file is larger than the field allows

API 400 response · from karni_storage (upload, confirm and the serializer field)

Why Karni objects. Each protected field has a size limit: its max_size, else KARNI_STORAGE_MAX_SIZE.

Fix. Send a smaller file, or raise the field's max_size (ProtectedFileField(max_size=...)) or KARNI_STORAGE_MAX_SIZE.

STORE012: The field does not take files of that type

API 400 response · from karni_storage (upload, confirm and the serializer field)

Why Karni objects. Each protected field lists the content types it takes. An image field takes JPEG, PNG, GIF and WebP by default. SVG is left out because it can carry script.

Fix. Send a file of an allowed type, or list the type in the field's content_types.

STORE013: The upload token is not valid

API 400 response · from karni_storage.tokens

Why Karni objects. A direct upload is attached to a row only with the token the upload and confirm steps gave this user for this field. A token that expired, was altered, belongs to someone else or to another field is refused, so nobody can attach another user's object.

Fix. Upload the file again: POST <resource>/files/<field>/upload/, send it to the bucket, POST .../confirm/, then save the row with the token confirm returned.

STORE014: The uploaded file is not in the bucket

API 400 response · from karni_storage.views (confirm)

Why Karni objects. Confirm checks the object before any row may point at it.

Fix. Send the file to the URL the upload step returned before its expiry, then confirm again.

STORE015: Direct uploads need the bucket

API 400 response · from karni_storage.views (confirm)

Why Karni objects. On local storage (KARNI_STORAGE=local) the upload step answers method 'api': the file goes through the API with the row, so there is nothing to confirm.

Fix. Send the file in the row's create or update request (multipart).

STORE016: No thumbnail size of that name

API 400 response · from karni_storage.views (?size=)

Why Karni objects. Thumbnails are made in the sizes KARNI_STORAGE_THUMBNAIL_SIZES names.

Fix. Use one of the names the message lists, or add the size to the setting.

STORE017: The thumbnail is not ready

API 400 response · from karni_storage.views (?size=, answered with HTTP 404)

Why Karni objects. Thumbnails are made by a Celery task after the image is confirmed or saved. Until it has run, or for a field that is not a protected image, there is none.

Fix. Try again shortly, show the full image meanwhile, and keep a Celery worker running. manage.py karni_thumbnails makes the missing ones.

STORE018: The row has no file in that field

API 400 response · from karni_storage.views (answered with HTTP 404)

Why Karni objects. The field is empty on this row.

Fix. Upload a file to the field first.

API 400 response · from karni_storage.views (answered with HTTP 403)

Why Karni objects. A signed download link opens one file for KARNI_STORAGE_URL_EXPIRY seconds. It expired, was altered, or the file was replaced since.

Fix. Ask for a fresh link: GET the download path again.

STORE020: A protected file's download path cannot be built

exception · from karni_storage.fields (ProtectedFieldFile.url)

Why Karni objects. The path is <resource>/<id>/files/<field>/ under karni_storage.urls. It needs the include and a viewset that serves the model.

Fix. Add path("api/", include("karni_storage.urls")) to config/urls.py and declare a BaseViewSet for the model. karni check names which is missing (STORE004, STORE006).

The karni command (C)

C001: Not inside a Karni project

karni command · from karni_cli.project.require_project and every project command

Why Karni objects. Project commands find the project by walking up to the directory with manage.py (and config/settings.py).

Fix. cd into the project (or a directory below it), or create one: karni new <name>.

C002: No way to run the project's Python

karni command · from karni_cli.project (runners: serve, migrate, test, shell, seed, ...)

Why Karni objects. Project commands run in the project's own interpreter: its .venv, else the active virtualenv (VIRTUAL_ENV), else the running docker compose stack.

Fix. Create the venv (python -m venv .venv && .venv/bin/pip install -e .), activate one that has the project's dependencies, or start the stack (docker compose up -d). The message says which one the command looked for.

C003: Docker is not installed

karni command · from karni_cli.project

Why Karni objects. Without --local, karni runs the project through docker compose.

Fix. Install Docker with the compose plugin, or run on the host: karni serve --local (with a .venv).

C004: These options cannot be combined

karni command · from karni serve, karni make model/page/schedule

Why Karni objects. Some options only apply in a particular mode (for example --host needs --local).

Fix. Drop one of the options as the message says, or add the option it needs.

C005: This karni-cli install is incomplete

karni command · from karni_cli (bundled templates, agent rules, changelog, error codes)

Why Karni objects. The wheel bundles the project template, agent rules, changelog, error codes and the settings reference. One is missing, so the install is broken.

Fix. Reinstall karni-cli (pipx reinstall karni-cli, or pip install --force-reinstall karni-cli).

C006: An optional tool is not installed

karni command · from karni mcp, karni types, karni ui detect

Why Karni objects. Some commands need extra tools: the MCP SDK for karni mcp, Node and openapi-typescript for karni types, Node for karni ui detect to evaluate a tailwind.config.

Fix. Install what the message names, e.g. pip install 'karni-cli[mcp]', or add openapi-typescript to frontend devDependencies (Node 20+).

C007: A configuration value is invalid

karni command · from karni config, KARNI_AGENT_SOURCE, KARNI_TEMPLATES, KARNI_UI_SRC, KARNI_DEV_PORT

Why Karni objects. karni reads its settings from karni config files and a few environment variables (the project's .env included).

Fix. Use a value the message lists (karni config shows the known settings), or unset the environment variable.

C008: A file cannot be written

karni command · from karni config, karni ui detect

Why Karni objects. The file or its directory is not writable.

Fix. Check the path's permissions. For karni config, set the value per project instead of --global. For karni ui detect, choose another place with --output.

C009: A command in the project failed

karni command · from karni context, karni upgrade, karni rules (project interpreter)

Why Karni objects. karni ran manage.py or Python in the project and it exited with an error.

Fix. Read the project's error in the message (often a settings or import error), fix it, and re-run. karni doctor checks the environment.

C010: The path is not a file inside the project

karni command · from karni rules --check, karni context --with-history

Why Karni objects. These commands read files of the current project only.

Fix. Pass an existing file path inside the project.

C011: pytest is not installed in the project interpreter

karni command · from karni test

Why Karni objects. karni test runs python -m pytest through the project's interpreter (its .venv, the active virtualenv, or the compose service). pytest and pytest-django are in the project's dev dependency group, not in karni.

Fix. Install them there: pip install pytest pytest-django (or uv sync for the dev group), then run karni test again.

C012: The project's database driver is not installed

karni command · from karni_cli.database (every command that starts Django: check, context, migrate, serve --local, test, ...)

Why Karni objects. Django imports the database driver as it starts (psycopg for PostgreSQL), so without it every project command stops with a traceback. A venv made for the quickstart has none: the quickstart uses SQLite.

Fix. Install the driver into the project interpreter: pip install "psycopg[binary]" (or pip install -e . for all of the project's dependencies). Or run in Docker: karni serve -d starts the stack, whose image has the driver, and --docker runs a project command inside it. KARNI_DB_CHECK=false skips the check.

C013: The project's database cannot be reached

karni command · from karni_cli.database (commands that open the database: migrate, seed, sync-roles, createsuperuser, serve --local, test, beat, manage)

Why Karni objects. These commands open the database at DATABASE_URL first. A server that is not running, a host that does not resolve (the compose default db, from the host) or rejected credentials would stop them with a traceback.

Fix. Start the database (karni serve -d runs the compose stack with PostgreSQL), or point DATABASE_URL in .env at one that runs (cp .env.example .env first). DATABASE_URL=sqlite:///db.sqlite3 needs no server. The message names the address and the driver's error. KARNI_DB_CHECK=false skips the check.

C101: The file karni make would write already exists

karni command · from karni make (every generator)

Why Karni objects. Generators never overwrite your code silently.

Fix. Pass --force to overwrite (or, for multi-file generators, to create only the missing files), or remove the file first.

C102: Which app? (none, unknown, or several)

karni command · from karni make (generators that write into an app)

Why Karni objects. Generators write into a local app listed in the # karni:apps block of config/settings.py.

Fix. Create one (karni make app <name>), or choose one with --app <label>.

C103: The name is not valid here

karni command · from karni make, karni new

Why Karni objects. Names become Python modules, classes, URLs or task names, each with its own rules, and must not shadow existing modules or Django/Karni commands.

Fix. Use the form the message shows (snake_case module, CamelCase model, kebab-case module or route) and a name nothing else uses.

C104: A field spec is invalid

karni command · from karni make model (name:type[:arg][?] fields)

Why Karni objects. Fields are written as name:type[:arg][?], e.g. title:str:200 or starts_at:datetime?, and relations name their target model.

Fix. Fix the field the message names. karni make model --help lists the types.

C105: Something the generator builds on does not exist yet

karni command · from karni make (viewset, test, serializer, listener, schedule, ...)

Why Karni objects. Generators wire new code into existing code: a viewset needs its model, a test its viewset, a listener its event.

Fix. Run the karni make command the message names first, then re-run this one.

C106: An option value is invalid

karni command · from karni make, karni new, karni types, karni ui detect

Why Karni objects. The option accepts specific values (the message lists them).

Fix. Use one of the values shown, e.g. --access owned:organizer or --every 15m.

C107: The new code would clash with existing code

karni command · from karni make (component, viewset, schedule, page, service)

Why Karni objects. Two components claiming one role, two viewsets for one model, or two schedules or routes with one name would shadow each other.

Fix. Extend or edit the existing code the message names, or choose another name.

C108: A karni marker is missing from a project file

karni command · from karni make, karni add (settings.py and routes.tsx markers)

Why Karni objects. Generators insert code at # karni: / // karni: markers that karni new writes. Older or hand-edited projects may lack them.

Fix. Add the change by hand as the message shows, or restore the marker from a fresh karni new project.

C109: An explicit serializer needs a reason

karni command · from karni make serializer

Why Karni objects. BaseViewSet generates the serializer from the model (rule K106), so a hand-written one must say why it exists.

Fix. Pass --reason "<why>", or tune the generated serializer with APIMeta instead.

C110: A project file cannot be parsed

karni command · from karni make (reads your Python before editing it)

Why Karni objects. karni make edits your files structurally and stops rather than guess.

Fix. Fix the syntax error at the file and line in the message, then re-run.

C111: The design folder has nothing to import

karni command · from karni import design

Why Karni objects. karni import design reads a folder of static pages: every .html file in it is a page (a meta-refresh stub is a redirect), and every other file is copied as an asset.

Fix. Pass the folder that holds the design's index.html and the other pages, with its css/, js/ and image folders inside it.

C112: The project's kind is not one Karni knows

karni command · from karni context, karni rules sync, karni add site (pyproject.toml [tool.karni] kind)

Why Karni objects. karni new records the project's kind in pyproject.toml: site, app, site+app, game or app+game. The agent files and karni context state it with its stack, so a value Karni cannot read stops them instead of guessing.

Fix. Set kind = "site", "app", "site+app", "game" or "app+game" under [tool.karni] in pyproject.toml (or remove the line, and Karni infers the kind from the project), then run karni rules sync.

C121: The content map cannot be used

karni command · from karni design extract --map, karni import design --map

Why Karni objects. The map says which structure of the design is which model and which element is which field. Extract follows it exactly, so a model, a field, a relation's target or a selector it cannot follow stops it before anything is written.

Fix. Fix each problem the message lists in the map (the field names come from the map's "fields", the selectors are CSS with an optional @attribute), or write a fresh draft with karni design analyze <design> --map <file> --force.

C122: The content map has decisions left

karni command · from karni design extract --map

Why Karni objects. karni design analyze marks what the markup cannot settle with a decide entry: a list on a detail page or a few items on the home page may be hand-picked or derived by a query. Extract will not guess either way.

Fix. For each one: keep the value (remove its "decide", and add the field to the model's karni make model command) or delete the value from the map and query the rows in the view.

C123: A content map is there already

karni command · from karni design analyze --map

Why Karni objects. The map is a file the agent edits: names, decisions, selectors. Writing a new draft over it would lose those edits.

Fix. Write the draft to another file, or pass --force to replace the map.

C140: The database to read the table from cannot be used

karni command · from karni make model --external

Why Karni objects. karni make model <Name> --external --table <table> writes the model from the table's columns, so it reads them from the database (manage.py karni_inspect, in the project's interpreter). The database did not answer, the alias is not in DATABASES, or the project's karni has no karni_inspect command.

Fix. Start the database or fix its settings (the message names the alias and the error), pass the alias with --database, or upgrade the project's karni. Then run the command again.

C141: The table or view is not in the database

karni command · from karni make model --external

Why Karni objects. The database answered, but has no table or view of that name, or the name has a schema (schema.table) on a database other than PostgreSQL, which has none.

Fix. Check the name and the alias (--database). A PostgreSQL table in another schema is written schema.table, e.g. --table reporting.sales.

C142: These options do not go with --external

karni command · from karni make model --external

Why Karni objects. An external model's fields come from the table, so it takes no field list and needs --table. --table, --database and --writable describe an external model, so they need --external. Imports never write a read-only table, so --key does not apply.

Fix. Run karni make model <Name> --external --table <[schema.]table> [--database <alias>] [--writable], with no fields.

C124: A content map option has a value extract does not know

karni command · from karni design extract --map

Why Karni objects. Some options of the map take one of a few values: a relation's "by" (absent for a link to the row's page, "key" for the row's key, "title" for its title), a key's "from" (page, link, attr, field, position) and "link" ("path"). A value outside them would be read some other way without a word, so extract refuses it.

Fix. Write one of the values the message lists, or leave the option out for its default. docs/design-content.md#the-content-map describes each.

C199: Internal error in karni

karni command · from karni make, karni upgrade

Why Karni objects. A generator or codemod hit a case it does not handle. Nothing was written.

Fix. Report it with the command and the file it stopped on. Meanwhile, make the change by hand.

C201: karni upgrade needs a clean git work tree

karni command · from karni upgrade

Why Karni objects. Codemods rewrite many files. A clean tree lets you review and undo them with git.

Fix. Commit or stash first, preview with --dry-run, or pass --allow-dirty to write anyway.

C202: karni upgrade does not downgrade

karni command · from karni upgrade

Why Karni objects. Codemods only move code forward.

Fix. Pass a --to version newer than the project's karni, or check --from.

C203: That is not a version number

karni command · from karni upgrade (--to / --from)

Why Karni objects. Versions are MAJOR.MINOR[.PATCH].

Fix. Write e.g. --to 0.2 or --to 0.2.0.

C204: No such rule or procedure

karni command · from karni rules, karni explain

Why Karni objects. Rules (K codes) and procedures are listed by karni rules.

Fix. Run karni rules for the codes and procedures, then use one of them.

C205: The agent adapter configuration is invalid

karni command · from karni rules sync (karni.rules.py ADAPTERS)

Why Karni objects. Adapters are the generated agent guidance files. Each has an id and a line cap.

Fix. Use the adapter ids the message lists, and shorten project rules feeding an adapter that exceeds its cap.

C206: The OpenAPI schema cannot be turned into types

karni command · from karni types

Why Karni objects. karni types reads the backend's schema (x-karni-resource operations) to generate typed hooks.

Fix. Make sure the backend serves Karni viewsets (karni routes) and the schema uses only local $refs.

C207: karni add cannot edit pyproject.toml

karni command · from karni add

Why Karni objects. karni add manages the [project].dependencies table of the project's pyproject.toml.

Fix. Add the table (or the dependency) by hand, then re-run.

C210: No spec file

karni command · from karni spec validate

Why Karni objects. karni spec validate reads a karni.yaml: by default the project root's, else the current directory's.

Fix. Write one (docs/app-spec.md), export the project's with karni spec export -o karni.yaml, or pass --spec <file>.

C211: The spec is not valid YAML

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. The spec is YAML. A syntax error stops everything else, and the parser names the line.

Fix. Fix the line the message names: indent with spaces, and quote a value that holds ': ' or starts with *, &, !, %, @ or a backtick.

C212: Unknown key in the spec

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Every key of the format means one thing, so a misspelt key would be ignored without a word. A key that starts with x- is kept and ignored, for notes of your own.

Fix. Fix the spelling (the message lists the keys that mapping takes), remove the key, or prefix it with x-.

C213: A spec value has the wrong type, or a required key is missing

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Values are never coerced: a list where a string is expected, or a number written for a text, is an error rather than a guess. version and app.name are required.

Fix. Write the value in the form docs/app-spec.md shows for the key. Quote a value YAML would read as a date, a number or true/false.

C214: Unknown spec version

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. version moves only for a breaking change of the format, and this karni reads version 1.

Fix. Write version: 1, or upgrade karni-cli when the spec comes from a newer release.

C215: A name in the spec is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Names become code: app labels are Python packages, entities classes, pages file names and roles the slugs HasRole checks.

Fix. Use snake_case app labels (not one Django, Karni or a module takes), PascalCase entities, kebab-case page names, and role slugs of letters, digits, _, . and -.

C216: A field's type is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Fields use karni make model's own syntax and are checked by its own parser and renderer, so the spec and the generator accept exactly the same fields. The message is the generator's, with its code.

Fix. Write name: type[:arg...], a trailing ? for optional (karni make model --help lists the types and their arguments).

C217: An access rule is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. An entity's access maps onto Karni's Access(read=..., write=..., create=...): each slot takes public, authenticated, granted, role:<slug> or owned:<field>, or a list of them, any of which admits.

Fix. Use those forms, or write access: code and declare the viewset's Access(...) by hand (Where, Can, &, a computed get_access).

C218: A role grant is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Grants map onto KARNI_ROLES: a pattern app.entity[:action] (with * for a part, or * alone) to a scope all, own, own:<owner field>, related:<scope path key>, custom:<name> or tree:<path>. A spec grants the standard actions view, add, change and delete.

Fix. Fix the pattern or the scope. An entity's own actions, and a grant on a model outside the spec, go in KARNI_ROLES by hand.

C219: A feature's value is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Each feature is one setting: social_login names the built-in providers of KARNI_SOCIAL_TOKEN_PROVIDERS, and terms is KARNI_TERMS (a version of at most 100 characters, URL path prefixes that start with /).

Fix. Name google, microsoft or apple (a provider class of your own goes in settings), and fix the terms value the message names.

C220: A page entry is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Each entry of pages is one key: an entity with the pages karni make page makes for it (list, detail, form, and {detail: {related: [...]}} for a detail page with related tabs), or a page name with its kind (blank, login, code, or dashboard: the scaffold's home at /, or a page of charts at /<name>).

Fix. Write e.g. - Session: [list, detail, form], - about: blank, - home: dashboard or - overview: dashboard, each entity or page once.

C221: A module option is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A module's options are its settings: the option provider of payments is KARNI_PAYMENTS_PROVIDER. An option the module does not have, or a value of the wrong type, would be lost.

Fix. Use an option the message lists, with the type its setting takes (the module's README has the table). Credentials stay in .env.

C222: A key is written twice

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. YAML keeps the last of two equal keys in a mapping and drops the first without a word, so half of what was written would be lost.

Fix. Keep one of the two and merge what the other said into it.

C223: A seed count is not valid

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. seed sets each entity's demo rows per karni seed run (a Seeder's Meta.count), where 0 skips the entity.

Fix. Write a whole number, 0 or more.

C224: A key reserved for a later release

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Some keys are reserved for features Karni adds later (cross-entity search), so a spec written today keeps its meaning. pk, external and database were reserved before karni plan and are keys now, and so are taxonomies, aggregate and markdown.

Fix. Remove the key, and write that part by hand in the project until the feature ships.

C225: The app kind and the modules disagree

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. karni add site turns an app into a site+app, so a spec of kind app with the site module describes a project that cannot exist.

Fix. Write kind: site+app (karni new --kind site+app adds the site module by itself), or drop the module.

C230: A relation names an entity that does not exist

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A fk, m2m or o2o field must point at something karni make model can import: an entity of the spec, the user model, or a model of a module the spec adds.

Fix. Fix the name, add the entity, add the module, or point at User. A model of the project outside the spec cannot be named.

C231: A relation name is ambiguous

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Two apps of the spec define an entity of that name, so the bare name could mean either.

Fix. Write app.Name, e.g. fk:shop.Product.

C232: Access names a role the spec does not declare

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. role:<slug> becomes HasRole("<slug>"), which nobody would hold if no role of that slug exists. Without roles, the spec has Karni's shipped roles (staff, user, customer), plus the roles of the modules it adds.

Fix. Declare the role under roles, or fix the slug.

C233: A grant names an entity the spec does not have

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A grant pattern that matches no model grants nothing, and Karni refuses it at startup (E206).

Fix. Name an entity as app.entity (lowercase or as written), or add the module whose model it names.

C234: A grant's scope does not fit the entity

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. own compares the entity's owner field with the user, and related:<key> its scope path <key> with the user's attribute <key>. own:<field> must name that owner field, and related:<key> a scope path the entity declares.

Fix. Set owner: on the entity, add scope_paths: {<key>: <lookup>}, or change the scope.

C235: A page names an entity that does not exist

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. An entity's pages compose its API resource, which only an entity of the spec has.

Fix. Name an entity of the spec (app.Name when two apps define it), or add it.

C236: A module Karni does not know

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. modules lists what karni add installs: the modules of the catalog (karni modules list), which are Karni's own (approvals, impersonation, payments and site) and any module installed next to karni-cli that ships a manifest.

Fix. Fix the name. A module of your own joins the spec once it ships a karni.module.toml (docs/modules.md). Without one, add it with karni add and leave it out of the spec.

C237: A field group names a field the entity does not have

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. groups become Karni.field_groups (the sections of the React form and detail page and the admin's fieldsets), and karni check refuses a name that is not a field or a field in two groups (karni.E551, karni.E552).

Fix. Name the entity's fields, each in one group.

C238: An entity option names a field the entity does not have

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. key, search, order, audit and scope_paths each name fields of the entity (key, search and order may also name id, created_at and updated_at).

Fix. Name a field the entity declares, or add it under fields.

C239: owner does not lead to the user

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. The own scope compares the owner field with the signed-in user, so it must be a relation to the user or a path through relations ending at one.

Fix. Name a relation to the user (member: fk:User, then owner: member) or a path such as workspace__members.

C240: owned:<path> in access does not lead to the user

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. owned:<path> becomes Owned("<path>"), which keeps the rows whose path points at the signed-in user.

Fix. Name a relation to the user (owned:member) or a path through relations (owned:session__instructor).

C241: seed names an entity that does not exist

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. seed counts demo rows per entity of the spec.

Fix. Name an entity of the spec (app.Name when two apps define it).

C242: Two pages share a route

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. Each page karni make page writes has a route (an entity's list at /<route>, its detail at /<route>/$id, its form at /<route>/new and /<route>/$id/edit, a named page at /<name>), and two pages cannot answer the same path.

Fix. Rename the page or drop one of them.

C245: karni spec export cannot read the project

karni command · from karni spec export

Why Karni objects. The export reads the project through manage.py karni_facts, run by the project's interpreter, which needs this karni (the command is new in it).

Fix. Upgrade the project's karni, then fix what the message shows (the command's last output lines): a settings error, a model that fails to import, or output printed at startup.

C246: The output file exists

karni command · from karni spec export

Why Karni objects. karni spec export does not overwrite a spec: it may hold edits of your own.

Fix. Pass --force to replace it, or write to another file with -o.

C250: karni plan cannot read the project

karni command · from karni plan

Why Karni objects. The plan compares the spec with the project as karni spec export reads it: through manage.py karni_facts, run by the project's interpreter, which needs this karni.

Fix. Upgrade the project's karni, then fix what the message shows (the command's last output lines): a settings error, a model that fails to import, or output printed at startup.

C251: An external entity's keys do not fit

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. external: true is a table another system owns, so it needs table, its key is the table's own column (no pk), and karni seed skips it. table and writable mean nothing without external.

Fix. Add table: <[schema.]table> to an external entity, remove pk and its seed count, or add external: true where table or writable is written.

C252: database names an alias the project does not have

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. database sends an entity's reads, writes and migrations to an alias of DATABASES (class Karni: database). karni plan checks the name against the project's DATABASES, and karni spec validate checks that it is an alias name.

Fix. Add the alias to config/settings.py (DATABASES["warehouse"] = env.db_url("WAREHOUSE_DATABASE_URL")), or fix the name.

C253: A relation joins two databases

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. Django joins related tables in one database, so a fk, m2m or o2o between entities on different databases cannot work (karni.E276 at startup). The user and the modules' models are on the default database.

Fix. Keep both entities on one database, or store the other row's key in a plain field and look it up in code.

C254: A rename (was) is not valid

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. was: <old name> on a field or an entity tells karni plan and karni build to rename it and keep its data. The old name must be a valid name, differ from the new one, no longer be declared, and be claimed by one field or entity only.

Fix. Write the old name once, on the field or entity that takes over the data, and remove the old declaration.

C540: global_search names a field that is not a text field of the entity

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. Search across entities (class Karni: search) matches the query against the entity's own text fields and gives each a trigram index. Its fields come from global_search.fields, else from the entity's search list, which may name a related path (venue__name) or a non-text field that it cannot search.

Fix. List the entity's own text fields (str, text, email, url, slug, choice, phone, country, currency, state) under global_search.fields, e.g. global_search: {fields: [name, sku]}.

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. global_search takes its fields from global_search.fields, else from the entity's search list. With both empty there is nothing to match the query against.

Fix. Name the text fields under global_search.fields, or list them under search.

C542: global_search's title or subtitle is not a field of the entity

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. Each hit of search across entities shows its title and subtitle, read from the entity's fields. A name the entity does not have, or a __ path through something that is not a foreign key, cannot be read.

Fix. Name a field of the entity, or a path through one of its foreign keys (supplier__name). Leave title out to use the first searched field.

C270: A risky change without --allow-destructive

karni command · from karni build (karni_cli.builder)

Why Karni objects. A risky change can lose data or open it to more people: a field or an entity removed, a type narrowed, a choice dropped, a relation pointed elsewhere, access widened. karni plan marks each with ! and the rows it affects, and karni build applies none of them without being told.

Fix. Check each change karni plan lists (a rename keeps its rows: write was: on the field or the entity), then run karni build --allow-destructive, or change karni.yaml.

C271: A module removal

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni.yaml no longer lists a module the project has. Removing a module drops its tables, and karni remove (with the module catalog) is not built yet, so karni build refuses it.

Fix. Put the module back in karni.yaml, or remove it by hand: migrate its app to zero, then take it out of the karni:apps block and its dependency out of pyproject.toml.

C272: A key type switch

karni command · from karni build (karni_cli.builder)

Why Karni objects. Switching an entity's pk between uuid and bigint rewrites every row and every relation to it: a data migration karni build does not write.

Fix. Put pk back in karni.yaml. docs/models.md (choosing the key type) says how to write that migration by hand.

C273: A Karni-owned file was edited by hand

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build rewrites its own files (<app>/karni/, <app>/tests/karni/, frontend/src/pages/karni/, the karni:spec blocks) on every build, and records a sha256 of each in .karni/build.json. A file whose content no longer matches was edited by hand, and a build must not silently lose the edit. The message names the file and the changed lines, and nothing is written.

Fix. Move the change into the project's own file (<app>/models.py, viewsets.py or seeds.py: the subclass of each class, a page or test of your own) or into karni.yaml, then run karni build. Or karni build --force replaces the file and keeps your copy as <file>.orig. Or karni build --adopt <file> makes it the project's: karni build stops managing it and says so on every run.

C274: --adopt names a file karni build does not own

karni command · from karni build (karni_cli.builder)

Why Karni objects. --adopt hands a Karni-owned file or block to the project. The files karni build owns are the ones .karni/build.json lists. Any other file is the project's already.

Fix. Name a file the record lists (classes/karni/api.py), or config/settings.py and frontend/src/routes.tsx for their karni:spec blocks.

C275: The project's code is in the way

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni.yaml asks for something the project already has as code of its own: a model of that name outside the spec, a class of that name in models.py, viewsets.py or seeds.py that does not extend Karni's, or a route a page of the project's holds. karni build never replaces the project's code.

Fix. Rename the entity or page in karni.yaml, or rename (or remove) the project's own class or route. A page of the project's can stay in the spec as - <name>: code.

C276: A module karni build added is not installed

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build adds a new module the way karni add does: the dependency in pyproject.toml and the app in INSTALLED_APPS. The project's interpreter must have it installed before Django can start with it.

Fix. Install the project's dependencies (uv pip install -r pyproject.toml, or docker compose build), then run karni build again: it continues from where it stopped.

C277: makemigrations failed

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build writes the migrations with manage.py karni_makemigrations: the renames first, then Django's makemigrations. A required field added to a table that holds rows needs values Django cannot invent.

Fix. Read the output it shows. For a required field on a table with rows: add it as optional first (str?), fill it, then make it required. Then run karni build again.

C278: migrate failed

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build applies the migrations on the default database and on every alias its entities name.

Fix. Read the output it shows (a database that does not answer, a constraint the rows break), fix it, then run karni build again.

C279: Seeding failed

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build seeds only the tables it created in this build, and only while they hold no row, so demo rows never mix with real data.

Fix. Read the output it shows, fix it (karni seed --help), then run karni build again: it continues from seed.

C280: karni types failed

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build writes the TypeScript types and hooks from the API schema, as karni types does. It needs the backend to print its schema and Node for openapi-typescript.

Fix. Read the output it shows. Install Node (and npm install in frontend/), then run karni build again.

C281: The project's tests fail

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build runs the project's own tests (karni test) after it built the code, including the API tests it wrote in <app>/tests/karni/.

Fix. Run karni test to see every failure, fix the code (the project's files or karni.yaml), then run karni build again: it continues from test.

C282: karni check fails

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni build ends with karni check: the architecture rules, the system checks and the frontend's lint. The code it writes passes them, so a failure comes from the project's code or its environment.

Fix. Run karni check to see every finding, fix them, then run karni build again: it continues from check.

C283: A project class karni build must change has code of its own

karni command · from karni build (karni_cli.builder)

Why Karni objects. karni.yaml removes an entity, and the project's subclass of it (in models.py, viewsets.py or seeds.py) holds code of its own. karni build removes such a class only while it is still the one it wrote.

Fix. Move that code elsewhere or delete the class, then run karni build again.

C284: A marker karni build writes at is missing

karni command · from karni build (karni_cli.builder)

Why Karni objects. The settings block goes right above karni_settings(globals()) in config/settings.py, where every setting takes effect. The pages' routes go before the // karni:page-imports and // karni:routes markers of frontend/src/routes.tsx.

Fix. Restore the call or the markers (see the scaffold's files), or pass --adopt for the block and keep those settings or routes yourself.

C285: The build record cannot be read

karni command · from karni build (karni_cli.builder)

Why Karni objects. .karni/build.json holds the fingerprints of the files karni build owns. It is missing a part, is not JSON, or comes from a newer karni-cli.

Fix. Restore it from version control, or upgrade karni-cli. Deleting it makes karni build treat every Karni-owned file as new: it stops on each one that exists (C273), and --force or --adopt settles them.

C301: No frontend found

karni command · from karni ui detect

Why Karni objects. karni ui detect reads a frontend: its package.json, stylesheets and theme files. It looks in the current directory, in ./frontend, and in the Karni project's frontend/.

Fix. Run it in the frontend directory (the one with package.json), or pass --frontend <dir>.

C302: A generated file was edited, so karni ui detect does not overwrite it

karni command · from karni ui detect (karni-theme.css, karni-primitives.tsx)

Why Karni objects. The files karni ui detect writes belong to the project. Each carries a digest of what was generated. A file whose content no longer matches it (or that has none) was edited by hand, and a re-run must not silently lose those edits.

Fix. Compare with karni ui detect --dry-run and copy what you need, overwrite with --force, or write the new file elsewhere with --output.

C303: A theme source cannot be read

karni command · from karni ui detect (components.json, the stylesheet it names, tailwind.config)

Why Karni objects. karni ui detect maps the project's theme from its files: shadcn/ui's components.json and the stylesheet it names, or a tailwind.config that Node evaluates in the project (with the project's own packages). The message names the file and what failed.

Fix. Fix the file the message names (or run npm install so a config's imports load), or pass --source to read another theme source.

C304: The frontend has no theme of the --source kind

karni command · from karni ui detect --source

Why Karni objects. --source makes karni ui detect read one source (shadcn, tailwind, mui, chakra, mantine) instead of detecting. That source is not in this frontend.

Fix. Run karni ui detect without --source to detect what the frontend has, or name a source it uses.

C310: karni why: the target is malformed

karni command · from karni why, karni why-empty

Why Karni objects. A question names one thing: <resource>/<id> (a row), <resource>.<field> (a field), <resource> (its list), or a status followed by the request id of a recorded request.

Fix. Use one of those forms, e.g. karni why events/42 --as alice@example.com or karni why 403 <request-id>.

C311: karni why: --as is missing

karni command · from karni why, karni why-empty

Why Karni objects. An access decision is always for one user, and only a recorded request carries its own.

Fix. Pass --as with an email, username or primary key, or --as anonymous.

C312: karni why: the project's karni is too old

karni command · from karni why, karni why-empty

Why Karni objects. The question runs as manage.py karni_why in the project, which ships with karni. A project on an older karni does not have it.

Fix. Upgrade karni in the project (pip install -U karni, or rebuild the image), then ask again.

C313: No module or feature of that name in the catalog

karni command · from karni modules show, karni remove (karni_cli.catalog)

Why Karni objects. The catalog holds Karni's modules and built-in features, the copies karni-cli bundles and the manifests (karni.module.toml) of the modules the project has installed.

Fix. Run karni modules list for the names. A module of your own joins the catalog with a karni.module.toml and a karni.modules entry point (docs/modules.md).

C314: A module manifest is not valid

karni command · from karni modules, karni add, karni remove (karni.catalog)

Why Karni objects. Each module describes itself in karni.module.toml: its purpose, what it provides, the questions to ask and the wiring karni add performs. A manifest that does not follow the format, or that names a module or feature the catalog does not have, cannot be used.

Fix. Fix the key the message names (docs/modules.md lists every key), then run karni modules show <name>. A module's own tests check it with karni.testing.assert_module_manifest.

C315: The module conflicts with one the project has

karni command · from karni add

Why Karni objects. A module's manifest lists the modules and features it cannot work next to (conflicts). karni add refuses before it writes anything.

Fix. Remove the other one first (karni remove <name>, or turn the feature off), or choose another module.

C316: Another module requires the one being removed

karni command · from karni remove

Why Karni objects. A module's manifest lists what it needs (requires). Removing a module another added module needs would leave that one broken.

Fix. Remove the module that requires it first (the message names it), then this one.

C317: The module is not in this project

karni command · from karni remove

Why Karni objects. karni remove takes out what karni add wrote: the dependency in pyproject.toml, the app in the # karni:apps block, its middleware, context processors and URL include, and its recorded agent guidance. None of that is in this project.

Fix. Check the name with karni modules list (an added module says added).

C318: A built-in feature is switched by a setting, not added or removed

karni command · from karni add, karni remove

Why Karni objects. Features (two_factor, terms, api_cache and the others) ship with karni. There is no package to add and nothing to take out: one setting turns each on or off.

Fix. Turn it on or off with its key under features: in karni.yaml, or its setting (karni modules show <name> names both).

C319: The module's tables exist in the database

karni command · from karni remove

Why Karni objects. karni remove never drops data. Once the module is out of INSTALLED_APPS, Django can no longer drop its tables, so the choice is made now: drop them while the module is still added, or keep them.

Fix. To drop the tables and their rows, run the printed karni migrate <app> zero, then karni remove again. To keep them in the database, run karni remove --keep-tables.

C320: karni explain needs a code or --failure, not both

karni command · from karni explain

Why Karni objects. karni explain explains one thing: an error code (E104, C101, PAY004, K106) or a captured failure (--failure <id>).

Fix. Run karni explain E104, or karni explain --failure <id> (a failure id, a failed request's id, or last).

C321: A --set value is not FIELD=VALUE

karni command · from karni replay --set

Why Karni objects. --set supplies a value the capture redacted, by its place in the request.

Fix. Write the body path, '=', then the value: --set password=s3cret, --set card.token=tok_1, or --set query:token=abc for a query parameter. The value is parsed as JSON when it can be (numbers, true/false), else used as text.

C322: The project's karni has no debugging commands

karni command · from karni trace, karni replay, karni explain --failure

Why Karni objects. These commands run manage.py karni_trace, karni_replay and karni_failure in the project's interpreter. A karni older than the CLI does not have them.

Fix. Upgrade karni in the project: karni upgrade, or bump karni in pyproject.toml and reinstall (uv pip install -r pyproject.toml, or rebuild the image).

C323: A debugging command failed in the project

karni command · from karni trace, karni replay, karni explain --failure

Why Karni objects. The command ran in the project's interpreter and failed without a coded Karni error, usually because Django could not start (settings, imports, the database).

Fix. Run the command it names with karni manage ... to see the full output, fix what it reports, then retry.

C324: A module or feature needs another, or cannot be next to one

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. The catalog's manifests say what each module and feature requires and conflicts with. The spec lists one without what it requires, or two that conflict.

Fix. Add what the message says is required (under modules: or features:), or leave one of the two that conflict out. karni modules show <name> lists both.

C500: aggregate names a field or path the entity does not have

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. An entity's aggregate: lists what GET <resource>/aggregate/ may group by (group_by) and read (values). Each name is a field of the entity, or a path through its relations (category__parent), and group_by holds at least one.

Fix. Name a field the entity declares, or follow a relation (fk, o2o, m2m) with __ to a field of the entity it points at.

C501: aggregate names a metric that is not one

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. The metrics are count, sum, avg, min, max and distinct_count. aggregate.metrics lists the ones a request may name, all of them when it is left out.

Fix. List metrics from count, sum, avg, min, max and distinct_count, or leave metrics out.

C502: A date bucket in aggregate that does not fit

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A group may take a bucket after a colon (launched_on:year) to group a date or datetime field by year, quarter or month. Another bucket, or one on a field that is not a date, cannot be grouped.

Fix. Write <date field>:year, :quarter or :month, or the field alone to allow every bucket.

C340: Nothing to explain

karni command · from karni explain

Why Karni objects. karni explain answers for a code (karni explain E104) or for pasted text: a traceback, a test failure or a log line read from stdin. It got neither: no code, and stdin was a terminal or empty.

Fix. Pass a code (karni explain E104), or pipe the text in: karni explain - < traceback.txt, or pbpaste | karni explain -. Agents: the explain_text MCP tool takes the text as an argument.

C341: The project's karni has no karni_queries command

karni command · from karni queries

Why Karni objects. karni queries runs manage.py karni_queries in the project's interpreter. That command ships with karni from the release that added karni queries, and the project has an older karni installed.

Fix. Upgrade karni in the project (pip install -U karni, or bump it in pyproject.toml and reinstall), then run karni queries again. karni doctor shows both versions.

C360: A typed-field argument in the model DSL is invalid

karni command · from karni make model (money, percent, email, slug, json, array fields)

Why Karni objects. Typed fields take arguments that name the database guarantee: a money field's ISO 4217 currency, a percentage's integer bounds, the field a slug is built from (it must be declared in the same command), an array's base type.

Fix. Fix the field the message names: price:money:EUR, rate:percent:0:100, slug:slug:title, email:email:unique, meta:json:queried, tags:array:str:40. karni make model --help lists them.

C361: The project's karni has no karni schema

karni command · from karni schema

Why Karni objects. karni schema runs manage.py karni_schema in the project's interpreter. A karni older than the typed field layer does not have it.

Fix. Upgrade the project's karni (karni upgrade, then reinstall the project's dependencies). karni doctor shows which karni the project uses.

C370: A state field spec is invalid

karni command · from karni make model (name:state:...)

Why Karni objects. A state column lists its states (draft,confirmed,cancelled) or its moves (draft>confirmed|draft>cancelled). The first state is where rows start, so every other state must be reachable from it. A state column is never optional.

Fix. Write e.g. 'status:state:draft>confirmed>refunded|draft>cancelled', or list the states and edit the generated transitions={...}.

C371: A range field spec is invalid

karni command · from karni make model (name:daterange, name:datetimerange)

Why Karni objects. Range columns take no arguments: daterange is a PostgreSQL daterange, datetimerange a tstzrange.

Fix. Write 'during:datetimerange' or 'nights:daterange' (add ? for an optional one).

C372: A capacity field spec is invalid

karni command · from karni make model (name:capacity[:total])

Why Karni objects. A capacity counter can name the integer field holding the total, which must be declared in the same command. The counter is never optional.

Fix. Write e.g. 'quantity:int remaining:capacity:quantity', or 'units:capacity' for a counter that starts at 0.

C373: No such setting

karni command · from karni explain <SETTING>

Why Karni objects. karni explain reads Karni's settings and every module's from the source docs/settings.md is generated from: Karni's karni/conf/base.py, each module's conf.py (installed next to karni-cli, or in the project), never Django.

Fix. Check the name against docs/settings.md, and run it inside the project so the project's modules are found. A setting the project defines itself is in config/settings.py.

C374: No such template tag

karni command · from karni explain <tag>

Why Karni objects. karni explain reads the karni-site module's tags and filters from the source docs/public-site.md's table is rendered from (karni_site/tagref.py): in this checkout, installed next to karni-cli, or in the project.

Fix. Check the name against the table in docs/public-site.md (karni_seo, image, editable, get_menu ...), and run it inside a project that installs karni-site. A tag of Django's own ({% if %}, {% url %}) is in Django's documentation.

C375: No such content map key

karni command · from karni explain map.<key>

Why Karni objects. A content map key is written at one level of the map (the map, a model, a source, a key, a value), and karni explain reads them from karni_cli/design/mapref.py, the source of docs/design-content.md's tables.

Fix. Run karni explain map for every key by level, then karni explain map.<key> or map.<level>.<key> (map.source.key, map.value.by).

C400: No open question has this id

karni command · from karni spec answer (karni_cli.spec.questions)

Why Karni objects. karni spec answer writes the answer to a question karni plan --questions asks. The id is not one of them: it is mistyped, or karni.yaml settles that question already (an answered question is gone, and so is one the file was edited to settle).

Fix. Run karni plan --questions --max 0 for the open ids, then karni spec answer <id> <value> with one of them.

C401: The value is not an answer the question takes

karni command · from karni spec answer (karni_cli.spec.questions)

Why Karni objects. A question with options takes one of them (several, comma-separated, when it says so). A question without options takes a value of the types it lists (string, integer, boolean, null, array).

Fix. Pass one of the options karni plan --questions prints under the question, or a value of its type.

C402: The answer cannot be written into karni.yaml

karni command · from karni spec answer (karni_cli.spec.edit)

Why Karni objects. karni spec answer changes only the key the question names and keeps every other line of the file. It writes nothing when it cannot: an anchor or alias shares the key, the key sits in a layout it cannot place a key in, or the result would not pass karni spec validate.

Fix. Set the key the message names in karni.yaml by hand, then run karni spec validate and karni plan --questions.

C420: No recipe of that name

karni command · from karni recipes show, the MCP tool recipes (karni_cli.recipes)

Why Karni objects. Recipes are the folders built into karni-cli and the karni.recipes entry points of its environment. blank is the blank start, the one name that is always there.

Fix. Run karni recipes list for the names, or karni recipes list --match "<the request>" for the closest. A recipe of your own joins with a recipe.toml, a karni.yaml and an entry point (docs/app-spec.md#recipes).

C421: A recipe cannot be used

karni command · from karni recipes list, karni recipes show, the MCP tool recipes (karni_cli.recipes)

Why Karni objects. A recipe is a folder with a recipe.toml that follows its schema, a name that is the folder's (or the entry point's), and a karni.yaml. One that does not, or whose name another recipe has already, is left out and reported.

Fix. Fix the key the message names (docs/app-spec.md#recipes lists every key), or rename the recipe, then run karni recipes show <name>.

C480: No starter of that genre

karni command · from karni new --genre, karni starters show (karni_cli.starters)

Why Karni objects. The starters are the blank start built into karni-cli and the karni.starters entry points of its environment: karni-game ships the runner. A genre whose package is not installed is not there.

Fix. Run karni starters list for the genres (the message names them, and what to install for a known one), then karni new "<Name>" --kind game --genre <genre>.

C481: --genre with a kind or option it cannot go with

karni command · from karni new --genre (karni_cli.commands.new)

Why Karni objects. A starter is a game first: it writes game/<slug>/ and the game's server side. It goes with --kind game only, and not with --recipe or --design, which make an app or a site.

Fix. Add --kind game, or leave --genre out. An app with a game in it is --kind app+game.

C482: A starter cannot be used

karni command · from karni starters list, karni new --genre (karni_cli.starters)

Why Karni objects. A starter is a folder with a starter.toml (name, title, purpose, use_when, usually_changed) and a game/ folder, named by a karni.starters entry point. One that is not, or whose name another starter has already, is left out and reported.

Fix. Fix the folder or the key the message names (docs/game-starters.md), then run karni starters show <genre>.

C440: karni new --recipe with an option it cannot go with

karni command · from karni new --recipe (karni_cli.commands.new)

Why Karni objects. A recipe is an app: its karni.yaml has entities, roles and pages for signed-in users. --design builds a public site from a designer's pages instead, and --kind site or --no-staff-app leave out the React app the recipe's pages live in.

Fix. Leave the option out (--kind app or site+app go with a recipe), or make the project without --recipe and start karni.yaml from karni recipes show <name>.

C441: A recipe's file would replace code of the project's

karni command · from karni build after karni new --recipe (karni_cli.recipes.apply)

Why Karni objects. The first karni build after karni new --recipe writes the recipe's own files (its domain code, seeds and tests) over the stubs it writes itself. It never writes over anything else: a file that holds code of the project's stops the build, and nothing is written.

Fix. Move your code out of the way (rename the file), run karni build again, then put your code back into the recipe's file. To build without the recipe's files, delete it from "recipes" in .karni/build.json.

C442: A recipe's app label, or the recipe itself, is in the project already

karni command · from karni recipes add and karni new --recipe a --recipe b (karni_cli.recipes.compose)

Why Karni objects. A part is one Django app, so its app label must be new to the project, and a recipe is added once. The merge stops before anything is written.

Fix. Rename the project's app (apps.<new label>, with was: on each entity), or remove the part that brought it (karni recipes remove <name>). For a newer version of a part, run karni recipes upgrade <name>.

C443: A recipe's role does not follow the family rules

karni command · from karni recipes add and karni new --recipe a --recipe b (karni_cli.recipes.compose)

Why Karni objects. admin and customer are the family roles every part shares. Every other role of a part must be new to the project, and once the project holds another part it is named <prefix>-<role> (its app label first: bookings-staff), holds no "*" (only admin does) and is not a default role (customer is). Two parts with a staff role would otherwise give one part's staff the other part's rows.

Fix. Rename the role in the recipe's karni.yaml (and every role:<slug> and every test that signs in with it), move a default role's grants to customer, or grant the role its own app's patterns instead of "*".

C444: A route two apps want, or a family page's

karni command · from karni spec validate, karni recipes add (karni_cli.spec.validate, karni_cli.recipes.compose)

Why Karni objects. Each app's pages live under its own apps.<label>.route, and the family pages (home at /, signin, account, search, inbox, settings, people, cart, checkout, orders) belong to Karni and its contracts, never to a part. A part that lists home when the project has one, or a page another part lists, would take a route twice.

Fix. Give the app a route of its own (apps.<label>.route: /<label>), and drop the family page from the recipe's pages.

C445: Two recipes set a module option differently

karni command · from karni recipes add and karni new --recipe a --recipe b (karni_cli.recipes.compose)

Why Karni objects. Each part's module options are merged into one modules: section. A value the project wrote itself wins. Two parts that ask for different values of an option the project did not write leave karni-cli nothing to choose by.

Fix. Write the value you want under modules.<module>.<option> in karni.yaml, then add the recipe again.

C446: A recipe requires what the project cannot have

karni command · from karni recipes add and karni new --recipe (karni_cli.recipes.compose)

Why Karni objects. recipe.toml's requires names core contracts (people, events) and modules, each with an optional version range. A version of a contract this Karni does not have, or a name that is neither a contract nor a module karni-cli knows, cannot be met.

Fix. Upgrade Karni and karni-cli (karni upgrade), install the module (pip install karni-<name>), or use a version of the recipe made for this Karni.

C447: A recipe conflicts with a part or a module of the project

karni command · from karni recipes add and karni new --recipe a --recipe b (karni_cli.recipes.compose)

Why Karni objects. recipe.toml's conflicts names recipes and modules a part cannot share a project with. It is checked both ways: the new recipe's list and each installed part's.

Fix. Remove the other part first (karni recipes remove <name>), or leave the recipe out.

C448: The project does not hold that recipe

karni command · from karni recipes remove and karni recipes upgrade (karni_cli.recipes.compose)

Why Karni objects. Only a recipe app.recipes lists is a part of the project.

Fix. Name a recipe app.recipes lists in karni.yaml.

C449: A part has no record to upgrade from

karni command · from karni recipes upgrade (karni_cli.recipes.parts)

Why Karni objects. .karni/recipes/<name>/ holds the fragment a part was added with and the sha256 of each of its files. Without it, karni-cli cannot tell the recipe's files from the project's changes, so it changes nothing.

Fix. Compare with karni recipes show <name> --files and copy what you want by hand, or restore .karni/recipes/<name>/ from version control.

C460: A tree entity's keys do not fit

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. tree: true makes the entity a TreeModel, which adds a parent field (tree: ordered makes it an OrderedTreeModel, which adds position too). Karni adds that column, so it cannot be a table another system owns, and the entity cannot declare a field of that name.

Fix. Remove tree from an external entity, and remove parent (and position) from the fields of a tree entity, or rename a field that means something else.

C620: A role grant's tree:<path> does not lead to a tree entity

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. tree:<path> reaches the rows whose <path> is a node the user holds or a node below it. The path follows the entity's relation fields (fk, m2m, o2o) and taxonomies, each to an entity of the spec, and the last one must point at an entity with tree: true or tree: ordered. Karni refuses any other path at startup (E490).

Fix. Name the entity's relation to the tree, through relations when needed: tree:region, tree:product__categories. Add tree: true to the entity the path ends at, or grant another scope.

C640: A navigation entry names a page the spec does not have

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. Each menu entry links to the route of a page of pages: an entity's list page, or a named page. An entity whose pages all take an id (detail, form) has no route a menu can link to.

Fix. Name a page of pages by its key (Product, shop.Product, home), add the page to pages, or add list to the entity's pages.

C641: A navigation entry is not valid

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. An entry is a page's key, a page with its options ({label, icon, requires}), or a group: a label that names no page, with its entries (a list, or {items, icon, requires}). Each page is listed once, a group has entries, and an icon is a name such as home.

Fix. Write e.g. - home, - Catalog: [Product, Category] or - Region: {icon: map}.

C642: A navigation requirement is not valid

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. requires is public, authenticated or a permission pattern as in grants (app.entity:action, with * for a part), so role grants and per-user grants open the entry the way they open the API. A pattern that names an entity the spec does not have opens it for nobody.

Fix. Write public, authenticated, or a pattern such as shop.product:view, or leave requires out: each page takes its requirement from its access.

C643: A dashboard tile names something the spec does not have

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. A dashboard: tile counts or lists the rows of an entity of the spec, for the roles of the spec, or places a tile an app declares in code by its key. An entity or a role the spec does not have would show nothing, and two tiles with one key would hide one.

Fix. Name an entity of apps (Shipment, shop.Shipment) and roles of roles, give each tile its own key, or leave entity out to place a code tile (commerce.revenue).

C700: A taxonomy key is not a field name the entity can take

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. Each key of taxonomies becomes a many-to-many field of that name and the list parameters ?<key>= and ?<key>_descendants=, so it is a lowercase field name that does not end in _descendants, and it is not a field a mixin or the tree already gives the entity.

Fix. Rename the key, e.g. taxonomies: {region: Region}.

C701: A taxonomy does not point at a tree entity

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. A taxonomy tags rows with the nodes of a hierarchy, and its filters, facets and the tree:<key> scope walk the tree below a node. The target must be an entity of the spec with tree: true or tree: ordered. Karni refuses another target at startup (E571).

Fix. Point the key at a tree entity (Name or app.Name), or add tree: true to the entity it names. For tags without a hierarchy, declare a plain m2m field instead.

C702: A taxonomy key names a field that is not a many-to-many to its tree

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. When the entity declares a field under a taxonomy's key, Karni adopts that field instead of generating one. Only an m2m to the same tree entity can be adopted (E572).

Fix. Remove the field and let the taxonomy generate it, declare it as m2m:<the tree entity>, or rename one of them.

C703: An external entity declares taxonomies

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. A taxonomy adds a table of tags next to the entity's table and joins them. An external entity's table belongs to another system, and Karni never writes tables for it.

Fix. Remove taxonomies from the external entity, or remove external and let Karni own the table.

C520: An entity's cache value is not valid

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. cache: on an entity is its viewset's response caching: how many seconds a cached response lives (Cache(ttl=...)), or false (Uncached). true says nothing the setting does not, and a lifetime of 0 or less caches nothing.

Fix. Write cache: 60 (any whole number of seconds above 0), or cache: false to never cache the entity. Leave the key out to follow KARNI_API_CACHE_TTL.

C521: A cached entity reads a table Karni does not see written

karni command · from karni spec validate and karni plan (karni_cli.spec.validate)

Why Karni objects. With api_cache on, a cached response is cleared when Karni sees a write to a table it reads. An external table, a table on another database, or an external entity reached through ?expand= is written by another system, so its cached responses would stay stale until they expire. karni check refuses the same viewset in the project.

Fix. Add cache: <seconds> to the entity (how stale a response may be), or cache: false to never cache it.

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A detail page's related tabs ({detail: {related: [...]}}) each list the rows of another entity that point at the page's entity. The name is not an entity of the spec, or several apps define it.

Fix. Name an entity of the spec (app.Entity when two apps define it), or Entity.field.

karni command · from karni spec validate, karni make page --related (karni_cli.spec.validate)

Why Karni objects. A related tab is a table of the other entity's rows filtered to this record, and the list of that entity filters by its fk fields. The entity has no fk to the page's entity, or the field named is not one (a m2m or an o2o cannot back a tab).

Fix. Add a fk field to the page's entity on the other entity, or name the fk it has.

karni command · from karni spec validate, karni make page --related (karni_cli.spec.validate)

Why Karni objects. The entity named has two or more fks to the page's entity (a deal's company and its partner), so the tab must say which rows it lists.

Fix. Write Entity.field, one tab for each relation you want.

karni command · from karni spec validate, karni make page --related (karni_cli.spec.validate)

Why Karni objects. Each related tab is one relation. Deal and Deal.company name the same one when Deal has one fk to the page's entity.

Fix. List each related tab once.

C680: A column set names a field the entity does not have, or one twice

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. column_sets become Karni.column_sets, the presets of the React table's column set menu, and karni check refuses a set that names a field the model does not have (karni.E551) or lists one twice (karni.E553).

Fix. Name fields the entity declares (or id, created_at and updated_at), each once per set.

C681: A column set has no columns, or a name that is not snake_case

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. A set's name is what a user's choice is remembered by and its label in the Columns menu (financial reads Financial), and a set without columns shows an empty table.

Fix. Name the set in snake_case (default, financial) and list at least one field.

C580: The project's karni has no context slices

karni command · from karni_cli.commands.context

Why Karni objects. karni context --summary, --app and --model ask manage.py karni_context for a slice. The project's karni predates them.

Fix. Upgrade karni in the project (pip install -U karni), or run karni context without those flags.

C581: git cannot say which files changed

karni command · from karni_cli.commands.check.changed_files; karni check --changed

Why Karni objects. karni check --changed asks git for the files changed in the working tree and the index (against HEAD or the ref given), plus untracked files. git is missing, the project is not in a git repository, or git does not know the ref.

Fix. Run it inside a git repository (git init, then commit), pass a ref git knows (a branch, a tag, a commit), or run karni check without --changed.

C582: The project's karni has no check cache

karni command · from karni_cli.commands.check

Why Karni objects. karni check --changed and --no-cache pass options to manage.py karni_check that the project's karni predates.

Fix. Upgrade karni in the project (pip install -U karni), or run karni check without those flags.

C720: A protected file field needs the storage module

karni command · from karni spec validate, karni plan and karni make model (file:protected, image:protected)

Why Karni objects. file:protected and image:protected are ProtectedFileField and ProtectedImageField of the karni-storage module: files stored privately and downloaded only through the row's own viewset. Without the module the model cannot import them.

Fix. Add the module: modules: {storage: {provider: aws}} in karni.yaml, or karni add storage for karni make model. Or make the field a plain file or image.

C740: app.api_version is not a version name

karni command · from karni spec validate (karni_cli.spec.validate)

Why Karni objects. app.api_version is the API's current version. karni build writes it as KARNI_API_VERSION, and the API is then mounted at /api/<version>/. The name is a URL segment: lower case letters, digits and -, starting with a letter or digit, at most 16 characters, such as v1.

Fix. Write a name like v1 or 2026-11, or leave the key out for an unversioned API.

C760: An entity's bounds do not fit its fields

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. bounds gives a number, date or datetime field its lowest and highest value. It names a field of the entity, takes min or max, a number for a number and a date, $now or $today for a date, and becomes class Karni: bounds (E990 when a write breaks it).

Fix. Name a number, date or datetime field, e.g. bounds: {quantity: {min: 1}} or {expected_close: {min: $today}}.

C761: An entity's unique does not fit its fields

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. unique lists fields whose values are unique together among the live rows, as a list or as {fields, where}. It becomes a partial unique index, so it names fields of the entity, its where filter takes fixed values only, and an external entity takes none.

Fix. Write unique: [[slot, member]] or [{fields: [slot, member], where: {status: {not: cancelled}}}] with fields of the entity.

C762: An entity's targets name something that is not a foreign key

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. targets maps a foreign key of the entity to a row filter the row it points at must match (E993 when a write breaks it).

Fix. Name an fk or o2o field: targets: {listing: {active: true}}.

C763: An entity's frozen names a field it does not have

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. frozen maps a field to true (never changes after create) or to a row filter (cannot change while the row matches it, E994).

Fix. Name a field of the entity: frozen: {slot: true, value: {stage: won}}.

C764: An entity's delete rule does not fit

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. delete takes when (a row filter the row must match to be deleted) and blocked_by (entities with an fk to this one whose live rows keep it). E995 refuses such a delete.

Fix. Write delete: {when: {status: pending}, blocked_by: [Deal]}, naming an entity that points here (Entity.field when it has two fks to it).

C765: An entity's moves do not fit its states and fields

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. moves maps a state of the entity's state field (or a boolean field becoming true) to requires (fields), needs (entities that point here) and stamps (date or datetime fields). E996 refuses a move that misses one.

Fix. Write moves: {lost: {requires: [lost_reason], stamps: [closed_at]}} with a state the field declares and fields of the entity.

C766: An entity's actions do not fit its states or roles

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. actions are row actions: from (the states it runs from), to (the state it moves to), by (who may, in access words) and field (the state field when there are two). They become the viewset's row_actions and x-karni-actions (E997 when called in another state).

Fix. Name states of the entity's state field and access words of the spec: actions: {ship: {from: paid, to: shipped, by: owned:listing__seller__user}}.

C767: A row filter cannot be read

karni command · from karni spec validate (karni_cli.spec.rules)

Why Karni objects. A row filter is {path: value}: a field or a path through relations (ending in gt, gte, lt, lte, in or isnull), and a literal, $me, $now, $today, $<field of the row> or {not: <value>}. targets, frozen, delete, unique and blocked_by take one.

Fix. Fix the path or the value the message names: {active: true}, {seller__user: {not: $me}}, {company: $company}.

C780: The project's karni predates suggestions

karni command · from karni_cli.suggest.core_suggestions

Why Karni objects. karni suggest and karni doctor ask the project's interpreter for its suggestions (manage.py karni_suggest), and the project's karni does not have that command.

Fix. Upgrade karni in the project (pip install -U karni). karni check and karni doctor still run and print the suggestions that read karni.yaml and the README.

C781: manage.py karni_suggest failed

karni command · from karni_cli.suggest.core_suggestions

Why Karni objects. The project could not be started, or something in it prints to stdout at startup, so the command's JSON did not come back.

Fix. Run python manage.py karni_suggest --json in the project to see the error. karni check shows the same startup problem.

C850: The project folder already exists

karni command · from karni new

Why Karni objects. karni new writes a new folder named after the project and never writes into one that is there, so it cannot overwrite your files.

Fix. Pick another name or --output-dir, or remove or rename the folder if it is a leftover. To change an existing project, use karni make, karni add or karni build.

karni command · from karni build (the check step)

Why Karni objects. A code page in karni.yaml is a page of the project's own: karni build leaves it alone, so a navigation entry that names it links to a route nothing serves until the project writes the page (karni.E533).

Fix. Add the page's route to frontend/src/routes.tsx (karni make page <name> --kind blank starts one), then run karni build again. The routes are in the message.

C841: A feature's extra is in pyproject.toml but not installed

karni command · from karni build

Why Karni objects. A feature switched on in karni.yaml (two_factor needs karni[2fa], social_login needs karni[social-token]) needs a package the project's interpreter does not have. The build names the extra on the karni dependency and stops before the migrations, which would fail with a bare ModuleNotFoundError.

Fix. Install the project's dependencies (uv pip install -r pyproject.toml, or docker compose build), then run karni build again: it continues from the step that stopped.

C840: karni add was given a name that is not a module

karni command · from karni add

Why Karni objects. The name is neither in the module catalog nor a module installed in the project's interpreter (a distribution with a karni.module.toml). Wiring it would put an app into INSTALLED_APPS that Python cannot import, so every Django command would fail.

Fix. Check the spelling against karni modules list. A third-party module is installed first (pip install <distribution>), then added.

C830: karni make test --role names a role the project does not declare

karni command · from karni make test (karni_cli.generators.apitest)

Why Karni objects. The test acts as a user holding that role. A role KARNI_ROLES and the added modules do not declare grants nothing, so every request would be refused and the test would fail when it runs.

Fix. Pass one of the declared roles the error lists, or declare the role in KARNI_ROLES (config/settings.py) first.

C860: Tool-specific agent files are deprecated

karni command · from karni rules sync, karni doctor (karni_cli.adapters)

Why Karni objects. AGENTS.md is the one agent file Karni writes, and coding agents read it. Since 0.5.0 karni new no longer writes one tool's instruction file or command folder. A project that already has them keeps getting them updated by karni rules sync until 1.0, which stops updating them and removes them.

Fix. Point your tool at AGENTS.md. Keep project guidance in karni.rules.py, which feeds AGENTS.md, and delete the files the warning names once your tool reads AGENTS.md (docs/migrations/0.5.md).

Agent rules (K)

karni rules lists them in one screen. karni check and the architecture tests (pytest --pyargs karni.testing.architecture) enforce them.

K001: karni context first. Trust it.

agent rule, must · enforced by review

Rule. Run karni context before reading any files. It prints the current apps, models, viewsets, UI components, hooks, pages, public site routes and installed modules in a few hundred tokens. Trust it. On a large project read one area at a time: karni context --summary, then karni context --app <label> or --model <name> (--max-tokens N caps any of them).

Why Karni objects. The inventory is derived live from the app registry, the router and the @karni/ui manifest, so it is never stale and costs far fewer tokens than crawling source.

Fix.

K002: Rules beat other frameworks' habits.

agent rule, must · enforced by review

Rule. Run karni rules at the start of a session and follow what it returns. AGENTS.md only points here.

Why Karni objects. One source of truth exposed through the CLI cannot drift between tools.

Fix.

K003: Model changed: make migrate, then karni types.

agent rule, must · enforced by review

Rule. After any model change run make migrate && karni types.

Why Karni objects. Migrations and the frontend's TS types + typed hooks are derived from the models. Skipping either leaves the API and the UI out of sync.

Fix.

K004: karni rules --check FILE, then karni check pre-commit.

agent rule, must · enforced by review

Rule. Run karni rules --check <file> on files you write and karni check before committing. Every enforced rule fails the build, and nothing only warns. It ends with suggestions (SUG): read each and apply its fix.

Why Karni objects. Enforced rules fail CI anyway, so catching them while editing is cheaper.

Fix.

K005: Opt-outs need an inline reason.

agent rule, error · enforced by opt-out-reason, eslint-comments/require-description

Rule. Opt-outs are inline and REQUIRE a reason. Python: # karni: allow(<rule-id>): <why>. ESLint: // eslint-disable-next-line karni/<rule> -- <why>. jscpd: // jscpd:ignore-start -- <why>.

Why Karni objects. Rules without escape hatches cause forks, and a fork is worse than a duplicate. Every exception must still say why, so it can be reviewed.

Fix. Write the reason after the marker.

K006: Procedures: karni rules --procedure NAME.

agent rule, should · enforced by review

Rule. Prefer the standard procedures for routine work: new-model, new-page, add-module, new-module, site-from-design. Run one with karni rules --procedure <name>. A request that starts with /<name> asks for that procedure.

Why Karni objects. The procedures encode the shortest correct path for routine work.

Fix.

K007: Commands: karni --help.

agent rule, should · enforced by review

Rule. Use the project commands (karni --help lists them all). make up starts the stack. make migrate runs makemigrations + migrate. karni types regenerates TS types + typed hooks from the API schema. karni check runs architecture and system checks. karni context prints the inventory. karni make <type> scaffolds. Runners like karni test, karni shell, karni routes, karni worker, karni schedule list wrap manage.py/celery/pytest.

Why Karni objects. They run inside the right interpreter (project .venv or compose service).

Fix.

K009: Scaffold with karni make.

agent rule, must · enforced by review

Rule. Create apps, models, viewsets, serializers, migrations, tasks, schedules, events, listeners, management commands, services, middleware, pages, components, modules, site apps and their views with karni make <type> (karni make --list lists the types, --dry-run previews, --help works per type). Never hand-create a file, class or route a generator makes. Run the generator, then edit what it wrote.

Why Karni objects. Generators emit the conventions in one step (BaseModel, a mandatory access declaration, settings and route markers, ruff-clean imports) and are tested to pass every rule. Hand-written scaffolding drifts.

Fix. Delete the hand-written scaffold and run the matching karni make command.

K013: Traceback: karni explain - first.

agent rule, must · enforced by review

Rule. Paste a traceback, a test failure or a log line into karni explain - (stdin, or the MCP tool explain_text) before reading it by hand. It names the Karni failure class, the cause, where (the first project frame, file:line), the fix and the docs link, and says plainly when it does not recognise the failure.

Why Karni objects. Rebuilding context from a traceback is the expensive part of debugging. The catalogue already knows Karni's failure classes (codes, query budgets, access outcomes, database, migrations, settings, CSRF/CORS) and their fixes.

Fix.

K014: N+1: karni queries URL --as USER first.

agent rule, must · enforced by review

Rule. Before hunting an N+1 in serializers, run karni queries <endpoint> --as <user> (MCP tool queries). It runs the endpoint in-process, groups the repeated queries by the serializer field and relation that caused them, says why the optimiser did not fetch them and prints the hint that fixes it.

Why Karni objects. The optimiser derives select_related/prefetch_related itself and records what it cannot see (method fields, properties, to_representation), so the cause and the fix come from the same knowledge instead of guesswork.

Fix.

K015: Row/field/action missing or refused: karni why first.

agent rule, must · enforced by review

Rule. When a row, field or action is unexpectedly missing or refused (a 403, a 404, an empty list, a field absent from a response), run karni why <resource>/<id> --as <user> [--action ...], karni why <resource>.<field> --as <user>, karni why-empty <resource> --as <user> or karni why 403 <request-id> (MCP: why, why_empty) before reading viewsets, KARNI_ROLES or the access layer, and act on its verdict.

Why Karni objects. Access bugs raise no error: the row is just absent. karni why computes the decision with the code that enforces it and prints the user's roles, the grants and where each comes from, the predicate that decided, the row's values, file:line and the fix. That is one call instead of reconstructing the rules from source.

Fix. Run the matching karni why command and apply the fix it prints.

K030: A failure: karni explain --failure first.

agent rule, should · enforced by review

Rule. When a request or task fails in development, run karni explain --failure <id> (or --failure last) before reading a traceback by hand: it names the failing frame with its locals, the user and their roles, the SQL and the next steps.

Why Karni objects. The snapshot was taken when it failed, with secrets redacted. Reconstructing the same context from a traceback and the code costs far more.

Fix.

K031: Follow a request: karni trace ID.

agent rule, should · enforced by review

Rule. To see what a request set in motion (Celery tasks and their retries, email, webhooks, change-log entries) run karni trace <request-id> (its X-Request-ID response header, or last) instead of correlating log timestamps.

Why Karni objects. The request's tasks, retries, email and audit entries all carry its id, so the trace is exact. Timestamps from several processes are not.

Fix.

K032: Confirm a fix: karni replay ID --as USER.

agent rule, should · enforced by review

Rule. After changing access, roles or fixing a bug a request hit, confirm it with karni replay <request-id> [--as <email|username|pk>]. It re-runs the captured request against the current code and prints what changed ("was 403, now 200"). Writes are rolled back unless you pass --commit.

Why Karni objects. Replaying the real request as the real user tests the case that failed, not the one you think failed.

Fix.

K101: Models inherit BaseModel or compose its mixins.

agent rule, error · enforced by model-base

Rule. Models inherit karni.models.BaseModel (= UUIDModel + TimestampedModel + SoftDeleteModel + AuditedModel), or compose those mixins directly when a model should not have all four (e.g. an append-only log: UUIDModel, TimestampedModel). Declare APIMeta / AdminMeta only for fields that must be hidden, read-only or write-only. BigIntBaseModel (experimental) is the same with an integer id, chosen per model in its class line; karni context shows each model's key type.

Why Karni objects. The mixins supply the primary key (a UUID, or an integer with BigIntBaseModel), timestamps, soft delete, audit stamping and the managers the derived API/admin rely on. The exception is a table or view another system owns: a plain models.Model with class Meta: managed = False and class Karni: external = True (experimental, karni make model <Name> --external --table <table>), which Karni only reads unless writable = True.

Fix. Inherit karni.models.BaseModel or BigIntBaseModel (or compose its mixins).

K102: Viewsets inherit BaseViewSet.

agent rule, error · enforced by viewset-base

Rule. Viewsets inherit karni.api.BaseViewSet, usually just model = X plus its access declaration (K109) (+ search_fields). The auto-router registers it.

Why Karni objects. BaseViewSet derives serializer, filters, pagination, permissions and schema.

Fix. Inherit karni.api.BaseViewSet and set model = X.

K103: No ModelAdmin. Use AdminMeta.

agent rule, error · enforced by admin-convention

Rule. Do not register a plain ModelAdmin. Declare AdminMeta on the model (the admin is derived), or subclass karni.admin.KarniModelAdmin.

Why Karni objects. The derived admin stays consistent with the model and the API.

Fix. Delete the admin class and use AdminMeta, or subclass KarniModelAdmin.

K104: Raw SQL only under /sql/.

agent rule, error · enforced by raw-sql

Rule. No raw SQL (.raw(), cursor.execute(), RawSQL) outside */sql/* or migrations.

Why Karni objects. Raw SQL bypasses managers (soft delete, owner scoping) and the ORM's safety.

Fix. Use the ORM, or move the query into a sql/ module.

K105: HTTP clients only in /services/.

agent rule, error · enforced by http-client

Rule. Import requests / httpx / urllib.request only in */services/* or */providers/* modules.

Why Karni objects. External calls in one layer are mockable, retryable and auditable.

Fix. Move the call into a services module and call that.

K106: No Meta-only ModelSerializer.

agent rule, error · enforced by redundant-serializer

Rule. Never write a Meta-only ModelSerializer. BaseViewSet(model=X) generates it.

Why Karni objects. A redundant serializer silently diverges from the generated one.

Fix. Delete it. Customise via APIMeta or override get_serializer_class().

K107: No duplicated code.

agent rule, error · enforced by duplicate

Rule. No structurally duplicated code (8+ identical statements in two places). Reuse the named Karni API or extract one implementation.

Why Karni objects. Duplicates are where boilerplate creeps back in.

Fix. Call the existing implementation instead of copying it.

K108: Off-request writes: current_user(u).

agent rule, must · enforced by review

Rule. AuditedModel stamps created_by/updated_by from the current request. Outside a request (Celery tasks, management commands) nothing is stamped unless you wrap the writes in with current_user(user): from karni.middleware. Never assign created_by/updated_by by hand.

Why Karni objects. One stamping path keeps the audit trail trustworthy under WSGI, ASGI and workers.

Fix. Import current_user from karni.middleware and wrap the writes in with current_user(user): ....

K109: Viewsets declare access: karni explain access.

agent rule, error · enforced by viewset-access

Rule. Every BaseViewSet declares access: Granted() (the default: the roles' grants for the model, row-scoped) or Access(read=..., write=...) built from Owned("<fk to user>"), HasRole(...), Authenticated(), Public() and Where(lambda request: Q(...)) with | / &. Reads are public only when you write Public(). No access denies every request. Unscoped(reason=...) is the explicit opt-out.

Why Karni objects. One declaration compiles into both the request gate and the row filter, so neither can be forgotten. A forgotten permission class fails open silently.

Fix. Add access = Granted() (or Access(read=..., write=...) for a custom rule).

K110: Row rules: in access.

agent rule, error · enforced by access-override

Rule. Express who sees which rows in access (Where(...) for custom logic, @action(..., access=...) for one action). An overridden get_queryset is still read-scoped, so never use it to widen. Overriding filter_queryset_for_user needs # karni: allow(access-override): <why>. Rows under the nodes of a tree a user was granted are the tree:<path> scope of a grant, never a hand-written subtree filter.

Why Karni objects. The queryset is the authoritative layer: lists, details, actions, relation PKs and ?expand= all go through the read scope, so a bypass leaks everywhere.

Fix. Move the condition into access (Where(lambda request: Q(...))), or add the marker.

K111: Paginate lists. No N+1.

agent rule, error · enforced by unpaginated-action, query-scaling

Rule. Lists stay bounded and flat. A list-returning @action returns self.paginated_response(queryset), never Serializer(qs, many=True).data. pagination_class = None needs pagination = Unpaginated(max_rows=N, reason=...). Query counts must not grow with rows: BaseViewSet derives select_related/prefetch_related from the serializer, so hint only what it cannot see (SerializerMethodField, properties) with select_related = [...] / prefetch_related = [...] on the viewset. Raise a budget only with query_budget = Budget(list=N, reason=...).

Why Karni objects. An unpaginated list or an N+1 passes with test data and falls over with real data. The scaling check (2 vs 12 rows) and per-action query budgets catch both in CI.

Fix. Return self.paginated_response(qs) and hint opaque fields with prefetch_related.

K113: Audited models: no update()/bulk_update().

agent rule, error · enforced by audited-bulk-write

Rule. A model with class Karni: audit = True keeps field-level change history through save() and delete(). QuerySet.update() and bulk_update() bypass it and leave no entry. Save the instances instead, or opt out with # karni: allow(audited-bulk-write): <reason>.

Why Karni objects. A silent gap in the history is exactly the bug someone discovers during an audit. The rule names every bulk write on an audited model at build time.

Fix. Loop and save(), or add the allow marker with the reason.

K114: Money: MoneyField, never float.

agent rule, must · enforced by review

Rule. Declare what a value is with karni.fields so the database enforces it: money is MoneyField(currency="EUR") or currency_field=... (never FloatField: karni.E960 fails boot), counts that must never go negative are QuantityField, rates PercentField, ISO codes CountryField/CurrencyField, phone numbers PhoneField, emails EmailField(unique=True) (case-insensitive). Uniqueness on soft-deletable models: unique=True on a Karni field, or LiveUniqueConstraint(fields=[...]) in Meta.constraints, so a deleted row frees its value. Pick on_delete deliberately (karni.W965 flags CASCADE on financial or audited models). karni schema <app> shows every column, constraint and index and why it exists. Long text a page shows formatted is MarkdownField (name:markdown). A model with many fields declares class Karni: field_groups (form and detail sections or tabs) and column_sets (table presets) instead of hand-built screens.

Why Karni objects. Float money, free-text codes and case-sensitive unique emails pass every test and fail in production. A database constraint is the one layer raw SQL, bulk updates and other services cannot skip.

Fix. karni make model Product price:money:EUR stock:quantity country:country email:email:unique (field types: karni make model --help).

K115: Status column: StateField + transitions.

agent rule, must · enforced by review

Rule. A lifecycle column (status, state, stage) is karni.fields.StateField(states=[...], transitions={...}), never a free or choices CharField. Move it with row.transition("status", "confirmed") (or assign and save()), never with QuerySet.update(). The column CHECKs the declared states. An illegal move is E980 (a 400), a concurrent one E981 (a 409).

Why Karni objects. A free status column takes any value in any order from any code path. Tests pass and production rows end up refunded without ever being paid.

Fix. status = StateField(states=[...], transitions={...}), or generate it: karni make model ... 'status:state:draft>confirmed|draft>cancelled'.

K116: Stock/slots: reserve(), no_overlap. No check-then-write.

agent rule, must · enforced by review

Rule. Anything with a limited quantity (seats, stock, licences) is a CapacityField consumed only with karni.capacity.reserve(row, n) / release() inside transaction.atomic(). Anything that must not overlap in time (rooms, slots, appointments) declares class Karni: no_overlap = NoOverlap("<resource>", "<range>", ignore={...}). Never count, compare and then write in Python.

Why Karni objects. A read-then-write check never fails in tests and double-books in production: two requests pass it together. The database refuses the oversell or the overlap (CHECK, EXCLUDE) and Karni names it (E985 / E984, a 409).

Fix. Inside with transaction.atomic(), call reserve(tier, n), then create the booking. Slots: no_overlap = NoOverlap('room', 'during', ignore={'status': ['cancelled']}).

K201: Compose @karni/ui. No raw table/form/input.

agent rule, error · enforced by karni/no-raw-elements

Rule. Screens compose @karni/ui components (Page, ResourceTable, ResourceForm, ResourceDetail, ...). Never hand-roll a table or form: no raw <table>/<form>/<input>/<select>/<textarea>/<details>. Dashboards and reports compose DashboardGrid, ChartCard, DataTable (computed rows), ComparisonTable, Accordion and MarkdownView.

Why Karni objects. The components already handle data, validation, a11y and theming.

Fix. Compose ResourceTable / DataTable / ComparisonTable / Accordion / ResourceForm / Input / Select from @karni/ui.

K202: Pages: max 50 lines.

agent rule, error · enforced by karni/max-page-lines

Rule. Page files stay at 50 lines or fewer. Past that you are rebuilding something Karni ships, so use the component's props.

Why Karni objects. A long page is reimplementing a component.

Fix. Use the components' props and move logic into hooks.

K203: Import only the @karni/ui barrel.

agent rule, error · enforced by karni/no-deep-imports

Rule. Import only the public @karni/ui barrel, never @karni/ui/dist/* or /src/*.

Why Karni objects. Internals change without notice. The barrel is the versioned API.

Fix. Import from "@karni/ui".

K204: Data only via Karni hooks. No fetch/axios.

agent rule, error · enforced by karni/no-direct-http

Rule. Data access only via @karni/ui hooks (useResourceList, useResourceItem, useResourceMutations, the KarniClient) and the typed hooks generated by karni types. No fetch/axios/XMLHttpRequest/WebSocket outside src/api/.

Why Karni objects. The hooks share caching, auth, errors and query-key invalidation.

Fix. Use the generated typed hook or useKarniClient().

K205: No duplicated frontend code.

agent rule, error · enforced by jscpd

Rule. No duplicated frontend code above the frontend/.jscpd.json threshold.

Why Karni objects. Duplicates are where boilerplate creeps back in.

Fix. Extract one component or hook, or compose the existing @karni/ui one.

K206: Style with token classes. No literal values.

agent rule, error · enforced by karni/no-style-literals

Rule. Style with the @karni/ui preset's classes (bg-primary, p-4, rounded-md, z-popover), which read --karni-* tokens. No arbitrary literals (w-[13px], bg-[#fff]), palette colours (bg-slate-500) or literal inline styles. It fails the build where the project enables karni/no-style-literals.

Why Karni objects. One stylesheet (or karni ui detect) then rethemes every screen.

Fix. Use a preset class, or add the token to the project's karni-theme.css.

K301: Domain code only. Extend Karni.

agent rule, must · enforced by review

Rule. Karni already implements everything generic. You write only domain code. Extending Karni is always cheaper than reinventing it.

Why Karni objects. Generic code written per project is the boilerplate Karni exists to remove.

Fix.

K302: Never write auth, admin, serializers, routers, settings, infra, or app-screen tables and forms.

agent rule, must · enforced by review

Rule. Never write auth flows, user models, admin registration, serializers, routers, settings, Docker/Compose config, Celery config, HTML tables, forms, or detail views, nor a search over several models (declare class Karni: search on each model: GET /api/search/ and <GlobalSearch> serve it). Karni provides all of these. Never write a table of per-user permissions either: access given to one user is a per-user grant (features: user_grants, karni.accounts.grants), which Granted() already reads. If you think you need one, you need an override on an existing Karni base instead. The tables, forms and detail views meant here are app screens. A public server-rendered site (K309) is the one place for hand-written HTML pages, and its forms still post to a BaseViewSet.

Why Karni objects. Each of these ships in Karni with tested defaults and override points. A public site is the client's own markup, so it has its own rule.

Fix. Find the Karni base that provides it (karni context BASES) and override it.

K303: Extend via props/methods, never fork.

agent rule, must · enforced by review

Rule. If an existing component or base class almost fits, extend it through its override props / hooks (columns, fields, slots, AdminMeta, APIMeta, overridable methods). Do not create a parallel variant.

Why Karni objects. A forked variant stops receiving fixes and doubles the surface to maintain.

Fix.

K304: No extra state/form/table/HTTP/CSS library.

agent rule, must · enforced by review

Rule. The stack is fixed. Do not introduce a state library, form library, table library, HTTP client or CSS framework beyond what Karni ships (TanStack Query/Table, react-hook-form, Zod, Tailwind, Radix via @karni/ui). Backend HTTP clients are allowed only in services modules (K105).

Why Karni objects. Every extra library is a second way to do something Karni already does.

Fix.

K305: Per entity: models.py and viewsets.py.

agent rule, must · enforced by review

Rule. Backend code per entity goes in <app>/models.py and <app>/viewsets.py, nothing else. No admin.py, serializers.py or forms.py. urls.py is only for non-API endpoints such as webhooks and a public site's pages (K309), because viewsets ride the auto-router.

Why Karni objects. Admin, serializers, filters, routes and schema are derived from those two.

Fix.

K306: App pages: frontend/src/pages/. Public site pages: K309.

agent rule, must · enforced by review

Rule. App screens (the React frontend) live in frontend/src/pages/, one file per page, with the route registered alongside the existing pages. Public server-rendered pages do not go there (K309). A menu that differs per user is data, not code: KARNI_NAVIGATION (or navigation: in karni.yaml) with <Layout navSource="server">, never a menu a component filters by role.

Why Karni objects. The page cap (K202) and the inventory (karni context PAGES) rely on it.

Fix.

K307: Cross-project code: a Karni module (karni modules list).

agent rule, should · enforced by review

Rule. Anything reusable across projects belongs in a Karni module (a karni_<name> package), not in this project. Say so instead of building it. Read the catalog first: the CATALOG lines of karni context, karni modules list and karni modules show <name> list every module and built-in feature (payments, approvals, login as a user, a public site, two-factor sign-in, sign-in with a code or with Google, Microsoft or Apple, terms acceptance, per-user grants, response caching), whether the project has it, its options and the questions to ask. Add a module with karni add <name> (or modules: in karni.yaml), turn a feature on with its setting (or features:), and take a module out with karni remove <name>, which never drops its tables. A mobile client needs a URL that does not move: set api_version: under app: in karni.yaml (KARNI_API_VERSION) for /api/v1/, deprecation headers and a client per version, and never write /v1/ routes by hand.

Why Karni objects. Code that would be written more than once belongs in Karni, never per project. Each catalog entry is tested, and rebuilding one costs more tokens than adding it.

Fix. Run karni modules show <name>, answer its questions, then karni add <name>.

K308: Modules: configure via settings.

agent rule, must · enforced by review

Rule. Configure an installed module only through the settings it documents. Never patch its internals.

Why Karni objects. Patched internals break on the module's next release.

Fix.

K309: Public site: a site app with Django views and templates.

agent rule, must · enforced by review

Rule. A public, server-rendered website (SEO-indexed pages in the client's own HTML and CSS) is a site app, not React pages. karni make site <app> creates it: function views in <app>/views.py, <app>/urls.py with app_name, included at path("", ...) in config/urls.py (which replaces the welcome page), templates in <app>/templates/<app>/ and the site's CSS and JS in <app>/static/<app>/. A designer's static pages go in with karni import design <dir> --app <app> --editable, which keeps the markup as written, never by copying them by hand. karni make view <name> --app <app> adds a page. Text and images a client may change are {% editable %} and {% editable_image %} blocks, navigation is {% get_menu "<name>" as items %} looped in the design's markup, and the site's name, logo and contact details are site: never hard-coded, and never a model or template tag of the project's own. The site's runtime (these tags, {% ifactive %}, {% csp_hash %}, the error pages, redirects) is the karni-site module, never project code. Views read content through each model's default manager (Model.objects, so model scopes apply and soft-deleted rows stay hidden) and filter drafts themselves. A public form (a contact form, a booking request, a sign-up) is karni make form <name> <field:type> ... [--notify SETTING] and {% karni_form "<name>" %} in the page: it saves through a BaseViewSet with create=Public(), works without JavaScript, carries the CSRF token and a honeypot, and its script, rate limit and email come from Karni. Never write a form view, a throttle or a form script for it. The site's page test, <app>/tests/test_pages.py, passes every page's URL to assert_pages: give a page whose path has a capture a real URL there. The React rules (K201, K202, K206) apply to app screens only.

Why Karni objects. A marketing site must be crawlable and faithful to the client's design, which the app-screen rules forbid for good reason. One Django app with plain views keeps the API, the admin and the access layer as the only write path.

Fix. Run karni make site <app>, then karni import design <dir> --app <app> --editable for a designer's pages or karni make view <name> --app <app> per page, and karni make form for each form. Karni's docs page public-site covers editable content, SEO and public forms.

K310: Before karni build: ask only karni plan --questions.

agent rule, must · enforced by review

Rule. When the app is described in karni.yaml, run karni plan --questions before karni build and ask the user only the questions it prints, in its order, with their options and defaults. Write each answer with karni spec answer <id> <value> (or in karni.yaml), and run it again until none is open. Never ask about anything karni.yaml already settles, nor about the stack, names, labels, colours or page titles: those are yours to choose.

Why Karni objects. Karni chooses the questions with fixed rules over the spec and the module manifests (owners, access, the sign-up role, the kind, each module's and feature's asks), so every agent asks the same few, and the user is never asked what the spec or Karni's defaults already decide.

Fix. Run karni plan --questions, ask the user those questions only, then karni spec answer <id> <value> for each answer.

K311: New app: /new-app. Never hand-write what karni.yaml expresses.

agent rule, must · enforced by review

Rule. To build an app from a request, follow the new-app procedure (/new-app <the app in one line>, or karni rules --procedure new-app): a recipe or the blank start, karni.yaml, karni plan --questions, karni plan, karni build. Never hand-write what karni.yaml can express (apps, entities, fields, owners, access, roles, modules, features, pages, seed counts): change karni.yaml and run karni build again. Write only the domain logic that is left, in the project's own files.

Why Karni objects. karni build turns the spec into models, viewsets, migrations, seeds, tests, types and settings without a language model, so the agent writes a short YAML file instead of thousands of lines, and a later change to the spec updates the app without touching the code written by hand.

Fix. Move the hand-written entity, field, access, role or setting into karni.yaml, then run karni build.

K312: Trees: TreeModel.

agent rule, error · enforced by hand-written-tree

Rule. A hierarchy (categories, regions, organisation units, a menu) is a tree model: class Region(TreeModel, BaseModel), or OrderedTreeModel when siblings have an order, or tree: true / tree: ordered in karni.yaml. Never declare a parent foreign key to the model itself, never write recursive SQL or a loop over .parent, and never write a tree endpoint or a tree component. Model.objects.descendants(), ancestors() and subtree_ids() walk it, the API serves tree/, children/, ancestors/ and move/, and @karni/ui shows TreeView and TreeSelect. Tag a model to a tree with class Karni: taxonomies = {"region": "geo.Region"} (taxonomies: in karni.yaml), never a hand-written many-to-many with its own subtree filter or counts: the list filters ?region= and ?region_descendants=, facets/ and the tree:region scope come with it.

Why Karni objects. Hand-written trees loop on cyclic data, cost one query per level and repeat the same endpoints and widgets in every project. TreeModel's walks are one cycle-safe query each.

Fix. Inherit TreeModel first and drop the parent field, or opt out with the reason.

K314: GROUP BY: Karni.aggregate.

agent rule, must · enforced by review

Rule. Grouped counts, sums, averages, top N with Other, and figures per year, quarter or month for a chart or a report are class Karni: aggregate = {...} on the model (group_by, values, metrics, expressions) and GET <resource>/aggregate/ with useAggregate and <DataChart aggregate={...} />. A number stored as text is TextNumber. A chart people edit in the admin is a saved chart (karni add charts, <SavedChart />). Never write a view, an @action or a hook of your own that groups rows.

Why Karni objects. The aggregate action runs under the list's filters and access, in one query (two with Other), and refuses what the model does not declare. A hand-written GROUP BY view repeats the filters and the access check and is where hidden rows leak into totals.

Fix. Declare the groups and values in class Karni: aggregate, then call GET <resource>/aggregate/?group_by=...&metric=...&value=.... Karni's docs page aggregations lists every parameter.

K315: Parts: never name another part.

agent rule, error · enforced by part-imports-part, part-role-prefix, part-route

Rule. A project may hold several recipes (app.recipes), each one a part with its app label as its prefix. A part's files (its app folder and frontend/src/<prefix>/) never import another part's code and never name its app label: no import crm, no "crm.Deal" in a foreign key, no "crm.deal:own", no "crm:deal-list", no apps.get_model("crm", ...), no migration dependency on it, no {% include "crm/..." %}, no frontend import of another part's folder. Parts meet through the contracts: karni.people, karni.events (publish and subscribe by event name), karni.timeline, karni.preferences, karni_commerce and the modules the recipe requires. A connection to another part is code in <prefix>/connections.py that needs contracts and modules, never a recipe. Once a project holds a second part, every role a part adds is named <prefix>-<role> (bookings-staff) except admin and customer, and its pages live under its own base route (apps.<label>.route), never a family page's route (/, /signin, /account, /search, /inbox, /settings, /people, /cart, /checkout, /orders) and never another app's. karni check reads karni.yaml and .karni/recipes/ and fails a role or route that breaks this, even after the merge accepted it.

Why Karni objects. Every part must work alone and stay removable (karni recipes remove). One import or one foreign key to a sibling's model makes the pair inseparable and breaks the third part that was never meant to know either.

Fix. Replace the reference with a contract: a person through karni.people, an event through karni.events.publish and a subscriber, a timeline entry through karni.timeline.record. Opt out with # karni: allow(part-imports-part): <reason> (// in TypeScript) only for a file that is meant to join two parts. Rename a role <prefix>-<role>, or give the app its own apps.<label>.route, then karni build.

ESLint rules (@karni/ui/eslint-plugin)

Every rule is an error in karni.configs.recommended. An opt-out needs an eslint-disable comment with a -- reason.

karni/no-raw-elements: Raw <table>/<form>/<input>/<select>/<textarea>/<details> in project code

Why Karni objects. @karni/ui ships these as components (sorting, pagination, validation, export, keyboard and screen-reader support). Rebuilding them per page is the boilerplate Karni exists to remove, and the copies drift.

Fix. Compose the component the message names: ResourceTable for a resource's rows, DataTable for rows the page computed, ComparisonTable for entities side by side, Accordion for a <details> disclosure, ResourceForm for <form>, Input / Select / ResourceSelect / Textarea for fields (ResourceForm renders the right field for you). Opt out only with // eslint-disable-next-line karni/no-raw-elements -- <reason>.

karni/max-page-lines: A page file is longer than its cap (50 lines by default)

Why Karni objects. Pages compose @karni/ui components. A long page is rebuilding something Karni ships.

Fix. Compose Page / ResourceTable / ResourceForm / ResourceDetail, and on a dashboard DashboardGrid / ChartCard / DataTable / ComparisonTable, with their props, or move logic into hooks and components. Opt out only with /* eslint-disable karni/max-page-lines -- <reason> */.

karni/no-deep-imports: An import reaches into @karni/ui internals

Why Karni objects. Only the package root is public API (docs/stability.md). Internals change without notice, and a vendored copy forks the component.

Fix. Import from "@karni/ui" and compose or extend the exported component. Opt out only with // eslint-disable-next-line karni/no-deep-imports -- <reason>.

karni/no-direct-http: fetch / axios / XMLHttpRequest / WebSocket outside the api client

Why Karni objects. The generated typed hooks and KarniClient handle auth, errors, retries and types in one place. Ad-hoc HTTP calls bypass all of it.

Fix. Use the generated typed hooks (useResourceList / useResourceItem / useResourceMutations) or createKarniClient from @karni/ui, and keep transports under the api/ directory. Opt out only with // eslint-disable-next-line karni/no-direct-http -- <reason>.

karni/no-style-literals: A class or inline style holds a literal value instead of a design token

Why Karni objects. @karni/ui's preset resolves every colour, spacing step, radius, type size, shadow, z-index, opacity and duration from a --karni-* custom property, so one stylesheet (or karni ui detect) rethemes every component. A literal (w-[13px], bg-slate-500, bg-primary/90, style={{ color: "#333" }}) is out of the theme's reach.

Fix. Use a class from the @karni/ui preset (bg-primary-hover, bg-muted-subtle, max-w-96, z-popover), or add the token to styles.css and the preset. @karni/ui enables this rule for its own source. A project opts in with "karni/no-style-literals": "error". Opt out only with // eslint-disable-next-line karni/no-style-literals -- <reason>.