# Canonry CLI Reference

## SEO data

`cnry seo trends <project> --profile-id <id> [--days 30|90|180] [--keyword <search>] --format json`
reads comparable saved refreshes. The default window is 180 days ending on the
latest observation. Domain
profiles report ranked searches, top-10 rankings and estimated organic traffic
for the first target. Market profiles report the page-one count for matching
non-brand query assignments. Ranked-keyword profiles report organic position
for a selected search from the saved sample. Keep each point's observation date
and `runId` with its values, and retain null readings and the returned change basis.

`cnry seo context <project>` lists configured sources, exact scopes and permissions. Use `seo profile list/show/set` to manage profiles, `seo overview`, `seo keyword-metrics`, `seo domain-intelligence`, `seo ranked-keywords`, `seo competitors`, `seo keyword-gaps` and `seo market-rankings` for stored evidence. Preserve `--profile-id` and `--run-id` when paging with `--limit` and `--offset`. `seo market-rankings` is the site's Google position for its tracked non-brand queries in each market (the same queries AI visibility measures), searched from that market's location; `--market` and `--region` narrow the rows, `--outcome` (`needs-work`, `page-1`, `ranks-11-20`, `ranks-21-plus`, `not-ranked`, `partly-checked`, `rival-ahead`, `failed`, `cancelled`) and `--search <text>` filter them, and `--sort=rank` puts the closest to page 1 first (`--sort=-rank` the furthest). `searchStatus` says how each search ended: a null rank in a `completed` or `partial` row means not in the checked results (`depth`, lower for a partial search, whose unranked rows are `partly-checked`, never `not-ranked`), and a `failed` or `cancelled` row has no rank because the search returned nothing. `seo market-summary` counts the rows by outcome for the profile (one group per region), `--region` (one group per market) or `--market`.

To set up a profile, read `seo context` for the `connectionId` and supported scopes, then run `seo profile set <project> <profile-id> --file profile.json`. Saving never starts paid work, but an enabled `seo-sync` schedule refreshes every saved profile at its next firing. A profile holds `name`, `connectionId`, `capabilities`, `targets`, `keywords`, `locationCode`, `languageCode`, `limit` and `scope`. `targets` takes at most 20 plain hostnames: `{"kind":"domain","value":"example.com","includeSubdomains":true}` for a whole domain (domain intelligence requires one) or `"kind":"host"` with `"includeSubdomains":false` for one exact host. `keyword-metrics` requires at least one keyword. `locationCode` is the provider's location code (2840 is the United States). `scope` is `{"kind":"project"}` on Simple projects; Advanced profiles add the scope key and `expectedPlanRevision` from `seo context`. Overview metrics describe the first target only. For organic competitor discovery, add `competitor-discovery` to a whole-domain project profile. For search comparisons, add `keyword-gaps` and `competitors`, an explicit list of at most five whole-domain targets. Both capabilities require whole domains including subdomains and work at project scope for Simple and Advanced portfolios; they do not represent individual Properties or markets. Discovery never adds competitors to tracking automatically. A gap refresh collects shared and missing searches for each target/rival pair under the saved locale and row limit. `cnry seo keyword-gaps <project> --kind shared|missing|outranked` filters saved evidence: shared includes outranked; missing means the source comparison found no target rank, not that the target disappeared from a paginated sample. A positive `rankGap` means the rival is ahead; null means at least one position is unavailable. `seo market-rankings` returns the server's `topCompetitor` and the same signed gap from its observed results.

Both comparison reads sort all saved matching rows on the server before pagination. `seo keyword-gaps --sort` accepts `keyword`, `kind`, `target-rank`, `competitor-rank`, `rank-gap` and `volume`; `seo competitors --sort` accepts `domain`, `shared`, `position` and `traffic`. Prefix a field with `-` for descending order, using `=` when it starts with a dash, for example `--sort=-volume`. Missing values stay last in either direction. Omit sort to retain source order. Keep `--run-id`, filters and sort fixed while paging. Sorting is read-only and never refreshes provider data.

Market rankings need their own profile: `"capabilities":["market-rankings"]`, exactly one target that is one of the project's own domains, `"keywords":[]`, and `rankings` with `locations`, `depth` (10 to 100 in steps of 10), `device` (`desktop` or `mobile`) and `searchText` (`query` or `query-without-market-region`). They search the project's tracked non-brand queries, so the project needs a brand name to tell branded queries apart. Every market needs a location, or the profile is refused with the markets that lack one. A Simple project with locations searches every tracked query in each location, keyed by its location label; an Advanced market resolves through its own key, then its group and that group's parents. Only a project with no locations or markets falls back to the profile's `locationCode`; an explicit `project` key gives that location a readable label. The CLI has no location lookup: take each code and its label from the provider's location list (for example `200623` is the Dallas-Ft. Worth metro). Tracked competitors are reported in each row without further setup.

After explicit approval for the profile and bounded work, prepare `seo refresh-intent <project> <profile-id>`, then pass its token and a stable retry key to `seo sync --intent-token ... --idempotency-key ...`. A `seo-sync` schedule (`schedule set <project> --kind seo-sync --cron '0 7 2 * *'`) refreshes every saved profile on its cadence; it is standing approval for recurring paid work, so set one only when the operator asked for that cadence. Enabling it needs `seo.run`. `cnry doctor --project <project> --check seo.data.recent-refresh` warns, and the health pass alerts, when the latest scheduled refresh failed (with its reason) or none completed within two days of its due date. Inspect `seo runs` and `seo run show`; `seo run cancel` stops undispatched work. Use `--format json` for API-shaped output. Hosted budgets are internal. Never infer actual traffic from provider estimates or broaden a Property into a domain.

The CLI is invoked as `cnry` (short form) or `canonry` — both ship with the `@canonry/canonry` npm package and behave identically. This reference uses `cnry`.

## Find a command

`cnry help` lists every command group in this binary. Use `cnry help --format json`
for the complete catalog, or `cnry help ga --format jsonl` for one command per line
in a group. `cnry --help --format json` and `cnry ga --help --format json` provide
the same discovery output. The catalog includes access, flags, dry-run support and
supported rolling windows. Contextual help prints `Access: stored`, `Access: live`
or `Access: write`; live means the command calls a provider now, while write means
it changes server or local state. `--trace` reports the response access header for
API calls. Help is local and does not contact the server.

## Server Management

```bash
cnry bootstrap                                 # local config/database; providers optional
cnry init                                      # optional interactive provider/OAuth setup
cnry start                                     # start daemon
cnry stop                                      # stop daemon
cnry serve                                     # foreground mode
cnry serve --host 0.0.0.0 --port 4100
cnry serve --embed --embed-allow-origin https://app.example.com   # read-only embed mode (#716)
cnry dashboard reset-password                  # clear a forgotten dashboard password (edits local config.yaml)
cnry --version
```

`cnry bootstrap` is the provider-free Agent Readiness path. It stores state under
`$CANONRY_CONFIG_DIR` when set, otherwise `~/.canonry`, and prints a new API key
once. With no provider, its `--format json` output lists `nextSteps` for adding
one, and `agent-readiness run|score|overview` print a
`NO_PROVIDER` notice on stderr (one `{"notice":{...}}` line for JSON): AI
Visibility is the next step after Agent Readiness. The operator adds the key in the
dashboard or in their own terminal; never ask for it in chat. `cnry settings
provider` registers a provider on the running server immediately. `cnry init` is the optional interactive path when provider/OAuth setup is
wanted at the same time. An agent must ask the operator to run either
secret-bearing command in a private terminal without pasting the output back.

Rerunning `cnry bootstrap` saves provider settings and, when they changed,
reloads a running local server whose config and database match. A provider key
from the environment replaces that provider's saved credentials as a unit
(`GEMINI_API_KEY` drops a saved Vertex project, and `GEMINI_VERTEX_PROJECT`
drops a saved key); saved models, quotas, and batch settings stay unless their
environment variables are set. `serverReload` reports `reloaded` with the active
provider names, `unchanged` when the saved providers did not change (no request
is sent), `unavailable` when startup is needed, `not-local` for a remote API
URL, or `not-matching` when the server on that URL belongs to another install
(`reason: other-install`) or cannot reload (`reason: reload-unsupported`).
`not-matching` exits 0: run `cnry settings reload-providers` against this
install's server, or restart it, to apply the saved providers. Any other
rejected reload reports `failed` and exits nonzero; the saved config remains
available. Bootstrap never reloads a remote server automatically.

### Stored-only mode

Use `cnry --stored-only <command>` or set `CANONRY_STORED_ONLY=1` when the
workflow may read saved evidence but must not perform provider work or change
Canonry operational, configuration, or business state. The guard runs before
telemetry, anonymous first-run setup, skills synchronization, update checks,
configuration writes, or API access. A refused command exits 1 with
`STORED_ONLY_REFUSED`; `doctor` remains a live diagnostic and is refused unless
run outside stored-only mode. The local client refuses live and write operations
before any network call on older servers; newer servers also honor
`x-canonry-stored-only: 1` before their handlers run.

Access follows the invocation: competitor change previews, alias reads, and
alias detection without `--apply` work in stored-only mode. The corresponding
writes remain refused. `get --from doctor` is a live diagnostic; other stored
evidence sources and the settings read are allowed. Use `cnry help <group>
--access stored` or `<group> --help --access stored` to filter help. A known
group with no matching commands returns an empty result; `--access` is only a
help/catalog option.

Results exports are allowed because they read stored evidence; writing the
requested export artifact is not a Canonry state mutation. Ordinary server
request and authentication accounting remains separate from caller business
mutations. The MCP adapter has the equivalent `--stored-only`,
`--scope=stored-only`, `CANONRY_MCP_SCOPE=stored-only`, and
`CANONRY_STORED_ONLY=1` forms, and a later read-only or all-scope option cannot
widen a stored-only request.

`cnry dashboard reset-password` clears a forgotten dashboard password. It edits
`config.yaml` under `$CANONRY_CONFIG_DIR` on this machine and never calls the
server, so run it where the server's config lives. A missing file is a
`CONFIG_REQUIRED` error, not "nothing to reset". Restart the server afterward:
until then it still accepts the old password. The dashboard then asks for a new
password under the first-run rules, so stop any port forwarder first and set it
right away. `--format json` returns
`{ reset, configPath, restartRequired, namedAccounts, nextSteps[] }`; `reset` is
`false` when no password was set. On an install with named accounts
(`namedAccounts: true`) the shared password is not used, so clearing it changes
nothing: restore an account with `cnry user delete <name>` and `cnry user
create`. The command has no API route and no MCP tool.

`cnry user invite <email> --role <admin|viewer>` lets that address sign in with
ChatGPT on an install with `chatgpt.signIn` on: the first sign-in whose
verified ChatGPT email matches creates the account with that role. Nothing is
emailed. `cnry user invitations` lists them with status (`pending`,
`accepted`, `revoked`, `expired`) and `cnry user uninvite <id>` revokes a
pending one. Invitations expire after 14 days and never attach to an existing
account. Administrator or full-instance key; no MCP tool. See
`docs/chatgpt-sign-in.md` for the config and plan usage.

### Read-only embed mode (#716)

Opt-in, OFF by default. Renders the dashboard "chromeless" (no nav/topbar/settings) so it can be iframed read-only, and emits a fail-closed framing contract. With `--embed` absent, served HTML + headers are byte-for-byte unchanged.

```bash
cnry serve --embed --embed-allow-origin https://app.example.com [--embed-allow-origin https://b.example] [--embed-view overview]
cnry start --embed --embed-allow-origin https://app.example.com   # daemon form (forwards flags to serve)
# Env equivalents (env overrides config.yaml `embed:`):
#   CANONRY_EMBED=1   CANONRY_EMBED_ORIGINS=https://a.com,https://b.com   CANONRY_EMBED_VIEWS=overview,project
```

- **Framing:** emits `Content-Security-Policy: frame-ancestors <origins>` on the SPA document, **failing CLOSED to `frame-ancestors 'none'`** when no valid origins are configured (so a misconfigured embed is un-framable, not open to everyone). Origins must be bare `scheme://host[:port]` — paths, wildcards (`*.host`), and non-http(s) schemes are rejected. No `X-Frame-Options` is emitted (CSP is the single source of truth).
- **Read-only is server-enforced:** embed mode adds NO write surface; the read-only API-key gate (403 on POST/PUT/PATCH/DELETE) is unchanged.
- **Cross-origin auth caveat:** the `SameSite=Lax` session cookie is NOT sent in a cross-site iframe and the shipped bundle has no API key. v1 works for a **same-origin** embed (cookie flows) OR a self-hosted build with a read-only `VITE_API_KEY` baked in (then client-visible). Do not loosen the cookie to `SameSite=None`.

Production managed by PM2:
```bash
pm2 status
pm2 logs canonry
pm2 restart canonry
```

## Project Management

```bash
cnry project list                              # list all projects
cnry project create <name> --domain <url> --country US --language en   # brand name from the domain unless --display-name
cnry project show <name>                       # project detail
cnry project setup <name>                      # first-run setup: Agent Readiness audit scan, AI Visibility check, next step
cnry project update <name>                     # update project settings
cnry project update <name> --add-lead-event book_demo --remove-lead-event old_event
cnry project update <name> --no-count-key-events   # count only the lead events above, not the GA4 property's key events (--count-key-events turns it back on)
cnry project update <name> --brand-term "Sample Brand" --add-brand-term "Sample Pro"
cnry project update <name> --marketing-host offers.example --remove-marketing-host old.example
cnry project update <name> --display-name "Sample Brand" --expect-revision 4
cnry project update <name> --dispatch-mode claude=batch   # scheduled sweeps batch this provider (repeatable; see Batch mode below)
cnry project update <name> --clear-dispatch-mode claude   # back to sync
cnry project update <name> --negative-review-max-stars 2   # review.negative for 1-2 star Google reviews only (1-4, or "default" for 3)
cnry project update <name> --site-audit-max-pages 2500   # Agent Readiness page budget for scans that set none (1-50000, or "full" for the full site); create takes it too, spec.siteAuditMaxPages in apply
cnry project update <name> --add-site-audit-domain shop.example.com   # every Agent Readiness scan also covers this owned domain (--remove-site-audit-domain, or --site-audit-domain to replace the list); spec.siteAuditDomains in apply
cnry project update <name> --add-domain shop.example.com --add-site-audit-domain shop.example.com   # a site must be an owned domain first; one command can do both
cnry project update <name> --competitor-auto-aliases apply   # store answer-derived competitor names after each sweep (off | preview | apply; default preview logs only); spec.competitorAutoAliases in apply
cnry project update <name> --add-qualified-alias "Acme NYC"      # sentiment treats this existing alias as the brand's own name (see Brand aliases)
cnry project update <name> --remove-qualified-alias "Acme NYC"   # repeatable; create takes --qualified-alias
cnry project delete <name>                     # delete a project
cnry project delete <name> --dry-run           # preview cascade impact (GET /delete-preview) without writing
cnry status <project>                          # stored run, integration and health status for one project
cnry status --all [--problems]                 # stored status for every project and connected integration
```

`project setup` reads `GET /projects/<name>/setup` from stored state only: no provider call, crawl or write. Each track is the latest non-probe run of its kind (`not_started` when there is none): the Agent Readiness audit scan (`site-audit`) and the AI Visibility check (`answer-visibility`). A check that measured every location is one sweep of sibling runs (`aiVisibility.runIds`, newest first), read as one check: running while any run is, partial when only some saved results. Neither gates the other. A queued or running track reports stored progress (scan pages found and checked against its page budget; check answers saved against the answers it planned), a completed or partial one its result (scan score and pages scored; check answers, engines, and query counts with non-brand and branded kept apart, and text output labels it `Baseline` or `Latest check`). `aiVisibility.baselineRunId` names the baseline, the first check to finish with a result, in every state (null before any); the latest check is the baseline when `runId` equals it, and a failed one its reason; a failed check also lists each engine's failure kind (`failedEngines[].code`, such as `PROVIDER_BILLING` for an account out of credit), and text output adds the step that fixes it. `aiVisibility.blockedBy` is the run preview's readiness (`no_engine`, `no_queries`, `plan_unpublished`, `engines_failing`; Simple and Advanced). `nextAction` is the server's next step: `run_agent_readiness`, `retry_agent_readiness`, `connect_engine`, `add_queries`, `publish_plan`, `run_ai_visibility`, `repair_ai_visibility`, `wait` or `open_project`; text output prints it as a `Next:` command. It names a step and grants nothing: the scan and the check (which spends the operator's AI engine accounts) each need approval. `--format json` is the API object; MCP `canonry_project_setup` returns the same.

Project updates use PATCH and preserve omitted settings and config source. Measurement
flags are repeatable: `--lead-event`, `--brand-term`, and `--marketing-host` replace
only their named list; `--add-*` and `--remove-*` adjust it. Lead event matching is
case-sensitive; brand-term and host removals ignore case. Values use the shared
measurement validation. `project show` includes these lists in human output.

Conversions are the configured lead events plus the events the GA4 property
marks as key events, read from the GA4 Admin API on each GA sync, so a store's
`purchase` or a site's own conversion events count without setup. Key events
that are funnel or engagement steps (GA4's standard names such as
`view_item`, `add_to_cart`, `begin_checkout`, `page_view`, `scroll`) are not
counted and are listed in `leads.countedEvents.ignoredKeyEvents`; configure
one as a lead event to count it. Omitted
`measurement.countKeyEvents` means on; `--no-count-key-events` (or
`countKeyEvents: false`) counts only the configured events. When the counted set
changes, the next GA sync refreshes 180 days of lead-event data. A failed
key-event read keeps the previous list and never fails the sync.

The CLI sends the revision it read, or validates an explicit positive
`--expect-revision`. A stale revision returns `PROJECT_REVISION_CONFLICT` without
writing. A server whose PATCH route is unavailable uses the legacy full PUT after
a second read confirms the revision is unchanged. That old-server fallback cannot
provide atomic compare-and-swap protection; upgrade the server for that guarantee.
The native MCP tool `canonry_project_update` accepts the same partial request.

### Brand aliases

`spec.aliases: string[]` on the project (set via `cnry apply`, `cnry project update <name> --add-alias <name>`, or the dashboard) widens the mention detector. Use it when the answer text says "Meta" but the canonical brand is "Facebook", or for a product or former name ("AcmeCloud Pro"). Matching ignores case, spacing and punctuation, so "AcmeCloud" already matches "Acme Cloud"; it is the same answer-text scan that powers `answerMentioned`.

