@contentrain/rules 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +3 -0
  2. package/ide/claude-code/rules/contentrain-accessibility-rules.md +155 -0
  3. package/ide/claude-code/rules/contentrain-content-conventions.md +314 -0
  4. package/ide/claude-code/rules/contentrain-content-quality.md +294 -0
  5. package/ide/claude-code/rules/contentrain-i18n-quality.md +293 -0
  6. package/ide/claude-code/rules/contentrain-mcp-usage.md +405 -0
  7. package/ide/claude-code/rules/contentrain-media-rules.md +165 -0
  8. package/ide/claude-code/rules/contentrain-normalize-rules.md +312 -0
  9. package/ide/claude-code/rules/contentrain-schema-rules.md +380 -0
  10. package/ide/claude-code/rules/contentrain-security-rules.md +141 -0
  11. package/ide/claude-code/rules/contentrain-seo-rules.md +224 -0
  12. package/ide/claude-code/rules/contentrain-workflow-rules.md +262 -0
  13. package/ide/cursor/rules/contentrain-accessibility-rules.mdc +160 -0
  14. package/ide/cursor/rules/contentrain-content-conventions.mdc +319 -0
  15. package/ide/cursor/rules/contentrain-content-quality.mdc +299 -0
  16. package/ide/cursor/rules/contentrain-i18n-quality.mdc +298 -0
  17. package/ide/cursor/rules/contentrain-mcp-usage.mdc +410 -0
  18. package/ide/cursor/rules/contentrain-media-rules.mdc +170 -0
  19. package/ide/cursor/rules/contentrain-normalize-rules.mdc +317 -0
  20. package/ide/cursor/rules/contentrain-schema-rules.mdc +385 -0
  21. package/ide/cursor/rules/contentrain-security-rules.mdc +146 -0
  22. package/ide/cursor/rules/contentrain-seo-rules.mdc +229 -0
  23. package/ide/cursor/rules/contentrain-workflow-rules.mdc +267 -0
  24. package/ide/windsurf/rules/contentrain-accessibility-rules.md +160 -0
  25. package/ide/windsurf/rules/contentrain-content-conventions.md +319 -0
  26. package/ide/windsurf/rules/contentrain-content-quality.md +299 -0
  27. package/ide/windsurf/rules/contentrain-i18n-quality.md +298 -0
  28. package/ide/windsurf/rules/contentrain-mcp-usage.md +410 -0
  29. package/ide/windsurf/rules/contentrain-media-rules.md +170 -0
  30. package/ide/windsurf/rules/contentrain-normalize-rules.md +317 -0
  31. package/ide/windsurf/rules/contentrain-schema-rules.md +385 -0
  32. package/ide/windsurf/rules/contentrain-security-rules.md +146 -0
  33. package/ide/windsurf/rules/contentrain-seo-rules.md +229 -0
  34. package/ide/windsurf/rules/contentrain-workflow-rules.md +267 -0
  35. package/package.json +4 -4
