canonry

Data Model

Source of truth: packages/db/src/schema.ts

Entity Relationships

erDiagram
  runtime_logs {
    integer sequence PK
    text ts
    text actor
    text requestId
    text context
  }
  runtime_log_metadata {
    text id PK
    text cursorNamespace
    integer nextSequence
    integer captureErrors
    integer dropped
  }
  projects ||--o{ queries : has
  projects ||--o{ competitors : has
  projects ||--o{ runs : has
  projects ||--o| measurement_plans : "activates"
  projects ||--o{ measurement_plan_versions : "publishes"
  projects ||--o{ measurement_segments : "identifies"
  measurement_plan_versions ||--o{ runs : "optionally pins"
  projects ||--o{ schedules : has
  projects ||--o{ notifications : has
  notifications ||--o{ review_webhook_deliveries : delivers
  projects ||--o{ audit_log : has
  projects ||--o{ insights : has
  projects ||--o{ health_snapshots : has
  projects ||--o{ social_mentions : "monitors"
  runs ||--o{ social_mentions : finds
  projects ||--o{ social_connections : "authenticates"

  projects ||--o| sentiment_settings : "opts in"
  runs ||--o{ sentiment_completion_receipts : "durably completes"
  sentiment_definitions ||--o{ sentiment_jobs : "freezes evaluator"
  projects ||--o{ sentiment_jobs : "admits"
  sentiment_jobs ||--o{ sentiment_job_items : "selects"
  sentiment_work_items ||--o{ sentiment_job_items : "shares assessment"
  query_snapshots ||--o{ sentiment_work_items : "assesses subjects"
  sentiment_work_items ||--o| sentiment_results : "stores once"
  sentiment_work_items ||--o{ sentiment_attempts : "records dispatches"
  runs ||--o| sentiment_alert_runs : "alerted once"

  runs ||--o{ query_snapshots : contains
  runs ||--o{ run_fills : "completed by"
  runs ||--o{ provider_batches : "dispatches"
  provider_batches ||--o{ provider_batch_requests : "maps custom_id to slot"
  provider_batches ||--o{ query_snapshots : "recorded"
  runs ||--o{ insights : "analyzed in"
  runs ||--o{ health_snapshots : "scored in"
  queries ||--o{ query_snapshots : "tracked in"

  runs ||--o| site_crawl_run_requests : "freezes request identity"
  runs ||--o{ site_crawl_attempts : "executes"
  runs ||--o| site_crawl_snapshots : "publishes"
  site_crawl_attempts ||--o| site_crawl_graph_layouts : "publishes derived layout"
  site_crawl_attempts ||--o{ site_crawl_pages : "observes"
  site_crawl_attempts ||--o{ site_crawl_edges : "observes"
  site_crawl_graph_layouts ||--o{ site_crawl_graph_nodes : "positions sampled pages"
  site_crawl_graph_layouts ||--o{ site_crawl_graph_edges : "samples rendered edges"
  site_crawl_attempts ||--o{ site_crawl_findings : "derives"
  site_crawl_attempts ||--o{ site_crawl_event_receipts : "checkpoints"

  projects ||--o| ga_connections : "has (1:1)"
  projects ||--o{ ga_traffic_snapshots : has
  projects ||--o{ ga_daily_totals : has
  projects ||--o{ ga_window_metrics : has
  projects ||--o{ ga_traffic_summaries : has
  projects ||--o{ ga_ai_referrals : has
  projects ||--o{ ga_social_referrals : has
  projects ||--o{ ga_search_landing_windows : has
  projects ||--o{ ga_search_landing_pages : has

  projects ||--o{ gbp_locations : has
  projects ||--o{ gbp_daily_metrics : has
  projects ||--o{ gbp_keyword_impressions : has
  projects ||--o{ gbp_keyword_monthly : has
  projects ||--o{ gbp_place_actions : has
  projects ||--o{ gbp_lodging_snapshots : has
  projects ||--o{ gbp_attributes_snapshots : has
  projects ||--o{ gbp_place_details : has
  projects ||--o{ gbp_reviews : has
  projects ||--o{ gbp_review_ratings : has
  projects ||--o| gbp_review_settings : has

  projects ||--o{ gsc_search_data : has
  projects ||--o{ gsc_daily_totals : has
  projects ||--o{ gsc_query_daily_totals : has
  projects ||--o{ gsc_url_inspections : has
  projects ||--o{ gsc_coverage_snapshots : has

  projects ||--o{ bing_url_inspections : has
  projects ||--o{ bing_keyword_stats : has
  projects ||--o{ bing_coverage_snapshots : has

  projects ||--o{ traffic_sources : has
  traffic_sources ||--o{ traffic_event_receipts : deduplicates
  traffic_sources ||--o{ crawler_events_hourly : "rolls up"
  traffic_sources ||--o{ ai_user_fetch_events_hourly : "rolls up"
  traffic_sources ||--o{ ai_referral_events_hourly : "rolls up"
  traffic_sources ||--o{ ai_referral_visitors : "remembers arrivals"
  traffic_sources ||--o{ raw_event_samples : "samples"
  projects ||--o{ journey_visitors : has
  traffic_sources ||--o{ journey_visits : "sessionizes"
  journey_visits ||--o{ journey_events : contains

  projects ||--o| agent_sessions : "active conversation"
  projects ||--o{ agent_conversations : "saved conversations"
  projects ||--o{ agent_memory : has

  projects ||--o{ discovery_sessions : has
  discovery_sessions ||--o{ discovery_probes : contains
  projects ||--o{ research_runs : has
  research_runs ||--o{ research_run_queries : contains
  users ||--o{ api_keys : delegates
  users ||--o| user_external_identities : "signs in with"
  users ||--o| chatgpt_plan_connections : "funds Aero with"
  user_external_identities ||--o| chatgpt_plan_connections : grants
  users ||--o{ user_invitations : accepted
  api_keys ||--o{ dashboard_sessions : authenticates

Table Groups

Core Domain

Table Purpose Key Constraints
projects Root entity: domain, location config, provider list, aliases, qualified_aliases (JSON: the operator-chosen subset of aliases that Simple sentiment tells its evaluator are the brand’s own names; frozen into each Simple run’s sidecar, never read by mention detection), per-project provider_models overrides, provider_dispatch_modes (JSON: provider → sync/batch, read by scheduled sweeps only), measurement_config (JSON: marketing hosts, brand terms, and GA4 lead-event names), optional icp_description (free-text ICP used by discovery seed phase), nullable site_audit_max_pages (migration 169: the Agent Readiness page budget for scans that set none, 1 to 50,000; null means the full site), site_audit_domains (migration 219, JSON NOT NULL DEFAULT []: owned domains every Agent Readiness scan covers besides the main domain, as bare hosts; each is one of owned_domains, and a write that stops owning one drops it), competitor_auto_aliases (migration 171, NOT NULL DEFAULT preview: what the unattended answer-derived competitor alias pass does, queued after a completed or partial sweep, a competitor add, an unblock or a market pin write that changes pins: off runs no pass, preview logs and stores nothing, apply stores the names; an explicit apply-now stores in every mode), nullable answer_fields_recompute (migration 171: full or competitors while a recompute of the stored answer fields queued after an identity change is unfinished; the local server requeues it on boot), social_platforms (migration 225, JSON string[], NOT NULL DEFAULT []: the social platforms the project monitors; every existing project reads []) Unique: name
queries Tracked queries per project. provenance tags where the entry came from (e.g. cli, discovery:<session_id>) so adopted basket entries can be traced back to a discovery run. Unique: (projectId, query)
competitors Competitor domains per project. provenance tags origin (cli, discovery:<session_id>) for the same traceability reason. aliases (JSON string[], migration 168, default []) holds operator-curated names the competitor goes by in answer text; every competitor mention matcher layers them onto the domain label, and a Simple run freezes them into its definition. Never auto-filled from the domain label. auto_aliases (JSON, migration 171, default []) holds names detected automatically from the project’s own stored answers, each with its evidence (CompetitorAutoAlias: direct pairs, co-occurrences, naming answers, precision, lift, answers writing it as a name, distinct sweeps (runs), first and last seen, when applied); auto_aliases are stored only by a detection pass that applies (the project’s competitor_auto_aliases is apply, or an explicit apply-now). blocked_aliases (JSON string[], migration 171) holds names the operator blocked from that detection; removing the competitor keeps them on market_competitor_names, and a new row for the same domain starts with them. Readers match curated plus auto names minus blocked ones (competitorIdentityAliases); curated identity always wins a conflict. Every competitor list read orders by domain. Unique: (projectId, domain)
market_competitor_names Answer-derived names of a competitor an Advanced market pins without a competitors row (migration 172): domain (registrable), auto_aliases and blocked_aliases as on competitors. Published plan revisions are immutable, so readers that score a market answer against live identity layer these onto the pin (readMarketCompetitorNames); a new pin by domain never copies them. A row also keeps the blocked names of a removed project competitor (with auto_aliases [] when it had no learned names), which a re-added or promoted competitor starts with: a row holding only blocked names is not empty and must be kept. Unique: (projectId, domain)
measurement_plans Optional active-plan pointer for a project. PK: projectId; composite FK (projectId, activeVersionId) → plan version
measurement_plan_versions Immutable canonical Target-model revisions. A revision freezes project brand identity, Targets, optional reporting groups, URL matchers, query snapshots, deduplicated execution nodes with expected snapshot counts, and baseline/Target usage edges. Groups never own queries or execution edges. Unique: (projectId, revision)
measurement_segments Stable project-local identity for a Target or group, including its immutable kind. Only explicit retirement permanently prevents key reuse; omission from a revision does not. First publish a revision without the key, then run canonry measurement-plan retire <project> <stable-key> (or the matching API/MCP mutation). Retirement is idempotent and irreversible. Labels, memberships, aliases, and URL matchers remain versioned in canonical plan JSON. Unique: (projectId, stableKey)
runs Existing sweep executions. A run queued for a project with an active plan pins measurement_plan_version_id and freezes its execution graph, provider list, and any group/target scope in measurement_manifest; planless runs keep both null. provider_dispatch_modes freezes which providers go to a batch API (null = all sync); pending_provider_errors holds sync-provider errors while finalization waits on a batch; skipped_providers (nullable JSON, migration 175) freezes the providers the run does not call because each keeps failing on its account, with the streak that decided it (null = none skipped); provider_failures (nullable JSON, migration 216) records each engine’s failures so far while a sweep runs (first reason, failed queries, whether the sweep stopped calling it), read on the run detail only while the run is active; planned_answers (nullable integer, migration 217) is the number of answers an answer-visibility sweep set out to collect, written by the job runner when the sweep starts from its actual work list (every query times every engine it calls, or a published plan’s slots for those engines; skipped or unreachable engines left out), read as plannedAnswers on the run detail and as progress.answersPlanned on GET /projects/:name/setup, and null before the sweep starts and on older runs. FK: projectId → projects; optional composite FK (projectId, measurementPlanVersionId) → plan version
query_snapshots Per-query per-provider results. citation_state is cited, not-cited, or not-measured (the engine returns no sources, such as a local model; never a miss). Older Local rows hold not-cited (or, before #871, a cited taken from answer text); read every row through readCitationState (contracts), which reads every Local row, and any not-cited with retrieval_status = 'not-applicable', as not measured without rewriting them. A row written by a plan-aware run also records measurement_execution_id, the requested_context it was measured under, and supported_context — filled only when the provider actually forwards the location, null otherwise. Historical and planless rows keep all three null. dispatch_mode (sync/batch), provider_batch_id, stop_reason, and usage (tokens, searches, estimated cost) are null on rows that predate batch dispatch. mention_identity (wrong-subject or null) and wrong_subject_target_keys (JSON Property stable keys or null) cache sentiment’s identity verdicts (migration 185): a Simple answer judged wrong-subject has answer_mentioned false, and an Advanced report drops the listed Properties’ mentions of the answer (docs/sentiment.md). FK: runId → runs, queryId → queries, providerBatchId → provider_batches (SET NULL, indexed)
run_fills One attempt to complete a partial plan run in place; its answers land in the parent run’s own snapshot rows. Composite FK (projectId, runId) → runs
provider_batches One batch submitted to a provider’s asynchronous batch API for a run (see docs/batch-mode.md). Written as submitting before the submit call; carries the provider’s batch id, status, counts, deadline, and the stored daily-quota reservation. Composite FK (projectId, runId) → runs (CASCADE); indexes on status, run_id
provider_batch_requests Maps each batch line’s short custom_id (the row id) to its slot: execution id, query, requested model and location, and the ingest outcome. FK: batchId → provider_batches (CASCADE), queryId → queries (SET NULL, indexed); unique (batchId, executionId)
research_runs Saved batch header for ad-hoc model research. Isolated from tracked monitoring; initiatedBy records the account or API key that started new runs. Historical rows can be null. FK: projectId → projects, unique (projectId, idempotencyKey)
research_run_queries One persisted answer/evidence result per research batch query. FK: researchRunId → research_runs, unique (researchRunId, position)
schedules One schedule per project and run kind. Each row stores timing, timezone, and enablement. Unique: (projectId, kind)
notifications Alert configurations per project FK: projectId → projects
review_webhook_deliveries One durable delivery per negative-review event and destination (v189), empty on upgrade. state is pending, attempting, sent, uncertain (a chat send that got no answer, never resent), failed (refused, or out of retries) or canceled; retry_at is when a pending delivery is next due. An engine timer drains due rows every minute. FK: projectId → projects, notificationId → notifications; unique (project_id, notification_id, event_id)
audit_log Change tracking. Authenticated actor plus nullable credentialId and requestId; client/session hints are not identity. Credential IDs remain after key deletion. FK: projectId → projects (optional)

research_runs and research_run_queries are the durable ad-hoc research history. They are deliberately not linked to queries, runs, or query_snapshots: a research request never changes the tracked basket or any monitoring metric. New run headers preserve initiating-principal attribution; rows created before that field was introduced remain unattributed. Deleting a project cascades to its research runs, and deleting a research run cascades to its query results.

Simple projects can run without a published plan. The measurement compiler deduplicates execution nodes that share query text and context. Target assignments point to those nodes. Groups derive their reporting edges from member Target assignments. When the queue creates a plan-aware run, it pins the published revision and freezes the run manifest. Historical reads retain that execution context after the active plan or tracked queries change.

Agent Readiness Crawl Persistence

Migration 126 adds the local full-crawl graph beside the legacy site_audit_snapshots and site_audit_pages scorecard tables. Migration 127 adds the separately persisted Agent Readiness visualization projection: a publication-time Graphology ForceAtlas2 worker lays out a deterministic bounded sample (at most 20,000 nodes and 50,000 edges). Coordinates never alter the canonical crawl inventory or run in the browser. A new layout seeds surviving node keys from the prior complete, compatible layout so rescans preserve the operator’s spatial frame while newly discovered pages receive deterministic hash seeds. Migration 128 preserves both the operator-requested crawl root and the effective root followed after a supported host redirect. It also indexes both graph-edge endpoints so derived-layout cleanup stays bounded. Migration 131 separates nav, header, and footer links from content links. A (target page, normalized anchor) pair carried by at least 70 percent of the scan’s fetched pages is template chrome; on real sites that distribution is bimodal, so the threshold sits in an empty middle. A stored link row aggregates EVERY anchor the crawl saw between the same two pages, so migration 133 corrects which anchor decides: chrome only when every anchor on the row is ubiquitous. Migration 131 used the most ubiquitous one, which handed an in-prose link that shared a row with a footer link to the same target the footer’s ratio and hid it. Any site with a comprehensive footer had this, so 133 re-runs the same backfill to reclassify every stored scan. Template links are excluded from the ForceAtlas2 physics, so positions describe content structure, but they are still published in the sample and tagged, so a viewer can draw them without a refetch and without any page moving. Below 15 fetched pages nothing is marked and the snapshot records unavailable-too-few-pages, because on a site that small every link looks ubiquitous. The backfill classifies every stored scan from rows the crawl already persisted; it deliberately does not rewrite immutable layout coordinates, and those rows keep template_links_excluded = 0 so the map can say their positions predate the split. Migration 138 replaces the rule for every NEW scan. The crawler (audit engine 4.7.0+) reports where each link occurrence sat, from the page’s own landmarks, and those three counts are stored per link beside the landmark ruleset version on the snapshot. Any content occurrence makes a link editorial, navigation with no content occurrence makes it chrome, and unknown carries no evidence, so a link the page said nothing about falls back to ubiquity where the scan is large enough. Where it is not, the link is still a content link (is_template is a strict boolean on every classified row, so the layout input, the graph sample, both link filters, the totals, and the map all keep ONE definition of a content link) and templateSource reports unmeasured so a consumer can subtract it. Ubiquity keys on (target URL, anchor text), so it cannot see an editorial link whose anchor text matches the nav’s, which is the common case because good anchor text reuses the destination’s name: 53 editorial links added to canonry.ai moved the measured content-link count by zero. Migration 138 adds only columns and backfills NOTHING, because a crawl captured before the ruleset existed never observed placement and any value written for it would be invented; those scans keep their ubiquity classification and a NULL ruleset version, which is what makes reads report applied rather than applied-placement. Which rule produced a scan’s numbers is reported by template_detection (applied, applied-placement, applied-placement-with-ubiquity, applied-placement-partial) and per link by the derived templateSource, so no count mixes the two rules silently. Changing which links reach the ForceAtlas2 input changes positions, so the layout algorithm moved to site-health-fa2-v5 and v4 coordinates are not reused as seeds.

Table Purpose Key Constraints
site_crawl_run_requests Canonical effective options and identity for a queued crawl. Its stored maxPages option is the resolved budget: the request’s, else the project’s site_audit_max_pages, else the full site. Its sites (identity schema 4) are the extra owned domains it covers: the request’s, else the project’s site_audit_domains. Identical requests may reuse one active run; different options receive a conflict. PK: runId; composite FK (projectId, runId) → runs
site_crawl_attempts Mutable event-stream progress for one execution attempt. Unique: (runId, attemptNumber); composite FK to runs
site_crawl_snapshots Immutable terminal crawl metadata, including the requested root, effective root, which rule classified the links (template_detection; NULL means a scan published before it existed), and the crawler landmark ruleset behind that rule (link_placement_ruleset_version; NULL means the scan recorded no placement and can never be reclassified), and sites (migration 219: every site the scan covered, main domain first, with page counts, score and why a site was not reached; NULL means a scan made before, of the main domain only). Default reads select the newest snapshot of a completed or partial (budget-capped) run; any older run stays selectable by ID. Unique: runId; composite FK to runs and attempt
site_crawl_pages URL inventory with discovery provenance, fetch/indexability state, depth, internal-link counts, and link score. site (migration 219) is the bare host of another owned site the scan covered; NULL is the main domain, which is every row of an older scan. path never carries a host. Unique: (projectId, runId, attemptId, nodeKey)
site_crawl_edges Bounded typed link observations with occurrence, followability, anchor summaries, the crawler placement split (placement_navigation_occurrences / placement_content_occurrences / placement_unknown_occurrences; all NULL means the scan recorded none, which is different from all zero), and the template-link decision (is_template plus the template_ratio that the ubiquity fallback produced). NULL is_template means never classified, never “not a nav link”. Unique: (projectId, runId, attemptId, edgeKey)
site_crawl_graph_layouts One immutable derived-layout status per crawl attempt, with version, failure code, source totals (including the template-link share), sampled counts, and whether template links were kept out of the physics. Absent means a pre-v127 snapshot; unavailable means layout could not safely publish and does not invalidate the crawl. Unique: (projectId, runId, attemptId)
site_crawl_graph_nodes The bounded, ranked subset of canonical pages rendered by the Agent Readiness map, carrying only persisted finite x/y coordinates. Unique: (projectId, runId, attemptId, nodeKey) and (projectId, runId, attemptId, sampleRank)
site_crawl_graph_edges Exact bounded, ranked canonical-edge subset used for both ForceAtlas2 and the WebGL renderer, each carrying its template-link flag; both endpoints reference persisted graph nodes. Template links stay in the sample so the map can draw them without a refetch. Unique: (projectId, runId, attemptId, edgeKey) and (projectId, runId, attemptId, sampleRank)
site_crawl_findings Deterministic crawl findings. Dead-link rows exist only when that run opted in. Unique: (projectId, runId, attemptId, findingKey)
site_crawl_event_receipts Idempotency receipts for streamed page, edge, metric, progress, and summary batches. Unique: (attemptId, sequence, batchId)

All detail rows carry the project, run, and attempt tuple. Composite foreign keys prevent data from crossing project or attempt boundaries. The mutable attempt is not the current graph; only a complete terminal snapshot is the default current graph. An explicitly selected partial terminal snapshot remains inspectable. Layout failure, timeout, empty crawl, or absence on a legacy snapshot is exposed as a truthful unavailable graph state; it never makes a successful crawl fail or causes the UI to recompute positions.

Agent reads use the canonical site_crawl_pages and site_crawl_edges rows, not the sampled visualization tables. A bounded semantic subgraph exposes the same page state, crawl depth, importance, and link evidence that the operator can inspect. Path reads follow persisted internal links. Run-change reads compare two immutable complete snapshots by stable page and edge identity at query time; ForceAtlas2 coordinates are never considered a website change.

Migration 180 adds nullable site_crawl_snapshots.issue_evidence, a versioned record of the crawler’s cross-page findings. NULL means the scan did not record that source; an envelope with an empty siteIssues list means no groups were observed within that scan’s coverage. Existing scans are not backfilled. Duplicate metadata groups retain sorted, distinct affected URLs. Their stable keys use the full exact trimmed metadata value, issue code and identity version, so a changing page count or a truncated display message cannot change identity. If the original metadata cannot establish that identity, the group survives with a null key. Stored issue reads combine these groups with recorded page findings, independently of the score, and expose source coverage and pagination. The existing page/link comparison does not establish issue resolution.

projects.provider_models

projects.provider_models is a JSON map of provider name to a model ID used for future sweeps. {} inherits the instance-level provider settings. It is not historical attribution — for that, see the two model columns on query_snapshots below.

query_snapshots.model vs served_model

Every snapshot records two model strings, and they answer different questions:

Column Meaning
model What we requested — the configured model ID resolved at sweep time.
served_model What the provider reported serving, read back off its own response. Nullable.

model is not the source of truth for model continuity or trend interpretation. It records our request, not the model that produced the answer, and the two diverge routinely: every OpenAI row in production requested gpt-5.4 and was served the dated snapshot gpt-5.4-2026-03-05. Attribute a change in answers to served_model; use model only to describe configuration.

Compare served_model at top-level granularity for attribution. A dated snapshot is the same model for our purposes, so gpt-5.4 → gpt-5.4-2026-03-05 is not a model change, while gpt-5.6 → gpt-5.6-sol is (a tier suffix is a different model at a different price). Comparing the raw strings would also manufacture a fake model change at every provider deploy boundary.

Known gaps — served_model is nullable because absence is common and honest:

Never fall back to model when served_model is NULL — that would launder a configuration value into an observation. Treat NULL as unknown.

Integrations — Google

Table Purpose
google_connections OAuth credentials, domain-scoped. Unique: (domain, connectionType)
gsc_search_data GSC search analytics data synced per run (query × page × country × device × date)
gsc_daily_totals GSC property-level daily totals (no query/page dimensions). Headline clicks/impressions/CTR/position + daily trend source. Unique: (project_id, date)
gsc_query_daily_totals Per-QUERY daily totals fetched with dimensions: ['date','query'] (no page). Summing gsc_search_data by query fans one SERP into one row per ranking page, inflating impressions ~0% for single-page queries but ~500% for terms where several pages rank together. Complete for queries Google NAMES; anonymized rare queries are still absent, so it does not sum to the property total. Unique: (project_id, date, query)
gsc_url_inspections URL inspection results from GSC
gsc_coverage_snapshots Index coverage snapshots from GSC. indexed / not_indexed / unknown_pages are three distinct states — a page with no impressions and no inspection is UNKNOWN, never not-indexed. verified_by_inspection / derived_from_impressions record how much of the number is a real Google verdict versus derived free from search analytics.

Integrations — Bing

Table Purpose
bing_connections API credentials, domain-scoped. Unique: domain
bing_url_inspections URL inspection results from Bing
bing_keyword_stats Keyword performance data from Bing
bing_coverage_snapshots Bing index coverage snapshots

Integrations — Google Analytics

Each project syncs data from one GA4 property. Sync coverage and Search Console landing-page windows record the property ID with the data. When a connection change moves a project to another property or removes its property, Canonry clears its sync data and state (packages/api-routes/src/ga-property-data.ts). The next sync backfills acquisition and lead events in full.

Table Purpose
ga_connections GA4 property connection (1:1 with project)
ga_traffic_snapshots Per-page daily traffic snapshots. Includes sessions, organic_sessions, and direct_sessions (nullable; populated by GA4 sync) — supports per-channel landing-page breakdowns.
ga_daily_totals GA4 property totals by date. GA4 deduplicates users within each date. SUM(users) over ga_traffic_snapshots overcounts visitors who land on multiple pages. v116 adds nullable engagement_rate and new_users. v188 adds nullable active_users, organic_sessions, views, event_count, key_events, engagement_seconds, and bounce_rate. The sync plans 360 complete days plus the current day in the property’s reporting time zone. It replaces the date ranges that the coverage plan requests. Unique key (project_id, date).
ga_sync_coverage Successful sync dates by project and report component, including dates with no rows. Canonry reuses older coverage for the same property and report definition for 30 days. Each sync refreshes the latest 14 days in scope. Primary key (project_id, component, date).
ga_window_metrics GA4 totals for each overview window (7d / 30d / 90d / 180d) and the preceding period of equal length. Both use complete days in the property’s reporting time zone. Each sync replaces the current and previous rows together (v188). GA4 computes distinct users and rates over each whole period. Figures are nullable because GA4 can return no row for a period. Unique key (project_id, window_key, period).
ga_traffic_summaries Aggregated traffic summaries
ga_ai_referrals AI engine referral tracking. traffic_class splits paid AI traffic (paid/cpc/sponsored UTM values or GA4 paid channel groups, including tagged ChatGPT ads) from organic/non-paid AI referrals. Unique: (projectId, date, source, medium, sourceDimension, channelGroup, landingPage)
ga_social_referrals Social media referral tracking. Unique: (projectId, date, source, medium, channelGroup)
ga_acquisition_daily GA4 session acquisition rows at (project, date, channel group, source, medium, host, landing page) grain. landing_page_normalized supports page rollups; sessions are non-negative.
ga_lead_events_daily GA4 configured lead-event counts at acquisition dimensions plus event_name and attribution_scope. Scope is landing-page or channel; counts are non-negative, and the full grain is unique.
ga_measurement_sync_state One per-project status row for the acquisition, lead and Search Console landing-page components. Acquisition and leads are never-synced, ready, or error, with their error/timestamp; lead scope is nullable until a lead sync establishes landing-page or channel. The landing-page component (v176, defaulted columns search_landing_status / _error / _synced_at / _attempted_at) adds unavailable (GA4 refused the Search Console metrics); synced_at is when the stored snapshot was written and attempted_at the last try, so a failed try keeps the old snapshot and its time. lead_event_names is the event set the last lead sync counted (a changed set refreshes the full GA4 window), key_event_names the property’s key events from the last successful Admin API read, and key_events_error the latest failed read (v194).
ga_search_landing_windows GA4’s “Google organic search traffic: Landing page + query string” report (Search Console link). Each window (7d / 28d / 90d / 180d) ends yesterday in the property’s reporting time zone. The row records the property ID, date range, time zone, GA4’s TOTAL row, row count, and cap and data-quality flags. CTR and position are null when GA4 reports zero impressions. The sync can reuse fresh windows with identical request definitions. A failed sync keeps the last successful snapshot for the same property. Unique key (project_id, window_key).
ga_search_landing_pages One landing page of one window of that report: GA4’s raw landingPagePlusQueryString in landing_page (never normalized), clicks, impressions, ctr (0..1) and average_position (both null with no impressions), active_users (GA4’s plain activeUsers). At most 10,000 rows per window, the most clicks, then impressions, first. Unique: (project_id, window_key, landing_page)

Integrations — Google Business Profile

Local-AEO signals. The OAuth connection reuses google_connections with connectionType = 'gbp'. All surface tables are scoped to the project’s selected locations.

Table Purpose
gbp_locations Discovered locations per project; selected flags which feed sync + analytics. place_id / maps_uri (from location metadata) link a location to the Places API. reviews_access / reviews_access_reason / reviews_checked_at record the last v4 reviews attempt (ok, unavailable with Google’s reason such as SERVICE_DISABLED, or error). FK: projectId → projects
gbp_daily_metrics Daily performance metrics per (location, date, metric). Range-replaced each sync.
gbp_keyword_impressions Search-keyword impressions over the trailing synced window (one aggregate per keyword; period_start/period_end are YYYY-MM). Range-replaced each sync. Unique: (projectId, locationName, periodEnd, keyword)
gbp_keyword_monthly Per-month keyword impressions series — accumulates across syncs (recent complete months upserted, older in-retention months preserved) so intelligence can detect month-over-month keyword drops. Unique: (projectId, locationName, month, keyword)
gbp_place_actions Booking / reservation / order CTAs per location (provider_type MERCHANT = direct, AGGREGATOR = OTA). Range-replaced each sync.
gbp_lodging_snapshots Hotel Lodging API resource, snapshot-on-change. populated_group_count = 0 means the Lodging API returned no readable structured groups; live testing found this can happen even when the owner-facing “Hotel details” panel has amenities set, so it is a verify signal, not a confirmed gap.
gbp_attributes_snapshots Owner-set Business Profile attributes (Business Information API getAttributes), snapshot-on-change. The generic, any-category amenity / service / accessibility / identity / social-URL tags the owner has set (e.g. has_onsite_services, offers_online_estimates, is_owned_by_women, url_instagram). attribute_count is the count of set attributes (the API returns only set ones), so unlike lodging this is a reliable owner-readable completeness signal. Works for every business type, not just hotels.
gbp_place_details Places (New) rendered-listing snapshots (amenities, accessibility, editorial summary) for lodging locations, fetched via the Places API key and snapshot-on-changed. tier records the field-mask SKU. Cross-referenced against the lodging profile for the gbp-listing-discrepancy insight (#648).
gbp_reviews One row per review per origin: gbp (Business Profile v4, every review) or places (public listing, at most five by relevance). Upserted on (project_id, origin, review_name); timestamps normalized to millisecond ISO. alert_state (none, baseline, stale, pending, sent, skipped, suppressed) is the review.negative webhook queue.
gbp_review_settings Per-project review alert settings: negative_review_max_stars, the highest star rating that counts as negative for review.negative (1-4). A row exists only while a project overrides the default of 3; served as ProjectDto.negativeReviewMaxStars. Kept off projects so the root table stays unchanged. PK and cascade FK: project_id.
gbp_review_ratings Average rating and review count per location and origin, snapshot-on-change (observed_at re-stamped when unchanged), with the replaced values in previous_*. The first row per location and origin is the baseline marker for review alerts; a falling Places rating queues review.rating-dropped through alert_state.

Integrations — OpenAI Ads (ChatGPT ads)

Table Purpose
ads_connections One OpenAI ad-account connection per project (ad accounts are not domain-bound, so this keys on project like ga_connections). Metadata + sync state only — the Ads Manager “SDK key” lives in ~/.canonry/config.yaml. Each sync records the account’s brand-review status plus integrity-review status and decision. conversion_tracking_configured is derived from whether any synced campaign carries a conversion-event setting.
ads_operations Durable receipts for upstream mutations. Unique (project_id, operation_key) plus a canonical request hash prevents duplicate sends and detects key reuse with a different request. Each new receipt is bound to the live-verified ad_account_id; legacy unbound receipts and receipts presented under another account remain unresolved. State is pending, reconciling, succeeded, failed, or unknown; ambiguous outcomes are reconciled by reading a checkpointed provider ID and are never resolved by retrying the original mutation. reconcile_strategy is the closed known_entity, create_fingerprint, or manual_only policy; an uncheckpointed create stays unknown because mutable-field equality cannot prove provenance. reconcile_parent_id independently binds a parented create and reconcile_fingerprint hashes the provider-visible safe-field projection actually compared during recovery. Attempt timestamps and an expiring worker lease support a five-attempt exponential-backoff policy; exhausted receipts remain visible as unknown with ADS_RECONCILIATION_QUARANTINED but are never reclaimed again. Stores sanitized error metadata and verification inputs, never the SDK key, URLs, or raw request payload.
ads_activation_grants Short-lived human approvals for one exact campaign tree. The row binds the canonical manifest hash and JSON, project, advertiser account, approver key, distinct executor key, expiry, lifecycle state, and the single activation operation that consumed it. Revocation is allowed only before execution. No provider credential or creative payload is stored.
ads_operation_steps Durable child checkpoints for a grant-bound campaign-tree activation. Each ordered campaign, ad-group, or ad step records the approved upstream timestamp, execution/rollback state, verified provider timestamp, and sanitized remediation text. These checkpoints let a replay inspect an ambiguous step without blindly resending activation and preserve the ads-first / groups-second / campaign-last execution order.
ads_campaigns Campaign snapshots, range-replaced per project on every ads-sync. Includes description, flight dates, upstream lifecycle timestamps, budgets in integer micros, the closed bidding_type vocabulary (impressions or clicks), attached conversion_event_setting_ids, and raw upstream targeting (the API projects location IDs). Ids are upstream ids (cmpn_…).
ads_ad_groups Ad-group snapshots incl. description, upstream lifecycle timestamps, and the closed billing_event_type vocabulary (impression or click). context_hints (JSON string[]) is the targeting primitive — entries are multi-line strings of newline-separated example queries; the paid/organic overlap matcher joins these against tracked queries. Cascades off ads_campaigns.
ads_ads Ad snapshots with the chat_card creative JSON and review status. Cascades off ads_ad_groups.
ads_insights_daily Daily paid-performance rollups, one row per (level, entity, date). spend_micros is integer micros — the upstream insights API returns decimal dollars, normalized at ingest. conversions is the integer conversion count (0 when the account has no conversion tracking). Derived ratios (ctr/cpc) computed at read time. Upserts on conflict so re-syncing an in-progress day replaces.

Server-Side Traffic Ingestion

Table Purpose
traffic_sources Per-connection metadata for Cloud Run, WordPress, Vercel, and Cloudflare. Status connected / paused / error / archived. Pull credentials, Cloudflare direct-push secrets, and Queue API tokens live in ~/.canonry/config.yaml, never here; push sources store only a bearer digest. Queue pull adds nullable owner/expiry fields for one durable source-scoped sync lease, including stale-owner recovery, plus the last observed residual Queue depth and observation time so a bounded drain cannot hide remaining work. ai_referral_older_count_until (v211) marks when a source’s AI-referral hours stopped being counted by the pre-v207 rule, which also counted a visitor’s later requests; NULL for sources with no such hours. A one-time startup recount rebuilds the hours AI visitor journeys cover (Cloudflare and Cloud Run sources only) and moves the mark back to where journeys began. ai_user_fetch_older_count_until (v222) is the exclusive end of the last hour whose hosted browser agent (Google-Agent, Claude-Agent) AI user fetches the source counted under older rules, which counted every file, data call and beacon their pages made (high) or sent whole visits to the likely fake counts (low); from it on, those agents count their page loads only. Set by v222 and the stored traffic pass, moved back or cleared by a replace-mode backfill; NULL for sources with no such hours. FK: projectId → projects.
traffic_event_receipts Durable transport-neutral idempotency claims keyed by (source_id, event_id). A push receiver or buffered pull consumer claims the event in the same transaction as its rollup writes, then acknowledges upstream only after commit. expires_at lets each delivery mode retain claims for its full replay/redelivery horizon: direct push keeps them 10 minutes; Queue pull keeps them for the Queue’s live retention (read from Cloudflare each sync) plus 10 minutes, or 14 days plus 10 minutes when that read fails. FK: sourceId → traffic_sources (cascade).
crawler_events_hourly Hourly rollup of server-observed bulk crawler hits (GPTBot, OAI-SearchBot, PerplexityBot, Googlebot, etc.). Composite PK (projectId, sourceId, tsHour, botId, verificationStatus, pathNormalized, status) so repeat syncs upsert via hits + ?. Excludes the per-user-fetch UAs — those land in ai_user_fetch_events_hourly.
ai_user_fetch_events_hourly Hourly rollup of on-demand per-user fetches from AI surfaces (ChatGPT-User, Perplexity-User, MistralAI-User). UA-evidenced like a crawler, but each hit was initiated by a real user inside an AI surface — kept disjoint from crawler_events_hourly so dashboard / API totals don’t conflate machine crawl with human-in-the-loop fetch. Composite PK matches crawler_events_hourly.
ai_referral_events_hourly Hourly rollup of server-observed human AI-referral clicks (UTM or referer evidence). Composite PK matches the crawler bucket pattern. paid_sessions_or_hits / organic_sessions_or_hits split sessions_or_hits by traffic class; unclassified is the residual sessions_or_hits - paid - organic. The split rides the measure (not the PK) because the paid marker lives in the query string that landing_path_normalized strips, so one bucket can hold both classes. Rows written before the ingest classifier (both counters 0) surface as unclassified rather than organic. Counts are arrivals: a later page, asset or API call that carries the landing page’s utm on a same-site referer is not counted again (hours before 7.87.2 did count it, about once per minute of a visit, and cannot be corrected).
ai_referral_visitors Each visitor’s recent AI-referral arrivals per source and engine, so ingest does not count a later request of the same visit as another arrival when it lands in a later or older batch. visitor_key is an HMAC (the install’s journeys secret) over project, source, IP, user agent and engine; no address is stored, and nothing is stored without the secret. arrivals (JSON, oldest first, at most 50) marks each arrival that a same-site request stood in for; writes merge into it and last_arrival_at is the newest. Rows are dropped 44 days after it. PK: (project_id, source_id, visitor_key). FK: sourceId → traffic_sources (cascade).
unrecognized_agent_events_hourly Hourly hits per bot or agent name no classifier rule recognized, PK (projectId, sourceId, tsHour, agentName), with the latest user agent and path as a sample. When a rule later recognizes a name, its hours move into crawler_events_hourly or ai_user_fetch_events_hourly as claimed hits with the path (path not recorded) and status 0.
traffic_reclassification_state One row (id = 'default'): the fingerprint of the traffic classification rules (bot rules, Canonry’s own tools, unrecognized-agent naming, agent trust, journey and browser-agent request rules) that stored traffic was last reclassified under, with the completion time and a summary. A canonry serve server compares it shortly after startup and reclassifies stored traffic once per change, including crawler hours whose sampled user agent today’s rules file elsewhere (another crawler rule, the AI user fetch counts, the unrecognized agents, or nowhere for Canonry’s own tools); the Cloud Run app (apps/api) does not. The summary also records the browser-agent request rules the pass ran under (browserAgentRequestRules: version and bot ids); when they differ or are missing, the pass marks every source holding browser-agent hours in traffic_sources.ai_user_fetch_older_count_until.
unrecognized_agent_notify_state One row per unrecognized agent name a project has decided on for the traffic.agent.discovered alert, PK (projectId, agentName): sent (a webhook accepted it), skipped (nothing subscribed), stale (first seen before the 7-day window) or baseline (first seen in the project’s first 7 days of recorded traffic). Each name alerts at most once.
raw_event_samples Bounded sample tail for classifier debugging. Source writes reject already-expired samples and prune source-local rows; a startup and daily global sweep removes expired rows from dormant sources. Timestamps are canonical UTC, and the 30-day boundary is inclusive. FK: sourceId → traffic_sources.
journey_visitors AI visitor journeys: one row per keyed visitor with at least one AI-referred visit, followed from that first AI visit (earlier visits are not stored). visitor_key is an HMAC (the install’s journeys.visitorKeySecret, kept in config.yaml, never here) over project, key basis, IP and user agent; key_basis is ip-ua, or ua for sources with no IP (Vercel), which can merge people on the same device and browser version. No IP is stored. Holds the full user_agent, first_ai_at/first_ai_engine, last_ai_at and last_seen_at (writes only widen these bounds), and capped_days, the UTC days on which the key reached the 300-requests-per-day cap (a set, so replays never count twice; AI touches are always stored). PK: (project_id, visitor_key). FK: projectId → projects (cascade).
journey_visitor_aliases A visitor key that ingest found to be another visitor seen from a new IP (iCloud Private Relay, a mobile network): its first request loaded the same AI-tagged page as that visitor, with the same browser, within 5 seconds. Requests under alias_key are kept under visitor_key; both are keyed hashes, never an IP. Journey retention drops a row once its visitor is gone. PK: (project_id, alias_key). FK: projectId → projects (cascade).
journey_visits 30-minute visits of those visitors: requests within 30 days after an AI visit, and the rest of a visit already kept. A late request that becomes a visit’s first rewrites its landing_path and entry. entry_class is ai / search / social / paid / referral / direct, with entry_name, entry_host, paid, landing_path, request_count and page_count. A request from a different outside source starts a new visit; a same-site, sign-in, payment or booking-engine referer is a step inside one. A background data call never opens a visit or becomes its first request. FK: sourceId → traffic_sources (cascade).
journey_events The requests in each visit: time, method, path (query cut to utm_*, secret-like segments such as tokens, UUIDs and emails masked), status, kind (page, or data for JSON and API calls) and ai_touch (the request started or renewed the lookback; only page requests are AI touches). Visit times and counts are recomputed from these rows after every write. Unique (project_id, source_id, source_event_id) makes every traffic write path idempotent. Journey rows are deleted 180 days after their time by the daily traffic sweep, which also removes visitors left with no visits. FK: visitId → journey_visits (cascade).

Sentiment

Table Purpose
sentiment_definitions Immutable evaluator content, content hash, and requested Jev model. A source answer changes assessment identity without changing the reusable definition.
sentiment_settings Default-off project opt-in, effective sentiment enablement configuration, enablement epoch, completion-sequence boundary, reconcile cursor, round-robin dispatch turn, and persisted install suspension. No credentials.
sentiment_completion_receipts Monotonic AUTOINCREMENT completion order, including fills. Enablement uses the sequence high-water mark, which survives source deletion.
sentiment_jobs / sentiment_job_items Project/action/idempotency-key admissions and frozen selections. Per-selection cancellation remains visible when a later explicit backfill reuses the assessment. Jobs keep incremental member counts by dispatch state.
sentiment_work_items One leased work identity per project, snapshot, source-text hash, subject hash, and evaluator definition. Exact frozen inputs and usage edges, durable retry time, attempt count, and dispatch priority (automatic before backfill); indexed by (run_id, snapshot_id) for snapshot cascades.
sentiment_results One stored result per assessment work item. Composite foreign keys prevent cross-project source/result links and cascade evidence cleanup with source deletion.
sentiment_attempts Each external dispatch, requested/returned model, reported or unknown usage, safe failure, and estimated rate-limit tokens. Reported tokens also enter llm_usage_events as provider typesafe. Result uniqueness does not guarantee exactly-once remote billing after a crash.
sentiment_alert_runs One row per sweep a project has decided on for the sentiment.unfavorable alert (migration 224), PK (projectId, runId), both cascading: sent (a webhook accepted it), skipped (nothing subscribed), quiet (no answer newly unfavorable) or baseline (settled before the project’s first alert pass). Written only by Notifier.dispatchSentimentAlerts once the sweep’s automatic sentiment jobs have no pending, retrying or running assessment, the worker has admitted every class of its newest completion receipt (sentiment_settings.reconciled_sequence), and every earlier sweep has settled. A sweep no webhook accepted, or one read while sentiment is off, has no row and is retried while its jobs are under 7 days old.
sentiment_dispatch_state One install-wide row: the provider rate-limit or credential pause, next dispatch time, rate-limit streak and a one-way credential fingerprint (never the key).

Sentiment JSON columns use native Drizzle JSON mode. Provider calls run outside database transactions. Migration 164 creates the tables, supporting composite indexes, and an immutable-definition update trigger; it does not enable projects or admit historical work.

Social Monitoring

Table Purpose
social_mentions One social post a social monitoring run found (migration 225), with columns named after contracts SocialMentionResult: platform, the platform’s post id and URL, matched_query (the search term that found it; null for a post found by a domain-only search, never an invented query), author, title and text, linked_urls (the project URLs the post links to; link data, not a mention), nullable sentiment, likes/shares/comments, community (a subreddit on Reddit), hashtags and metadata (platform-specific fields such as a platform score). Author, follower and engagement fields are null when the platform does not expose them, never zero. Unique: (projectId, platform, externalId), so each project keeps its own copy of a post. FK: projectId → projects (cascade); (projectId, runId) → runs(project_id, id) (cascade; the pair must match). No tracked-query link: it is deferred until a caller needs one, and then needs a key that checks the query belongs to the same project
social_connections Which social platforms a project has connected (migration 225): token_expires_at, scopes and metadata only. SQLite holds connection metadata only; secrets live in ~/.canonry/config.yaml per root AGENTS.md “Authentication Storage”: install-level app credentials once per platform (SocialMonitorConfig in contracts) and, for platforms that authorize per project, project-level grants keyed by projectId (SocialMonitorProjectGrant in contracts), the same two levels as GoogleAdsConfigEntry and its connections[] in packages/canonry/src/config.ts. Unique: (platform, projectId). FK: projectId → projects (cascade)

Intelligence

Table Purpose
insights Per-run analysis insights (regressions, gains). FK: projectId → projects, runId → runs
health_snapshots Per-run mention and citation health. Mention rates use all pairs. Citation rates exclude pairs whose sources the adapter cannot measure. FK: projectId → projects, runId → runs

System

Table Purpose
api_keys API authentication. Unique: keyHash. Internal nullable delegatedUserId → users (cascade delete) preserves OAuth account authority and research attribution across the MCP-to-REST hop; ordinary/historical keys remain null.
dashboard_sessions Durable shared-password/API-key browser sessions (migration 173). PK: SHA-256 token digest; FK: apiKeyId → api_keys (cascade delete). Fixed twelve-hour expiry, indexed by key and expiry. Migration 174 adds apiKeyHash and nullable passwordFingerprint to bind the credential used at sign-in. Rotation/revocation deletes bound sessions transactionally; native startup removes sessions with missing or outdated password bindings. Named-account sessions remain in user_sessions.
usage_counters Rate limiting and usage tracking. Unique: (scope, period, metric)
provider_connection_tests The latest provider connection test per connection (migration 215; PK: provider, the connection name; no foreign key, since connections live in config.yaml). Holds the result as returned (status, redacted message, model, checkedAt, durationMs) and fingerprint, a keyed HMAC of the registration the test checked (key, endpoint, model, CDP endpoint, Vertex settings), never a credential. A connection’s lastTest reads the row only while its active registration still matches the fingerprint, so a changed key or endpoint hides it while a restart or an unchanged reload keeps it; disconnecting deletes it.
doctor_health_state Health alert bookkeeping, one row per project (PK: projectId → projects, cascade delete). Holds the last scheduled doctor pass (status, headline code, failingSignature as sorted status:code pairs, and since migration 178 failingChecks, the same set as status:code:id) and the last alert a webhook accepted (notifiedAt, and notifiedSignature since migration 177, also status:code:id). Migration 179 adds nullable pendingSignature: triggering breaches owed by an unaccepted degraded alert, separate from the delivered set so quiet clearances and recurrences cannot erase retries. Pending triggers are stored before delivery, survive restarts, and stop retrying when they clear, ease or become superseded; accepted delivery clears them. The notifier compares checks by id to alert only on new or worse results, and uses the last delivered set to list what cleared. Internal only: the live report is GET /projects/:name/doctor.
site_health_notify_state Site Health alert bookkeeping, one row per project (migration 214; PK: projectId → projects, cascade delete). reportedKeys is the sorted set of critical page problems the site-health.issue.new webhook already reported, as defectId|page with the page as the first 16 hex characters of the SHA-256 of its URL; runId is the audit last applied. Written only by Notifier.onSiteAuditCompleted: after a subscriber accepts an alert (so a refused one is owed after the next audit) and when a complete scan no longer finds a problem (so a comeback is reported). A partial scan only adds. No row while no webhook lists the event. Internal only: the live list is GET /projects/:name/technical-aeo/issues.
runtime_logs Sanitized runtime messages and allowlisted metadata, queried with indexed identity/time filters and opaque keyset cursors. Default retention: 10,000 events/seven days. Separate from business audit history; logs contain no raw HTTP bodies, headers, or provider payloads.
runtime_log_metadata Store identity, sequence, and eviction accounting for restart-safe pagination and honest retention/loss reporting. Runtime diagnostic data is bounded; audit history is not pruned by this policy.
oauth_clients OAuth 2.1 clients for the remote MCP surface. registration records how one came to exist: operator (created deliberately) or dynamic (registered itself over the open RFC 7591 endpoint and chose its own display name, so the consent screen marks that name unverified). secretHash is NULL for a public client authenticating by PKCE alone. redirectUris is an exact-match allowlist, except that RFC 8252 s7.3 lets the PORT float for loopback redirects so a native app can bind an ephemeral one. Revoking a client also revokes its outstanding tokens
oauth_authorization_codes Single-use authorization codes, 60s TTL, bound to their PKCE challenge and RFC 8707 resource. Key is the SHA-256 of the code. Burned on first redemption even when that attempt fails, so a wrong verifier cannot be retried. FK: clientId → oauth_clients, userId → users
oauth_grants Durable identity of one authorization and its rotated token family. Revocation covers all access/refresh tokens and delegated MCP keys for that grant. Migration 199 groups historical tokens only within the same user, client, audience and scope because historical rotations stored no lineage. It removes only tokens with a missing client or user, and retires old mcp-session:<delegatedUserId> keys plus unbound keys under the reserved mcp-session: namespace and their dashboard sessions; clients reinitialize with preserved OAuth tokens. Ordinary keys outside that namespace and Aero viewer keys survive. FK: clientId → oauth_clients, userId → users
oauth_tokens Issued access and refresh tokens, stored as SHA-256 digests for the same reason user_sessions stores one: the row records that a token exists, it is not a way to become it. resource is the audience and is enforced on every resource request. Refresh tokens rotate atomically and retain grantId; revoking a valid token revokes its entire family. Explicit revocation of a stale token is a no-op; authenticated reuse of a consumed refresh token at the token endpoint revokes the active family. FK: grantId → oauth_grants, clientId → oauth_clients, userId → users
user_external_identities Sign in with ChatGPT identities linked to accounts (migration 220). Unique: (issuer, client_id, subject), so a new OAuth client ID starts new links; and (user_id, provider), one ChatGPT identity per account. email is display only and never decides which account an identity signs in to. FK: userId → users (cascade)
user_invitations Email invitations to sign in with ChatGPT. email_key is the trimmed lower-cased address a VERIFIED ChatGPT email is matched against; the first match creates the account with role and sets accepted_at / accepted_user_id. Expires after 14 days; re-inviting revokes the pending row. Never attaches to an existing account. FKs: created_by_id, accepted_user_id → users (set null)
chatgpt_plan_connections One person’s ChatGPT plan grant for their own Aero turns. PK user_id; id is new on every connect. tokens is AES-256-GCM ciphertext under chatgpt.tokenKey with the connection id and account as associated data, the one credential kept in the database (per person, rotated hourly); scopes is what OpenAI granted. Refresh is compare-and-swap on revision. status is connected or reconnect-required. FKs: user_id → users, identity_id → user_external_identities (cascade)
chatgpt_login_transactions In-flight ChatGPT sign-ins, single use, ten minutes. Holds digests of the OAuth state and of the browser-binding secret only; the PKCE verifier stays in the browser’s HttpOnly cookie. intent is login or connect (with the signed-in user_id)

Health notification migration 183 adds nullable native JSON urgentReceipts to doctor_health_state and site_liveness_state. Each notification id stores its URL and outstanding breach signature or outage timestamp. These histories separate new destinations from receivers that already heard an alert. Legacy urgentNotified and urgentNotifiedAt remain aggregate summaries. Older rows without recipient identity establish no receipt, and changed aggregate summaries invalidate histories left behind by an older writer.

Agent

Table Purpose
agent_sessions One active operator Aero conversation per project. Durable half of the hybrid session registry — stores transcript, queued follow-ups, and chosen provider/model so a live pi-agent-core Agent can be rehydrated after a restart. Unique: projectId. FK: projectId → projects
agent_provider_cooldowns Install-wide Aero automatic-work holds shared across projects and restarts. Primary key is a provider/credential digest. Stores a safe auth/billing reason, expiry and unique failure identity, so an older in-flight success cannot clear a newer failure. No credentials or raw provider text. The providers API exposes only reason, retry time and recovery instructions.
agent_conversations Archived operator Aero conversations. Stores title, transcript, prompt snapshot, model, pending follow-ups, and timestamps. New/resume swaps with the active slot in one transaction. llm_usage_events and agent_tool_events keep the conversation id through new, resume and archive (a plain column since migration 165, because the id moves between the two tables); deleting a conversation clears it. FK: projectId → projects
agent_memory Project-scoped durable notes written by Aero (remember), the operator (CLI / API), or the compaction summarizer. Shared notes and only the active conversation’s compaction summaries hydrate its system prompt under <memory>. Keys starting with compaction: are reserved for summarized transcript slices. Unique: (projectId, key). FK: projectId → projects

Discovery (three-ring model)

Table Purpose
discovery_sessions One row per canonry discover run invocation. Captures the research artifact for a session: ICP snapshot, seed/dedup/probe phase counts, bucket counts (cited / aspirational / wasted-surface), competitor_map as a JSON array of {domain, hits} entries (default '[]'), a nullable warning (non-fatal operator flag, e.g. the seed-dedup degenerate-collapse guard), and the nullable seed-source diagnostics seed_from_answer_count / seed_from_grounding_count, seed_brand_filtered_count (split of raw seed candidates by origin — answer text vs. grounding fan-out — recorded at seed time; null on legacy sessions, consumed by no gate). Status flows queued → seeding → probing → completed (or failed). FK: projectId → projects
discovery_probes One row per (session × candidate query) probe. Stores the query text (free-form — not promoted to queries until the operator adopts it), citation_state, cited_domains, answer_mentioned (the answer-text mention signal, independent of citation; nullable for legacy rows), bucket classification, and raw provider response. Gemini executes the probes. The bucket uses cited domains, and answer_mentioned remains a separate signal. FK: sessionId → discovery_sessions, projectId → projects
research_runs / research_run_queries Saved, isolated free-form research batches. Each result stores the answer, source links, cited domains, answer-text named competitors, and cited competitor domains as separate signals. They never create tracked queries, shared runs, snapshots, insights, notifications, or schedules.

Content

Table Purpose
content_target_dismissals Per-recommendation “mark addressed” records. Content-target reads filter out any target_ref present here. List, dismiss, and restore records through the content API, CLI, or MCP. Unique: (projectId, targetRef). FK: projectId → projects
recommendation_explanations Cached LLM prose rationale (“Why this?”) for a content recommendation. Keyed by prompt version so a template bump invalidates forward. Unique: (projectId, targetRef, promptVersion). FK: projectId → projects
recommendation_briefs Cached LLM structured content brief (brief JSON column: {targetQuery, winnabilityClass, angle, whyWinnable, schemaHookup, controllableSurfaceRationale}). Separate table from recommendation_explanations so the structured payload and its version-keyed cache never collide with the prompt-version-blind explanation lookup. Gated to ownable targets. Unique: (projectId, targetRef, promptVersion). FK: projectId → projects
domain_classifications Durable per-domain cited-surface classification (competitorType) accumulated from discovery completions, upserted last-write-wins. Powers the deterministic winnabilityClass gate on content targets without re-running discovery. Unique: (projectId, domain). FK: projectId → projects

JSON Columns

Several text columns store serialized JSON. Always use parseJsonColumn() from @canonry/canonry-db:

Table.Column Expected Shape
projects.locations LocationContext[]
projects.providers string[]
projects.tags string[]
projects.labels Record<string, string>
projects.ownedDomains string[]
measurement_plan_versions.canonicalJson MeasurementPlan (native mode: 'json')
runs.measurementManifest MeasurementRunManifest (native mode: 'json')
runs.providerDispatchModes Record<provider, 'batch'> (native mode: 'json'; null = every provider sync)
runs.pendingProviderErrors Record<provider, message> (native mode: 'json')
runs.providerFailures Record<provider, RunProviderFailure> (native mode: 'json')
projects.providerDispatchModes ProviderDispatchModesMap (native mode: 'json')
competitors.aliases string[] (native mode: 'json'; normalized by normalizeCompetitorAliases)
competitors.autoAliases CompetitorAutoAlias[] (native mode: 'json'; written by api-routes/src/competitor-auto-aliases.ts, pruned by competitor-writes.ts)
competitors.blockedAliases string[] (native mode: 'json'; compared by brand key)
market_competitor_names.autoAliases CompetitorAutoAlias[] (native mode: 'json'; written by api-routes/src/competitor-auto-aliases.ts and the block routes)
market_competitor_names.blockedAliases string[] (native mode: 'json'; compared by brand key)
query_snapshots.usage SnapshotUsage (native mode: 'json')
provider_batch_requests.requestedContext LocationContext (native mode: 'json')
query_snapshots.citedDomains string[]
query_snapshots.groundingSources GroundingSource[]
query_snapshots.competitorOverlap string[] (legacy mixed mention/citation evidence; never a metric source by itself)
query_snapshots.wrongSubjectTargetKeys string[] or null (Advanced Properties sentiment judged wrong-subject for the answer)
insights.recommendation { action: string; detail?: string }
insights.cause { category: string; detail?: string }
health_snapshots.providerBreakdown Record<string, { citedRate: number \| null; mentionRate: number; cited: number; mentioned: number; total: number; citationNotMeasured?: number }>. citedRate is cited / (total - citationNotMeasured), null when none of the engine’s pairs carried sources. Older snapshots lack the mention fields and citationNotMeasured; the API reads them as 0.
discovery_sessions.competitorMap Array<{ domain: string; hits: number; competitorType: DiscoveryCompetitorType }>
discovery_probes.citedDomains string[]
research_run_queries.namedCompetitors string[]
research_run_queries.citedCompetitorDomains string[]
projects.socialPlatforms SocialMonitorPlatform[] (native mode: 'json')
social_mentions.linkedUrls string[] (native mode: 'json')
social_mentions.hashtags string[] (native mode: 'json')
social_mentions.metadata Record<string, unknown> (native mode: 'json'; platform-specific fields)
social_connections.scopes string[] (native mode: 'json')
social_connections.metadata Record<string, unknown> (native mode: 'json')
recommendation_briefs.brief ContentBriefDto (native mode: 'json', not via parseJsonColumn)

Conventions