canonry is an agent-first open-source AEO operating platform that tracks how AI answer engines cite a domain for tracked queries and acts on the signal through the content engine and integrations. Published exclusively as @canonry/canonry on npm. The CLI and API are the primary interfaces — the web dashboard is supplementary.
It ships a built-in analyst agent, Aero (packages/canonry/src/agent/), and a stdio MCP adapter, canonry-mcp (packages/canonry/src/mcp/).
This file holds the rules for every change. Before you edit, read the AGENTS.md files for the affected packages and apps. See docs/CODEMAP.md for source paths and docs/README.md for documentation.
apps/api/ Cloud Run REST entry point (imports packages/api-routes)
apps/web/ Vite SPA, bundled into packages/canonry/assets/ (also read PRODUCT.md, DESIGN.md)
packages/canonry/ Publishable npm package: CLI + server + SPA (+ src/mcp/AGENTS.md, src/agent/AGENTS.md)
packages/api-routes/ Shared Fastify route plugins (+ src/doctor/AGENTS.md, src/discovery/AGENTS.md)
packages/contracts/ DTOs, enums, config schema, error codes, shared utilities
packages/config/ Typed environment parsing
packages/db/ Drizzle ORM schema, SQLite client, migrations
packages/intelligence/ Insight and health analysis over snapshots
packages/provider-*/ Answer-engine adapters (gemini, openai, claude, perplexity, local, cdp)
packages/integration-*/ Third-party integrations (Google, GA4, Bing, OpenAI ads, Cloudflare, WordPress, ...)
skills/, plugins/ Canonical agent skills and the portable plugin (rules for both: plugins/AGENTS.md)
docs/ Architecture, data model, setup guides, testing
canonry serve (local) and apps/api (Cloud Run) are single-tenant: one trust boundary per instance — one operator’s projects on one machine, or one team’s projects on one Cloud Run service. Never multiplex unrelated tenants behind one instance.
owner_id, and resolveProject(app.db, name) is a global lookup, so a full-instance cnry_… key reads and writes every project. A project-scoped key (api_keys.project_id, canonry key create --project) is a project boundary, not a tenant boundary: instance-global /settings/* and shared google_connections are unchanged.google_connections / bing_connections are keyed on (domain, connectionType), so projects tracking the same domain share one OAuth connection by design.apps/api as multi-tenant SaaS (one Cloud Run service, database, and OAuth client per team), and hand out cnry_… keys only within the trust boundary you’d give a teammate.requirePaidReadScope + requireAdminSession, not just the read/write split. Any new route that calls a provider live on the caller’s behalf must be added to this gate.CANONRY_OPERATOR_KEY_IDS; never add an API that self-grants it.Key types, scope gates, read-only keys, keys.write, and what a multi-tenant migration would cost: packages/api-routes/AGENTS.md → “Deployment posture and key authority”.
pnpm verify. Run tests only after changes are finalized and ready for push or review.pnpm check, affected package tests, typechecks, and type-aware lint. Include dependent packages for shared runtime, contract, dependency, DB, or auth changes. Reuse passing results while their inputs remain unchanged. For owner changes, pnpm verify is optional locally, not a per-push requirement.pnpm check and pnpm verify. Follow CONTRIBUTING.md and the PR template: 1–3 summary bullets, security review, styling checks, and exact-head results. Missing or failed required checks block submission without an explicit maintainer exception.pnpm gen (API client) or pnpm plugin:sync (plugin mirrors).MERGEABLE before handoff or merge. Report commands, results, SHA, and blockers; failed or unrun required checks block readiness. Skipped owner CI proves nothing.arberx validation is local. All releases stay enabled. Hooks remain staged lint and drift only. Docs/config: diff/live checks; no new tests needed../canonry-install.sh # one-command dev setup: install deps, build all packages, install canonry globally
pnpm install
pnpm check # fast lint of staged, unstaged, and untracked JS/TS files
pnpm lint:staged # fast lint of the exact staged JS/TS content
pnpm verify # full check; required before outside code PRs
pnpm build:cli # CLI/server bundle only; skips the dashboard
pnpm build:web # build or reuse dashboard output and copy changed assets
pnpm build # complete publishable package
pnpm run typecheck && pnpm run test && pnpm run lint
pnpm typecheck:tsc # typecheck with TypeScript's own tsc instead of tsrs (docs/testing.md)
pnpm gen # regenerate the API client after changing openapi.ts
pnpm plugin:sync # refresh plugin skill mirrors + portable/client manifest versions
pnpm plugin:check # fail on plugin spec, skill, or version drift (CI gate)
pnpm guide:sync # generate MCP guidance + optional native skills from docs/agent-operations/v1.md
pnpm run dev:web
For the product CLI, canonry <command> --help is authoritative and skills/canonry/references/canonry-cli.md is the full reference. Rules a command must follow live with the code that implements it (“Where rules live”), not in a command list.
Here, a simple portfolio means the standard project flow. A custom portfolio means an Advanced Measurement portfolio.
Use these sections only for review handoffs. Keep simple answers and routine status updates short.
When proposing work, requesting feedback, or showcasing changes:
1, 2, 3 for one section; A1, A2, B1 when there are multiple sections.SHOWCASE section when presenting them for review.FEEDBACK NEEDED section only when a real user question or decision is needed. Put every question there, indexed, and keep it separate from SHOWCASE; omit the section when there are no questions.packages/api-routes/ must not import from apps/*.packages/canonry/ is the only publishable artifact. Every other package is internal and bundled via tsup.@canonry/canonry-* naming convention.packages/config, provider logic in packages/provider-*/, and route plugins in packages/api-routes (no app-level concerns; thin handlers).cited / not-cited, or not-measured when the engine returns no sources); compute transitions at query time.Every (query × provider) snapshot carries two independent signals — a model can do either, both, or neither. Never conflate them in code, copy, or contract field names.
| Term | Meaning | Source field |
|---|---|---|
| mention / mentioned | The project’s brand or domain appears in the LLM’s answer prose. Citation links written into the text (chips such as ([domain](url)), links labelled with a URL or a lowercase host, [1] markers, bare http(s):// URLs) are citations and never count; match through answerProseForMentions. |
query_snapshots.answer_mentioned (boolean) |
| cited | The project’s domain appears in the answer’s source links / grounding. An engine that returns no sources (Local) records 'not-measured', which is never a miss. |
query_snapshots.citation_state = 'cited', read through readCitationState |
mention / mentioned for answer-text presence. answer, visible, and visibility are legacy terms (visibility_state, run kind answer-visibility, visibilityStateFromAnswerMentioned); new APIs, fields, flags, and UI labels say mentioned (mentionRate, never answerRate).cited for source-list presence; never use citation as an umbrella for both.citationState; a “mentioned” label reads answerMentioned. A metric named for one and computed from the other is a bug — fix it.C/c cited or not, · citation not measured, M/m mentioned or not, – missing) with the legend above the table, as canonry citations and canonry run do (packages/canonry/src/snapshot-cell.ts).canonry-vocabulary/no-banned-metric-literal bans conflating literals ('answerRate', 'visibility run', 'paid mentions', …) in the CLI, api-routes, and web trees; the list is in eslint-rules/canonry-vocabulary.js. Bare 'visible' stays legal (DOM, legacy enum) — review owns it.Branded and non-brand queries never share a denominator, except the API’s compatibility overall sentiment headline (rule 7). A branded query names the project, so the model was handed the answer; pooling lets brand recall outvote the category and can invert a ranking (measured on a real basket: pooled ranked the subject FIRST at 42%, non-brand ranked it LAST at 3%).
visibility-stats --share-of-voice, and visibility-compare default to non-brand. Historical competitor landscapes require explicit queryClass=non-brand (--query-class non-brand) for competitive percentages; omitted class or all returns pooled counts with null shares.branded) with its own labelled section and denominator — never dropped, never pooled.scope / queryClass on the wire; “· non-brand queries” in the delta, chart title, column header, and CLI line. A GROUP of figures sitting directly under a heading that names the class may rely on that heading for the visible label (the dashboard’s AI Visibility headline strip names the class once in its h2), but each figure still carries the class in its own accessible text via an sr-only suffix beside the value. A reader who sees only the number, or hears only the figure, must still be able to tell which instrument produced it.pooled appears only when the project has no usable brand alias. Never label an unsplit figure non-brand, and never silently classify an unclassifiable basket.compileQueryClassifier (packages/contracts/src/query-class.ts) runs effectiveBrandNames through the shared brand matcher; queryClassSchema IS measurementQueryClassSchema. No hand-rolled regex, no second enum (canonry-guards/no-second-query-classifier). Surfaces show the server’s queryClass (canonry query list).competitorOverlap is legacy MIXED evidence (answer text, source links, or both). Citation metrics use citedDomains plus grounding-source hosts; mention metrics use answer text with the shared matcher.sentiment.branded, or no metric when no branded judgment exists. overall (queryClass = 'all', computed server-side from distinct answer-subject assessments, never averaged class rates) stays in the API for compatibility and is not shown on the dashboard or the human CLI overview. The dashboard shows non-brand sentiment only as its unfavorable and mixed answers (exceptions), never a favorable share; the detailed canonry sentiment --query-class non-brand read keeps the class’s full counts. Preserve both class summaries in the API; competitive metrics remain separate.The tracked thing (canonry query add, the queries / query_snapshots tables, queryText / queryId / queryClass on the wire) is a query.
query: UI labels, headings, tooltips, aria-label, placeholders, CLI output, and exported output — with correct agreement (“Assign at least one query”, “3 query assignments”)./measurement-property-questions and /measurement-question-result, MCP tools canonry_measurement_property_questions and canonry_measurement_question_result, and every SDK symbol, field, prop, and file built on them. The copy/wire mismatch is deliberate.canonry-vocabulary/no-question-ui-copy enforces this in apps/web/src. Machine tokens (no whitespace, e.g. property-questions) and className / id / aria-labelledby values are exempt; only two files are excluded, permanently: DiscoverySection.tsx (rule 3’s framing can’t be separated by regex) and mock-data.ts (test fixture).Never compare domain values as raw string literals: write kind === RunKinds['answer-visibility'], not kind === 'answer-visibility'. The constant objects (RunKinds, RunStatuses, RunTriggers, CitationStates, VisibilityStates, ComputedTransitions) come from packages/contracts/src/run.ts via @canonry/canonry-contracts.
kind: RunKind, not string).default, or default: { const _exhaustive: never = value }.run.ts; the constant object derives from it. Worked example: packages/contracts/AGENTS.md → “Enum constants”.Agent-first. The API is the backbone, the CLI is the primary user-facing surface, and the web UI is important but never blocks a release. A new feature needs an API endpoint in packages/api-routes/ and a CLI command in packages/canonry/; UI in apps/web/ is ideal.
Everything the dashboard shows must be readable through the API and CLI, with the same data. The UI consumes the API; it is not a privileged surface.
--format json output matches the API response the UI consumes.Every derived number — percentage, trend, score, rank, bucket, residual, roll-up, dedupe, classification — is tested against the business invariant it claims to represent.
toBeGreaterThanOrEqual(0), typeof, “renders without crashing”).<1%, 0%, 100%), clamping, and stale/legacy rows.The CLI and API are the agent interface. If an agent can’t do something with canonry <command> --format json or an HTTP call, it’s a bug.
config.yaml; node:readline is lint-banned in command files. Only canonry init may prompt, and all its values are also flags.--format json goes to stdout; errors go to stderr as { "error": { "code": "...", "message": "..." } } with a code from CliError.canonry apply as the model. Creating POSTs (runs) return a stable identifier and handle conflicts (e.g. runInProgress with the existing run id)./projects/:name/runs/latest, /projects/:name/search?q=).0 success, 1 user error (bad input, not found, validation), 2 system error (network, provider failure, internal) — agents use them to decide whether to retry.canonry-mcp may use createApiClient() and public client methods only — no DB, route, job-runner, CLI-dispatch, telemetry, or logger imports, and nothing on stdout but MCP frames.deferred / excluded-protocol with a rationale in packages/canonry/src/mcp/openapi-classification.ts. MCP never adds capabilities the API/CLI lack. Details and the deliberate exceptions: packages/canonry/src/mcp/AGENTS.md.packages/api-routes/AGENTS.md → “Request parameters: identity vs tuning”).packages/api-routes/src/openapi.ts is the single source of truth for HTTP shapes; the web client, the CLI’s ApiClient, and the MCP adapter consume types regenerated from it.
jsonResponse(...); new rawJsonResponse(..., looseObjectSchema) routes fail no-new-loose-routes.test.ts. Steps: packages/api-routes/AGENTS.md → “Typed responses”.api.ts and api-aero.ts may use raw fetch. Details: apps/web/AGENTS.md → “API calls”.openapi-contract.test.ts requires every registered schema to be referenced by a route.
Generic, pure helpers (formatX, parseX, normalizeX, clampX, …) live once in packages/contracts/ and are imported everywhere they’re needed.
packages/contracts/src/ first; the “Where utilities live” table in packages/contracts/AGENTS.md maps each concern to its file.packages/contracts/test/<name>.test.ts, not in its callers.Show every percentage with formatPercent(value, unit), never (x * 100).toFixed(…): each ratio field declares its wire unit on its schema (fraction() / percent(), checked by ratio-units.test.ts), and canonry-guards/no-inline-percent flags inline percent formatting.
Fit trends and other statistics server-side (linearTrend, wilsonInterval) and put them in the DTO; a regression computed in a chart component is invisible to the CLI. Render a caught unknown with describeError, never err instanceof Error ? err.message : String(err).
Each rule is detailed in the linked file. The one-liners live here because these have caused real bugs.
AppError factories from @canonry/canonry-contracts (notFound(), validationError(), …) and let the global handler serialize them; never catch-and-reply or hand-build an { error } envelope. → packages/api-routes/AGENTS.md “Error handling”packages/db/src/schema.ts needs a new MIGRATION_VERSIONS entry in migrate.ts; never edit MIGRATION_SQL or a shipped version. → packages/db/AGENTS.mdprojects uses Drizzle’s native modes (direct access); other tables still need parseJsonColumn<T>() and manual boolean coercion. → packages/db/AGENTS.mddb.transaction() (async I/O before it, the audit log inside it, callbacks after commit). Increment counters with INSERT … ON CONFLICT DO UPDATE, never read-then-write. → packages/db/AGENTS.mdApiClient methods return contracts DTOs, and commands never cast responses. → packages/canonry/AGENTS.md “ApiClient usage”canonry apply / POST /api/v1/apply is declarative; spec.queries replaces the basket only when present (omitted = untouched). → packages/api-routes/AGENTS.md “Config-as-code apply”Every integration that calls a third party over HTTP must back off when that service pushes back. Wrap the package’s HTTP layer in withRetry from @canonry/canonry-contracts — one private fetchOnce, one exported wrapper (reference: packages/integration-bing/src/bing-client.ts) — and use isRetryableHttpError rather than a hand-written status check. packages/contracts/test/integration-retry-coverage.test.ts fails CI for a new HTTP-calling integration without it. Throttles that aren’t HTTP 429, Retry-After, base-delay tuning, and testing both directions: packages/contracts/AGENTS.md → “Third-party HTTP calls”.
~/.canonry/config.yaml is the source of truth for authentication credentials.All endpoints live under /api/v1/ with Authorization: Bearer cnry_...; the full contract is GET /api/v1/openapi.json (no auth). Never change an existing endpoint path or HTTP method — the CLI, UI, and external integrations are hard-coded to them. Additive changes (new endpoints, new optional fields) are fine; renaming or restructuring needs a versioned migration plan and explicit user approval. If a route is wrong, fix the logic, not the URL.
A probe run (runs.trigger = 'probe', RunTriggers.probe; canonry run --probe or POST /api/v1/projects/:name/runs with "trigger": "probe") writes a snapshot for operator/agent inspection but MUST NOT influence the dashboard, analytics, intelligence, reports, or notifications.
notProbeRun() from packages/api-routes/src/helpers.ts, including recent-runs windows. Add a case to packages/api-routes/test/probe-exclusion.test.ts for every new aggregate endpoint.runId (GET /runs/:id, screenshots, browser diffs, GSC inspect lookups) include probes.GET /runs, GET /projects/:name/runs) include probes. The dashboard overview filters them in apps/web/src/queries/use-dashboard-overview.ts.RunCoordinator (packages/canonry/src/run-coordinator.ts) returns early for probes — no intelligence, webhooks, or Aero wake. New post-run subscribers keep that check.manual or probe (runTriggerRequestSchema); scheduled, config-apply, and backfill are server-set.Canonry can run behind a reverse proxy sub-path (e.g. /canonry/); code that ignores basePath produces silent 404s in production.
createApiClient() — it folds config.yaml and CANONRY_BASE_PATH into apiUrl. Never new ApiClient(loadConfig().apiUrl, …).routePrefix; never hardcode /api/v1. Redirect and OAuth callback URLs use publicUrl or apiUrl, which already include the base path.window.__CANONRY_CONFIG__.basePath for API calls and the router base.GET /health (also served at <basePath>health) reports basePath plus build and instance identity. Field contract: packages/canonry/AGENTS.md → “Health endpoint”; adding fields is fine, renaming or removing one is breaking.Bump the package version only for non-documentation changes of more than 100 changed lines (features, bug fixes, refactors, dependency updates, and the tests that accompany them); documentation-only changes (README, docs/, AGENTS.md) and smaller changes don’t bump. A bump updates the root package.json and packages/canonry/package.json together, in sync with the latest published @canonry/canonry. Use semver: patch for fixes, minor for features, major for breaking changes.
For a user-facing major or minor release, consider adding a highlight to apps/web/src/lib/release-notes.ts under its stable package version. Put the newest release first. Patch installs carry forward existing highlights without generating another unread indicator.
Native-plugin exception: any change shipped through plugins/canonry/ or its canonical skills/canonry/ / skills/aero/ sources bumps Canonry, the portable manifest, and both client manifests even when the diff is small — clients use the manifest version to discover updates. pnpm plugin:sync copies the package version into all three manifests.
Use the repository test-audit skill whenever writing, changing, reviewing, running, or auditing tests. Read it before selecting or editing tests. Apply its authoring gate to new or changed tests; for routine runs, check the affected tests’ observable contract and credible failure mode without starting a full-suite audit. Follow its evidence and retention bars before removing coverage. Canonry validation commands and workflow details live in docs/testing.md.
Every non-trivial change ships with tests — features, bug fixes, and refactors. Typo, comment, and config-only changes are exempt. Vitest runs the workspace projects in vitest.config.ts; tests live in each package’s test/ directory.
os.tmpdir() and clean up in afterEach.canonicalDomain raw — full URLs and mixed case included) and use the canonical helpers (hostOf, normalizeQueryText). A clean-fixture-only suite passes while production values miss the match.defaultLocation) feeds another feature (run creation), exercise the full path with no explicit override — not just “the default is stored” and “the consumer accepts a value”.// else use project default is a wish, not an implementation: a branch a comment describes must exist. The no-warning-comments lint rule flags TODO / FIXME / HACK so deferred work doesn’t rot.// allLocations handled in the block below).Several rules in this file are true only because a lint guard enforces them — see docs/GUARDS.md for the full guard table and Adding a guard procedure. Lint runs on oxlint: .oxlintrc.json, with the custom rules as JS plugins in eslint-rules/. Every guard has its own rule id; never add options to core no-restricted-syntax (overrides resolve rules last-wins, so a later block clobbers prior guards with no diagnostic — 4 dead guards found 2026-08-05). Key guards: canonry-guards/no-raw-http-web (apps/web → SDK), canonry-guards/no-raw-http-cli (canonry → ApiClient), canonry-vocabulary/no-banned-metric-literal, design-tokens/no-literal-palette — full list in docs/GUARDS.md.
Per-package AGENTS.md must stay in sync — see docs/DOC_UPDATE.md for the full “When you… → Update…” table (route/CLI/MCP/doctor/guard/provider etc.).
Put a new rule in the AGENTS.md closest to the code it governs; add it here only if every change must follow it. Point to the source (path or file:line) instead of copying it, and leave out what an agent can learn from the code, --help, or docs/CODEMAP.md.
AGENTS.md is the only agent-instruction file. Claude Code v2.1.277+ reads it directly, but only where no CLAUDE.md, .claude/CLAUDE.md, or CLAUDE.local.md is on the path, so never add one: it hides the AGENTS.md beside and below it. Claude Code sessions that cannot read AGENTS.md directly (before v2.1.277, on Bedrock / Vertex / Foundry, or with telemetry disabled) get no project instructions from this repo.