Skip to content

State Machine System - Quick Reference Guide

Core Architecture Summary

┌─────────────────────────────────────────────────────────────────┐
│                        DEAL SYSTEM                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  TEMPLATE (Optional) ──────▶ DEAL ──────▶ VERSIONS              │
│  (Structure only)            (Container)   (Working/Submitted)   │
│                                                                  │
│  VERSION contains:                                               │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │ CLAUSE_BLOCK (1 or more per version)                    │    │
│  │   ├── static_variables: { v_guarantee, v_artist_pct }   │    │
│  │   ├── STATES: Calculated values with status             │    │
│  │   ├── INPUTS: User-provided data                        │    │
│  │   ├── FINANCIAL_CLAUSES: Financial obligations          │    │
│  │   ├── BENEFIT_CLAUSES: Non-cash value (optional)        │    │
│  │   ├── OBLIGATION_CLAUSES: Deliverables (optional)       │    │
│  │   └── OTHER_CLAUSES: Terms/territory (optional)         │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

TODO - Not yet defined

  1. Define expression parser - Parse and evaluate calculation strings
  2. Build dependency graph - Track references for incremental recalc
  3. Implement validation - Check references, cycles, required fields
  4. Refine payment terms - Still some open quetsions in payment terms
  5. Commission and Participants - Define how parties and participants and commissions are incorporated. Have not started this yet.
  6. Non-Financial Clauses - I have briefly touched on some of the non-financial clauses by defining the BENEFIT_CLAUSES, OBLIGATION_CLAUSES, and OTHER_CLAUSES but I am sure there is more to do here.
  7. Rights - I have done nothing with rights management. Is that even in scope?

Status Codes

State Status (D/F/C/O)

CodeNameCalculation Behavior
DDraftCalculation runs, sets value
FForecastCalculation runs, sets value
CConfirmedCalculation runs, sets value
OOverrideCalculation runs but value preserved

Input Status (P/C/X)

CodeNameMeaning
PPendingExpected but not yet received
CConfirmedReceived and verified
XNot RequiredNot needed for this deal path

Version Status

StatusMeaning
workingMutable, user can edit
submittedImmutable, locked forever

Version Lifecycle (Git-Like)

1. CREATE working version (from template, submitted version, or scratch)

2. MODIFY inputs, states, variables (auto-saves)

3. Calculation engine runs (real-time)

4. SUBMIT → becomes immutable

5. To change: create NEW working version from any submitted version

Key Rules:

  • Versions are 100% independent
  • Multiple working versions can exist simultaneously
  • Cross-deal references must specify exact version_id
  • No auto-sync between versions or deals

Data Structure Quick Reference

Deal Document

javascript
{
  deal_id: "deal_xxx",
  deal_type: "guarantee_vs_percentage_nbor",
  artist_id: "...",
  promoter_id: "...",
  version_pointers: { primary: "v_001", forecast: "v_002" },
  versions: [ ... ]
}

Version Document

javascript
{
  version_id: "v_submitted_001",
  status: "submitted",  // or "working"
  created_from: "v_000",  // lineage
  submitted_at: "...",
  submitted_by: "user_id",
  clause_blocks: [ ... ]
}

Clause Block

javascript
{
  clause_block_id: "cb_xxx",
  clause_block_ref: "CB_SHOW_1",  // for cross-references
  name: "Show 1 - The Fonda",
  static_variables: { v_guarantee: 5000 },
  states: [ ... ],
  inputs: [ ... ],
  financial_clauses: [ ... ],
  benefit_clauses: [ ... ],      // Optional
  obligation_clauses: [ ... ],   // Optional
  other_clauses: [ ... ]         // Optional
}

State

javascript
{
  state_key: "SHOW_SETTLED",
  state_type: "object",
  value: { net_box_office: 18000 },
  status: "C",  // D/F/C/O
  calculation: "TICKET_INPUT.value.total - FEES_INPUT.value.total"
}

Input

