PART 02 — PHASE 1 · REVIEWED 31 AUG 2026

Proposed service boundaries.

A reference design for separating seven bounded responsibilities through typed events. It is a discussion model—not a requirement to deploy seven agents or a production blueprint.

45–60 Min Architecture Systems Thinking

This part is architecture for review, not implementation guidance. A qualified team must threat-model the actual workflow and verify current platform APIs, terms and law. Begin with one read-only or proposal-only service using synthetic fixtures, then require representative, adversarial and regression evaluation, explicit approval, observability, stop conditions and rollback before any write authority.

The system, at a glance

Seven proposed services, a tenant-isolated event store, and an orchestrator. Each service has one responsibility, a typed input and output, an explicit identity, a data boundary and failure handling. Analysis services read approved views and emit proposals; only a separate deterministic executor with human-approved authority may perform a material write.

SALLA / ZID store orders + customers SHOPIFY store orders + customers META ADS API campaigns, insights, library TIKTOK ADS API campaigns, creative center WHATSAPP API messages + events PERMITTED PUBLIC DATA terms + provenance THE DATA SPINE tenant isolation · typed events · append-only proposals · audited execution SCOUT Agent 01 gap detection 4h cadence CREATIVE Agent 02 ad generation on-trigger ANALYST Agent 03 monitor 1h cadence OPTIMIZER Agent 04 budget proposals event-driven RETARGETER Agent 05 audience refresh 48h cadence REPORTER Agent 06 daily brief 08:00 daily CLOSER Agent 07 WA handler event-driven ORCHESTRATOR · event bus + scheduler Inngest · Temporal · or n8n self-hosted YOU (OPERATOR) reviews · approves · directs CANDIDATE MODEL A task-specific eval quality + safety CANDIDATE MODEL B task-specific eval schema + reliability SIMPLE BASELINE rules / templates compare before adding LLM EMBEDDINGS voyage-3 pgvector

Event-driven vs polling — and when to use which

Half the agents wake on a timer. Half wake when something happens. Mixing these correctly is the difference between a responsive system and one that either wastes compute or misses windows.

⏱ Polling (timer-based)

Agent wakes on a fixed interval regardless of activity. Simple to reason about. Wasteful if the system is quiet — but predictable.

Use for:

  • Scout (every 4h)
  • Analyst (every 1h)
  • Retargeter (every 48h)
  • Reporter (daily 08:00)
⚡ Event-driven (reactive)

Agent wakes when a specific signal fires — webhook, DB change, message in queue. Responsive but adds coordination complexity.

Use for:

  • Creative (wakes on Scout output)
  • Optimizer (wakes on Analyst flag)
  • Closer (wakes on WA message)

Model routing — evaluate candidates per task

There is no permanent best-model map. Define the task, language mix, risk, latency and cost constraints; build representative normal, edge and adversarial cases; compare a simple non-LLM baseline and current eligible models; then pin the chosen model and rerun regression tests before any change.

Service
Baseline
Evaluation focus
Scout
Rules + retrieval
Source fidelity, permission, unsupported inference, freshness
Creative
Human brief
Arabic/RTL, claims, rights, culture, accessibility, diversity
Analyst
SQL + thresholds
Schema validity, arithmetic, lag, false alerts, explanations
Proposal service
Deterministic policy
Never grants write authority; policy and approval are external
Audience steward
Eligibility query
Consent, suppression, minimization, isolation, deletion
Reporter
Template
Citation coverage, Arabic quality, uncertainty, decision utility
Support drafter
Approved FAQ
Correct resolution, escalation, privacy, policy, accessibility
Total cost Measure model, infrastructure, integration, review, support, security, privacy, evaluation and incident-response cost in your pilot. Do not borrow a monthly figure from this lesson.

Agent contracts — the TypeScript interface every agent implements

Treat each service as an untrusted proposal generator behind typed validation. Idempotency applies to the surrounding operation—not automatically to a model call. A retry must not duplicate a campaign, message, audience or order action.

// Every agent implements this contract interface Agent<TInput, TOutput> { name: string; version: string; modelVersion: string; // pinned after task-specific eval // The main function. Idempotent. Safe to retry. run(input: TInput, ctx: RunContext): Promise<TOutput>; // Validates output before writing to spine. Fails loud. validate(output: TOutput): ValidationResult; // Evaluation metrics. Computed per run for observability. evaluate(input: TInput, output: TOutput): EvalScore; } interface RunContext { readStore: TenantScopedReadStore; proposals: AppendOnlyProposalQueue; // no platform writes llm: LLMClient; // model-agnostic wrapper logger: StructuredLogger; storeId: string; // enforced server-side tenant isolation traceId: string; deadline: string; triggeredBy: "timer" | "event" | "manual"; }

The orchestration pattern — who triggers who

Agents talk through events on the spine, not through function calls. This is the same pattern Stripe, Shopify, and most serious SaaS products use internally. It sounds like overkill until you need to retry a failed agent run from 48 hours ago — then it's the only thing that saves you.

