Skip to content

Content Engine ​

The Content Engine is Studio's write path for all content operations. It orchestrates validation, serialization, branching, and commit operations through the GitProvider interface. It is a thin layer over the shared @contentrain/mcp core operations, so Studio and the MCP server produce the same files.

Source: server/utils/content-engine/

Architecture ​

Content Engine
├── index.ts               # Factory function + public API
├── types.ts               # Shared types and constants
├── helpers.ts             # Common utilities
├── save-content.ts        # Collection/singleton/dictionary writes
├── save-document.ts       # Document kind (markdown + frontmatter)
├── save-model.ts          # Model definition writes
├── delete-content.ts      # Content deletion
├── delete-model.ts        # Model deletion
├── rename-dictionary-key.ts # Dictionary key rename across locales
├── replace-text.ts        # Exact find/replace in text fields
├── config-ops.ts          # Config changes (for example adding a locale)
├── init-project.ts        # Project initialization
├── update-status.ts       # Status changes + locale copying
├── locale-fanout.ts       # Multi-locale write helpers
├── entry-mode.ts          # Create vs update intent per entry
├── field-merge.ts         # Field-level merge of incoming data
├── model-merge.ts         # Model definition merge
├── context-build.ts       # context.json regeneration
├── errors.ts              # Engine error types
└── branch-ops.ts          # Branch guard, merge, reject, list

Creating an Engine Instance ​

The engine is created per-request with a GitProvider scoped to the target repository:

ts
import { createContentEngine } from '~/server/utils/content-engine'

const engine = createContentEngine({
  git: useGitProvider({
    installationId: workspace.github_installation_id,
    owner: 'org',
    repo: 'my-repo',
  }),
  contentRoot: '',     // or 'apps/web' for monorepos
  projectId: 'uuid',
})

Public API ​

ts
interface ContentEngineAPI {
  // Content CRUD
  saveContent(modelId: string, locale: string, data: Record<string, unknown>,
    userEmail: string, options?: SaveOptions): Promise<WriteResult>
  saveDocument(modelId: string, locale: string, slug: string,
    frontmatter: Record<string, unknown>, body: string,
    userEmail: string, options?: SaveOptions): Promise<WriteResult>
  saveDocuments(modelId: string, locale: string, documents: DocumentInput[],
    userEmail: string, options?: SaveOptions): Promise<WriteResult>   // several documents, one commit
  deleteContent(modelId: string, locale: string, entryIds: string[],
    userEmail: string, locales?: string[]): Promise<WriteResult>
  replaceText(modelId: string, locale: string, edits: TextEdit[],
    userEmail: string, options?: SaveOptions): Promise<WriteResult>
  renameDictionaryKey(modelId: string, from: string, to: string,
    userEmail: string): Promise<WriteResult>

  // Model and project operations
  saveModel(definition: ModelDefinition, userEmail: string): Promise<WriteResult>
  deleteModel(modelId: string, userEmail: string): Promise<WriteResult>
  addLocale(locale: string, userEmail: string): Promise<WriteResult>
  saveVocabulary(terms: VocabularyTerms, userEmail: string,
    options?: { replace?: boolean }): Promise<WriteResult>

  // Status management
  updateEntryStatus(modelId: string, locale: string, entryIds: string[],
    status: 'draft' | 'published' | 'archived', userEmail: string,
    locales?: string[]): Promise<WriteResult>
  copyLocale(modelId: string, from: string, to: string,
    userEmail: string): Promise<WriteResult>

  // Branch operations
  listContentBranches(): Promise<Branch[]>
  mergeBranch(branch: string, options?: { expectedHead?: string }): Promise<MergeResult>
  mergeToContentrain(branch: string): Promise<{ merged: boolean, conflict?: boolean }>  // step 1 only: cr/* -> contentrain
  finalizeContentrain(mergedBranches: string[]): Promise<MergeResult>  // context regeneration + default branch advance
  rejectBranch(branch: string): Promise<void>
  ensureContentBranch(): Promise<void>

  // Project initialization
  initProject(stack: string, locales: string[], domains: string[],
    models: ModelDefinition[], userEmail: string): Promise<WriteResult>
}

SaveOptions carries autoPublish, an optional schedule applied to every entry the save touches, an optional per-entry mode ('create' or 'update'), an optional status ('published' or 'draft'), and the entry source to record. When expectedHead is passed to mergeBranch, the merge is pinned to the commit that was approved and a write is never replayed onto a newer head.

Each write forks from the contentrain commit it read. If a colleague's change lands in between, the merge reports a real conflict instead of silently reverting it; an auto-merge in the same request redoes the write once on top of the new head, and a second conflict is returned to the caller as conflict: true.

Write Result ​

Every write operation returns a WriteResult:

ts
interface WriteResult {
  branch: string                    // Branch name (e.g., 'cr/content/blog-post/en/...')
  commit: Commit                    // Git commit with SHA
  diff: FileDiff[]                  // Changed files
  validation: ValidationResult     // Schema validation result
}

Write Flow ​

Every content write follows this pipeline:

The content write flow Every content write runs these steps in order: ensure the contentrain branch exists and is synced with main; open a write snapshot of contentrain and read the model; normalise media paths to delivery URLs; merge the sent fields into the existing entry and validate against the schema, stopping on errors; fan media and relation values out to every locale; plan the save as canonical JSON; stamp the meta file (status, updated_at, source); if the plan matches what is already on contentrain, stop without a branch; otherwise commit everything to a new cr/* branch forked from contentrain, without context.json; return the branch and its diff. 1 Ensure contentrain branch create from main, or sync main in 2 Open a write snapshot read the model from contentrain 3 Normalise media paths media/… → delivery URLs 4 Merge + validate sent fields into the entry, schema check 5 Locale fan-out media/relations to every locale 6 Plan the save canonical JSON files 7 Stamp meta status, updated_at, source 8 Commit to a new cr/* branch forked from contentrain, no context.json 9 Return the result branch name + diff invalid: stop, return errors plan = what is live: stop, no branch

Branch Strategy ​

Constants ​

ts
const CONTENT_BRANCH = 'contentrain'   // SSOT branch
const BRANCH_PREFIX = 'cr/'            // Feature branch prefix

Branch Naming Convention ​

cr/{operation}/{modelId}/{locale}/{timestamp}-{random}

Examples:

  • cr/content/blog-post/en/1774800862-27c1
  • cr/model/blog-post/1774800862-a3b4
  • cr/new/init/1774800862-c5d6

Merge Flow ​

The merge flow Step one, mergeToContentrain: the cr/* branch lands on contentrain, usually as a fast-forward, and the feature branch is deleted. Step two, finalizeContentrain: context.json is regenerated on contentrain, then main is advanced to contentrain. If main has its own commits Studio tries to reconcile; if main is protected it opens a pull request instead. cr/* branch one logical change contentrain content source of truth main your site 1 2 mergeToContentrain step 1 · cr/* → contentrain usually a fast-forward feature branch deleted finalizeContentrain step 2 · contentrain → main regenerate context.json advance main to contentrain reconcile if diverged · PR if protected

If main has branch protection requiring pull requests, the engine creates a PR and attempts to merge it programmatically.

Branch Guard ​

The engine ensures the contentrain branch exists before any operation. If it does not exist, it is created from the default branch head (and any legacy contentrain/* branches are merged into it and removed). If it already exists, the default branch is merged into it so the later fast-forward stays possible.

ts
// Runs once per engine instance (cached flag)
await engine.ensureContentBranch()

Canonical Serialization ​

All JSON output follows the canonical format from @contentrain/types:

ts
const CANONICAL_JSON = {
  indent: 2,              // 2-space indentation
  encoding: 'utf-8',
  trailingNewline: true,  // Final newline character
  omitNull: true,         // Remove null values
  omitDefaults: true,     // Remove fields matching their default value
  sortKeys: true,         // Alphabetical key ordering
}

This ensures Studio-written JSON is byte-identical to MCP-written JSON, preventing unnecessary diffs.

ts
import { canonicalStringify } from '@contentrain/types'

const json = canonicalStringify(data)
// Output: sorted keys, 2-space indent, trailing newline

Entry ID Generation ​

Collection entries use 12-character hex IDs:

ts
import { generateEntryId } from '@contentrain/types'

const id = generateEntryId()  // e.g., 'a1b2c3d4e5f6'

Content Validation ​

Validation runs against model field definitions before every write. validateContent delegates to the validator in @contentrain/mcp, so Studio and MCP apply the same rules:

ts
import { validateContent } from '~/server/utils/content-validation'

const result = validateContent(data, fields, modelId, locale, entryId, {
  allEntries: existingEntries,      // For unique checks
  currentEntryId: entryId,
  models: allModels,                // For relation resolution
  // loadContent: optional content loader for flows that still pass one
})

if (!result.valid) {
  // result.errors contains detailed validation errors
}

See Field Types for validation rules per field type.

Path Resolution ​

File paths are resolved using patterns from @contentrain/types:

ts
import { resolveContentPath, resolveModelPath } from '~/server/utils/content-paths'

const ctx = { contentRoot: '' }

resolveModelPath(ctx, 'blog-post')
// → '.contentrain/models/blog-post.json'

resolveContentPath(ctx, model, 'en')
// → '.contentrain/content/blog/blog-post/en.json'

resolveContentPath(ctx, model, 'en', 'getting-started')
// → '.contentrain/content/blog/blog-post/getting-started/en.md' (document kind)

Custom Content Path ​

Models can override their content path with content_path:

json
{
  "id": "docs",
  "kind": "document",
  "content_path": "content/docs"
}

Path traversal and sensitive directory access are blocked by validation.

Document Support ​

Document-kind content uses markdown files with YAML frontmatter:

ts
import { parseMarkdownFrontmatter, serializeMarkdownFrontmatter }
  from '@contentrain/types'

const { frontmatter, body } = parseMarkdownFrontmatter(raw)
const serialized = serializeMarkdownFrontmatter(frontmatter, body)

Context Tracking ​

.contentrain/context.json holds:

  • Last operation details (tool, model, locale, timestamp)
  • Project stats (model count, entry count, active locales)

Feature branches never carry it: a write's applyPlan commit leaves it out, so parallel cr/* branches cannot conflict on it. It is regenerated on contentrain after each merge (regenerateContextOnContentrain in branch-ops.ts), and initProject writes the first copy. On a review project that means it changes only once a branch is approved and merged.

The agent sees the last operation and stats as part of the project state in each turn.

Commit Author ​

All commits are authored by Studio:

ts
const STUDIO_AUTHOR = {
  name: 'Contentrain Studio',
  email: 'ai@contentrain.io',
}

Released under the AGPL-3.0 License. Privacy