javascript
{
  input_key: "TICKET_DETAIL_INPUT",
  input_type: "object",
  value: { quantity: 900, total_amount: 22500 },
  status: "C"  // P/C/X
}

Financial Clause

javascript
{
  clause_id: "clause_guarantee_vs_nbor",
  name: "Guarantee vs NBOR",
  amount: 15300,  // calculated
  trigger: "SHOW_SETTLED.status == 'C'",
  calculation: "MAX(v_guarantee, SHOW_SETTLED.value.net_box_office * v_artist_pct / 100)",
  payment_terms: [ ... ],      
}

Benefit Clause (Optional)

javascript
{
  benefit_clause_id: "BEN_TRAVEL_001",
  benefit_clause_name: "Travel & Accommodation",
  benefit_type: "reimbursement",     // reimbursement | service | goods | access | credit | IP | other
  benefit_direction: "to_client",    // to_client | to_buyer | mutual
  description: "Round-trip economy airfare and 3 nights hotel for up to 4 people",
  trigger: "SHOW_STATE.value == true",
  quantitative_terms: {
    caps: { max_airfare_per_person: 800, max_nights: 3 },
    units: "USD"
  }
}

Obligation Clause (Optional)

javascript
{
  obligation_clause_id: "OBL_SOCIAL_001",
  obligation_clause_name: "Social Media Posts",
  obligation_type: "promotion",      // performance | promotion | exclusivity | usage | conduct | deliverable | approval | compliance | other
  party: "client",                   // client | buyer | mutual | third_party
  description: "4 social media posts per month on Instagram and TikTok",
  obligation_detail: {
    actions: ["Post at least 4 times per month", "Tag @brand_handle"],
    metrics: { min_posts_per_month: 4, platforms: ["instagram", "tiktok"] },
    approval_required: true
  },
  timeframe: { start_date: "2026-01-01", end_date: "2026-12-31", frequency: "monthly" }
}

Other Clause (Optional)

javascript
{
  other_clause_id: "OTH_TERM_001",
  other_clause_name: "Term and Territory",
  other_clause_type: "term",         // term | territory | renewal | option | rights | termination | dispute | force_majeure | insurance | confidentiality | other
  description: "12-month agreement from first campaign post, worldwide excluding China",
  key_terms: {
    term: { start_date: "2026-01-01", end_date: "2026-12-31", auto_renew: false },
    territory: { regions_included: ["worldwide"], regions_excluded: ["CN"] }
  },
  business_impact_summary: "Client locked in for one year; no auto-renewal"
}

Calculation Engine Rules

When Calculations Run

  • User modifies input in working version → recalc dependents
  • User changes state status from O → other → recalc that state
  • Working version created → full recalc

Override Behavior (Status = O)

State.status == O:
  → Calculation RUNS (for transparency)
  → Value NOT updated (user value preserved)
  → calculated_value stored separately

Error Handling

  • Errors are non-blocking
  • Previous value preserved on error
  • Error stored in calculation_error field
  • User can fix and retry

Null Safety

Key Rule: User-provided values are NEVER overwritten with null due to missing inputs.


Reference Syntax

Local (same clause_block)

v_guarantee                           // static variable
TICKET_INPUT.value.quantity           // input value
SHOW_SETTLED.value.net_box_office     // state value
SHOW_SETTLED.status                   // state status

Cross-Block (same version)

CB_SHOW_1.states.SHOW_SETTLED.value.net_box_office
CB_MERCH.inputs.MERCH_INPUT.value.gross_sales
CB_SHOW_2.financial_clauses.clause_main.amount

Cross-Deal (must specify version)

DEAL:deal_001:VERSION:v_abc123.clause_blocks.CB_MAIN.financial_clauses.clause_main.amount

Aggregation

SUM(cb.financial_clauses[0].amount for cb in [CB_SHOW_1, CB_SHOW_2, CB_SHOW_3] where cb.financial_clauses[0].trigger == true)

Common Functions

