Long-Horizon AI Agents Tested: Building a Video SaaS in Three Hours
This article reports a hands-on test of a long-horizon coding agent tasked with building a commercial video-generation SaaS in three hours. It explains why long-horizon tasks—not single-turn code completion—are the real dividing line for coding agents, and shows how spec-driven development, a six-plane architecture, asynchronous job handling, authentication and billing, and automated acceptance checks keep the agent on track. Readers will find the prompt skeleton, core data model, async pseudocode, common failure modes, and a reusable implementation checklist.
1. Why Long-Horizon Tasks Are the Real Dividing Line for Coding Agents
Over the past two years, the core metric for code generation has been single-turn completion accuracy: given a function signature, the model fills in the implementation; given an error, the model proposes a fix. These tasks operate on a scale of seconds, and the context window only needs to hold a single file. But once the goal shifts to “delivering a commercially usable system,” the nature of the problem changes completely: the time scale stretches from seconds to hours, the context expands from one file to dozens of files, and the constraints are upgraded from “it runs” to “it is operable, billable, and scalable.”
The difficulty of a long-horizon task lies not in writing a beautiful piece of code, but in three points:
- State retention: across an execution chain lasting hours, requirement decisions, interface contracts, and data models must not drift;
- Dependency closure: frontend routes, backend services, database migrations, and queue consumers must stay version-aligned;
- Failure recovery: after any step fails, the agent must be able to locate, roll back, and retry, rather than starting over.
Therefore, the standard for judging whether a coding agent has reached the “next level” is not how good the demo looks, but whether it can steadily advance system-level requirements to an acceptance-ready state without human intervention.
2. Experiment Design: Constraining the Agent with Spec-Driven Development
The goal of this experiment was a typical content-production SaaS: users upload product images and copy, the system automatically generates short videos, returns results asynchronously, and bills by usage. To keep the long task controllable, I adopted spec-driven development as the overall framework, forcing the agent to advance through four phases—research → architecture → development → acceptance—with each phase required to produce a document artifact on disk before moving to the next.
Prompt skeleton (pseudocode):
Phase 1 Research: output requirements list, role-permission matrix, non-functional metrics (concurrency/latency/availability)Phase 2 Architecture: output system context diagram, module breakdown, data model, interface contracts, failure modesPhase 3 Development: implement module by module; after each layer, run static checks and unit testsPhase 4 Acceptance: output deployment manual, rollback plan, load-test and observability metrics checklistConstraint: no phase may skip its document artifact; interface changes must update the contract document
The value of these constraints is that they split “uncontrollable long-form generation” into “checkable short loops.” Every step has a clear artifact and acceptance condition, and the probability of context drift drops sharply.
3. Architecture Breakdown: Six Planes of a Content-Production SaaS
To keep the agent from going off track, the architecture description must be concrete down to the “plane” level. I split the system into six planes:
- Access plane: web frontend plus open APIs, handling uploads, job submission, and result preview;
- Service plane: the business service layer, handling authentication, quotas, orders, and job orchestration;
- Data plane: a relational database for business entities, object storage for source assets and finished videos, and a cache layer for hot data and idempotency keys;
- Async plane: message queue plus consumers, carrying minute-level generation jobs so request threads are not held for long periods;
- Generation plane: a model-inference adapter layer that wraps different capabilities behind a unified interface for easy replacement and canary rollout;
- Ops plane: logging, metrics, tracing, alerting, and key management.
The core tables of the data model can be abstracted into four:
users(id, phone, created_at)projects(id, user_id, name, status)assets(id, project_id, storage_key, kind)render_jobs(id, project_id, status, progress, cost_credits, error_code)
Key design point: render_jobs must carry an idempotency key and cost fields, the state machine should be queued → running → succeeded/failed, and every state transition should be written to an event table to support replay and troubleshooting.
4. Async Jobs: The Right Way to Handle Minute-Level Generation
Video generation is a typical “long-running, result-oriented” task; synchronous waiting causes connection pile-up and timeout cascades. The correct approach has three stages:
- Submit: the API only validates parameters, pre-deducts quota, and persists the job, returning a job ID immediately;
- Consume: the consumer takes the job from the queue, updates progress, calls the generation adapter, and writes artifacts to object storage;
- Callback/polling: the frontend polls the status endpoint with exponential backoff, or uses server-side push; at the terminal state, quota is settled and recorded.
Pseudocode:
def submit(project_id, params):job = create_job(project_id, params, idem_key=sha256(params))quota.reserve(job.user_id, cost=estimate(params))queue.publish("render", job.id)return job.iddef consume(job_id):job = repo.get(job_id)job.mark_running()out = adapter.generate(job.params) # unified generation interfacestorage.put(out.key, out.bytes)job.mark_succeeded(out.key)quota.settle(job.user_id, cost=job.cost_credits)
Three protections must be built in: idempotency (a repeated submission returns the same job), timeout and retry (distinguishing retryable errors from terminal errors), and quota rollback (releasing the pre-deducted amount on failure).
5. Authentication, Billing, and Multi-Tenant Isolation
The three red lines for a commercial SaaS are account security, billing accuracy, and data isolation.
- Authentication: phone-number verification-code login exchanges for a short-lived access token plus a refresh token; a token-validation middleware intercepts uniformly; sensitive operations require a second check.
- Billing: use a three-state ledger of “pre-deduct + settle + rollback,” with every change written to a transaction table to guarantee reconcilability; do not scatter deduction logic across business code.
- Isolation: if a managed database is used, row-level security policies can serve as a fallback for multi-tenant isolation, but the application layer must still enforce a tenant identifier to avoid privilege escalation caused by a misconfigured policy.
Illustrative policy:
alter table projects enable row level security;create policy tenant_isolation on projectsusing (tenant_id = current_setting('app.tenant_id')::text);
6. Pitfalls and Lessons: Why Long Tasks Fail
In practice, the most common failures are not “the code is wrong,” but the following:
- Vague specs: requirements containing unverifiable descriptions like “high performance” or “friendly” leave the agent to improvise, causing rework later;
- Contract drift: an interface field is changed mid-way without syncing the frontend and docs, and everything blows up during integration;
- Ignoring non-functional requirements: concurrency, latency, and capacity are not defined upfront, so the architecture lacks a queue and cache;
- Missing acceptance scripts: without automated checks, the agent cannot self-evaluate, and errors accumulate toward the end;
- Hard-coded secrets: the generation phase takes the easy path and writes credentials into code; this must be forced to environment variables and a key-management service.
The corresponding improvement is to move “verifiability” to the front: every requirement carries an acceptance condition, and every module carries a check command, turning a long task into a series of decidable short tasks.
7. A Reusable Implementation Checklist
- Requirements phase: three tables first—role-permission matrix, non-functional metrics, billing rules;
- Architecture phase: six-plane breakdown + four core tables + interface contract document;
- Development phase: layered implementation, static checks and unit tests per layer, no cross-layer direct access;
- Async phase: the four essentials—idempotency key, state machine, event table, retry strategy;
- Security phase: token rotation, tenant isolation, key management, audit logs;
- Ops phase: structured logs, job success-rate and queue-latency metrics, cost dashboard and alert thresholds.
8. Conclusion: From “Generating Code” to “Delivering a System”
This experiment shows that the competitive focus of coding agents has shifted from single-point completion to long-horizon delivery. For developers, the real capability is no longer “how fast you write,” but “whether you can translate business goals into machine-executable specs and design a solid acceptance loop.” When specs are clear enough, constraints are explicit enough, and acceptance is automated enough, finishing a runnable content-production platform in three hours is not a coincidence but the inevitable result of an engineering methodology.
