# HyperFlow-owned operations The operations service manages deliveries owned by HyperFlow. It does not grant access to Swiggy's fleet, warehouse inventory, or private operational metrics. The canonical operations workflow requires `user_input` or `simulation` provenance for each persisted job. Site, replenishment, and dispatch calculations are explicitly labelled simulations. ## Delivery and courier workflow Provision separate operator and courier accounts. A courier must explicitly enroll by submitting `owner_account_id`; the referenced account must be a provisioned operator or admin. Enrollment authorizes one workspace and cannot silently change to another. The operator lists enrolled couriers before assigning work. Create a delivery with: ```json { "label": "HyperFlow-owned parcel", "pickup": {"latitude": 12.9, "longitude": 77.6}, "dropoff": {"latitude": 12.91, "longitude": 77.61}, "load_units": 1, "source": "user_input" } ``` Assignment requires `courier_account_id`, declared integer `capacity_units`, and `speed_kmh`. Capacity is a workload budget; it is not inferred fleet capacity. Active job loads may not exceed that budget. Changing capacity while jobs remain active is rejected. Owner-scoped database/file locks serialize competing assignments, and optimistic record versions reject stale writes. Assigning a courier enrolled in another workspace is forbidden. The lifecycle is: ```text CREATED -> ASSIGNED -> PICKED_UP -> IN_TRANSIT -> DELIVERED CREATED or ASSIGNED -> CANCELLED ``` Only operators may cancel. Couriers can inspect and update only their own assigned jobs. Assignment indexes reference authoritative owner-scoped jobs and do not grant access unless the actual assignment matches. A failed write that leaves an index behind therefore fails closed. Every status change retains its actor and time. GPS updates require `location_consent: true`, `position`, timezone-qualified `captured_at`, and `accuracy_meters`. Observations older than five minutes, more than 30 seconds into the future, or older than the stored observation are rejected. GPS is accepted only for active jobs. Completion and cancellation clear the stored location. Domain events contain record references rather than location coordinates. ETA is a straight-line estimate using declared speed; accuracy remains unknown. A UI must obtain browser location permission before submitting GPS. ## Dispatch comparison `dispatch_plan(jobs, couriers, strategy)` accepts `nearest_first` or `cost`. Both receive identical inputs, nonnegative workload capacity, explicit speeds, and pickup/dropoff coordinates. The nearest-first baseline assigns jobs in input order to the nearest feasible courier. The MILP first maximizes assigned job count, then minimizes total independent-trip distance with that count held fixed. It uses [SciPy's MILP solver](https://docs.scipy.org/doc/scipy-1.12.0/reference/generated/scipy.optimize.milp.html). Non-optimal solver termination raises an error rather than claiming an optimum. The account-scoped dispatch service accepts created delivery IDs and enrolled couriers. It persists the proposal and job versions without executing assignments. Capacity is not reserved by a proposal. Assignment validates current state again. The model assumes separate trips from each courier's stated position, then pickup, then dropoff. It does not solve multi-stop routing, model traffic, estimate actual ETA accuracy, or establish real fuel/cost savings. Comparing total distances when assignment counts differ requires explicitly reporting those counts. Reproduce the controlled study: ```bash python3 scripts/eval_dispatch.py --seed 42 --cases 20 python3 scripts/eval_dispatch.py --seed 42 --cases 20 --output /tmp/hyperflow-dispatch.json ``` The script writes files only when `--output` is supplied. Results include source, seed, per-case input hashes, assignment counts, distance, runtime measurements, Python/SciPy versions, and host architecture. No credentials or user locations are used. The retained historical local report with the default 20 cases recorded (current reproduction is pending): | Strategy | Assigned jobs | Independent-trip distance | | --- | ---: | ---: | | Nearest first | 146 | 862.395670 km | | Cost MILP | 150 | 847.215198 km | These are reproducible simulation outputs, not measured operational improvements. Timings depend on local hardware and exclude initial SciPy imports. ## Operational review The review service applies versioned, explainable rules to supplied observations: three or more refund requests within the supplied 30-day aggregate, refund amount exceeding the supplied order total, and an explicitly identified duplicate receipt. Each matched rule records its observed value and threshold. The result is a review signal, not a fraud probability. No model precision or accuracy is invented. Operators/admins record `CONFIRMED_ISSUE`, `CLEARED`, or `NEEDS_INFORMATION` with a reason. Decisions append to the audit history rather than deleting previous judgments. Public reviewer accounts remain read-only in their own partition. The service does not infer verified fraud labels from rule matches. ## Explicit economic scenarios Site sensitivity requires `currency`, `daily_orders`, `average_order_minor`, `gross_margin_fraction`, `competition_loss_fraction`, `monthly_rent_minor`, `monthly_other_fixed_minor`, `per_order_cost_minor`, and `setup_cost_minor`. `days_per_month` defaults to 30. Optional `sensitivity` entries provide a name and nonnegative demand/rent multipliers. Default demand multipliers are 0.8, 1, and 1.2. Monthly contribution equals monthly orders after the assumed competition loss, multiplied by unit contribution, minus rent and other fixed costs. Outputs use integer minor currency units. Setup payback is absent when contribution is not positive. Scenario ranges are deterministic sensitivity, never confidence intervals. Replenishment requires explicit `stock_units`, `inbound_units`, `committed_units`, `daily_demand_units`, `lead_time_days`, `review_period_days`, `safety_stock_units`, `unit_cost_minor`, `fixed_order_cost_minor`, and `currency`. Target stock is demand through lead time plus the review period, with explicit safety stock. Recommended order is the positive shortfall against stock plus inbound minus commitments. Estimated cost includes a fixed order charge only for a positive order quantity. Missing inputs, invalid units/counts, and nonfinite numbers produce validation errors. Recommendations do not imply verified provider inventory or optimize unknown holding, shortage, or shelf-life costs. ## Verification ```bash python3 -m pytest tests/flagship_ops -q ``` Tests cover exhaustive small-case solver comparison, infeasibility, invalid numbers, role and workspace isolation, explicit enrollment, overcapacity, failed writes, GPS consent/freshness/privacy, lifecycle validation, evidence histories, sensitivity, and replenishment inputs. Integration tests use real migrated temporary SQLite files, provisioned accounts, separate Store instances, simultaneous assignment, and restart durability. PostgreSQL deployment requires the separate database integration suite; SQLite results do not establish PostgreSQL behavior. ## Retained surface adapter audit The canonical delivery/dispatch contract above is implemented in `backend/flagship/operations.py`. Newer surface adapters also exist in `api.py` and services for routing, weather, fraud and merchant scenarios. They require separate authentication, provenance and behavior verification; canonical service tests do not certify every mounted page. Road-network responses are provider observations only when actually returned with source/time evidence. Geometric/tortuosity distance and weather speed multipliers are assumptions. A smoothed ETA is not a measured improvement in arrival accuracy. Compare identical inputs, disclose routing failures and label every fallback as an estimate. Refund plausibility taxonomies and merchant SLA calculations are scenario/review rules. No authority to debit real merchant payouts, hold escrow or downrank Swiggy merchants is established by consumer MCP access. Show proposed/simulated consequences explicitly; do not claim executed financial enforcement. Real fraud precision/recall requires verified outcome labels and an appropriate held-out study. Audit empty and unavailable states for invented stores, couriers, demand curves, coupon savings and revenue. Publish an operational metric only when its event type, account/time window, amount/unit and outcome can be traced to evidence. Benchmarks stay separate from operational measurements.