Skip to content
DocspackagesDocumentation

@lunora/advisor

Schema and query lints — splinter-style advisors that surface in the Studio Advisors view, most of them at codegen time before you ship.

PackagesAdvisor

@lunora/advisor is a set of lints over your Lunora app, modeled on Supabase's splinter. Each lint is a pure rule over a normalized LintContext; runAdvisor() runs a set of them and flattens the results into a single list of findings that the CLI, the Vite plugin, and the Studio Advisors view all render.

You rarely call this package directly. @lunora/codegen runs the static lints during lunora dev and lunora codegen, so a problem shows up in your terminal and in Studio while you work. Most of them run before the code ships, unlike an advisor that can only inspect a live database.

Two evidence tiers

A lint draws its evidence from one of two sources:

  • static: runs against the declared defineSchema (tables, indexes, relations) plus the query reads and inserts the codegen feeder discovers in your function bodies. Deterministic and runnable at build time. Most lints are static.
  • runtime: reads observed signal from a running deployment (per-shard traffic, table scans, index hits, row samples). Three lints are runtime-only; they need a live worker.

Every finding carries a level (ERROR, WARN, or INFO) and a category of SECURITY, PERFORMANCE, or SCHEMA.

How findings surface

Write or change a schema, query, or mutation in lunora/.
lunora dev / lunora codegen runs the static lints through @lunora/codegen. Findings print in the terminal.
The Studio Advisors view renders the same findings in tabs for each level (ERROR, WARN, INFO), with the remediation text for each.

The runtime tier is filled by the Studio backend from each shard's durable counters; it appears in the same Advisors view once a deployment has traffic.

Static lints

Security

Secrets, injection & server-side request forgery (SSRF):

LintLevelFlags
hardcoded_secretERRORA secret literal committed in source
plaintext_secret_in_wrangler_varsERRORA plaintext secret in wrangler.jsonc vars (belongs in the Secrets Store)
sql_injection_riskERRORUnsafe interpolation in a ctx.sql string
action_fetch_ssrfERRORA ctx.fetch URL derived from user args (SSRF)
browser_allow_private_targetsERRORBrowser rendering with the private-target SSRF guard disabled
browser_user_url_without_allowlistWARNBrowser navigation to an arg-derived URL with no allowlist

Insecure direct object reference (IDOR) and unscoped access (a user-derived key/id reaches a resource without a server-scoped check):

LintLevelFlags
owner_field_from_args_not_authERRORAn ownership column written from args instead of the server identity
storage_key_from_user_argsERRORA Cloudflare R2 object key taken directly from user args
kv_unscoped_user_key_idorERRORA KV key derived from unscoped user args
container_instance_key_from_user_inputWARNA container instance key from arg-derived unscoped input (cross-tenant IDOR)
images_url_source_from_user_inputWARNAn image-delivery URL built from unscoped user input
mail_recipient_from_request_inputWARNA mail recipient derived from request input
vectors_namespace_from_user_inputWARNA Vectorize namespace derived from unscoped user input
normalize_id_used_as_authorizationINFOA normalizeId() result gates access with no ownership/RLS check; it validates id shape, not ownership

Row-level security (RLS), masking & output shape:

LintLevelFlags
external_source_unscopedERRORA .source() + .shardBy() table with no tenantBy; every tenant Durable Object (DO) replicates the whole multitenant table
unrestricted_where_branchERRORA shape/policy predicate arm returning {} or undefined — a filter matching EVERY row, where a deny was meant
rls_uncovered_tableWARNAn RLS-gated table read without the rls() middleware
policy_references_unknown_tableWARNAn RLS policy bound to a table that doesn't exist
public_table_rls_optout_confusionWARNA .public() table that opts out of RLS but carries sensitive columns
allow_unauthenticated_shard_access_enabledWARNUnauthenticated shard access enabled on an RLS-gapped schema
open_shard_accessERRORthe open-shard option set to anything but a literal false in the app; lunora deploy refuses it without --allow-open-shards
mask_uncovered_pii_columnWARNA maskable column returned without the mask() middleware
mask_weak_hash_strategy_on_piiWARNA mask() "hash" strategy (unsalted FNV-1a) on a PII column; the value is recoverable
masked_relation_leak_via_withINFOA masked table surfaced unmasked through a with-relation on a public read
output_projection_missing_on_public_readINFOA public query returns raw rows with PII columns and no .output(...) projection
soft_delete_include_deleted_from_argsINFOSoft-deleted rows resurfaced via includeDeleted on a public read

