tuff-core 0.1.0

Core lifecycle engine and adapter contract for Tuff.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use tuff_hooks_spec::{CompatibilityMatrix, CoverageLevel};

use crate::error::{Result, TuffError};
use crate::manifest::{CapabilityManifest, CapabilityType, HookConfig};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmittedFile {
    pub path: String,
    pub hash: String,
    #[serde(rename = "baselineHash")]
    pub baseline_hash: String,
}

#[derive(Debug, Clone)]
pub struct PlannedFile {
    pub path: String,
    pub content: Vec<u8>,
    pub allow_existing: bool,
}

impl PlannedFile {
    pub fn new(path: String, content: Vec<u8>) -> Self {
        Self {
            path,
            content,
            allow_existing: false,
        }
    }

    pub fn mergeable(path: String, content: Vec<u8>) -> Self {
        Self {
            path,
            content,
            allow_existing: true,
        }
    }
}

#[derive(Debug, Clone)]
pub struct NativeHookConfig {
    pub fragment: serde_json::Value,
    pub source_files: Vec<(String, Vec<u8>)>,
}

#[derive(Debug, Clone)]
pub enum HookRenderDiagnosticLevel {
    Warning,
}

#[derive(Debug, Clone)]
pub struct HookRenderDiagnostic {
    pub level: HookRenderDiagnosticLevel,
    pub message: String,
}

#[derive(Debug, Clone)]
pub struct HookRenderContext<'a> {
    pub capability_id: &'a str,
    pub hook: &'a HookConfig,
    pub source_files: &'a [(String, Vec<u8>)],
    pub repo_root: &'a Path,
    pub track_managed_hooks: bool,
}

#[derive(Debug, Clone)]
pub struct HookRenderPlan {
    pub files: Vec<PlannedFile>,
    pub managed_hooks: Vec<crate::lockfile::ManagedHook>,
    pub diagnostics: Vec<HookRenderDiagnostic>,
}

#[derive(Debug, Clone)]
pub enum HookDefinition {
    Command(crate::manifest::HookConfig),
    Native(NativeHookConfig),
}

#[derive(Debug, Clone)]
pub enum CapabilityKind {
    Skill,
    Tool {
        parameters: serde_json::Value,
        implementation: crate::manifest::ImplementationConfig,
    },
    Hook {
        hook: HookDefinition,
    },
    Workflow {
        workflow: crate::manifest::WorkflowConfig,
    },
}

impl CapabilityKind {
    pub fn capability_type(&self) -> CapabilityType {
        match self {
            Self::Skill => CapabilityType::Skill,
            Self::Tool { .. } => CapabilityType::Tool,
            Self::Hook { .. } => CapabilityType::Hook,
            Self::Workflow { .. } => CapabilityType::Workflow,
        }
    }
}

pub struct ResolvedCapability {
    pub id: String,
    pub capability_type: CapabilityType,
    pub version: String,
    pub description: String,
    pub source_files: Vec<(String, Vec<u8>)>,
    pub source_dir: PathBuf,
    pub kind: CapabilityKind,
}

pub fn resolve_capability(manifest: &CapabilityManifest) -> Result<ResolvedCapability> {
    let source_files = manifest.read_source_contents_with_names()?;
    let kind =
        match manifest.capability_type {
            CapabilityType::Skill => CapabilityKind::Skill,
            CapabilityType::Tool => CapabilityKind::Tool {
                parameters: manifest.parameters.clone().ok_or_else(|| {
                    TuffError::new("tool capability requires [parameters] section")
                })?,
                implementation: manifest.implementation.clone().ok_or_else(|| {
                    TuffError::new("tool capability requires [implementation] section")
                })?,
            },
            CapabilityType::Hook => {
                CapabilityKind::Hook {
                    hook: HookDefinition::Command(manifest.hook.clone().ok_or_else(|| {
                        TuffError::new("hook capability requires [hook] section")
                    })?),
                }
            }
            CapabilityType::Workflow => CapabilityKind::Workflow {
                workflow: manifest.workflow.clone().ok_or_else(|| {
                    TuffError::new("workflow capability requires [workflow] section")
                })?,
            },
            CapabilityType::Policy => {
                return Err(TuffError::new(
                    "policy capabilities are not installable yet",
                ));
            }
        };
    Ok(ResolvedCapability {
        id: manifest.id.clone(),
        capability_type: manifest.capability_type,
        version: manifest.version.clone(),
        description: manifest.description.clone(),
        source_files,
        source_dir: manifest.root.clone(),
        kind,
    })
}

