monochange_schema 0.2.1

Durable JSON schemas and migration helpers for monochange artifacts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Durable JSON schema versions and migration pipelines for monochange artifacts.

use std::fmt;
use std::str::FromStr;

use serde::Serialize;
use serde::Serializer;
use serde_json::Value;
use thiserror::Error;

/// Raw schema version text embedded at compile time from the `SCHEMA_VERSION` file.
///
/// Validated to `major.minor` format by [`current_schema_version`].
pub const CURRENT_SCHEMA_VERSION_TEXT: &str = include_str!("../SCHEMA_VERSION").trim_ascii_end();

mod migrations;

/// A durable schema version written as `major.minor`.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SchemaVersion {
	major: u64,
	minor: u64,
}

impl SchemaVersion {
	/// Create a schema version from major and minor components.
	#[must_use]
	pub const fn new(major: u64, minor: u64) -> Self {
		Self { major, minor }
	}

	/// Major component.
	#[must_use]
	pub const fn major(self) -> u64 {
		self.major
	}

	/// Minor component.
	#[must_use]
	pub const fn minor(self) -> u64 {
		self.minor
	}

	/// Derive a schema version from a semantic package version string.
	pub fn from_package_version(package_version: &str) -> Result<Self, SchemaVersionParseError> {
		let (major, remainder) = package_version
			.split_once('.')
			.ok_or(SchemaVersionParseError::MissingMinor)?;
		let (minor, patch) = remainder
			.split_once('.')
			.ok_or(SchemaVersionParseError::MissingPatch)?;
		if patch.is_empty()
			|| patch.contains('.')
			|| !patch.chars().all(|character| character.is_ascii_digit())
		{
			return Err(SchemaVersionParseError::InvalidPatch(patch.to_string()));
		}
		let major = parse_component(major, SchemaVersionParseError::InvalidMajor)?;
		let minor = parse_component(minor, SchemaVersionParseError::InvalidMinor)?;
		Ok(Self { major, minor })
	}
}

impl fmt::Display for SchemaVersion {
	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(formatter, "{}.{}", self.major, self.minor)
	}
}

impl FromStr for SchemaVersion {
	type Err = SchemaVersionParseError;

	fn from_str(value: &str) -> Result<Self, Self::Err> {
		let (major, minor) = value
			.split_once('.')
			.ok_or(SchemaVersionParseError::MissingSeparator)?;
		if minor.contains('.') {
			return Err(SchemaVersionParseError::TooManyComponents);
		}
		let major = parse_component(major, SchemaVersionParseError::InvalidMajor)?;
		let minor = parse_component(minor, SchemaVersionParseError::InvalidMinor)?;
		Ok(Self { major, minor })
	}
}

impl Serialize for SchemaVersion {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_string())
	}
}

fn parse_component(
	component: &str,
	make_error: fn(String) -> SchemaVersionParseError,
) -> Result<u64, SchemaVersionParseError> {
	if component.is_empty()
		|| !component
			.chars()
			.all(|character| character.is_ascii_digit())
	{
		return Err(make_error(component.to_string()));
	}
	component
		.parse::<u64>()
		.map_err(|_| make_error(component.to_string()))
}

/// Return the current durable schema version.
pub fn current_schema_version() -> Result<SchemaVersion, SchemaVersionParseError> {
	SchemaVersion::from_str(CURRENT_SCHEMA_VERSION_TEXT)
}

fn current_schema_version_for_error() -> SchemaVersion {
	current_schema_version().unwrap_or_else(|_| SchemaVersion::new(0, 0))
}

/// Errors while parsing `major.minor` schema versions.
#[derive(Debug, Clone, Eq, Error, PartialEq)]
pub enum SchemaVersionParseError {
	/// Version text did not contain a `.` separator.
	#[error("missing `.` separator")]
	MissingSeparator,
	/// Package version text did not contain a major component.
	#[error("missing major component")]
	MissingMajor,
	/// Package version text did not contain a minor component.
	#[error("missing minor component")]
	MissingMinor,
	/// Package version text did not contain a patch component.
	#[error("missing patch component")]
	MissingPatch,
	/// Version text had more than major/minor components.
	#[error("expected exactly major.minor")]
	TooManyComponents,
	/// Major component was not a non-negative integer.
	#[error("invalid major component `{0}`")]
	InvalidMajor(String),
	/// Minor component was not a non-negative integer.
	#[error("invalid minor component `{0}`")]
	InvalidMinor(String),
	/// Patch component was not a non-negative integer.
	#[error("invalid patch component `{0}`")]
	InvalidPatch(String),
}

