Skip to document
← ContentForge AIAbdul Moiz / Engineering studies Download PDF
Contents 12 chapters + figures

An engineering study of brand-aware content creation

A voice that survives the workflow.

How reusable brand context, strategy-driven generation, authenticated persistence, and calendar planning turn a content prompt into a complete product workflow.

  • Generative AI
  • Brand voice
  • Content workflows
  • Provider resilience

Part I / The product

01

Content needs context, not just a prompt.

A useful content-generation product has to preserve more than a topic. It needs to know who is speaking, who is reading, what the content should achieve, and how a particular format changes the delivery. Re-entering that information for every request creates friction and inconsistency.

ContentForge AI combines reusable brand profiles with a structured brief. Generated pieces can be saved, edited, repurposed, and planned on a calendar. The workspace is individual and authenticated; it is not a team collaboration or autonomous publishing platform.

InputProduct responsibilityOutcome
Brand voice and examplesRetain reusable writing contextA consistent starting point for prompts
Brief and target formatSelect constraints and creative strategiesOne to three candidate drafts
Saved content and date/timeManage reuse and planning stateA searchable library and calendar plan

Part I / The product

02

Make the workflow visible.

The interface separates Dashboard, Create, Library, Calendar, Brands, and Settings. The dashboard summarizes usage, content counts, recent work, and upcoming schedules. The creation form puts the brief next to its output rather than hiding the process behind a conversational interface.

ContentForge AI creation form and output area
The creation workspace pairs explicit controls with a generated-content area.

The library exposes the lifecycle of a piece through search and filters for format, status, and brand. Editing, copying, duplication, repurposing, scheduling, and deletion remain explicit user actions. The calendar shows the intended release date rather than promising automatic distribution.

  • Loading states explain when generation is in progress.
  • Empty states separate an unused workspace from a failed request.
  • Validation and provider errors are surfaced without returning sensitive upstream details.

Part II / The system

03

One application, several responsibilities.

Next.js 16 App Router and TypeScript provide both the web product and server API route handlers. Tailwind CSS handles the product interface. Clerk manages authentication; Prisma connects application services to PostgreSQL. AI access is isolated in a server-only provider layer.

One application. Explicit server boundaries.ContentForge AI / System map
ProductAuthenticated APIServices & state
Next.js interfacedashboard · create · library · calendar · brands
Clerk sessionsign in → authenticated workspace
Typed API clientvalidated requests · loading & error states
Route handlersresolve active user · validate input
Ownership & limitsuser-scoped queries · atomic AI allowance
Application servicesgenerate · repurpose · schedule · synchronize
AI provider adapterOpenAI-compatible / Anthropic / mock
Prisma → PostgreSQLbrands · content · schedules · usage
Google Calendaroptional consent-based event synchronization
Next.js serves the interface and route handlers. AI credentials stay server-side; records are scoped to the authenticated user.
LayerResponsibilityBoundary
BrowserCollect briefs and display contentNo AI provider secrets
API routesResolve identity, validate requests, enforce ownershipDo not trust a client-supplied resource ID alone
ServicesGenerate, repurpose, persist, schedule, synchronizeSeparate local records from external integrations
PostgreSQLDurable workspace records and concurrency controlNot a content-quality evaluator

Part II / The system

04

The brand profile is reusable context.

The profile has eleven fields: name, description, industry, target audience, personality, tone, values, preferred phrases, avoided phrases, writing style, and example content. A selected profile is loaded with the authenticated user's ownership constraint before being transformed into prompt input.

ContentForge AI brand identity and voice fields
Identity, voice, phrases, and examples are configured once and reused across generation and repurposing.

The prompt builder introduces those fields as writing guidance. Preferred phrases are encouraged, avoided phrases are constrained, and example copy helps communicate rhythm and diction. Example text is clipped to 1,200 characters for the prompt, keeping stored profile size separate from inference context size.

Part III / Execution

05

Variation means a different approach.