pub trait AgentAdapter {
    fn id(&self) -> &'static str;
    fn display_name(&self) -> &'static str;
    fn dir_prefix(&self) -> &'static str;
    fn mcp_config_relpath(&self) -> &'static str;
    fn supported_agents(&self) -> &[&'static str];
    fn hook_compatibility(&self) -> &'static CompatibilityMatrix;
    fn hook_settings_relpath(&self) -> &'static str;
    fn scaffold_hook_event(&self) -> &'static str;
    fn hook_filename(&self) -> &'static str;
    fn hook_file_content(&self, hook_cfg: &crate::manifest::HookConfig) -> Result<Vec<u8>>;
    fn render_standard_hook(&self, context: HookRenderContext<'_>) -> Result<HookRenderPlan> {
        let matrix = self.hook_compatibility();
        let Some(entry) = matrix.find_event(&context.hook.event) else {
            return Err(TuffError::new(format!(
                "{} does not support hook event '{}'. Supported events: {}",
                self.display_name(),
                context.hook.event,
                matrix.supported_native_events().join(", ")
            )));
        };
        let Some(native_event) = entry.native_event_name() else {
            let suffix = entry
                .caveat
                .map(|caveat| format!(": {caveat}"))
                .unwrap_or_default();
            return Err(TuffError::new(format!(
                "{} does not support hook event '{}'{}",
                self.display_name(),
                context.hook.event,
                suffix
            )));
        };

        let command = format!(
            "sh {}/hooks/{}/{}",
            self.dir_prefix(),
            context.capability_id,
            self.hook_filename()
        );
        let target_path = context
            .repo_root
            .join(self.dir_prefix())
            .join("hooks")
            .join(context.capability_id)
            .join(self.hook_filename());
        let script = self.hook_file_content(context.hook)?;
        let settings_relpath = self.hook_settings_relpath();
        let fragment = self.command_hook_fragment(native_event, &command);
        let settings_path = context.repo_root.join(settings_relpath);
        let existing = if settings_path.is_file() {
            Some(std::fs::read(&settings_path)?)
        } else {
            None
        };
        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;

        let mut files = vec![PlannedFile::new(
            relative_or_absolute_fs(&target_path, context.repo_root),
            script,
        )];
        for (relative, content) in context.source_files {
            let path = context
                .repo_root
                .join(self.dir_prefix())
                .join("hooks")
                .join(context.capability_id)
                .join(relative);
            files.push(PlannedFile::new(
                relative_or_absolute_fs(&path, context.repo_root),
                content.clone(),
            ));
        }
        files.push(PlannedFile::mergeable(
            relative_or_absolute_fs(&settings_path, context.repo_root),
            merged,
        ));

        let mut diagnostics = Vec::new();
        if entry.coverage == CoverageLevel::Partial {
            let scope = if entry.scope.is_empty() {
                "partial coverage".to_string()
            } else {
                format!("scope: {}", entry.scope.join(", "))
            };
            let caveat = entry
                .caveat
                .map(|caveat| format!("; {caveat}"))
                .unwrap_or_default();
            diagnostics.push(HookRenderDiagnostic {
                level: HookRenderDiagnosticLevel::Warning,
                message: format!(
                    "{} renders '{}' with partial compatibility ({scope}{caveat})",
                    self.display_name(),
                    entry.event
                ),
            });
        }

        let managed_hooks = if context.track_managed_hooks {
            crate::lockfile::managed_hooks_from_fragment_with_canonical(
                context.repo_root,
                settings_relpath,
                &fragment,
                Some(entry.event.as_str()),
            )?
        } else {
            Vec::new()
        };

        Ok(HookRenderPlan {
            files,
            managed_hooks,
            diagnostics,
        })
    }
    fn command_hook_fragment(&self, native_event: &str, command: &str) -> serde_json::Value;
    fn merge_hook_fragment(
        &self,
        existing: Option<&[u8]>,
        fragment: &serde_json::Value,
    ) -> Result<Vec<u8>>;
    fn remove_hook_settings(
        &self,
        repo_root: &Path,
        managed_hooks: &[crate::lockfile::ManagedHook],
    ) -> Result<()>;
    fn detect(&self, repo_root: &Path) -> bool;

    fn kinds_supported(&self) -> &[CapabilityType];

    fn supports(&self, capability_type: CapabilityType) -> bool {
        self.kinds_supported().contains(&capability_type)
    }

    fn native_hook_event(&self, raw_event: &str) -> Result<&'static str> {
        let matrix = self.hook_compatibility();
        let Some(entry) = matrix.find_event(raw_event) else {
            return Err(TuffError::new(format!(
                "{} does not support hook event '{}'. Supported events: {}",
                self.display_name(),
                raw_event,
                matrix.supported_native_events().join(", ")
            )));
        };
        entry.native_event_name().ok_or_else(|| {
            let suffix = entry
                .caveat
                .map(|caveat| format!(": {caveat}"))
                .unwrap_or_default();
            TuffError::new(format!(
                "{} does not support hook event '{}'{}",
                self.display_name(),
                raw_event,
                suffix
            ))
        })
    }

