Skip to main content

tuff_core/
lockfile.rs

1use std::{
2    collections::BTreeMap,
3    ffi::OsStr,
4    path::{Path, PathBuf},
5};
6
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9
10use crate::error::{Result, TuffError};
11use crate::manifest::{CapabilityType, ImplementationConfig, McpServerConfig};
12
13/// Current on-disk schema. Older readable versions are migrated in memory
14/// by `read_lockfile_at`; writers always emit this version.
15///
16/// Versions 1 and 2 are TOML. Version 3 carries the same rows as version 2
17/// encoded as JSON, in the layout `JSON.stringify(value, null, 2)` produces:
18/// two-space indent, one array element per line, a trailing newline. That
19/// is the layout npm, jq, Python, and VS Code's JSON formatter all agree
20/// on, so a formatter that a repository runs over its JSON files leaves
21/// the lockfile byte for byte unchanged instead of rewriting it.
22///
23/// Version 4 adds the top-level `packs` section (RFC-110 D2): one entry per
24/// installed pack with its source, which for a git pack is the repository
25/// and commit. A version 3 writer would drop that section without an error,
26/// so the version changed rather than the section being added quietly.
27pub const LOCKFILE_VERSION: u8 = 4;
28/// Oldest schema this build still reads.
29pub const OLDEST_READABLE_LOCKFILE_VERSION: u8 = 1;
30
31/// How a lockfile is encoded on disk. Decided by the file's first byte,
32/// never by its version: a lockfile that has been mangled into the wrong
33/// syntax must be reported as such, not parsed as whatever it claims.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35enum WireFormat {
36    Toml,
37    Json,
38}
39
40impl WireFormat {
41    fn detect(raw: &str) -> Self {
42        if raw.trim_start().starts_with('{') {
43            Self::Json
44        } else {
45            Self::Toml
46        }
47    }
48
49    /// The encoding a schema version is defined in.
50    fn for_version(version: u8) -> Self {
51        if version >= 3 { Self::Json } else { Self::Toml }
52    }
53}
54
55impl std::fmt::Display for WireFormat {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.write_str(match self {
58            Self::Toml => "TOML",
59            Self::Json => "JSON",
60        })
61    }
62}
63
64#[derive(Debug, Serialize, Deserialize)]
65pub struct Lockfile {
66    /// The schema version the file was read as, or `LOCKFILE_VERSION` for a
67    /// lockfile built in memory. Writers ignore it and emit the current one.
68    pub version: u8,
69    pub capabilities: BTreeMap<String, CapabilityLockEntry>,
70    /// Installed packs by name (RFC-110 D2). The members are the
71    /// capabilities whose source names the pack; this map holds what the
72    /// pack has as a whole, chiefly where it came from. Kept in step with
73    /// the members on every write by [`Lockfile::normalized_packs`].
74    #[serde(default)]
75    pub packs: BTreeMap<String, PackLockEntry>,
76}
77
78impl Lockfile {
79    /// An empty lockfile of the current schema.
80    pub fn empty() -> Self {
81        Self {
82            version: LOCKFILE_VERSION,
83            capabilities: BTreeMap::new(),
84            packs: BTreeMap::new(),
85        }
86    }
87
88    /// Every capability the lockfile attributes to one pack, sorted by id.
89    pub fn pack_members(&self, pack_name: &str) -> Vec<String> {
90        self.capabilities
91            .iter()
92            .filter(|(_, entry)| {
93                entry
94                    .source
95                    .as_pack()
96                    .is_some_and(|pack| pack.name == pack_name)
97            })
98            .map(|(id, _)| id.clone())
99            .collect()
100    }
101
102    /// The packs section as it should be written: one entry for every pack
103    /// a member names, with the version and digest its members record, and
104    /// none for a pack whose members are all gone. A pack no entry
105    /// describes, such as one read from a version 3 file, came from an
106    /// artifact, with the registry its members recorded.
107    pub fn normalized_packs(&self) -> BTreeMap<String, PackLockEntry> {
108        let mut packs = BTreeMap::new();
109        for entry in self.capabilities.values() {
110            let Some(provenance) = entry.source.as_pack() else {
111                continue;
112            };
113            if packs.contains_key(&provenance.name) {
114                continue;
115            }
116            let recorded = self.packs.get(&provenance.name);
117            let source = recorded.map(|pack| pack.source.clone()).unwrap_or_else(|| {
118                PackSource::Artifact(PackArtifactSource {
119                    registry: provenance.registry.clone(),
120                })
121            });
122            packs.insert(
123                provenance.name.clone(),
124                PackLockEntry {
125                    version: provenance.version.clone(),
126                    digest: provenance.digest.clone(),
127                    source,
128                    x: recorded.map(|pack| pack.x.clone()).unwrap_or_default(),
129                },
130            );
131        }
132        packs
133    }
134}
135
136/// One installed pack (RFC-110 D2).
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
138pub struct PackLockEntry {
139    /// The pack release version.
140    pub version: String,
141    /// Digest of the artifact that was installed, bare lowercase hex. For a
142    /// git pack it is the artifact Tuff built from the checkout, which a
143    /// later Tuff can render differently, so updates compare commits.
144    pub digest: String,
145    pub source: PackSource,
146    /// The pack's host tables (RFC-110 D6), as JSON, carried for the host
147    /// that installed it.
148    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
149    pub x: crate::host::HostTablesJson,
150}
151
152/// Where an installed pack came from.
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(tag = "kind", rename_all = "lowercase")]
155pub enum PackSource {
156    /// A `.tuffpack` file, pulled from an OCI registry when `registry` is set.
157    Artifact(PackArtifactSource),
158    /// A repository holding a `tuff-pack.toml`, at one commit.
159    Git(PackGitSource),
160}
161
162impl PackSource {
163    pub fn as_git(&self) -> Option<&PackGitSource> {
164        match self {
165            Self::Git(git) => Some(git),
166            Self::Artifact(_) => None,
167        }
168    }
169
170    /// The OCI repository an artifact pack was pulled from, when known.
171    pub fn registry(&self) -> Option<&str> {
172        match self {
173            Self::Artifact(artifact) => artifact.registry.as_deref(),
174            Self::Git(_) => None,
175        }
176    }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180pub struct PackArtifactSource {
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub registry: Option<String>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct PackGitSource {
187    pub url: String,
188    /// The repository folder holding `tuff-pack.toml`, empty for the root.
189    #[serde(default)]
190    pub path: String,
191    /// The commit that was installed.
192    #[serde(rename = "ref")]
193    pub git_ref: String,
194    /// The release tag that chose the commit, when one did.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub tag: Option<String>,
197    /// The branch that chose the commit, when the install followed one.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub branch: Option<String>,
200    /// The bundle format the folder holds when it is not a Tuff pack, such
201    /// as `claude-plugin`. Each update imports it the same way (RFC-110 D12).
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub format: Option<String>,
204    /// The entry of a marketplace the pack was chosen from.
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub plugin: Option<String>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct CapabilityLockEntry {
211    #[serde(rename = "type")]
212    pub capability_type: CapabilityType,
213    /// The capability's own version: a declared manifest version, or the
214    /// commit that was installed when nothing better exists. Which one is
215    /// recorded in `version_scheme`, never guessed from the string.
216    pub version: String,
217    #[serde(default)]
218    pub version_scheme: VersionScheme,
219    #[serde(default, skip_serializing_if = "String::is_empty")]
220    pub description: String,
221    /// Where this capability came from. One typed value, so every lifecycle
222    /// verb dispatches on `match` instead of comparing strings.
223    pub source: CapabilitySource,
224    pub targets: BTreeMap<String, TargetLockEntry>,
225    /// Cached from the manifest at install/update time, the same way
226    /// `description` is: after install, only the `files` a manifest declares
227    /// get copied to disk, `tuff.toml` itself does not, so this is the only
228    /// durable record of how a tool is invoked. Consumed by the generated
229    /// capability-index skill (RFC-103 tier 1).
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub implementation: Option<ImplementationConfig>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub parameters: Option<serde_json::Value>,
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub server: Option<McpServerConfig>,
236}
237
238/// What kind of string `CapabilityLockEntry::version` holds (RFC-105 D4).
239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
240#[serde(rename_all = "lowercase")]
241pub enum VersionScheme {
242    /// A release chosen by tag resolution (RFC-101): `version` is the tag's
243    /// semver and `source.tag` names the tag.
244    Semver,
245    /// The version the manifest declares. Says nothing about releases.
246    #[default]
247    Declared,
248    /// A commit SHA: content-exact, semantically silent.
249    Sha,
250}
251
252/// The origin of an installed capability. Internally tagged as `kind` on
253/// the wire, so a lockfile row reads `[capabilities.source] kind = "git"`.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255#[serde(tag = "kind", rename_all = "lowercase")]
256pub enum CapabilitySource {
257    Local(LocalSource),
258    Git(GitSource),
259    Catalog(CatalogSource),
260    Pack(PackProvenance),
261}
262
263impl CapabilitySource {
264    pub fn local(path: impl Into<String>) -> Self {
265        Self::Local(LocalSource { path: path.into() })
266    }
267
268    /// The `kind` string as written to the lockfile.
269    pub fn kind(&self) -> &'static str {
270        match self {
271            Self::Local(_) => "local",
272            Self::Git(_) => "git",
273            Self::Catalog(_) => "catalog",
274            Self::Pack(_) => "pack",
275        }
276    }
277
278    pub fn as_git(&self) -> Option<&GitSource> {
279        match self {
280            Self::Git(git) => Some(git),
281            _ => None,
282        }
283    }
284
285    pub fn as_pack(&self) -> Option<&PackProvenance> {
286        match self {
287            Self::Pack(pack) => Some(pack),
288            _ => None,
289        }
290    }
291
292    /// The local path a capability was installed from, when it has one.
293    pub fn local_path(&self) -> Option<&str> {
294        match self {
295            Self::Local(local) => Some(local.path.as_str()),
296            _ => None,
297        }
298    }
299
300    /// What kind of string `version` is, given where it came from (RFC-101).
301    /// A git install chosen by a release tag is `semver`; one whose version
302    /// is the pinned commit itself is `sha`; anything else, including a git
303    /// install carrying the version its manifest or frontmatter declared,
304    /// is `declared`.
305    pub fn version_scheme_for(&self, version: &str) -> VersionScheme {
306        match self {
307            Self::Git(git) if git.tag.is_some() => VersionScheme::Semver,
308            Self::Git(git) if git.git_ref == version => VersionScheme::Sha,
309            _ => VersionScheme::Declared,
310        }
311    }
312}
313
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct LocalSource {
316    /// Path to the source directory, relative to the lockfile's root when it
317    /// lies inside it, absolute otherwise. Empty for an adopted capability
318    /// whose only copy is the installed tree.
319    #[serde(default)]
320    pub path: String,
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324pub struct GitSource {
325    pub url: String,
326    /// Subdirectory within the repository holding the capability.
327    #[serde(default)]
328    pub path: String,
329    /// The commit that was installed. Always present.
330    #[serde(rename = "ref")]
331    pub git_ref: String,
332    /// The tag that chose `ref`, when one did (RFC-101).
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub tag: Option<String>,
335    /// The range the user asked for, when they did (RFC-101).
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub requested: Option<String>,
338}
339
340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
341pub struct CatalogSource {
342    /// The catalog entry id: a built-in id, or the server's full registry
343    /// name when `registry` is set.
344    pub id: String,
345    /// That entry's version at install time.
346    pub version: String,
347    /// The MCP registry this entry came from, when it did not come from the
348    /// catalog compiled into the binary.
349    ///
350    /// Optional so a built-in install writes exactly what it always wrote:
351    /// an older Tuff reading a newer lockfile ignores the field rather than
352    /// failing to parse the row.
353    #[serde(default, skip_serializing_if = "Option::is_none")]
354    pub registry: Option<String>,
355}
356
357/// Immutable pack release that delivered a capability entry.
358#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
359pub struct PackProvenance {
360    pub name: String,
361    pub version: String,
362    /// Artifact digest, bare lowercase hex. `sha256:` prefixes exist only at
363    /// the OCI boundary.
364    pub digest: String,
365    /// The OCI registry and repository this pack was pulled from
366    /// ("registry/repository", no tag), when known. From schema version 4
367    /// the file records it once, on the pack's entry in `packs`, and the
368    /// reader copies it here so each member still carries it.
369    ///
370    /// `tuff add pack` only ever sees a local artifact file; it has no way to
371    /// know where that file came from unless the caller says so with
372    /// `--reference`. Absent, `tuff outdated` cannot check this capability
373    /// against anything and reports it as such rather than guessing.
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub registry: Option<String>,
376    /// The member's path inside the pack's `sources/` tree.
377    #[serde(default)]
378    pub path: String,
379}
380
381#[derive(Debug, Clone, Serialize, Deserialize)]
382pub struct TargetLockEntry {
383    #[serde(
384        default,
385        rename = "managedHooks",
386        skip_serializing_if = "Vec::is_empty"
387    )]
388    pub managed_hooks: Vec<ManagedHook>,
389    #[serde(
390        default,
391        rename = "managedMcpEntry",
392        skip_serializing_if = "Option::is_none"
393    )]
394    pub managed_mcp_entry: Option<ManagedMcpEntry>,
395    #[serde(
396        default,
397        rename = "managedPermissions",
398        skip_serializing_if = "Vec::is_empty"
399    )]
400    pub managed_permissions: Vec<ManagedPermission>,
401    #[serde(
402        default,
403        rename = "unenforcedRules",
404        skip_serializing_if = "Vec::is_empty"
405    )]
406    pub unenforced_rules: Vec<UnenforcedRule>,
407    #[serde(default)]
408    pub ownership: TargetOwnership,
409    #[serde(default)]
410    pub sha256: String,
411    #[serde(default)]
412    pub installed_path: String,
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct ManagedHook {
417    #[serde(rename = "settingsPath")]
418    pub settings_path: String,
419    pub event: String,
420    #[serde(
421        default,
422        rename = "canonicalEvent",
423        skip_serializing_if = "Option::is_none"
424    )]
425    pub canonical_event: Option<String>,
426    pub command: String,
427    #[serde(rename = "baselineHash")]
428    pub baseline_hash: String,
429}
430
431/// Baseline for one Tuff-managed `mcpServers.<id>` entry (RFC-102 stage b).
432///
433/// MCP config files are shared ground that users hand-edit, so the entry
434/// gets the managed-hook treatment: a content hash recorded at registration
435/// time, compared on every `check`/`list`, never whole-file ownership. The
436/// entry's key is the capability id, so only the file path and hash are
437/// stored.
438#[derive(Debug, Clone, Serialize, Deserialize)]
439pub struct ManagedMcpEntry {
440    #[serde(rename = "configPath")]
441    pub config_path: String,
442    #[serde(rename = "baselineHash")]
443    pub baseline_hash: String,
444}
445
446/// A native permission rule a policy compiled into a harness settings file,
447/// such as `Bash(git push --force *)` in `.claude/settings.json`'s
448/// `permissions.deny`. The rule string is its own identity: it is present
449/// in that list or it is not.
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
451pub struct ManagedPermission {
452    #[serde(rename = "settingsPath")]
453    pub settings_path: String,
454    /// The list the rule sits in: `deny` or `ask`.
455    pub list: String,
456    pub rule: String,
457}
458
459/// A policy rule the agent does not enforce, recorded when the policy was
460/// installed with `--accept-unenforced` (RFC-107 D6). `tuff check` reports
461/// each one, and `tuff check --strict` fails while any are recorded.
462#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
463pub struct UnenforcedRule {
464    /// One-based position of the rule in the policy.
465    pub rule: usize,
466    /// The rule as `tuff add` describes it, such as `deny read ".env"`.
467    pub description: String,
468    /// Why the agent does not enforce it.
469    pub reason: String,
470}
471
472/// Hash an MCP entry value exactly as `managed_mcp_entry_status` will when
473/// it re-reads the file: canonical `serde_json` bytes, so on-disk pretty-
474/// printing never matters.
475pub fn managed_mcp_entry_baseline(entry: &serde_json::Value) -> Result<String> {
476    Ok(hash_bytes(&serde_json::to_vec(entry)?))
477}
478
479/// `"clean"`, `"modified"`, or `"missing"` for a managed MCP entry.
480pub fn managed_mcp_entry_status(
481    repo_root: &Path,
482    capability_id: &str,
483    entry: &ManagedMcpEntry,
484) -> &'static str {
485    let path = repo_root.join(&entry.config_path);
486    if crate::mcp::is_toml(&path) {
487        return match crate::mcp::toml_entry(&path, capability_id) {
488            Ok(Some(current)) => match serde_json::to_vec(&current) {
489                Ok(bytes) if hash_bytes(&bytes) == entry.baseline_hash => "clean",
490                _ => "modified",
491            },
492            Ok(None) => "missing",
493            Err(_) => "modified",
494        };
495    }
496    let servers_key = crate::mcp::servers_key(&path);
497    let Ok(raw) = std::fs::read_to_string(path) else {
498        return "missing";
499    };
500    let Ok(config): std::result::Result<serde_json::Value, _> = serde_json::from_str(&raw) else {
501        return "modified";
502    };
503    let Some(current) = config
504        .get(servers_key)
505        .and_then(|servers| servers.get(capability_id))
506    else {
507        return "missing";
508    };
509    match serde_json::to_vec(current) {
510        Ok(bytes) if hash_bytes(&bytes) == entry.baseline_hash => "clean",
511        _ => "modified",
512    }
513}
514
515pub fn managed_hooks_from_fragment(
516    repo_root: &Path,
517    settings_path: &str,
518    fragment: &serde_json::Value,
519) -> Result<Vec<ManagedHook>> {
520    managed_hooks_from_fragment_with_canonical(repo_root, settings_path, fragment, None)
521}
522
523pub fn managed_hooks_from_fragment_with_canonical(
524    _repo_root: &Path,
525    settings_path: &str,
526    fragment: &serde_json::Value,
527    canonical_event: Option<&str>,
528) -> Result<Vec<ManagedHook>> {
529    let mut managed = Vec::new();
530    let Some(events) = fragment.get("hooks").and_then(serde_json::Value::as_object) else {
531        return Ok(managed);
532    };
533
534    for (event, groups) in events {
535        let Some(groups) = groups.as_array() else {
536            continue;
537        };
538        for group in groups {
539            let hooks = group
540                .get("hooks")
541                .and_then(serde_json::Value::as_array)
542                .map_or_else(|| vec![group], |hooks| hooks.iter().collect());
543            for hook in hooks {
544                let Some(command) = hook.get("command").and_then(serde_json::Value::as_str) else {
545                    continue;
546                };
547                let baseline = serde_json::to_vec(hook)?;
548                managed.push(ManagedHook {
549                    settings_path: settings_path.to_string(),
550                    event: event.clone(),
551                    canonical_event: canonical_event.map(str::to_owned),
552                    command: command.to_string(),
553                    baseline_hash: hash_bytes(&baseline),
554                });
555            }
556        }
557    }
558    Ok(managed)
559}
560
561pub fn managed_hook_status(repo_root: &Path, hook: &ManagedHook) -> &'static str {
562    let path = repo_root.join(&hook.settings_path);
563    let Ok(settings) = std::fs::read_to_string(path) else {
564        return "missing";
565    };
566    let Ok(settings): std::result::Result<serde_json::Value, _> = serde_json::from_str(&settings)
567    else {
568        return "modified";
569    };
570    let Some(groups) = settings
571        .get("hooks")
572        .and_then(|hooks| hooks.get(&hook.event))
573        .and_then(serde_json::Value::as_array)
574    else {
575        return "missing";
576    };
577
578    for group in groups {
579        let entries = group
580            .get("hooks")
581            .and_then(serde_json::Value::as_array)
582            .map_or_else(|| vec![group], |entries| entries.iter().collect());
583        for entry in entries {
584            if entry.get("command").and_then(serde_json::Value::as_str)
585                == Some(hook.command.as_str())
586            {
587                let Ok(content) = serde_json::to_vec(entry) else {
588                    return "modified";
589                };
590                return if hash_bytes(&content) == hook.baseline_hash {
591                    "clean"
592                } else {
593                    "modified"
594                };
595            }
596        }
597    }
598    "missing"
599}
600
601#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
602#[serde(rename_all = "lowercase")]
603pub enum TargetOwnership {
604    #[default]
605    Generated,
606    Imported,
607}
608
609/// The project-scope lockfile. Never falls through to the global one: the
610/// caller resolved a scope and this is the file for it (RFC-105 D3).
611pub fn project_lockfile(repo_root: &Path) -> PathBuf {
612    repo_root.join("tuff.lock")
613}
614
615/// The lockfile for a resolved scope: `<root>/tuff.lock` for a project,
616/// the XDG state file for the global scope (where `scope_root` is the home
617/// directory). The scope is always passed, never inferred from the path.
618pub fn scoped_lockfile(scope_root: &Path, scope: crate::resolver::Scope) -> PathBuf {
619    match scope {
620        crate::resolver::Scope::Project => project_lockfile(scope_root),
621        crate::resolver::Scope::Global => crate::paths::global_lockfile(scope_root),
622    }
623}
624
625pub fn require_scoped_lockfile(
626    scope_root: &Path,
627    scope: crate::resolver::Scope,
628) -> Result<Lockfile> {
629    read_lockfile_at(&scoped_lockfile(scope_root, scope))
630}
631
632pub fn write_scoped_lockfile(
633    scope_root: &Path,
634    scope: crate::resolver::Scope,
635    lockfile: &Lockfile,
636) -> Result<()> {
637    write_lockfile_at(&scoped_lockfile(scope_root, scope), lockfile)
638}
639
640pub fn init_lockfile(repo_root: &Path) -> Result<PathBuf> {
641    let lock_path = project_lockfile(repo_root);
642    init_lockfile_at(&lock_path)?;
643    Ok(lock_path)
644}
645
646pub fn init_lockfile_at(lock_path: &Path) -> Result<()> {
647    if !lock_path.exists() {
648        write_lockfile_at(lock_path, &Lockfile::empty())?;
649    }
650    Ok(())
651}
652
653pub fn require_lockfile(repo_root: &Path) -> Result<Lockfile> {
654    read_lockfile_at(&project_lockfile(repo_root))
655}
656
657/// Read a lockfile that may legitimately not exist.
658///
659/// `Ok(None)` means "no lockfile here", which is normal for the global
660/// scope on a machine that has never used `--global`. Anything else, in
661/// particular a corrupt or too-new file, is an error: reporting it as
662/// "nothing installed" would be a confident wrong answer.
663pub fn read_optional_lockfile(path: &Path) -> Result<Option<Lockfile>> {
664    match read_lockfile_at(path) {
665        Ok(lockfile) => Ok(Some(lockfile)),
666        Err(error) if error.kind() == crate::error::ErrorKind::NotFound => Ok(None),
667        Err(error) => Err(error),
668    }
669}
670
671/// Read a lockfile of any supported schema version into the current model.
672///
673/// The version is read before anything else is deserialised, so a file from
674/// a newer tuff fails with a message about versions rather than a shape
675/// error naming some field the reader has never heard of.
676pub fn read_lockfile_at(path: &Path) -> Result<Lockfile> {
677    if !path.exists() {
678        let parent = path.parent().unwrap_or(Path::new("."));
679        return Err(TuffError::not_found(format!(
680            "{} is missing",
681            parent
682                .join(path.file_name().unwrap_or(OsStr::new("tuff.lock")))
683                .display()
684        ))
685        .with_hint("run 'tuff init' first"));
686    }
687    let raw = std::fs::read_to_string(path)?;
688    let format = WireFormat::detect(&raw);
689    let version = peek_version(&raw, format, path)?;
690    if version > LOCKFILE_VERSION {
691        return Err(TuffError::unsupported(format!(
692            "unsupported lockfile version: {version} ({} was written by a newer tuff; this tuff {} reads versions {OLDEST_READABLE_LOCKFILE_VERSION} to {LOCKFILE_VERSION}, upgrade tuff)",
693            path.display(),
694            env!("CARGO_PKG_VERSION")
695        )));
696    }
697    let expected = WireFormat::for_version(version);
698    if format != expected {
699        return Err(TuffError::corrupt(format!(
700            "{} declares lockfile version {version}, which is {expected}, but the file is {format}",
701            path.display()
702        )));
703    }
704    let (rows, wire_packs): (Vec<Row>, BTreeMap<String, WirePack>) = match version {
705        1 => (read_v1_rows(&raw)?, BTreeMap::new()),
706        2 => (read_v2_rows(&raw)?, BTreeMap::new()),
707        _ => read_json_rows(&raw)?,
708    };
709    let mut capabilities: BTreeMap<String, CapabilityLockEntry> = BTreeMap::new();
710    for row in rows {
711        let Row {
712            name,
713            target,
714            target_entry,
715            entry,
716        } = row;
717        // A lockfile can be committed to someone else's repository, and
718        // every command that deletes or rewrites a capability builds its
719        // paths from this name. Refuse the file rather than act on it.
720        crate::manifest::validate_capability_id(&name).map_err(|_| {
721            TuffError::corrupt(format!(
722                "{} records a capability named '{}', which is not a relative path of plain names",
723                path.display(),
724                name.escape_debug()
725            ))
726            .with_hint("remove that entry from the lockfile by hand; Tuff will not act on it")
727        })?;
728        match capabilities.entry(name) {
729            std::collections::btree_map::Entry::Occupied(mut existing) => {
730                existing.get_mut().targets.insert(target, target_entry);
731            }
732            std::collections::btree_map::Entry::Vacant(slot) => {
733                let mut entry = entry;
734                entry.targets.insert(target, target_entry);
735                slot.insert(entry);
736            }
737        }
738    }
739    let packs = wire_packs
740        .into_iter()
741        .map(|(name, pack)| {
742            (
743                name,
744                PackLockEntry {
745                    version: pack.version,
746                    digest: pack.digest,
747                    source: pack.source,
748                    x: pack.x,
749                },
750            )
751        })
752        .collect::<BTreeMap<_, _>>();
753    // Members are the record of membership; an entry is the record of the
754    // pack's source. A member naming a pack must agree with its entry, and
755    // carries the entry's registry the way version 3 members did.
756    for (id, entry) in &mut capabilities {
757        let CapabilitySource::Pack(provenance) = &mut entry.source else {
758            continue;
759        };
760        let Some(pack) = packs.get(&provenance.name) else {
761            continue;
762        };
763        if pack.version != provenance.version || pack.digest != provenance.digest {
764            return Err(TuffError::corrupt(format!(
765                "{} records '{id}' as part of pack {} {}, but the pack's entry says {}",
766                path.display(),
767                provenance.name,
768                provenance.version,
769                pack.version
770            )));
771        }
772        if let Some(registry) = pack.source.registry() {
773            provenance.registry = Some(registry.to_string());
774        }
775    }
776    Ok(Lockfile {
777        version,
778        capabilities,
779        packs,
780    })
781}
782
783/// One wire row folded to its capability entry plus its target.
784struct Row {
785    name: String,
786    target: String,
787    target_entry: TargetLockEntry,
788    entry: CapabilityLockEntry,
789}
790
791fn peek_version(raw: &str, format: WireFormat, path: &Path) -> Result<u8> {
792    #[derive(Deserialize)]
793    struct VersionOnly {
794        version: Option<u8>,
795    }
796    let invalid = |message: String| {
797        TuffError::corrupt(format!(
798            "{} is not a valid lockfile: {message}",
799            path.display()
800        ))
801    };
802    let peek: VersionOnly = match format {
803        WireFormat::Toml => {
804            toml::from_str(raw).map_err(|error| invalid(error.message().to_string()))?
805        }
806        WireFormat::Json => {
807            serde_json::from_str(raw).map_err(|error| invalid(error.to_string()))?
808        }
809    };
810    match peek.version {
811        Some(version) if version >= OLDEST_READABLE_LOCKFILE_VERSION => Ok(version),
812        Some(version) => Err(TuffError::unsupported(format!(
813            "unsupported lockfile version: {version} ({} predates every schema this tuff reads)",
814            path.display()
815        ))),
816        None => Err(TuffError::corrupt(format!(
817            "{} has no version field; it is not a Tuff lockfile or it is corrupt",
818            path.display()
819        ))),
820    }
821}
822
823/// Schema version 1, read for migration only (RFC-105 D5). Never written.
824fn read_v1_rows(raw: &str) -> Result<Vec<Row>> {
825    let wire: WireLockfileV1 = toml::from_str(raw)
826        .map_err(|error| TuffError::corrupt(format!("invalid version 1 lockfile: {error}")))?;
827    Ok(wire
828        .capabilities
829        .into_iter()
830        .map(|item| {
831            let source = match item.pack {
832                // A pack member was written as "local" with an empty path
833                // plus a pack table; the pack is the real origin. The member
834                // path inside the pack was not recorded in v1, and the member
835                // id is what `tuff add pack` used, so it is the best backfill.
836                Some(pack) => CapabilitySource::Pack(PackProvenance {
837                    name: pack.name,
838                    version: pack.version,
839                    digest: pack.digest,
840                    registry: pack.registry,
841                    path: item.name.clone(),
842                }),
843                None => match item.source.as_str() {
844                    "git" => CapabilitySource::Git(GitSource {
845                        url: item.repository,
846                        path: item.source_path,
847                        git_ref: item.resolved_ref,
848                        tag: None,
849                        requested: None,
850                    }),
851                    // A v1 lockfile predates registry installs, so every
852                    // catalog row in one came from the built-in catalog.
853                    "catalog" => CapabilitySource::Catalog(CatalogSource {
854                        id: item.source_path,
855                        version: item.resolved_ref,
856                        registry: None,
857                    }),
858                    // The generated capability index wrote a sentinel path
859                    // in v1; it has no source tree and v2 says so plainly.
860                    _ if item.source_path == "<generated>" => CapabilitySource::local(""),
861                    _ => CapabilitySource::local(item.source_path),
862                },
863            };
864            let version_scheme = source.version_scheme_for(&item.version);
865            Row {
866                name: item.name,
867                target: item.target,
868                target_entry: TargetLockEntry {
869                    managed_hooks: item.managed_hooks,
870                    managed_mcp_entry: item.managed_mcp_entry,
871                    managed_permissions: Vec::new(),
872                    unenforced_rules: Vec::new(),
873                    ownership: item.ownership,
874                    sha256: item.sha256,
875                    installed_path: item.installed_path,
876                },
877                entry: CapabilityLockEntry {
878                    capability_type: item.capability_type,
879                    version: item.version,
880                    version_scheme,
881                    description: item.description,
882                    source,
883                    targets: BTreeMap::new(),
884                    implementation: item.implementation,
885                    parameters: item.parameters,
886                    server: item.server,
887                },
888            }
889        })
890        .collect())
891}
892
893/// Schema version 2: the current rows, TOML-encoded. Read for migration
894/// only; never written.
895fn read_v2_rows(raw: &str) -> Result<Vec<Row>> {
896    let wire: WireLockfile = toml::from_str(raw).map_err(|error| invalid_lockfile(&error))?;
897    Ok(rows_from_wire(wire))
898}
899
900/// Schema versions 3 and 4: the current rows, JSON-encoded, and from
901/// version 4 the packs section.
902fn read_json_rows(raw: &str) -> Result<(Vec<Row>, BTreeMap<String, WirePack>)> {
903    let mut wire: WireLockfile =
904        serde_json::from_str(raw).map_err(|error| invalid_lockfile(&error))?;
905    let packs = std::mem::take(&mut wire.packs);
906    Ok((rows_from_wire(wire), packs))
907}
908
909/// A lockfile that does not parse, with a pointer for the one known cause:
910/// an entry of a capability type Tuff no longer has.
911fn invalid_lockfile(error: &dyn std::fmt::Display) -> TuffError {
912    let message = error.to_string();
913    let corrupt = TuffError::corrupt(format!("invalid lockfile: {message}"));
914    if message.contains("unknown variant `workflow`") {
915        corrupt.with_hint(
916            "Tuff no longer has workflow capabilities; remove the workflow entries from tuff.lock and their workflows/ folders",
917        )
918    } else {
919        corrupt
920    }
921}
922
923fn rows_from_wire(wire: WireLockfile) -> Vec<Row> {
924    wire.capabilities
925        .into_iter()
926        .map(|item| Row {
927            name: item.name,
928            target: item.target,
929            target_entry: TargetLockEntry {
930                managed_hooks: item.managed_hooks,
931                managed_mcp_entry: item.managed_mcp_entry,
932                managed_permissions: item.managed_permissions,
933                unenforced_rules: item.unenforced_rules,
934                ownership: item.ownership,
935                sha256: item.sha256,
936                installed_path: item.installed_path,
937            },
938            entry: CapabilityLockEntry {
939                capability_type: item.capability_type,
940                version: item.version,
941                version_scheme: item.version_scheme,
942                description: item.description,
943                source: item.source,
944                targets: BTreeMap::new(),
945                implementation: item.implementation,
946                parameters: item.parameters,
947                server: item.server,
948            },
949        })
950        .collect()
951}
952
953pub fn write_lockfile(repo_root: &Path, lockfile: &Lockfile) -> Result<()> {
954    write_lockfile_at(&project_lockfile(repo_root), lockfile)
955}
956
957pub fn write_lockfile_at(path: &Path, lockfile: &Lockfile) -> Result<()> {
958    if let Some(parent) = path.parent() {
959        std::fs::create_dir_all(parent)?;
960    }
961    std::fs::write(path, render_lockfile(lockfile)?)?;
962    Ok(())
963}
964
965/// The bytes `write_lockfile_at` writes: the current schema, whatever
966/// schema the lockfile was read from.
967pub fn render_lockfile(lockfile: &Lockfile) -> Result<String> {
968    let packs = lockfile.normalized_packs();
969    let mut capabilities = Vec::new();
970    for (name, entry) in &lockfile.capabilities {
971        // The pack's entry holds its registry; a member row names the pack.
972        let mut source = entry.source.clone();
973        if let CapabilitySource::Pack(provenance) = &mut source {
974            provenance.registry = None;
975        }
976        for (target, target_entry) in &entry.targets {
977            capabilities.push(WireCapability {
978                name: name.clone(),
979                capability_type: entry.capability_type,
980                version: entry.version.clone(),
981                version_scheme: entry.version_scheme,
982                description: entry.description.clone(),
983                target: target.clone(),
984                installed_path: target_entry.installed_path.clone(),
985                sha256: target_entry.sha256.clone(),
986                ownership: target_entry.ownership,
987                source: source.clone(),
988                managed_hooks: target_entry.managed_hooks.clone(),
989                managed_mcp_entry: target_entry.managed_mcp_entry.clone(),
990                managed_permissions: target_entry.managed_permissions.clone(),
991                unenforced_rules: target_entry.unenforced_rules.clone(),
992                implementation: entry.implementation.clone(),
993                parameters: entry.parameters.clone(),
994                server: entry.server.clone(),
995            });
996        }
997    }
998    capabilities.sort_by(|a, b| {
999        a.name
1000            .cmp(&b.name)
1001            .then_with(|| a.capability_type.as_str().cmp(b.capability_type.as_str()))
1002            .then_with(|| a.target.cmp(&b.target))
1003            .then_with(|| a.installed_path.cmp(&b.installed_path))
1004    });
1005    let packs = packs
1006        .into_iter()
1007        .map(|(name, pack)| {
1008            let members = lockfile.pack_members(&name);
1009            (
1010                name,
1011                WirePack {
1012                    version: pack.version,
1013                    digest: pack.digest,
1014                    source: pack.source,
1015                    members,
1016                    x: pack.x,
1017                },
1018            )
1019        })
1020        .collect();
1021    let wire = WireLockfile {
1022        version: LOCKFILE_VERSION,
1023        packs,
1024        capabilities,
1025    };
1026    // `to_string_pretty` is the `JSON.stringify(value, null, 2)` layout;
1027    // the trailing newline is the one thing it leaves out. See
1028    // `LOCKFILE_VERSION` for why this layout and no other.
1029    let mut content = serde_json::to_string_pretty(&wire)?;
1030    content.push('\n');
1031    Ok(content)
1032}
1033
1034/// The current rows (RFC-105 D1): one per capability per target. Written
1035/// as JSON since schema version 3; version 2 was the same rows in TOML,
1036/// which is why scalars come first and tables after, so that serializer
1037/// never had to emit a value beneath a table. JSON has no such constraint,
1038/// but the order is the field order readers of the file expect.
1039#[derive(Debug, Serialize, Deserialize)]
1040struct WireLockfile {
1041    version: u8,
1042    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1043    packs: BTreeMap<String, WirePack>,
1044    capabilities: Vec<WireCapability>,
1045}
1046
1047/// A pack's entry as written. `members` is derived from the capability
1048/// rows on every write so a reader sees the pack's contents in one place;
1049/// the reader takes membership from the rows.
1050#[derive(Debug, Serialize, Deserialize)]
1051struct WirePack {
1052    version: String,
1053    digest: String,
1054    source: PackSource,
1055    #[serde(default)]
1056    members: Vec<String>,
1057    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1058    x: crate::host::HostTablesJson,
1059}
1060
1061#[derive(Debug, Serialize, Deserialize)]
1062struct WireCapability {
1063    name: String,
1064    #[serde(rename = "type")]
1065    capability_type: CapabilityType,
1066    #[serde(default)]
1067    version: String,
1068    #[serde(default)]
1069    version_scheme: VersionScheme,
1070    #[serde(default, skip_serializing_if = "String::is_empty")]
1071    description: String,
1072    target: String,
1073    installed_path: String,
1074    sha256: String,
1075    #[serde(default)]
1076    ownership: TargetOwnership,
1077    source: CapabilitySource,
1078    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1079    managed_hooks: Vec<ManagedHook>,
1080    #[serde(default, skip_serializing_if = "Option::is_none")]
1081    managed_mcp_entry: Option<ManagedMcpEntry>,
1082    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1083    managed_permissions: Vec<ManagedPermission>,
1084    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1085    unenforced_rules: Vec<UnenforcedRule>,
1086    #[serde(default, skip_serializing_if = "Option::is_none")]
1087    implementation: Option<ImplementationConfig>,
1088    #[serde(default, skip_serializing_if = "Option::is_none")]
1089    parameters: Option<serde_json::Value>,
1090    #[serde(default, skip_serializing_if = "Option::is_none")]
1091    server: Option<McpServerConfig>,
1092}
1093
1094/// Schema version 1 as tuff 0.1.x wrote it. Read-only; see `read_v1_rows`.
1095#[derive(Debug, Deserialize)]
1096struct WireLockfileV1 {
1097    #[allow(dead_code)]
1098    version: u8,
1099    capabilities: Vec<WireCapabilityV1>,
1100}
1101
1102#[derive(Debug, Deserialize)]
1103struct WireCapabilityV1 {
1104    name: String,
1105    #[serde(rename = "type")]
1106    capability_type: CapabilityType,
1107    source: String,
1108    #[serde(default)]
1109    repository: String,
1110    #[serde(default)]
1111    source_path: String,
1112    #[serde(default)]
1113    resolved_ref: String,
1114    sha256: String,
1115    target: String,
1116    installed_path: String,
1117    #[serde(default)]
1118    version: String,
1119    #[serde(default)]
1120    description: String,
1121    #[serde(default)]
1122    ownership: TargetOwnership,
1123    #[serde(default)]
1124    managed_hooks: Vec<ManagedHook>,
1125    #[serde(default)]
1126    managed_mcp_entry: Option<ManagedMcpEntry>,
1127    #[serde(default)]
1128    pack: Option<PackProvenanceV1>,
1129    #[serde(default)]
1130    implementation: Option<ImplementationConfig>,
1131    #[serde(default)]
1132    parameters: Option<serde_json::Value>,
1133    #[serde(default)]
1134    server: Option<McpServerConfig>,
1135}
1136
1137#[derive(Debug, Deserialize)]
1138struct PackProvenanceV1 {
1139    name: String,
1140    version: String,
1141    digest: String,
1142    #[serde(default)]
1143    registry: Option<String>,
1144}
1145
1146pub fn hash_bytes(content: &[u8]) -> String {
1147    let mut hasher = Sha256::new();
1148    hasher.update(content);
1149    format!("{:x}", hasher.finalize())
1150}
1151
1152pub fn relative_or_absolute_fs(path: &Path, repo_root: &Path) -> String {
1153    path.strip_prefix(repo_root)
1154        .map(|relative| relative.to_string_lossy().replace('\\', "/"))
1155        .unwrap_or_else(|_| path.to_string_lossy().to_string())
1156}
1157
1158pub fn absolutize(repo_root: &Path, path: &Path) -> PathBuf {
1159    if path.is_absolute() {
1160        path.to_path_buf()
1161    } else {
1162        repo_root.join(path)
1163    }
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use std::fs;
1170    use tempfile::TempDir;
1171
1172    #[test]
1173    fn init_lockfile_at_creates_new_file() {
1174        let tmp = TempDir::new().unwrap();
1175        let path = tmp.path().join("tuff.lock");
1176        init_lockfile_at(&path).unwrap();
1177        assert!(path.exists());
1178
1179        let lf = read_lockfile_at(&path).unwrap();
1180        assert_eq!(lf.version, LOCKFILE_VERSION);
1181        assert!(lf.capabilities.is_empty());
1182    }
1183
1184    #[test]
1185    fn read_lockfile_at_rejects_missing() {
1186        let tmp = TempDir::new().unwrap();
1187        let path = tmp.path().join("tuff.lock");
1188        assert!(read_lockfile_at(&path).is_err());
1189    }
1190
1191    #[test]
1192    fn read_lockfile_at_rejects_a_newer_schema_in_either_encoding() {
1193        let tmp = TempDir::new().unwrap();
1194        let path = tmp.path().join("tuff.lock");
1195        for raw in [
1196            "{\n  \"version\": 5,\n  \"capabilities\": []\n}\n",
1197            "version = 5\ncapabilities = []\n",
1198        ] {
1199            fs::write(&path, raw).unwrap();
1200            let error = read_lockfile_at(&path).unwrap_err().to_string();
1201            assert!(error.contains("unsupported lockfile version: 5"), "{error}");
1202        }
1203    }
1204
1205    #[test]
1206    fn a_lockfile_in_the_wrong_encoding_for_its_version_is_corrupt() {
1207        // Version 3 is JSON and versions 1 and 2 are TOML; a file claiming
1208        // one in the syntax of the other was rewritten by something that
1209        // is not tuff, and the message says which way round it is.
1210        let tmp = TempDir::new().unwrap();
1211        let path = tmp.path().join("tuff.lock");
1212        fs::write(&path, "version = 3\ncapabilities = []\n").unwrap();
1213        let error = read_lockfile_at(&path).unwrap_err().to_string();
1214        assert!(
1215            error.contains("declares lockfile version 3, which is JSON, but the file is TOML"),
1216            "{error}"
1217        );
1218        fs::write(&path, "{\"version\": 2, \"capabilities\": []}\n").unwrap();
1219        let error = read_lockfile_at(&path).unwrap_err().to_string();
1220        assert!(
1221            error.contains("declares lockfile version 2, which is TOML, but the file is JSON"),
1222            "{error}"
1223        );
1224    }
1225
1226    #[test]
1227    fn an_empty_lockfile_is_canonical_json() {
1228        let tmp = TempDir::new().unwrap();
1229        let path = tmp.path().join("tuff.lock");
1230        init_lockfile_at(&path).unwrap();
1231        assert_eq!(
1232            fs::read_to_string(&path).unwrap(),
1233            "{\n  \"version\": 4,\n  \"capabilities\": []\n}\n"
1234        );
1235    }
1236
1237    #[test]
1238    fn write_and_read_roundtrip() {
1239        let tmp = TempDir::new().unwrap();
1240        let path = tmp.path().join("tuff.lock");
1241        let mut lf = Lockfile::empty();
1242        lf.capabilities.insert(
1243            "test".into(),
1244            CapabilityLockEntry {
1245                capability_type: CapabilityType::Skill,
1246                version: "1.0".into(),
1247                version_scheme: VersionScheme::Declared,
1248                description: "test skill".into(),
1249                source: CapabilitySource::local(""),
1250                targets: BTreeMap::from([(
1251                    "open-agents".into(),
1252                    TargetLockEntry {
1253                        managed_hooks: Vec::new(),
1254                        managed_mcp_entry: None,
1255                        managed_permissions: Vec::new(),
1256                        unenforced_rules: Vec::new(),
1257                        ownership: TargetOwnership::Generated,
1258                        sha256: hash_bytes(b"content"),
1259                        installed_path: ".agents/skills/test".into(),
1260                    },
1261                )]),
1262                implementation: None,
1263                parameters: None,
1264                server: None,
1265            },
1266        );
1267        write_lockfile_at(&path, &lf).unwrap();
1268        let read = read_lockfile_at(&path).unwrap();
1269        assert_eq!(read.capabilities.len(), 1);
1270        assert_eq!(read.version, LOCKFILE_VERSION);
1271
1272        // The layout is the one `JSON.stringify(value, null, 2)` produces:
1273        // two-space indentation, nothing trailing, one newline at the end.
1274        let written = fs::read_to_string(&path).unwrap();
1275        assert!(
1276            written.starts_with(
1277                "{\n  \"version\": 4,\n  \"capabilities\": [\n    {\n      \"name\": \"test\",\n"
1278            ),
1279            "{written}"
1280        );
1281        assert!(written.ends_with("\n  ]\n}\n"), "{written}");
1282        for line in written.lines() {
1283            let indent = line.len() - line.trim_start_matches(' ').len();
1284            assert_eq!(indent % 2, 0, "odd indentation: {line:?}");
1285            assert!(!line.contains('\t'), "tab in {line:?}");
1286            assert_eq!(line, line.trim_end(), "trailing whitespace in {line:?}");
1287        }
1288        serde_json::from_str::<serde_json::Value>(&written).unwrap();
1289    }
1290
1291    #[test]
1292    fn missing_target_ownership_defaults_to_generated() {
1293        let tmp = TempDir::new().unwrap();
1294        let path = tmp.path().join("tuff.lock");
1295        fs::write(&path, "version = 1\ncapabilities = []\n").unwrap();
1296        let read = read_lockfile_at(&path).unwrap();
1297        assert!(read.capabilities.is_empty());
1298    }
1299
1300    #[test]
1301    fn hash_bytes_produces_consistent_output() {
1302        let h1 = hash_bytes(b"hello");
1303        let h2 = hash_bytes(b"hello");
1304        assert_eq!(h1, h2);
1305        assert_eq!(h1.len(), 64);
1306        assert_ne!(h1, hash_bytes(b"world"));
1307    }
1308
1309    #[test]
1310    fn a_version_1_lockfile_migrates_every_source_kind() {
1311        let tmp = TempDir::new().unwrap();
1312        let path = tmp.path().join("tuff.lock");
1313        fs::write(
1314            &path,
1315            r#"version = 1
1316
1317[[capabilities]]
1318name = "git-skill"
1319type = "skill"
1320source = "git"
1321repository = "https://example.com/skills.git"
1322source_path = "skills/git-skill"
1323resolved_ref = "9b9c499"
1324sha256 = "aa"
1325target = "open-agents"
1326installed_path = ".agents/skills/git-skill"
1327version = "9b9c499"
1328
1329[[capabilities]]
1330name = "memory"
1331type = "mcp-server"
1332source = "catalog"
1333repository = "builtin"
1334source_path = "memory"
1335resolved_ref = "1.0.0"
1336sha256 = "bb"
1337target = "open-agents"
1338installed_path = ".agents/mcp-servers/memory"
1339version = "1.0.0"
1340
1341[[capabilities]]
1342name = "pack-skill"
1343type = "skill"
1344source = "local"
1345source_path = ""
1346resolved_ref = ""
1347sha256 = "cc"
1348target = "open-agents"
1349installed_path = ".agents/skills/pack-skill"
1350version = "1.5.0"
1351
1352[capabilities.pack]
1353name = "com.acme/fixture"
1354version = "1.0.0"
1355digest = "dd"
1356registry = "ghcr.io/acme/fixture"
1357
1358[[capabilities]]
1359name = "local-skill"
1360type = "skill"
1361source = "local"
1362source_path = "sources/local-skill"
1363resolved_ref = ""
1364sha256 = "ee"
1365target = "open-agents"
1366installed_path = ".agents/skills/local-skill"
1367version = "1.0.0"
1368"#,
1369        )
1370        .unwrap();
1371
1372        let lf = read_lockfile_at(&path).unwrap();
1373        assert_eq!(lf.version, 1, "the version read is reported, not rewritten");
1374        assert_eq!(
1375            lf.capabilities["git-skill"].source,
1376            CapabilitySource::Git(GitSource {
1377                url: "https://example.com/skills.git".into(),
1378                path: "skills/git-skill".into(),
1379                git_ref: "9b9c499".into(),
1380                tag: None,
1381                requested: None,
1382            })
1383        );
1384        assert_eq!(
1385            lf.capabilities["git-skill"].version_scheme,
1386            VersionScheme::Sha
1387        );
1388        assert_eq!(
1389            lf.capabilities["memory"].source,
1390            CapabilitySource::Catalog(CatalogSource {
1391                id: "memory".into(),
1392                version: "1.0.0".into(),
1393                registry: None,
1394            })
1395        );
1396        assert_eq!(
1397            lf.capabilities["pack-skill"].source,
1398            CapabilitySource::Pack(PackProvenance {
1399                name: "com.acme/fixture".into(),
1400                version: "1.0.0".into(),
1401                digest: "dd".into(),
1402                registry: Some("ghcr.io/acme/fixture".into()),
1403                path: "pack-skill".into(),
1404            })
1405        );
1406        assert_eq!(
1407            lf.capabilities["local-skill"].source,
1408            CapabilitySource::local("sources/local-skill")
1409        );
1410        assert_eq!(
1411            lf.capabilities["local-skill"].version_scheme,
1412            VersionScheme::Declared
1413        );
1414
1415        // Writing produces v4, and v4 round-trips byte for byte. The pack's
1416        // registry moves to its entry in `packs` and comes back on read.
1417        write_lockfile_at(&path, &lf).unwrap();
1418        let written = fs::read_to_string(&path).unwrap();
1419        assert!(
1420            written.starts_with("{\n  \"version\": 4,\n  \"packs\": {\n"),
1421            "{written}"
1422        );
1423        assert!(written.contains("\"kind\": \"pack\""), "{written}");
1424        assert!(written.contains("\"kind\": \"artifact\""), "{written}");
1425        assert_eq!(
1426            written.matches("ghcr.io/acme/fixture").count(),
1427            1,
1428            "{written}"
1429        );
1430        assert!(!written.contains("resolved_ref"));
1431        let again = read_lockfile_at(&path).unwrap();
1432        assert_eq!(again.version, 4);
1433        assert_eq!(
1434            again.capabilities["pack-skill"].source,
1435            lf.capabilities["pack-skill"].source
1436        );
1437        write_lockfile_at(&path, &again).unwrap();
1438        assert_eq!(fs::read_to_string(&path).unwrap(), written);
1439    }
1440
1441    #[test]
1442    fn a_version_2_lockfile_is_read_as_is_and_written_as_the_current_version() {
1443        let tmp = TempDir::new().unwrap();
1444        let path = tmp.path().join("tuff.lock");
1445        fs::write(
1446            &path,
1447            r#"version = 2
1448
1449[[capabilities]]
1450name = "git-skill"
1451type = "skill"
1452version = "1.4.0"
1453version_scheme = "semver"
1454target = "open-agents"
1455installed_path = ".agents/skills/git-skill"
1456sha256 = "aa"
1457ownership = "generated"
1458
1459[capabilities.source]
1460kind = "git"
1461url = "https://example.com/skills.git"
1462path = "skills/git-skill"
1463ref = "9b9c499"
1464tag = "v1.4.0"
1465requested = "^1.2"
1466"#,
1467        )
1468        .unwrap();
1469        let lf = read_lockfile_at(&path).unwrap();
1470        assert_eq!(lf.version, 2, "the version read is reported, not rewritten");
1471        let entry = &lf.capabilities["git-skill"];
1472        assert_eq!(entry.version_scheme, VersionScheme::Semver);
1473        assert_eq!(
1474            entry.source,
1475            CapabilitySource::Git(GitSource {
1476                url: "https://example.com/skills.git".into(),
1477                path: "skills/git-skill".into(),
1478                git_ref: "9b9c499".into(),
1479                tag: Some("v1.4.0".into()),
1480                requested: Some("^1.2".into()),
1481            })
1482        );
1483
1484        write_lockfile_at(&path, &lf).unwrap();
1485        let written = fs::read_to_string(&path).unwrap();
1486        assert!(written.starts_with("{\n  \"version\": 4,\n"), "{written}");
1487        assert!(written.contains("\"requested\": \"^1.2\""), "{written}");
1488        let again = read_lockfile_at(&path).unwrap();
1489        assert_eq!(again.version, 4);
1490        assert_eq!(again.capabilities["git-skill"].source, entry.source);
1491    }
1492
1493    fn pack_member(pack: &str, version: &str) -> CapabilityLockEntry {
1494        CapabilityLockEntry {
1495            capability_type: CapabilityType::Skill,
1496            version: "1.0.0".into(),
1497            version_scheme: VersionScheme::Declared,
1498            description: String::new(),
1499            source: CapabilitySource::Pack(PackProvenance {
1500                name: pack.into(),
1501                version: version.into(),
1502                digest: "ab".repeat(32),
1503                registry: None,
1504                path: "capabilities/review".into(),
1505            }),
1506            targets: BTreeMap::from([(
1507                "open-agents".into(),
1508                TargetLockEntry {
1509                    managed_hooks: Vec::new(),
1510                    managed_mcp_entry: None,
1511                    managed_permissions: Vec::new(),
1512                    unenforced_rules: Vec::new(),
1513                    ownership: TargetOwnership::Generated,
1514                    sha256: hash_bytes(b"content"),
1515                    installed_path: ".agents/skills/review".into(),
1516                },
1517            )]),
1518            implementation: None,
1519            parameters: None,
1520            server: None,
1521        }
1522    }
1523
1524    #[test]
1525    fn a_git_pack_source_round_trips_through_the_packs_section() {
1526        let tmp = TempDir::new().unwrap();
1527        let path = tmp.path().join("tuff.lock");
1528        let mut lf = Lockfile::empty();
1529        lf.capabilities
1530            .insert("review".into(), pack_member("acme/review", "1.2.0"));
1531        let source = PackSource::Git(PackGitSource {
1532            url: "https://example.com/review-pack".into(),
1533            path: "packs/review".into(),
1534            git_ref: "4b1e".repeat(10),
1535            tag: Some("v1.2.0".into()),
1536            branch: None,
1537            format: None,
1538            plugin: None,
1539        });
1540        lf.packs.insert(
1541            "acme/review".into(),
1542            PackLockEntry {
1543                version: "stale".into(),
1544                digest: "stale".into(),
1545                source: source.clone(),
1546                x: BTreeMap::from([(
1547                    "host".to_string(),
1548                    serde_json::json!({ "default_level": "read" }),
1549                )]),
1550            },
1551        );
1552        write_lockfile_at(&path, &lf).unwrap();
1553        let written = fs::read_to_string(&path).unwrap();
1554        assert!(
1555            written.contains("\"members\": [\n        \"review\"\n      ]"),
1556            "{written}"
1557        );
1558        assert!(
1559            !written.contains("stale"),
1560            "version and digest come from the members: {written}"
1561        );
1562
1563        let read = read_lockfile_at(&path).unwrap();
1564        assert_eq!(read.packs["acme/review"].source, source);
1565        assert_eq!(read.packs["acme/review"].x["host"]["default_level"], "read");
1566        assert_eq!(read.packs["acme/review"].version, "1.2.0");
1567        assert_eq!(read.pack_members("acme/review"), vec!["review".to_string()]);
1568    }
1569
1570    #[test]
1571    fn a_pack_with_no_members_left_is_not_written() {
1572        let tmp = TempDir::new().unwrap();
1573        let path = tmp.path().join("tuff.lock");
1574        let mut lf = Lockfile::empty();
1575        lf.packs.insert(
1576            "acme/gone".into(),
1577            PackLockEntry {
1578                version: "1.0.0".into(),
1579                digest: "ab".repeat(32),
1580                source: PackSource::Artifact(PackArtifactSource { registry: None }),
1581                x: BTreeMap::new(),
1582            },
1583        );
1584        write_lockfile_at(&path, &lf).unwrap();
1585        assert_eq!(
1586            fs::read_to_string(&path).unwrap(),
1587            "{\n  \"version\": 4,\n  \"capabilities\": []\n}\n"
1588        );
1589    }
1590
1591    #[test]
1592    fn a_member_that_disagrees_with_its_pack_entry_is_corrupt() {
1593        let tmp = TempDir::new().unwrap();
1594        let path = tmp.path().join("tuff.lock");
1595        let mut lf = Lockfile::empty();
1596        lf.capabilities
1597            .insert("review".into(), pack_member("acme/review", "1.2.0"));
1598        write_lockfile_at(&path, &lf).unwrap();
1599        let edited = fs::read_to_string(&path).unwrap().replacen(
1600            "\"version\": \"1.2.0\"",
1601            "\"version\": \"9.9.9\"",
1602            1,
1603        );
1604        fs::write(&path, edited).unwrap();
1605        let error = read_lockfile_at(&path).unwrap_err();
1606        assert_eq!(error.kind(), crate::error::ErrorKind::Corrupt);
1607        assert!(
1608            error.to_string().contains("pack's entry says 9.9.9"),
1609            "{error}"
1610        );
1611    }
1612
1613    #[test]
1614    fn a_lockfile_without_a_version_is_corrupt_not_empty() {
1615        let tmp = TempDir::new().unwrap();
1616        let path = tmp.path().join("tuff.lock");
1617        fs::write(&path, "capabilities = []\n").unwrap();
1618        let error = read_lockfile_at(&path).unwrap_err().to_string();
1619        assert!(error.contains("no version field"), "{error}");
1620
1621        fs::write(&path, "version = 2\n[[capabilities]\n").unwrap();
1622        let error = read_lockfile_at(&path).unwrap_err().to_string();
1623        assert!(error.contains("not a valid lockfile"), "{error}");
1624    }
1625
1626    #[test]
1627    fn managed_mcp_entry_status_tracks_the_entry_not_the_file() {
1628        let tmp = TempDir::new().unwrap();
1629        let config_path = tmp.path().join("mcp.json");
1630        let entry_value = serde_json::json!({"command": "npx", "args": ["-y", "srv"]});
1631        let both = |neighbour: &str| {
1632            serde_json::to_string_pretty(&serde_json::json!({
1633                "mcpServers": {"github": entry_value, "neighbour": {"command": neighbour}}
1634            }))
1635            .unwrap()
1636        };
1637        fs::write(&config_path, both("hand")).unwrap();
1638        let managed = ManagedMcpEntry {
1639            config_path: "mcp.json".into(),
1640            baseline_hash: managed_mcp_entry_baseline(&entry_value).unwrap(),
1641        };
1642
1643        // Pretty-printing and neighbouring hand-written entries never matter,
1644        // and editing the neighbour leaves ours clean.
1645        assert_eq!(
1646            managed_mcp_entry_status(tmp.path(), "github", &managed),
1647            "clean"
1648        );
1649        fs::write(&config_path, both("edited")).unwrap();
1650        assert_eq!(
1651            managed_mcp_entry_status(tmp.path(), "github", &managed),
1652            "clean"
1653        );
1654
1655        // Editing our entry is modified; removing it, or the file, is missing.
1656        fs::write(
1657            &config_path,
1658            r#"{"mcpServers": {"github": {"command": "tampered"}}}"#,
1659        )
1660        .unwrap();
1661        assert_eq!(
1662            managed_mcp_entry_status(tmp.path(), "github", &managed),
1663            "modified"
1664        );
1665        fs::write(&config_path, r#"{"mcpServers": {}}"#).unwrap();
1666        assert_eq!(
1667            managed_mcp_entry_status(tmp.path(), "github", &managed),
1668            "missing"
1669        );
1670        fs::remove_file(&config_path).unwrap();
1671        assert_eq!(
1672            managed_mcp_entry_status(tmp.path(), "github", &managed),
1673            "missing"
1674        );
1675    }
1676}