Long-Horizon Agent Full-Stack Practice: Building a Video Generation SaaS in Hours

    Long-horizon agent coding is shifting from snippets to shippable systems. This article walks through a spec-driven experiment that builds a minimum commercial loop for a short-video UGC generation SaaS—auth, uploads, async jobs, credits, isolation, and observability—and how to keep architecture, context, and engineering constraints consistent over a multi-hour task.

    The takeaway first: long-horizon agent coding is moving from “generate a snippet” to “deliver a system you can accept.” What matters is not whether one page looks polished, but whether the agent can keep architecture consistent, context coherent, and engineering constraints intact across a multi-hour automated task—and turn system-level requirements into a runnable, testable, operable loop.

    This article is a neutral technical experiment: use a coding assistant with long-horizon task capability to build, from scratch, a minimum commercial loop for a short-video UGC generation SaaS. It is not a demo page. It includes registration and login, asset upload, asynchronous video generation, job polling, credit deduction, data isolation, audit, and observability. The narrative follows why it is hard, how to specify it, how to architect it, how to implement it, and how to accept it.

    Why a full-stack long task is the right test

    A commercially viable video generation SaaS grows in complexity quickly. The backend must handle auth, rate limits, orchestration, and callbacks. The data layer needs users, a credit ledger, jobs, assets, outputs, and audit tables, plus row-level security. The async path must handle minutes-long generation with queues, retries, idempotency, and timeouts. Billing must pre-authorize, confirm, and refund without overcharging under concurrency. Operations still need logs, metrics, traces, and alerts.

    This is no longer a “write code” problem. It is system architecture plus engineering acceptance. Traditionally it takes product, backend, frontend, QA, and ops. A long-horizon agent’s value is that it can keep spec, architecture decisions, and implementation aligned in a long context, turning hours of work into a staged, reviewable pipeline. Evaluation should move from “can it generate” to “can it run, pass acceptance, scale, and be operated.”

    Spec-driven development: prompts become executable specs

    Long tasks fail when you chat and rewrite as you go. A more stable approach is spec-driven development (SDD): research, then architecture, then implementation, then acceptance. Each stage produces artifacts on disk. After each stage the agent writes a summary, decision log, and TODOs so context does not grow without bound.

    A spec should include goal, roles, boundaries, data model, API contracts, job state machine, acceptance cases, and non-functional constraints. Illustration:

    1. # Task spec (illustrative, not a real API)
    2. goal: Build a minimum commercial loop for a short-video UGC generation SaaS
    3. roles: [product, architecture, backend, frontend, QA, ops]
    4. boundary:
    5. - no social graph
    6. - no complex editing
    7. - image assets only for short-video generation
    8. acceptance:
    9. - users log in via phone OTP and receive a token
    10. - uploading an image creates a generation job whose status can be polled
    11. - success settles credits at actual cost; failure refunds automatically
    12. - users can access only their own jobs and assets
    13. non_functional:
    14. - idempotent jobs, idempotent billing, signed callbacks
    15. - queues with retry, dead-letter, and alerting

    The prompt no longer holds all context; the spec is the contract. The agent reads only the relevant spec and artifacts per stage, which reduces drift. Humans check delivery against acceptance cases instead of line-by-line code review.

    Architecture: from requirements to modules

    Split by ingress, application, domain services, orchestration, data, storage, and observability. A reasonable main path: submit job → reserve credits → insert job row → enqueue → generation worker consumes → callback or poll advances state → confirm charge or refund → notify the client.

    Define the state machine explicitly so states cannot jump arbitrarily:

    1. CREATED -> QUEUED -> RUNNING -> SUCCEEDED
    2. \-> FAILED -> REFUNDED

    Submit-job pseudocode wraps “charge + create job + enqueue” in an idempotency key:

    1. def submit_job(user_id, image_id, template_id, request_id):
    2. with transaction():
    3. if exists_idempotent(request_id):
    4. return existing_job(request_id)
    5. cost = estimate_cost(image_id, template_id)
    6. reserve_credits(user_id, cost, request_id)
    7. job = insert_job(status="QUEUED", owner_id=user_id, reserved=cost)
    8. enqueue("video.generate", job.id)
    9. return job.id

    Data model and row-level security

    Core tables: users, credit ledger, jobs, assets, outputs, audit logs. Do not store only a balance. Use ledger plus a balance snapshot: every reserve, confirm, and refund writes a ledger entry; the balance is updated idempotently so you can reconcile and attribute.

    Isolation cannot rely on application filters alone. Relational row-level security is a second line of defense. Illustrative SQL:

    1. CREATE POLICY job_owner_policy ON video_jobs
    2. FOR SELECT USING (owner_id = current_setting('app.user_id')::uuid);
    3. CREATE POLICY asset_owner_policy ON assets
    4. FOR ALL USING (owner_id = current_setting('app.user_id')::uuid);

    Every job query, asset download, and output access must check ownership. Admin actions write audit logs, sensitive fields are redacted, and secrets and config stay out of the repository.

    Async jobs and polling

    Generation is slow, so it must be asynchronous. Queue by priority and cost: throttle free or low-priority work; prefer paid jobs. Retries need max attempts, backoff, and a dead-letter queue. The generator should support timeout cancel and idempotent consume so charges are not applied twice.

    Frontend polling is enough for a minimum loop: submit returns a job ID; the client polls status on an interval. The backend can also advance state via callback when generation finishes. Callbacks must be signed, replay-protected, and applied idempotently against the state machine. Metrics that matter: queue depth, success rate, generation-duration percentiles, failure-reason mix, and cost per job.

    Auth and credit settlement

    Auth can be phone OTP plus tokens. OTP needs rate limits, anti-abuse, and expiry; tokens need refresh and revocation; critical APIs add device risk controls and frequency limits. Credits use a three-phase reserve–confirm–refund:

    1. def confirm_job(job_id, actual_cost):
    2. with transaction():
    3. job = lock_job(job_id)
    4. if job.status == "SUCCEEDED":
    5. return
    6. delta = actual_cost - job.reserved
    7. if delta > 0:
    8. charge_extra_or_fail(job.owner_id, delta, job_id)
    9. else:
    10. refund_credits(job.owner_id, -delta, job_id)
    11. job.status = "SUCCEEDED"

    Under concurrency, use idempotency keys and row locks or optimistic locking so one job cannot settle twice. Failed jobs refund automatically and record a reason so the ledger stays auditable.

    Observability and deployment

    A long-running system needs observability: structured logs with job ID and user ID; metrics for queue depth, consume rate, failure rate, generation latency, and ledger anomalies; traces that stitch submit–enqueue–generate–callback–settle; alerts on backlog, dead-letter growth, charge failures, and callback signature failures.

    Deploy with generic cloud building blocks: object storage for assets and outputs, a message queue for decoupling, a container platform for services, and logging plus monitoring for observability. If you use Baidu AI Cloud, map only to these generic capability categories and follow the official documentation; this article does not bind to specific APIs. Manage config and secrets centrally; release with canary and rollback.

    Collaboration tactics and failure modes

    First, context breakage is the largest risk. Fix it with specs, stage artifacts, and acceptance cases; write a decision log per stage; do not run one unbounded conversation. Second, agents invent APIs. Define contracts and generic interfaces first, then integration tests; describe external capabilities only by generic category. Third, scarce resources slow long tasks. Batch, cache stages, rate-limit, and resume from checkpoints so hours of work split into rerunnable stages. Fourth, security is not an afterthought: RLS, least privilege, audit, redaction, and callback signing belong in architecture. Fifth, acceptance is end-to-end: login, upload, submit, poll, success settlement, failure refund, unauthorized access, and duplicate callbacks, plus fault injection and a basic load test.

    Overall, long-horizon agents can already execute most of a system-level long task, but only with spec-driven work, architectural constraints, and automated acceptance. The next level of AI coding is not how much code is generated at once, but whether hours of work turn requirements into a runnable, acceptable, operable delivery. What is worth reusing is not a single prompt, but a method that splits long tasks into stages, turns stages into artifacts, and folds artifacts into acceptance.