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        // `{{hook_dir}}` in a hook's command names the folder its files are
246        // installed in, relative to the project root, so a hook can run a
247        // script it ships however the harness lays folders out (RFC-110 D10).
248        let hook_dir = format!("{}/hooks/{}", self.dir_prefix(), context.capability_id);
249        let hook = with_hook_dir(context.hook, &hook_dir);
250        let target_path = context
251            .repo_root
252            .join(self.dir_prefix())
253            .join("hooks")
254            .join(context.capability_id)
255            .join(self.hook_filename());
256        let script = self.hook_file_content(&hook)?;
257        let settings_relpath = self.hook_settings_relpath();
258        let fragment = self.command_hook_fragment(native_event, &command);
259        let settings_path = context.repo_root.join(settings_relpath);
260        let existing = if settings_path.is_file() {
261            Some(std::fs::read(&settings_path)?)
262        } else {
263            None
264        };
265        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;
266
267        let mut files = vec![PlannedFile::new(
268            relative_or_absolute_fs(&target_path, context.repo_root),
269            script,
270        )];
271        for (relative, content) in context.source_files {
272            let path = context
273                .repo_root
274                .join(self.dir_prefix())
275                .join("hooks")
276                .join(context.capability_id)
277                .join(relative);
278            files.push(PlannedFile::new(
279                relative_or_absolute_fs(&path, context.repo_root),
280                content.clone(),
281            ));
282        }
283        files.push(PlannedFile::mergeable(
284            relative_or_absolute_fs(&settings_path, context.repo_root),
285            merged,
286        ));
287
288        let mut diagnostics = Vec::new();
289        if entry.coverage == CoverageLevel::Partial {
290            let scope = if entry.scope.is_empty() {
291                "partial coverage".to_string()
292            } else {
293                format!("scope: {}", entry.scope.join(", "))
294            };
295            let caveat = entry
296                .caveat
297                .map(|caveat| format!("; {caveat}"))
298                .unwrap_or_default();
299            diagnostics.push(HookRenderDiagnostic {
300                level: HookRenderDiagnosticLevel::Warning,
301                message: format!(
302                    "{} renders '{}' with partial compatibility ({scope}{caveat})",
303                    self.display_name(),
304                    entry.event
305                ),
306            });
307        }
308
309        let managed_hooks = if context.track_managed_hooks {
310            crate::lockfile::managed_hooks_from_fragment_with_canonical(
311                context.repo_root,
312                settings_relpath,
313                &fragment,
314                Some(entry.event.as_str()),
315            )?
316        } else {
317            Vec::new()
318        };
319
320        Ok(HookRenderPlan {
321            files,
322            managed_hooks,
323            diagnostics,
324        })
325    }
326    /// The hooks-only fragment that registers `command` under `native_event`.
327    fn command_hook_fragment(&self, native_event: &str, command: &str) -> serde_json::Value {
328        self.hook_settings_shape()
329            .command_fragment(native_event, command)
330    }
331    /// Merge a hooks-only fragment into the settings file's current bytes.
332    fn merge_hook_fragment(
333        &self,
334        existing: Option<&[u8]>,
335        fragment: &serde_json::Value,
336    ) -> Result<Vec<u8>> {
337        self.hook_settings_shape()
338            .merge_fragment(self.hook_settings_relpath(), existing, fragment)
339    }
340    /// Take Tuff's registrations out of the settings file, leaving the
341    /// user's own alone.
342    fn remove_hook_settings(
343        &self,
344        repo_root: &Path,
345        managed_hooks: &[crate::lockfile::ManagedHook],
346    ) -> Result<()> {
347        crate::hook_settings::remove_registrations(
348            self.hook_settings_relpath(),
349            self.display_name(),
350            repo_root,
351            managed_hooks,
352        )
353    }
354    /// Whether a project already uses this harness.
355    fn detect(&self, repo_root: &Path) -> bool;
356
357    /// How this harness enforces each kind of policy rule, one row per
358    /// effect and subject. The default says, for every row, that Tuff does
359    /// not compile policies for this harness, so a policy is refused for it
360    /// rather than reported as installed.
361    fn policy_compatibility(&self) -> Vec<crate::policy::PolicyCoverageEntry> {
362        crate::policy::not_implemented_matrix()
363    }
364
365    /// The settings file this harness reads native permission rules from,
366    /// when it has one a repository can carry.
367    fn permissions_settings_relpath(&self) -> Option<&'static str> {
368        None
369    }
370
371    /// The settings file rules of one subject compile into, for a harness
372    /// that keeps different kinds of rule in different files. The default is
373    /// `permissions_settings_relpath`.
374    fn permission_relpath_for(
375        &self,
376        _subject: crate::policy::PolicySubjectKind,
377    ) -> Option<&'static str> {
378        self.permissions_settings_relpath()
379    }
380
381    /// Why this harness cannot enforce one rule that its matrix row covers,
382    /// such as a pattern its native setting has no form for, or `None`.
383    fn policy_rule_gap(&self, _rule: &crate::policy::PolicyRule) -> Result<Option<String>> {
384        Ok(None)
385    }
386
387    /// The native permission rules one policy rule compiles to on this
388    /// harness, or `None` when the harness has no such rules. The list the
389    /// rules go in follows the policy rule's effect.
390    fn native_permission_rules(
391        &self,
392        _rule: &crate::policy::PolicyRule,
393    ) -> Result<Option<Vec<String>>> {
394        Ok(None)
395    }
396
397    /// Whether this harness enforces one policy rule through the
398    /// `tuff policy evaluate` hook (RFC-107 D3). The default is never.
399    fn policy_hook_use(
400        &self,
401        _rule: &crate::policy::PolicyRule,
402    ) -> Result<crate::policy_eval::PolicyHookUse> {
403        Ok(crate::policy_eval::PolicyHookUse::Never)
404    }
405
406    /// The hooks-only fragment that registers `command` for rules of these
407    /// subjects, in the file at `hook_settings_relpath`, or `None` when this
408    /// harness has no hook for policies.
409    fn policy_hook_fragment(
410        &self,
411        _command: &str,
412        _subjects: &[crate::policy::PolicySubjectKind],
413    ) -> Option<serde_json::Value> {
414        None
415    }
416
417    /// Read the tool call a policy hook was run for from the harness's hook
418    /// input.
419    fn policy_hook_request(
420        &self,
421        _input: &serde_json::Value,
422    ) -> Result<crate::policy_eval::PolicyHookRequest> {
423        Err(TuffError::unsupported(format!(
424            "{} does not run policy hooks",
425            self.display_name()
426        )))
427    }
428
429    /// The answer a policy hook gives the harness. The default refuses
430    /// every call it has a reason to and says nothing otherwise.
431    fn policy_hook_answer(
432        &self,
433        _event: &str,
434        verdict: crate::policy_eval::PolicyVerdict<'_>,
435    ) -> crate::policy_eval::PolicyHookAnswer {
436        use crate::policy_eval::{PolicyHookAnswer, PolicyVerdict};
437        match verdict {
438            PolicyVerdict::NoMatch => PolicyHookAnswer {
439                stdout: String::new(),
440                exit_code: 0,
441            },
442            PolicyVerdict::Matched(decision) => PolicyHookAnswer {
443                stdout: decision.message(),
444                exit_code: 2,
445            },
446            PolicyVerdict::Failed(message) => PolicyHookAnswer {
447                stdout: message.to_string(),
448                exit_code: 2,
449            },
450        }
451    }
452
453    fn kinds_supported(&self) -> &[CapabilityType];
454
455    fn supports(&self, capability_type: CapabilityType) -> bool {
456        self.kinds_supported().contains(&capability_type)
457    }
458
459    fn native_hook_event(&self, raw_event: &str) -> Result<&'static str> {
460        let matrix = self.hook_compatibility();
461        let Some(entry) = matrix.find_event(raw_event) else {
462            return Err(TuffError::unsupported(format!(
463                "{} does not support hook event '{}'. A manifest can use: {}",
464                self.display_name(),
465                raw_event,
466                matrix.accepted_events_summary()
467            )));
468        };
469        entry.native_event_name().ok_or_else(|| {
470            let suffix = entry
471                .caveat
472                .map(|caveat| format!(": {}", caveat.trim_end_matches('.')))
473                .unwrap_or_default();
474            TuffError::unsupported(format!(
475                "{} does not support hook event '{}'{}. A manifest can use: {}",
476                self.display_name(),
477                raw_event,
478                suffix,
479                matrix.accepted_events_summary()
480            ))
481        })
482    }
483
484    fn canonical_hook_event(&self, raw_event: &str) -> Result<&'static str> {
485        let matrix = self.hook_compatibility();
486        let Some(entry) = matrix.find_event(raw_event) else {
487            return Err(TuffError::unsupported(format!(
488                "{} does not support hook event '{}'",
489                self.display_name(),
490                raw_event
491            )));
492        };
493        entry
494            .coverage
495            .is_supported()
496            .then_some(entry.event.as_str())
497            .ok_or_else(|| {
498                let suffix = entry
499                    .caveat
500                    .map(|caveat| format!(": {caveat}"))
501                    .unwrap_or_default();
502                TuffError::unsupported(format!(
503                    "{} does not support hook event '{}'{}",
504                    self.display_name(),
505                    raw_event,
506                    suffix
507                ))
508            })
509    }
510
511    fn ensure_project_dir(&self, repo_root: &Path) -> std::io::Result<()> {
512        std::fs::create_dir_all(repo_root.join(self.dir_prefix()))
513    }
514
515    /// How this harness spells a reference to an environment variable inside
516    /// its MCP config. Claude Code and most stdio clients expand `${VAR}`.
517    fn mcp_env_reference(&self, var: &str) -> String {
518        format!("${{{var}}}")
519    }
520
521    /// The `mcpServers.<id>` entry this harness needs for an external MCP
522    /// server. Secrets are emitted as env references, never values.
523    fn mcp_server_entry(&self, server: &crate::manifest::McpServerConfig) -> serde_json::Value {
524        use crate::manifest::McpTransport;
525        match server.transport {
526            McpTransport::Stdio => {
527                let mut entry = serde_json::json!({
528                    "command": server.command.clone().unwrap_or_default(),
529                    "args": server.args,
530                });
531                if !server.env.is_empty() {
532                    let env: serde_json::Map<String, serde_json::Value> = server
533                        .env
534                        .iter()
535                        .map(|(name, reference)| {
536                            (
537                                name.clone(),
538                                serde_json::Value::String(
539                                    self.mcp_env_reference(&reference.from_env),
540                                ),
541                            )
542                        })
543                        .collect();
544                    entry["env"] = serde_json::Value::Object(env);
545                }
546                entry
547            }
548            McpTransport::Http => {
549                let mut entry = serde_json::Map::new();
550                if self.mcp_http_declares_type() {
551                    entry.insert("type".into(), serde_json::Value::String("http".into()));
552                }
553                entry.insert(
554                    "url".into(),
555                    serde_json::Value::String(server.url.clone().unwrap_or_default()),
556                );
557                if !server.headers.is_empty() {
558                    let headers: serde_json::Map<String, serde_json::Value> = server
559                        .headers
560                        .iter()
561                        .map(|(name, reference)| {
562                            let value =
563                                reference.render(&self.mcp_env_reference(&reference.from_env));
564                            (name.clone(), serde_json::Value::String(value))
565                        })
566                        .collect();
567                    entry.insert("headers".into(), serde_json::Value::Object(headers));
568                }
569                serde_json::Value::Object(entry)
570            }
571        }
572    }
573
574    /// Whether this harness wants an explicit `"type": "http"` on a remote
575    /// server entry. Claude Code and Codex do; Cursor infers the transport
576    /// from `url` and has no `type` key for remote servers.
577    fn mcp_http_declares_type(&self) -> bool {
578        true
579    }
580
581    /// `mcp_server_entry`, for a harness whose config cannot express every
582    /// declaration. The default expresses everything; an override refuses
583    /// what its harness would silently get wrong, such as a renamed
584    /// variable, so the install stops before anything is written.
585    fn mcp_server_entry_checked(
586        &self,
587        server: &crate::manifest::McpServerConfig,
588    ) -> Result<serde_json::Value> {
589        Ok(self.mcp_server_entry(server))
590    }
591
592    /// A note `tuff add` prints after installing a capability of this kind,
593    /// for a harness that applies the installed files only under a
594    /// condition the file itself cannot state, such as Codex loading a
595    /// project's `.codex/` layer only once the project is trusted.
596    fn install_note(&self, _kind: CapabilityType) -> Option<&'static str> {
597        None
598    }
599
600    fn plan(&self, capability: &ResolvedCapability, repo_root: &Path) -> Result<Vec<PlannedFile>> {
601        match capability.capability_type {
602            CapabilityType::Tool => self.plan_tool(capability, repo_root),
603            CapabilityType::Hook => self.plan_hook(capability, repo_root),
604            CapabilityType::McpServer => self.plan_mcp_server(capability, repo_root),
605            CapabilityType::Policy => self.plan_policy(capability, repo_root),
606            CapabilityType::Skill => self.plan_skill(capability, repo_root),
607        }
608    }
609
610    fn remove(
611        &self,
612        primitive_id: &str,
613        repo_root: &Path,
614        managed_hooks: &[crate::lockfile::ManagedHook],
615    ) -> Result<()> {
616        // Settings first, files last. Taking registrations out of a settings
617        // file is the step that can refuse, when the user's file is not valid
618        // JSON; deleting directories cannot meaningfully be refused. In this
619        // order a corrupt file stops the removal with every file still in
620        // place and the capability still tracked, instead of after its files
621        // are gone.
622        self.remove_hook_settings(repo_root, managed_hooks)?;
623        crate::mcp::remove_tool(&repo_root.join(self.mcp_config_relpath()), primitive_id)?;
624        let prefix = self.dir_prefix();
625        for kind in &["skills", "tools", "hooks", "mcp-servers", "policies"] {
626            self.remove_dir(repo_root, prefix, kind, primitive_id)?;
627        }
628        Ok(())
629    }
630
631    // ── internal helpers ───────────────────────────────────────────────
632
633    fn plan_skill(
634        &self,
635        capability: &ResolvedCapability,
636        repo_root: &Path,
637    ) -> Result<Vec<PlannedFile>> {
638        if capability.source_files.is_empty() {
639            return Err(TuffError::usage("no source files to emit"));
640        }
641
642        let mut files = Vec::new();
643        for (rel_path, content) in &capability.source_files {
644            let target_path = repo_root
645                .join(self.dir_prefix())
646                .join("skills")
647                .join(&capability.id)
648                .join(rel_path);
649
650            files.push(PlannedFile::new(
651                relative_or_absolute_fs(&target_path, repo_root),
652                content.clone(),
653            ));
654        }
655        Ok(files)
656    }
657
658    fn plan_tool(
659        &self,
660        capability: &ResolvedCapability,
661        repo_root: &Path,
662    ) -> Result<Vec<PlannedFile>> {
663        let mut files = Vec::new();
664
665        for (rel_path, content) in &capability.source_files {
666            let target_path = repo_root
667                .join(self.dir_prefix())
668                .join("tools")
669                .join(&capability.id)
670                .join(rel_path);
671
672            files.push(PlannedFile::new(
673                relative_or_absolute_fs(&target_path, repo_root),
674                content.clone(),
675            ));
676        }
677
678        if capability.source_files.is_empty() {
679            let placeholder = repo_root
680                .join(self.dir_prefix())
681                .join("tools")
682                .join(&capability.id)
683                .join(".gitkeep");
684            files.push(PlannedFile::new(
685                relative_or_absolute_fs(&placeholder, repo_root),
686                vec![],
687            ));
688        }
689
690        Ok(files)
691    }
692
693    fn plan_hook(
694        &self,
695        capability: &ResolvedCapability,
696        repo_root: &Path,
697    ) -> Result<Vec<PlannedFile>> {
698        let CapabilityKind::Hook { hook } = &capability.kind else {
699            return Err(TuffError::new("plan_hook called on non-hook capability"));
700        };
701
702        match hook {
703            HookDefinition::Command(hook_cfg) => {
704                let render = self.render_standard_hook(HookRenderContext {
705                    capability_id: &capability.id,
706                    hook: hook_cfg,
707                    source_files: &capability.source_files,
708                    repo_root,
709                    track_managed_hooks: false,
710                })?;
711                Ok(render.files)
712            }
713            HookDefinition::Native(native) => self.plan_native_hook(capability, native, repo_root),
714        }
715    }
716
717    fn plan_native_hook(
718        &self,
719        capability: &ResolvedCapability,
720        native: &NativeHookConfig,
721        repo_root: &Path,
722    ) -> Result<Vec<PlannedFile>> {
723        let hook_root = repo_root
724            .join(self.dir_prefix())
725            .join("hooks")
726            .join(&capability.id);
727        let hook_root_rel = relative_or_absolute_fs(&hook_root, repo_root);
728        let in_harness_source =
729            path_is_under(&capability.source_dir, &repo_root.join(self.dir_prefix()));
730
731        let mut files = Vec::new();
732        if in_harness_source {
733            for (rel_path, content) in &native.source_files {
734                let target_path = capability.source_dir.join(rel_path);
735                files.push(PlannedFile::mergeable(
736                    relative_or_absolute_fs(&target_path, repo_root),
737                    content.clone(),
738                ));
739            }
740        } else {
741            for (rel_path, content) in &native.source_files {
742                let target_path = hook_root.join(rel_path);
743                files.push(PlannedFile::new(
744                    relative_or_absolute_fs(&target_path, repo_root),
745                    content.clone(),
746                ));
747            }
748        }
749
750        let fragment = replace_hook_dir_placeholder(native.fragment.clone(), &hook_root_rel);
751        let settings_relpath = self.hook_settings_relpath();
752        let settings_path = repo_root.join(settings_relpath);
753        let existing = if settings_path.is_file() {
754            Some(std::fs::read(&settings_path)?)
755        } else {
756            None
757        };
758        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;
759        files.push(PlannedFile::mergeable(
760            relative_or_absolute_fs(&settings_path, repo_root),
761            merged,
762        ));
763        Ok(files)
764    }
765
766    /// Emit the canonical `server.toml` record. The JSON entry in the
767    /// harness's MCP config is the artifact the harness reads; this file is
768    /// what gives the capability a tree to hash, so `check`/`diff`/`delete`
769    /// work exactly as they do for every other kind.
770    fn plan_mcp_server(
771        &self,
772        capability: &ResolvedCapability,
773        repo_root: &Path,
774    ) -> Result<Vec<PlannedFile>> {
775        let CapabilityKind::McpServer { server } = &capability.kind else {
776            return Err(TuffError::new(
777                "plan_mcp_server called on non-mcp-server capability",
778            ));
779        };
780
781        let target_path = repo_root
782            .join(self.dir_prefix())
783            .join("mcp-servers")
784            .join(&capability.id)
785            .join("server.toml");
786
787        let content = serialize_mcp_server(capability, server)?;
788
789        Ok(vec![PlannedFile::new(
790            relative_or_absolute_fs(&target_path, repo_root),
791            content,
792        )])
793    }
794
795    /// Emit the canonical `policy.toml` record. The rules the harness reads
796    /// live in its settings file; this record gives the capability a tree
797    /// to hash, so `check`, `diff`, and `delete` treat it like every other
798    /// kind, and `update` can tell when the policy's rules changed.
799    fn plan_policy(
800        &self,
801        capability: &ResolvedCapability,
802        repo_root: &Path,
803    ) -> Result<Vec<PlannedFile>> {
804        let CapabilityKind::Policy { policy } = &capability.kind else {
805            return Err(TuffError::new(
806                "plan_policy called on non-policy capability",
807            ));
808        };
809        let target_path = repo_root
810            .join(self.dir_prefix())
811            .join("policies")
812            .join(&capability.id)
813            .join("policy.toml");
814        let content = serialize_policy(capability, policy)?;
815        Ok(vec![PlannedFile::new(
816            relative_or_absolute_fs(&target_path, repo_root),
817            content,
818        )])
819    }
820
821    fn remove_dir(
822        &self,
823        repo_root: &Path,
824        base: &str,
825        kind: &str,
826        primitive_id: &str,
827    ) -> Result<()> {
828        let dir = repo_root.join(base).join(kind).join(primitive_id);
829
830        if dir.exists() {
831            std::fs::remove_dir_all(&dir)?;
832        }
833
834        let kind_dir = dir.parent().expect("kind dir should have parent");
835        if kind_dir.exists() {
836            let mut rd = match std::fs::read_dir(kind_dir) {
837                Ok(rd) => rd,
838                Err(_) => return Ok(()),
839            };
840            if rd.next().is_none() {
841                std::fs::remove_dir(kind_dir)?;
842            }
843        }
844
845        let base_dir = kind_dir.parent().expect("base dir should have parent");
846        if base_dir.exists() {
847            let mut rd = match std::fs::read_dir(base_dir) {
848                Ok(rd) => rd,
849                Err(_) => return Ok(()),
850            };
851            if rd.next().is_none() {
852                std::fs::remove_dir(base_dir)?;
853            }
854        }
855
856        Ok(())
857    }
858}
859
860fn render_hook_script(hook_cfg: &HookConfig) -> Result<Vec<u8>> {
861    let working_directory = shell_single_quote(&hook_cfg.working_directory)?;
862    let command = shell_single_quote(&hook_cfg.command)?;
863    Ok(format!(
864        "#!/usr/bin/env bash\nset -euo pipefail\ncd -- {working_directory}\nexec bash -euo pipefail -c {command}\n"
865    )
866    .into_bytes())
867}
868
869fn shell_single_quote(value: &str) -> Result<String> {
870    if value.contains('\0') {
871        return Err(TuffError::usage(
872            "hook working directory and command cannot contain NUL bytes",
873        ));
874    }
875    Ok(format!("'{}'", value.replace('\'', "'\"'\"'")))
876}
877
878#[derive(Serialize)]
879struct McpServerDocument<'a> {
880    id: &'a str,
881    version: &'a str,
882    #[serde(rename = "type")]
883    capability_type: CapabilityType,
884    description: &'a str,
885    server: &'a crate::manifest::McpServerConfig,
886}
887
888fn serialize_mcp_server(
889    capability: &ResolvedCapability,
890    server: &crate::manifest::McpServerConfig,
891) -> Result<Vec<u8>> {
892    let document = McpServerDocument {
893        id: &capability.id,
894        version: &capability.version,
895        capability_type: capability.capability_type,
896        description: &capability.description,
897        server,
898    };
899    let mut content = toml::to_string_pretty(&document)?;
900    if !content.ends_with('\n') {
901        content.push('\n');
902    }
903    Ok(content.into_bytes())
904}
905
906#[derive(Serialize)]
907struct PolicyDocument<'a> {
908    id: &'a str,
909    version: &'a str,
910    #[serde(rename = "type")]
911    capability_type: CapabilityType,
912    description: &'a str,
913    policy: &'a crate::policy::PolicyConfig,
914}
915
916fn serialize_policy(
917    capability: &ResolvedCapability,
918    policy: &crate::policy::PolicyConfig,
919) -> Result<Vec<u8>> {
920    let document = PolicyDocument {
921        id: &capability.id,
922        version: &capability.version,
923        capability_type: capability.capability_type,
924        description: &capability.description,
925        policy,
926    };
927    let mut content = toml::to_string_pretty(&document)?;
928    if !content.ends_with('\n') {
929        content.push('\n');
930    }
931    Ok(content.into_bytes())
932}
933
934fn path_is_under(path: &Path, root: &Path) -> bool {
935    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
936    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
937    canonical_path.starts_with(canonical_root)
938}
939
940/// A standard hook with `{{hook_dir}}` in its command replaced by `hook_dir`.
941pub fn with_hook_dir(hook: &HookConfig, hook_dir: &str) -> HookConfig {
942    HookConfig {
943        command: hook.command.replace(HOOK_DIR_PLACEHOLDER, hook_dir),
944        ..hook.clone()
945    }
946}
947
948/// The placeholder for a hook's own folder, in native fragments and in
949/// standard hook commands.
950pub const HOOK_DIR_PLACEHOLDER: &str = "{{hook_dir}}";
951
952pub fn replace_hook_dir_placeholder(
953    mut value: serde_json::Value,
954    hook_dir: &str,
955) -> serde_json::Value {
956    match &mut value {
957        serde_json::Value::String(s) => {
958            *s = s.replace(HOOK_DIR_PLACEHOLDER, hook_dir);
959        }
960        serde_json::Value::Array(items) => {
961            for item in items {
962                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
963            }
964        }
965        serde_json::Value::Object(map) => {
966            for item in map.values_mut() {
967                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
968            }
969        }
970        _ => {}
971    }
972    value
973}
974
975fn relative_or_absolute_fs(path: &Path, repo_root: &Path) -> String {
976    crate::lockfile::relative_or_absolute_fs(path, repo_root)
977}
978
979#[cfg(test)]
980mod tests {
981    use super::*;
982
983    #[cfg(unix)]
984    #[test]
985    fn hook_script_preserves_shell_sensitive_values() {
986        use std::process::Command;
987
988        let temp = tempfile::tempdir().expect("tempdir");
989        let working_directory = temp.path().join("directory with ' quote");
990        std::fs::create_dir(&working_directory).expect("create working directory");
991        let hook = HookConfig {
992            event: "stop".to_string(),
993            command: "printf '%s\\n' 'safe; $HOME `literal`' > result.txt".to_string(),
994            working_directory: working_directory.to_string_lossy().into_owned(),
995        };
996        let script_path = temp.path().join("run.sh");
997        std::fs::write(
998            &script_path,
999            render_hook_script(&hook).expect("render script"),
1000        )
1001        .expect("write script");
1002
1003        let syntax = Command::new("bash")
1004            .arg("-n")
1005            .arg(&script_path)
1006            .status()
1007            .expect("check script syntax");
1008        assert!(syntax.success());
1009        let executed = Command::new("bash")
1010            .arg(&script_path)
1011            .status()
1012            .expect("execute script");
1013        assert!(executed.success());
1014        assert_eq!(
1015            std::fs::read_to_string(working_directory.join("result.txt"))
1016                .expect("read command output"),
1017            "safe; $HOME `literal`\n"
1018        );
1019    }
1020
1021    #[test]
1022    fn hook_script_rejects_nul_bytes() {
1023        let hook = HookConfig {
1024            event: "stop".to_string(),
1025            command: "printf '\0'".to_string(),
1026            working_directory: ".".to_string(),
1027        };
1028
1029        assert!(render_hook_script(&hook).is_err());
1030    }
1031}