Inspiration

MARGIN — The AI-Powered Commercial Operating System & Profit Sentinel

"Revenue is vanity, profit is sanity, but margin is survival." Small-to-medium project-based enterprises event production agencies, custom fabricators, specialty contractors, and creative studios suffer from a silent, lethal epidemic: unintentional margin collapse.

In these industries, founders and estimators routinely calculate quotes under high time pressure. They often price jobs based on intuition or customer-dictated budgets without rigorously accounting for:

  1. True unit-level hard costs (direct materials, specialized crew labor, freight/logistics, subcontractor rentals, sundries).

  2. Dynamic risk premiums (tight turnaround penalties, client volatility history, peak-season capacity locks).

  3. Operational scope creep and real-time expense inflation during job execution.

  4. Weak cash milestone discipline, where crews load in and deliver work before deposits or milestones are collected.

The result is a dangerous paradox: companies look busy and generate high top-line revenue, but bleed cash on the bottom line.

We were inspired to build MARGIN to give project-based business owners an uncompromising Commercial Decision Engine & Profit Sentinel.

We wanted to replace guesswork with deterministic cost baselines, enforce mathematical margin guardrails, and utilize Gemini AI to act as a seasoned Chief Commercial Officer evaluating incoming inquiries, negotiating counter-offers, detecting mid-job profit leaks, and running post-mortem profit autopsies.

What it does

The Commercial & Mathematical Framework

MARGIN enforces hard mathematical boundaries before any quotation is generated:

  1. Deterministic Cost Equation For any opportunity or job item, the total hard cost is computed deterministically across five structured cost categories:

  2. Minimum Profitable Price Guardrail Given a mandatory business policy target margin percentage (e.g., ), the minimum acceptable quote price is computed as:

If an inbound client budget, the inquiry's margin at budget:

triggers a hard commercial constraint. MARGIN immediately flags the deal as NEGOTIATE or REJECT, generates an itemized counter-offer with de-scoped deliverables, and drafts the exact negotiation email to send to the client.

  1. Scope Change & Change Order Pricing When a client requests mid-execution additions (incremental costs), the recommended Change Order Price protects the original target margin:

  2. Post-Mortem Profit Autopsy & Variance Attribution Upon project completion, MARGIN computes the exact financial variance:

The Gemini LEARNER agent analyzes across line-item actuals to identify root-cause deviations (e.g., supplier material surcharges, overtime labor) and permanently adapts future pricing policies.

How we built it

We architected MARGIN as a responsive, full-stack application built for real-time commercial operations:

  1. Architecture & Tech Stack
  2. Frontend & UI Layer: React 18+ with TypeScript, Vite, Tailwind CSS, Lucide Icons, and Motion for fluid interactions.
  • Backend & Intelligence API: Node.js & Express server hosting secure server-side endpoints for Gemini integration, deterministic financial calculation engines, and simulation models.

  • AI Engine: @google/genai TypeScript SDK powering a multi-agent commercial pipeline:

  • PRISM Evaluator: Conducts commercial opportunity evaluations, assessing price elasticity, customer track records, and operational risk.

  • SENTINEL Monitor: Audits active operational expenses against budgeted allocations in real time, triggering alerts on cost overruns.

  • LEARNER Autopsy: Reviews completed job variances to extract institutional memory and calibrate baseline rates.

  • SCENARIO Engine: Simulates macroeconomic shifts, supplier inflation shocks, and catalog price elasticity.

  • Interactive Data Visualization: Custom SVG charts and financial tracking bars rendering cost-burn trajectories, margin distributions, and commercial pipelines.

Challenges we ran into

  1. Balancing Automated Guardrails with Commercial Flexibility: Business owners sometimes need to accept a lower margin to win strategic work. We had to design the UI to clearly highlight policy violations while allowing overrides with explicit rationale capture.

  2. Dynamic Scope Modification in Active Production: Creating a seamless bridge from an inbound inquiry formal quoted proposal active operational job post-mortem autopsy required a robust, state-synchronized data model where change orders and live expense logs dynamically updated projected profit.

  3. Cross-Platform Responsive Ergonomics: Crafting an interface that feels equally natural on an estimator’s desktop and on a mobile tablet at a job site required responsive touch targets, dark mode parity, and scannable visual typography.

