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:
- Integer or UUID primary key.
created_at and updated_at in UTC.
- Optional
archived_at rather than destructive deletion when history exists.
- Optimistic concurrency/version field for high-contention edits if needed.
Every provider-derived or imported fact should have:
- Source/provider identifier.
- Provider request or import-batch lineage.
- Retrieval time.
- Source URL or permitted artifact reference when available.
- Synthetic flag.
- Verification state.
- Confidence only when its meaning is defined.
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
key unique.
value_json without secrets.
updated_by when authentication exists.
updated_at.
Settings include public provider mode, budget limits, scoring weights, crawler limits, seed version, retention, and UI defaults. Secrets remain environment-only.
AuditEvent
entity_type, entity_id.
action.
before_json, after_json.
metadata_json.
actor or local-user marker.
job_id when system-driven.
created_at.
Audit events are append-only. Redact credentials and sensitive values before persistence.
3.2 Website ingestion
Website
- Domain and normalized domain.
- Brand and preferred URL.
- Default language.
- Target country/market hints.
- Explicit local HTML root.
- Notes.
- Active/archived and synthetic flags.
Domain uniqueness should be normalized and case-insensitive.
HTMLDocument
website_id.
- Root-relative path, never an untrusted absolute output path.
- Content hash.
- Title, meta description, legacy meta keywords.
- Canonical URL.
- Headings JSON.
- Truncated visible body text.
- Internal links JSON.
- Image-alt JSON.
- Structured-data JSON.
- File size and modified time.
- Parsed/retrieved time and parser version.
- Active/missing state for re-ingestion.
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:
phrase — current preferred display phrase.
normalized — deterministic matching value.
language_code.
default_intent — informational, navigational, commercial, transactional, buyer_discovery, or linkable_content.
keyword_type — head, supplier, wholesale, bulk, price, certification, importer, distributor, manufacturer, processor, private_label, content, backlink, custom, or extensible equivalent.
normalization_version.
review_state — needs_review, reviewed, disputed.
active and archived_at.
synthetic only for purely synthetic demo records.
- Optional canonical notes.
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:
keyword_id.
origin_type: reference_seed, html_extraction, manual, csv_import, provider_suggestion, codex_suggestion, discovery_fallback, or migration.
source_entity_type and source_entity_id.
raw_phrase and normalized raw phrase.
- Optional
html_document_id.
- Optional file-relative path and HTML element.
- Evidence snippet.
- Extraction/generation reason.
- Frequency.
- Confidence.
- Source URL.
- Provider request/import batch/job lineage.
- Catalog/template version.
- Retrieved/observed time.
active for source disappearance tracking.
synthetic.
- Deterministic
origin_fingerprint for idempotency.
Examples:
- Seed generation attaches one origin with product definition, market profile, language, rule, and catalog version.
- HTML extraction attaches one origin per document/element/evidence fingerprint.
- A user entry attaches a manual origin even when it matches an existing keyword.
- Codex suggestions remain
codex_suggestion and needs_review; they never masquerade as provider facts.
KeywordAlias
keyword_id.
- Alias phrase, normalized value, and language.
- Alias reason.
- Source/origin link.
- Active state.
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:
keyword_id.
- Optional
product_id.
- Optional
market_id.
- Optional
website_id.
- Required stable
context_key, generated from explicit IDs, for cross-database uniqueness. Example: k:42|p:7|m:12|w:0.
- Optional context-specific intent/type override.
status: proposed, active, excluded, archived.
discovery_enabled.
ranking_enabled.
backlink_enabled.
content_enabled.
selected_by and selection time.
- Tags and user notes through normalized tables where practical.
- Priority override, if any, stored separately from deterministic score.
predefined and user_modified.
- Catalog version for generated assignments.
- Created/updated/archived times.
At least one of product, market, or website must be present. Business validation:
- Discovery requires product + market and
discovery_enabled=true.
- Ranking requires website + market and
ranking_enabled=true.
- Backlink analysis requires website + market plus prior ranking/competitor lineage.
- An HTML-discovered phrase may begin with website only, then receive market/product assignments after review.
- A seeded phrase normally begins with product + market.
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:
- Keyword and optional context.
- Decision and reason.
- Actor.
- Before/after state.
- Created time.
KeywordMerge
survivor_keyword_id.
merged_keyword_id.
- Reason and actor.
- Mapping of moved origins, aliases, contexts, and conflict decisions.
- Created time.
Merge behavior:
- Lock both keywords.
- Reject cross-language merges unless explicitly overridden with a documented reason.
- Move origins and aliases idempotently.
- Deduplicate contexts by context key while combining non-conflicting source history.
- Repoint metric/rank/discovery/opportunity relationships only where semantics remain valid.
- 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:
keyword_id.
market_id.
provider_request_id.
- Provider and endpoint.
- Search engine, location code, and language code.
- Search volume.
- CPC and currency.
- Competition label/index.
- Keyword difficulty.
- Monthly searches JSON or normalized child rows.
- Retrieval time.
- Provider timestamp when available.
- Raw artifact reference when permitted.
- Synthetic flag.
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:
keyword_context_id.
- Optional
metric_snapshot_id.
- Volume, CPC, intent, and attainability components.
- Final value score.
- Formula/weights JSON.
- Score version.
- Calculated time.
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
- Name, country, ISO code.
- Search engine.
- Provider location code.
- Device.
- Currency.
- Optional region/city/timezone.
- Active, predefined, archived.
MarketLanguage
market_id, language_code.
- Priority/order.
- Enabled.
- Query-pack version.
- Optional notes.
Do not hide multilingual markets inside one string column.
Product
- Stable catalog code.
- Canonical name.
- Organic flag.
- Category and commodity type.
- Description.
- Forms, grades, applications.
- Certifications.
- Origin country.
- Storage/shelf-life/regulatory notes.
- Active, predefined, synthetic, archived.
ProductName
product_id.
- Phrase.
- Language.
- Name type: canonical, alias, local_name, scientific_name, trade_name.
- Source and verification state.
- Active.
This normalized table is preferable to unqueryable JSON arrays for a fresh build.
ProductMarket
- Product and market.
- Enabled/disabled.
- Commercial priority.
- Notes.
- Created/updated times.
This is the target-market relationship. Keyword contexts refer to both dimensions but do not replace it.
HSCodeMapping
product_id.
- HS code and nomenclature version.
- Description.
- Destination market when subdivision-specific.
- Source URL/reference.
- Verification state: needs_verification, verified_by_user, rejected, superseded.
- Verified by/time and notes.
3.5 Ranking, competitors, backlinks, and opportunities
RankingJob
- Parent
job_id.
- Website and market.
- Selected keyword-context IDs.
- Search engine/device/location snapshot.
- Requested time.
RankSnapshot
- Ranking job and
keyword_context_id.
- Owned rank nullable when absent.
- Ranking URL, title, snippet.
- Search features JSON.
- Result-page depth checked.
- Provider request and retrieval time.
- Synthetic flag.
Competitor
Canonical domain identity:
- Normalized domain.
- Display domain/name.
- Marketplace/directory/social flags when known.
- Active and notes.
CompetitorAppearance
- Rank snapshot or ranking job.
- Keyword context and market.
- Competitor.
- Organic position, URL, title, snippet.
- First/last observed.
- Eligibility decision and exclusion reason.
- Provider request.
ExclusionRule
- Pattern/domain/category.
- Scope: global, website, market, or job type.
- Reason.
- Active.
- Created/updated by.
Backlink
- Provider-stable identity when available.
- Referring domain and URL.
- Target domain and URL.
- Anchor and surrounding evidence when licensed.
- Link type/attributes/follow state.
- First/last seen.
- Language/country.
- Domain/page/traffic metrics.
- Spam/risk signals.
- Provider timestamps and request.
BacklinkGap
- Job, website, market, and competitor scope.
- Owned-domain presence/absence.
- Calculation version.
- Created time.
Opportunity
- Canonical referring URL/domain.
- Opportunity type.
- Suggested target page/topic/anchor direction.
- Likely contact/submission route supported by evidence.
- Quality, relevance, attainability, priority.
- Components/weights/version.
- Verification state.
- Status, owner, notes, next action date.
- Source provider and retrieval time.
- Synthetic flag.
OpportunityKeyword
- Opportunity.
- Keyword context.
- Source competitor.
- Gap/backlink evidence relationship.
This association preserves every keyword relationship while deduplicating the action by exact referring URL.
3.6 Discovery, company evidence, certification, and leads
DiscoveryJob
- Parent job.
- Product and market.
- Selected keyword-context IDs.
- Query/language/provider plan snapshot.
- Candidate and crawler limits.
DiscoveryQuery
- Discovery job.
- Optional keyword-context ID.
- Query text and language.
- Derivation type/rule when it is a fallback.
- Product and market.
- Provider request.
- Result count and created time.
No executed query may be untraceable. Fallback queries still store derivation lineage.
Company
Canonical organization identity:
- Legal name and normalized legal name.
- Trading names.
- Official normalized domain.
- Country and public business location.
- Website.
- Active/merged state.
Domain is the strongest normal dedup key. When absent, use normalized legal name + country and flag lower-confidence matches for human review.
CompanySource
- Company.
- Provider/source type.
- Source record identifier.
- Exact source/verification URL.
- Import batch/provider request.
- Retrieval time.
- Reuse/licensing notes.
- Raw artifact reference when permitted.
- Synthetic flag.
Keep every source relationship even after company deduplication.
CompanyCandidate
- Discovery job, company, product, and market.
- Classification.
- Total score and tier.
- Separate product relevance, importer evidence, organic relevance, buyer fit, evidence quality, contactability, and India-sourcing components.
- Scoring version/components.
- Verification state and reviewer.
- Status and created/updated times.
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
- Candidate, discovery job, observed classification/score.
- Evidence set hash.
- Freshness.
- Created time.
This preserves historical changes rather than overwriting the candidate.
CompanyEvidence
- Company and optional candidate.
- Evidence type: exact_product, related_category, confirmed_importing, importer_role, wholesale_distribution, processing_manufacturing, packaging, private_label, bulk_b2b, organic, india_sourcing, business_contact, or other.
- Exact URL and page title.
- Quotation-sized snippet.
- Source type and source relationship.
- Language and country.
- Retrieval/observed time.
- Confidence.
- Verification state and reviewer/time.
- Product-context flag proving the evidence applies to the selected product/category.
- Provider request/crawl job.
- Synthetic flag.
Do not flatten certificates into generic evidence.
OrganicCertification
- Company.
- Operator ID and certificate number.
- Control body name/code.
- Status.
- Valid-from and valid-until.
- Activities.
- Product scopes/categories.
- Certificate URL and registry URL.
- Market/country.
- Source and retrieved time.
- Verification/reuse notes.
Certification is evidence of certified operations, not automatic importer or buyer proof.
BusinessContact
- Company.
- Contact type and value.
- Department/role, not inferred personal identity.
- Exact public source URL.
- Verification date/state.
- Lawful-use notes.
- Active/obsolete.
CompanyLead
- Company and source candidate.
- Product and market.
- Status, owner, notes, next action date.
- Qualification snapshot.
- Created/updated times.
LeadMerge
Append-only duplicate merge ledger preserving contacts, sources, candidates, and decisions.
3.7 Jobs, requests, artifacts, schedules, and AI
Job
- Kind and status.
- Input JSON using IDs and safe parameters, never credentials.
- Output summary JSON.
- Estimated and actual cost.
- Currency.
- Queued/started/finished/cancelled times.
- Parent/retry job ID.
- Progress counters.
- Redacted error summary.
- Synthetic.
JobTask
- Job.
- Stable idempotency key.
- Scope/entity identifiers.
- Status, attempts, progress.
- Estimated/actual cost.
- Started/finished times.
- Redacted error.
Partial success belongs at task level.
ProviderRequest
- Job/task.
- Provider and operation.
- Redacted request parameters.
- Response status/HTTP status.
- Attempt number.
- Started/finished/duration.
- Estimated and actual cost.
- Currency.
- Rows/items returned.
- Rate-limit metadata.
- Error category and redacted message.
- Raw artifact reference when license permits.
- Synthetic.
Artifact
- Logical type.
- Local relative path or encrypted reference.
- Content hash, size, MIME type.
- Provider/license retention policy.
- Created and expires times.
- Encryption metadata when applicable.
Schedule
- Name and job kind.
- Scope parameters by entity IDs.
- Standard five-field cron expression or scheduler-neutral schedule payload.
- Timezone.
- Active.
- Last/next run and last status.
- Created/updated times.
AIAnalysis
- Entity type/ID.
- Purpose.
- Prompt template name/version.
- Input lineage IDs.
- Schema version.
- Validated structured result.
- Model/config metadata.
- Exit code, duration, redacted stderr.
- Created time and synthetic flag.
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:
- Validate phrase and language.
- Normalize without translating.
- Find an active canonical row by language + normalized form.
- Create only if none exists.
- Attach an idempotent origin even when the keyword already exists.
- Attach or update the context without silently changing user decisions.
- Flag near-duplicates for review; do not fuzzy-merge automatically.
- Emit an audit event for user-visible changes.
Examples:
- Seed
Organic turmeric and HTML organic turmeric resolve to one English keyword with two origins.
- French
curcuma biologique remains a separate French keyword, related through the same product rather than merged across languages.
organic turmeric supplier and organic turmeric importer remain separate because intent differs.
4.2 Seed generation
For each enabled predefined product-market pair:
- Resolve market languages in priority order.
- Choose a curated/user-verified product name for that language; otherwise retain the known trade name instead of fabricating a translation.
- Combine it with localized organic, supplier, wholesale, bulk, price, importer, distributor, manufacturer, processor, private-label, and buyer-role patterns.
- Add English content/backlink hypotheses when appropriate.
- Resolve every phrase through the canonical service.
- Create a product + market context with
predefined=true.
- 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
- Parse a document safely.
- Emit candidate occurrences with evidence.
- Resolve each through the canonical service.
- Attach an HTML origin.
- Attach a website-only proposed context if none exists.
- Suggest product/market matches but require user confirmation.
- Re-ingestion deactivates vanished occurrence origins rather than deleting keyword history.
4.4 Review and merge
The review queue prioritizes:
- New HTML/manual/provider/AI origins.
- Normalization collisions.
- Near duplicates.
- Missing product/market/website assignments.
- Conflicting language or intent.
- Stale/missing metrics.
No source type is inherently more truthful than verified user judgment. Seeded means predefined, not verified demand.
4.5 Metric enrichment
- User selects keyword contexts or a scheduled scope.
- Collapse them into unique
(keyword_id, market_id) requests so shared contexts do not incur duplicate API cost.
- Validate enabled state and batch cap.
- Estimate cost and run budget guard.
- Group by provider location and language.
- Create Job and JobTask records before external calls.
- Call
KeywordMetricsProvider.
- Persist ProviderRequest and permitted raw artifact.
- Append KeywordMetricSnapshot rows.
- Calculate a KeywordContextScore for every affected active context using its effective intent.
- Mark missing provider values null.
- Complete, partially complete, cancel, or fail with retained successes.
4.6 Discovery selection
For product + market:
- Load active contexts with
discovery_enabled=true.
- Prefer buyer_discovery and transactional intent.
- Order by current value score, evidence/review state, then deterministic phrase order.
- Enforce language balance so English does not consume a multilingual market’s full budget.
- Deduplicate query strings.
- Fill unused query capacity with deterministic fallbacks.
- Persist every selected/fallback query before calling search.
4.7 Ranking selection
For website + market:
- Load active contexts with
ranking_enabled=true.
- Validate website ownership/domain and market location mapping.
- Collapse duplicate canonical keywords.
- Estimate cost.
- Persist job scope with exact context IDs.
- Run SERP calls and store immutable snapshots.
5. Deterministic scoring
5.1 Keyword value
Keep components 0–100:
- Volume signal: log-scaled within documented bounds.
- CPC signal: capped/log-scaled within market currency context.
- Intent signal: versioned lookup; transactional/buyer intent normally exceeds informational intent.
- Attainability:
100 - difficulty when available, otherwise inverse competition index, otherwise documented neutral 50.
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:
- Quality: domain/page authority or rank, traffic, follow state, spam/risk deduction.
- Relevance: keyword/topic, product, market/language, and competitor overlap.
- Attainability: opportunity type, visible contact/submission route, editorial difficulty, recency.
- Priority: versioned weighted combination plus overlap/risk adjustments.
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:
- Verified Importer requires exact product + confirmed importing.
- Probable Importer requires importing plus product/category or wholesale evidence.
- Verified Product Buyer requires exact product plus wholesale, processing, manufacturing, packaging, or private label.
- Relevant Category Buyer requires strong organic commercial-category evidence.
- Otherwise Unqualified Prospect.
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:
- US → USDA INTEGRITY permitted local dataset/sanctioned API.
- France → Agence BIO open API plus optional
FR.csv.
- Other countries → permitted
<ISO>.csv until a sanctioned structured adapter exists.
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:
- Subprocess argument array;
shell=False.
- Prompt via stdin.
- Timeout and active cancellation.
- Capture stdout, stderr, exit code, model/config, and duration.
- Structured JSON output validated by Pydantic.
- Prompt template version and response lineage.
- Credential-stripped environment and redaction.
- Output-size limit.
- Safe failure when executable is absent, times out, returns non-zero, or emits invalid output.
- No destructive actions.
- No invented facts to fill missing provider data.
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:
- HTTPS start URLs by default.
- DNS resolution and rejection of loopback, private, reserved, link-local, and otherwise non-global IPs.
- Robots handling fails closed.
- Identifying user agent.
- Same-domain redirects and traversal only.
- Timeouts, throttling, page/byte limits, and cancellation.
- Relevant path prioritization for about, product, ingredient, wholesale, distribution, import/export, supplier, private label, certification, contact, and catalogue pages.
- Public HTML and PDF only.
- Local cache with bounded retention.
- No authentication or access-control bypass.
- Commercial evidence requires a configured product/category term in appropriate context; generic “we import” text is not exact-product proof.
8. Exports and traceability joins
Provide CSV exports for:
- Websites and documents.
- Canonical keywords.
- Keyword origins.
- Keyword contexts/assignments.
- Current keyword metrics.
- Keyword metric history.
- Markets and market languages.
- Products, names, product-market targets, and HS suggestions.
- Rankings and competitors.
- Backlinks, gaps, and opportunities.
- Discovery queries.
- Companies, sources, evidence, certificates, candidates, observations, contacts, and leads.
- Jobs, tasks, provider requests, schedules, and audit events where safe.
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
- Keyword with origins, metrics, rank history, queries, or opportunities: archive; do not hard-delete.
- Keyword context with completed workflow lineage: archive/disable; retain decisions.
- Product/market/website with jobs or evidence: archive.
- Company with sources/candidates/leads: merge or archive.
- Provider requests and audit events: retain according to explicit local retention policy; never cascade silently from a UI delete.
- Artifacts may expire according to license/retention rules while keeping hash, metadata, and a “content expired” state.
- User-requested destructive operations must preview impact and record an audit event.
10. Data invariants to test
- One active canonical keyword per normalized phrase + language.
- Every keyword has at least one origin.
- Every keyword context points to the same canonical keyword; no copied phrase entity exists.
- Context keys are unique across SQLite and PostgreSQL.
- Discovery-enabled contexts have product + market.
- Ranking-enabled contexts have website + market.
- Metrics are market-scoped immutable snapshots.
- Scores reference their inputs and score version.
- Rank snapshots and discovery queries reference exact keyword contexts.
- Merge preserves origins, decisions, histories, and a merge ledger.
- Seed upgrades preserve user modifications and snapshot IDs.
- Missing provider measurements remain null.
- A certificate alone never creates importer evidence.
- Verified Importer cannot exist without exact-product and confirmed-importing evidence.
- Public contact values require source URL and verification time.
- Every external result has provider/import lineage and retrieval time.
- Every mock result is synthetic.
- Costs use decimals and estimated cost never overwrites actual cost.
- No secret appears in stored request JSON, errors, logs, exports, or rendered HTML.