Back to .md Directory

Data Structures and Operations Reference

Defines 11 data entities, their fields, business rules, and REST endpoints for a growth marketing experimentation system.

May 2, 2026
0 downloads
1 views
rag
View source

What this file does

Defines 11 data entities, their fields, business rules, and REST endpoints for a growth marketing experimentation system.

When to use it

  • Designing a backend for hypothesis-driven ad experiments
  • Planning a database schema with product isolation and soft deletes
  • Mapping entity relationships for a multi-platform marketing tool
  • Defining API endpoints for hypothesis and variant CRUD operations

Assumes this stack

PostgreSQLREST API

Data Structures and Operations Reference

This document describes all data structures in the Growth Marketing Experimentation System and the operations performed on each entity. Use this as a reference for backend database design and API endpoint planning.


Table of Contents

  1. Entity Relationship Overview
  2. Core Entities
  3. Supporting Entities
  4. Enums
  5. Operations by Entity
  6. API Endpoint Suggestions

Entity Relationship Overview

┌─────────────────────────────────────────────────────────────────┐
│                         PRODUCT                                  │
│  (Aggregate Root - isolated state per product)                   │
├─────────────────────────────────────────────────────────────────┤
│  ├── ProductDefinition (embedded)                                │
│  │                                                               │
│  └── KernelState (per-product)                                  │
│       ├── Hypotheses (1:N)                                      │
│       │    └── CreativeVariants (1:N, platform-specific)        │
│       │                                                          │
│       ├── Insights (1:N)                                        │
│       │                                                          │
│       └── Beliefs (1:N)                                         │
│            └── EvidenceReferences (1:N)                         │
│                                                                  │
│  MetricsSnapshots (linked to Hypothesis, platform-specific)     │
└─────────────────────────────────────────────────────────────────┘

Platform (lookup table - not per-product)
  └── PlatformSpecs

Core Entities

Product

The top-level aggregate root. Each product has isolated state (hypotheses, variants, beliefs).

Fields:

FieldTypeRequiredDescription
product_idstringYesUnique identifier (UUID)
definitionProductDefinitionYesSynthesized product info (embedded)
source_urlsstring[]NoURLs used to extract product info
additional_textstringNoUser-provided additional context
enabled_channelsstring[]NoMarketing channels enabled
created_atISO datetimeYesCreation timestamp
updated_atISO datetimeYesLast update timestamp

Storage: products/<product_id>/context.json


Hypothesis

The atomic unit of learning. A structured, testable marketing claim.

Fields:

FieldTypeRequiredDescription
hypothesis_idstringYesUnique ID (format: "H-{timestamp}")
statementstringYesThe testable claim (max 500 chars)
independent_variablestringYesVariable being tested (e.g., "headline", "image")
dependent_metricstringYesMetric to measure (e.g., "ctr", "cpa")
audience_scopestringYesTarget audience definition
expected_directionenumYes"increase", "decrease", "change"
confidence_levelenumYes"low", "medium", "high"
statusenumYesSee HypothesisStatus enum
created_atISO datetimeYesCreation timestamp
updated_atISO datetimeNoLast update timestamp
expected_magnitudestringNoExpected size of effect (e.g., "20-30%")
conclusionenumNo"confirmed", "refuted", "inconclusive"
abandonment_reasonenumNoReason if abandoned
evidence_summarystringNoSummary of test results
rationalestringNoWhy hypothesis was proposed
psychological_triggerstringNoPsychological principle being tested
risk_factorsstringNoPotential risks
success_criteriastringNoWhat success looks like
test_duration_suggestionstringNoSuggested test duration
budget_suggestionstringNoSuggested budget
creative_briefstringNoBrief for creative development
data_quality_flagsstring[]NoQuality flags (e.g., "low_sample_size")
creative_variantsCreativeVariant[]NoAssociated variants (embedded)

Business Rules:

  • Cannot be deleted (soft delete only via abandonment)
  • Cannot activate without >= 3 variants per platform
  • Conclusion is immutable once set
  • Status transitions: proposed → approved → active → concluded/abandoned