    fn canonical_hook_event(&self, raw_event: &str) -> Result<&'static str> {
        let matrix = self.hook_compatibility();
        let Some(entry) = matrix.find_event(raw_event) else {
            return Err(TuffError::new(format!(
                "{} does not support hook event '{}'",
                self.display_name(),
                raw_event
            )));
        };
        entry
            .coverage
            .is_supported()
            .then_some(entry.event.as_str())
            .ok_or_else(|| {
                let suffix = entry
                    .caveat
                    .map(|caveat| format!(": {caveat}"))
                    .unwrap_or_default();
                TuffError::new(format!(
                    "{} does not support hook event '{}'{}",
                    self.display_name(),
                    raw_event,
                    suffix
                ))
            })
    }

    fn ensure_project_dir(&self, repo_root: &Path) -> std::io::Result<()> {
        std::fs::create_dir_all(repo_root.join(self.dir_prefix()))
    }

    fn plan(&self, capability: &ResolvedCapability, repo_root: &Path) -> Result<Vec<PlannedFile>> {
        match capability.capability_type {
            CapabilityType::Tool => self.plan_tool(capability, repo_root),
            CapabilityType::Hook => self.plan_hook(capability, repo_root),
            CapabilityType::Workflow => self.plan_workflow(capability, repo_root),
            CapabilityType::Policy => Err(TuffError::new(
                "policy capabilities are not installable yet",
            )),
            _ => self.plan_skill(capability, repo_root),
        }
    }

    fn remove(
        &self,
        primitive_id: &str,
        repo_root: &Path,
        managed_hooks: &[crate::lockfile::ManagedHook],
    ) -> Result<()> {
        let prefix = self.dir_prefix();
        for kind in &["skills", "tools", "hooks", "workflows"] {
            self.remove_dir(repo_root, prefix, kind, primitive_id)?;
        }
        crate::mcp::remove_tool(&repo_root.join(self.mcp_config_relpath()), primitive_id)?;
        self.remove_hook_settings(repo_root, managed_hooks)?;
        Ok(())
    }

    // ── internal helpers ───────────────────────────────────────────────

    fn plan_skill(
        &self,
        capability: &ResolvedCapability,
        repo_root: &Path,
    ) -> Result<Vec<PlannedFile>> {
        if capability.source_files.is_empty() {
            return Err(TuffError::new("no source files to emit"));
        }

        let mut files = Vec::new();
        for (rel_path, content) in &capability.source_files {
            let target_path = repo_root
                .join(self.dir_prefix())
                .join("skills")
                .join(&capability.id)
                .join(rel_path);

            files.push(PlannedFile::new(
                relative_or_absolute_fs(&target_path, repo_root),
                content.clone(),
            ));
        }
        Ok(files)
    }

    fn plan_tool(
        &self,
        capability: &ResolvedCapability,
        repo_root: &Path,
    ) -> Result<Vec<PlannedFile>> {
        let mut files = Vec::new();

        for (rel_path, content) in &capability.source_files {
            let target_path = repo_root
                .join(self.dir_prefix())
                .join("tools")
                .join(&capability.id)
                .join(rel_path);

            files.push(PlannedFile::new(
                relative_or_absolute_fs(&target_path, repo_root),
                content.clone(),
            ));
        }

        if capability.source_files.is_empty() {
            let placeholder = repo_root
                .join(self.dir_prefix())
                .join("tools")
                .join(&capability.id)
                .join(".gitkeep");
            files.push(PlannedFile::new(
                relative_or_absolute_fs(&placeholder, repo_root),
                vec![],
            ));
        }

        Ok(files)
    }

    fn plan_hook(
        &self,
        capability: &ResolvedCapability,
        repo_root: &Path,
    ) -> Result<Vec<PlannedFile>> {
        let CapabilityKind::Hook { hook } = &capability.kind else {
            return Err(TuffError::new("plan_hook called on non-hook capability"));
        };

        match hook {
            HookDefinition::Command(hook_cfg) => {
                let render = self.render_standard_hook(HookRenderContext {
                    capability_id: &capability.id,
                    hook: hook_cfg,
                    source_files: &capability.source_files,
                    repo_root,
                    track_managed_hooks: false,
                })?;
                Ok(render.files)
            }
            HookDefinition::Native(native) => self.plan_native_hook(capability, native, repo_root),
        }
    }

    fn plan_native_hook(
        &self,
        capability: &ResolvedCapability,
        native: &NativeHookConfig,
        repo_root: &Path,
    ) -> Result<Vec<PlannedFile>> {
        let hook_root = repo_root
            .join(self.dir_prefix())
            .join("hooks")
            .join(&capability.id);
        let hook_root_rel = relative_or_absolute_fs(&hook_root, repo_root);
        let in_harness_source =
            path_is_under(&capability.source_dir, &repo_root.join(self.dir_prefix()));

        let mut files = Vec::new();
        if in_harness_source {
            for (rel_path, content) in &native.source_files {
                let target_path = capability.source_dir.join(rel_path);
                files.push(PlannedFile::mergeable(
                    relative_or_absolute_fs(&target_path, repo_root),
                    content.clone(),
                ));
            }
        } else {
            for (rel_path, content) in &native.source_files {
                let target_path = hook_root.join(rel_path);
                files.push(PlannedFile::new(
                    relative_or_absolute_fs(&target_path, repo_root),
                    content.clone(),
                ));
            }
        }

        let fragment = replace_hook_dir_placeholder(native.fragment.clone(), &hook_root_rel);
        let settings_relpath = self.hook_settings_relpath();
        let settings_path = repo_root.join(settings_relpath);
        let existing = if settings_path.is_file() {
            Some(std::fs::read(&settings_path)?)
        } else {
            None
        };
        let merged = self.merge_hook_fragment(existing.as_deref(), &fragment)?;
        files.push(PlannedFile::mergeable(
            relative_or_absolute_fs(&settings_path, repo_root),
            merged,
        ));
        Ok(files)
    }

    fn plan_workflow(
        &self,
        capability: &ResolvedCapability,
        repo_root: &Path,
    ) -> Result<Vec<PlannedFile>> {
        let CapabilityKind::Workflow { workflow: wf } = &capability.kind else {
            return Err(TuffError::new(
                "plan_workflow called on non-workflow capability",
            ));
        };

        let target_path = repo_root
            .join(self.dir_prefix())
            .join("workflows")
            .join(&capability.id)
            .join("workflow.toml");

        let mut content = format!(
            "id = \"{}\"\nversion = \"{}\"\ntype = \"workflow\"\ndescription = \"{}\"\n",
            capability.id, capability.version, capability.description
        );
        for req in &wf.requires {
            content.push_str(&format!(
                "[[workflow.requires]]\nid = \"{}\"\ntype = \"{}\"\n",
                req.id, req.capability_type
            ));
        }

        Ok(vec![PlannedFile::new(
            relative_or_absolute_fs(&target_path, repo_root),
            content.into_bytes(),
        )])
    }

    fn remove_dir(
        &self,
        repo_root: &Path,
        base: &str,
        kind: &str,
        primitive_id: &str,
    ) -> Result<()> {
        let dir = repo_root.join(base).join(kind).join(primitive_id);

        if dir.exists() {
            std::fs::remove_dir_all(&dir)?;
        }

        let kind_dir = dir.parent().expect("kind dir should have parent");
        if kind_dir.exists() {
            let mut rd = match std::fs::read_dir(kind_dir) {
                Ok(rd) => rd,
                Err(_) => return Ok(()),
            };
            if rd.next().is_none() {
                std::fs::remove_dir(kind_dir)?;
            }
        }

        let base_dir = kind_dir.parent().expect("base dir should have parent");
        if base_dir.exists() {
            let mut rd = match std::fs::read_dir(base_dir) {
                Ok(rd) => rd,
                Err(_) => return Ok(()),
            };
            if rd.next().is_none() {
                std::fs::remove_dir(base_dir)?;
            }
        }

        Ok(())
    }
}

fn path_is_under(path: &Path, root: &Path) -> bool {
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    canonical_path.starts_with(canonical_root)
}

pub fn replace_hook_dir_placeholder(
    mut value: serde_json::Value,
    hook_dir: &str,
) -> serde_json::Value {
    match &mut value {
        serde_json::Value::String(s) => {
            *s = s.replace("{{hook_dir}}", hook_dir);
        }
        serde_json::Value::Array(items) => {
            for item in items {
                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
            }
        }
        serde_json::Value::Object(map) => {
            for item in map.values_mut() {
                *item = replace_hook_dir_placeholder(item.take(), hook_dir);
            }
        }
        _ => {}
    }
    value
}

fn relative_or_absolute_fs(path: &Path, repo_root: &Path) -> String {
    crate::lockfile::relative_or_absolute_fs(path, repo_root)
}