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, listCreating an Engine Instance
The engine is created per-request with a GitProvider scoped to the target repository:
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
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:
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:
Branch Strategy
Constants
const CONTENT_BRANCH = 'contentrain' // SSOT branch
const BRANCH_PREFIX = 'cr/' // Feature branch prefixBranch Naming Convention
cr/{operation}/{modelId}/{locale}/{timestamp}-{random}Examples:
cr/content/blog-post/en/1774800862-27c1cr/model/blog-post/1774800862-a3b4cr/new/init/1774800862-c5d6
Merge Flow
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.
// Runs once per engine instance (cached flag)
await engine.ensureContentBranch()Canonical Serialization
All JSON output follows the canonical format from @contentrain/types:
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.
import { canonicalStringify } from '@contentrain/types'
const json = canonicalStringify(data)
// Output: sorted keys, 2-space indent, trailing newlineEntry ID Generation
Collection entries use 12-character hex IDs:
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:
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:
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:
{
"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:
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:
const STUDIO_AUTHOR = {
name: 'Contentrain Studio',
email: 'ai@contentrain.io',
}Related Pages
- Contentrain Format -- directory structure specification
- Field Types -- validation rules per type
- Agent System -- how the agent invokes the engine
- Branches API -- REST endpoints for branches