`spec.qualifiedAliases: string[]` (sentiment only; `--add-qualified-alias` / `--remove-qualified-alias` on update, `--qualified-alias` on create) marks aliases the sentiment evaluator is told are the brand's own names, with their exact spelling, for example a former name or a spaced spelling of one. Each must already be an alias, must not be a spelling of the display name, needs a brand key of at least four characters, and must not be a competitor's name (its domain label or a curated competitor alias); a rejected entry is a 400 naming the reason. It changes neither `answerMentioned` nor query classes. An omitted field keeps the stored list (minus names that no longer qualify: a removed alias, a spelling of the display name, or a competitor's name) and `[]` clears it. Adding a competitor drops a qualified alias it shares a brand key with. It applies to runs dispatched afterward only; recorded answers are not rescored.

## Surgical Reads — `cnry get`

```bash
cnry get <project> scores.mentionShare.value
cnry get <project> mentionCoverage.populations --format json
cnry get <project> topInsights
cnry get <project> latestRun.status
cnry get <project> --from overview mentionCoverage.selection   # pick a registered source
cnry get <project> <path> --format json                          # raw JSON output
```

Resolves a dot/bracket path against the project's overview (default `--from overview`) or any registered source: `overview`, `doctor`, `runs`, `queries`, or `competitors` Returns the scalar (or sub-tree) at the path so an agent can lift a single number without pulling a 30 KB JSON payload. Use `--from <source> .` to see the available top-level keys for that source.

### Locations

Projects support multi-region location context for geographically-aware sweeps:

```bash
cnry project add-location <name> --label "NYC" --city "New York" --region NY --country US
cnry project locations <name>                  # list configured locations
cnry project set-default-location <name> <label>
cnry project remove-location <name> <label>
```

## Sweeps

```bash
cnry snapshot "Acme Corp" --domain acme.example.com      # one-shot sales snapshot
cnry snapshot "Acme Corp" --domain acme.example.com --md          # save markdown report
cnry snapshot "Acme Corp" --domain acme.example.com --output report.md  # custom path
cnry snapshot "Acme Corp" --domain acme.example.com --pdf         # save PDF report
cnry snapshot "Acme Corp" --domain acme.example.com --format json
cnry snapshot "Acme Corp" --domain acme.example.com --provider gemini --format json  # repeat --provider to select several
cnry snapshot "Acme Corp" --domain acme.example.com --provider-mode api  # all configured API providers
cnry snapshot "Acme Corp" --domain acme.example.com --provider-mode browser --queries "best widget suppliers"

cnry run <project>                             # sweep the project's configured measurement scope
cnry run preview <project> --format json       # stored-only workload/admission for the next default full manual sweep
cnry run <project> --provider gemini           # single provider only
cnry run <project> --query "alpha" --query "beta"  # scope sweep to a subset of tracked queries (repeatable)
cnry run <project> --wait                      # block until complete (a batch run: until batch-pending, then exit 0); exit 2 if the run failed
cnry run <project> --location <label>          # run with specific location context
cnry run <project> --all-locations             # run for every configured location
cnry run <project> --no-location               # explicitly skip location context
cnry run <project> --probe --provider openai --query "..."  # operator/agent test run — snapshot is inspectable but EXCLUDED from dashboard, analytics, intelligence, report, and notifications. Use for verification / "did this fix work?" / regression hypothesis testing.
cnry run <project> --dispatch-mode batch       # send every eligible provider to its batch API (half-price tokens; answers can take up to the deadline)
cnry run <project> --force                     # call every provider, even ones that keep failing on their accounts (see PROVIDERS_FAILING below)
cnry run --all --wait                          # all projects
cnry run cancel <project> [run-id]             # force-cancel stuck runs
cnry run completeness <run-id>                 # answered vs missing answers per provider, and whether a fill is allowed
cnry run fill <run-id> --dry-run               # what a fill would record, without spending quota
cnry run fill <run-id> [--provider claude] --wait  # record a partial run's missing answers under the SAME run id
cnry runs <project> --limit 10                 # list recent runs, including probes
cnry run list <project> --kind traffic-sync --status failed --since 2026-10-01T00:00:00Z --limit 20 --format json
cnry run show <id>                             # show run details
```

`run list <project>` and `runs <project>` read the same stored history. Filters
include `--kind`, `--status`, `--since`, `--exclude-kind`, and repeatable or
comma-separated `--exclude-kinds`. The inclusive `--since` timestamp accepts
UTC or an offset. Omit it for all dates; omit `--limit` for all matching runs.
The newest limited rows retain chronological order. Traffic sync rows include
`sourceId` when stored, and human output shows failed and partial errors.
JSON is the API array; JSONL emits each run with its project. With no second
positional, `run list` retains the sweep shorthand for a project named `list`.

`run preview` reports query classes, engines/models, locations and Advanced published revision/assignments. `expectedRequestCount` counts planned answer slots; `requestCount` excludes unavailable engines and held provider accounts. It makes no provider calls or writes, reserves no work, and does not preview scoped, forced, or all-location overrides. A draft-only Advanced project must be published before an ordinary sweep.

Run statuses: `queued` → `running` → `completed` / `failed` / `partial`

`partial` = some providers failed (usually rate limits) — successful snapshots are still saved.

`--wait` exit code (`run <project>`, `--all-locations`, and `--all`): the run detail, location table, or JSON prints in full first, then the exit code reports the final status.

- `failed` → exit `2`: every provider call failed (for example an invalid API key), so fix the cause and retry. stderr carries `{ "error": { "code": "RUN_FAILED", "message", "details": { "waitedRunCount", "failedRuns": [{ "runId", "project", "location"?, "error" }] } } }`; stdout is unchanged.
- `--all --wait` and `--all-locations --wait` exit `2` when any waited run failed. A project whose trigger returned an `error` row has no run to wait on and does not count.
- `completed`, `partial`, and `cancelled` → exit `0`. A partial run kept its answers, so finish it with `cnry run fill` instead of re-running the sweep. A cancelled run was stopped by an operator.
- A batch-pending run (see Batch mode below) still reads `running`, so `--wait` stops there and exits `0`.
- Without `--wait` the command exits `0` once the run is queued; read the outcome with `cnry run show <id>`.

A provider that failed on its account in each of its last 10 runs that called it, with a rejected key or denied access (`PROVIDER_AUTH`) or no credit left (`PROVIDER_BILLING`), is held back. A narrower run (`--provider`, a probe) neither resets nor extends the other providers' counts.

- When only some of a run's providers are held back, the run is queued without them. `skippedProviders` on the run names each with its code, streak and `retryAfter`; the run calls the rest and ends `partial`, and `error.providers.<name>` has `skipped: true`. `cnry run` and `cnry run show` print a `Skipped:` line for each.
- When every provider it would call is held back, the run is refused before it starts, exit `1` with `PROVIDERS_FAILING`. `details.providers` names each provider's code, as does `error.providers.<name>.code` on each failed run. Scheduled sweeps skip their slots instead: the first skipped slot writes a `run.refused` row to `cnry history <project>`.
- `cnry status <project>` reports whether sweeps would be refused or which providers they would skip. `admission` on `GET /projects/<name>/runs/latest` (or `latestRun.admission` on the overview) uses the schedule's providers; `manualAdmission` uses the project's providers, as a manual full sweep does. Both use a published plan's frozen providers. Read these when sweeps look stalled: a refused sweep leaves no run.

Another call would only fail the same way, so fix the key, access or billing in the provider's console or settings, then:

- Saving a new key, model or endpoint in the provider's settings (`cnry settings provider <name> --api-key <key>`) releases it at once. A quota-only edit, or a change to the project's own model override, does not.
- Otherwise (a billing top-up, an edited `config.yaml`) the provider is called again 24 hours after its newest failure finished (its `retryAfter`; a refusal's `details.retryAfter` is the earliest).
- `cnry run <project> --probe` is never held back, and a probe that succeeds clears the provider's streak: use it to check a fix.
- `--force` (`"force": true` on the API, `request.force` over MCP) calls every provider now. Use it only when the user asks to run anyway.
- `cnry run fill <run-id>` calls a skipped provider's missing answers too: a fill is an explicit request for them.

A partial run of a published measurement plan can be finished with `cnry run fill <run-id>`: it asks only the questions that have no answer yet, writes them into the same run, and marks the run `completed` once every expected answer exists. The run keeps its id, timestamps and place in history, so reports show one sweep, never two. It is refused (with a reason code) when the plan was republished since, the run started more than 24 hours ago (for a run that used batch mode: finished more than 24 hours ago), a newer sweep exists, or a missing answer has no frozen model. A provider that fails 3 times in a row is stopped for that fill; fill again once its limit lifts. Do not re-run the whole sweep to recover a few failed answers.

### Batch mode

Scheduled sweeps can send a provider's answers to its asynchronous batch API
(Claude today) at half the token price. It needs `providers.<name>.batch.enabled:
true` in `config.yaml` and the project's `--dispatch-mode <provider>=batch`.
Manual runs stay sync unless given `--dispatch-mode batch`, which is refused
(exit 1, `details.ineligible` names each provider's reason) when no provider can
batch. Only a full sweep of a published plan batches: planless runs, slices and
probes always run sync. While a batch is outstanding the run stays `running`,
`cnry run show <id>` prints `waiting on provider batch: ...`, and the project's
next scheduled sweep is skipped. `--wait` (also with `--all` and
`--all-locations`) never waits for a batch to end: once the run is
batch-pending (a batch `submitted` or `ended`) it stops polling and exits 0.
Text output adds `Waiting on provider batch(es): <provider> — N requests,
submitted <t>, deadline <t>; check with canonry run show <id>` per
batch-pending run. With `--format json`, `cnry run <project> --wait` prints the
run detail unchanged (`status: running`, outstanding `providerBatches`), and
`--all-locations --wait` prints each location's trigger row merged with its
run detail. `cnry run --all --wait --format json` prints only
`{ project, runId, status, location }` rows (plus `error`): a batch-pending
run reads `status: running` with no `providerBatches`, so read those with
`cnry run show <runId> --format json`. Treat that as success, not a timeout,
and read the outcome later with `cnry run show <id>`; re-triggering gets
`RUN_IN_PROGRESS`. Missing answers
after the deadline make the run `partial`; fill them with `cnry run fill` (sync
price, 24 hours after the run finalized). `cnry run show` also prints tokens,
searches and estimated cost per provider and tier (a priced cost under $0.00005
prints `<$0.0001`; only a real zero prints `$0.0000`); `--format json` is the
API response (`dispatchModes`,
`providerBatches`, `usage`). Batch mode is not zero-data-retention eligible on
Anthropic, so keep it off on deployments that need ZDR.

### Probe vs real runs

| Trigger | Source | Feeds dashboard/analytics | Runs intelligence | Fires notifications | Wakes Aero |
|---|---|---|---|---|---|
| `manual` | `cnry run <project>` | ✅ | ✅ | ✅ | ✅ |
| `scheduled` | cron schedule | ✅ | ✅ | ✅ | ✅ |
| `config-apply` | `cnry apply` after queries change | ✅ | ✅ | ✅ | ✅ |
| `backfill` | `cnry backfill ...` | partial (historical) | ✅ | — | — |
| **`probe`** | `cnry run --probe ...` | ❌ | ❌ | ❌ | ❌ |

After explicit approval for the exact provider/query (or a bounded batch), use
`--probe` for verification rather than producing data the user/dashboard will
consume. A probe still costs provider quota and writes a snapshot; approval for
one probe does not authorize repeats.

`snapshot` does not create a project or write to the DB. It generates category queries, runs providers, and produces a report for prospecting.

`--provider <name>...` and `--provider-mode all|api|browser` constrain both answers
and analysis calls. Omit both to use every configured provider. A named provider
must be configured and match the selected mode. Browser-only selection requires
manual `--queries` and uses no API provider for analysis. API:
`POST /api/v1/snapshot` with optional `providers` and `providerMode`. MCP:
`canonry_snapshot` in the discovery toolkit; unavailable to read-only connections
because generation spends provider quota.

## Mention + Citation Data

Two independent signals per (query × provider): **mention** (`answerMentioned` — brand named in the answer text; the **primary** read) and **citation** (`cited`/`citedDomains` — domain in the grounding sources; **secondary**). Read mention first. Never compute one from the other; never coerce `answerMentioned` null → false (null = "not checked").

```bash
cnry citations visibility <project>            # two-glyph [citation][mention] cell per (query × engine) + Cite/Ment counts
cnry citations urls <project> --category forum,social,video --format json   # every cited thread/post, one row per page: answers, how many mention the brand, engines, queries, first and last sweep
cnry citations urls <project> --category forum,social,video --new-in-latest   # only pages the latest sweep cited for the first time (window all by default)
cnry citations urls <project> --domain reddit.com --sort newest --limit 50    # one site, most recent first citation first; follow nextCursor for more
cnry evidence <project>                        # latest citation per query (✓ cited / ✗ not-cited / · not measured) + Cited: X / Y
cnry evidence <project> --format json          # JSON output: each query's runs with citation and mention state
cnry history <project>                         # audit trail
cnry history <project> --entity-type competitor --format json
cnry history <project> --action-prefix competitors. --exclude-entity-type traffic_source --since 2026-10-01T00:00:00Z --until 2026-10-02T00:00:00Z
cnry export <project> --include-results        # export as YAML
cnry export <project> --include-secrets        # include webhook URLs; requires administrator authority or a wildcard key
cnry backfill answer-mentions                  # recompute answerMentioned (primary) from stored answers (honors aliases)
cnry backfill answer-mentions --dry-run
cnry backfill answer-visibility                # recompute citationState (secondary) from stored answers
cnry backfill answer-visibility --dry-run      # preview which snapshots would change
cnry backfill insights <project>               # recompute insights for completed runs
cnry backfill insights <project> --since 2026-04-01 --dry-run
cnry backfill traffic-classification --project <name> --dry-run  # stored traffic under today's rules; the dry run lists every change
```

History filters compose on project reads and `history --all`. `--action` remains
exact; `--action-prefix` matches a literal prefix. Repeat `--exclude-entity-type`
or supply a comma list to remove noisy entity types before paging. `--entity-id`
selects one entity. Time bounds are inclusive, normalize offsets to UTC, and
reject invalid values. `--actor api` includes legacy API, API-key, and user
actors; other actors match exactly. Empty filters are rejected. Human output shows actor and client origin; instance-wide rows include the project name. Select either a project or `--all`.
New competitor replacement records include `added`, `removed`, and any discarded
aliases beside the resulting `competitors` list. Older records remain unchanged.

`backfill traffic-classification` runs on demand the pass a `canonry serve`
server runs once after a rules change. It re-files stored traffic under today's
rules: unknown samples and unrecognized agents a rule now names, crawler hours
whose sampled user agent today's rules file elsewhere, agent traffic the trust
rules now call likely fake, browser-agent journey requests capture now leaves
out, and journeys a background call opened. Unlike the server's pass, it also
makes the crawler changes that leave verified hits claimed (stored traffic keeps
no IP to check again); `--dry-run` lists every change, those included
(`crawlers.unverifiedHits`). An unknown `--project` exits 1 with `NOT_FOUND`.

Project exports redact notification webhook URLs by default as `redacted://<host>/<notification-id>`.
Applying that export preserves the existing notification ID, signing secret, source, enabled state and creation time. The HTTPS `/redacted` placeholder from notification listings also preserves the matched stored destination. A real URL change appears in preview and audit as a URL-change marker without exposing its path or secret.
Use `--include-secrets` only when the credential has administrator authority. The CLI prints a redaction note to stderr when URLs remain redacted.

`cnry citations visibility` prints a two-glyph cell per (query × engine): citation first, mention second. Uppercase = present, lowercase = absent, `·` = citation not measured (the engine returns no sources, such as a local model), `–` = no snapshot. **C/c = cited** (secondary), **M/m = mentioned** (primary). The legend prints above the table; never collapse the two signals into one cell.

```
(cell = [citation][mention];  C=cited c=not ·=not measured, M=mentioned m=not, –=no data)
Query             gemini  local  openai  Cite  Ment
acme corp ny      CM      ·M     CM      2/2   3/3   ← mentioned AND cited
best crm for smb  cM      ·M     cM      0/2   3/3   ← mentioned, not cited (mention win, citation gap)
crm pricing       Cm      ·m     cm      1/2   0/3   ← cited, not mentioned (citation without share of voice)
free crm tools    cm      ·m     cm      0/2   0/3   ← neither
crm for agencies  –       ·M     –       ·     1/1   ← mentioned; citation not measured (no sources), never a citation gap
```

`Cite` is the engines that cited the query over those whose sources were checked (`·` when none were); `Ment` is the engines that mentioned it over those that answered. `Cited in sources: X/Y engines` and `Mentioned in answers: X/Y engines` above the table report the two signals independently — a query can be one, both, or neither.

`cnry evidence` prints each query's latest citation instead: `✓ cited`, `✗ not-cited` or `· not measured (no sources)`, with a transition such as `(lost)`. Its summary is `Cited: X / Y`, where `Y` counts only queries whose latest answers carried sources, and `Not measured: N` lists the rest apart. It prints no mention line; `--format json` carries each run's `mentionState` and `mentionTransition`.

## Results Export (historical observations)

```bash
cnry results export <project>                          # versioned JSON artifact → canonry-results-<project>-YYYY-MM-DD.json in cwd
cnry results export <project> --format csv             # flat spreadsheet representation of the same records
cnry results export <project> --format json --output - # stream the artifact to stdout (agent-friendly)
cnry results export <project> --since 2026-06-01 --until 2026-06-30   # inclusive run-creation window (date-only until covers the whole UTC day)
cnry results export <project> --include-probes         # opt IN to probe runs (excluded by default)
```

Bulk download of every persisted answer-visibility query × provider observation — one record per snapshot, ordered by run then snapshot. This is the raw-history primitive; use `visibility-stats` for aggregates and `visibility-compare` for month-over-month claims.

Behavior to know:
- **Citation and mention stay independent** per record: `citationState`/`cited` describe source-list attribution; `answerMentioned`/`mentionState` describe answer-text presence. `answerMentioned: null` means "not evaluated" (legacy snapshot), never not-mentioned. `citationState: not-measured` with `cited: null` (an empty CSV cell) means the engine returns no sources, never not-cited; an older row of such an engine that stored `not-cited` exports as `not-measured`.
- `query` is the snapshot-time text, so removed tracked queries keep their history; `queryId` is null for them.
- Includes completed, partial, and failed answer-visibility runs. Probe runs and other run kinds (site-audit etc.) are excluded unless `--include-probes`.
- CSV cells are spreadsheet-injection-safe (leading `=`, `+`, `-`, `@` neutralized) and JSON-array columns (`cited_domains_json`, …) are embedded JSON strings.
- Raw provider payloads and credentials are never included; grounding sources and issued search queries are.
- Backed by `GET /api/v1/projects/<name>/results/export` (`?format=json|csv&since&until&includeProbes`). Not exposed as an MCP tool by design — bulk attachments don't fit a context window; agents needing slices should use the paginated snapshot reads or this CLI with `--output -`.
- Distinct from `cnry export <project>`, which exports project CONFIGURATION as YAML, not results.

## Analytics

```bash
cnry analytics <project>                       # default analytics view
cnry analytics <project> --feature metrics     # mention + citation rate trends (BrandMetricsDto: mentionTrend primary, trend secondary)
cnry analytics <project> --feature gaps        # brand gap analysis — mention buckets (mentionedQueries[]/mentionGap[]/notMentioned[]) primary, cited buckets (cited[]/gap[]/uncited[], plus citationNotMeasured[] for queries whose engines return no sources) secondary
cnry analytics <project> --feature sources     # source breakdown by category
cnry analytics <project> --window 7d           # time window: 7d, 30d, 90d, all
cnry analytics <project> --feature metrics --query-class non-brand  # branded|non-brand answers only (metrics and sources); omitted = all, which pools both
cnry organic-evidence <project> --period 90 --format json  # reconcile stored Search Console, GA4, and server traffic evidence
```

### Cited-source rankings (`cnry sources`)

"Where do AI engines get the facts they cite?" — the full, per-provider, classified ranking of cited domains. Backed by `GET /api/v1/projects/<name>/analytics/sources` and the `canonry_analytics_sources` MCP tool. All counts/shares/classification are computed server-side; the CLI only renders.

```bash
cnry sources <project>                          # surface-class roll-up (own / direct-competitor / ota-aggregator / editorial-media / other)
cnry sources <project> --rank                   # full ranked cited-domain list, each tagged with category + surface class
cnry sources <project> --rank --limit 20        # top 20 domains; an explicit long-tail rollup preserves the totals
cnry sources <project> --by-provider            # per-provider cited-domain mix + each provider's total cited slots
cnry sources <project> --window 30d --format json   # window-filterable; --format json emits the SourceBreakdownDto directly
cnry sources <project> --rank --format jsonl    # stream the ranked domains, one self-contained record per line
cnry sources <project> --query-class non-brand --run-id <run-id> --rank   # sources behind the non-brand answers of one sweep
cnry sources <project> --include-by-query false --format json             # drop the large per-query breakdown (byQuery)
```

- **Surface class** is deterministic (no LLM): `own` = the project's `canonicalDomain`/`ownedDomains`; `direct-competitor` = a tracked competitor; `ota-aggregator` = directories/marketplaces (Yelp, Booking.com, Tripadvisor, Amazon…); `editorial-media` = news/blogs/reference; `other` = everything else. When discovery has run, its stored per-domain classifications (`domain_classifications`) enrich recall for niche OTAs/regional media the static allow-list misses — `own` and tracked competitors always stay authoritative. Running `cnry discover run` improves coverage.
- The ranked list is **not truncated** by default (the old top-5-per-category cap is gone). Pass `--limit N` to cap each list; the response carries `truncatedDomainCount` / `truncatedCitedSlots` so totals always reconcile.
- Counts are **cited slots**: one per (answer, cited domain) pair, so a domain cited 3× in one answer counts once. Probe runs are excluded.
- Without `--run-id` every run in the window is pooled (the scope line and `runCount` say how many); without `--query-class` branded and non-brand answers are pooled, and branded queries inflate your own domain. `--query-class branded|non-brand` takes the class from an active v2 measurement plan, otherwise from the project's brand name/aliases (a project with neither is refused). Answers the class filter cannot place are excluded and counted in `unclassifiedAnswers`. `--include-by-query` defaults to the server's `true`.

### Sitemaps across the site, Google and Bing (`cnry sitemaps`)

```bash
cnry sitemaps <project>                    # each engine's sitemaps and what it is missing, from stored data
cnry sitemaps <project> --engine bing      # one engine
cnry sitemaps <project> --format json      # SitemapCoverageResponse
cnry bing submit-sitemap <project> <url>   # ask Bing to read a sitemap (adds a new one, rereads a listed one)
cnry google submit-sitemap <project> <url> # the same for Google
```

Canonry compares three stored lists: the sitemap files the latest Agent Readiness audit scan read pages from (`site.sitemaps`), Search Console's list (stored by every Google sync, files inside each index included) and Bing's (stored by `bing sync`). For each engine, `missing` holds sitemaps the site declares, or someone submitted to the other engine, that this engine lacks (not offered from the other engine: a sitemap it only found by itself, one it reports errors for, or an index on a host where this engine already has every sitemap the site declares); a file inside a missing index is left out, since adding the index covers it. Google is offered only sitemaps inside the connected property, Bing only its site's host and subdomains. An engine is `null` until its list has been read once; after that an empty list means it has none. `submittedAt: null` on a top-level row means the engine found the sitemap itself; on a file inside an index it came through the index. A new submission shows in the stored list after that engine's next sync.

### Stored trend figures (`cnry trends`)

The figures a dashboard tab's trend card leads with, from stored data only: each figure's latest reading, its change since the first reading in the window, and its readings. Backed by `GET /api/v1/projects/<name>/trends` and the `canonry_trends` MCP tool, so the dashboard, the CLI and MCP agree on every figure.

```bash
cnry trends <project> --surface index-coverage          # Google and Bing indexed / not indexed pages, last 90 days by default
cnry trends <project> --surface site-health             # Agent Readiness score and pages checked, one reading per scan, all history by default
cnry trends <project> --surface backlinks --window 90d  # referring domains, linking hosts and top-10 concentration per Common Crawl release
cnry trends <project> --surface index-coverage --start 2026-08-01 --end 2026-08-31  # your own calendar range instead of a window
cnry trends <project> --surface backlinks --format json # TrendsResponse; jsonl degrades to the json document
```

- A figure is a level, never a sum. `change.difference` is in the figure's own unit (a share moves in points), `change.ratio` is null from a zero basis, and `change.basis` names the first reading in the window it is measured from.
- `tone` follows `better`: not indexed pages falling is `better`; pages checked and top-10 concentration are `neither`.
- The window ends on the latest reading, not today; `--start`/`--end` read a calendar range instead (never with `--window`; `window` is then null). `recordedFrom` is the first reading ever: earlier dates were never recorded, not zero.
- Scans are moments and carry `observedAt`; the human output prints the UTC date.
- Backlinks uses the crawler- and proxy-excluded totals the Backlinks tab shows, one reading per release in crawl order (however late a release was extracted), dated by the window's last month and named by its window in `label` ("May-Jul 2026"); the human output says "since May-Jul 2026". A release whose domain rows are missing is unknown, never zero.

### Aggregated visibility stats (`cnry visibility-stats`)

Per-query mention (answer-text) and citation (source-list) **counts with a sample size**, pooled across many answer-visibility runs — the data to compute a confidence-aware proportion (e.g. Wilson) or detect drift without fetching every run. Backed by `GET /api/v1/projects/<name>/visibility-stats` and the `canonry_visibility_stats` MCP tool. Probe runs and non-`answer-visibility` runs are excluded; only completed/partial runs count. `--share-of-voice` adds a head-to-head vs tracked competitors (`project / (project + competitor)` brand mentions) — the primitive for a month-over-month client report: call it with `--month <this>` and `--month <last>` and compare. **It is scoped to NON-BRAND queries by default and the response echoes `queryClass`.** A branded query hands the model your name, so you are mentioned on ~all of them and a competitor structurally cannot be; a pooled figure therefore reports brand recall as category placement (measured: one basket read 42% / rank 1 pooled and 3% / rank LAST non-brand). Pass `--query-class branded` for the recall figure. There is no "all" — the two never share a denominator. `--query-class` scopes share of voice only, never the counts: `TOTAL` (JSON `totals`) pools both classes, and the lines under it (JSON `byQueryClass`, plus `queryClass` on each query) split mention and citation counts into non-brand, branded and unclassified. Read the non-brand line for competitive placement.

```bash
cnry visibility-stats <project>                                   # all runs; per-query cited/measured (n/m: no sources) + mentioned/checked + pooled TOTAL
cnry visibility-stats <project> --last-runs 10                    # most recent 10 runs (mutually exclusive with --since/--until/--month)
cnry visibility-stats <project> --since 2026-06-01 --until 2026-06-30   # ISO date/time window on run createdAt
cnry visibility-stats <project> --month 2026-06                    # a whole calendar month (YYYY-MM), expanded to that month's UTC bounds
cnry visibility-stats <project> --by-provider                     # per-provider breakdown (counts sum to the pooled counts)
cnry visibility-stats <project> --month 2026-06 --share-of-voice   # share of voice vs competitors, NON-BRAND queries (the m/m report primitive)
cnry visibility-stats <project> --month 2026-06 --share-of-voice --query-class branded   # brand recall: are you named when asked about by name?
cnry visibility-stats <project> --format jsonl                    # stream one record per query, stamped with project + runCount

# Month-over-month comparison (the statistically honest m/m primitive — use this, not two --month calls diffed by hand):
cnry visibility-compare <project> --from 2026-05 --to 2026-06     # SoV-led, Wilson intervals, within-noise/moved verdict, model-continuity gated
cnry visibility-compare <project> --from 2026-05 --to 2026-06 --format json
cnry visibility-compare <project> --from 2026-05 --to 2026-06 --provider openai --location none   # narrow every frame (case-insensitive)
cnry visibility-compare <project> --from 2026-05 --to 2026-06 --scope property --scope-key <target>   # Advanced: one Property's frozen frame
```

- **Use `visibility-compare` for any month-over-month AEO claim.** It leads with **share of voice** (less exposed to an engine's broad naming propensity than an absolute rate, `driftRobust: true`), pools rates per-snapshot (invariant to sweep count), restricts to the query/provider PAIRS present in BOTH months, then to providers with one known, identical configured model id in both months, and attaches a Wilson 95% interval + a `verdict` to every metric. Verdicts: **`within-noise`** = NO confirmed change (never report it as a decline); **`moved`** = a real directional move; **`model-discontinuous` / `model-unknown`** = the engine's configured model changed, was mixed within a month, or is unrecorded, so no directional call is made (do not attribute the swing to the site). Read `continuity` (`status` + per-provider evidence) for what was excluded — `continuity` is the gate, `modelChanges` is advisory. A silent upstream version bump under an unchanged configured id remains undetectable. `lowRunCount` flags a month under 5 sweeps, where intervals are too wide to resolve a move.
- **Class rates:** `mention-rate-branded`, `cited-rate-branded`, `mention-rate-non-brand` and `cited-rate-non-brand` never pool the classes; a missing split reads `classification-unavailable`, and `excludedUnknown` counts rows without that metric's own signal. On an Advanced project without `--scope`/`--market-key`, the four original metrics keep the project frame while the class rates come from the frozen frame in **`classComparison`**: read `classComparison.continuity` (and its `basket`/run counts) as the gate for those four rates, not the top-level `continuity`. `--scope`/`--market-key` answer entirely from the frozen frame at the top level and are refused when a month holds unreconstructable schema-v1 runs.

- **Tri-state aware:** `checked` counts only snapshots where `answerMentioned` was recorded — `null` ("not checked") is **excluded**, never counted as not-mentioned. So `checked` is the correct `n` for a mention proportion. `mentionRate = mentioned/checked`; `citedRate = cited/(total - citationNotMeasured)`, where `citationNotMeasured` counts answers whose engine returns no sources (never a miss). Both rates are `null` when their denominator is 0 (undefined over no samples).
- **Date-only window:** `--since`/`--until` accept a full ISO instant or a bare `YYYY-MM-DD`. A date-only `--until 2026-06-30` covers the **whole** UTC day (through 23:59:59.999), so same-day runs are included; a date-only `--since` is that day's start.
- **Unbounded by default:** with no `--since`/`--until`/`--last-runs`, every completed/partial run is pooled (`window.runCount` reports how many). For a recent sample, bound it with `--last-runs N`.
- **`groupBy` in the payload:** present (`"provider"`) only with `--by-provider`; omitted otherwise (absent = no breakdown) — the generated SDK types it `groupBy?: 'provider'`.
- **mention vs cited stay independent** — a model can do either, both, or neither. Don't read one from the other.

<a id="site-health-technical-aeo-compatibility"></a>

## Agent Readiness

Site-wide Agent Readiness audit scan (structured data, AI-readable content, AI-crawler access, content depth/freshness/extractability, agent integrations, …) powered by `@canonry/agent-readiness`'s `runSiteCrawl`. Runs as the `site-audit` run kind — discovers in-scope URLs from the project root, sitemaps, and internal links; stores the URL/link graph; audits eligible HTML pages; and rolls the results into one 0–100 Agent Readiness score. Pure HTTP, no LLM cost; a large site can take minutes, so it runs in the background. The API serves the same data under `/api/v1/projects/<name>/agent-readiness/…`, and the MCP tools are `canonry_agent_readiness_*`.

```bash
# Scan
cnry agent-readiness run <project> [--sitemap-url <url>] [--max-pages <n>] [--max-edges <n>] [--max-depth <n>] [--site <domain>...] [--check-dead-links] [--include-geo] [--no-agent-skills] [--wait] [--format json]
cnry agent-readiness run <project> --wait                 # full crawl + audit; without --max-pages uses the project's saved page budget, else the full site (up to 50,000 pages); edges derived from the page count unless --max-edges is set; --wait polls up to 15 minutes, so follow a longer scan with agent-readiness progress
cnry agent-readiness run <project> --sitemap-url <url> --max-pages 5000 --max-edges 250000 --max-depth 12   # optional crawl seeds and custom budgets; hard caps are 50,000 pages / 1,000,000 edges
cnry agent-readiness run <project> --check-dead-links --wait   # opt in to dead-link checks; they are off by default
cnry agent-readiness run <project> --site shop.example.com --wait   # cover the main domain plus this owned domain (repeatable); without --site the saved sites apply; --site <main domain> alone scans just the main domain
cnry agent-readiness progress <project> --run-id <id> [--format json]   # exact durable phase and pages found / checked / failed counters; never a synthesized percentage
cnry schedule set <project> --kind site-audit --preset weekly   # keep it fresh
cnry schedule set <project> --kind site-audit --check-dead-links --include-geo   # make every scheduled scan a deep scan (keeps the timing)

# Score
cnry agent-readiness score <project> [--run-id <id>] [--format json]   # Agent Readiness score + per-factor scorecard (avg + pass/partial/fail per page) + delta vs the previous scan
cnry agent-readiness page-scores <project> [--run-id <id>] [--status success|error] [--sort score-asc|score-desc|url] [--limit <n>] [--format json|jsonl]   # per-page scores of audited pages (worst-first by default); --status error lists unreachable pages
cnry agent-readiness trend <project> [--limit <n>] [--format json|jsonl]   # Agent Readiness score history across past scans

# Scan overview, pages, and findings
cnry agent-readiness overview <project> [--run-id <id> | --date YYYY-MM-DD] [--format json]   # crawl metadata, budgets, completeness, and termination
cnry agent-readiness pages <project> [--run-id <id> | --date YYYY-MM-DD] [--inventory-eligible true|false] [--fetch-state <state>] [--indexability-state <state>] [--audit-state <state>] [--url-versions include|exclude|only] [--site <domain>] [--sort url|path|score-asc|score-desc] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # bounded URL inventory with depth and link score; --url-versions exclude lists pages only, as the dashboard does; --site lists one site the scan covered
cnry agent-readiness page-audit <project> (--node-key <key>|--url <url>) [--run-id <id>] [--format json]   # exact audit score, factor findings, recommendations, and crawl provenance for one graph page
cnry agent-readiness issues <project> [--run-id <id>] [--site <domain>] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # stored findings including passing-score issues, affected-page counts and example URLs; --site limits them to one site
cnry agent-readiness issue-pages <project> --issue-id <id> [--run-id <id>] [--site <domain>] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # affected URLs for one issue; pin the run from the issue list

# Site structure and links
cnry agent-readiness structure <project> [--run-id <id>] [--site <domain>] [--parent-path <path>] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # one level of one site's path hierarchy (the main domain unless --site names another)
cnry agent-readiness links <project> [--run-id <id>] [--source-url <url>] [--target-url <url>] [--followable|--nofollow] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # bounded internal-link edges
cnry agent-readiness neighbors <project> (--node-key <key>|--url <url>) [--run-id <id>] [--limit <n>] [--format json]   # bounded inbound/outbound neighborhood of one page
cnry agent-readiness dead-links <project> [--run-id <id>] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # disabled unless the run opted in
cnry agent-readiness subgraph <project> [--run-id <id>] [--node-key <key>|--url <url>] [--hops <n>] [--max-nodes <n>] [--max-edges <n>] [--format json]   # focused semantic graph (MCP defaults to 25 nodes / 50 edges)
cnry agent-readiness path <project> (--to-node-key <key>|--to-url <url>) [--run-id <id>] [--from-node-key <key>|--from-url <url>] [--max-depth <n>] [--format json]   # directed shortest followable-link path
cnry agent-readiness changes <project> [--from-run-id <id>] [--to-run-id <id>] [--scope all|pages|links] [--change all|added|removed|changed] [--cursor <cursor>] [--limit <n>] [--format json|jsonl]   # canonical scan diff; either scan ID is optional; JSONL begins with scan/cursor/filter metadata
```

**Deprecated names.** The older `technical-aeo …` and `site-health …` commands still work as aliases, with the same flags, output, JSON, and exit codes; they will be removed only in a future major version. Four subcommands have new names: `technical-aeo crawl` and `site-health overview` are `agent-readiness overview`; `technical-aeo crawl-pages` and `site-health pages` are `agent-readiness pages`; `technical-aeo pages` is `agent-readiness page-scores`; and `technical-aeo links neighbors` and `site-health neighbors` are `agent-readiness neighbors`. Every other subcommand keeps its name.

Agent integration checks run by default, inspecting discoverable actions, forms, and tool links. Use `--no-agent-skills` to disable them. Geographic checks are off by default; `--include-geo` adds location and service-area signals. Both selections change scan identity. Lighthouse is not exposed by Canonry.

A scheduled scan always covers the full site (or the project's saved page budget). Which checks it runs belongs to the schedule: `schedule set --kind site-audit` takes the same `--check-dead-links`, `--include-geo` and `--no-agent-skills` flags as a manual scan, and any of them sets the whole list of checks. `--default-checks` goes back to the defaults (no dead links, no location checks, agent checks on). Without these flags the schedule keeps its checks, so moving, pausing or resuming it never drops them; check flags alone keep the current timing. `schedule show` prints them on a `Checks:` line, and the API returns them as `siteAudit` (PUT `siteAudit`: omit to keep, `null` to reset).

To assess Agent Readiness, begin with `cnry agent-readiness score <project> --format json`. Use `cnry agent-readiness overview <project>` only to add crawl metadata; it never replaces the score. Use `cnry agent-readiness page-audit` (MCP: `canonry_agent_readiness_page_audit`) to tie a selected graph page's audit score to exact findings and fixes. Link score is importance, not an audit verdict. Then request a focused neighborhood, a shortest path, or scan-to-scan changes. Do not ask an agent to materialize the interactive graph: it can exceed the MCP tool-result limit. The matching traversal tools are `canonry_agent_readiness_subgraph`, `canonry_agent_readiness_path`, and `canonry_agent_readiness_changes`; the subgraph tool defaults to a small focused result and should be expanded only when needed.

- The score is only available after at least one scan runs — `score` returns `hasData: false` until then.
- A scan can cover owned domains besides the main domain (a property locator, a shop). Links between them count as internal and the page budget is shared. `overview` lists every site in `sites` with its page counts, score and, for a site it could not reach, the reason; `score` keeps one headline over every page and adds each site's score in `sites`. When the previous scan scored a different set of sites (one added, removed or not reached), `score` reports no change (`deltaScore` null, `deltaUnavailableReason: sites-changed`) instead of comparing unlike scores. A scan covers at most 20 sites besides the main domain. Each page carries its `site` (bare host), its `path` never includes the host, and `pages`, `structure`, `issues` and `issue-pages` take `--site` to read one site. A `--site` the scan did not cover is an error that names the sites it did. Scans made before this have no `sites` and covered the main domain only.
- URL versions are not scored. A parameter address (a filter, view or cache setting) whose canonical names the same path is a copy of that page: the audit fetches it to learn that, then leaves it out of the score, the factor counts, `agent-readiness page-scores` and the fix lists. `inventorySummary.urlVersions` counts them, each one's `auditState` is `url-version` with `urlVersionOf` naming its page, and `agent-readiness pages --url-versions only` lists them. Once 3 addresses with the same parameter pattern (site section plus parameter names) prove to be copies, the crawl stops fetching that pattern, unless one of them turns out to be a page of its own; those copies have no rows, and `inventorySummary.urlVersionsNotFetched` counts them. The URL versions a scan found are `urlVersions + urlVersionsNotFetched`, which is the number the dashboard and `agent-readiness overview` show. A parameter page with no such canonical (`?page=2`, `?id=123`) is scored like any page. Scans made before this rule scored every address.
- `issues` and `issue-pages` read stored evidence only. JSONL begins with provenance, coverage, total and continuation metadata, including for an empty result. An unavailable cross-page source in an older scan is not a measured zero, and a partial scan cannot establish site-wide absence. Follow the cursor before claiming a complete list. Issue dispositions guide review; advisory metadata findings do not automatically justify an edit or a blog post.
- Reads without `--run-id` use the newest scan that published a crawl, including one that stopped at its page budget (`complete: false`, `termination: max-pages`). A failed, cancelled, or still-running scan never replaces it. `changes` compares complete crawls only.
- Graph reads are server-paged and bounded. Use `--run-id` to inspect a specific retained run.
- A subgraph with `countAccuracy: "lower-bound"` hit a traversal cap: totals and omissions are minimums, not site-wide counts. Its `complete` and `termination` fields apply to every observation.
- Treat an `unreachable` or `truncated` path from `complete: false` as limited to persisted crawl observations; use `termination` to explain that qualification.
- `changes` returns its resolved filters and an exact post-filter summary only on its first page. JSONL headers retain `filters`, `summaryState`, nullable `summary`/`total`, and `nextCursor`; continuation records remain safe to stream without recomputing totals.

## Intelligence

```bash
cnry insights <project>                        # list active insights (regressions, gains, opportunities)
cnry insights <project> --type gbp-*           # filter by insight type; trailing * = prefix (e.g. only GBP insights)
cnry insights <project> --type gbp-description-missing   # exact type match
cnry insights <project> --severity high        # minimum severity (high returns high + critical)
cnry insights <project> --limit 10             # first N: newest analysis, needs-action before wins, most severe first
cnry insights <project> --dismissed            # include dismissed insights
cnry insights <project> --format json          # JSON output
cnry insights dismiss <project> <id>           # dismiss an insight
cnry health <project>                          # latest citation health snapshot (citation-only — see known gap below)
cnry health <project> --history                # health trend over time
cnry health <project> --history --limit 10     # limit history entries
cnry health <project> --format json            # JSON output
cnry backfill insights <project>              # backfill insights for all completed runs
cnry backfill insights <project> --from-run <id> --to-run <id>  # backfill a range
```

`cnry health` reports mention and citation rates with separate denominators. Use `cnry overview` for coverage by query class and scoped mention share.

### Content-target dismissals

```bash
cnry content targets <project> --format json
cnry content dismissals <project> --format json
cnry content dismiss <project> <targetRef> --addressed-url https://example.com/page --note "Addressed" --format json
cnry content restore <project> <targetRef> --format json
```

Use a `targetRef` from the content-target response. Dismissal records remain
project-scoped and hide that recommendation on later content reads. Listing
uses `GET /projects/:name/content/dismissals`; dismiss uses `POST` with
`targetRef` and optional `addressedUrl` and `note`. Re-dismissing updates those
optional values and the dismissal time. Restore uses
`DELETE /projects/:name/content/dismissals/:targetRef` and returns HTTP 204; CLI and
MCP acknowledge it as `{ targetRef, restored: true }`. A missing record returns
the API's not-found error.

All three commands support `json` and `jsonl`. The list JSON envelope is
`{ dismissals: [...] }`; JSONL streams its records. Dismiss and restore return
one document. MCP equivalents are `canonry_content_dismissals` (read),
`canonry_content_dismiss` (write), and `canonry_content_restore` (write), in the
`monitoring` toolkit. Dismiss and restore require write authority and explicit
approval; reading a recommendation does not authorize either action.

## Queries & Competitors

```bash
cnry query add <project> "phrase one" "phrase two"       # prints each query's class; JSON adds `queryClasses`
cnry query replace <project> "phrase one" "phrase two"   # set the basket to exactly this list
cnry query replace <project> "..." --dry-run             # preview adds/removes via /queries/replace-preview
cnry query remove <project> "phrase"
cnry query list <project>                                # CLASS column; JSON and JSONL rows carry `queryClass`
cnry query import <project> queries.txt
cnry query generate <project> --provider gemini --count 10 --save

cnry competitor add <project> competitor1.com competitor2.com
cnry competitor add <project> rival.example --dry-run --format json  # preview latest stored-evidence impact without writing
cnry competitor add <project> spoketuneworks.example --alias TuneSpoke   # one domain; repeat --alias for more names
cnry competitor add <project> competitor1.com competitor2.com --acknowledge-bulk-add  # operator acknowledgement for measured growth over 5 domains in 24 hours
cnry competitor list <project>                       # text shows each competitor's aliases and auto names; JSON rows carry `aliases`, `autoAliases`, `blockedAliases`
cnry competitor aliases <project> qvx.example                      # read one competitor's curated, auto-detected (with evidence) and blocked names
cnry competitor aliases <project> qvx.example --set QVX            # exact list (repeat --set); --clear empties it
cnry competitor aliases <project> qvx.example --set QVX --dry-run --format json  # preview an alias identity change
cnry competitor aliases <project> qvx.example --add "QVX Stores"   # appends server-side in one call
cnry competitor aliases <project> qvx.example --remove qvx         # read, edit, write back (a concurrent edit can be overwritten)
cnry competitor aliases <project> spoketuneworks.example --block "Spoke Crew"   # never auto-apply this name (removes it if auto)
cnry competitor aliases <project> spoketuneworks.example --unblock "Spoke Crew" # release it to detection again
cnry competitor aliases detect <project> --format json             # dry run: names the stored answers tie to each site, with evidence and impact
cnry competitor aliases detect <project> --apply                   # run detection now and store it, in any mode (after each sweep the project's mode decides)
cnry competitor landscape <project> --query-class non-brand --window 30d --format json
cnry competitor suggest <project> --window 30d --min-answers 3 --query-class non-brand --format json
```

`competitor suggest` reads stored answer and citation evidence and ranks possible competitors. It never starts a sweep or writes data. Use `--format jsonl` for one candidate per line. The response keeps naming counts separate from citation counts and includes the query class, answer floor, run IDs, sample URLs, exclusions, and count units. An exact suggestion read refuses with `VALIDATION_ERROR` above 10,000 eligible answer rows instead of sampling; narrow `--window` or use `--group-key` for one Advanced market. A Simple project without a usable brand alias uses the pooled `all` class unless an explicit class filter is requested. Exact reads also refuse more than 200,000 characters in one answer, 20 million evidence characters, or 200,000 source references with narrowing guidance. Scans yield so other requests remain responsive. Unknown untracked candidates with only unpaired prose matches are excluded as `unpaired-name`; mention counts stay unchanged for comparison with a bare-add preview. Human output shows both-answer and paired-answer counts and exclusion reasons.

### Tracking assignments

```bash
cnry query workspace <project> --format json            # read current assignments and workspace version
cnry query preview <project> changes.json --format json # preview assignment changes
cnry query commit <project> reviewed.json --format json # publish the reviewed changes
```

The assignment preview takes `expectedWorkspaceVersion`, `additions`, `removals`, and optional `edits`. Commit the same request with the returned `previewToken` and `reviewedAt`. Preview and commit require write access.

### Query class

Every tracked query is `branded` (it names the project) or `non-brand`, and the two are never counted together. The server decides the class; read it, never work it out from the query text.

- `cnry query list <project>` prints a `CLASS` column. `--format json` and `--format jsonl` rows carry `queryClass`: `"branded"`, `"non-brand"` or `null`.
- `cnry query add <project> ...` prints one line per query with its class after the count line. `--format json` adds `queryClasses: [{ query, queryClass }]`, one entry per distinct query in the order given. A query that was already tracked is listed with its class too.
- A project without an advanced measurement plan is classed from the query text against the project's brand names: display name, aliases and owned-domain labels. A legacy schema v1 plan stores no class, so its queries are classed the same way.
- A project with an active advanced measurement plan uses the class stored on the query's assignments in that plan, which an operator may have set by hand, so it can differ from what the text suggests.
- A dash in text output, `null` in JSON, means there is no single class: the project has no usable brand name, or the plan holds no single class for the query (it has no assignment, or it is assigned under both classes). A dash is never a `non-brand`. `cnry query workspace <project> --format json` lists the class of each assignment, one per Property.
- Against a server older than this field the JSON rows and `queryClasses` entries have no `queryClass` key, and text output shows a dash with the note "class not reported". That means unknown, not `null`.

MCP: `canonry_queries_list` rows carry the same `queryClass`, and `canonry_queries_add` returns `queryClasses`.

### Competitor aliases

A competitor is stored as its registrable domain, and every competitor mention matcher derives a name from the domain label (only when that label has 4 or more letters or digits). A competitor whose answers name it differently ("TuneSpoke" for `spoketuneworks.example`, "Ravenwood Cycling" for `ravenwoodbikeinc.example`) or whose brand is 3 letters (`QVX` for `qvx.example`) is never counted until you give it curated aliases. Without them, mention share overstates the project.

- Rules: trimmed, deduplicated case-insensitively (first spelling kept), at most 10 per competitor, 80 characters each, at least 3 letters or digits. Rejected with a 400 naming each alias and the name it overlaps: a brand key (letters and digits, case and punctuation folded) that contains, or sits inside, one of the project's own names or written hosts ("Acme", "Cycles", `acmecycles.example`, `shop.acmecycles.example` or "Acme Cycles Outlet" for the project "AcmeCycles" at `acmecycles.example`), or a name another tracked competitor answers to (its aliases, domain label or written host). Answers split and join the words of a name freely, so "Tune" cannot belong to one competitor while another answers to "Tune Spoke", "TuneSpoke" or `tunespoke.example`: an answer writing "Tune Spoke" would count both. Joined-word lookalikes ("Tune" and "Tuner") are refused too; pick a longer alias.
- A new competitor whose domain name overlaps another competitor's alias that way (adding `tunespoke.example` or `spoketuneworks.example` while another competitor carries "Tune", or `tune.example` while one carries "Tune Spoke") is rejected on `competitor add` and apply until you remove or restate that alias; discovery promote leaves it out with reason `claimed-by-alias`. No surface starts tracking the project's own site, a subdomain of it, or a parent of an owned domain. A project identity change that claims a competitor alias drops it, audited as `droppedCompetitorAliases`.
- On a measured project, a competitor add that would put more than 5 new or recently added domains inside the trailing 24 hours is refused with `bulk-add-unacknowledged`. Review stored evidence with `competitor suggest` or `competitor add --dry-run`, then pass `--acknowledge-bulk-add` for an operator-approved write. Projects without a completed or partial non-probe sweep are not guarded. The rule covers REST, CLI, MCP and dashboard writes; declarative apply and discovery promote remain outside this guard.
- Advanced markets: a competitor an active or draft market pins counts as another competitor, and so does one a superseded revision pins when the project's runs were measured under that revision (`supersededRevision`), since those runs are still scored with it. An alias overlapping its names is rejected (`market-competitor`, naming the `markets`), a stored one is dropped and audited, and a new competitor whose domain name a pin's label or curated alias claims is rejected (`claimed-by-alias`, naming the `markets`) until you remove that name from the pin. The other way round, pinning a competitor (or giving a pin a new name) fails with `claimed-by-alias` when a curated alias already answers to it, and with `other-competitor` when its label or alias overlaps a tracked competitor's own domain label or host; `pin-competitor`, `upsert-competitor`, `upsert-group` and draft publish all check the pins they add or rename.
- Not checked: two names that only share a part ("Tune Spoke" and "Spoke Works" both match the phrase "Tune Spoke Works"), and an alias equal to a subdomain label of another competitor's host. Avoid such pairs by hand.
- Any spelling of a tracked domain (`www.`, a subdomain, or a row an older build's discovery promote stored as a subdomain) finds its stored row; discovery promote now stores the registrable domain. A competitor stored as two rows refuses alias edits; the error names both rows and the aliases to restate: `competitor remove` (which removes every row of it), then `competitor add <project> <domain> --alias ...`.
- Matching is exact brand identity over answer prose (complete words, case and punctuation variants), never fuzzy. Aliases add to mention matching only; citations stay domain-based.
- Read time: mention share (overview card, trend buckets, `visibility-stats --share-of-voice`, `visibility-compare`), the competitor landscape, mention gaps, and run/history competitor signals reinterpret stored answers as soon as aliases change. The stored `competitorOverlap` / `recommendedCompetitors` columns are recomputed in the background; the project's own `answerMentioned` is never touched by an alias edit.
- Frozen: a Simple run freezes the competitor identity it dispatched with (domain label plus aliases), so the AI Visibility report keeps each run's own identity; only runs dispatched after the edit use new aliases. A names change does not break the comparison with the previous sweep: the definition identity behind it covers the project's own coverage and leaves competitor names out. Advanced plan revisions keep their own frozen competitor names (`measurement-plan advanced ... draft-action` with `upsert-competitor`); pinning a tracked competitor into a market by domain alone copies its curated aliases into the draft.
- REST: `PUT /api/v1/projects/{name}/competitors/{domain}/aliases` with `{ "aliases": [...] }` (exact set, idempotent, audited as `competitors.aliases-updated`); `POST /competitors` accepts `{ domain, aliases }` entries (aliases are added). `PUT /competitors` (domain replace) keeps the aliases of domains that stay. Deletes record the discarded aliases on the audit row. MCP: `canonry_competitors_aliases_set` and `canonry_competitors_add` with `{ domain, aliases }` entries (setup toolkit).
- Config-as-code: a `spec.competitors` entry is a domain string or `{ domain, aliases }`. A string keeps that competitor's stored aliases (no opinion); an object sets them exactly, and `aliases: []` clears them. `cnry export` writes aliased competitors as objects, so export then apply round-trips. Auto-detected and blocked names are not part of a config spec: apply keeps them for competitors that stay.

### Answer-derived auto aliases

Canonry also learns competitor names from the project's own stored answers, never from a competitor's website and never with a live call. The local server queues a pass after every completed or partial sweep (probes excluded), when a competitor is added (REST, apply or discovery promote), when a name is unblocked, and when a market pin write changes the pins; a curated alias edit, a competitor removal, a block and a project edit queue none. What the pass does follows the project's `competitorAutoAliases` mode (`cnry project update <project> --competitor-auto-aliases <mode>`, `spec.competitorAutoAliases` in apply, shown by `project show`):

- `preview` (every project's default, existing ones included): the pass scores the answers and logs what it would add or remove, and stores nothing. `detect` (dry run) shows the same evidence.
- `apply`: the pass stores the names that qualify.
- `off`: no pass runs.
- `cnry competitor aliases detect <project> --apply` stores one pass's result in every mode (a one-off apply). Switching to `apply` takes effect at the next queued pass (the next sweep, competitor add, unblock or pin change); `detect --apply` stores now. Switching to `preview` or `off` never deletes names already stored; block them to remove them.
- Restatement: the read-time competitor matchers use the names the project has now, so a names change restates every period they read, months already reported included. Frozen names are not restated: a Simple definition keeps the names it froze at dispatch, and Advanced measurement reports read each revision's own names. The competitor landscape, project-frame `visibility-compare` and analytics metrics responses carry `competitorIdentityChangedAt` (null if never): the newest change to a tracked competitor's curated or stored auto names (a block counts only when it removes a stored name), a detection pass that stores or removes a market-only competitor's learned names, a write that claims, releases or drops a market-only competitor's learned names (project edit, apply, competitor add, alias edit, block, unblock or removal, discovery promote, market pin write), or a published revision that renames a market pin. The landscape reads all of these names; `visibility-compare` share of voice and analytics mention share read only tracked competitors' names, so a pin or learned-name change moves the time without changing them. A scoped `visibility-compare` (a group, market or property scope, or a `marketKey`) reads frozen plan history and has no such field. A figure quoted before that time may differ from the same period read now.

- Evidence: a direct pair is an answer tying a name to the competitor's site: a provider citation anchoring the text that names it to a page on the domain (OpenAI annotations, Claude citations, Gemini grounding supports, Perplexity `[N]` markers), a named link `[TuneSpoke](https://spoketuneworks.example/...)`, or `TuneSpoke (spoketuneworks.example)` / `TuneSpoke - spoketuneworks.example`. A co-occurrence (the answer cites the site and lists the name elsewhere) is reported but never enough on its own. An answer names a candidate only where it writes it outside the competitor's longer names (its domain label, a curated alias, a longer stored name, and for a market-only competitor its plan label and aliases): an answer that writes only "Lark Bay Suites" does not name "Lark Bay". Of the scanned answers that name it: precision is the share citing the competitor's site; lift is how many times more often they cite it than the answers that do not name it (smoothed); name casing is how many write it capitalized as a name. Lift and casing are what reject generic phrases: a much-cited competitor gives any phrase near it a high precision, but naming a phrase barely moves its citation rate, and answers write a phrase in lowercase.
- Applied when: direct pairs in at least 2 answers from at least 2 sweeps (runs started together, one multi-location sweep, count once); at least 3 answers name it; precision at least 10%; lift at least 3; written as a name in at least 75% of them; it reads as a business name (at most 6 capitalized words, no `% + ? : / |`, no host, not a heading such as "Why ..." or "Top ...", a leading number only before a capitalized singular word such as "1 Spoke Lane", and not written as a place: "Larkfield, CO", "Larkfield, Colorado", "Oakvale County", "Metro Larkfield", "Downtown Larkfield", "West LA"); a brand key of at least 4 letters or digits; this competitor has at least twice the pairs of any other tracked competitor; and it visibly belongs to the domain. That tie holds when consecutive whole words of the name spell the domain label ("Spoke Garage Bikes" for `spokegarage.example`); when a name of two or more words opens the label whole, at its start or right after a lead word (my, the, get, try, go, use, hey, join, shop, visit), and covers at least half of it ("SpokeIQ" for `myspokeiq.example`); when two or more of its words sit back to back in the label from that opening and cover at least half of it, one of them 4 or more letters long and inside fewer than two tracked identity labels (the project's and every competitor's), so a shared industry word such as "roofing" proves nothing ("TuneSpoke" for `spoketuneworks.example`); or when a name of two or more words is an in-order abbreviation of the label that opens like it, with the same first 4 letters or a first word of 3 or more letters the label starts with ("FoamSeal" for `foamandsealworks.example`). One shared word never ties a name to the domain unless it is the whole label: a city the label opens or ends with ("Larkfield" for `larkfieldroofing.example`), a neighbour sharing the label's first word ("Rim Doctor" for `doctorspokes.example`) and a one-word brand shorter than its label ("Acme" for `acmecycles.example`) all go to review.
- Review: a candidate that passes everything except that tie (`no-label-affinity`) or the 4-character floor (`needs-approval`) is listed as `review` only, after checks at the 3-character floor against the project's names and hosts, other competitors' domain labels, hosts and curated aliases, market pins of another domain, blocks, and the competitor's own names and planned auto names. Unlike applied names, review names are not checked against other competitors' auto-detected names, so a name another competitor stores can still be listed. Such lists still mix the competitor's real names with its partners, rivals and services, and a one-word city or a longer region name has no place shape and can appear, so check that the name refers to that competitor in the answers, then add it with `--add` (never `--set`, which replaces the curated list).
- Never applied: a blocked name; a name the competitor's own identity already matches as complete words (`already-matched`: its domain label, a curated alias, a kept auto name, or a name of its own active or draft Advanced pin, so "Velo Hub Springfield" is not learned under the pin "Velo Hub"; a superseded revision's pin does not count); a name overlapping the project, another competitor's curated identity, or the names of an Advanced market pin of another domain (active, draft, or a superseded revision the project's runs were measured under) (curated always wins); a longer variant of an applied name (`subsumed`: blocking the short name frees the longer ones). At most 10 auto names per competitor: stored names first, then new names strongest evidence first (`over-limit` for the rest).
- Stored names are sticky: one is removed only when blocked; claimed by identity (the competitor's own curated aliases or domain label already cover it, `already-matched`; it overlaps the project's names or hosts, `project-brand`; or it overlaps another competitor's domain label, host or curated alias, a market pin of another domain, or, after an identity change, another competitor's stored auto name that resolves first (tracked competitors before market-only ones, each in domain order), `other-competitor`); replaced by an accepted shorter name it is built on (`subsumed`); or contradicted by the scanned answers: named in 3+ with precision under 5%, lift under 1.5, or written as a name in under half; another tracked competitor now pairing it in at least 2 answers and at least twice as often as this one (`other-competitor-dominates`); or no tie to the domain label left, judged on the stored spelling (`no-label-affinity`). A tracked competitor's own pin never removes a stored name; a market-only competitor's active pin names are its curated names and do (`already-matched`).
- Blocking: `--block` removes a stored auto name and keeps it out of detection. The block outlives the row: `competitor remove` keeps it, and the next `competitor add` of that domain (or an apply that re-adds it, or a market-only pin promoted to a competitor) starts with it. A curated alias cannot be blocked (remove it with `--remove`), and neither can a name the measurement plan's own pin of that competitor carries (active revision or pending draft): the pin keeps counting it, so change the pin's names in a measurement draft.
- Scan: the newest 60 completed or partial answer-visibility runs (probes excluded) and at most 6000 snapshots, stopping inside a run when the cap falls there. One pass per project at a time: an apply-now waits for a running storing pass and runs after it. A names change is audited (`competitors.auto-aliases-updated`, actor `system`; an apply-now that changed names also writes `competitors.auto-aliases-apply-requested` with who asked) and recomputes the stored competitor columns in the background. Matchers and frozen Simple definitions (for runs dispatched afterward) use curated + auto minus blocked. An Advanced pin by domain alone copies only the curated aliases; auto and learned names are layered onto it when answers are read, never frozen into a revision, so a later block can still take them back.
- Advanced: a competitor the active plan pins in a market without tracking it project-wide is detected from that market's answers only, its plan label and aliases count as its curated names, and its learned names apply only where a run's plan revision pins it (never as a project competitor). `detect` lists it with `(Advanced markets: ...)` and `marketKeys` in JSON; `--block` / `--unblock` work on it by domain, and on a domain a later revision stopped pinning while its learned or blocked names are still stored. `competitor aliases <project> <domain>` without a flag reads project competitors only; for a market-only competitor use `detect`.
- Aero can run the dry run (`canonry_competitors_auto_aliases_detect`) but never applies: `canonry_competitors_auto_aliases_apply` is not in its catalog, and it cannot change a project's `competitorAutoAliases` mode. Applying and switching a project to `apply` stay operator actions.
- REST: `GET` / `POST /api/v1/projects/{name}/competitor-auto-aliases` (dry run / apply), `POST /api/v1/projects/{name}/competitors/{domain}/aliases/block` and `/unblock` with `{ "aliases": [...] }`. MCP: `canonry_competitors_auto_aliases_detect` (read), `canonry_competitors_auto_aliases_apply`, `canonry_competitors_aliases_block`, `canonry_competitors_aliases_unblock` (setup toolkit). `detect` is a reserved word after `competitor aliases`.

```yaml
spec:
  competitors:
    - ravenwood.example
    - domain: spoketuneworks.example
      aliases: [TuneSpoke]
```

Historical competitor landscapes require explicit `--query-class non-brand`
for competitive percentages (REST `queryClass=non-brand`, MCP
`queryClass: "non-brand"`). Omitted class or `all` returns pooled counts and
null shares. Request branded evidence separately for brand recall.

## Research

```bash
cnry research run <project> "Which suppliers serve this market?" --provider gemini --idempotency-key <key> --wait --format json
cnry research batch <project> reviewed-runs.json --wait --format json
cnry research list <project> --limit 20 --format json
cnry research show <project> <run-id> --format json
```

Research saves answers separately from tracked measurement. `research run` accepts up to 50 queries. Use `--market` or `--property` for one Advanced destination. Select an engine location separately with `--location` or `--no-location`. `--model` requires `--provider`.

For a reviewed batch, provide one `idempotencyKey` and a `runs` array. Each run needs final `queries`, `provider`, `model`, and `location` (an object or `null`). For an Advanced destination, include `expectedPlanRevision` in `scope`. A batch can submit up to 20 destinations and 50 total queries. Use the same key and payload on retry. Pass the returned `nextCursor` to `research list --cursor` to read older runs.

## Target Measurement Plans

```bash
cnry measurement-plan discover <project> --sitemap-url https://example.com/sitemap.xml --rule discovery-rule.yaml
cnry measurement-plan discover <project> --sitemap-url https://example.com/sitemap.xml --rule discovery-rule.json --max-urls 500
cnry measurement-plan show <project>                    # active immutable revision
cnry measurement-plan show <project> --revision 2       # one historical revision
cnry measurement-plan versions <project>
cnry measurement-plan visibility <project> --format json # stored AI Visibility for Simple or Advanced
cnry measurement-plan visibility <project> selection.json --format json # filter the report
cnry measurement-plan publish <project> plan.yaml       # legacy schema v1 only; refuses over an active v2 plan (use: measurement-plan advanced <project> draft-action)
cnry measurement-plan report <project> --revision 2     # stored evidence only; never starts provider work; a schema v2 revision reads non-brand unless --query-class branded|all; a schema v1 revision reads every answer and refuses --query-class non-brand or branded
cnry measurement-plan retire <project> <stable-key>
```

`discover` fetches a public sitemap and applies an operator-supplied deterministic
route rule to project-owned URLs. It returns explicit proposed, alias, shared, unmatched, and excluded
buckets; it does not infer queries or publish a plan. A rule file uses this
shape:

```yaml
primary:
  host: example.com
  pathTemplate: /locations/{slug}
aliases:
  - host: directory.example
    pathTemplate: /{slug}
excludedSlugSuffixes:
  - blog
```

Review discovery output, author the plan, and publish it as a separate action.
`report` is pinned to one immutable revision and reads stored run evidence. It
does not execute providers.

## Scheduling & Notifications

```bash
cnry schedule set <project> --preset daily     # or: weekly, twice-daily, daily@09
cnry schedule set <project> --cron "0 9 * * *" --timezone America/New_York
cnry schedule set <project> --kind data-refresh --preset daily   # refresh all connected GSC/Bing (coverage + full data sync)/GA/GBP integrations (no --source)
cnry schedule set <project> --kind backlinks-sync --preset weekly # re-probe Common Crawl; sync only when a newer rolling window is published (no --source/--provider)
cnry doctor --project <project> --check site.reachability   # probe the homepage now; the server also probes every 10 min and pages health.degraded after two failed passes
cnry schedule set <project> --kind site-audit --preset weekly     # Agent Readiness audit scan: bounded full-site crawl and audit (no --source/--provider)
cnry schedule set <project> --kind site-audit --check-dead-links --include-geo   # weekly deep scan: dead links + location checks on every scheduled scan
cnry schedule set <project> --kind seo-sync --cron '0 7 2 * *'  # paid SEO refresh of every saved profile, monthly (needs seo.run; no --source/--provider)
cnry schedule preview <project> --preset weekly --format json  # preview the next occurrence without enabling a schedule
cnry schedule show <project>
cnry schedule list <project> --format json      # all configured schedule kinds
cnry schedule enable <project>
cnry schedule disable <project>
cnry schedule remove <project>

cnry notify add <project> --webhook <url> --events mention.lost,mention.gained,citation.lost,citation.gained
cnry notify events                             # list all available event types
cnry notify list <project>
cnry notify remove <project> <id>
cnry notify test <project> <id>
```

Use `cnry notify events --target server` for the connected server's current event catalog.

`mention.lost` / `mention.gained` fire when the project's brand or domain leaves or enters an answer's text since the previous sweep; `citation.lost` / `citation.gained` fire when its domain leaves or enters the answer's source links. The two move independently, so subscribe to both to see every AI visibility change. Each transition names the query, engine, location and `queryClass` (`branded`, `non-brand`, or null); mention transitions read `mentioned` / `not-mentioned`, citation transitions `cited` / `not-cited`. An answer whose mention was never checked, or whose citation was not measured (an engine with no sources), sends neither. On an Advanced project each transition is one Property's answer and adds `property` and `markets`, compared with the comparable previous sweep exactly as `cnry overview`'s What changed compares it: a sweep with different engines, models or plan definition, a partial one, or a spot check sends no transitions. `run.completed` keeps carrying the citation transitions only.

`sentiment.unfavorable` fires when sentiment rates an answer unfavorable where the previous rated sweep's matching answer (same query, engine, location and subject) had a known verdict that was not: `favorable`, `mixed`, `factual`, `subject-not-mentioned` or `wrong-subject`. It is sent once per sweep, in sweep order, after that sweep's automatic sentiment work settles (verdicts arrive minutes after `run.completed`; a sweep also waits for earlier sweeps to settle, and for sentiment to be on), listing each answer's query, `queryClass`, engine, location, `previousOutcome` and the evaluator's quoted `conclusion` and `complaint`, plus `property` and `markets` on an Advanced project. An answer that stays unfavorable is reported once; backfills, probes, answers whose engine or evaluator model changed, and a class judged by another evaluator definition send nothing. Non-brand verdicts are exceptions to read, not a share. Follow up with `cnry sentiment evidence <project> --run-id <id> --query-class <class> --outcome unfavorable`.

`insight.critical` and `insight.high` fire when the intelligence engine generates critical- or high-severity insights after a sweep completes.

**Health alerts** (`health.degraded`, `health.recovered`) report on the measurement itself, not on findings, and reach every enabled webhook whether or not it subscribes to them. A doctor pass runs every 6 hours per project. `health.degraded` is sent only when something is new or worse: the project stops being healthy, the worst status rises, or a check starts failing, gets more severe, or reports a different code at the same severity. A pass that finds the same problems, or fewer, sends nothing, so a check clearing, or easing from fail to warn, never produces a second "degraded" alert. An alert that no webhook accepted is sent again on the next pass. `health.recovered` is sent when every check passes again. The payload's `health.failing` lists every failing check; `health.added` lists the codes that are new or worse and `health.cleared` the codes of the checks that stopped failing since the last delivered alert. Each `failing` entry carries its own `remediation` and, when the check wrote plain wording, `alert` (`label`, `line`, `next`). Discord and Slack cards lead with the first new or worse problem: a short label in the title, one line on what happened, and a `Next` step when there is one. Other open problems follow under `Also open` as labels, new ones first and marked "(new)", three at most with the rest counted, and what cleared follows under `Fixed`. Check ids and codes stay in the payload and behind the dashboard link. Silent advisories (`report.*`, `content.winnability.coverage`, `traffic.source.cache-blindspot`) appear in `cnry doctor` with `notificationPolicy: "silent"` but never page. An optional integration the project does not use is `skipped`, not failed (`gbp.auth.not-connected`, `bing.auth.not-connected`), so it does not page either. Run `cnry doctor --project <project>` to see the current state at any time.

**Urgent health alerts** (`health.urgent`, `health.urgent-resolved`) carry only the problems a person has to act on now, for a channel people watch. A check marks its own result `urgent` (it shows as `urgent: true` in `cnry doctor --format json`):

- the website is down (`site.reachability.down`, `site.reachability.refused-address`);
- GA4 or Search Console data is stale: syncs run and have brought nothing new for 5 days (GA4) or 7 (Search Console) (`ga.data.stale`, `gsc.data.stale`), or the data is that old and nothing has synced for 8 days or more (`ga.data.not-syncing`, `gsc.data.not-syncing`). A project that syncs weekly or by hand is not urgent in between;
- a sync keeps failing (`<integration>.sync.repeated-failures`), including when the cause is a failed authorization: the alert then quotes the authorization check's explanation.

`health.urgent` is sent when an urgent problem starts. A problem already reported is not repeated, and an alert no webhook accepted is sent again on the next pass. `health.urgent-resolved` is sent when the reported problems have cleared; a check that was skipped or errored does not count as cleared. The scheduled health pass (every 6 hours) and the website check (every 10 minutes) report separately, so a data problem and an outage each get their own resolved message.

A webhook that lists either event receives **only the health events it lists**, so it is not sent routine warnings; every other webhook keeps receiving `health.degraded` and `health.recovered` as before. An urgent problem is always part of `health.degraded` too, so on the scheduled pass a webhook that lists both gets a message under each name (a website outage is sent once, as `health.degraded`). Example: `cnry notify add <project> --webhook <url> --events health.urgent,health.urgent-resolved`.

**Site Health alerts** (`site-health.issue.new`) go only to webhooks that list the event. After each site audit, Canonry sends it when the scan found a critical page problem (no H1, several H1s, no title, or a page that names another property) on pages where that problem was not reported before. The payload lists each problem with `affectedPages`, `newPages` and up to five new example URLs, plus `scanComplete`. A problem that stays unfixed is reported once. An alert no webhook accepted is sent again after the next audit. A complete scan that no longer finds a problem clears it, so it is reported again if it comes back; a partial scan never clears anything. Nothing is recorded while no webhook lists the event, so a new subscriber hears about every current problem after the next audit.

For mention-first monitoring, use `cnry overview` to read `mentionCoverage.populations`, `scores.mentionShare`, and `whatChanged.lostMentions`. The citation webhooks report citation changes. See `cnry notify events --target server` for available events.

**What changed.** `cnry overview <project>` prints the dashboard's "What changed" rows: the queries that lost a mention and those that lost a citation in the latest check (each query once, the two signals counted apart, with the engines, locations, and for Advanced the Properties and markets that lost it) and the runs in progress. `cnry overview --all` prints the portfolio's rows under its table. JSON carries them as `whatChanged`: `lostMentions` / `lostCitations` (`queryCount`, at most 25 `queries`, `truncated`), `activeRuns`, the rows as `items`, and `comparison`. Simple compares each engine's answer with its previous check of the same query and location; Advanced compares each Property's answer with the comparable previous sweep.

`comparison` is `{ "state": "available", "previousRunIds" }` when the latest check was compared. Otherwise it is `{ "state": "unavailable", "reason" }`, and the lost counts are 0 because nothing was compared, not because nothing was lost:

- `not-measured`: the project has no completed check yet. It says nothing about any answer's citation.
- `no-previous-check`: the latest check is the first, so there is nothing earlier to compare it with.
- Advanced only: `definition-changed` (the previous sweep measured another plan definition), `model-changed` (it asked other engines or models), `partial-run` (the latest or previous sweep is partial), `legacy-plan` (a schema v1 plan freezes no Property definition; republish setup) and `unreadable` (the previous sweep can't be read).

A project whose overview `cnry overview --all` can't read keeps its table row, marked "Couldn't be loaded" with the reason, and What changed names it instead of counting it as clear, as the dashboard does. In JSON it is `{ "project", "error": { "code", "message" } }` in its place. Once everything is printed the command exits with `OVERVIEW_INCOMPLETE` (`details.projects` names them): `2` when a retry may help (a server or network failure), otherwise `1`. Exit `0` means every element is a full overview.

## Provider Settings & Quotas

```bash
cnry settings                                  # show connected server's provider and Google OAuth settings
cnry settings --format json
cnry settings reload-providers --format json   # apply the server's saved provider config
cnry settings provider gemini --api-key <KEY> --model gemini-flash-latest
cnry settings provider openai --max-per-day 1000 --max-per-minute 20
cnry settings provider-info openai --format json   # saved config, defaults and project impact
cnry settings provider test openai --format json   # check the saved key with the provider now
cnry settings provider openai --reset-model --reset-limits
cnry settings provider local --remove-key         # remove an optional Local key
cnry settings disconnect-provider openai          # inspect impact; makes no changes
cnry settings disconnect-provider openai --confirm --if-impact-revision <REVISION>
cnry settings provider perplexity --api-key <KEY> --model fast
cnry settings provider muse --api-key <KEY> --model muse-spark-1.3
cnry settings provider openrouter --api-key <KEY>
```

Perplexity runs on its Agent API. `--model` takes a preset (`fast` default, `low`, `medium`, `high`, `xhigh`) or a `vendor/model` slug such as `perplexity/sonar`. Retired Sonar names still work and run as their replacement (`sonar` → `fast`, `sonar-pro` → `low`).

Quota flags: `--max-concurrent`, `--max-per-minute`, `--max-per-day`.
Use `--reset-limits` to inherit all connection limits, or repeat
`--reset-quota maxConcurrency|maxRequestsPerMinute|maxRequestsPerDay` for individual
fields. `--reset-model` removes the connection override. `--reset-base-url` restores a built-in endpoint (Local requires an explicit endpoint). Project overrides remain
independent. `--if-revision <revision>` from `provider-info` rejects stale updates.

`provider-info` is a stored read: it exposes no credentials and makes no vendor
calls. It returns editable capabilities, effective/default/overridden limits,
host-managed Vertex/batch/pricing settings, active-work blockers, and projects
that reference the connection through defaults, schedules or Advanced plans/drafts.
Disconnect previews use the same response. Without `--confirm` no state changes;
with it, the connection is removed from the connected server's saved config and
runtime. Project selections and result history remain available, and the key is
not revoked at its vendor. Reconnect before running those engine selections again.
Pass the preview's `impactRevision` with `--if-impact-revision` to reject changed
project impact. Resets and disconnect require install administrator authority and
`settings.write`; host-managed credentials must be changed on the host.

`provider test <name>` checks a saved connection with the provider now, using
the server's active settings, and changes no settings. Most answer engines answer one
tiny prompt on the provider account; Local lists its models; OpenRouter reads its
key; a search answer service with no free key check makes no request. `status` is
`connected`, `failed` (with the provider's redacted reason; no answer within 30
seconds also fails) or `not-verified` (saved, but the first real request is the
first proof). Exit 0 for `connected` and `not-verified`, 2 for `failed` after the
result is printed, 1 for an unknown or unconfigured provider, or one whose
previous test is still running. It requires install administrator authority and
`settings.write` (a project-scoped or narrower key is refused) and refuses
read-only and `--stored-only` use. A passing test proves the key and endpoint,
not the account's quota. The server keeps the latest result as the connection's
`lastTest`, shown by `settings` and `provider-info` (JSON and text), until the
key, endpoint, model, Vertex project, region or credentials, or CDP endpoint
changes, or the connection is disconnected; request-limit, batch and pricing
edits keep it. Read it before testing again.

`reload-providers` rereads the connected server's config file: provider keys,
models, Vertex AI settings, batch settings, pricing, quotas, and CDP. Any config
the server starts with also reloads, with the same result: a partial `quota:`
block keeps its saved limits and takes the defaults for the rest. It returns
active provider summaries without credentials. It requires install administrator
authority and `settings.write`. Current requests keep their provider settings;
quota changes preserve active requests and the rolling request history. Ports,
database paths, authentication, and other server settings still need a restart.
Changing or removing a provider with an outstanding batch is refused until the
batch settles; quota-only updates remain available.

Available connections: `gemini`, `openai`, `claude`, `perplexity`, `muse`, `local`, `openrouter`, `cdp`.

OpenRouter uses one connection key and several selected models. Add each model
to the project with repeatable `--provider openrouter:publisher/model` flags;
include direct providers you want to retain because the flag replaces the list.
The bare `openrouter` connection is not a sweep engine. Direct and routed models
have separate results, including Simple and Advanced Measurement. Routed models
share their connection limits; adding a new model requires `settings.write`.
Aero can use `--provider openrouter --model publisher/model` independently of
the project's sweep models. Classifications identify their own evaluator route.

Search answer services (hosted services that search the web and answer) take
only an API key: `cnry settings provider <service> --api-key <KEY>`, or the
environment variable each service names at bootstrap. `cnry settings` lists
every registered service with its key variable, its profiles and the workflows
each profile allows. Name a profile route `<service>:<profile>` in `--provider`;
the bare connection is not an engine, and an empty provider list, schedules,
discovery and Aero never pick a service up. Only complete answers are
measured, and each answer stores its evidence (source relationships,
completion, frozen profile settings, cost basis), so read what a service
discloses from that evidence rather than assuming it. See
[search answer services](https://github.com/Canonry/canonry/blob/main/docs/providers/answer-services.md)
and the service's own page under `docs/providers/answer-services/`.

Set `MUSE_API_KEY` before `cnry bootstrap` or `cnry init` to store the key. Setup also accepts `MUSE_MODEL` and `MUSE_BASE_URL`. `cnry init --muse-key <KEY>` stores a key directly. Muse uses Meta's Standard `muse-spark-1.3` by default. Contributor model IDs require an explicit model override; Meta permits training on their prompts and completions. See [the Muse provider guide](https://github.com/Canonry/canonry/blob/main/docs/providers/muse.md).

If a provider hits rate limits (429 errors), the run completes as `partial`. Reduce concurrency or increase time between sweeps.

### Gemini Vertex AI

Gemini supports Vertex AI as an alternative to API key authentication. Use GCP Application Default Credentials (ADC) or a service account JSON key file:

```bash
# Via env vars (recommended for servers)
export GEMINI_VERTEX_PROJECT=my-gcp-project
export GEMINI_VERTEX_REGION=us-central1            # optional, defaults to us-central1
export GEMINI_VERTEX_CREDENTIALS=/path/to/sa.json  # optional, falls back to ADC

# Or in canonry.yaml config
# vertexProject, vertexRegion, vertexCredentials fields under provider config
```

When Vertex AI is configured, no `GEMINI_API_KEY` is required. The provider uses the `@google-cloud/vertexai` SDK with `googleAuthOptions` for credential handling.

## API Keys

Mint, list, and revoke the `cnry_…` bearer tokens stored in the `api_keys` table. Keys are stored as a sha256 hash, never in plaintext.

```bash
cnry key list                                  # table: NAME / PREFIX / SCOPES / REACH / CREATED / LAST USED / STATUS
cnry key list --format json|jsonl              # jsonl streams one key per line
cnry key create --name ci-bot                  # mint a full-access key (scopes default to *)
cnry key create --name reader --read-only      # read-only key: scopes=['read'], denied every write HTTP method
cnry key create --name reader --scope read     # narrower key; repeat --scope or comma-separate (--scope a,b)
cnry key create --name ci-bot --format json    # JSON output includes the plaintext key
cnry key revoke <id>                           # revoke (does not delete); effective on the next request
cnry key whoami [--format json]                # introspect the CURRENT key (name, scopes, readOnly, status)
```

- **`--read-only` keys can read everything but write nothing.** The server denies every mutating method (POST/PUT/PATCH/DELETE) for a read-only key (`403 FORBIDDEN`); GET/HEAD pass. `--read-only` is sugar for `--scope read` and cannot be combined with `--scope`. The key DTO carries a derived `readOnly: boolean`. Point `canonry-mcp` at a read-only key and it auto-restricts to read tools.

- **Create returns the plaintext key exactly once.** It is shown with a "Save this now — it will not be shown again." warning (and is included in the JSON under `key`). It cannot be recovered later, so persist it on receipt.
- **List never exposes the hash or plaintext** — only safe metadata (id, name, prefix, scopes, created / last-used / revoked timestamps).
- **Mutations are gated by the `keys.write` scope.** The default key from `cnry init` carries `*`, which satisfies it. A narrower key needs `keys.write` to mint or revoke.
- **Revoke is not delete.** It sets `revokedAt`; the auth layer rejects the key on the next request. Revoking an already-revoked key is a no-op. You cannot revoke the key you are currently authenticating with (use a different key).

## Google Search Console

```bash
cnry google connect <project>                          # initiate OAuth flow
cnry google disconnect <project>                       # disconnect GSC
cnry google status <project>                           # connection status
cnry google properties <project>                       # list available properties
cnry google set-property <project> <url>               # set GSC property URL
cnry google set-sitemap <project> <url>                # set sitemap URL
cnry google list-sitemaps <project>                    # list submitted sitemaps
cnry google submit-sitemap <project> <url...>           # submit up to 50 explicit sitemap URLs
cnry google submit-sitemap <project> --configured       # submit Canonry's saved default
cnry google submit-sitemap <project> --all              # prefer sitemap indexes (fallback: top-level files)
cnry google submit-sitemap <project> --all-files        # include top-level files and index children (batched by 50)
cnry google discover-sitemaps <project> --wait         # auto-discover and inspect

cnry google sync <project>                             # sync GSC data
cnry google sync <project> --days 30 --full --wait     # full sync with wait
# `--full` re-fetches 480 days (GSC's 16-month retention ceiling) and is also the
# BACKFILL path: it repopulates the accurate per-query totals (`dimensions:
# ['date','query']`, no `page` fan-out) and the property daily totals for the
# whole retained window, not just recent days. Run it once per project after
# upgrading to pick up accurate history; a normal sync only covers its own window.

cnry google coverage <project>                         # index coverage summary
cnry google refresh <project>                         # force-fetch fresh GSC coverage data
cnry google performance <project>                      # search performance data
cnry google performance <project> --days 30 --keyword "term" --page "/url"
cnry google performance <project> --start 2026-06-01 --end 2026-06-30
cnry google performance <project> --order-by impressions --limit 2000 --offset 2000
# Rows are ordered by clicks descending by default; --order-by date|impressions
# changes the ranking. --days and --start/--end are mutually exclusive.
# One page, not the whole set: the response reports the total number of matching
# rows, and the CLI prints how many of them you are looking at. Never sum these
# rows for a property total, use `cnry google performance-daily`.
cnry google performance-daily <project>                # per-day series + property-level window totals
cnry google top-pages <project>                        # pages ranked by clicks, aggregated in SQL
cnry google top-pages <project> --start 2026-06-01 --end 2026-06-30 --limit 20
cnry google query-totals <project> --start 2026-06-01 --end 2026-06-30
cnry google query-totals <project> --window 90d --limit 500 --offset 500
# One row per named query over the window: clicks, impressions, CTR, position
# weighted by impressions, and `days` (the dates the query appeared). Ordered
# clicks desc, impressions desc, query asc; page with --limit/--offset until
# `truncated` is false. `source` marks rows that use the legacy page table for
# some days (`page-summed` or `mixed`: impressions over-count). Google leaves
# rare queries out, so never sum these rows for a property total, use
# `cnry google performance-daily`. Reads stored data only, never calls Google.
# `window.earliestDataDate` is the first stored per-query day: a window that
# starts before it is only partly covered (unsynced days, not zero traffic).

cnry google inspect <project> <url>                    # inspect specific URL
cnry google inspect-sitemap <project> --wait           # bulk inspect all sitemap URLs
cnry google inspections <project>                      # inspection history
cnry google inspections <project> --url <url>          # filter by URL
cnry google deindexed <project>                        # pages that lost indexing

cnry google request-indexing <project> <url>           # push URL to Google
cnry google request-indexing <project> --all-unindexed # push all unknown pages
```

**The dimensioned search-data table is valid for RANKING and invalid for TOTALS.** Read
any clicks/impressions total from the property-level daily figures (`performance-daily`
totals, or the `totals` block on `top-pages`), never by summing per-query or per-page rows.

Why: Google withholds rare/anonymised queries, so the dimensioned sum UNDER-counts clicks,
and one impression fans out across every query x page x country x device combination, so it
OVER-counts impressions. Measured on one real property-month: 792 summed clicks against
1,142 actual (31% under) and 45,266 summed impressions against 34,916 actual (30% over).
`top-pages` labels its total `totalsSource: "property-daily"` and returns `null` when no
property-level figure covers the window: a missing total, not a wrong one.

## Discovery (Tracked-Basket Expansion)

```bash
cnry discover run <project> --icp "..." --wait --format json    # full pipeline: seed → embed → cluster → probe → bucket
cnry discover run <project> --icp "..." --dedup-threshold 0.95  # tune cosine threshold (default 0.95)
cnry discover run <project> --icp "..." --max-probes 100         # per-session probe budget (default 100, hard cap 500)
cnry discover run <project> --icp "..." --probe-concurrency 3    # parallel probe workers (default 1 = serial, hard cap 8); probe rows stay in canonical order
cnry discover run <project> --icp-angle "angle 1" --icp-angle "angle 2" --wait  # multi-angle: one session per ICP angle, useful for hyperlocal/niche businesses
cnry discover run <project> --icp "..." --locations michigan,florida  # geo-constrain seed generation to a subset of project locations (omit = all project locations)

cnry discover list <project>                                     # newest-first session list
cnry discover show <project> <session-id>                        # per-query probe rows + buckets + classified competitor domains
cnry discover harvest <project> <session-id>                     # candidates from stored probes, with a possible live embedding call
cnry discover harvest <project> <session-id> --min-probe-hits 2 --no-anchor   # raise the recurrence floor / disable the subject anchor
cnry discover promote preview <project> <session-id>             # preview bucketed candidates + recurring suggested competitors of every classified type (read-only)
cnry discover promote <project> <session-id>                     # adopt cited + aspirational queries + direct-competitor domains
cnry discover promote <project> <session-id> --competitor-types direct-competitor,editorial-media   # widen the competitor merge to other classified types
cnry discover promote <project> <session-id> --bucket aspirational --no-competitors   # scope to a bucket subset / skip competitor merge
```

Discovery probes use Gemini. The embedding step requires a Gemini API key, including on a Vertex-only installation. Use `--seed-provider gemini`, `--seed-provider openai`, or repeat the flag to use both for seed generation.

The pipeline writes a `discovery_sessions` row, a `runs` row (kind `aeo-discover-probe`), and one `discovery.basket-divergence` insight when the session completes.

`discover harvest` ranks search queries from stored probe responses by how many probes issued each one. With Gemini embeddings, it can send candidate and tracked query text to Gemini to check for paraphrases. Obtain approval for that live provider read. The CLI needs a bearer key with `*` scope and access to the project. For stored-only work, use `discover show`. Read `semanticNoveltyApplied` to see whether the server used embeddings. When the embedding step cannot run, harvest checks for exact matches.

These are a third signal — *issued retrieval queries*, neither "mention" nor "cited" — and carry no demand of their own; they are candidate seeds, so review them and add the good ones with `cnry query add`. Use `--min-probe-hits` to require recurrence and `--no-anchor` to allow new-subject discovery on a well-scoped project.

Seed generation is location-aware: a project with locations configured (or a `--locations` label subset) geo-constrains the seed prompt so generated queries stay inside the service area, and a multi-location project gets a per-area seed quota so one area cannot dominate — `--locations` labels must match the project's configured locations or the run is rejected; projects with no locations are unaffected.

After probing, the configured classifier labels recurring cited domains. Gemini is the default. Failed or legacy classification leaves the type `unknown`. Aero wakes unprompted with the bucket-count payload so the operator can act without polling.

`discover eval` (quality-regression panel vs committed baseline, exit 1 on regression, --update-baseline to capture), `discover promote` defaults to cited + aspirational queries and `direct-competitor` domains only — aggregators and editorial media are suppressed; pass `--competitor-types` to widen the merge (or to recover legacy `unknown` entries) and `--bucket wasted-surface` for off-ICP competitor gaps. Promotion is add-only and idempotent — queries/domains already tracked are reported as skipped, never inserted twice — and only works on `completed` sessions; promoted rows carry `provenance="discovery:<sessionId>"`. Cited hosts are grouped into the registrable domain a competitor is stored as (`offers.rival.example` promotes as `rival.example`, shown with its source hosts) before the hit floor and the cap, counting each probe once. A competitor that is the project's own site, was cited as two or more different subdomains of one possibly shared host (`shared-host`), or whose name another competitor's alias claims (`claimed-by-alias`) is left out with a reason (`skippedCompetitors` in the preview, `competitorDetails` in the result) while the rest of the promote proceeds.

## Bing Webmaster Tools

```bash
cnry bing connect <project> --use-saved-key   # administrator, using the Bing key in Canonry Settings
cnry bing connect <project> --api-key <key>   # supply a Bing Webmaster Tools key for this project
cnry bing disconnect <project>                # disconnect
cnry bing status <project>                    # connection status
cnry bing sites <project>                     # list verified sites
cnry bing set-site <project> <url>            # set active site URL
cnry bing coverage <project>                  # URL coverage data
cnry bing refresh <project>                  # force-fetch fresh Bing coverage data
cnry bing inspect <project> <url>             # inspect specific URL
cnry bing inspect-sitemap <project>           # discover sitemap URLs and inspect each via Bing
cnry bing inspect-sitemap <project> --sitemap-url <url> --wait  # explicit sitemap, wait for run
cnry bing inspections <project>               # inspection history
cnry bing request-indexing <project> <url>    # submit URL for indexing
cnry bing request-indexing <project> --all-unindexed  # submit all unindexed (capped at the site's remaining Bing quota)
cnry bing performance <project>               # stored query rows, one per query per week (`date`); `bing queries` gives window totals

# Stored Bing data (written by `cnry bing sync`, which the daily data refresh runs)
cnry bing sync <project> [--wait]             # read every Bing data method and store it (about 20 to 50 Bing calls)
cnry bing traffic <project> [--window 30d] [--days 28]  # daily site clicks + impressions, window totals (the Bing site total), trend fits and a period comparison
cnry bing queries <project> [--window 30d] [--query text [--exact]] [--group-by week] [--limit n] [--offset n]  # per-query totals summed from Bing's weekly rows, plus all-matching totals vs the prior window
cnry bing pages <project> [--window 30d] [--page text [--exact]] [--group-by week]  # per-page totals summed from weekly rows
cnry bing crawl-stats <project> [--days 28]   # daily Bingbot crawl counts, HTTP codes, robots blocks, in-index pages
cnry bing sitemaps <project>                  # sitemaps Bing has, child sitemaps under their index
cnry bing site <project> [--kind <kind>]      # submission quotas left, crawl settings, crawl issues, blocked URLs, preview/sitelink blocks, URL parameters, geo-targeting, fetches, roles
cnry bing keyword-demand <project> [--query <tracked query>]  # weekly Bing search volume for tracked queries

# Live Bing reads (one call to Bing each; ask before running in an agent loop)
cnry bing query-pages <project> <query>       # which pages showed for a query, per week
cnry bing page-queries <project> <page-url>   # which queries a page showed for, per week
cnry bing query-history <project> <query> [--page <url>]  # one query per day, or per week with position on one page
cnry bing url-traffic <project> <url> [--children] [--page n]  # clicks/impressions for a URL and the URLs under it
cnry bing url-children <project> <url> [--page n]  # index details for the URLs under a directory
cnry bing links <project> [--url <page-url>]  # pages with inbound links, or the links to one page (often empty for small sites)
cnry bing fetched-urls <project> [--url <url>]  # Fetch as Bingbot history, or what Bingbot received
cnry bing keywords <project> <keyword> [--country us] [--language en-US]  # any keyword's Bing volume, weekly history, related keywords
```

`cnry bing traffic` is the Bing site total; `queries` and `pages` list only what Bing chooses to name, so never sum them for a total. Bing reports queries and pages per **week**: each stored row is one weekly bucket, and a window total sums the buckets dated inside it. Positions are impression-weighted; Bing's `-1` "no value" is stored as null. `latestAvailableDate` trails today by 2 to 3 days because Bing publishes late. `--window` takes `7d`, `30d`, `90d` or `all` and ends at the newest stored day. `bing traffic` returns `periodComparison` (the window against the stored window before it, or the window's own halves when the sync does not reach back that far, as `basis` says) and `trends` fitted over the calendar; days before the first sync never count as zero. `bing queries` and `bing pages` return `totals` (every matching row, before paging) and `comparison` against the window before, or null when the stored weeks do not reach it. `--exact` matches one whole query or page URL, which is how a single query's weeks are read (`--exact --group-by week`).

`cnry bing sync` runs as part of every `data-refresh` (with `inspect-sitemap`). It reads daily traffic, weekly query and page stats, daily crawl stats, sitemaps (expanding up to 20 sitemap indexes), 12 site settings and weekly search demand for tracked queries (refreshed once a week per query, at most 30 queries per sync, in the project's country and language). Every call goes through the same per-account pacing as the URL inspection sweep (one request start every 2 seconds per Bing key), and a throttle that outlasts the client's retries ends the run as `partial` instead of hammering the account. Sections fail independently: one failure marks the run `partial` and the rest still land. Owner-only settings (`connected-pages`, `site-roles`) are stored as `unauthorized` when the key is not the site owner's; that is not a failure. Bing AI Performance and Topics Portfolio (Copilot citations, grounding queries) are not in Bing's API, so Canonry cannot read them.

`cnry bing request-indexing` reads the site's remaining submission quota first (often 100 a day, not the documented 10,000) and submits only what Bing will accept; the rest come back as per-URL errors with the reason, and the response carries `quota`.

Bing is optional. `cnry doctor --project <project> --check 'bing.*'` reports `bing.auth.connection` as **skipped** (`bing.auth.not-connected`) for a project that never connected Bing, or whose domain's connection was removed with `cnry bing disconnect` (projects on one domain share the connection). It **fails** (`bing.auth.no-connection`) only when the connection is gone while the project still holds Bing data from an earlier connection. `bing.sync.recent-failures` fails after three `bing-sync` runs in a row fail, and `cnry status` shows a separate "Bing search data" row with the newest stored traffic day.

## WordPress Integration

```bash
cnry wordpress connect <project> --url <url> --user <user>   # connect (prompts for app password)
cnry wordpress disconnect <project>                          # disconnect
cnry wordpress status <project>                              # connection status
cnry wordpress pages <project> [--live|--staging]            # list pages
cnry wordpress page <project> <slug>                         # show page detail
cnry wordpress create-page <project> --title <t> --slug <s> --content <c>  # create page
cnry wordpress update-page <project> <slug> --content <c>   # update page
cnry wordpress set-meta <project> <slug> --title <t>        # set SEO meta (single page)
cnry wordpress set-meta <project> --from <file>              # bulk set SEO meta from JSON
cnry wordpress schema <project> <slug>                       # read page JSON-LD
cnry wordpress schema deploy <project> --profile <file>      # deploy schema from profile
cnry wordpress schema status <project>                       # schema status per page
cnry wordpress set-schema <project> <slug>                   # manual schema handoff
cnry wordpress audit <project>                               # audit pages for SEO issues
cnry wordpress diff <project> <slug>                         # compare live vs staging
cnry wordpress staging status <project>                      # staging config status
cnry wordpress staging push <project>                        # manual staging push handoff
cnry wordpress llms-txt <project>                            # read /llms.txt
cnry wordpress set-llms-txt <project>                        # manual llms.txt handoff
cnry wordpress onboard <project> --url <url> --user <user>  # full onboarding workflow
```

**Onboard** runs: connect → audit → set-meta → schema deploy → Google submit → Bing submit. Use `--skip-schema` or `--skip-submit` to skip steps. `--profile <file>` provides business data and page-to-schema mapping for schema deployment.

## Server-Side Traffic

To collect new Cloud Run logs as they arrive, connect with:

```bash
cnry traffic connect cloud-run <project> --gcp-project <id> --start-from-now
```

Include `--service` and `--location` to narrow the target. The server can
reuse a service account saved for that exact target. On first setup, pass
`--service-account-key <path>` with the private JSON file.

Cloudflare supports direct push and Queue pull. Run Cloudflare connect only from
the local host that owns the Canonry configuration and Wrangler profile. This
operation is not available through MCP because it uses local credentials.

```bash
# Direct push to a stable public Canonry HTTPS receiver:
cnry traffic connect cloudflare <project> \
  --delivery-mode direct-push \
  --zone-id <zone-id> --account-id <account-id> \
  --deploy --confirm-route --confirm-fail-open

# Create the Queue and enable its HTTP pull consumer first:
wrangler queues create canonry-traffic-<project>
# Workers Paid only: use this command to change the four-day default.
wrangler queues update canonry-traffic-<project> \
  --message-retention-period-secs <seconds>
wrangler queues info canonry-traffic-<project>
wrangler queues consumer http add canonry-traffic-<project>

# Queue pull keeps the API token in the local Canonry credential store:
cnry traffic connect cloudflare <project> \
  --delivery-mode queue-pull \
  --zone-id <zone-id> --account-id <account-id> \
  --queue-id <queue-id> --queue-name canonry-traffic-<project> \
  --api-token-file <mode-0600-token-file> \
  --retention-seconds <actual-queue-retention-seconds> \
  --deploy --confirm-route --confirm-fail-open

# Optional: also forward page views so AI visitor journeys see later visits.
# A reconnect without the flag keeps the setting; --no-forward-page-views turns it off.
cnry traffic connect cloudflare <project> --forward-page-views [same delivery options]
```

`--forward-page-views` adds people's document loads and form posts to what the
Worker forwards. It adds one Queue message (3 operations) or one push per page
view, not Worker invocations. Queue pull drains for up to 4 minutes per sync;
if doctor reports more than 1,000 messages left after syncs, shorten the
interval, raise `CANONRY_CLOUDFLARE_QUEUE_SYNC_DEADLINE_MS` or use direct push.
The Worker then reports a `+page-views` version; `cnry doctor` warns until the
deployed Worker matches.

Workers Free retention is fixed at `86400` seconds. Workers Paid defaults to
`345600` seconds. If you change paid retention with `wrangler queues update`,
pass the same value to Canonry. The Canonry flag does not change the Queue.

Both commands deploy an unattached Worker. Attach the exact site route in the
Cloudflare Dashboard. Then set its request-limit failure mode to **Fail open**.
Do not put the Queue API token on the command line or in an agent transcript.

```bash
# If connect reports activationRequired, activate after the route is live:
cnry traffic activate <project> --source <source-id>
cnry traffic sync <project> --source <source-id>      # pull adapters, including Cloudflare Queue pull
cnry traffic sources <project> --format json
cnry traffic status <project> --format json
cnry traffic analytics <project> --period 30 --format json    # complete 7|14|30|90-day totals, prior-period changes and breakdowns
cnry traffic events <project> --source <source-id> --format json
cnry traffic events <project> --kind ai-referral --since 2025-12-01T00:00:00Z --granularity month --format json   # series by UTC month; series.partialBuckets names part months (recording began inside, or still running), left out of the fits
cnry traffic events <project> --path /faq --group-by agent --since 2026-10-26 --format json   # which bots read a page: totals over the whole window (--path is the page and pages under it, never /faqs; totals, rows and groups all honor it)
cnry traffic events <project> --agent openai-searchbot --group-by path --since 2026-10-26 --format json   # which pages one bot read; --agent is the bot ID, or the AI product on ai-referral rows
cnry traffic events <project> --kind crawler --since 2026-10-26 --limit 5000 --cursor <eventRows.nextCursor> --format json   # next page of rows; repeat the filters, the cursor keeps the first page's window
cnry traffic referral-assessment <project> --start-date 2026-08-01 --end-date 2026-08-31 --burst-threshold 100 --ratio-threshold 3 --limit 100 --format json
cnry traffic declare-gap <project> --source <source-id>   # record an unrecovered skip as lost (WordPress, or past provider retention); clears the doctor check

cnry doctor --project <project> --check 'traffic.source.*' --format json
cnry schedule show <project> --kind traffic-sync --format json
cnry schedule set <project> --kind traffic-sync \
  --source <source-id> --cron "*/10 * * * *"
```

A first source becomes active automatically. A staged source stays paused until
the explicit activation command. Activation pauses sibling sources and moves the
one `traffic-sync` schedule for the project. Direct push rejects `traffic sync` and
does not use this schedule.

Queue pull drains for up to 4 minutes in one sync. Each run records why it
stopped: read `syncSummary.stopReason` with
`cnry runs <project> --kind traffic-sync --format json`. The doctor warns when
more than 1,000 messages remain afterwards and names the cause. After
`deadline` or `batch-cap` the drain hit its limit: if the operator approves a
manual drain, run a manual sync, and if the backlog recurs, get approval to
shorten the schedule interval or raise the time limit. After `empty-pulls`
Cloudflare still counted messages it would not return, even after waiting
between pulls; later syncs pull them.

Read the [server-side traffic guide](server-side-traffic.md) for token safety,
route checks, activation order, smoke tests, rollback, and troubleshooting.

`traffic referral-assessment` is a DB-only diagnostic, also available as MCP
`canonry_traffic_referral_assessment`. Date bounds are inclusive UTC dates, at
most 366 days. `--source` optionally selects one source. Thresholds tune only
the read; `--limit` caps candidate details, never totals. JSON and JSONL both
return the full assessment object.

Raw counts and existing headlines stay unchanged. The separate adjusted
estimate excludes every hit in a candidate burst group (one source, product,
normalized path and UTC hour), not proven automation.
The default 100-hit threshold is an uncalibrated review trigger. Normalized
paths may combine multiple pages, and sources may overlap. Simple and Advanced
projects use project/source scope; Property, Target and market attribution are
unavailable and unsupported filters are rejected.

`observedRatio` is a descriptive server/GA quotient, rounded to 2 decimals,
when GA sessions are positive and server rows exist.
`observedRatioAboveThreshold` compares that rounded value with
`--ratio-threshold`; it is not a quality verdict. Complete matching coverage and
the GA timezone are unknown. Server and GA observation states distinguish
missing evidence from an observed zero: server rows that are all redirects or
subresources are observed zero, and GA is observed zero only when the window
lies inside the latest GA sync window and that sync stored no AI row for it.
The silent `report.ai-referral-bursts` doctor check warns only when candidate
bursts exist, reports `candidateGroups`, and carries these limits in its
details. Keep GA evidence; this assessment does not establish a replacement
human-visit count.

`traffic analytics` reads complete stored server-traffic aggregates through
`GET /api/v1/projects/<name>/traffic/analytics?period=30` and the
`canonry_traffic_analytics` MCP tool. JSON preserves `{ activity }` unchanged;
JSONL emits the same document. With no non-archived source, `activity` is null.
Connected sources without events return zero stored aggregate counts; those
zeros do not prove measurement coverage or a successful source sync. Retain
`coverageStart` (the earliest stored project observation, or null) and
`priorWindowComplete` (whether it reaches the prior window's start). Incomplete
prior recording withholds all headline, arrival-class, and operator `deltaPct`
values while preserving current and prior counts. These fields do not prove
continuous collection or matching source coverage across the two windows.
It retains crawler
verification, user fetches, paid/organic/unclassified arrivals, redirect hops,
operators, crawled paths, referral products, landing paths, daily history, and
equal prior-window changes. It does not start a sync or provider work. The
scope is project-wide for Simple and Advanced portfolios; there is no Property,
Target, or market attribution. Server sessions and GA sessions remain separate.
Referral arrivals stored before Canonry 7.87.2 also counted a visitor's later
same-site requests, so a window or prior window that reaches back before that
upgrade reads high on that side.

## Google Analytics 4

GA4 integration supports service-account auth and OAuth (`canonry google connect <project> --type ga4`). With OAuth, `ga properties` lists the readable properties so the numeric id `ga connect --property-id` needs can be discovered without leaving canonry. The service account must have Viewer access on the GA4 property. `ga sync` writes the traffic tables (`gaTrafficSnapshots`, `gaAiReferrals`, `gaSocialReferrals`, `gaTrafficSummaries`) plus the GA4 Search Console landing-page snapshot (`gaSearchLandingWindows`, `gaSearchLandingPages`); every subsequent read command queries the local store rather than re-fetching from GA4, so reads are fast and quotaless. AI-referral rows are sessions GA4 puts in its `AI Assistant` channel (medium `ai-assistant`, since 2026-05-13, not retroactive) plus sessions whose source is an AI engine's host or a subdomain of it (`chatgpt.com`, `www.perplexity.ai`, `gemini.google.com`, `claude.ai`, `copilot.microsoft.com`, `grok.com`, `meta.ai`, `you.com`, …), its bare name (`chatgpt`, `gemini`, `grok`), its official Android app id, bare or as `android-app://` (`com.openai.chatgpt`, `com.microsoft.copilot`), or, for ChatGPT, Perplexity, Claude, DeepSeek and Phind, a tag that starts with the name or host (`perplexity_ai`, `chatgpt.com_ads`). These cover older history and AI visits GA4 files elsewhere. An engine name inside another source is never matched, so unrelated tunnel hosts, `philanthropic.org` and the Gemini exchange stay out. A channel row whose source names no engine is kept under its own source and counted in every AI total; visits that send no referrer still land in Direct. Rows are tracked across three GA4 attribution dimensions (`session` / `first_user` / `manual_utm`; the manual UTM lens matches sources only, since GA4 has no channel for it) and joined to landing pages. Social referrals are split Organic vs Paid via GA4's `sessionDefaultChannelGroup`. Synced rows carry no GA4 property, so anything that changes the property a project resolves to (`ga connect` to another property, `ga disconnect`, or `google disconnect --type ga4` with no service account behind it) deletes the project's GA rows; the next `ga sync` refills them from the new property. All commands support `--format json`.

```bash
cnry ga connect <project> --property-id <id> --key-file ./sa-key.json
                                                  # connect via service account (auth method = service_account)
cnry ga disconnect <project>                  # disconnect; deletes all synced rows for the project
cnry ga status <project>                      # connected, propertyId, authMethod, lastSyncedAt
cnry ga properties <project>                  # list GA4 properties the connected account can read,
                                                  # with their numeric ids. OAuth connections only —
                                                  # the id cannot be derived from the domain or the grant
cnry ga sync <project> [--days 30] [--only traffic|ai|social|search-landing]
                                                  # refresh from GA4 → DB; --only restricts which slice is replaced
                                                  # (search-landing = the Search Console landing-page snapshot)
                                                  # returns: synced, rowCount, aiReferralCount, socialReferralCount,
                                                  #          measurement.searchLandingPages{status, windows[], rowCount,
                                                  #          error?}, measurement.leads{days, status, rowCount,
                                                  #          eventNames (counted set), keyEvents{status read|error|
                                                  #          disabled, names, error?}}, syncedComponents (lists
                                                  #          search-landing only when its snapshot was stored), syncedAt
cnry ga measurement-analysis <project> [--window 30d|60d|90d]
    [--host-scope marketing|all] [--path-prefix /blog] [--limit 100]
                                                  # fixed 30-day cohorts across native GA4 channels,
                                                  # configured lead events, branded/non-brand GSC demand,
                                                  # ranked landing pages/queries, and independent freshness/errors
                                                  # for acquisition and leads; leads.aiEngines splits lead events
                                                  # by AI engine (ChatGPT, Perplexity, Gemini, ...) with the same
                                                  # engine's sessions and lead rate per cohort, organic and paid
                                                  # clicks apart; leads.countedEvents names the configured events
                                                  # and the GA4 key events counted (with any read error), and
                                                  # leads.events gives one series per counted event (origin
                                                  # configured, key-event or both); a measured event with no
                                                  # events reads as zero, and measured: false marks a counted
                                                  # event no lead sync has fetched yet (no series). Totals and
                                                  # attribution use only counted, measured events
cnry ga search-landing-pages <project> [--window 7d|28d|90d|180d] [--limit 50] [--offset 0]
                                                  # GA4's "Google organic search traffic: Landing page + query
                                                  # string" report (needs GA4's Search Console link): clicks,
                                                  # impressions, CTR, average position and active users per
                                                  # landing page for the 7/28/90/180 days ending YESTERDAY in the
                                                  # property time zone (28d = GA4's default). `total` is GA4's
                                                  # own Total row, never a sum of `rows`. status: never-synced |
                                                  # ready | unavailable (GA4 refused the Search Console metrics)
                                                  # | error; a failed refresh keeps the last snapshot. No
                                                  # --start/--end: every figure is GA4-computed per window
cnry ga traffic <project> [--window 30d] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
                                                  # current-period rollup; returns: totalSessions,
                                                  # totalOrganicSessions/totalDirectSessions/totalUsers,
                                                  # organicSharePct/aiSharePct/socialSharePct/directSharePct,
                                                  # topPages[], aiReferrals[], aiReferralLandingPages[],
                                                  # aiSessionsDeduped, aiSessionsBySession, socialReferrals[]
                                                  # (sessions only — the AI-referral user counts were withdrawn
                                                  #  in 4.135.0; GA counts users distinct per grain);
                                                  # aiEngines[] (aiReferrals grouped by engine, unattributed
                                                  # AI last with engine null), socialPlatforms[] (socialReferrals
                                                  # grouped by platform; an unmatched source is its own group),
                                                  # socialPlatformDaily (top 5 platforms + other, every series
                                                  # on every day), paidSocialSessions, paidSocialShare,
                                                  # socialPlatformPerformance (social and creator platforms in
                                                  # EVERY GA4 channel, so fb_ads ads GA4 files as Paid Other and
                                                  # ShopMy links in Unassigned count: platforms[] with sessions,
                                                  # paid/organic, conversions, conversionsPerThousandSessions,
                                                  # rank (null below minSessions=1,000) and sources[]; a session
                                                  # crossing hosts counts once; site{} whole-site reference
                                                  # (null when GA4 daily totals miss a day); rates null with
                                                  # conversionRateUnavailableReason when sessions and conversions
                                                  # cover different days). Human output prints the ranking.
cnry ga attribution <project> [--trend]       # unified channel breakdown (organic / ai / social / direct
                                                  # sessions + raw and display share %s); --trend adds 7d/30d
                                                  # direction per channel + biggest mover
cnry ga ai-referral-daily <project> [--window 30d] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
                                                  # AI sessions per day and per source: days[] with
                                                  # {date, sessions, paidSessions, organicSessions,
                                                  # bySource[]} + window totals + byEngine (top 5 engines +
                                                  # other, every series on every day). Landing pages summed inside
                                                  # ONE attribution dimension, never across dimensions, so
                                                  # totalSessions equals aiSessionsDeduped from `ga traffic`.
                                                  # Use this for any AI session COUNT. Sessions only: GA
                                                  # counts users DISTINCT per grain, so an AI-referral user
                                                  # count cannot be summed from these rows or fetched.
                                                  # months[] folds the same days by calendar month
                                                  # ({month, sessions, complete, engines[]}) and
                                                  # monthlyTrend fits the complete months
                                                  # (changePct = fitted end vs start). A month
                                                  # before the AI sync reached reads sessions
                                                  # null, even where GA4 kept site totals.
                                                  # Pass --start YYYY-MM-01 for whole months.
cnry ga ai-referral-history <project> [--window 30d] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
                                                  # RAW DETAIL, one row per (day × source × dimension ×
                                                  # landing page): {date, source, medium, attribution,
                                                  # landingPage, sessions, users}. Rows are fragments of a
                                                  # day, commonly worth 1 session each. Never collapse them
                                                  # into a total; read ai-referral-daily instead.
cnry ga social-referral-history <project> [--window 30d] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
                                                  # daily array of {date, source, medium, channel,
                                                  # sessions, users}; channel ∈ {Organic Social, Paid Social}
cnry ga social-referral-summary <project> [--trend]
                                                  # one-line social rollup: socialSessions, socialUsers,
                                                  # socialSharePct, topSources[]; --trend adds 7d/30d direction
cnry ga session-history <project> [--window 30d] [--start YYYY-MM-DD] [--end YYYY-MM-DD]
                                                  # daily totals: {date, sessions, organicSessions, users}
cnry ga overview <project> [--window 7d|30d|90d|180d]
                                                  # GA4's overview for the complete days ending yesterday
                                                  # (default 30d): users, new users, sessions, organic
                                                  # sessions, views, event count, key events, engagement
                                                  # rate, bounce rate, average engagement time, each against
                                                  # the previous period; --format json adds both periods by day
cnry ga coverage <project>                    # per-page overlay: {landingPage, sessions,
                                                  # organicSessions, users}
```

`--window` is rolling from now, so it can never name a calendar month. Pass `--start` / `--end` (inclusive, `YYYY-MM-DD`) for a calendar range; explicit dates win over `--window`. An unrecognised `--window` value is now REJECTED with a validation error rather than silently returning the full history under the label the caller asked for.

Every read command queries persisted DB rows, so a stale `lastSyncedAt` means the response is stale — always check `ga status` before drawing conclusions, and re-`ga sync` if the data is older than the analysis window. Use `--only ai`, `--only social` or `--only search-landing` to refresh just one slice when iterating.

`ga sync` reuses matching Search Console landing-page snapshots for up to one hour, fetching missing or stale windows. Property, reporting zone, exact dates and report definition must match; errors are retried and reused snapshots keep their original sync time. A new 180-day window is a full GA4 report, preserving distinct users and native totals.

`ga search-landing-pages` reads GA4's Search Console collection, not Canonry's own GSC sync: its clicks come through the GA4 property's Search Console link and can differ from `google performance` for the same days. Active users is GA4's plain `activeUsers` from the same request, which is what GA4's report shows (not limited to Google organic sessions). Search Console data reaches GA4 about two days late, so the last days of each window are thin, exactly as in GA4. A property not linked to the site's Search Console property reads `ready` with pages, active users, and 0 clicks and 0 impressions (observed live), so `searchConsoleLink` compares the window with Canonry's own Search Console data for the same days: `not-linked` when Search Console recorded impressions GA4 lacks, `no-search-data` when neither has any, `unknown` with no Search Console data to compare, `has-data` otherwise. GA4 can also refuse the report (`unavailable`, Google's message in `error`); the previous snapshot stays readable beside that status.

## Google Business Profile (Local AEO)

GBP integration tracks how AI engines see a business's local presence — search-keyword impressions, daily performance metrics, hotel lodging attributes, and booking CTAs. It reuses the **Google OAuth client** (same `google.clientId`/`clientSecret` as GSC; the connection is stored under the `gbp` connection type). **Hard prerequisite:** the Google Cloud project must be approved through Google's Business Profile API Basic Access form, or every call returns HTTP 403 at 0 QPM. See `references/google-business-profile.md` for the full GCP-setup + access-request playbook, the reviews/Q&A gating, and real-world data-shape quirks.

Like GA4, `gbp sync` writes to local DB tables and every read command queries the local store — reads are fast and quotaless; a stale sync means stale reads. All commands support `--format json`.

```bash
cnry gbp connect <project> [--public-url <url>]   # OAuth connect (reuses the Google client)
cnry gbp disconnect <project>                      # remove the GBP connection + ALL synced GBP data
cnry gbp accounts <project>                        # list GBP accounts this connection can access
                                                   # (account selection is per project — pick one below)
cnry gbp locations discover <project> [--account accounts/{n}] [--switch-account] [--no-select-new]
                                                   # discover a chosen account's locations; --account targets a
                                                   # specific account (omit = the account the project already tracks,
                                                   # else the first visible one); --switch-account opts into the
                                                   # destructive re-point to a different account; selects all new by default
cnry gbp locations <project> [--selected-only]     # list discovered locations + selection state
cnry gbp locations select   <project> --location locations/{n}
cnry gbp locations deselect <project> --location locations/{n}
                                                   # only SELECTED locations are synced; deselect also deletes
                                                   # that location's stored reviews, rating history and stats
                                                   # (selecting again fetches current data only). The list and
                                                   # select flag a location whose website is not one of the
                                                   # project's domains; discover leaves such a location unselected
cnry gbp sync <project> [--location locations/{n}] [--days N] [--months N] [--wait]
                                                   # fires the gbp-sync run: daily metrics + keyword impressions
                                                   # + place-action links + lodging snapshot per selected location;
                                                   # --wait polls to a terminal run status
cnry gbp metrics <project> [--location locations/{n}] [--metric <DailyMetric>]
                                                   # stored daily metrics + totals-by-metric
cnry gbp keywords <project> [--location locations/{n}]
                                                   # stored search-keyword impressions over the synced
                                                   # periodStart..periodEnd window; renders exact counts and
                                                   # <N thresholded floors + a thresholdedPct fidelity stat
cnry gbp place-actions <project> [--location locations/{n}]
                                                   # booking / reservation / order CTAs per location, with
                                                   # placeActionType, providerType (MERCHANT vs AGGREGATOR), isPreferred, uri
cnry gbp lodging <project> [--location locations/{n}]
                                                   # latest hotel-attribute snapshot per location (snapshot-on-change):
                                                   # populatedGroupCount + syncedAt; populatedGroupCount=0 means the Lodging
                                                   # API returns no structured attributes (common even for complete hotels;
                                                   # verify the "Hotel details" panel), a verify signal, not a confirmed gap
cnry gbp places <project> [--location locations/{n}]
                                                   # latest Places-API rendered-listing snapshot per location: the
                                                   # server-derived `amenities` the public listing advertises (#648 cross-reference).
                                                   # Needs a Places API key (places.apiKey / GOOGLE_PLACES_API_KEY)
cnry gbp reviews <project> [--location locations/{n}] [--negative] [--limit N]
                                                   # stored reviews newest first, plus each location's Business Profile
                                                   # review access (ok / unavailable + reason / error) and latest rating.
                                                   # --negative keeps reviews at or below the project's threshold
                                                   # (the review.negative threshold, 3 stars by default);
                                                   # each review carries its webhook alertState
cnry gbp summary <project> [--location locations/{n}]
                                                   # composite scorecard: performance totals + recent-vs-prior 7d
                                                   # deltas (deltaPct null when prior=0), keyword coverage,
                                                   # place-action CTA presence flags, Lodging API readable-group counts,
                                                   # owner-content profile completeness (secondary categories /
                                                   # description / service area / hours / phone + closed-status counts)
```

`gbp sync` produces a run with the standard statuses (`completed` / `partial` / `failed`); `partial` means some selected locations synced and others errored (the per-location errors are on the run). Non-lodging locations are skipped cleanly (Google answers the lodging call with HTTP 400, not 404). The Q&A API was retired (2025-11-03).

Reviews sync from the v4 Reviews API when Google has enabled it for the Cloud project. Most projects get `403 SERVICE_DISABLED`, which never fails the run: `gbp reviews` shows it per location, and the `gbp.reviews.access` doctor check explains how to request access. Without v4 access, locations fall back to the public Places listing when Places runs on the `atmosphere` tier with a key: the overall rating and at most five reviews chosen by relevance, so a new review can be missed. That fallback is at most one Place Details call per location per day, billed at Enterprise + Atmosphere.

Review webhooks: subscribe with `cnry notify add <project> --webhook <url> --events review.negative,review.rating-dropped`. `review.negative` is sent once per new or edited review at or below the project's threshold, 3 stars by default (`cnry project update <project> --negative-review-max-stars <1-4|default>`, or `spec.negativeReviewMaxStars` in `canonry apply`); `review.rating-dropped` when a location's public rating falls (Places fallback only). Lowering the threshold also stops alerts already queued; raising it applies to new and edited reviews only. A location's first sync records a baseline and sends nothing, a review older than 30 days never alerts, and nothing is held for a webhook added later. Discord and Slack URLs get a formatted message.

New-bot webhooks: subscribe with `cnry notify add <project> --webhook <url> --events traffic.agent.discovered`. Every 15 minutes Canonry sends one message per project naming the self-identified bots and agents no rule recognizes that were first seen in the last 7 days and reached 3 hits (the names `cnry traffic unrecognized` lists). Each name is sent once. Names first seen earlier never alert, and neither do the bots seen in a project's first 7 days of recorded traffic, which are a baseline. Nothing is held for a webhook added later. Discord and Slack URLs get a formatted message.

## Google Ads + Google Tag Manager conversion integrity

`google-ads` and `gtm` are separate first-class namespaces. **`ads` remains
OpenAI / ChatGPT Ads**; do not use it for Google Ads. Canonry v1 only reads
provider state: it never changes a Google Ads campaign/conversion action/goal,
and it never edits or publishes GTM.

```bash
# OAuth is an explicit same-browser operator flow. Start and confirm it from
# the project's Conversion Integrity dashboard; the CLI does not print OAuth URLs.

cnry google-ads status <project>                 # local connection + selection/freshness only
cnry google-ads customers <project> --format jsonl
cnry google-ads select <project> --customer <customer-id> [--login-customer <manager-id>]
cnry google-ads sync <project>                   # bounded read-only queries (GET + SearchStream POST) + redacted snapshots
cnry google-ads snapshots <project> --format jsonl
cnry google-ads snapshot <project> <snapshot-id>
cnry google-ads disconnect <project>             # removes private credential; retains redacted evidence

cnry gtm status <project>                         # local connection + selection/freshness only
cnry gtm accounts <project> --format jsonl
cnry gtm containers <project> --account <account-id> --format jsonl
cnry gtm workspaces <project> --account <account-id> --container <container-id> --format jsonl
cnry gtm select <project> --account <account-id> --container <container-id> [--workspace <workspace-id>]
cnry gtm sync <project>                           # bounded provider GETs + redacted live/draft snapshots
cnry gtm snapshots <project> --format jsonl
cnry gtm snapshot <project> <snapshot-id>
cnry gtm disconnect <project>                     # removes private credential; retains redacted evidence

# One contract joins business meaning to the selected Google Ads action and GTM graph.
cnry conversion-tracking contracts <project> --format jsonl
cnry conversion-tracking contracts get <project> <contract-id>
cnry conversion-tracking contracts create <project> --input contract.json
cnry conversion-tracking contracts update <project> <contract-id> --input contract.json
cnry conversion-tracking contracts delete <project> <contract-id>
cnry conversion-tracking contracts integrity <project> <contract-id> --format jsonl
```

Use this purchase contract as `contract.json`:

```json
{
  "name": "Purchase completed",
  "eventName": "purchase",
  "googleAds": {
    "customerId": "1234567890",
    "conversionActionId": "987654321",
    "conversionId": "AW-1234567890",
    "conversionLabel": "purchase_label",
    "campaignIds": [],
    "requireBiddableGoal": true,
    "requirePrimaryAction": true
  },
  "gtm": {
    "accountId": "123456",
    "containerId": "654321",
    "tagId": "42",
    "triggerIds": ["17"],
    "variableIds": ["21", "22", "23"]
  },
  "runtime": {
    "verificationRequired": true,
    "requireTransactionId": true,
    "requireValue": true,
    "requireCurrency": true,
    "productionHosts": ["example.com"]
  }
}
```

Replace every example ID with a canonical ID from the current snapshots. Use
the Ads customer ID without dashes, the conversion-action `id`, and each GTM
resource `id`. Do not use GTM resource paths or the public `GTM-...` container
ID.

Empty campaign, trigger, or variable arrays disable their corresponding
assertions. Canonry checks `requireBiddableGoal` only for listed campaigns. If
you do not know the exact GTM-facing values, omit `conversionId` and
`conversionLabel`. Do not supply server-owned IDs or timestamps.

Use the
[Google Marketing setup guide](https://github.com/Canonry/canonry/blob/main/docs/google-marketing.md)
for the operator workflow.

Stored snapshot and contract reads are local, redacted, and quota-free. Customer,
account, container, and workspace discovery plus sync are live Google reads; the
caller needs `google-marketing.read-live` in addition to normal write authority
for a sync. `google-ads sync` captures conversion actions and the **effective
per-campaign goal graph**; `gtm sync` captures sanitized live and selected-draft
configuration graphs. They do not prove a browser event fired or that Google Ads
recorded a conversion.

The integrity result is intentionally monotonic:

- `configured` means a contract exists but its static graph is unproven or inconsistent.
- `statically-consistent` means the stored Ads and GTM evidence agrees.
- `runtime-unverified` means the static graph agrees but runtime proof is missing.
- `observed` means static and trusted runtime evidence are both present.

The default Canonry runtime does not store runtime evidence in version 1. A
runtime-required contract therefore stops at `runtime-unverified`.

A selected GTM draft workspace produces stored draft evidence. Integrity uses
the live container graph and does not assess the draft graph.

Treat unrecognized GTM custom HTML/templates as `unknown` / needs-review, never
as a pass. An Ads action's `primaryForGoal` flag is not proof that a campaign
effectively bids toward it; inspect the effective campaign goal evidence.

`--format jsonl` streams one record per line for Google Ads customers and
snapshots, GTM accounts/containers/workspaces and snapshots, and
conversion-tracking contracts. Each line is stamped with `project`; live
discovery rows also include `fetchedAt`. Integrity JSONL streams deterministic
findings, each stamped with `project`, `contractId`, `integrityStatus`, and
`evaluatedAt`. Status, sync, one-snapshot, one-contract, connect/select, and
disconnect commands emit their normal JSON document when passed `--format
jsonl`.

## OpenAI ads (ChatGPT ads)

Paid-surface data for the project's connected OpenAI ad account. Ads render only in the ChatGPT consumer UI (never in API answers), so the Advertiser API is the only window into the paid layer. Money is integer micros in all stored/JSON data; insights `ctr`/`cpcMicros` are derived server-side and `null` on zero denominators. Paid metrics are "paid"/"sponsored" — never conflate with organic `cited`/`mentioned`.

```
cnry ads connect <project> --api-key <sdk-key>   # mint the key in OpenAI Ads Manager; validated upstream, stored in ~/.canonry/config.yaml
cnry ads status <project>
cnry ads account <project>                        # live account identity, currency/timezone, status, and integrity review
cnry ads geo search <project> --query "New York" --limit 20 --format jsonl
cnry ads conversions pixels <project> --format jsonl
cnry ads conversions event-settings <project> --format jsonl
cnry ads image upload <project> --input image.json
cnry ads campaign create <project> --input campaign.json
cnry ads campaign update <project> <campaign-id> --input update.json
cnry ads campaign pause <project> <campaign-id> --input pause.json
cnry ads ad-group create <project> --input group.json
cnry ads ad-group update <project> <ad-group-id> --input update.json
cnry ads ad-group pause <project> <ad-group-id> --input pause.json
cnry ads ad create <project> --input ad.json
cnry ads ad update <project> <ad-id> --input update.json
cnry ads ad pause <project> <ad-id> --input pause.json
cnry ads operation <project> <operation-key>     # inspect one durable mutation receipt
cnry ads operations unresolved <project> --limit 100 --format json
                                                   # list pending/unknown/reconciling receipts before new writes
cnry ads operations unresolved <project> --cursor <nextCursor> --limit 100 --format json
                                                   # advance past permanent rows with the opaque keyset cursor
cnry ads operation reconcile <project> --operation-key <key>
                                                   # verify nonactivation provider state; never retries the mutation
cnry ads operation resume-activation <project> --operation-key <key>
                                                   # exact-executor recovery for an existing activation receipt; no body
cnry ads activation-grant create <project> --input grant.json
                                                   # human approval for one exact tree + executor key + expiry
cnry ads activation-grant revoke <project> <grant-id>
                                                   # revoke only while the grant is unused
cnry ads campaign activate-tree <project> <campaign-id> --input activate.json
                                                   # executor consumes the exact approved grant
cnry ads sync <project>                          # ads-sync run: entity snapshots + daily rollups
cnry ads campaigns <project> --format jsonl      # lifecycle timestamps, location IDs, context hints, creative file IDs
cnry ads insights <project> --level campaign --from 2026-06-01 --format jsonl
cnry ads summary <project>                       # campaign-level totals only (no double counting)
cnry ads delivery-diagnostics <project>          # stored snapshot provenance, configuration facts, historical campaign activity
cnry ads live-delivery <project> --campaign <id> # LIVE provider read + stored-snapshot delta (read-only, bounded, 1/min per project)
cnry ads disconnect <project>
cnry schedule set <project> --kind ads-sync --preset daily
```

`ads sync` runs report `completed` / `partial` (some campaigns failed; per-campaign errors on the run) / `failed`. Doctor checks: `ads.auth.connection`, `ads.data.recent-sync` (both skipped when not connected).

The stored rollups include the ad account's CURRENT local day while it is still
running, so the newest date is a partial figure that grows on every sync. Do not
compare it against a finished day, and do not fold it into a period total
without saying so. Every read that can reach it says which date it is:
`ads insights` flags the row (`inProgress: true`), and `ads summary` /
`ads delivery-diagnostics` carry `window.inProgressDate` (null when the window
holds only closed days). "Current" means current in the ACCOUNT's timezone, not
yours.

One number on that row is not just partial, it is missing: conversions. OpenAI
will not report a conversion count for a day that is still open, so the current
day always shows 0 conversions no matter what actually happened. The real
figure lands on the first sync after the day closes. Impressions, clicks, and
spend are live on that row as usual.

`ads account`, `ads geo search`, and both `ads conversions` commands read the
live OpenAI Advertiser API rather than the local synced snapshot. Use `account`
to verify the connected advertiser and review state, `geo search` to resolve
campaign `locationIds` from provider-issued IDs, and the conversion reads to
verify the available pixel/CAPI sources, event goal, and attribution window
before launch. Geo search defaults to 20 results and accepts 1-100. Its JSONL
rows carry `{ project, query, ...location }`; conversion rows carry
`{ project, ...pixel }` or `{ project, ...eventSetting }`.

`ads delivery-diagnostics` reads stored snapshot provenance, stored
configuration, and historical campaign activity only. It is never a live OpenAI
serving or eligibility verdict. Agents must branch on `snapshot.status` /
`issue` and `assessment.state`; partial or unavailable structure must not be
treated as current provider state.

`ads live-delivery` is the opposite lane: it calls the provider RIGHT NOW and
returns the provider's current status and metrics per campaign / ad group / ad,
unaggregated and in the provider's own units, next to the stored snapshot values
and an explicit per-entity delta. Reach for it when the stored snapshot is
contradicted by the advertiser UI, not for routine checks: it is read-only but
it spends a third-party call budget, so one project may issue at most one live
read per minute (`429` with `retryAfterMs` otherwise). The attempt is counted as
soon as the provider is called, so a `502` still costs the interval: on an
upstream failure wait out `retryAfterMs` instead of retrying straight away. Read
`bounds.truncated` before concluding anything about entities you did not see,
and treat `presence: "stored-only"` as "absent upstream" ONLY on an untruncated,
error-free read. In `metricDeltas`, every date except the account's current
local day compares whole days on both sides, so a difference there is real; the
current local day is still accruing live while the stored side stopped at the
last sync, so a difference on it is snapshot staleness. `--lookback-days` (1-30,
default 7) sizes the metrics window; `--campaign` scopes the walk.

Lifecycle inputs are JSON files, or `--input -` for stdin. Every request carries
a unique `operationKey`. Identical replays return the stored receipt without a
second upstream request. Before issuing new lifecycle writes, run `ads
operations unresolved`; if a receipt is `pending`, `unknown`, or `reconciling`,
do not retry with a different key. Branch on `kind`: use `ads operation
resume-activation` for `campaign_tree_activate`, and generic `ads operation
reconcile` for other supported receipts. Generic reconciliation only reads and
verifies provider state. It never re-sends the mutation or accepts a
caller-selected provider entity. Canonry resolves a generic receipt only when
the provider ID was durably checkpointed and its live state matches the stored
safe fields on the receipt-bound account. An uncheckpointed create remains
unresolved because mutable-field equality cannot prove which request created an
entity. A pending generic receipt must be idle for five minutes before either a
human or the sweeper may claim it, so recovery cannot race a request that is
still returning from the provider. Automatic inconclusive inspections back off
from a five-minute base; explicit operator requests may inspect sooner, but
every generic path stops after five attempts. The receipt then remains visible
as `unknown` with `ADS_RECONCILIATION_QUARANTINED` and requires manual provider
remediation. JSON list responses return `nextCursor`; pass it back unchanged
with the same project and state filter to continue.
Creates are always paused. Updates require the entity to
already be paused and `expectedUpdatedAt` to equal the latest
`upstreamUpdatedAt` from `ads campaigns` after a sync. Canonry exposes pause as
the kill switch and deliberately omits archive and direct entity activation.
A human can instead approve one exact campaign tree for a different executor
key. The short-lived grant pins every campaign/ad-group/ad ID and
`expectedUpdatedAt`; execution rechecks the account and ad review gates, then
activates ads first, ad groups second, and the campaign last. Each step is
durably checkpointed. A failure rolls back the campaign before its children,
and an ambiguous outcome fails closed for manual remediation.

`biddingType` and `conversionEventSettingIds` are separate decisions.
`biddingType` is what the account is BILLED for (`clicks`, or the legacy
`impressions` default) and the provider makes it immutable after creation. Each
child ad group must then set `billingEventType` to `click` under a `clicks`
campaign, and Canonry rejects any ad-group billing mode that does not match its
live parent campaign before writing to the provider.
`conversionEventSettingIds` is what delivery OPTIMIZES toward: pass exact values
returned by `ads conversions event-settings` to get a conversion-optimized
campaign. A `clicks` campaign may omit them: click billing without conversion
tracking is a supported configuration. Canonry rejects duplicate conversion IDs.
Omit both fields to preserve the legacy impressions/impression mode.

Campaign updates may omit `locationIds` to preserve current geo targeting or
pass a non-empty list to replace it. The guarded operator cannot pass `null` or
an empty list to clear targeting. OpenAI documents that clearing targeting can
make the campaign eligible for all available locations, so an intentional
all-location change remains a human action in Ads Manager. See
[Campaign Targeting](https://developers.openai.com/ads/campaign-targeting) and
the [campaign update contract](https://developers.openai.com/ads/api-reference/campaigns#update-a-campaign).

### Guarded operator release gates

Default external automation to a project-scoped API key with exactly `read`,
`ads.write`, and `ads.activate`; never hand an external operator an unscoped
key:

```bash
canonry key create --name ads-operator --project <project> \
  --scope read --scope ads.write --scope ads.activate
canonry key create --name ads-approver --project <project> \
  --scope read --scope ads.approve
```

Keep the plaintext keys separate. The human approval request must authenticate
with the `ads-approver` key and name the operator key's ID as
`executorApiKeyId`; Canonry refuses a grant whose approver and executor IDs are
the same. Approval create/revoke exist in REST and CLI only. MCP and Aero expose
`activate-tree` plus bodyless recovery of its existing receipt, so the ads
operator cannot mint, replace, or widen its own grant.

The grant request is strict JSON. Its entity arrays must be uniquely sorted by
provider ID so the manifest has one canonical hash:

```json
{
  "manifest": {
    "campaign": {
      "id": "cmpn_...",
      "expectedUpdatedAt": 1780868842,
      "adGroups": [{
        "id": "adgrp_...",
        "expectedUpdatedAt": 1780864410,
        "ads": [{ "id": "ad_...", "expectedUpdatedAt": 1781139491 }]
      }]
    }
  },
  "executorApiKeyId": "key_...",
  "expiresAt": "2026-07-18T18:00:00.000Z"
}
```

The approval response returns `grant.id` and `grant.manifestHash`. Pass those
unchanged to the operator:

```json
{
  "operationKey": "launch:campaign:2026-07-18:1",
  "grantId": "grant_...",
  "manifestHash": "64-lowercase-hex-characters"
}
```

Before enabling spend on an advertiser account, run a paused, disposable
live-provider smoke test and capture sanitized raw responses for campaign get,
create, and pause. For every response, verify and record the exact case and type
of `status`, plus the type and exact returned value of `updated_at`. The
captured responses must agree with the typed client and fixtures without
coercion. After explicit budget approval, repeat the check through one minimal
grant-bound activate-tree execution and immediate campaign pause; verify every
activation response reports exact `active` plus an integer `updated_at`.

The receipt lifecycle is safe across concurrent writers: an atomic claim picks
one upstream sender and losers replay the canonical receipt. A leased generic
reconciler settles supported stale `pending` / `unknown` rows by verifying
provider state. Exact credential/account verification is cached for five
minutes, keyed by a one-way credential fingerprint plus the project and stored
account identity; credential rotation or account rebinding misses the cache
immediately. Activation receipts keep their grant and ordered step ledger
authoritative: only the exact bound executor may call the bodyless resume route,
which cannot substitute a manifest, grant, account, or campaign. When another
worker owns reconciliation or activation recovery, callers wait and read the
canonical receipt instead of starting a second pass.

## Backlinks (Common Crawl)

Canonry actively ingests backlinks from **Common Crawl**, a free public hyperlink graph that refreshes about monthly. The workspace-level release sync downloads each release once and reuses it across projects; per-project extraction requires DuckDB (install once with `cnry backlinks install`).

Databases created by older Canonry versions can retain historical `source=bing-webmaster` rows. Read filters remain compatible with those inert rows, but Canonry no longer fetches or refreshes them.

Common Crawl publishes the hyperlink graph as **rolling, monthly-stepped, overlapping 3-month windows** named by the window's first month's year: `cc-main-YYYY-<mon>-<mon>-<mon>` (e.g. `cc-main-2026-mar-apr-may`). Omit `--release` to auto-discover the newest published window.

```bash
cnry backlinks install                         # install bundled DuckDB binary
cnry backlinks doctor                          # show install + plugin status
cnry backlinks status                          # latest workspace Common Crawl release sync
cnry backlinks releases                        # list cached releases on disk
cnry backlinks releases latest                 # probe Common Crawl for the newest published rolling window
cnry backlinks sync                            # Common Crawl: auto-discover + download + query the newest release (workspace-wide)
cnry backlinks sync --release cc-main-2026-mar-apr-may --wait   # pin a window, block until ready/failed
cnry backlinks sources <project>               # active readiness + retained source data
cnry backlinks sources <project> --exclude-crawlers   # counts drop crawler/proxy hosts (matches the dashboard)
cnry backlinks list <project>                  # top Common Crawl linking domains
cnry backlinks list <project> --limit 100 --release <id>
cnry backlinks extract <project> --release <id> --wait  # Common Crawl: re-extract against a ready release
cnry backlinks cache prune --release <id>      # delete cached release files from disk
```

All commands support `--format json`; collection commands (`list`, `sources`, `releases`) also support `--format jsonl`. A Common Crawl release sync has statuses `queued` → `downloading` → `querying` → `ready` / `failed`. Per-project extracts use the standard run statuses (`queued` → `running` → `completed` / `failed`). Projects with `autoExtractBacklinks` enabled get an extract enqueued automatically when a release sync transitions to `ready`.

`backlinks sources` reports Common Crawl as `connected` when a release sync has completed and the project has stored Common Crawl data. Syncing the same release again keeps it connected while the download runs. The release sync writes every project's rows, so no project setting is needed. The `backlinks.source.connected` doctor check grades the same rule and warns `backlinks.source.none` otherwise: run `cnry backlinks extract <project>` when a release is currently `ready` but the project has no data yet, or `cnry backlinks sync` when no release is currently ready. Historical completion preserves existing project data through a re-sync but does not make that release available for extraction.

**`jsonl` output schema:** `backlinks list` streams `rows` (each `{ project, release, targetDomain, linkingDomain, numHosts, source }`); `backlinks sources` streams the per-source availability list (`{ project, targetDomain, source, connected, hasData, latestRelease, totalLinkingDomains, lastSyncedAt }`); `backlinks releases` streams cached-release rows bare.

To keep backlinks fresh automatically, schedule a `backlinks-sync` kind (`cnry schedule set <project> --kind backlinks-sync --preset weekly`): each tick re-probes Common Crawl and runs the workspace release sync **only when a newer rolling window is published** (it skips when the newest `ready` sync already covers the latest release, so it never re-downloads a near-identical window).

## CDP / Browser Provider

The `cdp:chatgpt` provider uses Chrome DevTools Protocol (CDP) to submit queries to the ChatGPT web UI. It captures the answer and citations from the browser session.

```bash
cnry cdp connect --host localhost --port 9222  # connect to Chrome CDP
cnry cdp status                                # show connection status
cnry cdp targets                               # list supported browser targets
cnry cdp screenshot <query> --targets chatgpt  # screenshot a query result
```

Start Chrome with `--remote-debugging-port=9222` and sign in to ChatGPT before you run browser queries.

## Telemetry

```bash
cnry telemetry status                          # show telemetry status
cnry telemetry enable                          # enable anonymous telemetry
cnry telemetry disable                         # disable telemetry
cnry telemetry status --target server --format json  # connected server, effective state and override reason
cnry telemetry disable --target server --format json # requires settings.write
```

## Feedback

Send feedback about Canonry itself to the Canonry team. Agents: when you uncover a struggle (a failure, confusing output, a workaround) or a concrete improvement, tell the user and send one report per issue. Be specific about the command, error code, and what you did instead. Never include secrets or customer data; credentials are redacted before sending. The anonymous install id is attached only while telemetry is enabled.

```bash
cnry feedback "run fails with RATE_LIMITED on a free Gemini key" --kind struggle --command "cnry run acme" --error-code RATE_LIMITED
cnry feedback "let me skip competitors from the CLI setup" --kind improvement --area setup
cnry feedback "<summary>" --kind bug --details "<what happened, what you expected>" --format json
```

Kinds: `struggle`, `bug`, `improvement`, `other` (default). MCP equivalent: `canonry_feedback`.

## Operational diagnostics

`cnry logs [--level trace|debug|info|warn|error|fatal] [--module <name>]
[--run-id <id>] [--project-id <id>] [--actor <user:id|api-key:id>]
[--request-id <id>] [--since <ISO>] [--until <ISO>]
[--limit <1..200>] [--cursor <cursor>] --format json`
returns `{entries,nextCursor,truncated,dropped,retention,retentionPolicy,captureErrors,observedAt}`.
`jsonl` preserves this object envelope. It requires a host-approved operator key
with an instance-wide `logs.read` grant (or wildcard). Only allowlisted
diagnostic metadata and sanitized messages are exposed, including application
and HTTP failures. File-backed hosts retain logs across restarts, capped at
10,000 events and seven days; in-memory hosts report process retention. Raw
request/response bodies, headers, cookies, provider payloads, and stacks are
excluded. Cursors bind the store and filters; expired or mismatched cursors
return a validation error. Inspect retention/loss counters before assuming
coverage. Use `history` for durable audit
events, with `--limit 1..500 --offset <n>` for traversal. Offset pages are not a
concurrent-write snapshot.

Google setup and telemetry default to local configuration. Pass `--target server`
to use the connected server; settings reads always describe the server.
Configured providers accept model/quota-only edits without resending secrets.
`cnry notify events --target server` discovers the remote event catalog while
the default remains the offline catalog. HTTP 4xx errors (including 429 policy
limits) retain exit 1; HTTP 5xx errors retain exit 2. Server-provided retry timing
and request IDs are exposed when available; no mutation is automatically retried.

## Config as Code

```bash
cnry apply project.yaml                        # apply declarative config
cnry apply file1.yaml file2.yaml               # multiple files
cnry export <project> --include-results > project.yaml
```

## Agent

Canonry ships the built-in **Aero** agent (backed by pi-agent-core) for users
who don't already have one, plus a webhook integration for users who want to
drive Canonry from Claude Code / Codex / a custom agent.

### Built-in Aero (one-shot CLI)

```bash
# One-shot turn — Aero picks its own tools, streams events to stdout.
cnry agent ask <project> "<prompt>"
cnry agent ask <project> "<prompt>" --format json      # JSON event stream

# Select a specific provider / model (otherwise auto-detected from config).
cnry agent ask <project> "<prompt>" --provider claude
cnry agent ask <project> "<prompt>" --provider zai
cnry agent ask <project> "<prompt>" --provider openai
cnry agent ask <project> "<prompt>" --provider gemini
cnry agent ask <project> "<prompt>" --provider openrouter --model publisher/model

# Restrict the tool surface. Default is --scope all (full read+write surface).
# --scope read-only matches the dashboard bar default so pasted "Copy as CLI"
# commands can't enable writes the UI turn couldn't perform.
# On an install that manages answer-visibility sweeps, even --scope all cannot
# start, fill or cancel a sweep, or change a schedule.
cnry agent ask <project> "<prompt>" --scope read-only
cnry agent ask <project> "<prompt>" --scope all

# Carry the selected view (also included by dashboard Copy as CLI).
cnry agent ask <project> "Explain this Property" --scope read-only --context '{"view":"property","selection":{"scope":"property","scopeKey":"hotel","queryClass":"non-brand","runId":"run-3"}}'
cnry agent ask <project> "Explain this page" --scope read-only --context '{"view":"site-health","page":{"runId":"scan-1","nodeKey":"page-2"}}'
cnry agent ask <project> "Top insights" --max-tool-calls 15 --timeout-ms 120000

# Session + provider introspection
cnry agent providers <project>                # list provider keys Aero will pick from + the resolved default
cnry agent transcript <project>               # dump the rolling transcript for the current session
cnry agent reset <project>                    # start a fresh session (drops in-memory state, keeps memory)
cnry agent clear <project>                    # delete the transcript row from the DB

# Durable project notes (the <memory> hydrate block on every new session)
cnry agent memory list <project>
cnry agent memory set <project> --key <k> --value <v>     # 2 KB cap per value
cnry agent memory forget <project> --key <k>
```

An explicit `--provider` takes precedence over the server's `agent.provider` setting. An unpinned turn can reuse the conversation's provider. Otherwise Aero checks for keys in order (`claude`, `openai`, `gemini`, `zai`, then `openrouter`) and picks the first match. Use `cnry agent providers <project>` to inspect the server's available choices.
If an older configuration uses the retired `deepinfra` provider, switch to a supported provider.

Conversations **persist per project** — `cnry agent ask` continues the
active conversation each invocation. Use `cnry agent conversations list <project>`
to list saved conversations, `new <project>` to save the current one and start
fresh, `show <project> --id <id>` to read one, `resume <project> --id <id>` to
continue it, and `delete <project> --id <id>` to remove it permanently. All support
`--format json`; list accepts `--limit 1..100` and `--offset` from `nextOffset`.
Creation accepts `--id <uuid>` for retry-safe callers (otherwise the CLI generates
one). `agent ask --conversation <id>` rejects a stale selection.

The dashboard exposes New conversation and History, with a separate delete
confirmation. Shared project notes survive; compaction summaries follow their
conversation and are deleted with it. One conversation is active per project,
shared across administrators. Older transcripts erased by the legacy reset
cannot be recovered. `agent reset`/`clear` retain their legacy destructive behavior.

Aero starts with core tools and loads authorized toolkits as needed. The
`ads-operator` profile keeps its explicit narrow catalog. Loading tools never
changes the caller's scope. Defaults are 30 tool calls and 180,000 ms of agent
execution; overrides allow 1–100 calls and 1,000–600,000 ms. The SSE/JSON stream
includes `aero_turn_status` with reason, call counts, duration, and limits.
Invalid context is rejected before generation. Context is per turn; it is not
an authorization grant or a persistent filter.

Stop with Ctrl-C in the CLI or Stop in the dashboard. Partial messages persist;
an action already dispatched may still finish. Inspect the transcript before
repeating a write. The dashboard offers Retry for read-only turns and prompt
review for write-capable turns. Unexpected stream EOF is an error.

### External agents (webhook)

```bash
# Wire an external agent webhook to a project
cnry agent attach <project> --url <webhook-url>        # register webhook subscription
cnry agent attach <project> --url <url> --format json  # JSON output
cnry agent detach <project>                            # remove the agent webhook
cnry agent detach <project> --format json              # JSON output
```

**Agent webhooks** fire on `run.completed`, `insight.critical`, `insight.high`, `citation.gained`, and `mention.gained`. The attach/detach pair is idempotent per project (one agent webhook per project, matched by source tag).

## Output Formats

Every command takes `--format`:

- **`text`** (default) — human-readable, decorated. Not a stable parse target.
- **`json`** — one pretty-printed JSON document (the full envelope). Stable contract.
- **`jsonl`** — newline-delimited JSON: the command's **primary collection**, one self-contained record per line. The agent-friendly machine format — no envelope key to guess (`.checks` vs `.results` vs `.rows`), no `jq` flattening, greppable line by line.

**Update notice.** When a newer canonry is published, the CLI writes one line to **stderr** before the command runs (stdout is never touched): `[canonry] UPDATE_AVAILABLE: ...` in text mode, or `{"notice":{"code":"UPDATE_AVAILABLE","current":"…","latest":"…","installMethod":"npm|homebrew|docker","upgradeCommand":"…","url":"…"}}` with `--format json|jsonl`. Tell the operator, or run the `upgradeCommand` (it already matches how canonry was installed) and restart `canonry serve`. `cnry doctor --check canonry.version.current` reports the same for the running server (`version.outdated` warns). Silence with `CANONRY_DISABLE_UPDATE_CHECK=1`. Over MCP the same notice arrives in the initialize instructions and as `updateAvailable` in `canonry_help`.

`jsonl` is supported by every **collection** command — one whose primary output is a list: `insights`, `runs`, `evidence`, `history`, `query/keyword/competitor list`, `notify list/events`, `google` reads (`performance`, `performance-daily`, `query-totals`, `inspections`, `coverage-history`, `deindexed`, `status`, `properties`, `list-sitemaps`), `bing` reads (`coverage-history`, `inspections`, `performance`, `sites`, `traffic`, `queries`, `pages`, `crawl-stats`, `sitemaps`, `site`, `keyword-demand`, `query-pages`, `page-queries`, `query-history`, `url-traffic`, `url-children`, `links`, `fetched-urls`, `keywords`), `ga` reads (`ai-referral-daily`, `ai-referral-history`, `social-referral-history`, `session-history`, `coverage`, `search-landing-pages`), `google-ads` customer/snapshot reads, `gtm` account/container/workspace/snapshot reads, conversion-tracking contracts and integrity findings, `ads geo search` and `ads conversions` reads, `traffic events/sources/status`, `discover list/show`, `content targets/sources/gaps/map`, `backlinks list/releases`, `project list/locations`, `key list`, `agent memory list`, `agent providers`, `sources` (streams the ranked cited-domain list), and `doctor`. (`content brief` is an object command — `jsonl` degrades to its JSON document.)

Each `jsonl` line re-injects the envelope context it would otherwise lose, so a line lifted out still self-describes:

- project-scoped lists stamp `{ "project": "<name>", …row }`;
- `ga *-history` also stamps `window`; `ga search-landing-pages` stamps `window`/`windowStart`/`windowEnd`; `traffic events` stamps `windowStart`/`windowEnd`; `backlinks list` stamps `release`/`targetDomain`; `discover show` stamps `sessionId`; `content targets` stamps `latestRunId`; `project locations` stamps `isDefault`;
- global lists whose rows already self-identify (`project list`, `notify events`, `backlinks releases`) emit bare rows.

Empty collection → **no output** (the exit code still conveys success, so "no records" stays distinct from "failure"). On failure a command prints its records (if any), then exits non-zero — branch on the **exit code**, never on parsing stderr. JSON field names and the `{ "error": { "code", "message" } }` envelope are a public contract.

**Composite** commands return a single aggregate object (not a list), so there is nothing to stream — on them `--format jsonl` **degrades to the same JSON document** as `--format json`; it never falls through to decorated human text. So `--format jsonl` is safe to pass to *any* command: collection commands stream their records, every other command emits its JSON document. Composite shapes are below.

## Output schema per command

Compact reference for the composite / keyed commands agents read most (shapes can drift — the linked DTO source file is the source of truth; collection commands simply emit their primary array, see each command's own section above).

| Command | JSON output shape (top-level keys → DTO) | `jsonl` |
|---|---|---|
| `cnry project setup <p>` | `ProjectSetupDto` @ `contracts/project-setup.ts`: `{ project{name,displayName,canonicalDomain}, complete, firstResultAt, nextAction, tracks{ agentReadiness{state,runId,startedAt,finishedAt,progress{phase,pagesFound,pagesChecked,pageLimit,linksFound,pagesFailed}\|null,result{score,pagesScored}\|null,error}, aiVisibility{state,runId,runIds[],startedAt,finishedAt,baselineRunId,mode,blockedBy,engines[],queries{total,nonBrand,branded,unclassified},progress{answersSaved,answersPlanned}\|null,providerFailures,result{first,answers,engines,queryCounts,queryCountsByClass}\|null,error,failedEngines[{provider,code,message,skipped}]\|null} } }`. `complete` = each track has produced a result (a completed or partial non-probe run) at least once; a newer run in progress does not undo it. | → degrades to the `json` document |
| `cnry status --all [--problems]` | `InstanceStatusDto` @ `contracts/status.ts`: `{ generatedAt, summary{projects,ok,failing,warning,stale,neverSynced}, projects[{project,displayName,state,health,integrations[]}] }`. Stored reads only; a successful read exits 0 even when rows are failing. | One integration per line as `{project, health, ...row}`; a project without integration rows emits `{project,state,health}`. Single-project `status <p>` keeps its JSON envelope and emits one compact record for JSONL. Stored health failures and warnings affect project state, summary and `--problems`; explicit project reads always retain health. |
| `cnry doctor [--project p] [--all] [--report-month YYYY-MM]` | `{ scope, project, reportMonths?, generatedAt, durationMs, summary{total,ok,warn,fail,skipped}, checks[] }` — `DoctorReportDto` @ `contracts/doctor.ts`. `checks[]` = `CheckResultDto{ id, category, scope, title, status(ok\|warn\|fail\|skipped), notificationPolicy?(health\|silent), code, summary, remediation?, details?, durationMs }`. `report.*` checks are silent report-readiness advisories: they never page or change health state. `--report-month` picks the month they grade (default: the current month, plus the closed month through day 3, when only the closed month is graded). With `--all`: an object keyed by `__global__` + each project name, each value a full report. | ✅ one check / line as `{project, …check}`; still exits non-zero if any `fail` |
| `cnry analytics <p> [--feature metrics\|gaps\|sources] [--window 7d\|30d\|90d\|all]` | Object **keyed by feature**: `{ metrics?, gaps?, sources? }` (all three present with no `--feature`; one with `--feature X`). `metrics`=`BrandMetricsDto{ window, buckets[], overall, byProvider, trend, mentionTrend, queryChanges[] }` (each metric's `citationRate` is over `citedTotal`, the answers whose sources were checked, and null when no answer carries sources; the human output prints "not measured"); `gaps`=`GapAnalysisDto{ cited[], gap[], uncited[], citationNotMeasured[], mentionedQueries[], mentionGap[], notMentioned[], runId, window }` (each `[]`=`GapQuery`; `citationNotMeasured` holds queries whose latest answers all lack sources; `consistency.citedRuns` is out of `consistency.citedTotalRuns`); `sources`=`SourceBreakdownDto` (same shape as `cnry sources`, below). @ `contracts/analytics.ts` | → degrades to the `json` document |
| `cnry sources <p> [--rank] [--limit N] [--by-provider] [--window …]` | `SourceBreakdownDto{ overall[], byQuery, ranked, byProvider, runId, window, limit }` @ `contracts/analytics.ts`. `ranked`/each `byProvider[name]` = `RankedSourceList{ totalCitedSlots, domainTotal, entries[], truncatedDomainCount, truncatedCitedSlots, bySurfaceClass[] }`; `entries[]`=`SourceRankEntry{ domain, count, percentage, category, label, surfaceClass }`; `bySurfaceClass[]`=`SurfaceClassCount{ surfaceClass, label, count, percentage, domainCount }`. `surfaceClass` ∈ own \| direct-competitor \| ota-aggregator \| editorial-media \| other. | ✅ streams `ranked.entries` one / line as `{project, …entry}` |
| `cnry visibility-stats <p> [--since <iso>] [--until <iso>] [--month <YYYY-MM>] [--last-runs N] [--by-provider] [--share-of-voice] [--query-class branded\|non-brand]` | `VisibilityStatsDto{ project, groupBy, window{since,until,lastRuns,runCount}, totals, byProvider?[], queries[], shareOfVoice? }` @ `contracts/visibility-stats.ts`. Each query / provider / totals entry = `{ total, citationNotMeasured, checked, mentioned, cited, mentionRate, citedRate }` (+ `query`/`queryId`/`firstObserved`/`lastObserved` on queries, + `provider`/observed on provider entries). `checked`=snapshots with non-null `answerMentioned` (tri-state n for mention); `citationNotMeasured`=snapshots whose engine returns no sources (never a miss); `mentionRate=mentioned/checked`, `citedRate=cited/(total-citationNotMeasured)`, both `null` on a 0 denominator. `byProvider`/per-query `providers` present only with `--by-provider`; counts sum to pooled. `--month YYYY-MM` echoes the resolved `window.since`/`until`. `shareOfVoice` present only with `--share-of-voice` = `{ queryClass, percent, projectMentions, competitorMentions, snapshotsWithAnswerText, perCompetitor[{domain,mentions}] }`; `percent` (0-100) = `projectMentions/(projectMentions+competitorMentions)`, `null` when no competitors configured. `queryClass` is what was actually served: `non-brand` (the default), `branded` (via `--query-class`), or `pooled` — which appears ONLY when the project has no usable brand alias to split by, never as a default. Branded and non-brand never share a denominator. | ✅ streams `queries` one / line as `{project, runCount, …query}` (envelope-only `shareOfVoice` not in the jsonl rows) |
| `cnry trends <p> --surface index-coverage\|site-health\|backlinks [--window 7d\|30d\|90d\|all \| --start YYYY-MM-DD --end YYYY-MM-DD]` | `TrendsResponse{ project, surface, window (null for a date range), startDate, endDate, groups[] }` @ `contracts/trends.ts`. Each group = `{ key, label, figures[] }`; each figure = `TrendFigure{ key, label, unit(count\|score\|fraction), better(higher\|lower\|neither), value, asOf, change{ difference, ratio, tone(better\|worse\|neutral), basis{ type: first-in-window, date, observedAt, label } }\|null, series[{ date, observedAt, label, value }], recordedFrom }`. A group that never recorded a reading is omitted; an empty surface has no groups and null dates. | → degrades to the `json` document |
| `cnry google coverage <p>` (index coverage) | `{ summary{total,indexed,notIndexed,deindexed,percentage}, lastInspectedAt, lastSyncedAt, indexed[], notIndexed[], deindexed[], reasonGroups[] }` — `GscCoverageSummaryDto` @ `contracts/google.ts`. `indexed[]`/`notIndexed[]`=`GscUrlInspectionDto`, `deindexed[]`=`GscDeindexedRowDto`. | → degrades to the `json` document. The single-array reads `google inspections` / `coverage-history` / `deindexed` **stream** `jsonl`. |
| `cnry google query-totals <p> [--start …] [--end …] [--window …] [--limit N] [--offset N]` | `GscQueryTotalsDto{ rows[], totalMatching, truncated, window }` @ `contracts/google.ts`. Each row = `{ query, clicks, impressions, ctr, position, days, source(google\|page-summed\|mixed) }`; `window` = `GscWindowRange{ startDate, endDate, latestDataDate, daysSinceLatestData }` plus `earliestDataDate` (first stored per-query date, `null` with none; a window starting before it is only partly covered). Named queries only: the rows do not add up to the property total. | Streams one line per query, each tagged with `project` and `window`. |
| `cnry ga measurement-analysis <p> [--window 30d\|60d\|90d] [--host-scope marketing\|all] [--path-prefix /…]` | `GaMeasurementAnalysisDto` @ `contracts/measurement.ts`: fixed 30-day `acquisition.periods/channels/pages`, configured-event `leads.periods/channels` with explicit attribution/filter scope, `leads.aiEngines{ leadRateAvailable, leadRateUnavailableReason, organic, paid }`, each class `{ periods[], engines[{ engine, label, sources[], periods[] }], unattributed{ sources[], periods[] } }` (lead events per AI engine from GA4 `sessionSource` via the shared `aiEngineForReferralSource` mapping, split by `classifyAiReferralTrafficClass` so tagged ad clicks never pool with organic, with the landing page left out on both sides when leads are channel-scoped; each cohort has `eventCount`, same-source same-class `sessions` under the same host/path filters, and `leadRate` = eventCount / sessions as a fraction, `null` on 0 sessions or when `leadRateAvailable` is false; `leadRateUnavailableReason` is `no-data`, `sync-not-ready` (latest acquisition or lead sync failed), `channel-leads-unfiltered` (channel-scoped leads cannot follow the host/path filters), `paid-split-needs-landing-page` (channel-scoped leads, and some AI sessions were paid only by landing-page utm tags, so they count as organic), `sessions-behind-leads` (leads stored past the last acquisition date) or `sessions-missing-on-lead-days` (a day in the window has leads but no stored acquisition rows); `unattributed` is GA4 `AI Assistant` channel rows matching no engine; a class's `periods[]` is its engines plus `unattributed`), and `searchDemand.periods/queries/pages` with property totals, reported branded/non-brand rows, and unreported residuals. Each GA component carries independent status/error/sync freshness. | → degrades to the `json` document |
| `cnry ga search-landing-pages <p> [--window 7d\|28d\|90d\|180d] [--limit N] [--offset N]` | `GaSearchLandingPagesResponse` @ `contracts/ga.ts`: `{ source, status(never-synced\|ready\|unavailable\|error), error, syncedAt, attemptedAt, window, windowStart, windowEnd, windowDays, timeZone, subjectToThresholding, dataLossFromOtherRow, total, reportRowCount, rowsCapped, totalRows, limit, offset, rows[], searchConsoleLink }`. `searchConsoleLink` = `{ state: has-data\|not-linked\|no-search-data\|unknown, searchConsoleImpressions (Canonry's own Search Console impressions for the window's days, null when none) }`, null with no snapshot. `total` and each `rows[]` entry = `{ organicGoogleSearchClicks, organicGoogleSearchImpressions, organicGoogleSearchClickThroughRate (0..1, null with no impressions), organicGoogleSearchAveragePosition (null with no impressions), activeUsers }` (+ `landingPage`, GA4's raw `landingPagePlusQueryString`, on rows). `total` is GA4's TOTAL row and null with no snapshot. `rowsCapped` = GA4 reported `reportRowCount` pages and only the top 10,000 by clicks, then impressions, were stored. | ✅ streams `rows` one / line as `{project, window, windowStart, windowEnd, …row}` (the Total is in `json` only) |
| `cnry ga traffic <p> [--window …]` | Object summary — `GA4TrafficSummaryDto` / `GaTrafficResponse` @ `contracts/ga.ts`: `{ totalSessions, totalOrganicSessions, totalDirectSessions, totalUsers, aiSessionsDeduped, paidAiSessionsDeduped, organicAiSessionsDeduped, aiSessionsBySession, paidAiSessionsBySession, organicAiSessionsBySession, socialSessions, socialUsers, paidSocialSessions, paidSocialShare, socialPlatformPerformance{status, unavailableReason, sessions, sharePct(+Display), paidSessions, paidShare, conversions, conversionRateAvailable, conversionRateUnavailableReason, countedEventNames[], minSessions, site{sessions, conversions, conversionsPerThousandSessions(+Display)}, platforms[{key, platform, label, sessions, organicSessions, paidSessions, share, conversions, conversionsPerThousandSessions(+Display), enoughSessions, rank, paid{}, organic{}, channelGroups[], sources[{source, medium, channelGroup, trafficClass, sessions, share, conversions, conversionsPerThousandSessions(+Display)}]}], daily} (every GA4 channel; ranked by conversions per 1,000 sessions from minSessions), channelBreakdown{organic,social,direct,ai,other→{sessions,sharePct,sharePctDisplay}}, *SharePct (+ `*Display`), topPages[], aiReferrals[], aiEngines[{engine,label,sessions,organicSessions,paidSessions,share,sources[]}], aiReferralLandingPages[], socialReferrals[], socialPlatforms[{platform,label,sessions,organicSessions,paidSessions,share,sources[]}], socialPlatformDaily{series[],otherCount,days[{date,sessions,values}]}, lastSyncedAt, periodStart, periodEnd }`. Groups partition their rows: `aiEngines` sums to the `aiReferrals` sessions and `socialPlatforms` to `socialSessions`; AI traffic whose source names no engine is the `engine: null` group, never assigned an engine. **AI referrals are sessions only.** The six `ai*Users*` fields and the `users` on `aiReferrals[]` / `aiReferralLandingPages[]` were withdrawn in 4.135.0 — GA reports users as a COUNT DISTINCT at the grain requested, so the stored column re-counted one visitor per landing page, medium, channel and date, and no un-dimensioned AI-referral fetch exists to supply a correct figure. `totalUsers` and `socialUsers` are unaffected. | → degrades to the `json` document |
| `cnry ga attribution <p> [--trend]` | Object — a **renamed projection** of `GaTrafficResponse` (⚠️ field names differ from the DTO): `aiSessions`(←`aiSessionsDeduped`), `organicSessions`(←`totalOrganicSessions`), `directSessions`(←`totalDirectSessions`), plus `totalSessions, totalUsers, paidAiSessions, organicAiSessions, aiSessionsBySession, paidAiSessionsBySession, organicAiSessionsBySession, socialSessions, socialUsers, {ai,social,organic,direct}SharePct (+ `*Display`), otherSessions, otherSharePct, channelBreakdown, aiReferrals[], aiReferralLandingPages[], socialReferrals[], periodStart, periodEnd`. With `--trend`: drops `periodStart/End`, adds `trend` (`GaAttributionTrendResponse`). Assembled inline in `commands/ga.ts`. | → degrades to the `json` document |
| `cnry key list` / `key create` / `key revoke <id>` | `list`: `{ keys[] }` — each `ApiKeyDto{ id, name, keyPrefix, scopes[], projectId, projectName, readOnly, createdAt, lastUsedAt, revokedAt }` (SAFE metadata, never the hash or plaintext). `create`: `CreatedApiKeyDto` = `ApiKeyDto` **plus a one-time `key`** (the plaintext `cnry_…` token, shown once). `revoke`: the `ApiKeyDto` with `revokedAt` set. @ `contracts/api-keys.ts` | `key list` streams one key / line; `create` / `revoke` degrade to the `json` document |
| `cnry gbp summary <p> [--location …]` | `{ scope{locationName,locationCount}, performance{totals,recent7d,prior7d,deltaPct} (metric-keyed maps; keys are raw `BUSINESS_*` / `WEBSITE_CLICKS` tokens — label via `formatGbpMetricLabel`), freshness{dataThroughDate,latestStoredDate,pendingDays}, timeseries[], keywords{total,thresholdedCount,thresholdedPct}, placeActions{total,hasReservationCta,hasBookingCta,hasDirectMerchantCta}, lodging{lodgingLocationCount,populatedLodgingCount,emptyLodgingCount}, profileCompleteness{locationCount,withSecondaryCategories,secondaryCategoryTotal,withDescription,withServiceArea,withHours,withPrimaryPhone,permanentlyClosed,temporarilyClosed} }` — `GbpSummaryDto` @ `contracts/gbp.ts`; `emptyLodgingCount` means 0 readable Lodging API groups, a verify signal rather than proof the Hotel details panel is empty. `timeseries[]`=`{date,pending,metrics}`. | → degrades to the `json` document |
| `cnry ads account <p>` | `AdsAccountDto{ id, name, status, currencyCode, timezone, url, reviewStatus, integrityReviewStatus, integrityDecision }` @ `contracts/ads.ts`. This is live provider state, not a synced snapshot. | → degrades to the `json` document |
| `cnry ads geo search <p> --query <text>` | `AdsGeoSearchResponse{ count, query, results[] }` @ `contracts/ads.ts`; each location has `{ id, type, canonicalName, countryCode, name, regionCode }`. | ✅ one result / line as `{project, query, …location}` |
| `cnry ads conversions pixels <p>` / `event-settings <p>` | `{ pixels[] }` / `{ eventSettings[] }` @ `contracts/ads.ts`. Event settings include the conversion event, attribution window, source IDs/details, archive state, and version. | ✅ one pixel/event setting / line as `{project, …row}` |

## Sentiment

```bash
canonry sentiment settings <project> --format json
canonry sentiment configure <project> --enabled true --format json
canonry sentiment <project> --run-id <run> --query-class non-brand --format json
canonry sentiment <project> --run-id <run> --query-class non-brand --include assessments,locations --query-limit 50 --format json
canonry sentiment evidence <project> --run-id <run> --query-class non-brand --query-id <query> --evaluation-definition-id <definition> --format json
canonry sentiment evidence <project> --run-id <run> --query-class non-brand --assessment-id <assessment> --provider <engine> --model <served-model> --format json
canonry sentiment evidence <project> --query-class non-brand --outcome mixed,unfavorable --format json
canonry sentiment evidence <project> --query-class branded --scope property --scope-key <property> --outcome mixed,unfavorable --format json
canonry sentiment compare <project> --from-run-id <before> --to-run-id <after> --format json
canonry sentiment backfill <project> --preview --query-class non-brand --run-id <run> --format json
canonry sentiment backfill <project> --preview --query-class branded --from <ISO-date-time> --to <ISO-date-time> --format json
canonry sentiment backfill <project> --preview-token <returned-token> --idempotency-key <key> --format json
canonry sentiment jobs <project> --format jsonl
canonry sentiment job <project> <job-id> --attempt-limit 50 --format json
```

Reads are stored-only. Install and project switches default off; the install key is
configured locally, never through remote commands. Configure and backfill submission
require install administrator authority. Enabling processes future complete runs;
preview/submit is the explicit historical workflow. Preview requires --query-class branded|non-brand; backfill each class with its own preview and submission. A repeated key with the same
preview returns the same job; changed payloads conflict. Initial settings only
control enablement; there are no theme presets or custom themes.

Summary, evidence, comparison and preview accept run/revision, mode, query class, query ID,
scope/scope key, market key, provider/model, location and evaluation definition.
Advanced `--scope property --scope-key <key> --market-key <key>` preserves exact
frozen usage edges. Keep every selection field and the returned evaluator ID while
following `--cursor`. Branded and non-brand are supported with separate denominators;
select the class explicitly (the default remains branded). Summary includes
server-computed per-query scores, 25 rows per page by default (`--query-limit`
1..500; follow `Next query cursor` / `queryPage.nextCursor` with `--query-cursor`).
Advanced rows are per execution node (`executionNodeKey`; `--execution-node-key`
narrows any read to one node). `--include assessments,locations` adds per-location
scores and `queries[].assessments` with exact engine verdicts, requested/served
models, source IDs, subject, location, state and exclusions; a named `--query-id`
includes both by default. Unclassified sources have no verdict; absent subjects are
not unfavorable. Evidence-only `--assessment-id` selects one returned assessment
within the other filters; retain it with the evaluator and scope when following
a cursor. Evidence-only `--outcome` (comma-separated or repeated) keeps only those
outcomes and is echoed as `selection.outcome`; it never changes scoring. Keep it
when following a cursor. `--model` matches the served source model. For a grouped read, summary and
evidence accept `--run-ids <first> --run-ids <second>` instead of `--run-id`.
Backfill retains repeated `--run-id` for its historical selection. JSON equals the HTTP DTO;
evidence JSONL is one complete page document so empty state and cursor survive.
Jobs JSONL streams one project-stamped job summary (with `attemptCount`) per line; `sentiment job` pages attempt receipts newest first (`--attempt-limit`, `--attempt-cursor`). Favorable rates use judged
assessments; mixed gets no partial credit, absent subjects are excluded, and
partial scores cannot establish improvement or decline. A Simple subject carries the
project's qualified aliases frozen at dispatch as `subject.qualifiedAliases` (see Brand
aliases); earlier runs keep their list (empty before opting in) and are not rescored.
Every change to the list (first set, edit, or clear) starts a new subject boundary at
the first run captured afterward: a pooled read or comparison across it is refused, so
read from the most recent change onward.

Sentiment is a branded figure: non-brand answers name the brand almost only to
recommend it, so read non-brand as exceptions with `--outcome mixed,unfavorable`.
`canonry overview` text prints the branded headline (`Sentiment: <x> favorable ·
branded queries` plus favorable / judged); JSON keeps `sentiment.branded`,
`nonBrand` and `overall` unchanged. A branded summary spanning more than one
Property carries `criticizedProperties` (`total`, and `keys`: the first 5 property
breakdown keys, most mixed plus unfavorable first). Text output lists them under
`Most criticized properties: N of total` with favorable, mixed and unfavorable
counts; read one with `--scope property --scope-key <key> --outcome mixed,unfavorable`
(in a market view, pass that market as `--market-key`).

Sentiment also checks mentions. When its latest verdict on an answer is
`wrong-subject` (the answer uses the name but is about a namesake or a shared word),
the answer stops counting as mentioned everywhere: run detail and snapshot JSON carry
`mentionIdentity: "wrong-subject"` with `matchedTerms` still listing the name, and
`canonry run show` marks the row `different subject`. An Advanced Property's answer
evidence carries the same field on that Property's row. `ambiguous-subject` never
changes a mention. Probes are never assessed.

### Stored traffic samples

```bash
cnry traffic samples <project> --kind ai-referral --since 2026-10-10T00:00:00Z --until 2026-10-11T00:00:00Z --format json
cnry traffic samples <project> --source <id> --path /blog --limit 100 --offset 100 --format jsonl
```

A stored sampled tail with 30-day retention, not visits or sessions. Use `traffic
events` for totals. Default `--kind all` includes crawler, AI user-fetch, and AI
referral samples; unknown requests require `--kind unknown`. A Claude-Agent or
Google-Agent sample carries `classifier.aiUserFetch.requestKind` (`page`,
`action` or `resource`). Browser agents count only page loads, so unless a
sample is likely fake, only a `page` sample was counted; sync results count
their other requests in `aiUserFetchBrowserNonPageHits`, and text output labels
those samples `(<trust>; <kind>, not counted)`. Time bounds are
inclusive ISO timestamps or `YYYY-MM-DD` dates (midnight UTC), defaulting to the last 24 hours. `--since-minutes`
selects a positive relative duration and cannot be combined with `--since`. Path
prefixes are literal. Limit is 1 to 500; offset starts at zero. Project/source
attribution applies equally to Simple and Advanced portfolios; Property, Target,
and market attribution is unavailable. No provider call or write. Signed-in
viewers and embeds cannot read samples; API read keys retain project scope.

### Agent request journeys

```bash
cnry traffic agent-journeys <project> --since 2026-10-20 --until 2026-10-27 --source <source-id> --format json
cnry traffic agent-journey <project> <journey-id> --since 2026-10-20 --until 2026-10-27 --source <source-id> --limit 50 --offset 0
```

These commands follow recorded user-triggered agent requests, separately from
AI-referred browser visitors. Both accept `--agent <id>`, `--trust
verified|likely_real|unknown`, and `--target-key <key>` in addition
to the window/source selectors. The default window is 24 hours; the maximum is
31 days. Keep selectors unchanged when opening a detail or requesting another
page. Reads over 20,000 selected source/agent events require a narrower window.
Limits are 1 to 200. JSON matches the API response;
JSONL streams a `journey` or an `event` with its full scope and coverage context.

IP and user-agent grouping is inferred and can merge tasks. Requests without
an IP stay unlinked; trust does not prove a user session. Each request carries
`trust` and `trustReasons`: verified by the operator's published IP list, likely
real (unchecked, but the operator's published user agent), or unknown. Likely
fake requests are counted in `coverage.likelyFakeRequests` and never listed;
with `--target-key` that count is null, because hourly totals carry no page
path. `cnry traffic sync` reports them as `aiUserFetchLikelyFakeHits`.
Claude-Agent and Google-Agent journeys keep page loads, actions such as form
posts and failed requests only; `coverage.limitations` lists what they leave
out.
The API reports retention, inactivity gap, daily caps and source gaps. Advanced
Properties match the current plan's URL coverage, not the historical user's
intent. Keep its plan revision and unavailable dimensions with the evidence.
HTTP status and paths do not prove a completed purchase, booking or other task.
Stored reads only. Viewers and embeds are denied; API read keys retain project
scope.

### Unrecognized bots and agents

```bash
cnry traffic unrecognized <project> --format json
cnry traffic unrecognized <project> --source <id> --since 2026-10-01 --limit 25
```

Self-identified bots and agents that no rule names yet, summed by the name in
their user agent, busiest first, each with hits, first and last seen hours, an
example user agent and path, and its sources. Default window: the last 30 days.
`--since`/`--until` take inclusive ISO timestamps or `YYYY-MM-DD` dates. Browsers,
generic HTTP tools (curl, python-requests and the like), static files and writes
are left out. Stored rows only, no provider call. Viewers and embeds are denied.
When a new rule recognizes a name, its stored hours move to that bot once the
engine runs the new rules; `cnry backfill traffic-classification` does the same
on demand.

### AI-referred visitor journeys

```bash
cnry journeys summary <project> --since 2026-10-01 --format json
cnry journeys list <project> --engine ChatGPT --returned true --limit 50 --format jsonl
cnry journeys show <project> <visitor-key> --limit 100 --offset 0
cnry journeys show <project> <visitor-key> --events pages   # pages plus every non-GET/HEAD request
```

Follows visitors with at least one AI-referred visit, from that first AI visit
on (earlier visits are not stored), from every traffic source, with no site
setup. `summary` counts AI visitors whose first AI visit
falls in the window (default 30 days), how many came back in a later visit, by
which entry (`ai`, `search`, `social`, `paid`, `referral`, `direct`), and median
days to return. `list` returns those visitors newest first with their first 20
visits (`visitCount` is the total) and marks user-agent-only keys; `show` pages
through one visitor's visits and requests; `--events pages` keeps page
requests plus every request that is not GET or HEAD, while each visit keeps its
stored `requestCount`. A visit ends after 30 idle minutes
or when the visitor arrives again from another outside source; a same-site,
sign-in, payment or booking-engine referer is a step inside the visit.

Visits are stored when they fall within 30 days after one of the visitor's AI visits;
rows are deleted after 180 days. A visitor key is a keyed hash, never an IP.
Sources without an IP (Vercel) key on the user agent only, so people with the
same device and browser version can merge; `keyBasis` says which. Visitor and
return figures count only IP-and-user-agent keys and are null (not measurable)
when there are none; `list` takes `--key-basis ip-ua|ua`. A key stores
at most 300 requests per UTC day besides AI touches; `cappedDays` counts the days it hit
that cap. `partialSources` names sources whose logs miss later visits (the
Cloudflare Worker forwards only AI and bot requests). Query
strings keep only `utm_*`, and path segments that look like secrets (tokens,
UUIDs, emails) are masked. A Cloudflare source records later visits only when
connected with `--forward-page-views` and redeployed; until then it is listed in
`partialSources`. Stored reads only, no provider call. Viewers and embeds cannot
read journeys.

### Stored GA acquisition

```bash
cnry ga acquisition <project> --start 2026-09-01 --end 2026-09-30 --channel "Organic Search" --landing-page /pricing --format json
cnry ga acquisition <project> --group-by source,medium --limit 100 --offset 100 --format jsonl
```

Reads stored GA4 sessions only, with no Google call. `--window 7d|30d|90d|all`
defaults to all history. Use either a rolling window or explicit `--start` and `--end`; combining them is rejected. `--source` and `--medium` match exactly; `--channel` and `--host`
match exactly without case sensitivity. `--landing-page` normalizes the supplied path like stored pages, removing trailing slashes and tracking parameters while retaining meaningful query parameters. `--path-prefix` matches a path or its
descendants, treating percent and underscore literally. Group keys are date,
channel, source, medium, host, landing-page (API names are also accepted). Default
grouping uses all six. `totalSessions` covers every filtered row, independent of
grouping and pagination; `totalRows` counts groups. Maximum page size is 1000.

### Stored read windows and calendar dates

Stored reads accept a positive day count such as `30` or its lowercase token
`30d`, restricted to the command's available stored windows:

| Read | Windows |
| --- | --- |
| Analytics, sources, competitor landscape, GA acquisition, traffic and referral/session histories, Google performance reads | `7d`, `30d`, `90d`, `all` |
| GA measurement analysis | `30d`, `60d`, `90d` |
| GA search landing pages | `7d`, `28d`, `90d`, `180d` |
| Google Ads performance | `7d`, `14d`, `30d` |
| Traffic analytics | `7d`, `14d`, `30d`, `90d` |
| Organic evidence | `60d`, `90d` |

Defaults remain specific to each command. `--help` prints its full set. Traffic
analytics and organic evidence accept `--window`; `--period` remains an alias.
Use either `--window` or explicit calendar bounds, never both.
For reads with calendar bounds, use inclusive `--start` and `--end` in
`YYYY-MM-DD` form. Traffic referral assessment retains `--start-date` and
`--end-date`; ads insights retains `--from` and `--to`. Supplying an alias and its
canonical flag together is an error. Invalid calendar dates or reversed ranges
fail before an API request. Explicit dates retain their existing precedence over
rolling windows. Google performance `--days` remains a separate span selector.
These changes do not alter sync/backfill depths, run/history ISO timestamps, or
calendar-month report selections.

### Applying project configuration

```bash
canonry apply <file...> --dry-run [--format json]
canonry apply <file...> [--format json]
```

`--dry-run` calls the server preview route for every YAML document and reports
field, query, competitor, schedule and notification changes. It performs no
database writes and prints `No DB writes performed. Re-run without --dry-run to
apply.` in text mode. JSON and JSONL emit the same `{ dryRun, files,
changedCount, errorCount }` document. A server without the preview route exits
with `APPLY_PREVIEW_UNSUPPORTED`; the command never falls back to apply.

### Preview competitor impact

Add, remove/delete and curated alias set/add/remove/clear accept `--dry-run`.
JSON and JSONL include `dryRun`, the planned changes and the server's `impact`;
text prints before/after mention share and counts. No competitors, names or
audit rows change. The latest stored landscape is the estimate, while a real
change restates every stored period. Advanced scope includes all markets; the
response names its exact runs and query class. This is not the overview card.

`project update <project> --competitor-auto-aliases apply --dry-run` previews
the mode and detected-name impact. Other change flags are refused. Detection
is a stored read; `competitor aliases detect --dry-run --apply` is invalid.
Block/unblock, market pin writes, project identity edits, apply and discovery
promotion are not covered. Ordinary writes keep their request count and output.
Preview POSTs require a write-capable key; the detection GET accepts read keys.
### Batch curated competitors and wait for stored fields

`canonry competitor import <project> <file> [--wait] [--wait-timeout 120]` sends
one append request for the whole file. A JSON file is an array of domains or
`{ "domain": "rival.example", "aliases": ["Rival Name"] }` entries. Other files
contain one `domain[,alias,alias]` per line; blank lines and `#` comments are
ignored. Import only a curated set, not every cited domain. Repeating an import
is idempotent and reports `addedCount: 0` when nothing is newly tracked.

`competitor add` and `competitor aliases` also accept `--wait` with a positive
integer timeout in seconds (default 120). This waits for stored answer fields
to be recomputed after name changes, such as `competitor add demo rival.example
--alias "Rival Name" --wait`. A bare-domain add sets no recomputation mark.
Answer-derived alias detection has a separate lifecycle and is not covered by
this wait. Cloud already completes the backfill within the write request.

Timeout exits 2 with `OPERATION_IN_PROGRESS` and `writeCommitted: true`; read
`project show` to inspect `answerFieldsRecompute` rather than treating the write
as failed. Older servers that omit the field return `WAIT_STATUS_UNAVAILABLE`
after the committed write. Without `--wait`, add timing and output are unchanged.
The existing `canonry_project_get` MCP tool returns this additive field.
