AdPilot Server v1 — Architecture & API Specification
AdPilot Server v1 — Architecture & API Specification
Status: authoritative for
services/apiandapps/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
- Durable server of record: campaigns, plans, daily metrics, audit log (SQLite).
- Content generation pipeline (image / video / copy) behind a provider interface, with a deterministic sandbox implementation that renders real bytes (PNG / GIF / text).
- DAM ("Library"): upload, tag, search, link-to-campaign, serve files.
- API contract clean enough that
apps/web, the mobile app (later), and scripts are all clients. - 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/)
- Transport: stdlib
net/http(method-pattern routing), JSON, all routes under/v1, camelCase JSON keys (matches the TypeScript clients). Errors:{"error": "..."}with correct status codes. - Store: SQLite in WAL mode; migrations as embedded SQL applied on boot; all times RFC3339 UTC.
- Determinism: same RNG discipline as the mobile engine (mulberry32, seeded from ids/dates) so demo metrics and sandbox renders are reproducible.
- Logging:
log/slogto stdout. Observability:/healthreports version + store + adapter set.
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.
PlatformId:meta | google | microsoft | tiktok(same as mobilePLATFORM_SPECS, which carryminDailyBudget, benchmark CTR/CPM).CampaignPlan: prompt, product, category, goal, dailyBudget, days, platforms[] (each with platform, dailyBudget, rationale), audience {description, ageRange, interests}, estimatedKpis.Campaign: id, name, status (active|paused), goal, dailyBudget, days, platforms[], audience, createdAt, updatedAt.DailyMetrics: date (YYYY-MM-DD), spend, impressions, clicks, conversions, revenue.Asset(DAM): id, kind (image|video|copy), name, mimeType, width, height, byteSize, tags[], source (generated|uploaded), brief, generationId, campaignIds[], createdAt, fileUrl (/v1/assets/{id}/file).Generation: id, kind, brief, platform, tone, count, status (queued|done|failed), error, assetIds[], createdAt, completedAt.LogEvent: id, ts, actor (system|api), event, details (free-form object).
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:
- 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. - 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. - 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
data/adpilot.db(SQLite WAL) +data/assets/{id}.{ext}; both gitignored.- First boot on an empty DB seeds: 3 demo campaigns with 14 days of metrics (one TikTok campaign
with a recent 3-day dip so client-side alert detection fires), 6 assets (3 image, 1 video,
2 copy) linked across campaigns, and matching log events — mirroring the mobile
seed.tsspirit.
7. Gates & CI
- Local:
cd services/api && gofmt -l .(empty),go vet ./...(clean),go test ./...— ≥15 tests covering store CRUD/migrations, planner port bounds & platform minimums & locked-requested-platforms, generation determinism (two runs byte-identical), every endpoint viahttptestincl. 400/404 paths, budget ceiling guardrail. - Smoke:
make smokeboots the server on an ephemeral port with a temp data dir and curls the full happy path (health → plan → launch → advance → generate image → fetch asset bytes → list). - CI:
.github/workflows/ci.ymlgains aservices/apijob (setup-go 1.23, vet + test) alongside the mobile/backend jobs.
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
- T-014 (this): Go server is the backend of record for web.
- Backlog: mobile app gains a server-sync mode reading this API (same shapes).
- After that: delete
apps/backend, drop its CI job, update AGENTS.md gates.