Inspiration
I kept noticing the same painful pattern in small businesses: they were losing customers not because their products were weak or demand was missing, but because the owner had no capacity left to serve them.
A customer might be waiting for an answer while the owner is reconciling inventory, checking a promotion, updating prices, coordinating fulfillment, or trying to understand why sales changed. The person who understands the customer best is often trapped inside the operation of the business.
Most commerce software helps by displaying more information or automating isolated tasks. However, the owner still has to notice what happened, decide what to do, execute the change, and return later to check whether it worked.
We asked a different question:
What if a merchant could define the business outcome and its boundaries once, while an autonomous operator continuously handled the operational path required to pursue it?
That question became Margvia: Margin via autonomy.
We began with commercial operations because pricing, inventory, promotions, merchandising, and checkout decisions are frequent, measurable, and directly connected to business outcomes. The broader ambition is to progressively absorb more of the operational load that keeps small-business owners away from their customers.
What Margvia does
Margvia is a 24/7 agentic commerce operator running online stores toward human-defined goals, acting and adapting within human-defined constraints—so merchants can focus on customers and growth.
A merchant can state an objective such as:
“Maximize revenue this week while maintaining gross margin above 30%, spending no more than $300 on marketing, and avoiding stockouts.”
Margvia compiles that objective into an editable operating contract containing the goal, time horizon, permitted actions, margin floor, marketing budget, inventory limits, and risk boundaries. The merchant confirms that contract once. After activation, Margvia can operate autonomously inside it without requesting approval for every individual action.
The central idea is persistent goal ownership under governed autonomy. Margvia does not complete one task and disappear. It keeps responsibility for the objective across the entire operating period, while deterministic rules prevent the model from exceeding the authority the merchant granted.
Margvia continuously watches orders, inventory, conversion, margin, campaigns, product relationships, and checkout behavior. Raw commerce events update the business state through deterministic services; they do not invoke an AI model individually.
Seven deterministic detectors look for material situations:
- Inventory plans at risk.
- Conversion deterioration.
- Margin-floor risk.
- Campaign underperformance.
- Bundle opportunities.
- Overstock exposure.
- Checkout friction.
When a change is economically relevant to the active goal, Margvia starts one bounded decision workflow. It:
- Diagnoses why the situation matters for the goal.
- Generates multiple candidate strategies, with doing nothing always among them whenever an action is proposed — a rule the code enforces on the model's output, not merely a prompt instruction.
- Simulates the expected commercial impact of each strategy.
- Rejects candidates that violate the merchant’s constraints.
- Audits the remaining alternatives for unsupported assumptions and side effects.
- Executes the best feasible plan through a constrained Tool Gateway.
- Measures the result after a predefined observation window.
- Maintains, replans, or rolls back the action according to what actually happened.
Margvia currently has fourteen bounded commerce tools, thirteen of which can be granted by the merchant. They cover prices, discounts, bundles, storefront placement, campaigns, checkout economics, restocking, and product availability. Plans contain at most three sequential actions, and every forward mutation is typed, idempotent, version-checked, recorded with before-and-after state, and designed with a reversal path. The fourteenth tool is the rollback itself, which is deliberately not reversible — the same reason it is the one tool a merchant cannot grant.
A harmful action is not left for the merchant to discover. The verifier can reverse it automatically and use the result of that reversal as evidence for future decisions. The action ledger therefore also becomes Margvia’s memory: the next time it considers acting on the same product or campaign, it knows what was previously attempted and how it performed.
The merchant remains the principal throughout the process. From the Console, they can pause or cancel the goal, manually roll back a change, amend the contract, or give natural-language guidance to a running situation. That guidance is converted into typed instructions and still passes through the same simulation, policy, and audit layers; it cannot create an exception to the rules.
Margvia is not primarily a chatbot or a recommendation dashboard. Its main product is the complete operational loop:
Observe → Diagnose → Plan → Simulate → Validate → Act → Measure → Adapt
The Console presents every decision as a business story: what happened, why it mattered, what Margvia decided, what changed in the store, and whether it worked. The underlying evidence—detector evaluations, rejected alternatives, model calls, tool calls, token usage, estimated cost, verification, and rollback—is available under Technical details.
How we built it
We separated Margvia into deterministic perception, bounded model reasoning, controlled execution, and deterministic verification.
The main flow is:
Commerce events
→ business state and forecasts
→ deterministic detectors
→ signal and situation
→ Google ADK decision workflow
→ deterministic simulation
→ policy gate and risk audit
→ Tool Gateway
→ scheduled verification
→ maintain, replan, or rollback
The model proposes; code controls.
The agent workflow is built with Google ADK. Model stages handle the judgments that benefit from language and strategic reasoning: compiling the objective, diagnosing a situation, generating alternatives, auditing risk, interpreting merchant guidance, and writing the daily merchant brief.
Forecasting, signal detection, simulation, policy enforcement, ranking, idempotency, execution, the verification verdict, and rollback are deterministic code. Every model output must satisfy a strict Pydantic schema and receives exactly one repair attempt. For every stage that runs before execution, a second invalid response fails the run closed and no tool executes. Two model stages run after execution, and they fail differently. The morning brief is persisted as FAILED_SCHEMA while the decision, its status and its executed tools are left untouched — the merchant loses a paragraph, never an action. The verifier's summary stage is stricter: the verification run itself is recorded as FAILED_SCHEMA and its verdict is not applied, so the executed action stays in place unverified. That failure is reported as a completed delivery, so no further verification is scheduled automatically — recovery needs an external retry, and closing that gap is on the list below.
The production model configuration selects Gemini 3.7 Flash through Vertex AI. The same ADK execution path can be exercised locally with a real model, while a private deterministic model double is injected only into tests and evaluations.
Margvia is built as four deployable services:
- A Next.js and React web application containing the storefront, Merchant Console, and Scenario Lab.
- A FastAPI Commerce API that acts as the source of truth and contains the Tool Gateway.
- A FastAPI Signal Worker that maintains state and runs the deterministic detectors.
- A FastAPI Agent Runtime containing the ADK workflow, policy gate, verifier, and merchant-intervention logic.
The architecture uses ports and adapters. Local development uses an in-memory document store, HTTP-compatible event delivery, and an asynchronous task queue. The same application code has adapters for Firestore, Pub/Sub, and Cloud Tasks; Cloud Scheduler drives the daily review, and OpenTelemetry spans are exported to Cloud Trace. The entire cloud topology is defined in Terraform.
Margvia is not only deployable to Google Cloud — it is deployed and running there today. Four Cloud Run services in us-central1 host the web Console, the Commerce API, the Signal Worker, and the Agent Runtime. Firestore holds the business audit ledger, three Pub/Sub topics carry commerce events, business signals, and agent-run events, three Cloud Tasks queues drive verification, merchant instructions, and retries, Secret Manager holds the internal service token, and the decision stages run on Gemini 3.7 Flash through Vertex AI. The Terraform deployment pins the agent runtime to the native ADK workflow topology, so the graph judged in the demo is the graph running in production.
Every artifact carries causal identifiers linking it to the event that started the process. Firestore is designed as the business audit source of truth, while OpenTelemetry traces explain execution across services and model stages. Observability is strictly downstream: a tracing or notification failure can never alter a commercial decision.
We also built a flag-gated integration with one Shopify development store. Shopify webhooks provide orders, inventory levels, and checkouts; the catalog is reconciled from the shop by a separate pull rather than pushed by a webhook. Margvia’s actions are translated through one canonical field-mapping registry and applied to Shopify before being committed locally. Rollbacks reverse the Shopify state first and then restore Margvia’s record, preventing the Console from claiming that a change was undone while the merchant’s store remained modified.
The default demo environment uses deterministic synthetic data: one personal-care store, twelve products, sixty days of commerce history, seven individual business scenarios, and one integrated autonomous week. A separate real-store gauntlet validates the integration against the Shopify development store.
Challenges we ran into
Making autonomy safe without turning it back into an approval workflow
Asking for approval before every action would have removed most of the value of the product. Allowing a model to write directly to the store would have been unsafe.
We solved this by separating authority from intelligence. The model can propose a strategy, but nine deterministic policy rules, typed tool schemas, resource locks, version checks, spending limits, and rollback requirements decide whether anything can execute. The merchant approves the operating contract, not every individual task.
Making simulations deterministic enough to govern real actions
Stockout risk is estimated through Monte Carlo simulation. Our initial implementation used the standard Poisson sampler with the same random seed for before-and-after scenarios, but a lower demand forecast could still occasionally produce a higher sampled stockout risk. That sampling noise was large enough to reject valid plans at the policy gate.
We replaced it with inverse-CDF Poisson sampling using common random numbers. The same demand produces the same path, and reducing demand can no longer increase the simulated risk merely because of random sampling. This made policy decisions reproducible across retries, processes, and scenario replays.
Closing the gap between Margvia’s world and a real Shopify store
A synthetic catalog is clean. A real store contains archived products, discontinued variants, stale links, unusual price structures, and operations that can fail between an external write and the local audit commit.
Testing against Shopify exposed cases that mocks had hidden. For example, a zero-demand archived product could incorrectly pin store-wide stockout risk at 100% and block every plan. We also had to handle the difference between Shopify’s effective selling price and Margvia’s separate list-price and discount representation.
This led us to build one bidirectional field map, perform external writes before local commits, reverse the external change if the local commit fails, and persist any remaining divergence rather than hiding it.
Making asynchronous execution safe under redelivery
Pub/Sub and task queues provide at-least-once delivery. Originally, a redelivered trigger could receive a new workflow identifier, which also created new tool idempotency keys and risked executing the same commercial action twice.
Workflow identifiers are now derived from the business trigger itself. Tool idempotency keys are derived from the workflow, plan, and step, while delivery leases and optimistic concurrency ensure that retries reproduce the existing result instead of duplicating the effect.
Working with real reasoning-model behavior
Real reasoning models do not always return a clean JSON object. Some providers merge reasoning prose and the structured answer into one text stream, while unbounded output reservations can consume provider credit far faster than expected.
We added robust JSON extraction, strict schema validation, one bounded repair attempt, and stage-specific output limits with additional room for the planner. The system now treats malformed model output as a contained workflow failure rather than as permission to improvise.
Accomplishments that we are proud of
- We built the complete loop from a raw business event to a measured commercial outcome—not a chatbot wrapped around a tool call.
- The real-store gauntlet completed 22 of 22 checks across ten scenarios against one Shopify development store, with a real model driving every decision through the full loop. That certification was recorded on 28 August; the native ADK graph now selected in production runs the same stages and invariants but has not yet been re-certified against the live store.
- One scenario changed a product price from $22.00 to $25.11, read the new value directly from Shopify, rolled the action back, and confirmed that Shopify returned to $22.00.
- In another scenario, nobody instructed the agent to act. A real inventory squeeze opened a situation, Margvia selected a restock action autonomously, and Shopify recorded the resulting inventory transfer.
- The repository’s safety net grew to 2,429 automated tests and 57 agent evaluation cases.
- The deterministic integrated-week scenario exercises daily strategic reviews, multiple autonomous changes, replanning, verification, and rollback without per-action approvals after goal activation.
- Every material decision can be reconstructed from its root event through detector evidence, candidate plans, rejected alternatives, model usage, tool mutations, verification, and reversal.
- We built merchant-facing oversight rather than only technical observability: a daily morning brief, goal-scoped marketing ledger, decision stories, intervention threads, outbound notifications, and a view of exactly what structured context the model received.
Every business-performance figure in this document comes from the deterministic synthetic demo scenario described above, not from a real merchant's trading results. The exceptions are the real-store gauntlet numbers, which come from a live Shopify development store.
What we learned
Agentic behavior is an architectural property, not a model feature. Most of Margvia’s reliability comes from the deterministic system surrounding the model: state, simulation, policy, idempotency, tools, verification, and rollback.
Event-driven does not have to mean model-driven. Thousands of raw events can update the business state without consuming model tokens. The model should be used only when economic judgment is required.
Execution is not completion. Generating a plausible plan was the easy part. Deciding what to measure, waiting for enough evidence, handling inconclusive results, and reversing harmful changes were the harder and more valuable parts.
The ledger can be the memory. A stateless model reading a deterministic projection of previous actions and outcomes is easier to test, reproduce, and audit than a long-running conversational memory.
Real integrations reveal a different class of defect. The live Shopify store exposed problems in identity, product lifecycle, external consistency, and API behavior that deterministic scenarios could not reproduce.
Trust requires a business explanation, not only a trace. A technically perfect audit trail is not enough for a merchant. They need to understand what happened, why it mattered, what changed, and what the result was without reading internal identifiers or tool names.
What’s next for Margvia
The first productization step is to harden the current one-store Shopify development integration into a production application: OAuth installation, multi-merchant isolation, multiple inventory locations, production-grade authentication, stronger inventory-spend guardrails, and broader live certification of every store-writing tool.
We also want to improve verification through controlled experiments, stronger entity-scoped measurements, more reliable attribution between an action and the observed outcome, and automatic recovery when a verification fails its own schema instead of leaving the action unverified.
From there, Margvia can expand beyond today’s commercial levers into the other operational areas that consume an owner’s attention: customer-service incidents, supplier delays, procurement decisions, fulfillment problems, returns, customer communications, advertising platforms, and coordination across multiple stores.
Cold-start support would allow newer businesses to begin with category priors and safe experimentation instead of requiring a long operating history. Longer-term outcome memory could help Margvia learn which actions work for each individual merchant without weakening the deterministic controls around execution.
The long-term goal remains the same as the original inspiration:
Let business owners define the destination and the boundaries, while Margvia absorbs more of the operational path—so humans can return their attention to customers, relationships, and growth.
Log in or sign up for Devpost to join the conversation.