Auth configuration (createAuth):

LintLevelFlags
auth_csrf_check_disabledERRORcreateAuth with the CSRF check disabled
auth_secure_cookies_disabledERRORcreateAuth with secure cookies disabled
auth_trusted_origins_wildcardERRORcreateAuth trustedOrigins set to a wildcard
auth_scim_without_transactionsERRORscim() (System for Cross-domain Identity Management) on a database adapter with no native transactions; every request fails
auth_email_verification_disabledWARNcreateAuth with email verification disabled
auth_session_freshage_zeroWARNcreateAuth session freshAge of zero
auth_api_call_without_headersWARNA privileged ctx.authApi call missing request headers
identity_undeclared_claim_trustedWARNAuthorization trusts an undeclared (forgeable) identity claim

HTTP handlers, procedures & rate limits:

LintLevelFlags
mail_inbound_dispatch_without_verifyERRORAn inbound-email handler with no verify hook (runs under the admin bearer)
privileged_dispatch_unvalidated_payloadERRORA queue/workflow forwards an untrusted payload into an RLS-gated function
admin_route_without_guardWARNAn admin route with no auth guard
http_action_missing_auth_guardWARNAn HTTP handler that does a side effect but never reads ctx.auth
http_action_response_header_injectionWARNA response header written from unsanitized request input (CRLF injection)
insert_many_unsafe_user_dataWARNA public procedure using insertManyUnsafe (bypasses validators + triggers)
public_arg_uses_anyWARNA public argument typed v.any()
public_mutation_without_ratelimitWARNA public write with no rate limit
user_creating_mutation_without_captchaWARNAn account-creating / mail-sending write with no CAPTCHA
signup_mutation_without_disposable_gatingWARNAn account-creating write with no disposable-email gate
ratelimit_default_memory_storeWARNA RateLimiter using the per-isolate default memory store
ratelimit_middleware_fail_openWARNA fail-open rate-limit / CAPTCHA guard on a sensitive procedure
ratelimit_key_spoofable_or_globalWARNA rate-limit key derived from spoofable user input
flag_gates_security_with_unsafe_defaultWARNA security flag that fails open to the permissive branch
unbounded_string_argINFOA public string argument with no length bound

Storage, AI, containers & payments:

LintLevelFlags
payment_create_without_authorizeERRORcreatePayment(...) with no authorize gate
storage_upload_without_content_type_allowlistWARNA storage upload with no content-type allowlist (stored XSS)
storage_upload_without_max_sizeWARNA storage upload with no size cap
storage_generate_upload_url_no_content_type_pinWARNA signed upload URL with no content-type pin
storage_presigned_url_for_private_contentWARNA native presigned / near-max-TTL signed URL for private content
privileged_fanout_from_public_procedureWARNA public procedure fanning out to a privileged dispatch surface
ai_unbounded_generation_publicWARNA public procedure running AI generation with no maxOutputTokens
ai_raw_run_escape_hatchWARNA ctx.ai.run model selected from user args
ai_tool_side_effect_prompt_injectionWARNAn AI tool side effect reachable via prompt injection
container_start_enable_internet_overrideWARNA runtime .start() override re-enabling container internet
container_runtime_egress_relaxationWARNA runtime egress mutation relaxing the container firewall
payment_webhook_wide_toleranceWARNA payment-webhook replay-tolerance window that's implausibly wide
container_public_internetINFOA container with public egress enabled by default

Performance

