Skip to content

Tractus — Logistics Branch Specification

Version: 1.1 · Date: March 2026 · Owner: Citerius Holdings LLC
Audience: All agents, engineers, PM
Status: Canonical — covers both sub-branches (longhaul + lastmile)

Tractus is the Logistics Branch of alaivOS Business. Architecture is Deployment Mode B (multi-tenant SaaS, firestore_primary). This document covers the complete Tractus specification including the two formal sub-branches: logistics.longhaul (cross-border, MX-US corridor, partner-led) and logistics.lastmile (urban last-mile, MX metropolitan, ampm as reference implementation). All capsules are shared — the delivery_model field in the branch manifest gates sub-branch behavior.


§01 — Sub-Branch Model

Long-haul and last-mile logistics are the same family but different subspecies. They share 60–70% of the capsule architecture. The differences drive fundamentally different Finance Agent behavior, CFDI types, routing models, driver portals, and operational triggers.

Dimension longhaul lastmile
Finance trigger Escrow release on delivery ePOD-triggered revenue accrual — no escrow
COD Rare, B2B wire transfer Critical — MXN 43M+ daily float at scale
Routing Route corridor, 1 shipment/trip Density routing — 150+ stops/driver/day
Driver portal Single trip view Multi-stop daily manifest
CFDI type Carta Porte 3.0 (cross-border) CFDI 4.0 (lastmile shipment)
Marketplace-discovery Core — blind auction, 24h window Phase 2 — contracted clients dominate v1
External order ingestion Manual / marketplace Required Day 1 — MELI/Amazon webhooks
Accounting period control Standard Hard cutoff — ePOD server timestamp gates period

Implementation note: The delivery_model field is read by every capsule with sub-branch–specific behavior. A capsule that ignores delivery_model defaults to longhaul. New capsule code must always branch on this field explicitly.


§02 — Branch Identity

Field Value
branch_id logistics
branch_name Tractus Logistics
product_name Tractus
deployment_mode B
data_layer firestore_primary
tenancy multi-tenant
Firebase projects tractus-dev / tractus-staging / tractus-prod
Odoo reporting instance tractus-reporting.citerius.internal
Portals driver · client · admin

§03 — Branch Manifest

Base Manifest (shared)

{
  "branch_id": "logistics",
  "branch_name": "Tractus Logistics",
  "product_name": "Tractus",
  "version": "1.1.0",
  "min_backbone_version": "1.0.0",
  "deployment_mode": "B",
  "data_layer": "firestore_primary",
  "tenancy": "multi-tenant",
  "firebase_project": {
    "dev": "tractus-dev",
    "staging": "tractus-staging",
    "prod": "tractus-prod"
  },
  "odoo_reporting": true,
  "odoo_instance": "tractus-reporting.citerius.internal",
  "persona_skins": "./personas/logistics_skins.json",
  "odoo_surface": "./odoo/logistics_surface.json",
  "portals": ["driver", "client", "admin"],
  "payment_rails": {
    "MXN": { "provider": "conekta", "model": "escrow", "entity": "SA_de_CV" },
    "USD": { "provider": "stripe_connect", "model": "escrow", "entity": "Wyoming_LLC" }
  },
  "compliance": {
    "biometric_retention_days": 30,
    "kyc_aggregator": "truora",
    "kyc_fallback": "metamap"
  },
  "field_worker_safety": {
    "worker_term": "driver",
    "assignment_term": "shipment",
    "activation_methods": ["logo_longpress", "reverse_pin", "rapid_shake", "biometric_override"],
    "gps_ping_interval_seconds": 60,
    "clear_signal_window_minutes": 2,
    "authority_contacts": {
      "MX": { "agency": "SSPC", "protocol": "pre-established-MX-v1" },
      "US": { "agency": "local_911", "protocol": "standard" }
    },
    "checkin_twilio_number_secret": "TWILIO_SAFETY_NUMBER",
    "safety_ops_channel": "SAFETY_OPS_SLACK_CHANNEL"
  }
}

delivery_model: "longhaul" additions

