Skip to main content
Codex CLI — Case Study

How I Built a 9-Agent AI Platform With Two Codex /goal Commands

I did not write the code. I wrote the spec — twice. Here is exactly what Codex CLI built from each /goal command, what the architecture looks like, what surprised me, and why the quality of the spec was the only thing that mattered.

Eight Labs · May 2026

2goals submitted
9agents generated
230ktokens total
~47 minwall clock

01 — What is /goal

Not a prompt. A lifecycle object.

Most developers use Codex CLI like an autocomplete with a bigger context window — one prompt, one response, done. The /goal command is a different thing entirely. It attaches a persistent, server-side lifecycle object to a thread. The runtime re-engages the model automatically using continuation turns, tracking token and time budgets, until the objective is achieved — or you pause it.

Compare this to /plan, which generates a checklist for the current session and disappears when you close the tab. A goal survives reconnects, overnight runs, and laptop closes. State is stored server-side. The model does not forget it.

To enable it, add two lines to ~/.codex/config.toml:

[features]
goals = true

Requires Codex CLI v0.128.0 or newer.


02 — The First Command

The backend. 150,000 tokens. 9 agents.

This is the exact spec submitted as Goal 1. Every file, agent, route, and database table you see in the repo came from this text.

Goal 1 — submitted verbatim
/goal Build a production-grade Python AI platform called "Creator Intelligence Agent".

Core Objective:
Users submit a YouTube channel URL or Instagram profile URL.
The system fetches all public creator content using Apify actors, analyzes the content using Gemini multimodal AI, and generates strategic creator intelligence reports explaining:
* what is working
* what is not working
* why certain videos/posts perform better
* what future content should be created

Primary Stack:
* Python 3.12
* FastAPI
* PostgreSQL
* SQLAlchemy
* Redis
* Celery
* Docker Compose
* LangGraph
* Gemini 2.5 Pro API
* Apify SDK/API
* pgvector for embeddings
* Playwright (fallback only)

High-Level System Design:
The platform must use multi-agent orchestration.

Required Agents:
1. Channel Discovery Agent
2. Content Fetch Agent
3. Transcript Intelligence Agent
4. Thumbnail Intelligence Agent
5. Hook Analysis Agent
6. Engagement Pattern Agent
7. Viral Pattern Agent
8. Recommendation Strategist Agent
9. Report Generation Agent

Core Workflow:
1. User submits YouTube channel URL or Instagram profile URL
2. System creates project/job
3. Apify actors fetch: videos, reels, posts, thumbnails, captions, hashtags, comments, engagement metrics, publish dates
4. System stores structured data
5. Gemini analyzes: transcript quality, hook effectiveness, emotional intensity, storytelling structure, thumbnail psychology, CTA quality, pacing patterns, educational density, retention likelihood
6. AI agents generate strategic recommendations
7. Final creator intelligence report generated

Apify Requirements:
Use Apify for YouTube scraping, Instagram scraping, channel crawling, metadata extraction, comments extraction.
Implement: actor runner service, webhook support, retry logic, polling fallback, rate limiting, async ingestion.

Gemini Requirements:
Use Gemini multimodal capabilities to analyze: video transcripts, thumbnails, sampled video frames, captions, hooks, emotional tone, pacing, content structure.
Gemini must generate: engagement reasoning, viral hypotheses, content quality scores, hook effectiveness scores, thumbnail quality scores, future content recommendations.

Video Intelligence Features:
For every video/post: classify content category, detect content style, detect emotional tone, detect CTA patterns, detect curiosity hooks, detect storytelling quality, generate engagement score, generate viral probability estimate.

Insight Examples:
* "Videos with strong curiosity hooks in first 3 seconds perform 2.8x better."
* "Face-focused thumbnails outperform text-only thumbnails."
* "Tutorial content between 35-60 seconds drives highest engagement."
* "High-energy pacing correlates with better completion rates."

Embeddings + AI Memory:
Use pgvector for: semantic clustering, topic grouping, trend similarity, recurring pattern detection, content gap analysis.

Required APIs:
POST /projects
POST /projects/analyze
GET /projects/:id
GET /projects/:id/report
GET /projects/:id/recommendations
GET /projects/:id/videos
GET /health

Database Tables:
creators, channels, videos, reels, posts, thumbnails, transcripts, comments, ai_analysis, ai_recommendations, embeddings, jobs

Infrastructure Requirements:
* fully dockerized
* .env support
* structured logging
* OpenTelemetry-ready logging
* async workers
* retry queues
* resilient ingestion
* API authentication
* Swagger docs

Folder Structure:
backend/agents/ workers/ services/ apify/ gemini/ db/ api/ models/ prompts/ tests/ docker/

