Canonical Data Model and End-to-End Workflows

1. Modeling rule: one business fact, one canonical home

The implementation must not maintain separate seeded, discovered, and website keyword inventories. That separation forces users to promote/copy records, duplicates metrics, and breaks lineage across buyer discovery and SEO.

Use this pattern instead:

Keyword                         one normalized linguistic concept
  ├── KeywordOrigin[]           where each phrase/evidence came from
  ├── KeywordContext[]          how it is used by product/market/website
  ├── KeywordMetricSnapshot[]   market-specific provider measurements
  ├── RankSnapshot[]            website/market SERP history through context
  ├── DiscoveryQuery[]          buyer searches through context
  └── OpportunityKeyword[]      backlink relationships through context

Seeded, discovered, manual, imported, provider-suggested, and AI-suggested are provenance types. “Active for discovery,” “active for ranking,” and “excluded for this website” are contextual decisions. They are not different keyword entities.

2. Cross-cutting storage conventions

Every mutable entity should have:

Every provider-derived or imported fact should have:

Use UTC in storage and render the operator’s configured timezone. Use decimal/numeric types for monetary cost, CPC, and currency-sensitive values. Never use floating-point values for billed currency.

Use normalized values for matching while preserving display/original values. Normalization must be Unicode-aware, language-preserving, deterministic, and versioned if rules change.

3. Canonical entities

3.1 Workspace and configuration

AppSetting

Settings include public provider mode, budget limits, scoring weights, crawler limits, seed version, retention, and UI defaults. Secrets remain environment-only.

AuditEvent

Audit events are append-only. Redact credentials and sensitive values before persistence.

3.2 Website ingestion

Website

Domain uniqueness should be normalized and case-insensitive.

HTMLDocument

Unique key: (website_id, relative_path).

HTMLDocument is document provenance; keyword occurrences are represented by KeywordOrigin.

3.3 Unified keyword model

Keyword

Canonical linguistic identity only:

Recommended uniqueness: (language_code, normalized) for active canonical rows. If homographs genuinely need separate semantics, model semantic variants explicitly rather than silently duplicating identical keys.

Do not store product, market, website, current metrics, or “seeded/discovered” directly on this row.

KeywordOrigin

Append-only provenance explaining how the keyword entered the system:

Examples:

KeywordAlias

Use aliases for alternate spelling or an intentionally merged display variant. Do not use aliases to collapse different languages or materially different intent phrases.

KeywordContext

This is the operational assignment joining a keyword to some combination of product, market, and website:

At least one of product, market, or website must be present. Business validation:

Use one row when all dimensions match. A website-targeted product keyword can have product + market + website on the same context. If both general product discovery and one website use the term, contexts may share the canonical keyword and metrics without copying the keyword itself.

KeywordTag and KeywordContextTag

Use normalized tag entities and association tables when filtering/exporting tags is important. Canonical tags apply globally; context tags express a local decision.

KeywordDecision

Append-only history of include/exclude/activate/archive/merge/split/assignment decisions:

KeywordMerge

Merge behavior:

  1. Lock both keywords.
  2. Reject cross-language merges unless explicitly overridden with a documented reason.
  3. Move origins and aliases idempotently.
  4. Deduplicate contexts by context key while combining non-conflicting source history.
  5. Repoint metric/rank/discovery/opportunity relationships only where semantics remain valid.
  6. Archive the merged record; never erase the merge ledger.

Split behavior creates a new canonical keyword and moves explicitly selected origins/contexts. It must not duplicate immutable provider snapshots without a recorded decision.

KeywordMetricSnapshot

Immutable provider measurement:

Uniqueness/idempotency may use provider + request + keyword + market. Never overwrite snapshots.

KeywordContextScore

Immutable or versioned calculation linked to a context and usually a metric snapshot:

The current UI view selects the newest valid score. Keeping it outside Keyword prevents a France metric or buyer-intent override from contaminating a US or website-specific use.

3.4 Markets, products, and tariff suggestions

Market

MarketLanguage

Do not hide multilingual markets inside one string column.

Product

ProductName

This normalized table is preferable to unqueryable JSON arrays for a fresh build.

ProductMarket

This is the target-market relationship. Keyword contexts refer to both dimensions but do not replace it.

HSCodeMapping

3.5 Ranking, competitors, backlinks, and opportunities

RankingJob

RankSnapshot

Competitor

Canonical domain identity:

CompetitorAppearance

ExclusionRule

Backlink

BacklinkGap

Opportunity

OpportunityKeyword

This association preserves every keyword relationship while deduplicating the action by exact referring URL.

3.6 Discovery, company evidence, certification, and leads

DiscoveryJob

DiscoveryQuery