{
  "delivery_model": "longhaul",
  "industry_tags": ["logistics", "cross-border", "MX-US"],
  "finance": { "model": "escrow_release", "trust_fee_pct": 2.5 },
  "compliance": {
    "cfdi_type": "carta_porte_cfdi",
    "carta_porte_retention_years": 5,
    "pac_primary": "finkok",
    "pac_fallback": "sw_sapien"
  },
  "routing": {
    "model": "corridor",
    "external_boards": ["cargamos.mx", "traycap.com"]
  },
  "capsule_defaults": [
    "entity-verification", "identity-lock", "regulatory-clearance",
    "evidence-audit", "field-worker-safety", "entity-reputation",
    "capacity-matcher", "coverage-referral", "green-badge",
    "marketplace-discovery"
  ],
  "marketplace_discovery": {
    "request_term": "shipment",
    "provider_term": "carrier",
    "client_term": "shipper",
    "currency_primary": "MXN",
    "currency_secondary": "USD",
    "bid_window_hours": 24,
    "client_selection_window_hours": 24,
    "min_bids_before_stats_visible": 3,
    "ranking_weights": { "W_rep": 0.40, "W_fit": 0.35, "W_bid": 0.25 },
    "contextual_fit_dimensions": [
      "route_corridor_performance", "capacity_match", "availability",
      "certification_match", "proximity"
    ],
    "blockchain": {
      "chain": "polygon", "network": "mumbai",
      "contract": "CiteriumMarketplace.sol", "anchor_async": true
    }
  }
}

delivery_model: "lastmile" additions

{
  "delivery_model": "lastmile",
  "industry_tags": ["logistics", "lastmile", "urban-delivery", "MX"],
  "finance": {
    "model": "epod_revenue_accrual",
    "period_enforcement": "hard_cutoff",
    "invoice_cycle": "monthly_batch",
    "client_model": "contracted"
  },
  "compliance": {
    "cfdi_type": "cfdi_4_lastmile",
    "pac_primary": "finkok",
    "pac_fallback": "sw_sapien"
  },
  "routing": {
    "model": "density",
    "engine": "google_or_tools",
    "engine_fallback": "optimoroute",
    "max_stops_per_driver": 200,
    "time_window_enforcement": true
  },
  "cod_treasury": {
    "enabled": true,
    "payment_methods": ["cash", "codi", "spei"],
    "shift_reconciliation": true,
    "float_reporting_enabled": true,
    "variance_alert_threshold_mxn": 200,
    "spei_matching_enabled": true
  },
  "carrier_integration": {
    "enabled": true,
    "platforms": ["meli", "amazon_seller_services"],
    "ingestion_model": "webhook_inbound"
  },
  "capsule_defaults": [
    "entity-verification", "identity-lock", "regulatory-clearance",
    "evidence-audit", "field-worker-safety", "entity-reputation",
    "capacity-matcher", "coverage-referral",
    "cod-treasury", "carrier-integration"
  ]
}

marketplace-discovery for lastmile: Phase 2 only. v1 contracted clients (MELI, Amazon) do not post requests to an open marketplace. Phase 2 activates marketplace-discovery when the operator opens spare capacity to third-party shippers (Temu, Shein, dark store operators).


§04 — Persona Skins

Backbone Persona Longhaul Skin Lastmile Skin Key Difference
risk-agent The Load Guard The Delivery Guard Lastmile evaluates ePOD + COD evidence simultaneously; looser thresholds for volume viability
compliance-agent The Compliance Officer The Fleet Compliance Officer CFDI 4.0 vs Carta Porte; IMSS driver registration
finance-agent The Freight Accountant The Revenue Controller Critical — escrow release vs. ePOD accrual
ops-agent The Load Planner The Dispatch Optimizer Density routing, multi-stop manifest generation
hr-agent The Dispatch Front Desk The Delivery Coordinator Shift management, hub assignment
analyst-agent The Network Analyst The Delivery Intelligence Cost-per-delivery by zone, COD float analysis
sales-agent Generic backbone Generic backbone Phase 2 for both

Delivery Guard (risk-agent, lastmile skin)