Storage: Part of products/<product_id>/state.json under hypotheses dict


CreativeVariant

A specific ad creative used in an experiment. Platform-specific.

Fields:

FieldTypeRequiredDescription
variant_idstringYesUnique ID (format: "V-{sequence}")
asset_typestringYesAd format (e.g., "single_image", "video")
asset_referencestringYesReference to creative asset
descriptionstringYesBrief description of variant approach
created_atISO datetimeYesCreation timestamp
platform_idstringNoPlatform identifier ("facebook", "linkedin")
primary_textstringNoMain ad copy (platform: intro_text for LinkedIn)
headlinestringNoAd headline
link_descriptionstringNoDescription below headline
cta_buttonstringNoCall-to-action button text
hookstringNoAttention-grabbing opening
anglestringNoPersuasion angle
rationalestringNoWhy variant was created
psychological_anglestringNoPsychological lever used
target_emotionstringNoEmotion being evoked
differentiationstringNoHow it differs from others
image_descriptionstringNoIdeal image description
image_stylestringNoVisual style direction
image_moodstringNoMood/atmosphere

Business Rules:

  • Platform_id is required for multi-platform support
  • Each platform must have >= 3 variants for hypothesis approval
  • Embedded within Hypothesis (not a separate table)

MetricsSnapshot

Performance data for a hypothesis over a time period.

Fields:

FieldTypeRequiredDescription
hypothesis_idstringYesFK to Hypothesis
period_startISO datetimeYesStart of measurement period
period_endISO datetimeYesEnd of measurement period
impressionsintegerYesNumber of impressions
clicksintegerYesNumber of clicks
conversionsintegerYesNumber of conversions
spendfloatYesAd spend in dollars
platform_idstringNoPlatform the metrics are from

Business Rules:

  • Immutable (frozen dataclass)
  • clicks <= impressions
  • conversions <= clicks
  • period_end > period_start

Derived Metrics (computed, not stored):

  • CTR = clicks / impressions
  • CPA = spend / conversions
  • CPC = spend / clicks

Insight

A validated learning extracted from concluded hypotheses.

Fields:

FieldTypeRequiredDescription
insight_idstringYesUnique ID (format: "I-{timestamp}")
statementstringYesThe insight claim
insight_classenumYes"messaging", "audience", "channel_mechanics"
evidence_hypothesis_idsstring[]YesReferences to supporting hypotheses
confidenceenumYes"low", "medium", "high"
reusabilityenumYes"single_use", "limited", "broad"
statusenumYes"proposed", "confirmed", "retired"
scopestringYesApplicability scope
discovered_atISO datetimeYesDiscovery timestamp
last_validated_atISO datetimeNoLast validation timestamp
decay_flagbooleanNoWhether insight is decaying

Business Rules:

  • Must reference at least one concluded hypothesis

Storage: Part of products/<product_id>/state.json under insights dict


Belief

A persistent claim that guides future decisions.

Fields:

FieldTypeRequiredDescription
belief_idstringYesUnique ID (format: "B-{timestamp}")
claimstringYesThe belief statement
confidencefloatYes0.1 to 1.0
sourceenumYes"insight", "seed", "inherited"
scopeenumYes"global", "segment_specific", "creative_specific"
lifecycle_stateenumYesSee BeliefLifecycleState enum
formed_atISO datetimeYesFormation timestamp
last_updated_atISO datetimeYesLast update timestamp
scope_detailstringNoAdditional scope info
evidence_forEvidenceReference[]NoSupporting evidence
evidence_againstEvidenceReference[]NoContradicting evidence

Business Rules:

  • Confidence must be in [0.1, 1.0]
  • Evidence references are append-only
  • Decays over time without new evidence
  • No untraceable beliefs (source is required)

Storage: Part of products/<product_id>/state.json under beliefs dict


Supporting Entities

ProductDefinition

Synthesized product information (embedded in Product).