The brief includes the target format, topic, audience, objective, tone, length, keywords, CTA, and variation count. Eight formats are supported: LinkedIn, X/Twitter, Instagram, Facebook, marketing email, ad copy, product description, and blog post. Each format introduces its own delivery constraints.

A shared voice. Distinct creative directions.ContentForge AI / System map
ContextStrategy fan-outValidate & retain
Brand voiceidentity · audience · phrases · style · examples
Content briefformat · topic · objective · tone · length · CTA
Prompt builderformat rules + voice + chosen strategy
Directclear benefit · immediate hook · focused CTA
Story-drivennarrative opening · tension · resolution
Educationalexplanation · practical steps · takeaway
Provider responsesbounded retries · structured title / body
JSON validationparse response · reject unreadable output
Preview or savetransactional draft records when requested
Up to three independent requests run in parallel. A single variation chooses one strategy; two use Direct and Story-driven; three include Educational.
StrategyCreative directionTemperature
DirectClear benefit, focused hook and CTA0.7
Story-drivenNarrative opening and progression0.9
EducationalExplanation and practical takeaways0.8

Three variations use all three strategies; two use Direct and Story-driven. A single variation chooses one strategy. The generator runs the requested variations with Promise.all, so they are independent provider calls, not a sequential multi-agent workflow. A failed variation rejects the group rather than silently returning a partial success.

The API can return previews without saving. If saving is requested, the variations are persisted together as drafts in a database transaction, retaining the original brief fields and variation index.

Part III / Execution

06

Switch the provider, keep the product.

A common adapter interface accepts messages, temperature, and token budget. OpenAI-compatible and Anthropic implementations translate this request to their respective APIs; a deterministic mock provider supports offline workflows and tests.

AdapterConfigurable defaultPurpose
OpenAI-compatiblegpt-4oChat-completions API; configurable model and base URL
Anthropicclaude-sonnet-4-20250514Messages API; configurable model and base URL
MockDeterministic templatesStrategy-aware test and development output

Transient network failures, rate limits, and selected 5xx responses receive bounded retries with exponential backoff and jitter. Retry-After is capped at five seconds. The ordinary upstream retry policy permits three attempts, and individual request timeouts are bounded at ninety seconds.

The OpenAI-compatible path also recognizes an empty completion caused by a length finish reason and can retry with an expanded token budget. This is a targeted compatibility mechanism, not a fallback to a different provider.

Part III / Execution

07

Treat generated output as untrusted input.

Request validation constrains the topic, audience, objective, tone, keywords, CTA, format, length, and variation count. The generation count must be between one and three. Invalid JSON or invalid request fields receive an explicit client error before model work begins.

The generation prompt asks for a JSON object containing title and body. The response parser accepts clean JSON, markdown-fenced JSON, and a balanced embedded object. It still validates the resulting object: a readable body is required, and an absent or invalid title can fall back to Untitled.

A structurally valid body can still contain inaccurate claims. Parsing protects the software contract, not the truth of the marketing copy. Provider failures and unreadable outputs return recoverable errors, while sensitive provider diagnostics stay in server logs.

  • Validate the request before loading external services.
  • Validate generated structure before previewing or persisting it.
  • Keep structural validation separate from human content review.

Part IV / Durable workflows

08

Every record belongs to a workspace.

The identity resolver reads the Clerk session and maps it to an active database user. A first login provisions the workspace through the same resolver used by APIs. Signed Clerk lifecycle webhooks keep identity changes synchronized, and inactive-user checks prevent stale access.

A workspace anchored to one identityContentForge AI / System map
IdentityCreative recordsOperational records
UserClerk identity · active workspace
Lifecycle synchronizationsigned webhooks · active-user checks
Brandvoice fields · owned by user
Contentformat · body · status · brand · source link
ScheduledContentdate/time · platform · event sync state
AiUsageunique user + UTC day · operation count
GoogleCalendarConnectionconsent preference · external account ID
User ownership is carried through brands, content, schedules, usage, and the calendar connection. OAuth tokens are retrieved through Clerk rather than stored as application records.

