Studio grew to many generators, each with its own models, prompts and renderers. The architecture exists to answer one question as that number grew: when I change the card-news pipeline, what else can break? The answer it aims for is "nothing outside that package", and this page is about how far the code gets towards that, including where it falls short.

Layers

Three bands. Apps, the deployables: studio-web on Next.js 15 and React with one client wrapper for the API; studio-api on FastAPI with explicit router registration, a lifespan and a scheduler; a task registry of asyncio tasks in the API process, one per document id; and a scheduler with APScheduler cron jobs and a 60-second schedule tick. Domain packages, one bounded context each: api, the routes and dependencies the app registers; usecases, holding pipelines, nodes, gates and pure algorithms; adapters for model providers, scrapers and renderers; and model, with Beanie documents and state types, connected left to right by arrows. Shared packages, the leaves: shared utils with the heartbeat, a refine loop and the API client; shared integrations for search, storage and provider wrappers; import contracts, import-linter for Python and module boundaries for TypeScript; and MongoDB, where every domain's documents are registered at start-up. An arrow shows apps importing packages, and another shows usecases reaching shared integrations.
Figure 1. Three layers. Apps are deployables that assemble. Each domain package is one bounded context with the same internal layering. Shared packages are leaves that no domain logic depends on in reverse.
LayerWhat lives thereRule
apps/The web app and the API. Wiring: router registration, start-up, the schedulerApps import packages. Packages do not import apps
packages/domain-*One bounded context each: articles, card news, detail pages, slides, banners, video, keywords, brand, billing, workspaceA domain reaches another domain only through its public index
packages/shared-*Utilities and integrations: search, storage, provider wrappers, heartbeatShared packages never import a domain

Inside every domain the layering is the same: api → usecases → {adapters, model}. A route handler may call a use case. A use case may call an adapter. Nothing in the model imports upward.

What checks it

The rules are checked by tools, not by review.

  • Python: import-linter contracts. One kind says a set of modules is forbidden to another. A second kind declares the layers of a package in order. This is the shape of the two, shortened from the repository’s contract file.
[importlinter:contract:shared-is-leaf]
name = shared-* packages must not depend on any trail_<domain>
type = forbidden
source_modules =
    trail_utils
    trail_integrations
forbidden_modules =
    trail_banner
    trail_article
    ...

[importlinter:contract:hexagonal-article]
name = trail_article Hexagonal layering
type = layers
layers =
    trail_article.api
    trail_article.usecases
    trail_article.adapters
    trail_article.model
  • TypeScript: Nx’s module-boundary rule with scope tags: an app may import a domain or a shared package, a domain may import shared, shared may import only shared.

Known violations are not hidden. Each is listed by name in the contract’s ignore list, so the debt is a countable list and a new violation fails the check.

A request becomes a run

Generation takes minutes, so a request cannot wait for it.

Two bands. Main graph: select_topic, where the editor-in-chief sets topic, outline and keywords; team_dispatch, which runs the team subgraph and streams its progress; parallel_enrich, adding images and SEO fields at the same time; final_review, which approves or sends back to the team with a dashed arrow labelled revise; and finalize, approved or waiting for a person. Team subgraph with the GEO flag on: brand_ammunition, verified brand facts for this article; preflight_brief, the article type and what it has to cover; researcher, search then claims mapped to sources; research gate, pass or the team ends without writing; writer, the user's model reading the revision guide; and reviewer, with fact check, editor and SEO in parallel and a dashed arrow labelled rewrite back to the writer. A note: there is no checkpointer; run state is the article document in MongoDB with the current step, the draft version and a heartbeat, and a retry rebuilds the graph from the step that failed.
Figure 2. The article pipeline, the longest run in the system. The request returns as soon as the run is started, and the graph writes its current step to the article document as it moves.
  1. The browser calls the API through one client wrapper that attaches the session token and the active workspace id and refreshes the token on a 401.
  2. The route resolves the user and the workspace, creates the document for the thing being generated, and charges credits.
  3. The route starts the pipeline as an asyncio task in the API process and returns the document id.
  4. The pipeline writes its progress onto the document as it goes. The browser reads the document to show which step is running.

There is no separate worker process and no queue. The task registry keeps one task per document id, and starting a new run for the same document cancels the old one.