FieldTypeDescription
namestringProduct name
taglinestringShort tagline
descriptionstringProduct description
target_audiencestringTarget audience description
value_propositionsstring[]Value propositions
key_benefitsstring[]Key benefits
brand_voicestringBrand voice/tone
unique_selling_pointsstring[]USPs
pain_points_addressedstring[]Pain points addressed
price_positioningstringPrice positioning
call_to_action_suggestionsstring[]Suggested CTAs

ProductRegistry

Tracks all products and active selection.

FieldTypeDescription
productsDict[string, string]product_id → display_name
active_product_idstringCurrently active product
versionstringRegistry format version

Storage: products/registry.json


EvidenceReference

Reference to evidence from a hypothesis (embedded in Belief).

FieldTypeDescription
hypothesis_idstringFK to Hypothesis
strengthenum"strong", "weak"
added_atISO datetimeWhen evidence was added

KernelState

Container for all per-product state.

FieldTypeDescription
hypothesesDict[string, Hypothesis]All hypotheses
insightsDict[string, Insight]All insights
beliefsDict[string, Belief]All beliefs
is_haltedbooleanEmergency halt flag
halt_reasonstringReason for halt

Storage: products/<product_id>/state.json


PlatformSpecs

Platform-specific constraints (lookup table).

FieldTypeDescription
namestringDisplay name (e.g., "Facebook Ads")
platform_idstringUnique ID (e.g., "facebook")
character_limitsDictField → {visible, max} limits
image_specsDictImage requirements
cta_optionsstring[]Available CTAs
ad_formatsstring[]Supported formats
objectivesstring[]Campaign objectives
audience_typesstring[]Targeting options
key_metricsDictMetric benchmarks

Note: This is config/lookup data, not stored per-product.


Enums

HypothesisStatus

PROPOSED → APPROVED → ACTIVE → CONCLUDED
                           └→ ABANDONED

Values: proposed, approved, active, concluded, abandoned

HypothesisConclusion

Values: confirmed, refuted, inconclusive

ConfidenceLevel

Values: low, medium, high

InsightClass

Values: messaging, audience, channel_mechanics

InsightConfidence

Values: low, medium, high

BeliefScope

Values: global, segment_specific, creative_specific

BeliefLifecycleState

Values: emerging, established, strong, challenged, retired

EvidenceStrength

Values: strong, weak

AbandonmentReason

Values: spend_cap, time_limit, early_stop, policy_block, human_override


Operations by Entity

Product Operations

OperationCLI OptionMethodDescription
Create0create_product()Create new product from URLs/text
List0list_products()Get all products
Get0get_product()Get single product details
Switch0switch_product()Change active product
Update0update_product_context()Update product definition
Delete0delete_product()Delete product

Hypothesis Operations

OperationCLI OptionMethodDescription
Create1create_hypothesis()Strategy agent proposes hypothesis
List8list_hypotheses()Get all hypotheses (with filters)
Get8get_hypothesis()Get single hypothesis with variants
Approve3approve_hypothesis()Transition proposed → approved
Activate4activate_hypothesis()Transition approved → active
Conclude7conclude_hypothesis()Set conclusion and transition to concluded
Abandon8abandon_hypothesis()Mark as abandoned with reason
Delete14delete_hypothesis()Soft delete (mark as deleted)
Set Flag11set_data_quality_flag()Add quality flag
Clear Flag11clear_data_quality_flag()Remove quality flag

CreativeVariant Operations

OperationCLI OptionMethodDescription
Generate2generate_variants()Creative agent generates for platform
List9(via get_hypothesis)Get all variants for hypothesis
Get9(via get_hypothesis)Get single variant details
Edit9update_variant()Edit variant fields
Delete9delete_variant()Remove variant from hypothesis
Regenerate9regenerate_variants()Generate fresh variants
Export15export_variants_for_ads()Export for platform (with filter)
Validate-validate_creative()Validate against platform specs

MetricsSnapshot Operations

OperationCLI OptionMethodDescription
Ingest5ingest_metrics_manual()Record metrics for platform
Get Latest-(via harness)Get most recent snapshot
Aggregate-merge_metrics_snapshots()Combine multiple snapshots