Brands, content, schedules, usage, and Google Calendar preferences carry user ownership. API queries scope resource lookups to that owner rather than treating possession of an ID as permission. Brand and content relationships preserve the context needed for later reuse.

EntityRetained state
UserClerk identity and active workspace
BrandIdentity and reusable voice fields
ContentBody, format, status, brand, brief, and source relationship
ScheduledContentRelease plan and external synchronization state
AiUsagePer-user UTC-day operation count
GoogleCalendarConnectionConsent preference and external account identity

Part IV / Durable workflows

09

Reuse the idea without losing its origin.

Repurposing starts from an owned, saved piece and a different target format. The prompt carries the source text, original and target formats, and available brand context. Source text is clipped to 6,000 characters for this prompt. Same-format repurposing is blocked.

The result is saved as a new draft linked through sourceContentId. The original remains intact, making adaptation a traceable relationship rather than a destructive edit. Library actions keep direct editing, duplication, and AI-driven repurposing conceptually separate.

From a saved idea to a planned releaseContentForge AI / System map
LibraryAdaptPlanOptional sync
Saved contentsearch · edit · copy · duplicate
Repurposesource text + brand voice → another format
Scheduleplatform + date/time → monthly calendar
Google eventopt-in synchronization · retryable errors
Schedule mutations use database transactions. Google updates use a per-schedule advisory lock and deterministic event identity.
Repurposed drafts retain sourceContentId. The calendar is a planning tool: a saved schedule is not an automatic social-media publication.

Part IV / Durable workflows

10

Save the plan before synchronizing it.

Scheduling records the content, platform, and intended date/time. A serializable database transaction creates or updates the schedule and adjusts the content status. Cancelling the last pending schedule returns scheduled content to Draft; archived content must be restored before scheduling.

ContentForge AI monthly calendar and optional Google Calendar connection
The monthly grid displays saved plans. Google Calendar connection is optional and explicitly consented.

The optional Google integration obtains OAuth tokens through Clerk. A deterministic event identity and a per-schedule PostgreSQL advisory lock coordinate concurrent synchronization attempts. Persisted event IDs and error state support retrying failed updates without discarding the local plan.

Part V / Reliability

11

Budget the work at the server boundary.

The server caps each user at three brands and fifty accepted generation or repurposing operations per UTC day. The daily allowance counts operations, not individual variations or provider retry attempts. A three-variation request is one operation even though it makes multiple upstream calls.

Usage reservation uses conditional atomic increments and handles concurrent row-creation races. An accepted operation remains consumed if the provider fails. Brand creation uses serializable transactions with bounded retries for transaction conflicts, avoiding a client-only limit that simultaneous requests could bypass.

BoundaryImplemented mechanismRemaining judgment
AI usageAtomic daily operation reservationQuota is not a provider-cost measurement
Brand creationSerializable limit check and insertProduct limits may change independently of schema
Upstream failuresBounded retries and generic client errorsNot an availability guarantee
Calendar updatesTransactional plans and advisory-locked syncExternal consent and service availability still matter

Closing / Engineering judgment

12

The workflow is the product.

The repository includes Vitest tests for prompt construction, generators, provider retries, validation, authorization, quotas, calendar behavior, lifecycle webhooks, and workspace provisioning. Opt-in PostgreSQL integration coverage exercises persistence boundaries. These are test surfaces in the implementation, not newly measured quality or latency results.

No supplied accuracy benchmark establishes brand fidelity or marketing effectiveness. Useful next evaluations would compare strategy diversity, review avoided-phrase behavior, check human-rated voice consistency, and test concurrent usage and calendar updates against a real database. Such evaluations should retain their prompts, models, samples, and failure cases.

  • Reusable context reduces repeated setup, but does not eliminate review.
  • Creative diversity comes from explicit strategies, not a multi-agent claim.
  • Ownership and quotas belong at the server boundary.
  • Local planning and external calendar state need separate failure handling.
  • A good AI product keeps the work usable after generation ends.