monochange 0.6.6

Manage versions and releases for your multiplatform, multilanguage monorepo
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::fmt::Write as _;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

use monochange_core::MonochangeError;
use monochange_core::MonochangeResult;
use serde::Serialize;
use serde_json::json;

use crate::SubagentOutputFormat;
use crate::SubagentTarget;

#[derive(Debug, Clone)]
pub(crate) struct SubagentOptions {
	pub targets: Vec<SubagentTarget>,
	pub force: bool,
	pub dry_run: bool,
	pub format: SubagentOutputFormat,
	pub generate_mcp: bool,
}

#[derive(Debug, Clone)]
struct GeneratedFileDraft {
	path: PathBuf,
	description: String,
	contents: String,
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum GeneratedFileOperation {
	Create,
	Overwrite,
	Skip,
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub(crate) struct GeneratedFile {
	pub path: PathBuf,
	pub description: String,
	pub operation: GeneratedFileOperation,
	pub contents: String,
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub(crate) struct SubagentPlan {
	pub targets: Vec<SubagentTarget>,
	pub files: Vec<GeneratedFile>,
	pub notes: Vec<String>,
	pub dry_run: bool,
}

pub(crate) fn run_subagents(root: &Path, options: &SubagentOptions) -> MonochangeResult<String> {
	let plan = build_subagent_plan(root, options)?;

	if !options.dry_run {
		write_subagent_plan(root, &plan, options.force)?;
	}

	match options.format {
		SubagentOutputFormat::Json => {
			serde_json::to_string_pretty(&plan)
				.map_err(|error| MonochangeError::Config(error.to_string()))
		}
		SubagentOutputFormat::Markdown => {
			Ok(crate::maybe_render_markdown_for_terminal(
				&render_subagent_plan_text(&plan),
			))
		}
		SubagentOutputFormat::Text => Ok(render_subagent_plan_text(&plan)),
	}
}

fn build_subagent_plan(root: &Path, options: &SubagentOptions) -> MonochangeResult<SubagentPlan> {
	let mut drafts = Vec::new();
	let mut notes = Vec::new();

	for target in &options.targets {
		for draft in generate_target_files(*target, options.generate_mcp, &mut notes)? {
			push_generated_file(&mut drafts, draft)?;
		}
	}

	let files = drafts
		.into_iter()
		.map(|draft| {
			let absolute_path = root.join(&draft.path);
			let operation = classify_generated_file(&absolute_path, &draft.contents)?;

			Ok(GeneratedFile {
				path: draft.path,
				description: draft.description,
				operation,
				contents: draft.contents,
			})
		})
		.collect::<MonochangeResult<Vec<_>>>()?;

	Ok(SubagentPlan {
		targets: options.targets.clone(),
		files,
		notes,
		dry_run: options.dry_run,
	})
}

fn push_generated_file(
	drafts: &mut Vec<GeneratedFileDraft>,
	draft: GeneratedFileDraft,
) -> MonochangeResult<()> {
	let Some(existing) = drafts.iter().find(|existing| existing.path == draft.path) else {
		drafts.push(draft);
		return Ok(());
	};

	if existing.contents == draft.contents {
		return Ok(());
	}

	Err(MonochangeError::Config(format!(
		"multiple subagent targets attempted to generate different contents for {}",
		draft.path.display()
	)))
}

fn classify_generated_file(
	path: &Path,
	expected: &str,
) -> MonochangeResult<GeneratedFileOperation> {
	if !path.exists() {
		return Ok(GeneratedFileOperation::Create);
	}

	let current = fs::read_to_string(path).map_err(|error| {
		MonochangeError::Io(format!("failed to read {}: {error}", path.display()))
	})?;

	if current == expected {
		return Ok(GeneratedFileOperation::Skip);
	}

	Ok(GeneratedFileOperation::Overwrite)
}

fn write_subagent_plan(root: &Path, plan: &SubagentPlan, force: bool) -> MonochangeResult<()> {
	if !force {
		let mut conflict_message = String::new();
		for file in plan
			.files
			.iter()
			.filter(|file| file.operation == GeneratedFileOperation::Overwrite)
		{
			if conflict_message.is_empty() {
				conflict_message
					.push_str("refusing to overwrite existing subagent files without --force: ");
			} else {
				conflict_message.push_str(", ");
			}
			let _ = write!(conflict_message, "{}", file.path.display());
		}
		if !conflict_message.is_empty() {
			return Err(MonochangeError::Config(conflict_message));
		}
	}

	for file in &plan.files {
		if file.operation == GeneratedFileOperation::Skip {
			continue;
		}

		let absolute_path = root.join(&file.path);
		let Some(parent) = absolute_path.parent() else {
			continue;
		};

		fs::create_dir_all(parent).map_err(|error| {
			MonochangeError::Io(format!("failed to create {}: {error}", parent.display()))
		})?;
		fs::write(&absolute_path, &file.contents).map_err(|error| {
			MonochangeError::Io(format!(
				"failed to write {}: {error}",
				absolute_path.display()
			))
		})?;
	}

	Ok(())
}

fn render_subagent_plan_text(plan: &SubagentPlan) -> String {
	let mut output = String::new();
	let _ = writeln!(output, "monochange subagents");
	let _ = writeln!(output);
	let _ = writeln!(output, "Targets:");

	for target in &plan.targets {
		let _ = writeln!(output, "- {}", subagent_target_name(*target));
	}

	let _ = writeln!(output);
	let _ = writeln!(output, "Files:");

	for file in &plan.files {
		let _ = writeln!(
			output,
			"- {} {}",
			generated_file_operation_name(&file.operation),
			file.path.display()
		);
	}

	if !plan.notes.is_empty() {
		let _ = writeln!(output);
		let _ = writeln!(output, "Notes:");

		for note in &plan.notes {
			let _ = writeln!(output, "- {note}");
		}
	}

	if plan.dry_run {
		let _ = writeln!(output);
		let _ = writeln!(output, "Dry run only. No files were written.");
	}

	output.trim_end().to_string()
}

fn generated_file_operation_name(operation: &GeneratedFileOperation) -> &'static str {
	match operation {
		GeneratedFileOperation::Create => "create",
		GeneratedFileOperation::Overwrite => "overwrite",
		GeneratedFileOperation::Skip => "skip",
	}
}

fn generate_target_files(
	target: SubagentTarget,
	generate_mcp: bool,
	notes: &mut Vec<String>,
) -> MonochangeResult<Vec<GeneratedFileDraft>> {
	let mut files = Vec::new();

	match target {
		SubagentTarget::Claude => {
			files.push(GeneratedFileDraft {
				path: PathBuf::from(".claude/agents/monochange-release-agent.md"),
				description: "Claude subagent definition".to_string(),
				contents: render_claude_agent(),
			});

			if generate_mcp {
				files.push(GeneratedFileDraft {
					path: PathBuf::from(".mcp.json"),
					description: "Claude MCP server configuration".to_string(),
					contents: render_claude_mcp_config()?,
				});
			}
		}

		SubagentTarget::Vscode | SubagentTarget::Copilot => {
			let description = if target == SubagentTarget::Vscode {
				"VS Code"
			} else {
				"GitHub Copilot"
			};
			files.push(GeneratedFileDraft {
				path: PathBuf::from(".github/agents/monochange-release-agent.agent.md"),
				description: format!("{description} agent definition"),
				contents: render_vscode_agent(),
			});

			if generate_mcp {
				files.push(GeneratedFileDraft {
					path: PathBuf::from(".vscode/mcp.json"),
					description: "VS Code MCP server configuration".to_string(),
					contents: render_vscode_mcp_config()?,
				});
			}
		}

		SubagentTarget::Pi => {
			files.push(GeneratedFileDraft {
				path: PathBuf::from(".pi/agents/monochange-release-agent.md"),
				description: "Pi project agent definition".to_string(),
				contents: render_pi_agent(),
			});
		}

		SubagentTarget::Codex => {
			files.push(GeneratedFileDraft {
				path: PathBuf::from(".codex/agents/monochange-release-agent.toml"),
				description: "Codex custom agent definition".to_string(),
				contents: render_codex_agent(),
			});
		}

		SubagentTarget::Cursor => {
			files.push(GeneratedFileDraft {
				path: PathBuf::from(".cursor/rules/monochange.mdc"),
				description: "Cursor workspace rule".to_string(),
				contents: render_cursor_rule(),
			});
			notes.push(
				"Cursor generation currently emits a repo-local workspace rule instead of a native custom subagent manifest.".to_string(),
			);
		}
	}

	Ok(files)
}

fn render_claude_agent() -> String {
	format!(
		"---\nname: monochange-release-agent\ndescription: Use this agent for monochange configuration, changesets, diagnostics, and release planning.\ntools: Bash, Read, Grep, Glob, LS\ncolor: blue\n---\n\n{}\n",
		shared_subagent_instructions(),
	)
}

fn render_vscode_agent() -> String {
	format!(
		"---\nname: monochange-release-agent\ndescription: Use this agent for monochange configuration, changesets, diagnostics, and release planning.\n---\n\n{}\n",
		shared_subagent_instructions(),
	)
}

fn render_pi_agent() -> String {
	format!(
		"---\nname: monochange-release-agent\ndescription: Use this agent for monochange configuration, changesets, diagnostics, and release planning.\ntools: read, grep, find, bash\n---\n\n{}\n",
		shared_subagent_instructions(),
	)
}

fn render_codex_agent() -> String {
	format!(
		"name = \"monochange-release-agent\"\ndescription = \"Use this agent for monochange configuration, changesets, diagnostics, and release planning.\"\ndeveloper_instructions = \"\"\"\n{}\n\"\"\"\n",
		shared_subagent_instructions(),
	)
}

fn render_cursor_rule() -> String {
	format!(
		"---\ndescription: monochange workflow guidance for release planning, changesets, diagnostics, and changelog updates\nglobs:\n  - \"**/*\"\nalwaysApply: false\n---\n\n{}\n",
		shared_cursor_instructions(),
	)
}

fn render_claude_mcp_config() -> MonochangeResult<String> {
	serde_json::to_string_pretty(&json!({
		"mcpServers": {
			"monochange": {
				"command": "npx",
				"args": ["-y", "@monochange/cli", "mcp"]
			}
		}
	}))
	.map_err(|error| MonochangeError::Config(error.to_string()))
}

fn render_vscode_mcp_config() -> MonochangeResult<String> {
	serde_json::to_string_pretty(&json!({
		"servers": {
			"monochange": {
				"type": "stdio",
				"command": "npx",
				"args": ["-y", "@monochange/cli", "mcp"]
			}
		},
		"inputs": []
	}))
	.map_err(|error| MonochangeError::Config(error.to_string()))
}

fn shared_subagent_instructions() -> &'static str {
	"You are the monochange release agent for this repository.

When working on release planning, versioning, changesets, changelogs, or monochange configuration:

1. Read `monochange.toml` before suggesting workflow or release changes.
2. Prefer the monochange CLI over MCP tools.
3. Choose the CLI executable in this order:
   - `mc`
   - `monochange`
   - `npx -y @monochange/cli`
4. Use structured JSON output when inspecting workspace state:
   - `<cli> validate`
   - `<cli> discover --format json`
   - `<cli> diagnostics --format json`
   - `<cli> release --dry-run --format json`
5. Prefer `mc change` and `.changeset/*.md` files over ad hoc release notes.
6. Run validation before and after release-affecting edits.
7. Do not run mutating release or publish commands unless the user explicitly asks.
8. If monochange MCP tools are available, use them as a secondary structured fallback when they are more useful than shelling out.

Recommended workflow:
- validate
- discover
- inspect diagnostics
- edit config or changesets
- run a dry-run release preview
- summarize the impact and next steps"
}

fn shared_cursor_instructions() -> &'static str {
	"When working in this repository on release planning, versioning, changesets, changelogs, or `monochange.toml`:

1. Read `monochange.toml` first.
2. Prefer the monochange CLI over MCP tools.
3. Choose the CLI executable in this order:
   - `mc`
   - `monochange`
   - `npx -y @monochange/cli`
4. Use JSON output when inspecting repository state:
   - `<cli> validate`
   - `<cli> discover --format json`
   - `<cli> diagnostics --format json`
   - `<cli> release --dry-run --format json`
5. Prefer `mc change` and `.changeset/*.md` files over ad hoc release notes.
6. Run validation before and after release-affecting edits.
7. Do not run mutating release or publish commands unless the user explicitly asks.
8. If monochange MCP tools are configured, use them only as a secondary structured fallback."
}

fn subagent_target_name(target: SubagentTarget) -> &'static str {
	match target {
		SubagentTarget::Claude => "claude",
		SubagentTarget::Vscode => "vscode",
		SubagentTarget::Copilot => "copilot",
		SubagentTarget::Pi => "pi",
		SubagentTarget::Codex => "codex",
		SubagentTarget::Cursor => "cursor",
	}
}

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