T + 00:00 · Timer fires
Scout wakes (every 4h)
Pulls competitor ad library snapshots. Runs pattern analysis. If gap detected, writes opportunity_brief event to spine.
T + 00:02 · Event fires
Creative wakes (on opportunity_brief)
Reads the brief. Generates 18–30 ad variants. Writes variant_batch event. Variants sit in REVIEW_QUEUE state until operator approves.
T + 01:00 · Timer fires
Analyst wakes (every 1h)
Scans last 24h of campaign data. Detects anomalies (CTR decay, CPA spikes, audience saturation). Writes anomaly_flag events per-campaign.
T + 01:05 · Event fires
Optimizer wakes (on anomaly_flag)
Reads a validated flag and current policy. Drafts a capped budget_proposal with evidence and expiry. No model credential can write to Meta or TikTok. A named operator approves the exact change before a separate idempotent executor acts.
T + 48:00 · Timer fires
Retargeter wakes (every 48h)
Evaluates a consented, minimized and suppression-filtered cohort after the normal delivery/return lag. Produces an eligibility report; any destination upload follows current platform terms and separate approval.
T = 08:00 daily · Timer fires
Reporter wakes
Reads the last 24h of events across all agents. Generates a plain-Arabic WhatsApp message summarizing what happened. Delivers to operator's WhatsApp.
Continuously · Event fires
Closer wakes (on WA message)
An eligible incoming WhatsApp message enters a tenant-isolated support queue. The service drafts from approved facts; uncertainty, complaints, payment/refund decisions, safety issues and unsupported languages escalate to a trained person.

Shared state — the canonical schema

Every agent reads and writes to the same few tables. Don't let agents own private state — it becomes impossible to reason about. Part 3 specs the full schema; here's the high-level shape.

-- Core tables every agent reads from CREATE TABLE orders ( id uuid PRIMARY KEY, store_id uuid NOT NULL, -- enforce tenant policy on every query store_platform text, -- 'salla' | 'zid' | 'shopify' payment_method text, -- 'card' | 'cod' | 'apple_pay' | ... cod_status text, -- 'pending' | 'delivered' | 'cancelled' ordered_at timestamptz, delivered_at timestamptz, -- NULL until confirmed delivered value_usd numeric, customer_id uuid ); CREATE TABLE ad_campaigns ( id uuid PRIMARY KEY, store_id uuid NOT NULL, platform text, -- 'meta' | 'tiktok' campaign_external_id text, status text, -- active | paused | killed daily_budget_usd numeric, last_optimized_at timestamptz ); CREATE TABLE agent_events ( id uuid PRIMARY KEY, store_id uuid NOT NULL, agent_name text, -- 'scout' | 'creative' | ... event_type text, -- 'opportunity_brief' | 'anomaly_flag' | ... payload jsonb, -- typed per event_type fired_at timestamptz, consumed_by text[] -- which agents have acted on this );
Core Principle

Make consequential state authoritative, tenant-scoped and auditable outside the model. Append events with trace IDs and versions; use access policies, retention and deletion rules; and derive current state through tested deterministic code. A database alone does not guarantee isolation or correctness.

Choose orchestration libraries through a current security and operability review. Whether custom or third-party, pin dependencies, inspect data flow and permissions, test failure recovery, and ensure an operator can trace every proposal and external write.

Failure modes — what breaks and how to handle it

Failure mode · 01
LLM timeout / rate limit
Retry bounded, idempotent reads with exponential backoff and jitter. Do not switch models without passing the same evaluation and policy; expire stale work and alert the owner.
Failure mode · 02
Invalid JSON from LLM
Run Zod/Pydantic validation. Re-prompt with error message inline. Cap at 2 re-prompts. Log to agent_errors.
Failure mode · 03
Meta API 5xx
Keep the proposal pending. A write executor uses platform-specific idempotency/deduplication, expiry, rate limits and bounded retry; uncertain results require reconciliation before another attempt.
Failure mode · 04
Conflicting agent writes
No model-facing service writes budget. A separate executor enforces tenant, exact approval, expiry, current version, spend cap and idempotency server-side; database policy is defense in depth.
Failure mode · 05
Creative generates policy-violating ad
Use deterministic claim, URL, rights and asset checks plus representative/adversarial review by qualified humans. A classifier is fallible and cannot establish policy compliance.
Failure mode · 06
Closer escalates a VIP customer poorly
Minimize and protect transcripts, honor retention/deletion, review errors and accessibility, and escalate by issue risk—not inferred status. Test appeal and correction paths.

Don't let agents write to external APIs synchronously. Always queue the write and apply it via a worker. This gives you retries, audit logs, and the ability to hold writes during a debugging session without breaking the agents themselves.

Don't share prompts between agents. Each agent owns its prompts in a versioned directory. When Scout's prompt changes, Creative shouldn't break. Versioning is cheap; regressions are expensive.

Don't confuse a self-score with evaluation. Use independently labelled representative, adversarial and regression sets; sample production proposals for human review; monitor drift and harm; and stop automatically when a pre-committed guardrail fails.

Recap

1
Tenant-isolated authoritative state and append-only proposal evidence.
2
Event bus + scheduler as the orchestrator.
3
Polling for routine work. Event-driven for reactive work.
4
Typed contracts. Every agent has input/output/validation/evaluation.
5
Task-specific model selection against a simple baseline and current evaluation set.
6
Fail closed. Bound retries. Require human approval, stop controls and tested rollback.

Part 3 goes into the data spine schema, the API integrations (Salla, Zid, Shopify, Meta, TikTok, WhatsApp), and the exact Supabase setup. After that, Parts 4–7 cover each agent in full.

← Part 1 — The GCC Market Part 3 — Data spine & APIs →