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