A ledger is the typed schema of the events your code emits. One logika.json per repository holds its ledger; it is the git-diffable source of truth. Your agent edits it like any other file, and logika check validates it.
The ledger is optional. With an empty one, Logika is a logging platform: everything your application sends is stored and queryable, and any span that closes with an error, or log record with an exception or an ERROR or FATAL severity, raises an issue, which can wake your agent. Events and their params come with instrumentation, as your agent logs the code's state transitions; the rules about what must hold (validate, paths, timeouts, rules, invariants) and the analytics (funnels, milestones, views) are written later, with you, in a reflection round with nock (nock reflect logika, which logika init installs), against real captures and proven on replays.
A ledger has ledger (its name), params, events, rules, invariants, funnels and milestones, plus views for the console. Any of them may be empty: Logika stores everything your application sends either way, and raises nothing but failures unless the ledger asks for more. The same file also holds the project's id and two things that are not the ledger: map and config (below).
Params
The vocabulary. A param name is declared once per project and binds its type and flags everywhere; events reference names and never redeclare types.
"params": {
"order_id": {"type": "str"},
"user_id": {"type": "str", "identity": true},
"email": {"type": "str", "pii": true},
"amount": {"type": "decimal"},
"provider": {"type": "str", "dimension": true}
}
- Types:
bool,int,float,decimal,str, andlist<T>of each.decimaltravels as a string and is stored with 38 digits, 9 of them fractional, so money sums exactly. pii: encrypted in the client with a key you hold; the server never receives the plaintext. String-shaped, excluded from aggregation, compared by its ciphertext, which is the same for equal values: a condition can ask only whether it is present (IS NOT NULL) or equal to anotherpiiparam.identity: names a person or entity. Logika keeps one row per value per active day, so "how many" and "do they come back" are exact.dimension: few values, worth grouping by. Logika counts per value, up to 50 a day with the rest as "other".
A name stays declared even when no event uses it, and check rejects a type change on any name that has ever shipped.
Events
{"name": "checkout",
"message": "Checkout {order_id} for {user_id}: {amount}",
"params": ["order_id", "user_id", "email?", "amount"],
"validate": "amount > 0",
"span": {"timeout": "2m",
"paths": ["reserved (captured|declined)", "reserved released .*"]},
"children": [
{"name": "reserved", "message": "Reserved {sku}", "params": ["sku"]},
{"name": "released", "message": "Released {sku}", "params": ["sku"]},
{"name": "captured", "message": "Captured {amount} via {provider}",
"params": ["order_id", "user_id", "provider", "amount"]},
{"name": "declined", "message": "Declined: {reason}", "params": ["reason"]}]}
| Key | Meaning |
|---|---|
name | Unique within its parent; dot-joined into a full path such as checkout.captured. Travels as the OpenTelemetry span name. Never starts with _, which Logika reserves for its own signals (_open, _heartbeat, _instance_end). |
message | A template over the event's params, rendered wherever a person or agent reads the event. |
params | Names from the vocabulary, each required unless a trailing ? marks it optional ("coupon?"). A required param that arrives missing is a finding on the event; checks on an absent optional param are skipped. |
validate | A condition in SQL, DuckDB's dialect, over the event's params: amount > 0 AND spent <= budget, status IN ('placed', 'cancelled'), coupon IS NOT NULL. Comparisons, AND/OR/NOT, IN, BETWEEN, IS NULL, LIKE, arithmetic, and the functions coalesce, abs, length, lower, upper, list_contains and regexp_full_match (RE2 syntax, inline flags such as (?i); no lookaround or backreferences). Each top-level AND term is judged and named on its own, and fails only on false, so a check on an absent optional param is skipped. An exact decimal is never compared with a float, and a pii param only with another pii param for equality, or by IS NULL; each such mistake is reported when the ledger is validated. |
anomaly | true when seeing the event at all warrants attention. Expected failures are not issues. |
span | Makes the event a span, with a timeout (a duration such as 30s, 15m, 2h or 7d) and its valid paths. Without it the event is a leaf. |
children | Nested definitions, emittable only inside their parent span. |
Span paths
paths lists the valid routes through a span: each a regular expression whose atoms are its direct children's names.
| Token | Meaning |
|---|---|
a b | a, then b: names separated by spaces |
a|b | either side; | binds loosest, so group it inside a sequence: reserved (captured|declined) |
( … ) | grouping |
? * + {m} {m,} {m,n} | after a name or a group: zero or one, zero or more, one or more, a count (at most 16) |
.* | any children |
{a b c} | each item once, in any order (at most 3 items) |
At close, the span's observed direct children are projected onto the names mentioned in any path, and the projection must match a path whole. Names no path mentions are unconstrained. A clean close matching no path is a path violation, and the issue shows both sides: "checkout closed with reserved captured captured, expected reserved (captured|declined)". An error close is accepted only by a path that is one sequence ending in .*; otherwise it is an error violation.
A path can also say what it means, for whoever reads the issue: {"match": "reserved (captured|declined)", "description": "A checkout reserves its stock, then captures or declines once"}, beside plain strings in the same list. When a clean close matches no path, the span's one described path titles the issue ("A checkout reserves its stock, then captures or declines once"); with several described, the title says "checkout: none of its paths matched". The evidence keeps both sides either way.
Everything judged on one sighting of an event (a failing validate clause, a missing required param, a wrong path, an error close, a timeout, a sighting of an anomaly: true event) raises that event's one issue. Its title and evidence list each violation with how many sightings showed it ("checkout: amount must be > 0, timed out"), and it closes only when your agent fixes it or someone dismisses it, never because the violations stopped. Rules, invariants, process liveness and change detection's regressions (worse on one app version, or since a deploy) raise issues of their own; change detection's other findings are insights for you, which the agent works only when asked.
You can know in advance that a flow might end early with an error, not that it will: reserved released .* says that once the stock is released, the checkout may end any way it ends. Place .* after the child that makes stopping acceptable; right after the first step it would accept every clean close too.
At most 8 paths per span; a sequence has at most 8 steps and a path 16 names; groups nest at most 3 deep.
timeout is judged by the span's own timestamps: a close after it is a timeout, whenever it arrives. A span still open fires when its deadline passes if its process kept heartbeating past it (the work is stuck); if the process went quiet too, Logika waits a short delivery margin for late data, then fires saying what it knows (the process died, or delivery stalled on Logika's side). A late close showing the span finished in time withdraws that occurrence, and an issue left with none, not yet picked up by your agent, disappears from the queue. Browser and React Native instances can go offline legitimately: their silence is never judged, and when their data resumes, their open spans are judged by their own timestamps.
Rules
"rules": [
{"name": "paid_orders_settle",
"on": "checkout.captured.order_id",
"expect": ["fulfil.batched.order", "refund.issued.order"],
"within": "15m",
"if": "amount > 0",
"description": "Every paid order is fulfilled or refunded within 15 minutes"}
]
When the trigger closes successfully, an expectation opens, keyed by the value of the on param. Any one expect entry with an equal value closes it when it closes between the trigger's start and the trigger's close plus within (up to 7d), give or take a few seconds of clock difference between machines; if none does, the rule raises an issue, timed like a timeout: on the deadline while the instances that could send the expected event keep delivering, after a short margin when they went quiet, and withdrawn if late data shows the event came in time. if, a condition as validate takes one, filters on the trigger's params. name, required and unique among the rules and invariants, is what Logika calls the rule (in logika map, logika test and its issue); description, optional, is one sentence that titles the rule's issue; without it the title names the rule ("paid_orders_settle not met in time"). Matching is by equality, within one environment. Every rule is judged on its own, and is identified by its on and expect: renaming it or changing within, if or description keeps the rule and its issue's history.
Invariants
What must hold between events: the same record over time, a parent and its children, a partner in another flow. A lost update or a double charge leaves every sighting correct on its own; only the relation is wrong.
"invariants": [
{"name": "receipt_continuity",
"description": "A receipt starts where the last receipt on its line ended",
"key": ["line_id"],
"query": "SELECT _span_id FROM (SELECT _span_id, received_before, LAG(received_after) OVER (PARTITION BY line_id ORDER BY _end, _span_id) AS previous FROM receive) WHERE previous IS NOT NULL AND received_before <> previous"}
]
The query reads views named after the ledger's events (receive, "checkout.captured"), with their params and the columns _span_id, _trace_id, _parent_span_id, _start, _end, _status, _app_version and _environment, and returns the _span_id of each row that breaks the invariant; any other column it returns is kept as evidence. It may relate rows only by its key or by _trace_id: every PARTITION BY, GROUP BY and join holds them. That is what lets Logika judge it on each pass over the new rows and the rows that share a trace or a key with them. The description is the issue's title; each violating key is an issue of its own, and a violation a late event disproves is withdrawn. At most 16 invariants, 2,000 characters each; logika check validates them offline, and logika replay shows them firing.
| Kind | Example |
|---|---|
| continuity | each change starts where the last ended: LAG(...) OVER (PARTITION BY key ...) |
| uniqueness | once per key: row_number() OVER (PARTITION BY order_id ...) > 1 |
| conservation | an operation adds up: GROUP BY _trace_id HAVING sum(out) <> sum(in) |
| ordering | a record's states move forward across flows |
| references | what one event names, another created: NOT EXISTS (... WHERE p.order_id = s.order_id) |
| agreement | a parent and its children, or two flows, agree: JOIN ... ON c._trace_id = p._trace_id WHERE c.batch <> p.batch |
Errors
Failures need no declaration. Any span that closes with an error status (an exception escaping it sets one) raises an issue, whatever the ledger declares: a library's spans (POST /checkout, SELECT orders), your own undeclared ones, a declared leaf event. So does any log record with an exception or an ERROR or FATAL severity, such as the logger.exception(…) your code already makes; Logika's and OpenTelemetry's own records are never judged. There is one issue per span name (for a record outside any span, its logger) and exception type, titled "POST /checkout failed with ValueError", with the exception's message and stack, or the record, as evidence. An exception that propagated is reported once, where it was raised, and a record logged in a span that failed with the same exception is that span's failure, not a second issue. Declared span events (with span) are judged by their own paths instead. logika replay '{"on": "capture", "fail": ["POST /checkout"]}' shows one firing, for any span name the last capture has.
Funnels and milestones
"funnels": [
{"name": "purchase", "within": "1h",
"steps": ["landing.viewed.user_id", "cart.added.user_id", "checkout.captured.user_id"]}],
"milestones": [
{"name": "first_post", "from": "signup.completed.user_id", "to": "post.created.user_id"}]
Every step of one funnel or milestone names the same identity param. A declaration is backfilled once, right after the sync that adds it, from the retained raw data (30 days on paid tiers, 3 on the free demo). Funnels are first-time conversion: an identity enters at its first occurrence of the first step and converts if the later steps follow within within. Each funnel's conversion is judged daily against its usual level, and a fall is an insight.
Views
"views": [
{"name": "overview",
"panels": [{"event": "checkout", "show": ["volume", "error_rate", "p95"]},
{"event": "checkout.declined", "by": "reason"},
{"funnel": "purchase"},
{"identity": "user_id", "show": "actives"}]}
]
The console renders views from stored aggregates at page load. A series may also show sum:<param> or avg:<param> of a numeric param, such as ["sum:amount"] on a paid invoice: money when the event carries a currency param (amounts in cents, each currency summed apart) or the panel says "unit": "usd", sizes with "unit": "bytes". Which params to count, and which funnels, milestones and views to declare, a reflection round works out with you from real captures (Reflection with nock).
Syncing
logika sync validates the ledger against its synced history (unknown params, type changes, malformed conditions and invariants, over-cap deadlines, dangling cross-ledger references) and, when it changed, uploads it as an immutable version with its digest, backfilling new funnels and milestones. Every event is judged by the ledger version its code was built with: the enhancer sends the digest of the logika.json it loaded, so code built before a stricter version keeps its own, and tightening is safe. Syncing is safe at any time: a version only matters once code built with it runs. Code running a ledger nobody synced is stored but not judged, and one account item says so. Events may be removed; old versions stay readable.
The digest covers the ledger alone: editing components or config never makes the ledger look changed.
The rest of logika.json
{"project": "pr_…",
"ledger": "shop", "params": {}, "events": [],
"components": [{"name": "api", "paths": ["backend/"], "languages": ["python"],
"init": ["backend/app/wsgi.py"], "version": "backend/pyproject.toml: project.version",
"instrumented": true,
"conventions": {"transitions": [{"files": "backend/app/orders/**", "about": "orders change state"}],
"helpers": ["traced"], "events": "orders.*", "identity": "*_id",
"before": "*_before", "after": "*_after"}}],
"config": {"generate": [{"template": "…", "output": "…"}], "ignore": ["**/tests/**"]}}
-
components: the components as Logika sees them, each with its paths, languages, where the enhancer is initialised and where its release version comes from.logika-instrumentwrites it, with each component'sconventions, whichlogika checkholds every change to, marked instrumented or not:transitions: where its state transitions happen, each a glob offiles, an ast-greppatterna function holds, or both, with an optionalabout;helpers: the names of your span helpers, whose call or decorator opens an event;eventsandidentity: globs its event names and the id param every event carries follow (orders.*,*_id);beforeandafter: globs with one*for the param's stem (*_before,*_after), given together;notes: anything else about how it logs, in the agent's words.
"instrumented": trueis set once the agent starts on a component; from then on Logika's reviewer reads changes to it and the daily re-instrumentation nudge watches it. -
config: the CLI's own settings.generatelists the templates for typed bindings, whichcheckregenerates when they or the ledger change;ignorelists what never runs in production, whichcheckandmapignore. The agent your monitor runs, how it delivers a fix, when it wakes and how long a run goes are each environment's, set in the console's Settings, under Environments. Members, billing, app keys, retention and everything else not about the repository stay on the server too.