Skip to main content

gitgrip/core/
manifest.rs

1//! Manifest parsing and validation
2//!
3//! The workspace file (gripspace.yml) defines the multi-repo workspace configuration.
4
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::path::Path;
8use thiserror::Error;
9
10/// Errors that can occur when loading or validating a manifest
11#[derive(Error, Debug)]
12pub enum ManifestError {
13    #[error("Failed to read manifest file: {0}")]
14    IoError(#[from] std::io::Error),
15
16    #[error("Failed to parse manifest YAML: {0}")]
17    ParseError(#[from] serde_yaml::Error),
18
19    #[error("Validation error: {0}")]
20    ValidationError(String),
21
22    #[error("Path escapes workspace boundary: {0}")]
23    PathTraversal(String),
24
25    #[error("Gripspace error: {0}")]
26    GripspaceError(String),
27}
28
29/// Hosting platform type
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
31#[serde(rename_all = "lowercase")]
32pub enum PlatformType {
33    #[default]
34    #[serde(rename = "github")]
35    GitHub,
36    #[serde(rename = "gitlab")]
37    GitLab,
38    #[serde(rename = "azure-devops")]
39    AzureDevOps,
40    #[serde(rename = "bitbucket")]
41    Bitbucket,
42}
43
44impl std::fmt::Display for PlatformType {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            PlatformType::GitHub => write!(f, "github"),
48            PlatformType::GitLab => write!(f, "gitlab"),
49            PlatformType::AzureDevOps => write!(f, "azure-devops"),
50            PlatformType::Bitbucket => write!(f, "bitbucket"),
51        }
52    }
53}
54
55/// Platform configuration for a repository
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct PlatformConfig {
58    #[serde(rename = "type")]
59    pub platform_type: PlatformType,
60    /// Base URL for self-hosted instances
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub base_url: Option<String>,
63}
64
65/// File copy configuration
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct CopyFileConfig {
68    /// Source path relative to repo
69    pub src: String,
70    /// Destination path relative to workspace root
71    pub dest: String,
72}
73
74/// Symlink configuration
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct LinkFileConfig {
77    /// Source path relative to repo
78    pub src: String,
79    /// Destination path relative to workspace root
80    pub dest: String,
81}
82
83/// Gripspace include configuration
84#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct GripspaceConfig {
86    /// Git URL for the gripspace repository
87    pub url: String,
88    /// Optional revision (branch, tag, or commit SHA) to pin
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub rev: Option<String>,
91}
92
93/// A part of a composed file
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct ComposeFilePart {
96    /// Source path, relative to whichever source kind this part names
97    pub src: String,
98    /// Name of the gripspace to source from
99    #[serde(skip_serializing_if = "Option::is_none")]
100    pub gripspace: Option<String>,
101    /// Name of a repo from `repos:` to source from, resolved against that
102    /// repo's checkout path.
103    ///
104    /// The third source kind, and the one that lets a gripspace compose from
105    /// the repos it actually manages. Without it a part could only read from a
106    /// gripspace or from the manifest repo, so a plain repo had to become a
107    /// gripspace before it could contribute to a composed file.
108    ///
109    /// Mutually exclusive with `gripspace`: a part naming both is ambiguous
110    /// and is refused rather than silently resolved to one of them.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub repo: Option<String>,
113}
114
115/// Composed file configuration
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct ComposeFileConfig {
118    /// Destination path relative to workspace root
119    pub dest: String,
120    /// Ordered parts to concatenate
121    pub parts: Vec<ComposeFilePart>,
122    /// Separator between parts (default: "\n\n")
123    #[serde(skip_serializing_if = "Option::is_none")]
124    pub separator: Option<String>,
125}
126
127/// Agent context for a repository — build/test/lint commands for AI agents
128#[derive(Debug, Clone, Default, Serialize, Deserialize)]
129pub struct RepoAgentConfig {
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub description: Option<String>,
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub language: Option<String>,
134    #[serde(skip_serializing_if = "Option::is_none")]
135    pub build: Option<String>,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub test: Option<String>,
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub lint: Option<String>,
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub format: Option<String>,
142}
143
144/// A context generation target for an AI tool
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct AgentContextTarget {
147    /// Target format: claude, opencode, codex, cursor, raw
148    pub format: String,
149    /// Destination path relative to workspace root ({repo} placeholder for per-repo generation)
150    pub dest: String,
151    /// Additional files to append to the generated context
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub compose_with: Option<Vec<String>>,
154}
155
156/// Agent context for a workspace — conventions and workflows for AI agents
157#[derive(Debug, Clone, Default, Serialize, Deserialize)]
158pub struct WorkspaceAgentConfig {
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub description: Option<String>,
161    #[serde(default, skip_serializing_if = "Vec::is_empty")]
162    pub conventions: Vec<String>,
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub workflows: Option<HashMap<String, String>>,
165    /// Source file for context generation (supports gripspace: prefix)
166    #[serde(skip_serializing_if = "Option::is_none")]
167    pub context_source: Option<String>,
168    /// Targets for multi-tool context generation
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub targets: Option<Vec<AgentContextTarget>>,
171}
172
173/// Remote configuration (top-level named remotes with base fetch URLs)
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub struct RemoteConfig {
176    /// Base fetch URL — repo name + ".git" is auto-appended
177    pub fetch: String,
178}
179
180/// Clone strategy for a repository
181///
182/// `worktree` was removed 2026-09-04: it was accepted by validation and then
183/// silently ignored by sync (both strategies
184/// fell through to clone_repo(), never implemented) -- worse than absent, since a
185/// manifest declaring it read as configured while doing nothing. Declaring
186/// `clone_strategy: worktree` now fails to deserialize (ManifestError::ParseError)
187/// on every repo, not only reference repos.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
189#[serde(rename_all = "lowercase")]
190pub enum CloneStrategy {
191    /// Standalone git clone (the only supported strategy — best isolation, no
192    /// shared .git state)
193    #[default]
194    Clone,
195}
196
197impl std::fmt::Display for CloneStrategy {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        match self {
200            CloneStrategy::Clone => write!(f, "clone"),
201        }
202    }
203}
204
205/// Repository configuration in the manifest
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct RepoConfig {
208    /// Git URL (SSH or HTTPS). Required unless `remote` is set.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub url: Option<String>,
211    /// Reference to a top-level remote (derives URL from remote's fetch base + repo name)
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub remote: Option<String>,
214    /// Local path relative to manifest root
215    pub path: String,
216    /// Upstream revision to sync/clone (e.g. "main", "master"). Inherits from settings.
217    #[serde(
218        default,
219        skip_serializing_if = "Option::is_none",
220        alias = "default_branch"
221    )]
222    pub revision: Option<String>,
223    /// PR base branch (just a branch name, e.g. "develop"). Falls back to revision.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub target: Option<String>,
226    /// Remote for fetch/rebase operations (e.g. "origin", "upstream"). Inherits from settings.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub sync_remote: Option<String>,
229    /// Remote for push operations (e.g. "origin"). Inherits from settings.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub push_remote: Option<String>,
232    /// Optional file copies
233    #[serde(skip_serializing_if = "Option::is_none")]
234    pub copyfile: Option<Vec<CopyFileConfig>>,
235    /// Optional symlinks
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub linkfile: Option<Vec<LinkFileConfig>>,
238    /// Optional platform override
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub platform: Option<PlatformConfig>,
241    /// Reference repo (read-only, excluded from branch/PR operations)
242    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
243    pub reference: bool,
244    /// Groups this repo belongs to (for selective operations)
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub groups: Vec<String>,
247    /// Agent context metadata (build/test/lint commands for AI agents)
248    #[serde(skip_serializing_if = "Option::is_none")]
249    pub agent: Option<RepoAgentConfig>,
250    /// Clone strategy: `clone` (default) or `worktree` (opt-in experimental).
251    /// Reference repos always use `clone` regardless of this setting.
252    /// Inherits from `settings.clone_strategy` if not set.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub clone_strategy: Option<CloneStrategy>,
255}
256
257/// Manifest repository self-tracking configuration
258#[derive(Debug, Clone, Serialize, Deserialize)]
259pub struct ManifestRepoConfig {
260    /// Git URL for the manifest repository
261    pub url: String,
262    /// Upstream revision (inherits from settings.revision if not set)
263    #[serde(
264        default,
265        skip_serializing_if = "Option::is_none",
266        alias = "default_branch"
267    )]
268    pub revision: Option<String>,
269    /// Optional file copies
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub copyfile: Option<Vec<CopyFileConfig>>,
272    /// Optional symlinks
273    #[serde(skip_serializing_if = "Option::is_none")]
274    pub linkfile: Option<Vec<LinkFileConfig>>,
275    /// Optional composed files (concatenated from gripspace + local parts)
276    #[serde(skip_serializing_if = "Option::is_none")]
277    pub composefile: Option<Vec<ComposeFileConfig>>,
278    /// Optional platform override
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub platform: Option<PlatformConfig>,
281}
282
283/// PR merge strategy
284#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
285#[serde(rename_all = "kebab-case")]
286pub enum MergeStrategy {
287    /// All linked PRs must be merged together or none
288    #[default]
289    AllOrNothing,
290    /// Each PR can be merged independently
291    Independent,
292}
293
294/// The git merge method used when `gr pr merge` is given no `--method`.
295///
296/// `Merge` is the default deliberately: it is the only method that preserves
297/// both parents, and a workspace that wants a different one should have to say
298/// so in the manifest rather than inherit it from whatever a host happens to
299/// allow.
300#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
301#[serde(rename_all = "lowercase")]
302pub enum DefaultMergeMethod {
303    #[default]
304    Merge,
305    Squash,
306    Rebase,
307}
308
309/// Global manifest settings
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct ManifestSettings {
312    /// PR title prefix (e.g., "[cross-repo]")
313    #[serde(default = "default_pr_prefix")]
314    pub pr_prefix: String,
315    /// Cross-repo coordination for linked PRs (all-or-nothing vs independent).
316    ///
317    /// NOT the git merge method -- see `merge_method`. The two names read
318    /// confusingly alike and mean unrelated things; the issue that prompted
319    /// `merge_method` called that out explicitly.
320    #[serde(default)]
321    pub merge_strategy: MergeStrategy,
322    /// The git merge METHOD `gr pr merge` uses when `--method` is not passed.
323    ///
324    /// Defaults to `merge`, a real merge commit. Auto-detection used to pick
325    /// the first method a repo allowed, in the order squash > merge > rebase,
326    /// which meant the tool actively selected squash on any repo permitting it.
327    /// A workspace whose policy is merge-commit-only got squashes from its own
328    /// tooling, and on a private repo -- where hosting rulesets are unavailable
329    /// on most plans -- nothing downstream could reject it.
330    #[serde(default)]
331    pub merge_method: DefaultMergeMethod,
332    /// Upstream revision for all repos (e.g. "main"). Overridden by per-repo revision.
333    #[serde(
334        default,
335        skip_serializing_if = "Option::is_none",
336        alias = "default_branch"
337    )]
338    pub revision: Option<String>,
339    /// PR base branch for all repos (just a branch name, e.g. "develop").
340    /// Overridden by per-repo target. Falls back to revision.
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub target: Option<String>,
343    /// Remote for fetch/rebase operations (default: "origin"). Overridden by per-repo sync_remote.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub sync_remote: Option<String>,
346    /// Remote for push operations (default: "origin"). Overridden by per-repo push_remote.
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub push_remote: Option<String>,
349    /// Default clone strategy for all repos. Per-repo `clone_strategy` overrides this.
350    /// Defaults to `clone` if not set.
351    #[serde(default)]
352    pub clone_strategy: CloneStrategy,
353}
354
355fn default_pr_prefix() -> String {
356    "[cross-repo]".to_string()
357}
358
359impl Default for ManifestSettings {
360    fn default() -> Self {
361        Self {
362            pr_prefix: default_pr_prefix(),
363            merge_strategy: MergeStrategy::default(),
364            merge_method: DefaultMergeMethod::default(),
365            revision: None,
366            target: None,
367            sync_remote: None,
368            push_remote: None,
369            clone_strategy: CloneStrategy::default(),
370        }
371    }
372}
373
374/// A step in a multi-step script
375#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct ScriptStep {
377    /// Step name for display
378    pub name: String,
379    /// Command to execute
380    pub command: String,
381    /// Optional working directory
382    #[serde(skip_serializing_if = "Option::is_none")]
383    pub cwd: Option<String>,
384}
385
386/// Workspace script definition
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct WorkspaceScript {
389    /// Optional description
390    #[serde(skip_serializing_if = "Option::is_none")]
391    pub description: Option<String>,
392    /// Single command (mutually exclusive with steps)
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub command: Option<String>,
395    /// Working directory for command
396    #[serde(skip_serializing_if = "Option::is_none")]
397    pub cwd: Option<String>,
398    /// Multi-step commands (mutually exclusive with command)
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub steps: Option<Vec<ScriptStep>>,
401}
402
403/// Condition for when a hook should run
404#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
405#[serde(rename_all = "lowercase")]
406pub enum HookCondition {
407    /// Always run the hook
408    #[default]
409    Always,
410    /// Only run if repos had changes during sync
411    Changed,
412}
413
414/// Hook command definition
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct HookCommand {
417    /// Command to execute
418    pub command: String,
419    /// Optional working directory
420    #[serde(skip_serializing_if = "Option::is_none")]
421    pub cwd: Option<String>,
422    /// Optional display name for the hook
423    #[serde(skip_serializing_if = "Option::is_none")]
424    pub name: Option<String>,
425    /// Optional list of repos this hook applies to (for condition: changed)
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub repos: Option<Vec<String>>,
428    /// When to run the hook (default: always)
429    #[serde(default)]
430    pub condition: HookCondition,
431}
432
433/// Workspace lifecycle hooks
434#[derive(Debug, Clone, Default, Serialize, Deserialize)]
435pub struct WorkspaceHooks {
436    /// Hooks to run after sync
437    #[serde(rename = "post-sync", skip_serializing_if = "Option::is_none")]
438    pub post_sync: Option<Vec<HookCommand>>,
439    /// Hooks to run after checkout
440    #[serde(rename = "post-checkout", skip_serializing_if = "Option::is_none")]
441    pub post_checkout: Option<Vec<HookCommand>>,
442}
443
444/// A step in a CI pipeline
445#[derive(Debug, Clone, Serialize, Deserialize)]
446pub struct CiStep {
447    /// Step name for display
448    pub name: String,
449    /// Command to execute
450    pub command: String,
451    /// Optional working directory (relative to workspace root)
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub cwd: Option<String>,
454    /// Optional environment variables for this step
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub env: Option<HashMap<String, String>>,
457    /// Continue pipeline even if this step fails
458    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
459    pub continue_on_error: bool,
460}
461
462/// A CI pipeline definition
463#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct CiPipeline {
465    /// Optional description
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub description: Option<String>,
468    /// Steps to execute sequentially
469    pub steps: Vec<CiStep>,
470}
471
472/// CI/CD configuration in the workspace
473#[derive(Debug, Clone, Default, Serialize, Deserialize)]
474pub struct CiConfig {
475    /// Named pipelines
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub pipelines: Option<HashMap<String, CiPipeline>>,
478}
479
480/// A version file to update during release
481#[derive(Debug, Clone, Serialize, Deserialize)]
482pub struct VersionFileConfig {
483    /// Path relative to workspace root (e.g. "gitgrip/Cargo.toml")
484    pub path: String,
485    /// Pattern with `{version}` placeholder (e.g. `version = "{version}"`)
486    pub pattern: String,
487}
488
489/// Release workflow configuration
490#[derive(Debug, Clone, Default, Serialize, Deserialize)]
491pub struct ReleaseConfig {
492    /// Version files to update (auto-detected if not specified)
493    #[serde(skip_serializing_if = "Option::is_none")]
494    pub version_files: Option<Vec<VersionFileConfig>>,
495    /// Path to changelog file (default: "CHANGELOG.md")
496    #[serde(skip_serializing_if = "Option::is_none")]
497    pub changelog: Option<String>,
498    /// Commands to run after release (supports {version} substitution)
499    #[serde(skip_serializing_if = "Option::is_none")]
500    pub post_release: Option<Vec<HookCommand>>,
501}
502
503/// Workspace configuration
504#[derive(Debug, Clone, Default, Serialize, Deserialize)]
505pub struct WorkspaceConfig {
506    /// Environment variables
507    #[serde(skip_serializing_if = "Option::is_none")]
508    pub env: Option<HashMap<String, String>>,
509    /// Named scripts
510    #[serde(skip_serializing_if = "Option::is_none")]
511    pub scripts: Option<HashMap<String, WorkspaceScript>>,
512    /// Lifecycle hooks
513    #[serde(skip_serializing_if = "Option::is_none")]
514    pub hooks: Option<WorkspaceHooks>,
515    /// CI/CD pipelines
516    #[serde(skip_serializing_if = "Option::is_none")]
517    pub ci: Option<CiConfig>,
518    /// Agent context metadata (conventions and workflows for AI agents)
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub agent: Option<WorkspaceAgentConfig>,
521    /// Release workflow configuration
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub release: Option<ReleaseConfig>,
524}
525
526/// The main manifest structure
527#[derive(Debug, Clone, Serialize, Deserialize)]
528pub struct Manifest {
529    /// Schema version
530    #[serde(default = "default_version")]
531    pub version: u32,
532    /// Named remotes with base fetch URLs (v2)
533    #[serde(default, skip_serializing_if = "Option::is_none")]
534    pub remotes: Option<HashMap<String, RemoteConfig>>,
535    /// Gripspace includes (composable manifest inheritance)
536    #[serde(skip_serializing_if = "Option::is_none")]
537    pub gripspaces: Option<Vec<GripspaceConfig>>,
538    /// Self-tracking manifest config (optional)
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub manifest: Option<ManifestRepoConfig>,
541    /// Repository definitions
542    pub repos: HashMap<String, RepoConfig>,
543    /// Global settings
544    #[serde(default)]
545    pub settings: ManifestSettings,
546    /// Workspace config (optional)
547    #[serde(skip_serializing_if = "Option::is_none")]
548    pub workspace: Option<WorkspaceConfig>,
549}
550
551fn default_version() -> u32 {
552    2
553}
554
555/// Keys `Manifest` accepts at the top level.
556///
557/// Kept beside the struct deliberately: if a field is added there and not here,
558/// a valid manifest starts warning, which is a loud failure rather than a silent
559/// one. That is the correct direction for this list to rot in.
560const TOP_LEVEL_KEYS: &[&str] = &[
561    "version",
562    "remotes",
563    "gripspaces",
564    "manifest",
565    "repos",
566    "settings",
567    "workspace",
568];
569
570/// Keys that are VALID somewhere else, mapped to where they belong.
571///
572/// MISPLACEMENT IS THE COMMON CASE, NOT TYPOS. Every entry here is a real field
573/// on `ManifestRepoConfig`, i.e. something a user writes at the top level
574/// because that is where it reads like it should go. Naming the right home
575/// turns a warning into a fix.
576const MISPLACED_KEY_HOMES: &[(&str, &str)] = &[
577    ("composefile", "manifest.composefile"),
578    ("copyfile", "manifest.copyfile"),
579    ("linkfile", "manifest.linkfile"),
580    ("platform", "manifest.platform"),
581    ("url", "manifest.url"),
582    ("revision", "manifest.revision"),
583];
584
585impl Manifest {
586    /// Top-level keys present in the YAML that no field will receive.
587    ///
588    /// *** WHY THIS EXISTS: SERDE DISCARDS UNKNOWN KEYS IN SILENCE. ***
589    ///
590    /// No manifest struct carries `deny_unknown_fields`, so a key that matches
591    /// no field is dropped during deserialization with no error, no warning and
592    /// exit 0. A `composefile:` block written at the top level instead of under
593    /// `manifest:` therefore vanishes: the block is in the file, `gr manifest
594    /// schema` knows the key, nothing is a parse failure, and nothing is
595    /// produced. Measured 2026-08-11; it cost two rounds of misdiagnosis
596    /// because every visible signal said success.
597    ///
598    /// `deny_unknown_fields` is the obvious fix and is the wrong one: it turns
599    /// every extra key into a hard parse error, so a manifest carrying a
600    /// forward-compatibility key stops loading on upgrade. That trades a silent
601    /// failure for a breaking one. Warning keeps every existing manifest
602    /// loading while making the discard impossible to miss.
603    ///
604    /// Returns messages rather than printing, so this is testable and so the
605    /// caller decides where they go.
606    pub fn unknown_top_level_keys(yaml: &str) -> Vec<String> {
607        let value: serde_yaml::Value = match serde_yaml::from_str(yaml) {
608            Ok(value) => value,
609            // A genuine syntax error is reported by the real parse; this pass
610            // must never turn one error into two.
611            Err(_) => return Vec::new(),
612        };
613        let mapping = match value.as_mapping() {
614            Some(mapping) => mapping,
615            None => return Vec::new(),
616        };
617
618        let mut warnings = Vec::new();
619        for (key, _) in mapping {
620            let key = match key.as_str() {
621                Some(key) => key,
622                None => continue,
623            };
624            if TOP_LEVEL_KEYS.contains(&key) {
625                continue;
626            }
627            match MISPLACED_KEY_HOMES.iter().find(|(name, _)| *name == key) {
628                Some((_, home)) => warnings.push(format!(
629                    "manifest key '{key}' is not valid at the top level and was IGNORED \
630                     - did you mean '{home}'?"
631                )),
632                None => warnings.push(format!(
633                    "manifest key '{key}' is not a known key and was IGNORED"
634                )),
635            }
636        }
637        warnings
638    }
639
640    /// Load a manifest from a YAML file
641    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, ManifestError> {
642        let content = std::fs::read_to_string(path)?;
643        Self::parse(&content)
644    }
645
646    /// Parse a manifest from a YAML string (deserialize only, no validation)
647    ///
648    /// Use this when you need to process the manifest before validation,
649    /// e.g., resolving gripspace includes that merge additional repos.
650    pub fn parse_raw(yaml: &str) -> Result<Self, ManifestError> {
651        // WARN HERE, NOT IN `load`. This is the single chokepoint: `parse`
652        // calls `parse_raw`, `load` calls `parse`, and `sync` calls `parse_raw`
653        // DIRECTLY -- so a hook in `load` fires on the least-used path and is
654        // silent for the command that matters. Verified by call-site count
655        // rather than assumed, after a first attempt hooked `load` and produced
656        // exactly nothing on `gr sync`, which is the same mistake as assuming
657        // where composition was invoked from.
658        //
659        // STDERR, not `Output::warning`, which uses println!. A correctness
660        // warning on stdout is swallowed by redirection and corrupts `--json`
661        // consumers, and a warning nobody reads is the defect this fixes one
662        // layer up.
663        for warning in Self::unknown_top_level_keys(yaml) {
664            eprintln!("\u{26a0} {warning}");
665        }
666        let mut manifest: Manifest = serde_yaml::from_str(yaml)?;
667        manifest.migrate_v1();
668        Ok(manifest)
669    }
670
671    /// Migrate v1 manifests to v2 semantics.
672    /// - `default_branch` → `revision` is handled by serde `alias`
673    /// - `target` containing "/" is split into (sync_remote, target)
674    fn migrate_v1(&mut self) {
675        if self.version > 1 {
676            return;
677        }
678        // Migrate settings.target: "origin/develop" → target="develop", sync_remote="origin"
679        if let Some(ref target) = self.settings.target {
680            if let Some((remote, branch)) = target.split_once('/') {
681                if remote != "origin" {
682                    self.settings.sync_remote = Some(remote.to_string());
683                }
684                self.settings.target = Some(branch.to_string());
685            }
686        }
687        // Migrate per-repo targets
688        for repo in self.repos.values_mut() {
689            // Ensure v1 repos that had a required `url` field get it wrapped in Some
690            // (serde alias handles default_branch → revision)
691            if let Some(ref target) = repo.target {
692                if let Some((remote, branch)) = target.split_once('/') {
693                    if remote != "origin" && repo.sync_remote.is_none() {
694                        repo.sync_remote = Some(remote.to_string());
695                    }
696                    repo.target = Some(branch.to_string());
697                }
698            }
699        }
700        self.version = 2;
701    }
702
703    /// Parse a manifest from a YAML string (deserialize + validate + migrate)
704    pub fn parse(yaml: &str) -> Result<Self, ManifestError> {
705        let manifest = Self::parse_raw(yaml)?;
706        // Note: migrate_v1() is already called in parse_raw()
707        manifest.validate()?;
708        Ok(manifest)
709    }
710
711    /// Resolve the effective clone strategy for a repo.
712    ///
713    /// Resolution order:
714    /// 1. Reference repos always return `Clone` regardless of config
715    /// 2. Per-repo `clone_strategy` if set
716    /// 3. Global `settings.clone_strategy`
717    pub fn effective_clone_strategy(&self, repo: &RepoConfig) -> CloneStrategy {
718        if repo.reference {
719            return CloneStrategy::Clone;
720        }
721        repo.clone_strategy.unwrap_or(self.settings.clone_strategy)
722    }
723
724    /// Validate the manifest
725    pub fn validate(&self) -> Result<(), ManifestError> {
726        // Must have at least one repo
727        if self.repos.is_empty() {
728            return Err(ManifestError::ValidationError(
729                "Manifest must have at least one repository".to_string(),
730            ));
731        }
732
733        // Validate each repo config
734        for (name, repo) in &self.repos {
735            self.validate_repo_config(name, repo)?;
736        }
737
738        // Validate manifest repo config if present
739        if let Some(ref manifest_config) = self.manifest {
740            self.validate_file_configs(
741                "manifest",
742                &manifest_config.copyfile,
743                &manifest_config.linkfile,
744            )?;
745            if let Some(ref composefiles) = manifest_config.composefile {
746                self.validate_composefiles(composefiles)?;
747            }
748        }
749
750        // Validate gripspace configs
751        if let Some(ref gripspaces) = self.gripspaces {
752            for gs in gripspaces {
753                if gs.url.is_empty() {
754                    return Err(ManifestError::ValidationError(
755                        "Gripspace has empty URL".to_string(),
756                    ));
757                }
758            }
759        }
760
761        // Validate workspace scripts
762        if let Some(ref workspace) = self.workspace {
763            self.validate_workspace_config(workspace)?;
764        }
765
766        Ok(())
767    }
768
769    /// Lint the manifest for portability issues (warnings, not errors).
770    /// Returns a list of warning messages about absolute paths in hooks,
771    /// scripts, and env values. (#418)
772    pub fn lint_absolute_paths(&self) -> Vec<String> {
773        let mut warnings = Vec::new();
774
775        if let Some(ref workspace) = self.workspace {
776            // Check hooks (post-sync and post-checkout)
777            if let Some(ref hooks) = workspace.hooks {
778                let all_hooks = hooks
779                    .post_sync
780                    .iter()
781                    .flatten()
782                    .chain(hooks.post_checkout.iter().flatten());
783                for hook in all_hooks {
784                    if hook.command.starts_with('/') || is_windows_absolute(&hook.command) {
785                        warnings.push(format!(
786                            "Hook command contains absolute path: {}",
787                            hook.command.chars().take(80).collect::<String>()
788                        ));
789                    }
790                }
791            }
792
793            // Check env values
794            if let Some(ref env) = workspace.env {
795                for (key, val) in env {
796                    if val.starts_with('/') || is_windows_absolute(val) {
797                        warnings.push(format!(
798                            "Env var {} contains absolute path: {}",
799                            key,
800                            val.chars().take(80).collect::<String>()
801                        ));
802                    }
803                }
804            }
805        }
806
807        warnings
808    }
809
810    /// Validate a gripspace manifest (allows empty repos since gripspaces may only contribute
811    /// scripts, hooks, env, or file configs).
812    pub fn validate_as_gripspace(&self) -> Result<(), ManifestError> {
813        // Validate each repo config (if any)
814        for (name, repo) in &self.repos {
815            self.validate_repo_config(name, repo)?;
816        }
817
818        // Validate manifest config if present
819        if let Some(ref manifest_config) = self.manifest {
820            self.validate_file_configs(
821                "manifest",
822                &manifest_config.copyfile,
823                &manifest_config.linkfile,
824            )?;
825            if let Some(ref composefiles) = manifest_config.composefile {
826                self.validate_composefiles(composefiles)?;
827            }
828        }
829
830        // Validate gripspace configs
831        if let Some(ref gripspaces) = self.gripspaces {
832            for gs in gripspaces {
833                if gs.url.is_empty() {
834                    return Err(ManifestError::ValidationError(
835                        "Gripspace has empty URL".to_string(),
836                    ));
837                }
838            }
839        }
840
841        // Validate workspace scripts
842        if let Some(ref workspace) = self.workspace {
843            self.validate_workspace_config(workspace)?;
844        }
845
846        Ok(())
847    }
848
849    fn validate_repo_config(&self, name: &str, repo: &RepoConfig) -> Result<(), ManifestError> {
850        // Must have either url or remote
851        let has_url = repo.url.as_ref().is_some_and(|u| !u.is_empty());
852        let has_remote = repo.remote.as_ref().is_some_and(|r| !r.is_empty());
853        if !has_url && !has_remote {
854            return Err(ManifestError::ValidationError(format!(
855                "Repository '{}' must have either a 'url' or 'remote'",
856                name
857            )));
858        }
859
860        // If remote is set, verify it exists in top-level remotes
861        if let Some(ref remote_name) = repo.remote {
862            if !remote_name.is_empty() {
863                let remote_exists = self
864                    .remotes
865                    .as_ref()
866                    .is_some_and(|r| r.contains_key(remote_name));
867                if !remote_exists {
868                    return Err(ManifestError::ValidationError(format!(
869                        "Repository '{}' references remote '{}' which is not defined in top-level remotes",
870                        name, remote_name
871                    )));
872                }
873            }
874        }
875
876        // Path must be non-empty
877        if repo.path.is_empty() {
878            return Err(ManifestError::ValidationError(format!(
879                "Repository '{}' must have a path",
880                name
881            )));
882        }
883
884        // Validate path doesn't escape boundary
885        if path_escapes_boundary(&repo.path) {
886            return Err(ManifestError::PathTraversal(format!(
887                "Repository '{}' path escapes workspace boundary: {}",
888                name, repo.path
889            )));
890        }
891
892        // Validate copyfile/linkfile configs
893        self.validate_file_configs(name, &repo.copyfile, &repo.linkfile)?;
894
895        Ok(())
896    }
897
898    fn validate_file_configs(
899        &self,
900        repo_name: &str,
901        copyfile: &Option<Vec<CopyFileConfig>>,
902        linkfile: &Option<Vec<LinkFileConfig>>,
903    ) -> Result<(), ManifestError> {
904        if let Some(ref copyfiles) = copyfile {
905            for cf in copyfiles {
906                if cf.src.is_empty() || cf.dest.is_empty() {
907                    return Err(ManifestError::ValidationError(format!(
908                        "Repository '{}' has copyfile with empty src or dest",
909                        repo_name
910                    )));
911                }
912                if path_escapes_boundary(&cf.src) {
913                    return Err(ManifestError::PathTraversal(format!(
914                        "Repository '{}' copyfile src escapes boundary: {}",
915                        repo_name, cf.src
916                    )));
917                }
918                if path_escapes_boundary(&cf.dest) {
919                    return Err(ManifestError::PathTraversal(format!(
920                        "Repository '{}' copyfile dest escapes boundary: {}",
921                        repo_name, cf.dest
922                    )));
923                }
924            }
925        }
926
927        if let Some(ref linkfiles) = linkfile {
928            for lf in linkfiles {
929                if lf.src.is_empty() || lf.dest.is_empty() {
930                    return Err(ManifestError::ValidationError(format!(
931                        "Repository '{}' has linkfile with empty src or dest",
932                        repo_name
933                    )));
934                }
935                if path_escapes_boundary(&lf.src) {
936                    return Err(ManifestError::PathTraversal(format!(
937                        "Repository '{}' linkfile src escapes boundary: {}",
938                        repo_name, lf.src
939                    )));
940                }
941                if path_escapes_boundary(&lf.dest) {
942                    return Err(ManifestError::PathTraversal(format!(
943                        "Repository '{}' linkfile dest escapes boundary: {}",
944                        repo_name, lf.dest
945                    )));
946                }
947            }
948        }
949
950        Ok(())
951    }
952
953    fn validate_workspace_config(&self, workspace: &WorkspaceConfig) -> Result<(), ManifestError> {
954        if let Some(ref scripts) = workspace.scripts {
955            for (name, script) in scripts {
956                // Scripts must have either command or steps, not both
957                match (&script.command, &script.steps) {
958                    (Some(_), Some(_)) => {
959                        return Err(ManifestError::ValidationError(format!(
960                            "Script '{}' cannot have both 'command' and 'steps'",
961                            name
962                        )));
963                    }
964                    (None, None) => {
965                        return Err(ManifestError::ValidationError(format!(
966                            "Script '{}' must have either 'command' or 'steps'",
967                            name
968                        )));
969                    }
970                    (None, Some(steps)) => {
971                        // Validate each step
972                        for step in steps {
973                            if step.name.is_empty() {
974                                return Err(ManifestError::ValidationError(format!(
975                                    "Script '{}' has a step with empty name",
976                                    name
977                                )));
978                            }
979                            if step.command.is_empty() {
980                                return Err(ManifestError::ValidationError(format!(
981                                    "Script '{}' step '{}' has empty command",
982                                    name, step.name
983                                )));
984                            }
985                        }
986                    }
987                    (Some(_), None) => {
988                        // Single command is valid
989                    }
990                }
991            }
992        }
993
994        Ok(())
995    }
996
997    fn validate_composefiles(
998        &self,
999        composefiles: &[ComposeFileConfig],
1000    ) -> Result<(), ManifestError> {
1001        for cf in composefiles {
1002            if cf.dest.is_empty() {
1003                return Err(ManifestError::ValidationError(
1004                    "Composefile has empty dest".to_string(),
1005                ));
1006            }
1007            if path_escapes_boundary(&cf.dest) {
1008                return Err(ManifestError::PathTraversal(format!(
1009                    "Composefile dest escapes boundary: {}",
1010                    cf.dest
1011                )));
1012            }
1013            if cf.parts.is_empty() {
1014                return Err(ManifestError::ValidationError(format!(
1015                    "Composefile '{}' has no parts",
1016                    cf.dest
1017                )));
1018            }
1019            for part in &cf.parts {
1020                if part.src.is_empty() {
1021                    return Err(ManifestError::ValidationError(format!(
1022                        "Composefile '{}' has a part with empty src",
1023                        cf.dest
1024                    )));
1025                }
1026                if path_escapes_boundary(&part.src) {
1027                    return Err(ManifestError::PathTraversal(format!(
1028                        "Composefile '{}' part src escapes boundary: {}",
1029                        cf.dest, part.src
1030                    )));
1031                }
1032                if let Some(ref gs_name) = part.gripspace {
1033                    if gs_name.is_empty() {
1034                        return Err(ManifestError::ValidationError(format!(
1035                            "Composefile '{}' has a part with empty gripspace name",
1036                            cf.dest
1037                        )));
1038                    }
1039                    if gs_name.contains("..") || gs_name.contains('/') || gs_name.contains('\\') {
1040                        return Err(ManifestError::PathTraversal(format!(
1041                            "Composefile '{}' gripspace name contains invalid characters: {}",
1042                            cf.dest, gs_name
1043                        )));
1044                    }
1045                }
1046            }
1047        }
1048
1049        Ok(())
1050    }
1051}
1052
1053fn is_windows_absolute(path: &str) -> bool {
1054    let bytes = path.as_bytes();
1055    (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
1056        || path.starts_with("\\\\")
1057}
1058
1059/// Check if a path escapes the workspace boundary
1060fn path_escapes_boundary(path: &str) -> bool {
1061    // Normalize path separators
1062    let normalized = path.replace('\\', "/");
1063
1064    // Reject: paths starting with "..", "/", containing "/../", ending with "/..",
1065    // or Windows absolute/UNC paths.
1066    if normalized.starts_with("..")
1067        || normalized.starts_with('/')
1068        || normalized.contains("/../")
1069        || normalized.ends_with("/..")
1070        || is_windows_absolute(path)
1071    {
1072        return true;
1073    }
1074
1075    false
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081
1082    #[test]
1083    fn test_parse_minimal_manifest() {
1084        let yaml = r#"
1085repos:
1086  myrepo:
1087    url: git@github.com:user/repo.git
1088    path: repo
1089"#;
1090        let manifest = Manifest::parse(yaml).unwrap();
1091        assert_eq!(manifest.repos.len(), 1);
1092        assert!(manifest.repos.contains_key("myrepo"));
1093    }
1094
1095    #[test]
1096    fn test_parse_full_manifest() {
1097        let yaml = r#"
1098version: 1
1099manifest:
1100  url: git@github.com:user/manifest.git
1101  default_branch: main
1102repos:
1103  app:
1104    url: git@github.com:user/app.git
1105    path: app
1106    default_branch: main
1107    copyfile:
1108      - src: README.md
1109        dest: APP_README.md
1110    linkfile:
1111      - src: config.yaml
1112        dest: app-config.yaml
1113settings:
1114  pr_prefix: "[multi-repo]"
1115  merge_strategy: all-or-nothing
1116workspace:
1117  env:
1118    NODE_ENV: development
1119  scripts:
1120    build:
1121      description: Build all packages
1122      command: npm run build
1123"#;
1124        let manifest = Manifest::parse(yaml).unwrap();
1125        assert_eq!(manifest.version, 2); // v1 auto-migrated to v2
1126        assert!(manifest.manifest.is_some());
1127        assert_eq!(manifest.repos.len(), 1);
1128        assert_eq!(manifest.settings.pr_prefix, "[multi-repo]");
1129    }
1130
1131    #[test]
1132    fn test_empty_repos_fails() {
1133        let yaml = r#"
1134repos: {}
1135"#;
1136        let result = Manifest::parse(yaml);
1137        assert!(result.is_err());
1138    }
1139
1140    #[test]
1141    fn test_path_traversal_fails() {
1142        let yaml = r#"
1143repos:
1144  evil:
1145    url: git@github.com:user/repo.git
1146    path: ../outside
1147"#;
1148        let result = Manifest::parse(yaml);
1149        assert!(matches!(result, Err(ManifestError::PathTraversal(_))));
1150    }
1151
1152    #[test]
1153    fn test_absolute_path_fails() {
1154        let yaml = r#"
1155repos:
1156  evil:
1157    url: git@github.com:user/repo.git
1158    path: /etc/passwd
1159"#;
1160        let result = Manifest::parse(yaml);
1161        assert!(matches!(result, Err(ManifestError::PathTraversal(_))));
1162    }
1163
1164    #[test]
1165    fn test_script_with_both_command_and_steps_fails() {
1166        let yaml = r#"
1167repos:
1168  app:
1169    url: git@github.com:user/app.git
1170    path: app
1171workspace:
1172  scripts:
1173    bad:
1174      command: echo hello
1175      steps:
1176        - name: step1
1177          command: echo step
1178"#;
1179        let result = Manifest::parse(yaml);
1180        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1181    }
1182
1183    #[test]
1184    fn test_path_escapes_boundary() {
1185        assert!(path_escapes_boundary(".."));
1186        assert!(path_escapes_boundary("../foo"));
1187        assert!(path_escapes_boundary("/etc"));
1188        assert!(path_escapes_boundary("foo/../../../etc"));
1189        assert!(path_escapes_boundary("foo/.."));
1190        assert!(path_escapes_boundary("foo/bar/.."));
1191        assert!(path_escapes_boundary("C:\\Windows\\System32\\drivers\\etc"));
1192        assert!(path_escapes_boundary("C:/Windows/System32/drivers/etc"));
1193        assert!(path_escapes_boundary("C:relative\\path"));
1194        assert!(path_escapes_boundary("\\\\server\\share\\folder"));
1195        assert!(!path_escapes_boundary("foo"));
1196        assert!(!path_escapes_boundary("foo/bar"));
1197        assert!(!path_escapes_boundary("./foo"));
1198    }
1199
1200    #[test]
1201    fn test_reference_repos() {
1202        let yaml = r#"
1203repos:
1204  main-repo:
1205    url: git@github.com:user/main.git
1206    path: main
1207  ref-repo:
1208    url: https://github.com/other/reference.git
1209    path: ./ref/reference
1210    reference: true
1211"#;
1212        let manifest = Manifest::parse(yaml).unwrap();
1213        assert_eq!(manifest.repos.len(), 2);
1214
1215        let main_repo = manifest.repos.get("main-repo").unwrap();
1216        assert!(!main_repo.reference);
1217
1218        let ref_repo = manifest.repos.get("ref-repo").unwrap();
1219        assert!(ref_repo.reference);
1220    }
1221
1222    #[test]
1223    fn test_manifest_groups_parse() {
1224        let yaml = r#"
1225repos:
1226  frontend:
1227    url: git@github.com:user/frontend.git
1228    path: frontend
1229    groups: [core, ui]
1230  backend:
1231    url: git@github.com:user/backend.git
1232    path: backend
1233    groups: [core, api]
1234  docs:
1235    url: git@github.com:user/docs.git
1236    path: docs
1237"#;
1238        let manifest = Manifest::parse(yaml).unwrap();
1239        assert_eq!(manifest.repos.len(), 3);
1240
1241        let frontend = manifest.repos.get("frontend").unwrap();
1242        assert_eq!(frontend.groups, vec!["core", "ui"]);
1243
1244        let backend = manifest.repos.get("backend").unwrap();
1245        assert_eq!(backend.groups, vec!["core", "api"]);
1246
1247        let docs = manifest.repos.get("docs").unwrap();
1248        assert!(docs.groups.is_empty());
1249    }
1250
1251    #[test]
1252    fn test_repos_without_groups_default_empty() {
1253        let yaml = r#"
1254repos:
1255  myrepo:
1256    url: git@github.com:user/repo.git
1257    path: repo
1258"#;
1259        let manifest = Manifest::parse(yaml).unwrap();
1260        let repo = manifest.repos.get("myrepo").unwrap();
1261        assert!(repo.groups.is_empty());
1262    }
1263
1264    #[test]
1265    fn test_reference_default_false() {
1266        let yaml = r#"
1267repos:
1268  myrepo:
1269    url: git@github.com:user/repo.git
1270    path: repo
1271"#;
1272        let manifest = Manifest::parse(yaml).unwrap();
1273        let repo = manifest.repos.get("myrepo").unwrap();
1274        assert!(!repo.reference); // Should default to false
1275    }
1276
1277    #[test]
1278    fn test_parse_gripspaces() {
1279        let yaml = r#"
1280gripspaces:
1281  - url: https://github.com/user/base-gripspace.git
1282    rev: main
1283  - url: https://github.com/user/other-gripspace.git
1284repos:
1285  myrepo:
1286    url: git@github.com:user/repo.git
1287    path: repo
1288"#;
1289        let manifest = Manifest::parse(yaml).unwrap();
1290        let gripspaces = manifest.gripspaces.unwrap();
1291        assert_eq!(gripspaces.len(), 2);
1292        assert_eq!(
1293            gripspaces[0].url,
1294            "https://github.com/user/base-gripspace.git"
1295        );
1296        assert_eq!(gripspaces[0].rev.as_deref(), Some("main"));
1297        assert_eq!(
1298            gripspaces[1].url,
1299            "https://github.com/user/other-gripspace.git"
1300        );
1301        assert!(gripspaces[1].rev.is_none());
1302    }
1303
1304    #[test]
1305    fn unknown_top_level_key_that_belongs_elsewhere_names_its_home() {
1306        // The exact defect: composefile written at the top level instead of
1307        // under `manifest:`. Serde discards it, so without this warning the
1308        // whole block vanishes at exit 0.
1309        let yaml = r#"
1310version: 2
1311repos: {}
1312composefile:
1313  - dest: CLAUDE.md
1314    parts:
1315      - src: A.md
1316"#;
1317        let warnings = Manifest::unknown_top_level_keys(yaml);
1318        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
1319        assert!(warnings[0].contains("composefile"));
1320        assert!(
1321            warnings[0].contains("manifest.composefile"),
1322            "a misplacement warning must name where the key belongs: {}",
1323            warnings[0]
1324        );
1325    }
1326
1327    #[test]
1328    fn unknown_top_level_key_with_no_home_is_still_reported() {
1329        let yaml = "version: 2\nrepos: {}\nreposs: {}\n";
1330        let warnings = Manifest::unknown_top_level_keys(yaml);
1331        assert_eq!(warnings.len(), 1, "got: {warnings:?}");
1332        assert!(warnings[0].contains("reposs"));
1333    }
1334
1335    #[test]
1336    fn a_correct_manifest_produces_no_warnings() {
1337        // CONTROL. A warning that fires on valid input is worse than none --
1338        // it trains readers to ignore the channel. Every top-level field is
1339        // exercised here so adding one to the struct without adding it to
1340        // TOP_LEVEL_KEYS turns this RED.
1341        let yaml = r#"
1342version: 2
1343remotes: {}
1344gripspaces: []
1345manifest:
1346  url: file:///tmp/x.git
1347  revision: main
1348  composefile:
1349    - dest: CLAUDE.md
1350      parts:
1351        - src: A.md
1352repos: {}
1353settings: {}
1354workspace: {}
1355"#;
1356        assert!(
1357            Manifest::unknown_top_level_keys(yaml).is_empty(),
1358            "valid manifest warned: {:?}",
1359            Manifest::unknown_top_level_keys(yaml)
1360        );
1361    }
1362
1363    #[test]
1364    fn a_syntax_error_does_not_become_two_errors() {
1365        // The real parse reports genuine syntax errors; this pass must stay
1366        // quiet so one failure is not reported twice in different words.
1367        assert!(Manifest::unknown_top_level_keys("this: [is: not: yaml").is_empty());
1368        assert!(Manifest::unknown_top_level_keys("- a list, not a mapping").is_empty());
1369    }
1370
1371    #[test]
1372    fn test_parse_composefile() {
1373        let yaml = r#"
1374manifest:
1375  url: git@github.com:user/manifest.git
1376  composefile:
1377    - dest: CLAUDE.md
1378      parts:
1379        - gripspace: base-gripspace
1380          src: CODI.md
1381        - src: PRIVATE_DOCS.md
1382      separator: "\n\n---\n\n"
1383    - dest: envsetup.sh
1384      parts:
1385        - gripspace: base-gripspace
1386          src: envsetup.sh
1387        - src: private-envsetup.sh
1388repos:
1389  myrepo:
1390    url: git@github.com:user/repo.git
1391    path: repo
1392"#;
1393        let manifest = Manifest::parse(yaml).unwrap();
1394        let manifest_config = manifest.manifest.unwrap();
1395        let composefiles = manifest_config.composefile.unwrap();
1396        assert_eq!(composefiles.len(), 2);
1397
1398        let cf1 = &composefiles[0];
1399        assert_eq!(cf1.dest, "CLAUDE.md");
1400        assert_eq!(cf1.parts.len(), 2);
1401        assert_eq!(cf1.parts[0].gripspace.as_deref(), Some("base-gripspace"));
1402        assert_eq!(cf1.parts[0].src, "CODI.md");
1403        assert!(cf1.parts[1].gripspace.is_none());
1404        assert_eq!(cf1.parts[1].src, "PRIVATE_DOCS.md");
1405        assert_eq!(cf1.separator.as_deref(), Some("\n\n---\n\n"));
1406
1407        let cf2 = &composefiles[1];
1408        assert_eq!(cf2.dest, "envsetup.sh");
1409        assert_eq!(cf2.parts.len(), 2);
1410    }
1411
1412    #[test]
1413    fn test_parse_raw_does_not_validate() {
1414        let yaml = r#"
1415repos: {}
1416"#;
1417        // parse_raw should succeed even with empty repos (no validation)
1418        let manifest = Manifest::parse_raw(yaml).unwrap();
1419        assert!(manifest.repos.is_empty());
1420
1421        // parse should fail with validation
1422        let result = Manifest::parse(yaml);
1423        assert!(result.is_err());
1424    }
1425
1426    #[test]
1427    fn test_gripspace_empty_url_fails() {
1428        let yaml = r#"
1429gripspaces:
1430  - url: ""
1431repos:
1432  myrepo:
1433    url: git@github.com:user/repo.git
1434    path: repo
1435"#;
1436        let result = Manifest::parse(yaml);
1437        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1438    }
1439
1440    #[test]
1441    fn test_composefile_empty_dest_fails() {
1442        let yaml = r#"
1443manifest:
1444  url: git@github.com:user/manifest.git
1445  composefile:
1446    - dest: ""
1447      parts:
1448        - src: file.md
1449repos:
1450  myrepo:
1451    url: git@github.com:user/repo.git
1452    path: repo
1453"#;
1454        let result = Manifest::parse(yaml);
1455        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1456    }
1457
1458    #[test]
1459    fn test_composefile_empty_parts_fails() {
1460        let yaml = r#"
1461manifest:
1462  url: git@github.com:user/manifest.git
1463  composefile:
1464    - dest: output.md
1465      parts: []
1466repos:
1467  myrepo:
1468    url: git@github.com:user/repo.git
1469    path: repo
1470"#;
1471        let result = Manifest::parse(yaml);
1472        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1473    }
1474
1475    #[test]
1476    fn test_composefile_path_traversal_fails() {
1477        let yaml = r#"
1478manifest:
1479  url: git@github.com:user/manifest.git
1480  composefile:
1481    - dest: ../outside.md
1482      parts:
1483        - src: file.md
1484repos:
1485  myrepo:
1486    url: git@github.com:user/repo.git
1487    path: repo
1488"#;
1489        let result = Manifest::parse(yaml);
1490        assert!(matches!(result, Err(ManifestError::PathTraversal(_))));
1491    }
1492
1493    #[test]
1494    fn test_composefile_gripspace_name_traversal_fails() {
1495        let yaml = r#"
1496manifest:
1497  url: git@github.com:user/manifest.git
1498  composefile:
1499    - dest: output.md
1500      parts:
1501        - gripspace: "../evil"
1502          src: file.md
1503repos:
1504  myrepo:
1505    url: git@github.com:user/repo.git
1506    path: repo
1507"#;
1508        let result = Manifest::parse(yaml);
1509        assert!(matches!(result, Err(ManifestError::PathTraversal(_))));
1510    }
1511
1512    #[test]
1513    fn test_composefile_empty_gripspace_name_fails() {
1514        let yaml = r#"
1515manifest:
1516  url: git@github.com:user/manifest.git
1517  composefile:
1518    - dest: output.md
1519      parts:
1520        - gripspace: ""
1521          src: file.md
1522repos:
1523  myrepo:
1524    url: git@github.com:user/repo.git
1525    path: repo
1526"#;
1527        let result = Manifest::parse(yaml);
1528        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1529    }
1530
1531    #[test]
1532    fn test_validate_as_gripspace_composefile_empty_parts_fails() {
1533        let yaml = r#"
1534manifest:
1535  url: git@github.com:user/manifest.git
1536  composefile:
1537    - dest: output.md
1538      parts: []
1539repos: {}
1540"#;
1541        let manifest = Manifest::parse_raw(yaml).unwrap();
1542        let result = manifest.validate_as_gripspace();
1543        assert!(matches!(result, Err(ManifestError::ValidationError(_))));
1544    }
1545
1546    #[test]
1547    fn test_validate_as_gripspace_composefile_invalid_gripspace_name_fails() {
1548        let yaml = r#"
1549manifest:
1550  url: git@github.com:user/manifest.git
1551  composefile:
1552    - dest: output.md
1553      parts:
1554        - gripspace: "../evil"
1555          src: file.md
1556repos: {}
1557"#;
1558        let manifest = Manifest::parse_raw(yaml).unwrap();
1559        let result = manifest.validate_as_gripspace();
1560        assert!(matches!(result, Err(ManifestError::PathTraversal(_))));
1561    }
1562
1563    #[test]
1564    fn test_parse_repo_agent_config() {
1565        let yaml = r#"
1566repos:
1567  myrepo:
1568    url: git@github.com:user/repo.git
1569    path: repo
1570    agent:
1571      description: "Rust CLI tool"
1572      language: rust
1573      build: "cargo build"
1574      test: "cargo test"
1575      lint: "cargo clippy"
1576      format: "cargo fmt"
1577"#;
1578        let manifest = Manifest::parse(yaml).unwrap();
1579        let repo = manifest.repos.get("myrepo").unwrap();
1580        let agent = repo.agent.as_ref().unwrap();
1581        assert_eq!(agent.description.as_deref(), Some("Rust CLI tool"));
1582        assert_eq!(agent.language.as_deref(), Some("rust"));
1583        assert_eq!(agent.build.as_deref(), Some("cargo build"));
1584        assert_eq!(agent.test.as_deref(), Some("cargo test"));
1585        assert_eq!(agent.lint.as_deref(), Some("cargo clippy"));
1586        assert_eq!(agent.format.as_deref(), Some("cargo fmt"));
1587    }
1588
1589    #[test]
1590    fn test_parse_workspace_agent_config() {
1591        let yaml = r#"
1592repos:
1593  myrepo:
1594    url: git@github.com:user/repo.git
1595    path: repo
1596workspace:
1597  agent:
1598    description: "Multi-repo workspace"
1599    conventions:
1600      - "Use conventional commits"
1601      - "All PRs require review"
1602    workflows:
1603      deploy: "./scripts/deploy.sh"
1604      release: "gr run release"
1605"#;
1606        let manifest = Manifest::parse(yaml).unwrap();
1607        let workspace = manifest.workspace.as_ref().unwrap();
1608        let agent = workspace.agent.as_ref().unwrap();
1609        assert_eq!(agent.description.as_deref(), Some("Multi-repo workspace"));
1610        assert_eq!(agent.conventions.len(), 2);
1611        assert_eq!(agent.conventions[0], "Use conventional commits");
1612        assert_eq!(agent.conventions[1], "All PRs require review");
1613        let workflows = agent.workflows.as_ref().unwrap();
1614        assert_eq!(workflows.get("deploy").unwrap(), "./scripts/deploy.sh");
1615        assert_eq!(workflows.get("release").unwrap(), "gr run release");
1616    }
1617
1618    #[test]
1619    fn test_agent_config_optional() {
1620        let yaml = r#"
1621repos:
1622  myrepo:
1623    url: git@github.com:user/repo.git
1624    path: repo
1625"#;
1626        let manifest = Manifest::parse(yaml).unwrap();
1627        let repo = manifest.repos.get("myrepo").unwrap();
1628        assert!(repo.agent.is_none());
1629        assert!(manifest.workspace.is_none());
1630    }
1631
1632    #[test]
1633    fn test_agent_config_serialization_roundtrip() {
1634        let yaml = r#"
1635repos:
1636  myrepo:
1637    url: git@github.com:user/repo.git
1638    path: repo
1639    agent:
1640      description: "Test repo"
1641      language: rust
1642      build: "cargo build"
1643      test: "cargo test"
1644workspace:
1645  agent:
1646    description: "Test workspace"
1647    conventions:
1648      - "convention one"
1649    workflows:
1650      deploy: "deploy.sh"
1651"#;
1652        let manifest = Manifest::parse(yaml).unwrap();
1653        let serialized = serde_yaml::to_string(&manifest).unwrap();
1654        let reparsed = Manifest::parse(&serialized).unwrap();
1655
1656        let orig_agent = manifest
1657            .repos
1658            .get("myrepo")
1659            .unwrap()
1660            .agent
1661            .as_ref()
1662            .unwrap();
1663        let re_agent = reparsed
1664            .repos
1665            .get("myrepo")
1666            .unwrap()
1667            .agent
1668            .as_ref()
1669            .unwrap();
1670        assert_eq!(orig_agent.description, re_agent.description);
1671        assert_eq!(orig_agent.language, re_agent.language);
1672        assert_eq!(orig_agent.build, re_agent.build);
1673        assert_eq!(orig_agent.test, re_agent.test);
1674
1675        let orig_ws_agent = manifest.workspace.as_ref().unwrap().agent.as_ref().unwrap();
1676        let re_ws_agent = reparsed.workspace.as_ref().unwrap().agent.as_ref().unwrap();
1677        assert_eq!(orig_ws_agent.description, re_ws_agent.description);
1678        assert_eq!(orig_ws_agent.conventions, re_ws_agent.conventions);
1679        assert_eq!(orig_ws_agent.workflows, re_ws_agent.workflows);
1680    }
1681
1682    #[test]
1683    fn test_repo_agent_config_partial() {
1684        let yaml = r#"
1685repos:
1686  myrepo:
1687    url: git@github.com:user/repo.git
1688    path: repo
1689    agent:
1690      language: python
1691      test: "pytest"
1692"#;
1693        let manifest = Manifest::parse(yaml).unwrap();
1694        let repo = manifest.repos.get("myrepo").unwrap();
1695        let agent = repo.agent.as_ref().unwrap();
1696        assert!(agent.description.is_none());
1697        assert_eq!(agent.language.as_deref(), Some("python"));
1698        assert!(agent.build.is_none());
1699        assert_eq!(agent.test.as_deref(), Some("pytest"));
1700        assert!(agent.lint.is_none());
1701        assert!(agent.format.is_none());
1702    }
1703
1704    #[test]
1705    fn test_manifest_with_no_gripspaces() {
1706        let yaml = r#"
1707repos:
1708  myrepo:
1709    url: git@github.com:user/repo.git
1710    path: repo
1711"#;
1712        let manifest = Manifest::parse(yaml).unwrap();
1713        assert!(manifest.gripspaces.is_none());
1714    }
1715
1716    #[test]
1717    fn test_clone_strategy_defaults_to_clone() {
1718        let yaml = r#"
1719repos:
1720  myrepo:
1721    url: git@github.com:user/repo.git
1722    path: repo
1723"#;
1724        let manifest = Manifest::parse(yaml).unwrap();
1725        let repo = &manifest.repos["myrepo"];
1726        assert_eq!(manifest.settings.clone_strategy, CloneStrategy::Clone);
1727        assert!(repo.clone_strategy.is_none());
1728        assert_eq!(
1729            manifest.effective_clone_strategy(repo),
1730            CloneStrategy::Clone
1731        );
1732    }
1733
1734    #[test]
1735    fn test_clone_strategy_worktree_rejected_on_ordinary_repo() {
1736        // CloneStrategy::Worktree was accepted by validation for ordinary repos
1737        // and then silently ignored by sync (both strategies fell through to
1738        // clone_repo()) -- worse than absent, since a manifest declaring it read as configured while
1739        // doing nothing. The variant is deleted below; an unknown "worktree" value now
1740        // fails to deserialize at all, refusing it unconditionally rather than only for
1741        // reference repos.
1742        let yaml = r#"
1743repos:
1744  myrepo:
1745    url: git@github.com:user/repo.git
1746    path: repo
1747    clone_strategy: worktree
1748"#;
1749        let result = Manifest::parse(yaml);
1750        assert!(matches!(result, Err(ManifestError::ParseError(_))));
1751    }
1752
1753    #[test]
1754    fn test_clone_strategy_worktree_rejected_as_global_default() {
1755        let yaml = r#"
1756repos:
1757  myrepo:
1758    url: git@github.com:user/repo.git
1759    path: repo
1760settings:
1761  clone_strategy: worktree
1762"#;
1763        let result = Manifest::parse(yaml);
1764        assert!(matches!(result, Err(ManifestError::ParseError(_))));
1765    }
1766
1767    #[test]
1768    fn test_clone_strategy_per_repo_override_still_resolves_clone() {
1769        // With a single-variant enum, "override" no longer selects a different
1770        // strategy -- it proves the Option<CloneStrategy> inheritance path (unset
1771        // -> global default) still resolves correctly now that worktree is gone.
1772        let yaml = r#"
1773repos:
1774  cloned:
1775    url: git@github.com:user/a.git
1776    path: a
1777  explicit:
1778    url: git@github.com:user/b.git
1779    path: b
1780    clone_strategy: clone
1781"#;
1782        let manifest = Manifest::parse(yaml).unwrap();
1783        assert_eq!(
1784            manifest.effective_clone_strategy(&manifest.repos["cloned"]),
1785            CloneStrategy::Clone
1786        );
1787        assert_eq!(
1788            manifest.effective_clone_strategy(&manifest.repos["explicit"]),
1789            CloneStrategy::Clone
1790        );
1791    }
1792
1793    #[test]
1794    fn test_reference_repo_effective_strategy_always_clone() {
1795        let yaml = r#"
1796repos:
1797  refonly:
1798    url: https://github.com/other/repo.git
1799    path: reference/repo
1800    reference: true
1801"#;
1802        let manifest = Manifest::parse(yaml).unwrap();
1803        assert_eq!(
1804            manifest.effective_clone_strategy(&manifest.repos["refonly"]),
1805            CloneStrategy::Clone
1806        );
1807    }
1808
1809    #[test]
1810    fn test_clone_strategy_backward_compat_no_field() {
1811        // Existing manifests without clone_strategy should parse and default to clone
1812        let yaml = r#"
1813version: 2
1814repos:
1815  synapt:
1816    url: git@github.com:user/synapt.git
1817    path: ./synapt
1818    revision: main
1819settings:
1820  pr_prefix: "[cross-repo]"
1821  merge_strategy: independent
1822"#;
1823        let manifest = Manifest::parse(yaml).unwrap();
1824        assert_eq!(manifest.settings.clone_strategy, CloneStrategy::Clone);
1825        assert_eq!(
1826            manifest.effective_clone_strategy(&manifest.repos["synapt"]),
1827            CloneStrategy::Clone
1828        );
1829    }
1830
1831    #[test]
1832    fn test_lint_catches_absolute_paths_in_hooks() {
1833        let yaml = r#"
1834repos:
1835  myrepo:
1836    url: https://github.com/test/repo.git
1837    path: ./myrepo
1838workspace:
1839  hooks:
1840    post-sync:
1841      - command: "/usr/local/bin/setup.sh"
1842    post-checkout:
1843      - command: "echo ok"
1844  env:
1845    HOME_DIR: "/Users/example/Development"
1846"#;
1847        let manifest: Manifest = serde_yaml::from_str(yaml).unwrap();
1848        let warnings = manifest.lint_absolute_paths();
1849        assert_eq!(warnings.len(), 2);
1850        assert!(warnings[0].contains("Hook command"));
1851        assert!(warnings[1].contains("Env var"));
1852    }
1853
1854    #[test]
1855    fn test_lint_no_warnings_for_relative_paths() {
1856        let yaml = r#"
1857repos:
1858  myrepo:
1859    url: https://github.com/test/repo.git
1860    path: ./myrepo
1861workspace:
1862  hooks:
1863    post-sync:
1864      - command: "./scripts/setup.sh"
1865  env:
1866    PROJECT: "myproject"
1867"#;
1868        let manifest: Manifest = serde_yaml::from_str(yaml).unwrap();
1869        let warnings = manifest.lint_absolute_paths();
1870        assert!(warnings.is_empty());
1871    }
1872}