/// Durable artifact migration error.
#[derive(Debug, Error)]
pub enum SchemaError {
	/// Artifact root was not a JSON object.
	#[error("artifact is not a JSON object")]
	NotObject,
	/// Artifact lacked a kind discriminator.
	#[error("artifact is missing required `kind`")]
	MissingKind,
	/// Artifact kind did not match the expected durable artifact.
	#[error("artifact uses unsupported kind `{actual}`; expected `{expected}`")]
	UnsupportedKind {
		/// Actual kind in the payload.
		actual: String,
		/// Expected artifact kind.
		expected: &'static str,
	},
	/// Artifact lacked the current version field.
	#[error("artifact is missing required schema version field `schemaVersion`")]
	MissingVersion,
	/// Current `schemaVersion` field was not a string.
	#[error("artifact schema version field `schemaVersion` must be a string")]
	NonStringVersion,
	/// Current `v` field could not be parsed.
	#[error("artifact uses invalid schema version `{version}`: {source}")]
	InvalidVersion {
		/// Invalid version text.
		version: String,
		/// Parse failure.
		source: SchemaVersionParseError,
	},
	/// Configured current schema version could not be parsed.
	#[error("current schema version `{version}` is invalid: {source}")]
	InvalidCurrentVersion {
		/// Invalid current schema version text.
		version: &'static str,
		/// Parse failure.
		source: SchemaVersionParseError,
	},
	/// Artifact used a schema version newer than this binary can read.
	#[error(
		"artifact uses unsupported schema version `{actual}`; current supported version is `{current}`"
	)]
	UnsupportedVersion {
		/// Version found in the payload.
		actual: String,
		/// Current supported version.
		current: SchemaVersion,
	},
	/// Artifact has no explicit migration path to the current schema version.
	#[error("artifact `{artifact}` has no migration path from schema version `{from}` to `{to}`")]
	MissingMigrationPath {
		/// Durable artifact kind.
		artifact: &'static str,
		/// Version found in the payload.
		from: SchemaVersion,
		/// Current supported version.
		to: SchemaVersion,
	},
	/// JSON conversion failure.
	#[error("artifact json error: {0}")]
	Json(#[from] serde_json::Error),
}

fn object_mut(value: &mut Value) -> Result<&mut serde_json::Map<String, Value>, SchemaError> {
	value.as_object_mut().ok_or(SchemaError::NotObject)
}

fn validate_kind(
	object: &serde_json::Map<String, Value>,
	expected: &'static str,
) -> Result<(), SchemaError> {
	let actual = object
		.get("kind")
		.and_then(Value::as_str)
		.ok_or(SchemaError::MissingKind)?;
	if actual != expected {
		return Err(SchemaError::UnsupportedKind {
			actual: actual.to_string(),
			expected,
		});
	}
	Ok(())
}

fn parse_current_version(value: &Value) -> Result<SchemaVersion, SchemaError> {
	let version = value.as_str().ok_or(SchemaError::NonStringVersion)?;
	SchemaVersion::from_str(version).map_err(|source| {
		SchemaError::InvalidVersion {
			version: version.to_string(),
			source,
		}
	})
}

/// Release-record durable artifact support.
pub mod release_record {
	use serde_json::Value;

	use crate::CURRENT_SCHEMA_VERSION_TEXT;
	use crate::SchemaError;
	use crate::SchemaVersion;
	use crate::current_schema_version_for_error;
	use crate::migrations;
	use crate::object_mut;
	use crate::parse_current_version;
	use crate::validate_kind;

	/// Durable artifact kind for commit-embedded release records.
	pub const KIND: &str = "monochange.releaseRecord";
	pub(crate) const SCHEMA_VERSION_FIELD: &str = "schemaVersion";
	pub(crate) const LEGACY_VERSION_FIELD: &str = "v";

	/// Return the current release-record schema version.
	pub fn current_version() -> Result<SchemaVersion, SchemaError> {
		Ok(current_schema_version_for_error())
	}

	/// Render the current deterministic populated release-record artifact.
	#[must_use]
	pub fn current_populated_artifact_json() -> String {
		populated_artifact_json(CURRENT_SCHEMA_VERSION_TEXT)
	}