{
  "persona_id": "risk-agent",
  "skin": {
    "display_name": "The Delivery Guard",
    "domain_prompt": "You are operating in last-mile urban delivery in Mexico. You evaluate proof-of-delivery evidence: recipient photo, GPS accuracy at delivery point, signature or biometric confirmation, and COD collection evidence where applicable. At 200K+ daily deliveries, false positives (blocking legitimate deliveries) are as costly as false negatives. Evaluate ePOD evidence efficiently and flag anomalies for human review. You are familiar with MELI and Amazon delivery SLA requirements.",
    "rag_corpus": ["sat_catalog_codes_v2024.json", "lfpdppp_biometric_obligations.md", "meli_sla_requirements.md", "amazon_delivery_standards.md"],
    "confidence_thresholds": { "auto_block": 80, "human_review": 65, "auto_approve": 90 }
  }
}

Threshold rationale: Lastmile thresholds are looser than longhaul. A 92% auto-approve threshold on 200K daily ePODs would route 16K+/day to human review — operationally impossible. 90% with strong CV training is the correct balance.


§05 — Finance Models (Critical Architectural Split)

Longhaul — Escrow Release

Shipper pays into escrow at booking. Finance Agent releases to carrier on HANDOFF_APPROVED. Standard pattern documented in BIZ-PLATFORM-MASTER-REF.md §03.

Lastmile — ePOD Revenue Accrual

No escrow. Contracted clients (MELI, Amazon) receive monthly invoices at negotiated per-delivery rates. Revenue is recognized on ePOD confirmation.

Cloud Function: tractus-financeAgentRevenueRecognition

Triggered by: HANDOFF_APPROVED event (Delivery Guard decision).

async function recognizeRevenue(handoffId: string, delivery: DeliveryData) {

  // 1. HARD CUTOFF: server timestamp gates accounting period.
  // No manual backdating is possible. If timestamp is outside open period,
  // entry writes to next period. This is the architectural enforcement
  // of the accounting control — it cannot be overridden by any user.
  const openPeriod = await AccountingPeriod.getOpen();
  const effectivePeriod = delivery.handoffTimestamp > openPeriod.closedAt
    ? openPeriod
    : await AccountingPeriod.getNext();

  // 2. Firestore write first — source of truth
  const revenueRef = db.collection('revenue_events').doc();
  await revenueRef.set({
    type: 'REVENUE_RECOGNIZED',
    handoffId,
    clientId: delivery.clientId,
    deliveryId: delivery.id,
    rateApplied: delivery.contractedRate,
    amount: delivery.billedAmount,
    currency: 'MXN',
    accountingPeriod: effectivePeriod.id,
    createdAt: FieldValue.serverTimestamp()  // enforced by Firestore rules
  });

  // 3. Odoo accrual + invoice queue (same execution context)
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      await odoo.createAccrualEntry(handoffId, {
        account: 'ingreso_envios',
        clientId: delivery.clientId,
        amount: delivery.billedAmount,
        period: effectivePeriod.odooId,
        reference: handoffId
      });
      await db.collection('invoice_queue')
        .doc(delivery.clientId)
        .collection('line_items')
        .add({ deliveryId: delivery.id, amount: delivery.billedAmount,
               period: effectivePeriod.id, createdAt: FieldValue.serverTimestamp() });
      break;
    } catch (err) {
      if (attempt === 3) {
        await db.collection('reconciliation_tasks').add({
          sourceDocId: revenueRef.id,
          odooPayload: { method, endpoint, args },
          error: err.message, attempts: 3,
          status: 'PENDING_MANUAL',
          createdAt: FieldValue.serverTimestamp()
        });
        await notifyOps('REVENUE_RECOGNITION_FAILED', handoffId);
      }
      await sleep(attempt * 2000);
    }
  }
  // Firestore revenue_events is the legal record. Odoo is the report.
}

Why the hard cutoff matters: Previous bad actors at last-mile operators have manually backdated revenue recognition to inflate period performance. The server timestamp on an append-only Firestore document cannot be changed by any user — it is set by Firestore at write time and enforced by security rules. The accounting period gating reads that immutable timestamp. The control is architectural, not procedural.


§06 — ePOD Workflows

Longhaul — Cargo Handoff