FunctionExample
MAXMAX(v_guarantee, nbor * 0.85)
MINMIN(cap, calculated)
SUMSUM(amounts)
IFIF(tickets > 1000, bonus, 0)
EXISTSEXISTS(MERCH_STATE)
COALESCECOALESCE(input, 0)
ROUNDROUND(amount, 2)

Template vs. Deal

AspectTemplateDeal
Contains values❌ (structure only)
Mutable✅ (creates new version)✅ (creates new version)
IndependentTemplates don't affect dealsDeals don't affect each other
Required to create deal❌ (can create from scratch)N/A

Initialization Flow:

Template (optional)
    ↓ [User provides values]
Deal (with first working version)
    ↓ [User modifies, submits]
Submitted versions (immutable)

Version Document Fields

FieldTypeDescription
version_idStringUnique ID
statusEnumworking | submitted
metadataObject[NEW] Non-calculable info (notes, etc.)
clause_blocksArrayList of blocks

Deal Types Summary

TypeCalculation
Flat Guaranteev_guarantee
% of GrossGBOR × v_artist_pct
% of Net(GBOR - tax - fees - expenses) × v_artist_pct
Guarantee vs NBORMAX(v_guarantee, NBOR × v_artist_pct)
Guarantee + Bonusv_guarantee + IF(threshold_met, v_bonus, 0)
Split Pointv_guarantee + MAX(0, NBOR - split_point) × v_backend_pct
Merchandise(gross_merch - hall_fee) × v_artist_pct

Validation on Submit

Before working version can be submitted:

  1. ✅ All references resolve
  2. ✅ No circular dependencies
  3. ✅ Required inputs (status != X) have values
  4. ✅ No unresolved calculation errors on required paths
  5. ✅ Cross-deal references point to submitted versions

Files in This Documentation Set

FilePurposeKey Sections
state-machine-arch.mdArchitecture overviewCore concepts, version lifecycle, clause block structure
template-system.mdTemplate designTemplate schema, initialization process, examples
calc-engine-v2.mdCalculation engineCalculation flow, override behavior, expression language
json-schemas-v2.mdJSON schemasDeal, version, clause_block, state, input, financial/benefit/obligation/other clause schemas
deal-examples.mdComplete examplesAll deal types with full JSON examples
quick-reference.mdThis fileSummary of all concepts

Key Design Decisions

  1. Versions replace settlements - Settlements are calculated from state, not stored separately

  2. Git-like versioning - Checkout, modify, commit pattern for audit trail

  3. Templates are optional - Users can create deals from scratch following grammar

  4. Complete independence - Versions never affect each other; deals never affect each other

  5. Override is explicit - Status O preserves user values while still showing calculated values

  6. Errors don't block - System continues with other calculations; errors stored for review

  7. Cross-references by object ID - Every clause_block has unique clause_block_ref for referencing

  8. Tour aggregation is just another clause_block - No special construct needed


Common Patterns

Show Cancelled

javascript
states: [{
  state_key: "SHOW_STATE",
  value: false,
  status: "C"  // Confirmed: definitely did not happen
}]
// Clause trigger fails → amount = 0

What-If Scenarios

javascript
// Create multiple working versions with different assumptions
version_pointers: {
  primary: "v_submitted_001",
  forecast_optimistic: "v_working_optimistic",
  forecast_pessimistic: "v_working_pessimistic"
}

Multi-Show Tour

javascript
// Clause blocks for each show + summary block
clause_blocks: [
  { clause_block_ref: "CB_SHOW_1", ... },
  { clause_block_ref: "CB_SHOW_2", ... },
  { clause_block_ref: "CB_SHOW_3", ... },
  {
    clause_block_ref: "CB_TOUR_SUMMARY",
    states: [{
      calculation: "SUM(cb.financial_clauses[0].amount for cb in [CB_SHOW_1, CB_SHOW_2, CB_SHOW_3])"
    }]
  }
]

Confidential. For internal use only.