LintLevelFlags
unbounded_loopERRORA while (true) / for (;;) / do … while (true) with no break, return or throw that can leave it
dispatch_cycleERRORFunctions that call or schedule each other (or themselves) with no guard on any hop: an endless chain
queue_dispatch_cycleERRORA queue consumer, or a function it runs, re-enqueues to its own queue (or through a topic) on every message, with no guard on any hop
filter_without_indexWARNA query .filter() with no .withIndex() at all: every row is loaded and filtered in memory
count_without_indexWARNA count() on a table with no aggregate index whose where no ordinary index covers (a bare count included): every call scans every row of the table to count them
filter_on_primary_keyWARNA query filtering on _id; ctx.db.get(table, id) fetches the row directly instead of walking the table
unbounded_collectWARNA .collect() with no index and no filter: the whole table, re-sent to every live subscriber on every write
unbounded_collect_on_open_rangeWARNA server-driven .collect() on a withIndex range with no lt/lte bound, in a function that nothing else removes rows from
filter_after_index_scanINFOA .filter() after .withIndex() on a field the index does not cover: extend the index so the read seeks
self_reschedule_without_progressWARNA guarded runAfter of the same function under one second, passing no cursor and removing no rows it selects. From one second to a minute it is an INFO poll, and a row rewrite on each tick does not count as progress
shape_targets_global_tableWARNA shape replicating from a global (cross-shard) table
unindexed_foreign_keyINFOA foreign-key column with no index on the owning table
unindexed_relation_targetINFOThe many-side foreign key of a relation is unindexed
duplicate_indexINFOA redundant index already covered by another
container_oversized_instanceINFOA container instance larger than its workload needs
container_long_sleep_afterWARNA container's idle window (sleepAfter, capped by hardTimeout) is over an hour, so each idle instance bills for that long
ai_run_without_loggingINFOAn AI generation with no structured event; spend can't be attributed and a bad answer can't be traced
topic_too_many_subscriptionsINFOA topic with more than 10 subscriptions; every publish sends to each, at most six at a time
cron_every_minuteINFOA cron job on the fastest cadence (every minute): a Worker and target dispatch billed per fire, work or not

Schema

LintLevelFlags
index_references_unknown_fieldERRORAn index naming a field the table doesn't have
relation_references_unknown_fieldERRORA relation pointing at a field that doesn't exist
relation_references_unknown_tableERRORA relation pointing at a table that doesn't exist
through_relation_missing_unique_indexERRORA many-to-many join table with no unique index over its two keys (a repeated connect stores the link twice)
shape_unknown_tableERRORA shape bound to a table that doesn't exist
workflow_unknown_targetERRORA workflow call naming a workflow that doesn't exist
workflow_duplicate_step_nameERRORA durable step name reused across two call sites in one workflow (which cache each gets becomes positional)
external_source_on_globalERRORA table that is both .source() and .global() (contradictory tiers)
external_source_incremental_no_delete_pathERRORAn incremental .source() table with no reconcileEveryMs/softDeleteColumn; upstream deletes never apply
export_sink_misconfiguredERRORA change data capture (CDC) export sink missing a required config field, so the tap silently drains nothing
geo_index_field_not_geopointERRORA .geoIndex(name, { field }) whose field is not a v.geoPoint()
ttl_field_not_timestampERRORA .ttl(field) pointing at a column that is not an epoch-millisecond timestamp
circular_fkWARNA circular foreign-key dependency between tables
cross_module_table_writeWARNA function writes to a table another module declares it owns, directly or through a helper
empty_indexWARNAn index declared with no fields
nondeterministic_query_mutationWARNfetch / Date.now / Math.random in a query or mutation
hyperdrive_outside_actionWARNctx.sql used outside an action
r2sql_outside_actionWARNctx.r2sql used outside an action
flag_read_in_subscriptionWARNctx.flags read in a query; a flag flip re-runs no subscription, so the branch goes stale
mutator_full_row_replaceWARNA mutator server impl overwriting a whole row with replace
mutator_without_owner_scopeWARNA defineMutator with no owner; a client-callable write endpoint that ties no write to its caller
queue_without_dlqWARNA defineQueue with no deadLetterQueue; exhausted messages are dropped, not captured
global_table_near_column_limitWARNA .global() table approaching D1's 100-column ceiling, past which it cannot be created
error_without_catalogWARNA bare new Error(...) thrown from a procedure; opaque to the caller and unfingerprintable
commit_ordered_hard_deleteWARNA .commitOrdered() table with no .softDelete(); a hard delete emits no event a consumer sees
action_without_error_handlingWARNAn action doing outbound I/O (fetch, mail, queues, storage, sql, ai) with no try/catch
notify_send_outside_actionWARNctx.notify/ctx.push used in a query or mutation — external I/O on a re-runnable path
notify_missing_push_configWARNctx.push with neither a Web Push nor a Firebase Cloud Messaging (FCM) channel configured, so every send fails
migration_stale_importWARNA migrated-away platform's SDK still imported from lunora/ source
table_without_insertINFOA table no function inserts into
workflow_unusedINFOA workflow that is never started
geo_index_unusedINFOA .geoIndex(...) no handler reads via withGeoIndex(...) — a companion column written for nothing
procedure_without_structured_eventINFOA public write that emits no structured event, so a failure is visible but not searchable

