← Research & specs
AdPilot · Corpus

AdPilot Server v1 — Architecture & API Specification

AdPilot Server v1 — Architecture & API Specification

Status: authoritative for services/api and apps/web. Written 2026-09-10 (T-014/T-015). Money rule applies: this server never calls a paid network service. All platform and content-generation integrations are sandbox adapters. Real providers require a task card whose acceptance criteria explicitly authorize credential handling.

0. Why a new backend (verdict on the old one)

apps/backend (Hono/TypeScript, 367 LOC) is a stateless agent gateway prototype: it plans a prompt, creates sandbox campaigns per platform, and forwards budget/status calls. It has no persistence, no metrics history, no assets, no content generation, no audit log. It served v0.1's demo well but cannot back a web product (Studio + DAM + dashboards).

Decision: build the real server in Go at services/api (T-014). apps/backend remains frozen and gated until the mobile app syncs to the Go API (backlog card), then it is deleted.

1. Goals / non-goals

Goals

  1. Durable server of record: campaigns, plans, daily metrics, audit log (SQLite).
  2. Content generation pipeline (image / video / copy) behind a provider interface, with a deterministic sandbox implementation that renders real bytes (PNG / GIF / text).
  3. DAM ("Library"): upload, tag, search, link-to-campaign, serve files.
  4. API contract clean enough that apps/web, the mobile app (later), and scripts are all clients.
  5. Guardrails carried over: per-account daily budget ceiling, validated payloads, audit log.

Non-goals (v1): multi-tenant auth (T-006 owns auth), billing (T-007), real ad-platform or real generation-provider calls, websockets/streaming, horizontal scaling. The single deployable is a modular monolith — internal packages are the seams for later service extraction.

2. Architecture

services/api/
  cmd/adpilot/main.go        # wiring, config, graceful shutdown
  internal/
    domain/                  # pure types + planner port + guards (no I/O)
    store/                   # SQLite (modernc.org/sqlite, pure Go), migrations (embedded SQL)
    api/                     # net/http handlers (Go 1.22 method-pattern mux), DTO <-> domain
    gen/                     # generation job orchestration
    adapters/                # platform + ContentGenerator sandbox adapters
  testfiles or *_test.go     # colocated tests
  Makefile                   # run / test / vet / smoke
  README.md
  data/                      # gitignored runtime state (adpilot.db + assets/)

3. Domain model

Mirrors apps/mobile/src/lib/types.ts so the engines stay interoperable. The Go agent must read that file plus platforms.ts, planner.ts, rng.ts, content.ts, metrics.ts and port faithfully; server-only fields are additive.

Guardrails: reject dailyBudget > MAX_DAILY_BUDGET_PER_ACCOUNT (env, default 200); reject platform budgets below the platform minimum (tolerance ×0.8, same as mobile); every mutating route appends a LogEvent.

4. API contract (all /v1, camelCase JSON)

Method & path Purpose Notes
GET /health liveness {ok, version, store, adapters}
POST /plans prompt → plan body {prompt}; heuristic planner port; {plan, engine:"heuristic"}
POST /campaigns launch plan body {plan, name?} → campaign + initial metrics day 0
GET /campaigns list ?status= filter
GET /campaigns/{id} detail
PATCH /campaigns/{id} status / budget body {status?, dailyBudget?}; guardrails enforced
GET /campaigns/{id}/metrics history ?days= (default all)
POST /campaigns/{id}/advance simulate one day demo affordance; appends DailyMetrics
POST /campaigns/{id}/assets link asset body {assetId}
DELETE /campaigns/{id}/assets/{assetId} unlink 204
POST /generations create generation body {kind, brief, platform?, tone?, count?, campaignId?}; processed synchronously, returned done (or failed + error)
GET /generations list ?status=
GET /generations/{id} detail
GET /assets DAM list ?kind=&campaignId=&q= (q matches name/brief/tags)
GET /assets/{id} metadata
GET /assets/{id}/file bytes correct Content-Type, Cache-Control: max-age=31536000, immutable
POST /assets/upload upload multipart file, name, tags (CSV); kind inferred from MIME
PATCH /assets/{id} rename / retag body {name?, tags?}
DELETE /assets/{id} delete 204; removes file + links
GET /logs audit ?limit= (default 100, newest first)

Validation: every body is schema-checked; unknown fields ignored; 400 with {"error"} on bad payloads; 404 on missing ids; 405/404 fallthrough handled centrally.

5. Sandbox content-generation contract

ContentGenerator interface in adapters: Generate(ctx, Brief) ([]RenderedAsset, error) where Brief = {kind, product, message, tone, platform, count, seed}. Three sandbox implementations:

  1. Copy — deterministic template bank per (platform, goal, tone); returns count (≤3) variants: headline ≤40 chars, body ≤90 chars, cta. Seeded by SHA-256 of the brief fields.
  2. Image — deterministic generative placeholder PNG via image/png + golang.org/x/image (basicfont for the small caption only): platform-sized canvas (meta 1080×1080, google 1200×628, microsoft 1200×628, tiktok 1080×1920), seeded gradient mesh + geometric composition + product monogram (first letters of the product). No network, no font binaries shipped.
  3. Video — same generative system animated: 8-frame GIF (stdlib image/gif), 720×720 or 540×960 by platform, gradient phase shift + monogram scale pulse.

Rules: generation is synchronous, <2s per asset, pure function of the brief (byte-identical reruns). Real providers (OpenAI images, Runway/Luma, ElevenLabs…) implement the same interface in separate future task cards; none are wired now.

6. Storage & seed

7. Gates & CI

8. Web client (apps/web) — contract summary

Vite + React + TypeScript strict. Talks only to this API via /v1 (Vite dev proxy to http://localhost:8080). Screens: Dashboard, Plan, Studio (generation), Library (DAM), Campaign detail. Client-side derivations (ROAS, WoW deltas, pacing, alerts) port the mobile optimizer.ts heuristics. Full design direction lives in the T-015 card; visual language must match the v3 "mission control" token system in apps/mobile/src/theme.ts.

9. Deprecation path

  1. T-014 (this): Go server is the backend of record for web.
  2. Backlog: mobile app gains a server-sync mode reading this API (same shapes).
  3. After that: delete apps/backend, drop its CI job, update AGENTS.md gates.