Skip to main content

tuff_core/
adapter.rs

1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use tuff_hooks_spec::{CompatibilityMatrix, CoverageLevel};
6
7use crate::error::{Result, TuffError};
8pub use crate::hook_settings::{HookSettingsShape, extend_hook_groups};
9use crate::manifest::{CapabilityManifest, CapabilityType, HookConfig};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct EmittedFile {
13    pub path: String,
14    pub hash: String,
15    #[serde(rename = "baselineHash")]
16    pub baseline_hash: String,
17}
18
19#[derive(Debug, Clone)]
20pub struct PlannedFile {
21    pub path: String,
22    pub content: Vec<u8>,
23    pub allow_existing: bool,
24}
25
26impl PlannedFile {
27    pub fn new(path: String, content: Vec<u8>) -> Self {
28        Self {
29            path,
30            content,
31            allow_existing: false,
32        }
33    }
34
35    pub fn mergeable(path: String, content: Vec<u8>) -> Self {
36        Self {
37            path,
38            content,
39            allow_existing: true,
40        }
41    }
42}
43
44#[derive(Debug, Clone)]
45pub struct NativeHookConfig {
46    pub fragment: serde_json::Value,
47    pub source_files: Vec<(String, Vec<u8>)>,
48}
49
50#[derive(Debug, Clone)]
51pub enum HookRenderDiagnosticLevel {
52    Warning,
53}
54
55#[derive(Debug, Clone)]
56pub struct HookRenderDiagnostic {
57    pub level: HookRenderDiagnosticLevel,
58    pub message: String,
59}
60
61#[derive(Debug, Clone)]
62pub struct HookRenderContext<'a> {
63    pub capability_id: &'a str,
64    pub hook: &'a HookConfig,
65    pub source_files: &'a [(String, Vec<u8>)],
66    pub repo_root: &'a Path,
67    pub track_managed_hooks: bool,
68}
69
70#[derive(Debug, Clone)]
71pub struct HookRenderPlan {
72    pub files: Vec<PlannedFile>,
73    pub managed_hooks: Vec<crate::lockfile::ManagedHook>,
74    pub diagnostics: Vec<HookRenderDiagnostic>,
75}
76
77#[derive(Debug, Clone)]
78pub enum HookDefinition {
79    Command(crate::manifest::HookConfig),
80    Native(NativeHookConfig),
81}
82
83#[derive(Debug, Clone)]
84pub enum CapabilityKind {
85    Skill,
86    Tool {
87        parameters: serde_json::Value,
88        implementation: crate::manifest::ImplementationConfig,
89    },
90    Hook {
91        hook: HookDefinition,
92    },
93    McpServer {
94        server: crate::manifest::McpServerConfig,
95    },
96    Policy {
97        policy: crate::policy::PolicyConfig,
98    },
99}
100
101impl CapabilityKind {
102    pub fn capability_type(&self) -> CapabilityType {
103        match self {
104            Self::Skill => CapabilityType::Skill,
105            Self::Tool { .. } => CapabilityType::Tool,
106            Self::Hook { .. } => CapabilityType::Hook,
107            Self::McpServer { .. } => CapabilityType::McpServer,
108            Self::Policy { .. } => CapabilityType::Policy,
109        }
110    }
111}
112
113pub struct ResolvedCapability {
114    pub id: String,
115    pub capability_type: CapabilityType,
116    pub version: String,
117    pub description: String,
118    pub source_files: Vec<(String, Vec<u8>)>,
119    pub source_dir: PathBuf,
120    pub kind: CapabilityKind,
121}
122
123pub fn resolve_capability(manifest: &CapabilityManifest) -> Result<ResolvedCapability> {
124    let source_files = manifest.read_source_contents_with_names()?;
125    let kind =
126        match manifest.capability_type {
127            CapabilityType::Skill => CapabilityKind::Skill,
128            CapabilityType::Tool => CapabilityKind::Tool {
129                parameters: manifest.parameters.clone().ok_or_else(|| {
130                    TuffError::usage("tool capability requires [parameters] section")
131                })?,
132                implementation: manifest.implementation.clone().ok_or_else(|| {
133                    TuffError::usage("tool capability requires [implementation] section")
134                })?,
135            },
136            CapabilityType::Hook => {
137                CapabilityKind::Hook {
138                    hook: HookDefinition::Command(manifest.hook.clone().ok_or_else(|| {
139                        TuffError::usage("hook capability requires [hook] section")
140                    })?),
141                }
142            }
143            CapabilityType::Policy => CapabilityKind::Policy {
144                policy: manifest.policy.clone().ok_or_else(|| {
145                    TuffError::usage("policy capability requires a [policy] section")
146                })?,
147            },
148            CapabilityType::McpServer => CapabilityKind::McpServer {
149                server: manifest.server.clone().ok_or_else(|| {
150                    TuffError::usage("mcp-server capability requires [server] section")
151                })?,
152            },
153        };
154    Ok(ResolvedCapability {
155        id: manifest.id.clone(),
156        capability_type: manifest.capability_type,
157        version: manifest.version.clone(),
158        description: manifest.description.clone(),
159        source_files,
160        source_dir: manifest.root.clone(),
161        kind,
162    })
163}
164
165/// What a harness adapter declares, and what Tuff does with it.
166///
167/// An adapter is a declaration: where the harness keeps its files, which
168/// hook events it has and how they map onto Tuff's, the shape of its hook
169/// settings file, and how to recognise a project that uses it. Everything
170/// else, planning files, rendering hooks, merging into and removing from
171/// the settings file, is a default method here, so there is one
172/// implementation of each and an adapter overrides one only when its
173/// harness genuinely differs (Cursor's `${env:VAR}` spelling, say).
174pub trait AgentAdapter {
175    fn id(&self) -> &'static str;
176    fn display_name(&self) -> &'static str;
177    fn dir_prefix(&self) -> &'static str;
178    fn mcp_config_relpath(&self) -> &'static str;
179    fn supported_agents(&self) -> &[&'static str];
180    fn hook_compatibility(&self) -> &'static CompatibilityMatrix;
181    fn hook_settings_relpath(&self) -> &'static str;
182    /// How the settings file at [`hook_settings_relpath`] lays out its
183    /// registrations. This is the whole of what differs between harnesses
184    /// in hook handling; the merge and removal follow from it.
185    ///
186    /// [`hook_settings_relpath`]: AgentAdapter::hook_settings_relpath
187    fn hook_settings_shape(&self) -> HookSettingsShape;
188    /// The native event `tuff create` registers a scaffolded hook under.
189    fn scaffold_hook_event(&self) -> &'static str;
190    fn hook_filename(&self) -> &'static str {
191        "run.sh"
192    }
193    fn hook_file_content(&self, hook_cfg: &crate::manifest::HookConfig) -> Result<Vec<u8>> {
194        render_hook_script(hook_cfg)
195    }
196    fn render_standard_hook(&self, context: HookRenderContext<'_>) -> Result<HookRenderPlan> {
197        let matrix = self.hook_compatibility();
198        let Some(entry) = matrix.find_event(&context.hook.event) else {
199            return Err(TuffError::unsupported(format!(
200                "{} does not support hook event '{}'. A manifest can use: {}",
201                self.display_name(),
202                context.hook.event,
203                matrix.accepted_events_summary()
204            )));
205        };
206        let Some(native_event) = entry.native_event_name() else {
207            let suffix = entry
208                .caveat
209                .map(|caveat| format!(": {}", caveat.trim_end_matches('.')))
210                .unwrap_or_default();
211            return Err(TuffError::unsupported(format!(
212                "{} does not support hook event '{}'{}. A manifest can use: {}",
213                self.display_name(),
214                context.hook.event,
215                suffix,
216                matrix.accepted_events_summary()
217            )));
218        };
219
220        // The wrapper is what the registration runs and what the install
221        // note describes. A listed runtime file landing on the same path
222        // would silently replace it, so the harness would run a script the
223        // user was never shown.
224        if let Some((listed, _)) = context
225            .source_files
226            .iter()
227            .find(|(relative, _)| relative == self.hook_filename())
228        {
229            return Err(TuffError::refused(format!(
230                "hook '{}' lists a file installed as '{listed}', which is the wrapper Tuff generates to run its command",
231                context.capability_id
232            ))
233            .with_hint(format!(
234                "rename that file; '{}' is reserved in the hook directory",
235                self.hook_filename()
236            )));
237        }
238
239        let command = format!(
240            "sh {}/hooks/{}/{}",
241            self.dir_prefix(),
242            context.capability_id,
243            self.hook_filename()
244        );
245        let target_path = context
246            .repo_root
247            .join(self.dir_prefix())
248            .join("hooks")
249            .join(context.capability_id)
250            .join(self.hook_filename());
251        let script = self.hook_file_content(context.hook)?;
252        let settings_relpath = self.hook_settings_relpath();
253        let fragment = self.command_hook_fragment(native_event, &command);
254        let settings_path = context.repo_root.join(settings_relpath);
255        let existing = if settings_path.is_file() {
256            Some(std::fs::read(&settings_path)?)
257        } else {
258            None
259        };
260        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;
261
262        let mut files = vec![PlannedFile::new(
263            relative_or_absolute_fs(&target_path, context.repo_root),
264            script,
265        )];
266        for (relative, content) in context.source_files {
267            let path = context
268                .repo_root
269                .join(self.dir_prefix())
270                .join("hooks")
271                .join(context.capability_id)
272                .join(relative);
273            files.push(PlannedFile::new(
274                relative_or_absolute_fs(&path, context.repo_root),
275                content.clone(),
276            ));
277        }
278        files.push(PlannedFile::mergeable(
279            relative_or_absolute_fs(&settings_path, context.repo_root),
280            merged,
281        ));
282
283        let mut diagnostics = Vec::new();
284        if entry.coverage == CoverageLevel::Partial {
285            let scope = if entry.scope.is_empty() {
286                "partial coverage".to_string()
287            } else {
288                format!("scope: {}", entry.scope.join(", "))
289            };
290            let caveat = entry
291                .caveat
292                .map(|caveat| format!("; {caveat}"))
293                .unwrap_or_default();
294            diagnostics.push(HookRenderDiagnostic {
295                level: HookRenderDiagnosticLevel::Warning,
296                message: format!(
297                    "{} renders '{}' with partial compatibility ({scope}{caveat})",
298                    self.display_name(),
299                    entry.event
300                ),
301            });
302        }
303
304        let managed_hooks = if context.track_managed_hooks {
305            crate::lockfile::managed_hooks_from_fragment_with_canonical(
306                context.repo_root,
307                settings_relpath,
308                &fragment,
309                Some(entry.event.as_str()),
310            )?
311        } else {
312            Vec::new()
313        };
314
315        Ok(HookRenderPlan {
316            files,
317            managed_hooks,
318            diagnostics,
319        })
320    }
321    /// The hooks-only fragment that registers `command` under `native_event`.
322    fn command_hook_fragment(&self, native_event: &str, command: &str) -> serde_json::Value {
323        self.hook_settings_shape()
324            .command_fragment(native_event, command)
325    }
326    /// Merge a hooks-only fragment into the settings file's current bytes.
327    fn merge_hook_fragment(
328        &self,
329        existing: Option<&[u8]>,
330        fragment: &serde_json::Value,
331    ) -> Result<Vec<u8>> {
332        self.hook_settings_shape()
333            .merge_fragment(self.hook_settings_relpath(), existing, fragment)
334    }
335    /// Take Tuff's registrations out of the settings file, leaving the
336    /// user's own alone.
337    fn remove_hook_settings(
338        &self,
339        repo_root: &Path,
340        managed_hooks: &[crate::lockfile::ManagedHook],
341    ) -> Result<()> {
342        crate::hook_settings::remove_registrations(
343            self.hook_settings_relpath(),
344            self.display_name(),
345            repo_root,
346            managed_hooks,
347        )
348    }
349    /// Whether a project already uses this harness.
350    fn detect(&self, repo_root: &Path) -> bool;
351
352    /// How this harness enforces each kind of policy rule, one row per
353    /// effect and subject. The default says, for every row, that Tuff does
354    /// not compile policies for this harness, so a policy is refused for it
355    /// rather than reported as installed.
356    fn policy_compatibility(&self) -> Vec<crate::policy::PolicyCoverageEntry> {
357        crate::policy::not_implemented_matrix()
358    }
359
360    /// The settings file this harness reads native permission rules from,
361    /// when it has one a repository can carry.
362    fn permissions_settings_relpath(&self) -> Option<&'static str> {
363        None
364    }
365
366    /// The settings file rules of one subject compile into, for a harness
367    /// that keeps different kinds of rule in different files. The default is
368    /// `permissions_settings_relpath`.
369    fn permission_relpath_for(
370        &self,
371        _subject: crate::policy::PolicySubjectKind,
372    ) -> Option<&'static str> {
373        self.permissions_settings_relpath()
374    }
375
376    /// Why this harness cannot enforce one rule that its matrix row covers,
377    /// such as a pattern its native setting has no form for, or `None`.
378    fn policy_rule_gap(&self, _rule: &crate::policy::PolicyRule) -> Result<Option<String>> {
379        Ok(None)
380    }
381
382    /// The native permission rules one policy rule compiles to on this
383    /// harness, or `None` when the harness has no such rules. The list the
384    /// rules go in follows the policy rule's effect.
385    fn native_permission_rules(
386        &self,
387        _rule: &crate::policy::PolicyRule,
388    ) -> Result<Option<Vec<String>>> {
389        Ok(None)
390    }
391
392    fn kinds_supported(&self) -> &[CapabilityType];
393
394    fn supports(&self, capability_type: CapabilityType) -> bool {
395        self.kinds_supported().contains(&capability_type)
396    }
397
398    fn native_hook_event(&self, raw_event: &str) -> Result<&'static str> {
399        let matrix = self.hook_compatibility();
400        let Some(entry) = matrix.find_event(raw_event) else {
401            return Err(TuffError::unsupported(format!(
402                "{} does not support hook event '{}'. A manifest can use: {}",
403                self.display_name(),
404                raw_event,
405                matrix.accepted_events_summary()
406            )));
407        };
408        entry.native_event_name().ok_or_else(|| {
409            let suffix = entry
410                .caveat
411                .map(|caveat| format!(": {}", caveat.trim_end_matches('.')))
412                .unwrap_or_default();
413            TuffError::unsupported(format!(
414                "{} does not support hook event '{}'{}. A manifest can use: {}",
415                self.display_name(),
416                raw_event,
417                suffix,
418                matrix.accepted_events_summary()
419            ))
420        })
421    }
422
423    fn canonical_hook_event(&self, raw_event: &str) -> Result<&'static str> {
424        let matrix = self.hook_compatibility();
425        let Some(entry) = matrix.find_event(raw_event) else {
426            return Err(TuffError::unsupported(format!(
427                "{} does not support hook event '{}'",
428                self.display_name(),
429                raw_event
430            )));
431        };
432        entry
433            .coverage
434            .is_supported()
435            .then_some(entry.event.as_str())
436            .ok_or_else(|| {
437                let suffix = entry
438                    .caveat
439                    .map(|caveat| format!(": {caveat}"))
440                    .unwrap_or_default();
441                TuffError::unsupported(format!(
442                    "{} does not support hook event '{}'{}",
443                    self.display_name(),
444                    raw_event,
445                    suffix
446                ))
447            })
448    }
449
450    fn ensure_project_dir(&self, repo_root: &Path) -> std::io::Result<()> {
451        std::fs::create_dir_all(repo_root.join(self.dir_prefix()))
452    }
453
454    /// How this harness spells a reference to an environment variable inside
455    /// its MCP config. Claude Code and most stdio clients expand `${VAR}`.
456    fn mcp_env_reference(&self, var: &str) -> String {
457        format!("${{{var}}}")
458    }
459
460    /// The `mcpServers.<id>` entry this harness needs for an external MCP
461    /// server. Secrets are emitted as env references, never values.
462    fn mcp_server_entry(&self, server: &crate::manifest::McpServerConfig) -> serde_json::Value {
463        use crate::manifest::McpTransport;
464        match server.transport {
465            McpTransport::Stdio => {
466                let mut entry = serde_json::json!({
467                    "command": server.command.clone().unwrap_or_default(),
468                    "args": server.args,
469                });
470                if !server.env.is_empty() {
471                    let env: serde_json::Map<String, serde_json::Value> = server
472                        .env
473                        .iter()
474                        .map(|(name, reference)| {
475                            (
476                                name.clone(),
477                                serde_json::Value::String(
478                                    self.mcp_env_reference(&reference.from_env),
479                                ),
480                            )
481                        })
482                        .collect();
483                    entry["env"] = serde_json::Value::Object(env);
484                }
485                entry
486            }
487            McpTransport::Http => {
488                let mut entry = serde_json::Map::new();
489                if self.mcp_http_declares_type() {
490                    entry.insert("type".into(), serde_json::Value::String("http".into()));
491                }
492                entry.insert(
493                    "url".into(),
494                    serde_json::Value::String(server.url.clone().unwrap_or_default()),
495                );
496                if !server.headers.is_empty() {
497                    let headers: serde_json::Map<String, serde_json::Value> = server
498                        .headers
499                        .iter()
500                        .map(|(name, reference)| {
501                            let value =
502                                reference.render(&self.mcp_env_reference(&reference.from_env));
503                            (name.clone(), serde_json::Value::String(value))
504                        })
505                        .collect();
506                    entry.insert("headers".into(), serde_json::Value::Object(headers));
507                }
508                serde_json::Value::Object(entry)
509            }
510        }
511    }
512
513    /// Whether this harness wants an explicit `"type": "http"` on a remote
514    /// server entry. Claude Code and Codex do; Cursor infers the transport
515    /// from `url` and has no `type` key for remote servers.
516    fn mcp_http_declares_type(&self) -> bool {
517        true
518    }
519
520    /// `mcp_server_entry`, for a harness whose config cannot express every
521    /// declaration. The default expresses everything; an override refuses
522    /// what its harness would silently get wrong, such as a renamed
523    /// variable, so the install stops before anything is written.
524    fn mcp_server_entry_checked(
525        &self,
526        server: &crate::manifest::McpServerConfig,
527    ) -> Result<serde_json::Value> {
528        Ok(self.mcp_server_entry(server))
529    }
530
531    /// A note `tuff add` prints after installing a capability of this kind,
532    /// for a harness that applies the installed files only under a
533    /// condition the file itself cannot state, such as Codex loading a
534    /// project's `.codex/` layer only once the project is trusted.
535    fn install_note(&self, _kind: CapabilityType) -> Option<&'static str> {
536        None
537    }
538
539    fn plan(&self, capability: &ResolvedCapability, repo_root: &Path) -> Result<Vec<PlannedFile>> {
540        match capability.capability_type {
541            CapabilityType::Tool => self.plan_tool(capability, repo_root),
542            CapabilityType::Hook => self.plan_hook(capability, repo_root),
543            CapabilityType::McpServer => self.plan_mcp_server(capability, repo_root),
544            CapabilityType::Policy => self.plan_policy(capability, repo_root),
545            CapabilityType::Skill => self.plan_skill(capability, repo_root),
546        }
547    }
548
549    fn remove(
550        &self,
551        primitive_id: &str,
552        repo_root: &Path,
553        managed_hooks: &[crate::lockfile::ManagedHook],
554    ) -> Result<()> {
555        // Settings first, files last. Taking registrations out of a settings
556        // file is the step that can refuse, when the user's file is not valid
557        // JSON; deleting directories cannot meaningfully be refused. In this
558        // order a corrupt file stops the removal with every file still in
559        // place and the capability still tracked, instead of after its files
560        // are gone.
561        self.remove_hook_settings(repo_root, managed_hooks)?;
562        crate::mcp::remove_tool(&repo_root.join(self.mcp_config_relpath()), primitive_id)?;
563        let prefix = self.dir_prefix();
564        for kind in &["skills", "tools", "hooks", "mcp-servers", "policies"] {
565            self.remove_dir(repo_root, prefix, kind, primitive_id)?;
566        }
567        Ok(())
568    }
569
570    // ── internal helpers ───────────────────────────────────────────────
571
572    fn plan_skill(
573        &self,
574        capability: &ResolvedCapability,
575        repo_root: &Path,
576    ) -> Result<Vec<PlannedFile>> {
577        if capability.source_files.is_empty() {
578            return Err(TuffError::usage("no source files to emit"));
579        }
580
581        let mut files = Vec::new();
582        for (rel_path, content) in &capability.source_files {
583            let target_path = repo_root
584                .join(self.dir_prefix())
585                .join("skills")
586                .join(&capability.id)
587                .join(rel_path);
588
589            files.push(PlannedFile::new(
590                relative_or_absolute_fs(&target_path, repo_root),
591                content.clone(),
592            ));
593        }
594        Ok(files)
595    }
596
597    fn plan_tool(
598        &self,
599        capability: &ResolvedCapability,
600        repo_root: &Path,
601    ) -> Result<Vec<PlannedFile>> {
602        let mut files = Vec::new();
603
604        for (rel_path, content) in &capability.source_files {
605            let target_path = repo_root
606                .join(self.dir_prefix())
607                .join("tools")
608                .join(&capability.id)
609                .join(rel_path);
610
611            files.push(PlannedFile::new(
612                relative_or_absolute_fs(&target_path, repo_root),
613                content.clone(),
614            ));
615        }
616
617        if capability.source_files.is_empty() {
618            let placeholder = repo_root
619                .join(self.dir_prefix())
620                .join("tools")
621                .join(&capability.id)
622                .join(".gitkeep");
623            files.push(PlannedFile::new(
624                relative_or_absolute_fs(&placeholder, repo_root),
625                vec![],
626            ));
627        }
628
629        Ok(files)
630    }
631
632    fn plan_hook(
633        &self,
634        capability: &ResolvedCapability,
635        repo_root: &Path,
636    ) -> Result<Vec<PlannedFile>> {
637        let CapabilityKind::Hook { hook } = &capability.kind else {
638            return Err(TuffError::new("plan_hook called on non-hook capability"));
639        };
640
641        match hook {
642            HookDefinition::Command(hook_cfg) => {
643                let render = self.render_standard_hook(HookRenderContext {
644                    capability_id: &capability.id,
645                    hook: hook_cfg,
646                    source_files: &capability.source_files,
647                    repo_root,
648                    track_managed_hooks: false,
649                })?;
650                Ok(render.files)
651            }
652            HookDefinition::Native(native) => self.plan_native_hook(capability, native, repo_root),
653        }
654    }
655
656    fn plan_native_hook(
657        &self,
658        capability: &ResolvedCapability,
659        native: &NativeHookConfig,
660        repo_root: &Path,
661    ) -> Result<Vec<PlannedFile>> {
662        let hook_root = repo_root
663            .join(self.dir_prefix())
664            .join("hooks")
665            .join(&capability.id);
666        let hook_root_rel = relative_or_absolute_fs(&hook_root, repo_root);
667        let in_harness_source =
668            path_is_under(&capability.source_dir, &repo_root.join(self.dir_prefix()));
669
670        let mut files = Vec::new();
671        if in_harness_source {
672            for (rel_path, content) in &native.source_files {
673                let target_path = capability.source_dir.join(rel_path);
674                files.push(PlannedFile::mergeable(
675                    relative_or_absolute_fs(&target_path, repo_root),
676                    content.clone(),
677                ));
678            }
679        } else {
680            for (rel_path, content) in &native.source_files {
681                let target_path = hook_root.join(rel_path);
682                files.push(PlannedFile::new(
683                    relative_or_absolute_fs(&target_path, repo_root),
684                    content.clone(),
685                ));
686            }
687        }
688
689        let fragment = replace_hook_dir_placeholder(native.fragment.clone(), &hook_root_rel);
690        let settings_relpath = self.hook_settings_relpath();
691        let settings_path = repo_root.join(settings_relpath);
692        let existing = if settings_path.is_file() {
693            Some(std::fs::read(&settings_path)?)
694        } else {
695            None
696        };
697        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;
698        files.push(PlannedFile::mergeable(
699            relative_or_absolute_fs(&settings_path, repo_root),
700            merged,
701        ));
702        Ok(files)
703    }
704
705    /// Emit the canonical `server.toml` record. The JSON entry in the
706    /// harness's MCP config is the artifact the harness reads; this file is
707    /// what gives the capability a tree to hash, so `check`/`diff`/`delete`
708    /// work exactly as they do for every other kind.
709    fn plan_mcp_server(
710        &self,
711        capability: &ResolvedCapability,
712        repo_root: &Path,
713    ) -> Result<Vec<PlannedFile>> {
714        let CapabilityKind::McpServer { server } = &capability.kind else {
715            return Err(TuffError::new(
716                "plan_mcp_server called on non-mcp-server capability",
717            ));
718        };
719
720        let target_path = repo_root
721            .join(self.dir_prefix())
722            .join("mcp-servers")
723            .join(&capability.id)
724            .join("server.toml");
725
726        let content = serialize_mcp_server(capability, server)?;
727
728        Ok(vec![PlannedFile::new(
729            relative_or_absolute_fs(&target_path, repo_root),
730            content,
731        )])
732    }
733
734    /// Emit the canonical `policy.toml` record. The rules the harness reads
735    /// live in its settings file; this record gives the capability a tree
736    /// to hash, so `check`, `diff`, and `delete` treat it like every other
737    /// kind, and `update` can tell when the policy's rules changed.
738    fn plan_policy(
739        &self,
740        capability: &ResolvedCapability,
741        repo_root: &Path,
742    ) -> Result<Vec<PlannedFile>> {
743        let CapabilityKind::Policy { policy } = &capability.kind else {
744            return Err(TuffError::new(
745                "plan_policy called on non-policy capability",
746            ));
747        };
748        let target_path = repo_root
749            .join(self.dir_prefix())
750            .join("policies")
751            .join(&capability.id)
752            .join("policy.toml");
753        let content = serialize_policy(capability, policy)?;
754        Ok(vec![PlannedFile::new(
755            relative_or_absolute_fs(&target_path, repo_root),
756            content,
757        )])
758    }
759
760    fn remove_dir(
761        &self,
762        repo_root: &Path,
763        base: &str,
764        kind: &str,
765        primitive_id: &str,
766    ) -> Result<()> {
767        let dir = repo_root.join(base).join(kind).join(primitive_id);
768
769        if dir.exists() {
770            std::fs::remove_dir_all(&dir)?;
771        }
772
773        let kind_dir = dir.parent().expect("kind dir should have parent");
774        if kind_dir.exists() {
775            let mut rd = match std::fs::read_dir(kind_dir) {
776                Ok(rd) => rd,
777                Err(_) => return Ok(()),
778            };
779            if rd.next().is_none() {
780                std::fs::remove_dir(kind_dir)?;
781            }
782        }
783
784        let base_dir = kind_dir.parent().expect("base dir should have parent");
785        if base_dir.exists() {
786            let mut rd = match std::fs::read_dir(base_dir) {
787                Ok(rd) => rd,
788                Err(_) => return Ok(()),
789            };
790            if rd.next().is_none() {
791                std::fs::remove_dir(base_dir)?;
792            }
793        }
794
795        Ok(())
796    }
797}
798
799fn render_hook_script(hook_cfg: &HookConfig) -> Result<Vec<u8>> {
800    let working_directory = shell_single_quote(&hook_cfg.working_directory)?;
801    let command = shell_single_quote(&hook_cfg.command)?;
802    Ok(format!(
803        "#!/usr/bin/env bash\nset -euo pipefail\ncd -- {working_directory}\nexec bash -euo pipefail -c {command}\n"
804    )
805    .into_bytes())
806}
807
808fn shell_single_quote(value: &str) -> Result<String> {
809    if value.contains('\0') {
810        return Err(TuffError::usage(
811            "hook working directory and command cannot contain NUL bytes",
812        ));
813    }
814    Ok(format!("'{}'", value.replace('\'', "'\"'\"'")))
815}
816
817#[derive(Serialize)]
818struct McpServerDocument<'a> {
819    id: &'a str,
820    version: &'a str,
821    #[serde(rename = "type")]
822    capability_type: CapabilityType,
823    description: &'a str,
824    server: &'a crate::manifest::McpServerConfig,
825}
826
827fn serialize_mcp_server(
828    capability: &ResolvedCapability,
829    server: &crate::manifest::McpServerConfig,
830) -> Result<Vec<u8>> {
831    let document = McpServerDocument {
832        id: &capability.id,
833        version: &capability.version,
834        capability_type: capability.capability_type,
835        description: &capability.description,
836        server,
837    };
838    let mut content = toml::to_string_pretty(&document)?;
839    if !content.ends_with('\n') {
840        content.push('\n');
841    }
842    Ok(content.into_bytes())
843}
844
845#[derive(Serialize)]
846struct PolicyDocument<'a> {
847    id: &'a str,
848    version: &'a str,
849    #[serde(rename = "type")]
850    capability_type: CapabilityType,
851    description: &'a str,
852    policy: &'a crate::policy::PolicyConfig,
853}
854
855fn serialize_policy(
856    capability: &ResolvedCapability,
857    policy: &crate::policy::PolicyConfig,
858) -> Result<Vec<u8>> {
859    let document = PolicyDocument {
860        id: &capability.id,
861        version: &capability.version,
862        capability_type: capability.capability_type,
863        description: &capability.description,
864        policy,
865    };
866    let mut content = toml::to_string_pretty(&document)?;
867    if !content.ends_with('\n') {
868        content.push('\n');
869    }
870    Ok(content.into_bytes())
871}
872
873fn path_is_under(path: &Path, root: &Path) -> bool {
874    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
875    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
876    canonical_path.starts_with(canonical_root)
877}
878
879pub fn replace_hook_dir_placeholder(
880    mut value: serde_json::Value,
881    hook_dir: &str,
882) -> serde_json::Value {
883    match &mut value {
884        serde_json::Value::String(s) => {
885            *s = s.replace("{{hook_dir}}", hook_dir);
886        }
887        serde_json::Value::Array(items) => {
888            for item in items {
889                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
890            }
891        }
892        serde_json::Value::Object(map) => {
893            for item in map.values_mut() {
894                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
895            }
896        }
897        _ => {}
898    }
899    value
900}
901
902fn relative_or_absolute_fs(path: &Path, repo_root: &Path) -> String {
903    crate::lockfile::relative_or_absolute_fs(path, repo_root)
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909
910    #[cfg(unix)]
911    #[test]
912    fn hook_script_preserves_shell_sensitive_values() {
913        use std::process::Command;
914
915        let temp = tempfile::tempdir().expect("tempdir");
916        let working_directory = temp.path().join("directory with ' quote");
917        std::fs::create_dir(&working_directory).expect("create working directory");
918        let hook = HookConfig {
919            event: "stop".to_string(),
920            command: "printf '%s\\n' 'safe; $HOME `literal`' > result.txt".to_string(),
921            working_directory: working_directory.to_string_lossy().into_owned(),
922        };
923        let script_path = temp.path().join("run.sh");
924        std::fs::write(
925            &script_path,
926            render_hook_script(&hook).expect("render script"),
927        )
928        .expect("write script");
929
930        let syntax = Command::new("bash")
931            .arg("-n")
932            .arg(&script_path)
933            .status()
934            .expect("check script syntax");
935        assert!(syntax.success());
936        let executed = Command::new("bash")
937            .arg(&script_path)
938            .status()
939            .expect("execute script");
940        assert!(executed.success());
941        assert_eq!(
942            std::fs::read_to_string(working_directory.join("result.txt"))
943                .expect("read command output"),
944            "safe; $HOME `literal`\n"
945        );
946    }
947
948    #[test]
949    fn hook_script_rejects_nul_bytes() {
950        let hook = HookConfig {
951            event: "stop".to_string(),
952            command: "printf '\0'".to_string(),
953            working_directory: ".".to_string(),
954        };
955
956        assert!(render_hook_script(&hook).is_err());
957    }
958}