Runtime lints

These read observed signal off a live deployment, so they only fire once a worker has traffic.

LintLevelCategoryFlags
hot_shardWARNPERFORMANCEA shard taking a disproportionate share of traffic
index_utilizationINFOPERFORMANCEA declared index that observed queries never use
fan_out_breadthWARNPERFORMANCEA shard set wide enough to strain a cross-shard read (it would approach the per-invocation subrequest ceiling)

Run the lints yourself

Adapt your schema with fromServerSchema and pass it to runAdvisor. The source option restricts to one tier: pass "static" to skip the runtime lints, which need a live deployment:

advisor-static.ts
import { fromServerSchema, runAdvisor } from "@lunora/advisor";

import schema from "./lunora/schema";

const findings = runAdvisor({ schema: fromServerSchema(schema) }, { source: "static" });

for (const finding of findings) {
    console.log(`[${finding.level}] ${finding.name}: ${finding.detail}`);
}

runAdvisor(context, options) returns a flat Finding[] in lint-declaration order. Each finding has level, name, title, detail, description, remediation, categories, facing, cacheKey, and metadata. Options:

  • lints: the set to run. Defaults to ALL_LINTS; STATIC_LINTS and RUNTIME_LINTS are also exported, as is each lint by name (e.g. unindexedForeignKey).
  • source: restrict to "static" or "runtime". Omit to run both.

Feeding the runtime lints

The runtime tier reads shardTraffic, tableScans, and indexHits off the LintContext. The Studio backend fills all three from the shards' admin signal.

An Analytics-Engine-backed alternative feeder, loadAnalyticsRuntimeMetrics, exists in source (src/ae-metrics.ts) but is quarantined: not exported from @lunora/advisor's package root, and not importable by consumers of the published package. Nothing in the runtime writes the AE events it would read, so wiring it up today would silently read as "no dead indexes" rather than "no data" for the index_utilization lint. It stays internal, as groundwork for a future writer, until that gap closes. See the docblock atop ae-metrics.ts for the full read contract.

Suppressing one finding

When a finding is accepted for your app, accept that one finding at one site with an inline directive above the code it concerns:

lunora/health.ts
// lunora-advisor-exempt procedure_without_structured_event -- a liveness probe with nothing to log
export const ping = mutation({ ... });