Insight Operations

OperationCLI OptionMethodDescription
Create-(future)Create from concluded hypothesis
List-(future)Get all insights
Confirm-(future)Confirm proposed insight
Retire-(future)Mark as retired

Belief Operations

OperationCLI OptionMethodDescription
List9list_beliefs()Get all beliefs
Get9get_belief()Get belief details
Update-(future)Update confidence based on evidence
Decay-(automatic)Confidence decays over time

System Operations

OperationCLI OptionMethodDescription
Halt12halt_system()Emergency halt
Resume12resume_system()Resume from halt
Summary13generate_daily_summary()Generate report
Events10get_events()Get event log

API Endpoint Suggestions

Based on the entities and operations above, here are suggested REST API endpoints:

Products

POST   /api/products                    # Create product
GET    /api/products                    # List products
GET    /api/products/:id                # Get product
PUT    /api/products/:id                # Update product
DELETE /api/products/:id                # Delete product
POST   /api/products/:id/activate       # Set as active product

Hypotheses

POST   /api/products/:pid/hypotheses                    # Create hypothesis
GET    /api/products/:pid/hypotheses                    # List hypotheses
GET    /api/products/:pid/hypotheses/:hid               # Get hypothesis
POST   /api/products/:pid/hypotheses/:hid/approve       # Approve
POST   /api/products/:pid/hypotheses/:hid/activate      # Activate
POST   /api/products/:pid/hypotheses/:hid/conclude      # Conclude
POST   /api/products/:pid/hypotheses/:hid/abandon       # Abandon
DELETE /api/products/:pid/hypotheses/:hid               # Delete
PUT    /api/products/:pid/hypotheses/:hid/flags         # Update flags

Variants

POST   /api/products/:pid/hypotheses/:hid/variants          # Generate variants
GET    /api/products/:pid/hypotheses/:hid/variants          # List variants
GET    /api/products/:pid/hypotheses/:hid/variants/:vid     # Get variant
PUT    /api/products/:pid/hypotheses/:hid/variants/:vid     # Update variant
DELETE /api/products/:pid/hypotheses/:hid/variants/:vid     # Delete variant
POST   /api/products/:pid/hypotheses/:hid/variants/export   # Export variants

Query params for variants:

  • ?platform_id=facebook - Filter by platform

Metrics

POST   /api/products/:pid/hypotheses/:hid/metrics       # Ingest metrics
GET    /api/products/:pid/hypotheses/:hid/metrics       # Get metrics history

Analysis

POST   /api/products/:pid/hypotheses/:hid/analyze       # Analyst propose conclusion

System

POST   /api/products/:pid/halt                          # Halt system
POST   /api/products/:pid/resume                        # Resume system
GET    /api/products/:pid/summary                       # Get summary report
GET    /api/products/:pid/events                        # Get event log

Platforms (lookup/config)

GET    /api/platforms                                   # List available platforms
GET    /api/platforms/:id                               # Get platform specs

Database Schema Suggestions

Relational (PostgreSQL)

-- Products
CREATE TABLE products (
    product_id UUID PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    tagline TEXT,
    description TEXT,
    target_audience TEXT,
    brand_voice TEXT,
    price_positioning TEXT,
    source_urls JSONB,
    additional_text TEXT,
    enabled_channels JSONB,
    value_propositions JSONB,
    key_benefits JSONB,
    unique_selling_points JSONB,
    pain_points_addressed JSONB,
    call_to_action_suggestions JSONB,
    is_active BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL
);