Step Actor Action SLA
1 Driver + identity-lock Biometric liveness check < 30s
2 identity-lock TFLite + AWS Rekognition (≥ 92.0) < 30s
3 Driver + evidence-audit Photo capture: CLAHE, GPS/EXIF, pHash < 30s
4 risk-agent (Load Guard) ≥ 92%: approve. 70–92%: review. < 70%: block < 15s
5 finance-agent escrow_events write → Odoo Vendor Bill + Customer Invoice < 60s
6 hr-agent WhatsApp to driver + push to shipper < 5s
7 compliance-agent Update carrier record, trigger insurance if escalated Async

Lastmile — ePOD Delivery

Step Actor Action SLA
1 Driver + identity-lock On-device biometric (no cloud round-trip at this step — volume) < 15s
2 Driver + evidence-audit ePOD: recipient photo, GPS pin, optional signature/biometric, pHash < 20s
3 cod-treasury (if COD) COD amount + payment method (cash/CoDi/SPEI) recorded < 10s
4 risk-agent (Delivery Guard) ≥ 90%: approve. 65–90%: review. < 65%: block. Evaluates ePOD + COD together. < 10s
5 finance-agent recognizeRevenue()revenue_events write → Odoo accrual → invoice queue < 60s
6 hr-agent Driver push (next stop). Client API notification (MELI/Amazon). < 5s
7 cod-treasury Accumulate COD for shift reconciliation. Update driver float position. Async

§07 — COD Treasury Module

Scale context: 217K deliveries/day × MXN 200 average COD = MXN 43M+ daily float. This is treasury management, not a feature.

Architecture (cod-treasury capsule):

Per delivery (real-time):
  cod_collections/{driverId}/shifts/{shiftId}/deliveries/{deliveryId}
  → driver float position updated

Shift close:
  reconciliation agent fires:
  - Expected COD: sum of COD-flagged deliveries assigned to driver
  - Collected COD: ePOD-confirmed cash + CoDi + SPEI
  - Variance > MXN 200: exception queue → ops review
  - SPEI/CoDi: auto-match deposit to shipment IDs via transaction reference
  - Cash: driver scans remittance at hub, hub agent confirms

Finance Agent receives reconciled shift report:
  - Writes cod_settlement_events (append-only)
  - Odoo: debit cash/bank, credit COD liability clearing
  - Float visibility report by hub

Nightly (analyst-agent):
  - Projects next-day float
  - Overnight investment recommendation (CETES / money market funds)
  - CFO/Treasurer WhatsApp alert

Firestore collections (lastmile only): - cod_collections/{driverId}/shifts/{shiftId} — append-only - cod_settlement_events/{id} — reconciled settlements - cod_exceptions/{id} — variance flags


§08 — External Order Ingestion (carrier-integration)

The problem: lastmile contracted clients push orders via webhooks — not marketplace. Without this capsule, ingestion is manual.

Webhook endpoint per platform:
  POST /webhooks/meli/{operatorId}
  POST /webhooks/amazon/{operatorId}

carrier-integration Cloud Function:
  1. Authenticate (HMAC per platform spec; Amazon uses SigV4)
  2. Normalize payload → internal shipments/{id} schema
  3. Write to Firestore (platform-stamped, append-only)
  4. Trigger capacity-matcher: assign driver/zone/route batch
  5. Acknowledge within SLA window (MELI: < 2s)
  6. Failure: retry queue → dead-letter → ops alert

Each platform has its own auth model and payload schema. The normalization pipeline is shared. Future platforms (Temu, Shein) each require their own auth + payload adapter plugging into the same pipeline.

This capsule is the day-1 critical path for any lastmile operator with contracted clients. Build before marketplace-discovery for any lastmile deployment.


§09 — Density Routing (Lastmile)

ops-agent (Dispatch Optimizer) responsibilities for lastmile: - Receive ingested orders for next window from carrier-integration - Run VRP optimization: group by zone → assign drivers → sequence stops (time windows) - Generate per-driver multi-stop manifest, push to Driver Portal - Re-optimize in-flight on delivery confirmation or failure (rolling horizon) - Failed delivery → re-attempt queue or return-to-hub routing

Engine (see OQ-5 in BIZ-PLATFORM-MASTER-REF.md): - v1: Google OR-Tools (open source, self-hosted). 200-stop VRP with time windows in < 5s. - SaaS alternative: OptimoRoute — faster to integrate, per-route cost.