The directive is // lunora-advisor-exempt <rule> -- <reason> on its own line. <rule> is the lint's snake_case name. The reason after -- is required.

  • Attachment. The directive attaches to the code on the next line that holds code; blank lines and other comments in between are skipped. In a .ts file that is the outermost node starting at that line's first token, so a directive above a statement covers the whole statement, including a multi-line chained call. When the line below is a property or a chained call rather than a statement, the directive covers only that property or call.
  • Matching. A finding is suppressed when it is of the named rule, it is reported in the same file, and its reported line falls inside that node's line span. A directive never matches by rule alone, by file alone, or by procedure, and it does not reach the statement below the one it sits above.
  • Where it is read. Files under lunora/, the worker entry and the root lunora.config.*. Only a // line comment is a directive; the same text inside a block comment or a string is not.
  • wrangler.jsonc. The same // comment above a key accepts findings of the named rule for that key only, the first key when a line holds several. A project whose config is wrangler.json uses the same form there. plaintext_secret_in_wrangler_vars is the rule that reports a plaintext secret in vars; the directive is then // lunora-advisor-exempt plaintext_secret_in_wrangler_vars -- <reason>.
  • Reason. A directive with an empty reason suppresses nothing.
  • Two WARN findings check the directives. advisor_suppression_invalid fires for a directive that cannot apply: no reason, an unknown rule id, a runtime lint, or a rule that reports no source location. advisor_suppression_unused fires for a valid directive that matches no finding, so a stale one gets removed. Both name the directive's file and line, and advisor.minSeverity applies to them as to any WARN. They are not lints, so they have no row in the tables above.
  • Gate. The ERROR gate on lunora codegen and lunora deploy ignores a suppressed finding. An unsuppressed ERROR still blocks, even when a suppressed one sits beside it.
  • Health map. A suppressed finding neither fails nor warns its procedure. The summary counts it as suppressed.
  • Visibility. A suppressed finding stays in the advisory list with its reason. It appears in the codegen terminal output under an N suppressed line, in the lunora advisor summary, in the Studio Advisors views with a Suppressed badge, and in the suppressed field of the lunora_get_advisories MCP tool.
  • Not suppressible. Runtime lints have no source site, so a directive cannot accept one. Some findings have no line to match: notify_missing_push_config reports no location at all, and findings about tables or indexes that an installed package contributes through its schema extension carry no line in your code. A directive for either is reported, as invalid or as unused.

A directive with no rule id, // lunora-advisor-exempt -- <reason>, is the older whole-procedure opt-out. It exempts the procedure from the health map score and suppresses no finding.

Health map — score, verdicts, baseline

The lints above answer "what is wrong?". scoreAdvisor() answers "how is the app doing, and did it get worse?" by rolling a lint run up into a weighted score, a grade, and a per-procedure verdict you can commit and diff in CI.

It is a pure function over findings you already have, so it never re-runs a lint:

The following script prints the score and grade of the app:

advisor-score.ts
import { fromServerSchema, runAdvisor, scoreAdvisor } from "@lunora/advisor";
import type { LintContext } from "@lunora/advisor";

import schema from "./lunora/schema";

const context: LintContext = { schema: fromServerSchema(schema) };
const map = scoreAdvisor(context.procedureProtections ?? [], runAdvisor(context, { source: "static" }));

console.log(map.score, map.grade); // e.g. 84 "good"

How a score is built

Every procedure starts at 100 and loses each fired rule's weight, charged once however many times that rule fires, so one lint hitting five call sites costs the same as one hitting a single call site.

LevelDefault weight
ERROR20
WARN10
INFO5

Severity is the only input — a lint carries no per-lint weight of its own, so two rules at the same level cost the same. Those per-procedure scores roll into a weighted mean over two factors:

  • Shape. Public handlers count double, internal ones and queries count half. Kind wins over visibility, so a public query counts half, not double.
  • Sensitivity. A procedure whose classifySensitivity says high then doubles again — visibility says who can reach a handler, sensitivity says what it touches. So a public sensitive mutation pulls 4×, while an internal sensitive one — or a sensitive query — pulls 1× instead of the half its shape alone would buy.

Findings that name no procedure (schema shape, wrangler.jsonc config) land in a project bucket weighted against the procedure population, so schema debt still moves the grade.

VerdictMeaning
cleanNo lint fired
warnedScored at or above 50
failingScored below 50
exemptOpted out; appears in the map, pulls no weight

Grades band the global score: excellent (≥ 90), good (≥ 70), needs-work (≥ 50), at-risk below that.

The verdicts are named for severity, not instrumentation, because every lint family feeds this score. A handler with a security finding is failing; that is not a statement about telemetry.

From the command line

lunora advisor does all of this for you: it scores the app, writes lunora.advisor.map.json, and gates on it.

lunora advisor                    # score, print a summary, write the artifact
lunora advisor --all              # every procedure, grouped by file
lunora advisor --entry messages#sendMessage  # one procedure and the rules that fired
lunora advisor --min-score 80     # exit 1 below 80
lunora advisor --baseline         # exit 1 on any regression vs the committed map
lunora advisor --no-write         # score without touching the artifact

The artifact is stamped deterministically, so committing it and re-running leaves no diff unless something actually changed.

Gate CI on a committed baseline