-- Hypotheses
CREATE TABLE hypotheses (
    hypothesis_id VARCHAR(50) PRIMARY KEY,
    product_id UUID REFERENCES products(product_id),
    statement TEXT NOT NULL,
    independent_variable VARCHAR(100) NOT NULL,
    dependent_metric VARCHAR(100) NOT NULL,
    audience_scope TEXT NOT NULL,
    expected_direction VARCHAR(20) NOT NULL,
    confidence_level VARCHAR(20) NOT NULL,
    status VARCHAR(20) NOT NULL,
    expected_magnitude VARCHAR(100),
    conclusion VARCHAR(20),
    abandonment_reason VARCHAR(50),
    evidence_summary TEXT,
    rationale TEXT,
    psychological_trigger TEXT,
    risk_factors TEXT,
    success_criteria TEXT,
    test_duration_suggestion VARCHAR(100),
    budget_suggestion VARCHAR(100),
    creative_brief TEXT,
    data_quality_flags JSONB,
    created_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ
);

-- Creative Variants
CREATE TABLE creative_variants (
    variant_id VARCHAR(50) PRIMARY KEY,
    hypothesis_id VARCHAR(50) REFERENCES hypotheses(hypothesis_id),
    platform_id VARCHAR(50),
    asset_type VARCHAR(50) NOT NULL,
    asset_reference TEXT,
    description TEXT NOT NULL,
    primary_text TEXT,
    headline TEXT,
    link_description TEXT,
    cta_button VARCHAR(100),
    hook TEXT,
    angle TEXT,
    rationale TEXT,
    psychological_angle TEXT,
    target_emotion VARCHAR(100),
    differentiation TEXT,
    image_description TEXT,
    image_style VARCHAR(100),
    image_mood VARCHAR(100),
    created_at TIMESTAMPTZ NOT NULL
);

-- Metrics
CREATE TABLE metrics_snapshots (
    id SERIAL PRIMARY KEY,
    hypothesis_id VARCHAR(50) REFERENCES hypotheses(hypothesis_id),
    platform_id VARCHAR(50),
    period_start TIMESTAMPTZ NOT NULL,
    period_end TIMESTAMPTZ NOT NULL,
    impressions INTEGER NOT NULL,
    clicks INTEGER NOT NULL,
    conversions INTEGER NOT NULL,
    spend DECIMAL(12,2) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Platforms (lookup)
CREATE TABLE platforms (
    platform_id VARCHAR(50) PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    character_limits JSONB,
    image_specs JSONB,
    cta_options JSONB,
    ad_formats JSONB,
    objectives JSONB,
    audience_types JSONB,
    key_metrics JSONB
);

-- Indexes
CREATE INDEX idx_hypotheses_product ON hypotheses(product_id);
CREATE INDEX idx_hypotheses_status ON hypotheses(status);
CREATE INDEX idx_variants_hypothesis ON creative_variants(hypothesis_id);
CREATE INDEX idx_variants_platform ON creative_variants(platform_id);
CREATE INDEX idx_metrics_hypothesis ON metrics_snapshots(hypothesis_id);

Notes for Backend Implementation

  1. Product Isolation: Each product's state is fully isolated. The current implementation uses file-based storage with separate directories per product.

  2. Hypothesis-Variant Relationship: Variants are currently embedded in hypotheses. For a database, normalize to a separate table with FK.

  3. Metrics History: Store all metrics snapshots for historical analysis and trend detection.

  4. Platform is Config: Platform specs are configuration data, not user data. Can be stored in code or a config table.

  5. Event Sourcing: Consider event sourcing for hypothesis state changes to maintain complete audit trail.

  6. Soft Deletes: Hypotheses should use soft delete (abandonment) rather than hard delete.

  7. Concurrency: Multiple users may work on same product - consider optimistic locking on hypothesis updates.

What's inside

6 core entities, 5 supporting entities, 7 enums, 40+ operations, 30+ REST endpoints, and a PostgreSQL schema

Change this for your project

  • Replace products/<product_id>/context.json with your storage path
  • Replace products/<product_id>/state.json with your storage path
  • Replace products/registry.json with your registry path
  • Replace jcolano/growth-agents with your repository name

Where it goes

Keep it in your repository where the agent or team that needs it will read it.

Worth borrowing

  • Product isolation via separate directories or schemas per product
  • Hypothesis lifecycle with immutable conclusion and soft delete via abandonment
  • Embedded variants within hypotheses with a minimum count rule per platform

Related Documents