@@ -0,0 +1,312 @@
1
+ # Contentrain Normalize Rules
2
+
3
+ > These rules govern the normalize flow: extracting hardcoded content from source code into `.contentrain/` (Phase 1) and patching source files to reference extracted content (Phase 2).
4
+
5
+ ---
6
+
7
+ ## 1. Purpose
8
+
9
+ Normalize converts a codebase with hardcoded strings into a Contentrain-managed content architecture:
10
+
11
+ - **Phase 1 (Extraction):** Pull content from source code into `.contentrain/` structure. Source files are NOT modified.
12
+ - **Phase 2 (Reuse):** Patch source files to replace hardcoded strings with content references. Requires completed extraction.
13
+
14
+ Each phase produces a separate branch for independent review. This separation ensures extraction can be reviewed and merged before any source file modifications occur.
15
+
16
+ ---
17
+
18
+ ## 2. Two-Phase Architecture
19
+
20
+ | Aspect | Phase 1: Extraction | Phase 2: Reuse |
21
+ |--------|-------------------|----------------|
22
+ | Purpose | Pull content from source to `.contentrain/` | Patch source files with content references |
23
+ | Scope | Full project scan | Per model or per domain |
24
+ | Source files modified | No | Yes |
25
+ | Branch pattern | `contentrain/normalize/extract/{domain}/{timestamp}` | `contentrain/normalize/reuse/{model}/{locale}/{timestamp}` |
26
+ | Prerequisite | Initialized `.contentrain/` | Completed extraction (content exists in `.contentrain/`) |
27
+ | Workflow mode | Always `review` | Always `review` |
28
+ | Standalone value | Yes -- content is manageable in Studio immediately | Depends on Phase 1 |
29
+
30
+ ### Why Two Phases?
31
+
32
+ - Phase 1 alone is valuable: content is extracted, Studio can manage it, new locales can be added.
33
+ - Phase 2 can be done incrementally, model by model, reducing risk.
34
+ - Separate reviews mean clearer diffs and easier rollback.
35
+
36
+ ---
37
+
38
+ ## 3. Agent vs MCP Responsibilities
39
+
40
+ ### Agent (Intelligence Layer -- You)
41
+
42
+ - **Decide what is content vs code.** This is a semantic judgment that requires understanding context.
43
+ - **Assign domain grouping.** Determine which domain each piece of content belongs to.
44
+ - **Determine model structure.** Group related content into models, choose the right kind.
45
+ - **Create replacement expressions.** These are stack-specific and require framework knowledge:
46
+ - Vue/Nuxt: `{{ $t('key') }}` or `{{ t('key') }}`
47
+ - React/Next: `{t('key')}` or `{intl.formatMessage({id: 'key'})}`
48
+ - Svelte/SvelteKit: `{$t('key')}`
49
+ - Astro: `{t('key')}`
50
+ - Generic: direct import from `#contentrain`
51
+ - **Filter false positives** from scan candidates.
52
+ - **Evaluate and group** candidates into logical models.
53
+
54
+ ### MCP (Deterministic Infrastructure)
55
+
56
+ - **Scan the file system** (build graph, find candidates).
57
+ - **Read and write files** in `.contentrain/`.
58
+ - **Patch source files** with exact string replacement (agent provides the replacement expression).
59
+ - **Create branches, commit, validate** all changes.
60
+ - **Enforce guardrails** (file limits, type restrictions, dry-run requirement).
61
+
62
+ **Rule:** MCP is framework-agnostic. It does NOT know how `{t('key')}` differs from `{{ $t('key') }}`. The agent provides all stack-specific logic.
63
+
64
+ ---
65
+
66
+ ## 4. Guardrails
67
+
68
+ These limits protect against runaway operations and ensure reviewable changes.
69
+
70
+ | Guardrail | Limit | Rationale |
71
+ |-----------|-------|-----------|
72
+ | Allowed source file types | `.vue`, `.tsx`, `.jsx`, `.ts`, `.js`, `.mjs`, `.astro`, `.svelte` | Only scan files that can contain UI content |
73
+ | Max files per scan | 500 | Prevent scanning entire monorepos |
74
+ | Max files per apply | 100 | Keep diffs reviewable |
75
+ | Dry-run before apply | **MANDATORY** | Preview all changes before executing |
76
+ | Workflow mode | Always `review` | Normalize changes are never auto-merged |
77
+ | Reuse scope | Per model or per domain | No whole-project reuse in one operation |
78
+ | Reuse prerequisite | Extraction must be complete | Content must exist in `.contentrain/` before patching source |
79
+
80
+ ### Enforcement
81
+
82
+ - Attempting to apply without a prior dry-run will be rejected.
83
+ - Attempting to reuse without completed extraction will be rejected.
84
+ - Exceeding file limits will truncate results with a warning.
85
+
86
+ ---
87
+
88
+ ## 5. What IS Content
89
+
90
+ Use these heuristics to identify content strings in source code. Content is user-visible text that should be managed separately from code.
91
+
92
+ ### Extract These
93
+
94
+ - **Headings and titles** in templates/JSX (`<h1>`, `<h2>`, etc.)
95
+ - **Paragraph text** and body copy
96
+ - **Button labels** (`<button>Submit</button>`)
97
+ - **Link text** (`<a>Learn more</a>`)
98
+ - **Form labels and placeholders** (`<label>`, `placeholder="..."`)
99
+ - **Error messages** shown to users
100
+ - **Success/notification messages**
101
+ - **Alt text** on images (`alt="..."`)
102
+ - **ARIA labels** (`aria-label="..."`)
103
+ - **Meta descriptions and page titles** (`<title>`, `<meta name="description">`)
104
+ - **Navigation items** (menu labels, breadcrumbs)
105
+ - **Tooltip text**
106
+ - **Empty state messages** ("No results found")
107
+ - **CTA (call-to-action) text**
108
+
109
+ ### Do NOT Extract These
110
+
111
+ - CSS class names, HTML IDs
112
+ - Variable names, function names, parameter names
113
+ - Technical identifiers (API endpoints, route paths, event names)
114
+ - Import paths and file paths
115
+ - Numbers used as constants (port numbers, HTTP status codes, pixel dimensions, timeouts)
116
+ - Strings shorter than 3 characters (unless semantically meaningful: "OK", "No", "Yes")
117
+ - Regular expressions
118
+ - Configuration values (environment variables, feature flags)
119
+ - Log messages (internal, not user-facing)
120
+ - Code comments
121
+ - Test assertion strings
122
+ - JSON keys
123
+ - Enum values used as code identifiers (not displayed to users)
124
+
125
+ ### Dictionary Interpolation Limitation
126
+
127
+ Strings containing dynamic expressions (`${variable}`, template literals with runtime values) cannot be stored in dictionaries. These must remain as hardcoded expressions in source code.
128
+
129
+ **CANNOT extract:**
130
+
131
+ - `"Add a new entry to ${modelId}"` — contains runtime variable
132
+ - `` `Hello, ${user.name}!` `` — template literal with variable
133
+
134
+ **CAN extract:**
135
+
136
+ - `"Add a new entry"` — static string (parameterize separately if needed)
137
+ - `"Hello, World!"` — no runtime variables
138
+
139
+ Agent should split parameterized strings: extract the static template pattern and leave the interpolation in code.
140
+
141
+ ```
142
+ // Instead of: `"Add a new entry to ${modelId}"`
143
+ // Extract: dictionary key "add-entry-to" = "Add a new entry to"
144
+ // Code: `${t['add-entry-to']} ${modelId}`
145
+ ```
146
+
147
+ ### Edge Cases
148
+
149
+ | String | Extract? | Reason |
150
+ |--------|----------|--------|
151
+ | `"OK"` | Yes | User-visible confirmation |
152
+ | `"px"` | No | CSS unit, not content |
153
+ | `"Loading..."` | Yes | User-visible state message |
154
+ | `"GET"` | No | HTTP method, technical |
155
+ | `"en"` | No | Locale code, technical |
156
+ | `"Submit Form"` | Yes | User-visible button label |
157
+ | `"/api/users"` | No | API endpoint |
158
+ | `"flex"` | No | CSS value |
159
+ | `"user.name"` | No | Object property path |
160
+ | `"An error occurred"` | Yes | User-facing error message |
161
+
162
+ ---
163
+
164
+ ## 6. Phase 1: Extraction Flow
165
+
166
+ ### Step-by-Step
167
+
168
+ 1. **Build project graph:**
169
+ ```
170
+ contentrain_scan(mode: "graph")
171
+ ```
172
+ Returns import/component dependency graph. Use this to understand project structure and prioritize files.
173
+
174
+ 2. **Find candidates:**
175
+ ```
176
+ contentrain_scan(mode: "candidates")
177
+ ```
178
+ Returns hardcoded string candidates with file locations, line numbers, and surrounding context.
179
+
180
+ 3. **Agent evaluation (your job):**
181
+ - Filter out false positives using the heuristics in Section 5.
182
+ - Group candidates by domain (e.g., `marketing`, `blog`, `system`).
183
+ - Determine model structure: which kind (singleton, collection, dictionary), which fields.
184
+ - Assign field names and keys.
185
+
186
+ 4. **Preview extraction:**
187
+ ```
188
+ contentrain_apply(mode: "extract", dry_run: true)
189
+ ```
190
+ Returns a preview of what will be created in `.contentrain/` without making changes.
191
+
192
+ 5. **Review dry-run output:**
193
+ - Verify models are structured correctly.
194
+ - Verify content assignments are accurate.
195
+ - Check for missing or misclassified candidates.
196
+
197
+ 6. **Execute extraction:**
198
+ ```
199
+ contentrain_apply(mode: "extract")
200
+ ```
201
+ Creates model definitions and content files in `.contentrain/`.
202
+
203
+ 7. **Validate and submit:**
204
+ ```
205
+ contentrain_validate
206
+ contentrain_submit
207
+ ```
208
+ Submit always uses `review` mode for normalize operations.
209
+
210
+ ### Extraction Rules
211
+
212
+ - Extraction creates content in `.contentrain/` but does NOT modify source files.
213
+ - Each extraction produces a single branch with all extracted content.
214
+ - Group related content into the fewest models that make semantic sense.
215
+ - Prefer dictionary kind for UI labels and error messages.
216
+ - Prefer singleton kind for page-specific content (hero, features).
217
+ - Prefer collection kind for repeating items (team members, FAQs, testimonials).
218
+
219
+ ---
220
+
221
+ ## 7. Phase 2: Reuse Flow
222
+
223
+ ### Step-by-Step
224
+
225
+ 1. **Select scope:** Choose one model or domain to process.
226
+
227
+ 2. **Determine replacement expressions (your job):**
228
+ Based on the project's tech stack, determine how source files should reference content:
229
+
230
+ | Stack | Pattern | Example |
231
+ |-------|---------|---------|
232
+ | Vue/Nuxt (i18n) | `{{ $t('key') }}` | `{{ $t('hero.title') }}` |
233
+ | React/Next (react-intl) | `{intl.formatMessage({id: 'key'})}` | `{intl.formatMessage({id: 'hero.title'})}` |
234
+ | React/Next (next-intl) | `{t('key')}` | `{t('hero.title')}` |
235
+ | Svelte/SvelteKit | `{$t('key')}` | `{$t('hero.title')}` |
236
+ | Astro | `{t('key')}` | `{t('hero.title')}` |
237
+ | SDK import | `query('model').all()` | Direct data access via `#contentrain` |
238
+
239
+ 3. **Preview reuse:**
240
+ ```
241
+ contentrain_apply(mode: "reuse", scope: "model-id", dry_run: true)
242
+ ```
243
+ Returns a preview of source file patches.
244
+
245
+ 4. **Review dry-run output:**
246
+ - Verify each replacement is correct.
247
+ - Verify import statements will be added where needed.
248
+ - Check that no non-content strings are being replaced.
249
+
250
+ 5. **Execute reuse:**
251
+ ```
252
+ contentrain_apply(mode: "reuse", scope: "model-id")
253
+ ```
254
+ Patches source files with content references.
255
+
256
+ 6. **Validate and submit:**
257
+ ```
258
+ contentrain_validate
259
+ contentrain_submit
260
+ ```
261
+
262
+ 7. **Repeat** for each model/domain until all extracted content is referenced.
263
+
264
+ ### Reuse Rules
265
+
266
+ - Process one model or domain at a time. Do NOT reuse the entire project in one operation.
267
+ - Ensure the i18n/content library is properly configured in the project before reuse.
268
+ - Add necessary imports to patched files (e.g., `import { useTranslation } from 'next-intl'`).
269
+ - Do NOT change the structure or behavior of components -- only replace string literals with content references.
270
+ - If a source file requires setup code (composable import, hook call), include it in the patch.
271
+
272
+ ---
273
+
274
+ ## 8. Domain and Model Grouping Guidelines
275
+
276
+ When evaluating scan candidates, group content logically:
277
+
278
+ ### Domain Assignment
279
+
280
+ | Content Location | Suggested Domain |
281
+ |------------------|-----------------|
282
+ | Landing page, marketing sections | `marketing` |
283
+ | Blog, articles, posts | `blog` |
284
+ | Navigation, footer, header | `ui` |
285
+ | Error messages, validation | `system` |
286
+ | Product pages, e-commerce | `product` |
287
+ | Documentation, help | `docs` |
288
+ | User-facing app strings | `app` |
289
+
290
+ ### Model Kind Selection
291
+
292
+ | Content Pattern | Kind | Rationale |
293
+ |----------------|------|-----------|
294
+ | One set of fields per page section | `singleton` | Hero, features, pricing header |
295
+ | Multiple items of same type | `collection` | Team members, FAQs, testimonials |
296
+ | Long-form with metadata | `document` | Blog posts, documentation pages |
297
+ | Key-value UI strings | `dictionary` | Error messages, button labels, form labels |
298
+
299
+ ---
300
+
301
+ ## 9. Common Mistakes to Avoid
302
+
303
+ | Mistake | Correct Approach |
304
+ |---------|-----------------|
305
+ | Extracting CSS values as content | Only extract user-visible text |
306
+ | Creating one model per component | Group related content into shared models |
307
+ | Skipping dry-run | ALWAYS preview before apply |
308
+ | Auto-merging normalize changes | Normalize ALWAYS uses review mode |
309
+ | Reusing before extraction is merged | Wait for extraction review and merge first |
310
+ | Processing all models in one reuse | Scope reuse to one model/domain at a time |
311
+ | Ignoring project graph | Use graph output to understand component relationships |
312
+ | Hardcoding replacement patterns | Detect the project's i18n stack and use its conventions |
@@ -0,0 +1,380 @@
1
+ # Contentrain Schema Rules
2
+
3
+ > These rules define the Contentrain type system, field definitions, model definitions, and relation system. Follow them exactly when creating or modifying models and content schemas.
4
+
5
+ ---
6
+
7
+ ## 1. Type System Overview
8
+
9
+ Contentrain uses a **flat type system** with 27 types. Each type is a single keyword -- there is no `format` sub-layer. `type: "email"` is the complete specification.
10
+
11
+ This design is optimized for AI agents: easy to produce, cheap to read, fast to validate.
12
+
13
+ ---
14
+
15
+ ## 2. Complete Type Reference (27 Types)
16
+
17
+ ### 2.1 String Family (11 types)
18
+
19
+ | Type | Description | Validation | JSON Schema Export |
20
+ |------|-------------|------------|-------------------|
21
+ | `string` | Single-line text | -- | `{ "type": "string" }` |
22
+ | `text` | Multi-line text | -- | `{ "type": "string" }` |
23
+ | `email` | Email address | RFC 5321 | `{ "type": "string", "format": "email" }` |
24
+ | `url` | URL | RFC 3986 | `{ "type": "string", "format": "uri" }` |
25
+ | `slug` | URL-safe identifier | `/^[a-z0-9]+(?:-[a-z0-9]+)*$/` | `{ "type": "string", "pattern": "..." }` |
26
+ | `color` | Hex color code | `/^#[0-9a-fA-F]{6}$/` | `{ "type": "string" }` |
27
+ | `phone` | Phone number | E.164 or freeform | `{ "type": "string" }` |
28
+ | `code` | Code snippet | -- | `{ "type": "string" }` |
29
+ | `icon` | Icon identifier | -- | `{ "type": "string" }` |
30
+ | `markdown` | Markdown content | -- | `{ "type": "string" }` |
31
+ | `richtext` | HTML rich text | -- | `{ "type": "string" }` |
32
+
33
+ ### 2.2 Number Family (5 types)
34
+
35
+ | Type | Description | Constraints | JSON Schema Export |
36
+ |------|-------------|-------------|-------------------|
37
+ | `number` | General number | -- | `{ "type": "number" }` |
38
+ | `integer` | Whole number | -- | `{ "type": "integer" }` |
39
+ | `decimal` | Decimal number | -- | `{ "type": "number" }` |
40
+ | `percent` | Percentage | 0-100 | `{ "type": "number", "minimum": 0, "maximum": 100 }` |
41
+ | `rating` | Rating score | 1-5 | `{ "type": "integer", "minimum": 1, "maximum": 5 }` |
42
+
43
+ ### 2.3 Primitives (3 types)
44
+
45
+ | Type | Storage Format | JSON Schema Export |
46
+ |------|---------------|-------------------|
47
+ | `boolean` | `true` / `false` | `{ "type": "boolean" }` |
48
+ | `date` | `"YYYY-MM-DD"` string | `{ "type": "string", "format": "date" }` |
49
+ | `datetime` | ISO 8601 string | `{ "type": "string", "format": "date-time" }` |
50
+
51
+ ### 2.4 Media (3 types)
52
+
53
+ | Type | Storage | Description |
54
+ |------|---------|-------------|
55
+ | `image` | Relative path (string) | Image file reference |
56
+ | `video` | Relative path (string) | Video file reference |
57
+ | `file` | Relative path (string) | Generic file reference |
58
+
59
+ In v1, media fields store URL/path strings only. Upload and processing are out of scope.
60
+
61
+ ### 2.5 Relations (2 types)
62
+
63
+ | Type | Cardinality | Storage |
64
+ |------|-------------|---------|
65
+ | `relation` | One-to-one | `"entry-id"` (string) |
66
+ | `relations` | One-to-many | `["id-1", "id-2"]` (string array) |
67
+
68
+ ### 2.6 Structural (3 types)
69
+
70
+ | Type | Description | Requires |
71
+ |------|-------------|----------|
72
+ | `select` | Fixed options, pick one | `options` property |
73
+ | `array` | Ordered list of items | `items` property |
74
+ | `object` | Nested key-value structure | `fields` property |
75
+
76
+ ---
77
+
78
+ ## 3. Field Definition
79
+
80
+ A field definition describes one field in a model. Include only the properties that apply -- omit all defaults.
81
+
82
+ ```json
83
+ {
84
+ "type": "string",
85
+ "required": true,
86
+ "min": 3,
87
+ "max": 100,
88
+ "unique": true,
89
+ "description": "Page title"
90
+ }
91
+ ```
92
+
93
+ ### 3.1 Field Properties
94
+
95
+ | Property | Applicable Types | Description |
96
+ |----------|-----------------|-------------|
97
+ | `type` | ALL | **Required.** One of the 27 types. |
98
+ | `required` | ALL | Mark field as mandatory. Default: `false`. Omit if `false`. |
99
+ | `unique` | `string`, `email`, `slug`, `integer` | Enforce uniqueness within model. Default: `false`. Omit if `false`. |
100
+ | `default` | ALL | Default value. Omit if `null`. |
101
+ | `min` | string/text: char count; numbers: value; array: element count | Minimum constraint. |
102
+ | `max` | Same as `min` | Maximum constraint. |
103
+ | `pattern` | `string`, `text`, `code` | Regex validation pattern. |
104
+ | `options` | `select` ONLY | Fixed choices: `["draft", "published", "archived"]` |
105
+ | `model` | `relation`, `relations` ONLY | Target model ID. String or string array for polymorphic. |
106
+ | `items` | `array` ONLY | Element type: `"string"` or `{ "type": "object", "fields": {...} }` |
107
+ | `fields` | `object` ONLY | Nested field definitions. |
108
+ | `accept` | `image`, `video`, `file` | Allowed MIME types: `"image/png,image/jpeg"` |
109
+ | `maxSize` | `image`, `video`, `file` | Maximum file size in bytes. |
110
+ | `description` | ALL | Human-readable hint (shown in Studio UI tooltip, used as agent context). |
111
+
112
+ ### 3.2 Omission Rules
113
+
114
+ These rules produce minimal, clean schema definitions:
115
+
116
+ - If `required` is `false` (the default), do NOT include it.
117
+ - If `unique` is `false` (the default), do NOT include it.
118
+ - If `default` is `null`, do NOT include it.
119
+ - Only include properties that add information. Fewer properties = fewer tokens = faster agent processing.
120
+
121
+ ---
122
+
123
+ ## 4. Model Definition
124
+
125
+ Model definitions live at `.contentrain/models/{model-id}.json`. One file per model.
126
+
127
+ ```json
128
+ {
129
+ "id": "blog-post",
130
+ "name": "Blog Post",
131
+ "kind": "document",
132
+ "domain": "blog",
133
+ "i18n": true,
134
+ "description": "Blog articles with markdown body",
135
+ "fields": {
136
+ "title": { "type": "string", "required": true, "max": 120 },
137
+ "slug": { "type": "slug", "required": true, "unique": true },
138
+ "author": { "type": "relation", "model": "team-members", "required": true },
139
+ "tags": { "type": "array", "items": "string" }
140
+ }
141
+ }
142
+ ```
143
+
144
+ ### 4.1 Model Properties
145
+
146
+ | Property | Type | Required | Description |
147
+ |----------|------|----------|-------------|
148
+ | `id` | `string` | Yes | Unique identifier, **kebab-case**. |
149
+ | `name` | `string` | Yes | Human-readable display name. |
150
+ | `kind` | `string` | Yes | One of: `singleton`, `collection`, `document`, `dictionary`. |
151
+ | `domain` | `string` | Yes | Organizational group (maps to content subdirectory). |
152
+ | `i18n` | `boolean` | Yes | Whether the model supports multiple locales. |
153
+ | `description` | `string` | No | Model description for documentation and agent context. |
154
+ | `fields` | `object` | Yes (except dictionary) | Field definitions. Dictionary kind has NO fields. |
155
+ | `content_path` | `string` | No | Framework-relative path for content files (e.g., `"content/blog"`, `"locales"`). When set, content is written here instead of `.contentrain/content/`. |
156
+ | `locale_strategy` | `string` | No | How locale is encoded in file names: `"file"` (default), `"suffix"`, `"directory"`, `"none"`. |
157
+
158
+ ### 4.2 System Fields
159
+
160
+ Do NOT define these in the schema. The platform manages them automatically:
161
+
162
+ | Field | Kind | Source |
163
+ |-------|------|--------|
164
+ | `id` | Collection | 12-char hex, used as object-map key |
165
+ | `slug` | Document | Directory name in content path |
166
+ | `createdAt` / `updatedAt` | All | Derived from Git commit history (not stored) |
167
+ | `status`, `source`, `updated_by`, `approved_by` | All | Stored in `.contentrain/meta/` |
168
+
169
+ ---
170
+
171
+ ### 4.3 Locale Strategy Rules
172
+
173
+ The `locale_strategy` property controls how locale is encoded in file paths:
174
+
175
+ | Strategy | i18n:true JSON path | i18n:true Document path | i18n:false path |
176
+ |----------|---------------------|------------------------|-----------------|
177
+ | `file` (default) | `{dir}/{locale}.json` | `{dir}/{slug}/{locale}.md` | `{dir}/data.json` |
178
+ | `suffix` | `{dir}/{model}.{locale}.json` | `{dir}/{slug}.{locale}.md` | `{dir}/data.json` |
179
+ | `directory` | `{dir}/{locale}/{model}.json` | `{dir}/{locale}/{slug}.md` | `{dir}/data.json` |
180
+ | `none` | **INVALID** (requires i18n:false) | **INVALID** | `{dir}/{model}.json` or `{dir}/{slug}.md` |
181
+
182
+ - `locale_strategy: "none"` requires `i18n: false`. The "none" strategy stores a single file without locale encoding.
183
+ - When `content_path` is set, `{dir}` is the content_path. Otherwise `{dir}` is `.contentrain/content/{domain}/{model-id}`.
184
+
185
+ ---
186
+
187
+ ## 5. The Four Model Kinds
188
+
189
+ ### 5.1 Singleton
190
+
191
+ **One instance per locale.** Use for page sections, site config, navigation.
192
+
193
+ | Aspect | Detail |
194
+ |--------|--------|
195
+ | Storage | JSON object (one file per locale) |
196
+ | File path | `content/{domain}/{model-id}/{locale}.json` |
197
+ | `i18n: false` path | `content/{domain}/{model-id}/data.json` |
198
+ | ID management | None (single instance) |
199
+ | Relation target | Cannot be referenced by relations |
200
+
201
+ ```json
202
+ {
203
+ "cta": "Get Started",
204
+ "title": "Build faster"
205
+ }
206
+ ```
207
+
208
+ ### 5.2 Collection
209
+
210
+ **Multiple entries.** Use for team members, products, FAQs, categories.
211
+
212
+ | Aspect | Detail |
213
+ |--------|--------|
214
+ | Storage | JSON object-map (entry ID as key, sorted lexicographically) |
215
+ | File path | `content/{domain}/{model-id}/{locale}.json` |
216
+ | Tool output | Array with `id` injected |
217
+ | ID management | Auto-generated 12-char hex |
218
+ | Relation target | Referenced by entry `id` |
219
+
220
+ ```json
221
+ {
222
+ "a1b2c3d4e5f6": { "name": "Ahmet", "role": "CEO" },
223
+ "f6e5d4c3b2a1": { "name": "Jane", "role": "CTO" }
224
+ }
225
+ ```
226
+
227
+ ### 5.3 Document
228
+
229
+ **Markdown with frontmatter.** Use for blog posts, documentation, changelogs.
230
+
231
+ | Aspect | Detail |
232
+ |--------|--------|
233
+ | Storage | `.md` file with YAML frontmatter |
234
+ | File path | `content/{domain}/{model-id}/{slug}/{locale}.md` |
235
+ | `i18n: false` path | `content/{domain}/{model-id}/{slug}.md` |
236
+ | ID management | `slug` field (URL-safe, unique) |
237
+ | Relation target | Referenced by `slug` |
238
+
239
+ ```markdown
240
+ ---
241
+ title: Getting Started
242
+ slug: getting-started
243
+ author: a1b2c3d4e5f6
244
+ ---
245
+ # Getting Started with Contentrain
246
+ ```
247
+
248
+ ### 5.4 Dictionary
249
+
250
+ **Flat key-value pairs.** Use for error messages, UI strings, translations.
251
+
252
+ | Aspect | Detail |
253
+ |--------|--------|
254
+ | Storage | Flat JSON object (key-value, all values are strings) |
255
+ | File path | `content/{domain}/{model-id}/{locale}.json` |
256
+ | Fields definition | None -- dictionary models have NO `fields` property |
257
+ | ID management | Key is identity |
258
+ | Relation target | Cannot be referenced by relations |
259
+
260
+ ```json
261
+ {
262
+ "auth.expired": "Session expired",
263
+ "auth.failed": "Authentication failed"
264
+ }
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 6. Relation Rules
270
+
271
+ ### 6.1 Basic Relations
272
+
273
+ ```json
274
+ "author": { "type": "relation", "model": "team-members", "required": true }
275
+ "categories": { "type": "relations", "model": "categories" }
276
+ ```
277
+
278
+ - `relation` (1:1): Value is a single string -- an entry ID or slug.
279
+ - `relations` (1:many): Value is a string array of entry IDs or slugs.
280
+
281
+ ### 6.2 Target Model Restrictions
282
+
283
+ | Target Kind | Reference Key | Can Be Target? |
284
+ |-------------|--------------|----------------|
285
+ | Collection | Entry `id` | Yes |
286
+ | Document | Document `slug` | Yes |
287
+ | Singleton | -- | No |
288
+ | Dictionary | -- | No |
289
+
290
+ ### 6.3 Polymorphic Relations
291
+
292
+ When a field can reference multiple model types:
293
+
294
+ ```json
295
+ "target": { "type": "relation", "model": ["blog-post", "page"] }
296
+ ```
297
+
298
+ Storage for polymorphic references uses a compound value:
299
+
300
+ ```json
301
+ { "model": "blog-post", "ref": "getting-started" }
302
+ ```
303
+
304
+ ### 6.4 Self-Referencing
305
+
306
+ Models can reference themselves (e.g., hierarchical categories):
307
+
308
+ ```json
309
+ "parent": { "type": "relation", "model": "categories" }
310
+ ```
311
+
312
+ ### 6.5 Resolution Rules
313
+
314
+ - Relations are resolved **1 level deep** -- no recursive resolution.
315
+ - **Unresolved IDs** (target entry does not exist) are kept as raw strings (graceful degradation).
316
+ - **Cascade deletion does not exist.** Deleting a referenced entry produces a broken relation warning.
317
+ - **Array order is preserved** for `relations` type.
318
+ - **IDs/slugs are locale-agnostic.** The same reference works across all locales.
319
+
320
+ ### 6.6 Validation
321
+
322
+ - Referenced ID/slug MUST exist in the target model.
323
+ - `model` property MUST reference an existing model ID.
324
+ - Referential integrity is checked by `contentrain_validate`.
325
+ - Deleting a model that is referenced by other models is BLOCKED.
326
+
327
+ ---
328
+
329
+ ## 7. Nesting Limits
330
+
331
+ ### 7.1 Object Type
332
+
333
+ ```json
334
+ "address": {
335
+ "type": "object",
336
+ "fields": {
337
+ "city": { "type": "string", "required": true },
338
+ "street": { "type": "string", "required": true },
339
+ "zip": { "type": "string" }
340
+ }
341
+ }
342
+ ```
343
+
344
+ ### 7.2 Array of Objects
345
+
346
+ ```json
347
+ "variants": {
348
+ "type": "array",
349
+ "items": {
350
+ "type": "object",
351
+ "fields": {
352
+ "color": { "type": "color", "required": true },
353
+ "price": { "type": "decimal", "required": true },
354
+ "size": { "type": "select", "options": ["S", "M", "L"] }
355
+ }
356
+ },
357
+ "max": 50
358
+ }
359
+ ```
360
+
361
+ ### 7.3 Depth Limit
362
+
363
+ **Maximum nesting depth: 2 levels.** An object inside an object is allowed. An object inside an object inside an object is NOT.
364
+
365
+ - Prefer flat types over deeply nested structures.
366
+ - Use relations to model complex data relationships instead of nesting.
367
+ - If you need deeper nesting, create a separate model and use a `relation` field.
368
+
369
+ ---
370
+
371
+ ## 8. Naming Conventions
372
+
373
+ | Element | Convention | Example |
374
+ |---------|-----------|---------|
375
+ | Model ID | kebab-case | `blog-post`, `team-members` |
376
+ | Field key | snake_case | `hero_image`, `cta_url` |
377
+ | Domain | lowercase, single word or kebab-case | `blog`, `marketing`, `system` |
378
+ | Dictionary key | dot-notation | `auth.failed`, `validation.required` |
379
+ | Slug | lowercase, kebab-case | `getting-started` |
380
+ | Locale | ISO 639-1 | `en`, `tr`, `de` |