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
- Define expression parser - Parse and evaluate calculation strings
- Build dependency graph - Track references for incremental recalc
- Implement validation - Check references, cycles, required fields
- Refine payment terms - Still some open quetsions in payment terms
- Commission and Participants - Define how parties and participants and commissions are incorporated. Have not started this yet.
- 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.
- Rights - I have done nothing with rights management. Is that even in scope?
Status Codes
State Status (D/F/C/O)
| Code | Name | Calculation Behavior |
|---|---|---|
| D | Draft | Calculation runs, sets value |
| F | Forecast | Calculation runs, sets value |
| C | Confirmed | Calculation runs, sets value |
| O | Override | Calculation runs but value preserved |
Input Status (P/C/X)
| Code | Name | Meaning |
|---|---|---|
| P | Pending | Expected but not yet received |
| C | Confirmed | Received and verified |
| X | Not Required | Not needed for this deal path |
Version Status
| Status | Meaning |
|---|---|
| working | Mutable, user can edit |
| submitted | Immutable, 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 versionKey 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
{
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
{
version_id: "v_submitted_001",
status: "submitted", // or "working"
created_from: "v_000", // lineage
submitted_at: "...",
submitted_by: "user_id",
clause_blocks: [ ... ]
}Clause Block
{
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
{
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
{
input_key: "TICKET_DETAIL_INPUT",
input_type: "object",
value: { quantity: 900, total_amount: 22500 },
status: "C" // P/C/X
}Financial Clause
{
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)
{
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)
{
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)
{
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 separatelyError Handling
- Errors are non-blocking
- Previous value preserved on error
- Error stored in
calculation_errorfield - 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 statusCross-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.amountCross-Deal (must specify version)
DEAL:deal_001:VERSION:v_abc123.clause_blocks.CB_MAIN.financial_clauses.clause_main.amountAggregation
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
| Function | Example |
|---|---|
| MAX | MAX(v_guarantee, nbor * 0.85) |
| MIN | MIN(cap, calculated) |
| SUM | SUM(amounts) |
| IF | IF(tickets > 1000, bonus, 0) |
| EXISTS | EXISTS(MERCH_STATE) |
| COALESCE | COALESCE(input, 0) |
| ROUND | ROUND(amount, 2) |
Template vs. Deal
| Aspect | Template | Deal |
|---|---|---|
| Contains values | ❌ (structure only) | ✅ |
| Mutable | ✅ (creates new version) | ✅ (creates new version) |
| Independent | Templates don't affect deals | Deals 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
| Field | Type | Description |
|---|---|---|
version_id | String | Unique ID |
status | Enum | working | submitted |
metadata | Object | [NEW] Non-calculable info (notes, etc.) |
clause_blocks | Array | List of blocks |
Deal Types Summary
| Type | Calculation |
|---|---|
| Flat Guarantee | v_guarantee |
| % of Gross | GBOR × v_artist_pct |
| % of Net | (GBOR - tax - fees - expenses) × v_artist_pct |
| Guarantee vs NBOR | MAX(v_guarantee, NBOR × v_artist_pct) |
| Guarantee + Bonus | v_guarantee + IF(threshold_met, v_bonus, 0) |
| Split Point | v_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:
- ✅ All references resolve
- ✅ No circular dependencies
- ✅ Required inputs (status != X) have values
- ✅ No unresolved calculation errors on required paths
- ✅ Cross-deal references point to submitted versions
Files in This Documentation Set
| File | Purpose | Key Sections |
|---|---|---|
| state-machine-arch.md | Architecture overview | Core concepts, version lifecycle, clause block structure |
| template-system.md | Template design | Template schema, initialization process, examples |
| calc-engine-v2.md | Calculation engine | Calculation flow, override behavior, expression language |
| json-schemas-v2.md | JSON schemas | Deal, version, clause_block, state, input, financial/benefit/obligation/other clause schemas |
| deal-examples.md | Complete examples | All deal types with full JSON examples |
| quick-reference.md | This file | Summary of all concepts |
Key Design Decisions
Versions replace settlements - Settlements are calculated from state, not stored separately
Git-like versioning - Checkout, modify, commit pattern for audit trail
Templates are optional - Users can create deals from scratch following grammar
Complete independence - Versions never affect each other; deals never affect each other
Override is explicit - Status O preserves user values while still showing calculated values
Errors don't block - System continues with other calculations; errors stored for review
Cross-references by object ID - Every clause_block has unique
clause_block_reffor referencingTour aggregation is just another clause_block - No special construct needed
Common Patterns
Show Cancelled
states: [{
state_key: "SHOW_STATE",
value: false,
status: "C" // Confirmed: definitely did not happen
}]
// Clause trigger fails → amount = 0What-If Scenarios
// 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
// 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])"
}]
}
]