Prompt Engineering:
Create reusable prompt templates for: hook analysis, thumbnail analysis, storytelling analysis, engagement analysis, viral scoring, recommendation generation.

Testing: pytest, integration tests, mocked Apify responses, mocked Gemini responses, API tests.

README Requirements: setup guide, architecture diagram, agent workflow, environment variables, local development instructions.

Success Criteria:
1. User submits creator URL
2. System fetches 50+ pieces of content
3. Gemini analyzes content successfully
4. AI generates strategic insights
5. Reports explain WHY content performs
6. Recommendations are actionable
7. APIs are production-ready
8. Docker environment runs locally

Constraints: modular architecture, async-first design, strongly typed Python, avoid massive service files, reusable prompt system, scalable worker architecture, structured JSON outputs.

Budget: 150000 tokens

What Codex shipped

Generated file structure
backend/
├── agents/
│   ├── channel_discovery.py
│   ├── content_fetch.py
│   ├── transcript_intelligence.py
│   ├── thumbnail_intelligence.py
│   ├── hook_analysis.py
│   ├── engagement_pattern.py
│   ├── viral_pattern.py
│   ├── recommendation_strategist.py
│   └── report_generation.py
├── workers/           # Celery task definitions
├── services/
│   ├── apify/         # Actor runner, webhooks, retry logic
│   └── gemini/        # Multimodal analysis client
├── db/                # SQLAlchemy models + pgvector
├── api/               # FastAPI routers
├── prompts/           # Reusable Jinja2 prompt templates
├── tests/             # pytest + mocked Apify/Gemini
├── docker/
│   └── docker-compose.yml
└── .env.example
150,247tokens consumed · Goal 1 complete · FastAPI docs live at localhost:8000/docs

03 — The Architecture

What Codex actually designed

The spec named the technologies. Codex made the architectural decisions — how agents communicate, how Apify results flow into Gemini analysis, how embeddings feed clustering. Here is what it built.

The 9 agents

01
Channel Discovery Agent
Resolves a YouTube or Instagram URL to canonical channel/profile metadata
02
Content Fetch Agent
Runs Apify actors to retrieve videos, reels, posts, thumbnails, captions, comments
03
Transcript Intelligence Agent
Extracts transcripts, scores hook quality, educational density, and pacing
04
Thumbnail Intelligence Agent
Runs Gemini multimodal analysis on thumbnails — face, text, emotional signal
05
Hook Analysis Agent
Scores first-3-second curiosity hook effectiveness across all content
06
Engagement Pattern Agent
Correlates content attributes with views, likes, comments, completion rate
07
Viral Pattern Agent
Identifies recurring patterns in top-performing content vs low performers
08
Recommendation Strategist Agent
Generates actionable future content recommendations with priority scores
09
Report Generation Agent
Compiles all agent outputs into a structured creator intelligence report

API surface

POST/projectsCreate a new analysis project
POST/projects/analyzeTrigger the full agent pipeline
GET/projects/:idGet project status and metadata
GET/projects/:id/reportGet the final AI report
GET/projects/:id/recommendationsGet actionable recommendations
GET/projects/:id/videosBrowse analyzed content items
GET/healthHealth check endpoint

Database tables (pgvector + PostgreSQL)

creatorschannelsvideosreelspoststhumbnailstranscriptscommentsai_analysisai_recommendationsembeddingsjobs

04 — The Second Command

The frontend. 80,000 tokens. 8 pages.

With the backend running, I submitted a second /goal for the Next.js dashboard. Codex had no memory of Goal 1 — the spec described the backend API surface it needed to connect to.

Goal 2 — submitted verbatim
/goal Build a production-ready Next.js frontend for the existing Creator Intelligence Agent backend.

Objective:
Create a modern dashboard where users can submit a YouTube channel URL or Instagram profile URL, track analysis progress, and view AI-generated creator intelligence reports.

Frontend Stack:
* Next.js 15
* React 19
* TypeScript
* Tailwind CSS
* shadcn/ui
* Recharts
* TanStack Query
* Zod
* React Hook Form
* Axios or fetch client

Required Pages:
1. Landing / Dashboard
2. Create Analysis Project
3. Project Detail
4. Processing Status
5. Creator Report
6. Recommendations
7. Videos / Posts Explorer
8. Settings / API Keys