§10 — Flutter Portals

Lastmile Driver Portal (differences from longhaul)

  • Multi-stop manifest view — ordered stops with address, recipient, parcel count, COD amount, delivery window, special instructions. Map with current stop highlighted.
  • Stop-by-stop ePOD — one-tap: photo + GPS pin + COD capture. Designed for speed at 150+ stops/shift.
  • COD screen — pre-populated amount, payment method selector, confirmation capture.
  • Failed delivery workflow — reason code, photo, re-attempt or return-to-hub.
  • Shift close — COD reconciliation summary, remittance confirmation.

Lastmile Client Portal (differences from longhaul)

  • No marketplace booking (API-push only from MELI/Amazon)
  • Bulk delivery dashboard — SLA performance by batch, on-time rate vs. contract
  • Monthly invoice viewer — itemized by delivery count × contracted rate
  • Cost-per-delivery analytics by zone

§11 — Compliance Architecture

CFDI by delivery_model

delivery_model CFDI type Standard Retention
longhaul Carta Porte CFDI CFDI 4.0 + Carta Porte 3.0 5 years
lastmile Standard CFDI CFDI 4.0 (envío de paquetes) 5 years

Both: Finkok primary / SW Sapien fallback. Circuit breaker: 3× 5xx in 10min → failover 60min.

Biometrics, KYC, AML — unchanged from v1.0

See BIZ-PLATFORM-MASTER-REF.md §03.


§12 — Odoo Surface

Lastmile-specific reporting views

View Content
Revenue by client MELI / Amazon / others — daily, MTD, vs. budget
Cost per delivery by zone Unit economics by zone and hub
COD float by hub Real-time float position, projected overnight
Accounting period close Open period status, accrual balance, pending recognition events
Monthly invoice status Client → invoice draft → issued → paid pipeline
SLA performance On-time delivery rate vs. MELI/Amazon contracted SLAs

§13 — Infrastructure (Lastmile additions)

Component Lastmile addition
Firebase Auth delivery_model custom claim gates portal features
Firestore Additional collections: revenue_events, cod_collections, invoice_queue, cod_settlement_events
Cloud Functions Min 1 instance on carrier-integration webhook handler — platforms expect < 2s acknowledgment
Density routing Google OR-Tools on dedicated compute (CPU-intensive — not Cloud Functions)
Secret Manager + MELI webhook secret, Amazon SigV4 credentials

§14 — ampm Reference Implementation

ampm (Guadalajara MX, 217K+ deliveries/day) drove the lastmile sub-branch design. Parameters that shaped the architecture:

Parameter Value Architectural decision
Daily delivery volume 217K+ Confidence thresholds must minimize human review queue
MELI concentration ~67% of revenue carrier-integration is day-1 critical path
Daily COD float MXN 43M+ cod-treasury is treasury function, not feature
Driver stops/shift 150–200 Multi-stop portal is required
Accounting control Hard period cutoff Server-timestamp gating is non-negotiable
Phase 2 opportunity Temu/Shein open capacity marketplace-discovery activates here

Implementation sequence (validated on ampm analysis):

Weeks Focus Deliverable
1–6 Finance layer ePOD revenue recognition + Odoo + period controls
6–12 COD treasury Driver reconciliation, SPEI matching, float visibility
12–20 Carrier integration MELI/Amazon webhooks, dispatch pipeline
20+ Phase 2 Density routing, hub ops, marketplace-discovery

§15 — Monetization

Longhaul

Basic $49/mo · Pro $149/mo · Enterprise $499/mo · Trust Fee 2–3% · Insurance 10–15% · Carta Porte add-on $1.50–3.00/CFDI

Lastmile

Stream Rate Notes
Operator subscription $299–999/month Volume-tiered
ePOD audit fee MXN 0.50–2.00/delivery Compliance value for contracted clients
COD treasury Included in Pro+ Float reporting, SPEI matching
Carrier integration Included in Enterprise MELI/Amazon webhook integration
Phase 2: marketplace Trust Fee 1–2% Open capacity market

Revenue Projections