Write the map to lunora.advisor.map.json, commit it, and compare against it on each run. compareToBaseline reports five independent regression signals: the global score fell, an existing procedure got worse, a procedure started failing, a procedure's findings grew without its score moving, or the project bucket gained findings.

The following fragment compares the current map with the committed baseline. It reuses map from the previous example:

advisor-gate.ts
import { readFile } from "node:fs/promises";

import { compareToBaseline, parseAdvisorMap } from "@lunora/advisor";

const baseline = parseAdvisorMap(JSON.parse(await readFile("lunora.advisor.map.json", "utf8")));

if (baseline === undefined) {
    // Missing, or shaped in a way this build can't read (hand-edited, truncated).
    throw new Error("advisor baseline is unreadable; regenerate it");
}

const diff = compareToBaseline(map, baseline);

if (!diff.comparable) {
    throw new Error(`baseline not comparable: ${diff.reason}`);
}

if (diff.regressed) {
    process.exitCode = 1;
}

parseAdvisorMap returns undefined for a missing or malformed baseline; version policy is compareToBaseline's alone, which returns comparable: false on a MAP_VERSION mismatch (a baseline from another version parses fine). Treat both as "cannot verify" and fail; reading them as "no regression" silently disables the gate.

The artifact is deterministic apart from its timestamp: pass generatedAt to make it byte-stable. @lunora/codegen exposes toAdvisorContext() to build the context straight from the feeder.

Some procedure-local lints (filter_without_index among them) currently report a file without an export name, so they land in the project bucket rather than their procedure's row. Closing that gap is tracked work on the codegen feeder.

API

Each lint is also exported under its camelCase name (for example unindexedForeignKey). The tables above list them by rule name.

runAdvisor(context, options?)

Type: (context: LintContext, options?: RunAdvisorOptions) => Finding[]

Runs options.lints (default ALL_LINTS) against the context and returns the findings in lint-declaration order. Pass { source: "static" } to skip the runtime lints.

scoreAdvisor(procedures, findings, options?)

Type: (procedures: ReadonlyArray<AdvisorProcedureProtection>, findings: ReadonlyArray<Finding>, options?: ScoreAdvisorOptions) => AdvisorMap

Rolls a set of findings up into the health map. It does not run lints. Each finding attaches to the procedure named by its metadata.file and metadata.exportName, and unattributed findings go to the project bucket.

ScoreAdvisorOptions

Type: { exempt?: ReadonlyArray<string>; generatedAt?: string }

exempt lists file#exportName ids to opt out of scoring. Procedures listed there get the exempt verdict and carry no weight. generatedAt sets the artifact timestamp; pass it to make the output byte-stable.

compareToBaseline(current, baseline)

Type: (current: AdvisorMap, baseline: AdvisorMap) => BaselineComparison

Returns { comparable: false, reason: "version-mismatch" } when the two maps have different version values. Otherwise it returns regressed, scoreDelta, dropped, newFailing, worsened and projectRegressed.

parseAdvisorMap(value)

Type: (value: unknown) => AdvisorMap | undefined

Narrows a parsed lunora.advisor.map.json to an AdvisorMap. Returns undefined when the value has a shape this build cannot read.

fromServerSchema(schema)

Type: (schema: Schema) => AdvisorSchema

Adapts a defineSchema result into the schema field that LintContext requires.

ALL_LINTS, STATIC_LINTS, RUNTIME_LINTS

Type: ReadonlyArray<Lint>

The lint sets that runAdvisor runs by default. ALL_LINTS is STATIC_LINTS followed by RUNTIME_LINTS.

MAP_VERSION

Type: number (currently 1)

The version of the AdvisorMap shape. compareToBaseline refuses a baseline written with a different version.

Lint

Type: interface

A lint is a pure rule: name, title, description, remediation, level, categories, facing, source and run(context). Pass your own lints in options.lints to runAdvisor.

LintContext

Type: interface

The input to every lint. schema is required. Every other field is optional evidence, such as procedureProtections, shardTraffic, tableScans and indexHits. The runtime lints read only the evidence that a live deployment supplies.

AdvisorMap

Type: interface

The health map that scoreAdvisor returns and lunora advisor writes to lunora.advisor.map.json. It holds generatedAt, grade, score, procedures, project, summary and version.