Core Features:
1. URL submission form — Accept YouTube channel URL, Accept Instagram profile URL, Validate URL type, Submit to backend API
2. Project dashboard — List previous analysis projects, Show platform type, Show creator/channel name, Show status: queued/processing/completed/failed, Show created date
3. Analysis progress screen — Poll backend job status, Show progress steps: Fetching content from Apify, Extracting metadata, Running Gemini analysis, Generating recommendations, Preparing report
4. Creator report page — Executive summary, What is working, What is not working, Top-performing themes, Weak content patterns, Hook analysis, Thumbnail analysis, Posting frequency insights, Audience engagement insights
5. Recommendations page — Suggested content ideas, Suggested titles, Suggested hooks, Thumbnail suggestions, Posting schedule suggestions, Priority score, Expected impact
6. Content explorer — title/caption, thumbnail, platform, views, likes, comments, engagement rate, AI score, publish date, category
7. Charts (Recharts) — views over time, engagement by content category, top-performing formats, posting frequency, AI score distribution
8. Settings page — Backend API URL, Apify key status, Gemini key status, Optional API key entry fields

API Integration:
POST /projects, POST /projects/analyze, GET /projects, GET /projects/:id, GET /projects/:id/report, GET /projects/:id/recommendations, GET /projects/:id/videos, GET /health

Frontend Requirements:
* Clean responsive UI
* Dark/light mode support
* Loading states, Empty states, Error states
* Toast notifications
* Skeleton loaders
* Mobile responsive layout
* Typed API client
* Environment variable NEXT_PUBLIC_API_BASE_URL
* No hardcoded localhost except in .env.example

Folder Structure:
frontend/app/ components/ components/ui/ features/projects/ features/reports/ features/recommendations/ features/content/ lib/api/ lib/types/ lib/utils/ hooks/ styles/

Design Direction: Professional SaaS dashboard, clean creator intelligence feel, use cards/tables/charts/insight blocks, make the report feel premium, avoid clutter, use strong hierarchy.

Success Criteria:
1. User can submit a YouTube or Instagram URL
2. Frontend creates an analysis project
3. User can see project status
4. User can open generated AI report
5. User can view recommendations
6. User can browse analyzed videos/posts
7. Charts render from backend data
8. App is responsive
9. TypeScript has no errors
10. npm run build passes

Budget: 80000 tokens

What Codex shipped

/
Landing / Dashboard
Project list with status chips
/projects/new
Create Analysis
URL submission form with validation
/projects/:id
Project Detail
Processing progress with live polling
/projects/:id/report
Creator Report
Executive summary + insight blocks
/projects/:id/recommendations
Recommendations
Priority-sorted content idea cards
/projects/:id/videos
Content Explorer
Filterable table with AI scores
81,903tokens consumed · Goal 2 complete · Dashboard live at localhost:3008 · npm run build passing

05 — What Surprised Me

Four honest observations

Not everything went perfectly. Here is what actually happened.

What Codex nailed

The agent orchestration. LangGraph was wired correctly on the first pass — each agent had typed inputs and outputs, clear handoff logic, and retry handling built in. I expected to rewrite this entirely. I didn't touch it.

What needed a nudge

The Apify webhook integration was initially polling-only. The /goal spec mentioned webhooks but Codex implemented the polling fallback as the default. One follow-up prompt flipped the priority. The spec was right — the implementation needed steering.

The budget_limited moment

Goal 1 hit budget_limited at 147,000 tokens with the pgvector embedding pipeline incomplete. Codex produced a clean wrap-up summary: what was done, what was blocked, what to run next. That summary became the input for a continuation goal. It was a handoff document, not a failure.

The spec quality insight

The folder structure in the spec was not a suggestion — it was the architecture. Every folder Codex created matched the spec exactly. The spec was load-bearing. A vague spec would have produced a vague codebase.


06 — The Repo

Run it yourself

The full codebase — backend, frontend, Docker Compose, tests — is on GitHub. You need an Apify API key and a Gemini API key to run analysis. The health endpoint works without either.

git clone https://github.com/eightlabs08/creator-intelligence-agent
cd creator-intelligence-agent
cp .env.example .env   # add APIFY_API_KEY + GEMINI_API_KEY
docker compose up
View on GitHubAPI docs: localhost:8000/docsDashboard: localhost:3008

07 — Key Takeaway
The one rule

The spec is the architecture. A vague spec produces a vague codebase.

Every agent name, folder, route, and table you see in this repo came from the text of the /goal command. Codex did not invent any of it. It implemented what the spec described — precisely and completely. The spec was load-bearing the moment it was submitted.

This changes how you should think about writing specs. It is not documentation. It is not a suggestion. It is the first line of code you write — and the most important one.


Watch the full tutorial

The complete Codex /goals walkthrough

The full screen recording — including every /goal command submitted, the live agent pipeline running, the budget_limited moment, and the CI/CD integration pattern — is on the channel.