Milestone MRR ARR Run Rate
Beta Month 6 $9K $108K
Month 12 $85K $1.02M
Year 3 (longhaul + lastmile + Business OS) $2.5M+

§16 — GTM

Phase 1 — Hard Blockers (both sub-branches)

SA de CV · Conekta · PAC/Finkok · SAT CFDI · Truora/Metamap · Genda/Mutuus · LFPDPPP · Provider ToS · AML · WhatsApp API

Longhaul Phase 2

Lane Development Rep · External load boards (Cargamos, Traycap) · Marketplace supply growth

Lastmile Phase 2

marketplace-discovery for open capacity → target Chinese platforms (Temu, Shein) entering MX · Hub operations module · Routing engine upgrade

Target Markets

  • Longhaul v1.0: MX-US cross-border. Guadalajara–US routes.
  • Lastmile v1.0: MX urban operators. 10K–500K deliveries/day. Contracted clients (MELI, Amazon, pharma, dark stores).

§17 — Data Architecture: Dual Layer

Firestore alone is not sufficient for all operational needs. The two layers are complementary — not competing.

Layer Technology Purpose
Operational ledger Firestore (append-only) Legal source of truth for every event — delivery confirmations, COD collections, revenue recognition, compliance records. Real-time, multi-party, tamper-evident.
Analytics & intelligence PostgreSQL / DuckDB KPI computation, LLM briefing payloads, anomaly detection, first-attempt failure predictions. Populated from Firestore via nightly batch (DuckDB works well on tabular aggregations; PostgreSQL for joins at scale).

Why not Firestore for KPIs: Firestore is document-oriented and append-only. Aggregating ingresos_devengados / envíos_entregados across 217K daily documents requires pulling and summing in application code — expensive and slow. DuckDB can run this in < 1s on a columnar snapshot. The pattern: Firestore events write → nightly batch exports to columnar store → KPI queries run there.

Why not PostgreSQL/DuckDB for the legal record: Relational databases can be updated, deleted, and retrospectively modified by anyone with DB access. Firestore with server-timestamp enforcement and append-only security rules cannot. The legal record lives where it cannot be edited.


§18 — COD Treasury — Full Operational Spec

The basic cod-treasury architecture is in §07. This section adds the operational depth required at scale.

SPEI Settlement Cycle

SPEI settles in approximately 40 seconds during banking hours. The cod-treasury reconciliation agent must handle:

  • Banking hours (Mon–Fri 9am–6pm MX): SPEI deposits auto-match within 2 minutes of ePOD confirmation. Match by: amount + CLABE origin + transaction reference (if driver includes shipment ID).
  • Evening / overnight: SPEI still settles but reconciliation agent batches matching until next business morning. Float report shows "pending SPEI settlement" balance.
  • Weekends / holidays: SPEI BBVA/Banorte inter-bank may be delayed. Cash becomes dominant payment method. Reconciliation agent flags all weekend COD as "cash-only shift" and routes to hub cash count at Monday morning opening.

CETES Overnight Placement

The nightly investment trigger is not just an alert — it is a structured recommendation:

Inputs (from cod-treasury nightly aggregation):
  - Total confirmed float by 11pm MX = F_confirmed
  - Projected next-day COD = F_projected (from route assignments)
  - Minimum operating reserve = R (configurable, default MXN 2M)

Recommendation logic:
  - Investible float = F_confirmed - R
  - If investible_float > MXN 500K: recommend CETES overnight (28-day rolling)
  - If investible_float > MXN 5M: recommend fondos de dinero (T+0 liquidity)
  - WhatsApp to CFO/Treasurer: amount + instrument + expected yield + instructions

Odoo entry:
  - Debit: "Inversiones Temporales" account
  - Credit: "Efectivo y Equivalentes" account
  - Next morning: reverse on receipt of proceeds

Why this matters structurally: At MXN 43M daily float × 10.5% CETES rate ÷ 365 = MXN ~1.24M annual yield that sits idle without this logic. The cod-treasury capsule pays for itself on day one.

The entity-reputation capsule must add a cod_integrity_rate dimension for lastmile operators. This is not optional — COD fraud by drivers is the largest recurring loss vector in last-mile operations.