No executed query may be untraceable. Fallback queries still store derivation lineage.

Company

Canonical organization identity:

Domain is the strongest normal dedup key. When absent, use normalized legal name + country and flag lower-confidence matches for human review.

CompanySource

Keep every source relationship even after company deduplication.

CompanyCandidate

Unique operational key: (company_id, product_id, market_id) with discovery-job history in a separate observation table if multiple runs must be retained.

CompanyCandidateObservation

This preserves historical changes rather than overwriting the candidate.

CompanyEvidence

Do not flatten certificates into generic evidence.

OrganicCertification

Certification is evidence of certified operations, not automatic importer or buyer proof.

BusinessContact

CompanyLead

LeadMerge

Append-only duplicate merge ledger preserving contacts, sources, candidates, and decisions.

3.7 Jobs, requests, artifacts, schedules, and AI

Job

JobTask

Partial success belongs at task level.

ProviderRequest

Artifact

Schedule

AIAnalysis

4. Unified keyword lifecycle

4.1 Ingestion and resolution

All sources call a single application service, conceptually:

resolve_keyword(
    raw_phrase,
    language,
    origin,
    optional_context,
    normalization_version,
) -> KeywordResolution

Resolution rules:

  1. Validate phrase and language.
  2. Normalize without translating.
  3. Find an active canonical row by language + normalized form.
  4. Create only if none exists.
  5. Attach an idempotent origin even when the keyword already exists.
  6. Attach or update the context without silently changing user decisions.
  7. Flag near-duplicates for review; do not fuzzy-merge automatically.
  8. Emit an audit event for user-visible changes.

Examples:

4.2 Seed generation

For each enabled predefined product-market pair:

  1. Resolve market languages in priority order.
  2. Choose a curated/user-verified product name for that language; otherwise retain the known trade name instead of fabricating a translation.
  3. Combine it with localized organic, supplier, wholesale, bulk, price, importer, distributor, manufacturer, processor, private-label, and buyer-role patterns.
  4. Add English content/backlink hypotheses when appropriate.
  5. Resolve every phrase through the canonical service.
  6. Create a product + market context with predefined=true.
  7. Add the generation rule and catalog version as an origin.

The first implementation should produce the same order of magnitude as the existing reference scope: approximately 73,699 product-market assignments. Test exact deterministic counts for the chosen catalog version.

4.3 HTML extraction

  1. Parse a document safely.
  2. Emit candidate occurrences with evidence.
  3. Resolve each through the canonical service.
  4. Attach an HTML origin.
  5. Attach a website-only proposed context if none exists.
  6. Suggest product/market matches but require user confirmation.
  7. Re-ingestion deactivates vanished occurrence origins rather than deleting keyword history.

4.4 Review and merge

The review queue prioritizes:

No source type is inherently more truthful than verified user judgment. Seeded means predefined, not verified demand.

4.5 Metric enrichment

  1. User selects keyword contexts or a scheduled scope.
  2. Collapse them into unique (keyword_id, market_id) requests so shared contexts do not incur duplicate API cost.
  3. Validate enabled state and batch cap.
  4. Estimate cost and run budget guard.
  5. Group by provider location and language.
  6. Create Job and JobTask records before external calls.
  7. Call KeywordMetricsProvider.
  8. Persist ProviderRequest and permitted raw artifact.
  9. Append KeywordMetricSnapshot rows.
  10. Calculate a KeywordContextScore for every affected active context using its effective intent.
  11. Mark missing provider values null.
  12. Complete, partially complete, cancel, or fail with retained successes.

4.6 Discovery selection

For product + market:

  1. Load active contexts with discovery_enabled=true.
  2. Prefer buyer_discovery and transactional intent.
  3. Order by current value score, evidence/review state, then deterministic phrase order.
  4. Enforce language balance so English does not consume a multilingual market’s full budget.
  5. Deduplicate query strings.
  6. Fill unused query capacity with deterministic fallbacks.
  7. Persist every selected/fallback query before calling search.

4.7 Ranking selection

For website + market:

  1. Load active contexts with ranking_enabled=true.
  2. Validate website ownership/domain and market location mapping.
  3. Collapse duplicate canonical keywords.
  4. Estimate cost.
  5. Persist job scope with exact context IDs.
  6. Run SERP calls and store immutable snapshots.

5. Deterministic scoring

5.1 Keyword value

Keep components 0–100:

value = volume × 0.35 + CPC × 0.25 + intent × 0.25 + attainability × 0.15

Store unrounded components; display one decimal. Clamp only after validating inputs. Missing volume/CPC are not zero measurements; the formula must mark component availability and explain fallback treatment.

5.2 Backlink opportunity

Return four 0–100 scores:

Store provider inputs, normalized components, weights, formula, and score version. Codex can explain but cannot replace calculations.

5.3 Company lead scoring

Initial evidence points:

Signal Points
Exact product match 25
Confirmed importing 20
Organic certification/evidence 15
Wholesale/distribution 10
Processing/manufacturing 8
Private label 7
Bulk/B2B 5
Recent evidence 5
Public commercial contact 5
India sourcing bonus 5

Store separate product relevance, importer evidence, organic relevance, commercial fit, evidence quality, contactability, and optional India sourcing scores.

Classification gates override pure totals:

6. Provider contracts

Application services depend on typed interfaces, not vendor SDKs.

KeywordMetricsProvider

Input: keyword phrases with IDs, location code, language, search engine, device, cancellation token.

Output per keyword: volume, CPC/currency, competition, difficulty, monthly history, provider timestamps, cost, raw-reference policy.

SerpProvider

Input: phrase, location, language, device, depth, owned domain.

Output: ordered typed results including result type, domain, URL, title, snippet, features, retrieval metadata, cost.

BacklinkProvider

Input: owned domain, competitor domains, optional gap/intersection operation, limits.

Output: normalized backlink/referring-domain evidence with provider metrics and timestamps.

OrganicOperatorProvider

Methods include supports_market and discovery by product/category. Output contains source record, company identity, normalized certificate fields, activities, product scope, URLs, and reuse notes.

Initial routing:

WebSearchProvider

Input: persisted query, country/language, result limit.

Initial real providers: Brave default, Tavily optional.

WebsiteEvidenceProvider

Input: official public website, product terms, market languages, limits.

Output: exact evidence records and contacts, not an unsupported company classification.

DirectoryImportProvider

Input: validated local CSV path and market/license metadata.

Output: source/company/certificate/evidence records with row lineage and validation errors.

AIIntelligenceProvider / CodexIntelligenceProvider

Use for keyword clustering/intent suggestions, change explanations, opportunity classification, outreach preparation, product-to-HS suggestions clearly marked unverified, trade summaries, and anomaly explanations.

Requirements:

Every real provider needs a deterministic mock with the same schema. Automated tests must never require paid calls.

7. Client-discovery source and crawler rules

CSV import maximum: 25 MB by default. Require one of company, legal_name, or name. Recommended fields:

legal_name,website,domain,country,role,
source_type,source_url,verification_url,
evidence_type,evidence,confidence,
operator_id,certificate_number,control_body,control_body_code,
certification_status,valid_from,valid_until,
activities,product_categories,products,certificate_url,reuse_notes

Use | for list values. A CSV row is a source relationship, not automatic importer proof.

Crawler guardrails:

8. Exports and traceability joins

Provide CSV exports for:

Filtered Keyword export should optionally flatten canonical phrase + origins + product/market/website context + latest metrics for operator convenience. The database remains normalized.

Minimum trace paths:

Lead
 → CompanyCandidate
 → CompanyEvidence / OrganicCertification / CompanySource
 → DiscoveryJob → DiscoveryQuery
 → KeywordContext → Keyword
 → Product + Market
 → ProviderRequest / Job
Opportunity
 → OpportunityKeyword
 → KeywordContext → Keyword
 → RankSnapshot → CompetitorAppearance
 → BacklinkGap → Backlink
 → Website + Market
 → ProviderRequest / Job
Keyword
 → KeywordOrigin (seed, HTML, manual, provider, AI)
 → KeywordContext (product, market, website, workflow flags)
 → KeywordMetricSnapshot (keyword + market)
 → KeywordContextScore

9. Deletion, archive, and retention rules

10. Data invariants to test

  1. One active canonical keyword per normalized phrase + language.
  2. Every keyword has at least one origin.
  3. Every keyword context points to the same canonical keyword; no copied phrase entity exists.
  4. Context keys are unique across SQLite and PostgreSQL.
  5. Discovery-enabled contexts have product + market.
  6. Ranking-enabled contexts have website + market.
  7. Metrics are market-scoped immutable snapshots.
  8. Scores reference their inputs and score version.
  9. Rank snapshots and discovery queries reference exact keyword contexts.
  10. Merge preserves origins, decisions, histories, and a merge ledger.
  11. Seed upgrades preserve user modifications and snapshot IDs.
  12. Missing provider measurements remain null.
  13. A certificate alone never creates importer evidence.
  14. Verified Importer cannot exist without exact-product and confirmed-importing evidence.
  15. Public contact values require source URL and verification time.
  16. Every external result has provider/import lineage and retrieval time.
  17. Every mock result is synthetic.
  18. Costs use decimals and estimated cost never overwrites actual cost.
  19. No secret appears in stored request JSON, errors, logs, exports, or rendered HTML.