Running long work inside the API process has an obvious hazard: the process restarts, and a document is left saying “generating” for ever. Three mechanisms cover that.

MechanismWhat it does
HeartbeatA running pipeline stamps its document every 30 seconds
SweeperEvery five minutes, documents with no heartbeat for 30 minutes are moved to an error state
Start-up recoveryOn boot, articles and videos still marked as generating are marked failed, and stuck storyboards are returned to their ready state

A pipeline that raises refunds its credits in its own error path, as described in Credits and tenancy. A run that dies with the process is handled differently: the sweeper and the start-up recovery change its status and leave the credits as they are.

Scheduled work

One APScheduler instance runs inside the API. It holds the fixed jobs: the sweeper, cleanups and periodic content jobs, some behind settings flags. One of those jobs is a tick every 60 seconds that looks for user-defined schedules stored in MongoDB that have come due.

State

Everything is in MongoDB through Beanie. Each domain exports the list of its document classes, and the API registers them all at start-up, so adding a domain does not mean editing a central schema. Generated files are served by the API from a local assets directory. An object-storage wrapper uploads to a bucket when credentials are configured and skips the upload when they are not.

The first versions kept operational data in SQLite. That was migrated: users, sessions, cost records and schedules are MongoDB collections now, and SQLite survives only in the one-off migration scripts.

Process and deployment

Two processes run under pm2: the API and the web app. A deploy script builds the web app locally, refuses to continue if a local dev server is running or if the build id is missing, syncs to the server, checks that the build id file arrived there, installs dependencies, reloads and runs health checks.

Decision records, and where the code stands

Eight decisions were written down as records in April 2026. The table gives the state of each in the code.

DecisionChosen overState in the code
Nx as the monorepo toolTurborepo, which is weak for Python and has no boundary enforcementIn use. The remote cache was never switched on
A uv workspace with one lock filePoetry, with its path workarounds and slower resolverIn use
No shared-types packageA general hub of shared typesHolds. There is no such package
Domains call each other’s public functions, with an event bus for side effectsAn event bus as the default, or HTTP between domainsDirect calls are used. The event bus was not built
Workspace and billing as injected dependenciesMiddleware that sets request stateWorkspace injection exists. Charging is an explicit call in each handler
Pipeline versions move through active, frozen, deprecated, removedKeeping versions side by side indefinitelyOld versions were removed. The bookkeeping the record asks for was not kept
A self-built feature-flag storeA hosted flag serviceNot built. Flags are environment variables
A shared package for the video rendererA separate app, or inside the video domainNot done. The renderer stayed where it was

Three are followed as written, two in part, and three were not built. The ones that held are structural and are checked by tools. The ones that did not were infrastructure to be built ahead of a need.

Decisions

1. Domains are packages. A package has a public index and a contract. A folder has neither, and nothing stops a deep import.

2. Long runs in the API process. A worker tier and a queue are the conventional answer. Here an in-process task with a heartbeat and a sweeper covers detection: a run that dies is found and marked failed, with nothing extra to deploy. Its credits are not returned automatically.

3. Progress on the document. The pipeline writes its step onto the same document the browser reads. There is no second channel to keep consistent.

4. No checkpointer in the graph. The article graph is compiled without one. The article document is the checkpoint, and a retry rebuilds the graph from the step that failed.

5. Explicit router registration. Every router is listed. Nothing is discovered by scanning, so removing a line removes a feature. The task checklist includes a manual check of the route count.

6. Unchanged when a flag is off. New behaviour arrives behind a flag, with tests on the flag-off path. The brand loader returns exactly an empty block for a request without a brand, and the team graph keeps its original topology with the strict mode off.

Limits

  • A run that dies with the process keeps its charge. The sweeper and the start-up recovery mark it failed and do not call the refund.
  • There is no CI. The contracts, the tests and the linters are run by hand and by the coding agents’ rules. The deploy script checks the build and health, not tests.
  • The app layer holds some logic. The article’s main graph lives under the API app, and a domain route calls back into it. That edge is on the contracts’ ignore list.
  • Some imports go deep. Callers import the billing use cases directly instead of through the package’s public index.
  • Tenant scoping is per query. Each query filters by workspace. There is no base class that applies the filter for you.
  • Tests run one package at a time. Test configuration names collide across packages, so there is no single command for the whole suite.