cod_integrity_rate = (
  shifts_with_zero_variance / total_shifts_closed
)

A driver who consistently reconciles to zero has a 1.0 cod_integrity_rate. One who consistently has "unexplained" cash variances trends toward 0. This feeds into the entity-reputation Trust Score at a 20% weight for lastmile — replacing the review_rate dimension which is less meaningful in a B2B contracted delivery model.

Updated entity-reputation scoring for delivery_model: "lastmile":

Trust Score (lastmile) =
  incident_rate × 0.40
  + completion_rate × 0.25
  + cod_integrity_rate × 0.20    ← replaces review_rate
  + compliance_standing × 0.15


§19 — Revenue Manipulation Monitor

The server-timestamp hard cutoff (§05) prevents backdating at the source. But manipulation can occur through other paths — rate misapplication, delivery count inflation, contract rate "errors." The revenue manipulation monitor catches these regardless of mechanism.

Monitor: ingresos_devengados / envíos_entregados ratio, computed weekly.

Rule: If (this_week_ratio - avg_last_4_weeks_ratio) / avg_last_4_weeks_ratio > 0.08
      AND week_over_week_delivery_volume_change < 0.05
      THEN: alert Finance + Ops via WhatsApp
            Write anomaly record to revenue_anomalies/{id} (append-only)
            Block period close until human review clears

Interpretation: Revenue per delivery rising >8% week-over-week with no volume justification
                is a red flag for rate misapplication or ghost deliveries.

This monitor runs independently of the timestamp cutoff — it detects manipulation through any remaining path. It runs on the DuckDB analytics layer (§17), not Firestore.

Firestore collection: revenue_anomalies/{id} — append-only, never cleared without CFO sign-off.


§20 — Morning Briefing (Canonical Lastmile Template)

The analyst-agent generates a daily morning briefing via WhatsApp to the operator's senior team. This template is canonical for any logistics.lastmile deployment — not ampm-specific.

System Prompt

You are the Delivery Intelligence analyst for a last-mile logistics operator.
Every morning at 6:30 AM MX time you generate a WhatsApp briefing for the operations
and finance team. You have access to:
- Yesterday's delivery performance (volume, completion rate, failed delivery rate by zone)
- Revenue recognized yesterday vs. plan
- COD float position (confirmed + pending SPEI + outstanding cash)
- Driver Trust Score movements (top 5 improvers, top 5 declines)
- MELI/Amazon SLA performance (on-time rate vs. contracted threshold)
- Any active revenue anomaly alerts

