-
Notifications
You must be signed in to change notification settings - Fork 0
feat: layout spec v1 and migration framework (M1.3) #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e8a3c0c
feat: add layout spec v1 and migration framework (M1.3)
e34a323
fix: harden layout version read/write validation
ddd7aa2
fix: use Keep a Changelog date format and add link reference for 1.1.0
4aaa313
chore: bump version to 1.1.1 and update CHANGELOG with review fixes
ef954cb
fix: remove redundant readLayoutVersion call and add whitespace test
6536766
chore: bump version to 1.1.2 and update CHANGELOG with round-2 fixes
318dc09
fix: document TOCTOU limitation and add Infinity edge case test
182eae5
chore: bump version to 1.1.3 and update CHANGELOG with round-3 fixes
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| # Layout Specification — v1 | ||
|
|
||
| > Canonical reference for the git-cms repository layout. | ||
| > Version changes are forward-only; see **Migration Policy** below. | ||
|
|
||
| ## Layout Version | ||
|
|
||
| Stored in git config under the key `cms.layout.version`. | ||
|
|
||
| | Key | Type | Default (if absent) | | ||
| |------------------------|--------|---------------------| | ||
| | `cms.layout.version` | string | `0` (pre-versioned) | | ||
|
|
||
| Current codebase version: **1**. | ||
|
|
||
| ## Ref Namespace | ||
|
|
||
| All CMS refs live under a configurable prefix (default `refs/_blog/dev`). | ||
|
|
||
| ``` | ||
| {refPrefix}/{kind}/{slug} | ||
| ``` | ||
|
|
||
| | Kind | Pattern | Purpose | | ||
| |--------------|------------------------------------|----------------------------| | ||
| | `articles` | `{refPrefix}/articles/{slug}` | Draft / working ref | | ||
| | `published` | `{refPrefix}/published/{slug}` | Published snapshot ref | | ||
| | `comments` | `{refPrefix}/comments/{slug}` | (Reserved for future use) | | ||
|
|
||
| Slugs are canonicalized per `ContentIdentityPolicy`: lowercase, `[a-z0-9]+(-[a-z0-9]+)*`, 1–64 chars, NFKC-normalized, no reserved words. | ||
|
|
||
| ## State Derivation | ||
|
|
||
| Effective state is derived from **two inputs**: | ||
|
|
||
| 1. The `status` trailer on the tip commit of `articles/{slug}` | ||
| 2. The presence or absence of the `published/{slug}` ref | ||
|
|
||
| | Effective State | `status` trailer | `published/{slug}` ref | | ||
| |-----------------|------------------|------------------------| | ||
| | draft | `draft` | absent | | ||
| | published | `draft` | present | | ||
| | unpublished | `unpublished` | absent | | ||
| | reverted | `reverted` | absent | | ||
|
|
||
| ### Allowed Transitions | ||
|
|
||
| ``` | ||
| draft → draft, published, reverted | ||
| published → unpublished, published | ||
| unpublished → draft, published | ||
| reverted → draft | ||
| ``` | ||
|
|
||
| ## Commit Message Format | ||
|
|
||
| Commit messages are encoded/decoded via `@git-stunts/trailer-codec`. | ||
|
|
||
| ``` | ||
| <title> | ||
|
|
||
| <body> | ||
|
|
||
| <key>: <value> | ||
| <key>: <value> | ||
| ... | ||
| ``` | ||
|
|
||
| ### Required Trailers | ||
|
|
||
| | Trailer | Description | | ||
| |--------------|------------------------------------------| | ||
| | `contentid` | Canonical slug (matches slug in v1) | | ||
| | `status` | One of: `draft`, `unpublished`, `reverted` | | ||
| | `updatedAt` | ISO 8601 timestamp of last mutation | | ||
|
|
||
| ### Optional Trailers | ||
|
|
||
| | Trailer | Description | | ||
| |-------------------|--------------------------------------| | ||
| | `restoredFromSha` | SHA of the version that was restored | | ||
| | `restoredAt` | ISO 8601 timestamp of the restore | | ||
|
|
||
| > **Note:** `trailer-codec` normalizes keys to lowercase during decode. | ||
| > Use camelCase when encoding; read lowercase when consuming decoded output. | ||
|
|
||
| ## Config Keys | ||
|
|
||
| | Key | Description | | ||
| |------------------------|------------------------------------| | ||
| | `cms.layout.version` | Repo layout version (integer as string) | | ||
|
|
||
| ## Invariants | ||
|
|
||
| The following invariants hold for a well-formed v1 repo. (Enforcement deferred to M1.4 `verify` command.) | ||
|
|
||
| 1. Every `articles/{slug}` tip commit has a valid `status` trailer. | ||
| 2. Every `published/{slug}` ref points to a commit reachable from `articles/{slug}`. | ||
| 3. No orphan `published/{slug}` ref exists without a corresponding `articles/{slug}`. | ||
| 4. All slugs satisfy `ContentIdentityPolicy` canonicalization rules. | ||
| 5. `cms.layout.version` equals `1` after migration. | ||
|
|
||
| ## Migration Policy | ||
|
|
||
| - **Forward-only:** migrations never downgrade the layout version. | ||
| - **Idempotent:** running `migrate` on an already-current repo is a no-op. | ||
| - **Guard:** if the repo version exceeds the codebase version, migration refuses to run (`layout_version_too_new`). | ||
| - **v0 → v1:** stamps `cms.layout.version = 1` (no structural changes — formalizes existing layout). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| /** | ||
| * Layout migration framework for git-cms. | ||
| * | ||
| * Pure-function module — takes a `graph` adapter (GraphPersistencePort) as | ||
| * dependency. No CmsService import. | ||
| * | ||
| * Layout version is stored in git config under `cms.layout.version`. | ||
| * A missing key is treated as version 0 (pre-versioned repo). | ||
| */ | ||
|
|
||
| import { CmsValidationError } from './ContentIdentityPolicy.js'; | ||
|
|
||
| export const CURRENT_LAYOUT_VERSION = 1; | ||
| export const LAYOUT_VERSION_KEY = 'cms.layout.version'; | ||
|
|
||
| /** | ||
| * Reads the current layout version from the graph's config. | ||
| * Returns 0 if the key is unset (pre-versioned repo). | ||
| * | ||
| * @param {import('@git-stunts/git-warp').GraphPersistencePort} graph | ||
| * @returns {Promise<number>} | ||
| */ | ||
| export async function readLayoutVersion(graph) { | ||
| const raw = await graph.configGet(LAYOUT_VERSION_KEY); | ||
| if (raw === null) return 0; | ||
| if (raw.trim() === '') { | ||
| throw new CmsValidationError( | ||
| `Invalid layout version in config: "${raw}"`, | ||
| { code: 'layout_version_invalid', field: LAYOUT_VERSION_KEY } | ||
| ); | ||
| } | ||
| const version = Number(raw); | ||
| if (!Number.isInteger(version) || version < 0) { | ||
| throw new CmsValidationError( | ||
| `Invalid layout version in config: "${raw}"`, | ||
| { code: 'layout_version_invalid', field: LAYOUT_VERSION_KEY } | ||
| ); | ||
| } | ||
| return version; | ||
| } | ||
|
|
||
| /** | ||
| * Writes a layout version to the graph's config. | ||
| * | ||
| * @param {import('@git-stunts/git-warp').GraphPersistencePort} graph | ||
| * @param {number} version | ||
| * @returns {Promise<void>} | ||
| */ | ||
| export async function writeLayoutVersion(graph, version) { | ||
| if (!Number.isInteger(version) || version < 0) { | ||
| throw new CmsValidationError( | ||
| `Cannot write invalid layout version: ${version}`, | ||
| { code: 'layout_version_invalid', field: LAYOUT_VERSION_KEY } | ||
| ); | ||
| } | ||
| await graph.configSet(LAYOUT_VERSION_KEY, String(version)); | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Ordered list of [targetVersion, migrateFn] pairs. | ||
| * Each migrateFn receives { graph, refPrefix } and performs the migration. | ||
| * | ||
| * @type {Array<[number, (ctx: {graph: any, refPrefix: string}) => Promise<void>]>} | ||
| */ | ||
| const MIGRATIONS = Object.freeze([ | ||
| Object.freeze([1, async (_ctx) => { /* v0→v1: no-op — stamps the version */ }]), | ||
| ]); | ||
|
|
||
| /** | ||
| * Returns the subset of migrations that need to run given the current version. | ||
| * | ||
| * @param {number} currentVersion | ||
| * @returns {Array<[number, Function]>} | ||
| */ | ||
| export function pendingMigrations(currentVersion) { | ||
| return MIGRATIONS.filter(([target]) => target > currentVersion); | ||
| } | ||
|
|
||
| /** | ||
| * Runs all pending migrations in order. | ||
| * Not concurrency-safe — caller must ensure exclusive access. | ||
| * | ||
| * @param {{ graph: any, refPrefix: string }} ctx | ||
| * @returns {Promise<{ from: number, to: number, applied: number[] }>} | ||
| */ | ||
| export async function migrate({ graph, refPrefix }) { | ||
| const from = await readLayoutVersion(graph); | ||
|
|
||
| if (from > CURRENT_LAYOUT_VERSION) { | ||
| throw new CmsValidationError( | ||
| `Repo layout version (${from}) is newer than codebase version (${CURRENT_LAYOUT_VERSION}). Upgrade git-cms first.`, | ||
| { code: 'layout_version_too_new', field: LAYOUT_VERSION_KEY } | ||
| ); | ||
| } | ||
|
|
||
| const pending = pendingMigrations(from); | ||
| const applied = []; | ||
|
|
||
| for (const [target, migrateFn] of pending) { | ||
| await migrateFn({ graph, refPrefix }); | ||
| await writeLayoutVersion(graph, target); | ||
| applied.push(target); | ||
| } | ||
|
|
||
| const to = applied.length > 0 ? applied[applied.length - 1] : from; | ||
| return { from, to, applied }; | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { describe, it, expect, beforeEach, afterEach } from 'vitest'; | ||
| import { mkdtempSync, rmSync } from 'node:fs'; | ||
| import path from 'node:path'; | ||
| import os from 'node:os'; | ||
| import { execFileSync } from 'node:child_process'; | ||
| import CmsService from '../src/lib/CmsService.js'; | ||
| import { migrate, readLayoutVersion, LAYOUT_VERSION_KEY } from '../src/lib/LayoutMigration.js'; | ||
|
|
||
| describe('Layout Migration (E2E — real git)', () => { | ||
| let cwd; | ||
| const refPrefix = 'refs/cms'; | ||
|
|
||
| beforeEach(() => { | ||
| cwd = mkdtempSync(path.join(os.tmpdir(), 'git-cms-layout-e2e-')); | ||
| execFileSync('git', ['init'], { cwd }); | ||
| execFileSync('git', ['config', 'user.name', 'Test'], { cwd }); | ||
| execFileSync('git', ['config', 'user.email', 'test@example.com'], { cwd }); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| rmSync(cwd, { recursive: true, force: true }); | ||
| }); | ||
|
|
||
| it('stamps version readable via raw git config', async () => { | ||
| const cms = new CmsService({ cwd, refPrefix }); | ||
| const result = await migrate({ graph: cms.graph, refPrefix }); | ||
|
|
||
| expect(result.from).toBe(0); | ||
| expect(result.to).toBe(1); | ||
|
|
||
| // Verify via raw git config (not through adapter) | ||
| const raw = execFileSync('git', ['config', '--get', LAYOUT_VERSION_KEY], { cwd }).toString().trim(); | ||
| expect(raw).toBe('1'); | ||
| }); | ||
|
|
||
| it('existing articles survive migration', async () => { | ||
| const cms = new CmsService({ cwd, refPrefix }); | ||
| await cms.saveSnapshot({ slug: 'survive-test', title: 'Before', body: 'Content' }); | ||
|
|
||
| await migrate({ graph: cms.graph, refPrefix }); | ||
|
|
||
| const article = await cms.readArticle({ slug: 'survive-test' }); | ||
| expect(article.title).toBe('Before'); | ||
| expect(article.body).toContain('Content'); | ||
| expect(await readLayoutVersion(cms.graph)).toBe(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.