Accomplishments that we're proud of

  1. Deterministic-First AI Architecture: We successfully merged hard deterministic unit economics with Gemini’s strategic reasoning. By computing costs, margin thresholds, and minimum viable price ceilings mathematically before handing off to the LLM, we achieved zero-hallucination commercial assessments. True Closed-Loop Business Lifecycle: Built a continuous, end-to-end commercial workflow:

The system doesn't just evaluate quotes; it learns from past execution deviations and updates baseline unit costs automatically.

  1. Real-Time Scope Creep & Sentinel Defense: Created an automated margin watchdog that detects expense anomalies, calculates incremental change order pricing on the fly, and enforces deposit & milestone holds before load-in. Complete Multi-Agent System in Production: Built a unified multi-agent architecture (PRISM, SENTINEL, LEARNER, SIMULATOR) operating against live Google Gemini endpoints on Google Cloud Run.

  2. High-Density, Mobile-First Commercial Cockpit: Designed a responsive interface with full dark mode support, accessible touch targets, and scannable visual typography for on-the-go estimators and business owners.

What we learned

  1. Deterministic Logic First, AI Reasoning Second: AI models shouldn't be asked to perform complex mental math on financial totals. By calculating all costs, margins, and minimum viable price thresholds deterministically in TypeScript first, we fed Gemini exact figures. Gemini then excelled at contextual reasoning, risk synthesis, and strategic negotiation drafts.

  2. Customer Memory is a Key Commercial Asset: A quotation cannot be evaluated in isolation. Factoring in customer lifetime margin, past scope volatility, and payment reliability completely changes whether a discount is an acceptable relationship investment or a catastrophic precedent.

  3. Execution Guardrails Are as Vital as Quoting: Generating a profitable quote is only half the battle. Real-time sentinels that alert managers to overtime, unapproved subcontractor fees, and enforce load-in payment holds are what preserve that margin in the real world.

What's next for Margin

  1. Autonomous Real-Time Contract & Scope Drift Detection
  • Proactive Change-Order Triggers: Monitor communication channels (email threads, Slack/Teams event channels, client WhatsApp groups) via webhook listeners to detect unquoted client scope additions ("Can we also add two 85” confidence monitors on the stage wings?") in real time.

  • Auto-Drafted Client Variation Addendums: Automatically match the detected scope change against the unit cost catalog and generate an instant, signed change-order agreement before team members on-site execute the request.

  1. Multi-Project Predictive Resource & Cash-Flow Arbitrage
  • Cross-Project Crew & Gear Clustering: Analyze simultaneous active jobs in the same metro area to eliminate duplicate delivery runs, avoid cross-renting identical fixtures, and pool rigging or carpentry labor across adjacent sites.

  • Predictive Working-Capital Forecasting: Forecast working capital drawdown 30 to 60 days out by modeling supplier net terms against milestone deposits, warning leadership if load-in expenditures threaten payroll liquidity.

  1. Dynamic Subcontractor Marketplace & Automated Negotiation Bots
  • Automated Reverse RFPs: When quoting a new bid, dispatch programmatic RFPs to pre-vetted regional subcontractors and suppliers with strict target margin caps.

  • Agentic Counter-Offer Bots: Empower MARGIN to automatically negotiate supplier quotes that exceed regional medians, using pre-approved commercial boundaries and volume package incentives.

  1. Direct ERP & Bank Automated Ledger Write-Back
  • Native Two-Way QuickBooks / Xero Sync: Transition from webhook ingestion to direct write-back, creating automated line-item job allocations, issuing progress claims, and locking project budgets against accounting ledger overruns.

  • Virtual Credit Card & Spend-Gate Enforcers: Issue single-use virtual cards for job site leads locked to specific category budgets (e.g., $400 for emergency hardware materials), preventing unauthorized operational overspend.

  1. Automated Post-Mortem Feedback Loops
  • Continuous Cost Baseline Recalibration: Automatically adjust standard service catalog rates when real-world supplier inflation consistently trends above initial catalog assumptions.

  • Client Margin Health Scoring: Track profitability decay across recurring clients over time, automatically applying custom risk markups to clients who historically require unpaid revisions or late access.

Share this project:

Updates