Generate a briefing that is:
- Under 300 words
- Starts with the single most important number (yesterday's net revenue recognized)
- Flags any anomaly that requires a decision today
- Ends with today's projected delivery volume and COD float estimate
- Written in the language configured for this operator (default: Spanish)
- Tone: direct, factual, no padding

n8n Payload Structure

{
  "trigger": "schedule_0630_MX",
  "payload": {
    "date": "YYYY-MM-DD",
    "deliveries_yesterday": {
      "total": 0,
      "completed": 0,
      "failed": 0,
      "completion_rate": 0.0,
      "top_failure_zones": []
    },
    "revenue_yesterday": {
      "recognized_mxn": 0,
      "plan_mxn": 0,
      "vs_plan_pct": 0.0,
      "anomaly_flag": false
    },
    "cod_position": {
      "confirmed_mxn": 0,
      "pending_spei_mxn": 0,
      "outstanding_cash_mxn": 0,
      "total_float_mxn": 0
    },
    "sla_performance": {
      "meli_ontime_rate": 0.0,
      "meli_contracted_threshold": 0.0,
      "amazon_ontime_rate": 0.0,
      "amazon_contracted_threshold": 0.0
    },
    "trust_score_alerts": [],
    "revenue_anomaly_alerts": [],
    "today_projected_deliveries": 0,
    "today_projected_cod_mxn": 0
  }
}

§21 — Phase 2 Capabilities

PUDO Network Management

PUDO (Pick-Up/Drop-Off) points are a Phase 2 lastmile capability that significantly reduces failed delivery rates in urban MX (typical failed delivery rate: 18–25% without PUDO option).

Concept: - Operator recruits local businesses (pharmacies, convenience stores, tlapalerías) as PUDO points - Each PUDO is scored for capacity, reliability, accessibility, and zone coverage - Failed deliveries → automatic PUDO re-routing notification to recipient (WhatsApp) - PUDO scores feed into entity-reputation system (same capsule, new entity type: pudo_point)

Capsule: pudo-network (spec pending — Phase 2). Dependency: entity-reputation, carrier-integration, capacity-matcher.

Dispatch Optimizer — WhatsApp Response Routing

The ops-agent (Dispatch Optimizer) Phase 2 enhancement: consume recipient WhatsApp responses to optimize next-day routing.

Pattern:
  Delivery notification sent to recipient via hr-agent
  Recipient replies: "No estaré mañana" / "Entrégalo después de las 6pm" / "Déjalo con el vecino del 201"
  NLP parser (analyst-agent) classifies response → time preference / absence / redirect
  ops-agent reads classified responses when building next-day manifest
  Driver manifest shows: preferred delivery time window per stop

This reduces failed delivery rate by 12–18% (industry benchmark for WhatsApp-enabled re-routing). It feeds directly into the first-attempt failure prediction model below.

First-Attempt Delivery Failure Prediction

Phase 2 ML capability. Predicts which stops in a driver's manifest are at risk of first-attempt failure — enabling proactive re-routing or recipient contact before the attempt.

Model: XGBoost on tabular features (no LLM required at inference time — fast, interpretable).

Feature Type
Stops in route Numeric
COD ratio (COD stops / total stops) Numeric
Historical zone completion rate (colonia-level) Numeric
Courier experience (days on platform) Numeric
Day of week + hour window Categorical
Weather proxy (rain probability) Numeric
Recipient WhatsApp response (if available) Binary/categorical
Previous failed attempts at this address Numeric

Accuracy trajectory: - Launch (thin data): 70–80% precision at 0.5 threshold - Month 6 (sufficient colonia-level history): 82–88% - Month 18 (full feature set + WhatsApp data): 88–95%

Integration: Dispatch Optimizer reads failure probability per stop. Stops above 0.7 threshold: recipient WhatsApp pre-notification sent automatically ("Hoy pasa tu paquete entre X–Y, ¿estarás?"). Operator KPI: first-attempt success rate (target: 88%+ by month 12 with full model).


§22 — Sequencing & Engagement Timeline

Now (April 2026)    → ampm interview process ongoing
                      Tractus fully specced, not yet built

April 15, 2026      → Tractus build begins (ACCELERATED — was June 12)
                      ampm Week 1: disclose Tractus context to Pablo
                      + propose Mode A Odoo deployment (works independently of Tractus)

May 28, 2026        → alaivOS Personal launch (separate product; Business runs parallel)

June 11, 2026       → FIFA World Cup 2026 kickoff (Personal marketing event)

Month 1–3 (ampm)    → Mode A Odoo Phase 1: core finance + CFDI + Odoo satellite
                      Tractus capsule builds in parallel (recognition, COD treasury)

Month 2–3 (ampm)    → Formal reference client proposal to Pablo (Day 60+ milestone)
                      "ampm gets features first, co-shapes the spec"

Month 3–6 (ampm)    → Tractus lastmile capsules come online
                      ampm deploys as first reference client

Month 6–12 (ampm)   → Full Tractus lastmile stack operational at ampm
                      Reference implementation complete — productize for next client

Phase 2 (12+ mo)    → marketplace-discovery activated (Temu/Shein open capacity)
                      PUDO network, failure prediction model, WhatsApp routing

Build priority order (April 15 start): 1. tractus-financeAgentRevenueRecognition Cloud Function 2. Odoo surface definition (logistics_surface_lastmile.json) — ampm chart of accounts 3. cod-treasury full implementation (SPEI cycle, CETES logic, cod_integrity_rate) 4. carrier-integration MELI adapter 5. carrier-integration Amazon adapter 6. Density routing (OR-Tools integration) 7. Multi-stop Driver Portal (Flutter) 8. Revenue manipulation monitor 9. Morning briefing pipeline (n8n + analyst-agent) 10. PUDO network capsule spec (Phase 2)