	/// Render a deterministic populated release-record artifact for a schema version.
	#[must_use]
	pub fn populated_artifact_json(version: &str) -> String {
		let release_version = format!("{version}.0");
		let tag_name = format!("v{release_version}");
		let schema_tag_name = format!("monochange_schema/v{release_version}");
		let artifact = serde_json::json!({
			"schemaVersion": version,
			"kind": KIND,
			"createdAt": "2026-01-01T00:00:00Z",
			"command": "mc release --commit",
			"version": release_version.as_str(),
			"versions": {
				"main": release_version.as_str(),
				"monochange_schema": release_version.as_str()
			},
			"releaseTargets": [
				{
					"id": "main",
					"kind": "group",
					"version": release_version.as_str(),
					"versionFormat": "primary",
					"tag": true,
					"release": true,
					"tagName": tag_name.as_str(),
					"members": ["monochange", "monochange_core"]
				},
				{
					"id": "monochange_schema",
					"kind": "package",
					"version": release_version.as_str(),
					"versionFormat": "namespaced",
					"tag": false,
					"release": false,
					"tagName": schema_tag_name.as_str(),
					"members": []
				}
			],
			"releasedPackages": ["monochange", "monochange_core", "monochange_schema"],
			"changedFiles": [
				"Cargo.toml",
				"crates/monochange_schema/Cargo.toml",
				"crates/monochange_schema/schemas/artifacts/current/release-record/01.json"
			],
			"updatedChangelogs": ["changelog.md"],
			"deletedChangesets": [".changeset/release-record-schema-compat.md"],
			"changesets": [
				{
					"path": ".changeset/release-record-schema-compat.md",
					"summary": "Keep release record schema compatibility checks stable",
					"details": "Generated release-record artifact fixtures are parsed through the same migration path as commit-embedded records.",
					"targets": [
						{
							"id": "monochange_schema",
							"kind": "package",
							"bump": "major",
							"origin": "frontmatter",
							"evidenceRefs": ["crates/monochange_schema/src/lib.rs"],
							"changeType": "fix",
							"causedBy": ["release-record-schema-compat"]
						}
					]
				}
			],
			"provider": {
				"kind": "github",
				"owner": "monochange",
				"repo": "monochange",
				"host": "github.com"
			}
		});
		serde_json::to_string_pretty(&artifact)
			.unwrap_or_else(|error| panic!("serialize release-record artifact fixture: {error}"))
	}

	/// Convert a release-record JSON value into the current durable wire shape.
	///
	/// This is intended for rendering new artifacts from existing in-memory domain
	/// structs. It writes `schemaVersion` and removes legacy `v`.
	pub fn render_current_value(mut value: Value) -> Result<Value, SchemaError> {
		let object = object_mut(&mut value)?;
		validate_kind(object, KIND)?;
		migrations::remove_top_level_field(&mut value, LEGACY_VERSION_FIELD)?;
		let object = object_mut(&mut value)?;
		object.insert(
			SCHEMA_VERSION_FIELD.to_string(),
			Value::String(CURRENT_SCHEMA_VERSION_TEXT.to_string()),
		);
		Ok(value)
	}

	/// Validate a release-record JSON value against the current durable wire shape.
	///
	/// Release records are embedded in git commits and must remain readable by
	/// newer monochange binaries after schema upgrades. Older `schemaVersion`
	/// values must traverse explicit migration edges; missing edges fail instead
	/// of silently accepting older records. Future versions still fail so older
	/// binaries do not silently misread newer data. Legacy `v` fields are accepted
	/// as a compatibility bridge.
	pub fn migrate_value(mut value: Value) -> Result<Value, SchemaError> {
		let object = object_mut(&mut value)?;
		validate_kind(object, KIND)?;
		let version_value = object
			.get(SCHEMA_VERSION_FIELD)
			.or_else(|| object.get(LEGACY_VERSION_FIELD))
			.ok_or(SchemaError::MissingVersion)?;
		let version = parse_current_version(version_value)?;
		let current = current_version()?;
		if version > current {
			return Err(SchemaError::UnsupportedVersion {
				actual: version.to_string(),
				current,
			});
		}
		migrations::apply_release_record_edges(&mut value, version, current)?;

		migrations::remove_top_level_field(&mut value, LEGACY_VERSION_FIELD)?;
		let object = object_mut(&mut value)?;
		object.insert(
			SCHEMA_VERSION_FIELD.to_string(),
			Value::String(CURRENT_SCHEMA_VERSION_TEXT.to_string()),
		);
		Ok(value)
	}
}

/// Configuration schema artifact support.
pub mod config {
	/// Render a deterministic populated workspace-configuration artifact.
	#[must_use]
	pub fn populated_artifact_json() -> String {
		let artifact = serde_json::json!({
			"source": {
				"owner": "monochange",
				"repo": "monochange",
				"provider": "github"
			}
		});
		serde_json::to_string_pretty(&artifact)
			.unwrap_or_else(|error| panic!("serialize config artifact fixture: {error}"))
	}
}

#[cfg(test)]
#[path = "__tests__/lib_tests.rs"]
mod tests;