zeph 0.21.4

Lightweight AI agent with hybrid inference, skills-first architecture, and multi-channel I/O
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::cli::SkillCommand;

#[allow(clippy::too_many_lines)]
pub(crate) async fn handle_skill_command(
    cmd: SkillCommand,
    config_path: Option<&std::path::Path>,
) -> anyhow::Result<()> {
    use crate::bootstrap::{managed_skills_dir, resolve_config_path};
    use std::collections::HashMap;
    use zeph_skills::manager::SkillManager;

    let config_file = resolve_config_path(config_path);
    let config = zeph_core::config::Config::load(&config_file).unwrap_or_default();

    let managed_dir = managed_skills_dir();
    std::fs::create_dir_all(&managed_dir)
        .map_err(|e| anyhow::anyhow!("failed to create managed skills dir: {e}"))?;

    let mgr = SkillManager::new(managed_dir.clone());

    let sqlite_path = crate::db_url::resolve_db_url(&config).to_owned();

    match cmd {
        SkillCommand::Install { source } => {
            let result = if source.starts_with("http://")
                || source.starts_with("https://")
                || source.starts_with("git@")
            {
                mgr.install_from_url(&source)
            } else {
                mgr.install_from_path(std::path::Path::new(&source))
            }
            .map_err(|e| anyhow::anyhow!("{e}"))?;

            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
            let (source_kind, source_url, source_path) = match &result.source {
                zeph_skills::SkillSource::Hub { url } => (
                    zeph_memory::store::SourceKind::Hub,
                    Some(url.as_str()),
                    None,
                ),
                zeph_skills::SkillSource::File { path } => (
                    zeph_memory::store::SourceKind::File,
                    None,
                    Some(path.to_string_lossy().into_owned()),
                ),
                zeph_skills::SkillSource::Local => {
                    (zeph_memory::store::SourceKind::Local, None, None)
                }
                _ => (zeph_memory::store::SourceKind::Local, None, None),
            };
            store
                .upsert_skill_trust(
                    &result.name,
                    zeph_common::SkillTrustLevel::Quarantined,
                    source_kind,
                    source_url,
                    source_path.as_deref(),
                    &result.blake3_hash,
                )
                .await
                .map_err(|e| anyhow::anyhow!("trust upsert failed: {e}"))?;

            println!(
                "Installed skill \"{}\" (hash: {}..., trust: quarantined)",
                result.name,
                &result.blake3_hash[..8]
            );

            let skill_md = managed_dir.join(&result.name).join("SKILL.md");
            if let Ok(meta) = zeph_skills::loader::load_skill_meta(&skill_md)
                && !meta.requires_secrets.is_empty()
            {
                println!(
                    "  Note: this skill requires secrets: {}",
                    meta.requires_secrets.join(", ")
                );
                println!("  Run `zeph vault set ZEPH_SECRET_<NAME> <value>` for each.");
            }
        }

        SkillCommand::Remove { name } => {
            mgr.remove(&name).map_err(|e| anyhow::anyhow!("{e}"))?;

            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
            store
                .delete_skill_trust(&name)
                .await
                .map_err(|e| anyhow::anyhow!("trust delete failed: {e}"))?;
            println!("Removed skill \"{name}\".");
        }

        SkillCommand::List => {
            let installed = mgr.list_installed().map_err(|e| anyhow::anyhow!("{e}"))?;
            if installed.is_empty() {
                println!("No skills installed in {}.", managed_dir.display());
                return Ok(());
            }
            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
            println!("Installed skills ({}):\n", installed.len());
            for skill in &installed {
                let trust = store
                    .load_skill_trust(&skill.name)
                    .await
                    .ok()
                    .flatten()
                    .map_or_else(
                        || "no trust record".to_owned(),
                        |r| r.trust_level.to_string(),
                    );
                if skill.requires_secrets.is_empty() {
                    println!("  {}{} [{}]", skill.name, skill.description, trust);
                } else {
                    println!(
                        "  {}{} [{}] (requires: {})",
                        skill.name,
                        skill.description,
                        trust,
                        skill.requires_secrets.join(", "),
                    );
                }
            }
        }

        SkillCommand::Verify { name } => {
            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;

            if let Some(name) = name {
                let current_hash = mgr.verify(&name).map_err(|e| anyhow::anyhow!("{e}"))?;
                let stored = store
                    .load_skill_trust(&name)
                    .await
                    .ok()
                    .flatten()
                    .map(|r| r.blake3_hash);
                match stored {
                    Some(ref h) if h == &current_hash => {
                        println!("{name}: OK (hash matches)");
                    }
                    Some(_) => {
                        println!("{name}: MISMATCH (hash changed, setting to quarantined)");
                        store
                            .set_skill_trust_level(&name, zeph_common::SkillTrustLevel::Quarantined)
                            .await
                            .map_err(|e| anyhow::anyhow!("trust update failed: {e}"))?;
                        store
                            .update_skill_hash(&name, &current_hash)
                            .await
                            .map_err(|e| anyhow::anyhow!("hash update failed: {e}"))?;
                    }
                    None => {
                        println!("{name}: no stored hash (hash: {}...)", &current_hash[..8]);
                    }
                }
            } else {
                // Verify all.
                let rows = store
                    .load_all_skill_trust()
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                let stored_hashes: HashMap<String, String> = rows
                    .into_iter()
                    .map(|r| (r.skill_name, r.blake3_hash))
                    .collect();
                let results = mgr
                    .verify_all(&stored_hashes)
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                for r in &results {
                    match r.stored_hash_matches {
                        Some(true) => println!("{}: OK", r.name),
                        Some(false) => {
                            println!("{}: MISMATCH (setting to quarantined)", r.name);
                            store
                                .set_skill_trust_level(
                                    &r.name,
                                    zeph_common::SkillTrustLevel::Quarantined,
                                )
                                .await
                                .map_err(|e| anyhow::anyhow!("trust update failed: {e}"))?;
                            store
                                .update_skill_hash(&r.name, &r.current_hash)
                                .await
                                .map_err(|e| anyhow::anyhow!("hash update failed: {e}"))?;
                        }
                        None => println!("{}: no stored hash", r.name),
                    }
                }
            }
        }

        SkillCommand::Trust { name, level } => {
            let trust_level = level.parse::<zeph_common::SkillTrustLevel>().map_err(|_| {
                anyhow::anyhow!(
                    "invalid trust level: {level}. Use: trusted, verified, quarantined, blocked"
                )
            })?;

            // REV-003: re-verify hash before promoting to trusted/verified.
            if matches!(
                trust_level,
                zeph_common::SkillTrustLevel::Trusted | zeph_common::SkillTrustLevel::Verified
            ) {
                let managed_dir = crate::bootstrap::managed_skills_dir();
                let mgr = zeph_skills::manager::SkillManager::new(managed_dir.clone());
                let name_clone = name.clone();
                let current_hash = tokio::task::spawn_blocking(move || mgr.verify(&name_clone))
                    .await
                    .map_err(|e| anyhow::anyhow!("spawn_blocking failed: {e}"))??;

                let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                    .await
                    .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
                let row = store
                    .load_skill_trust(&name)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                match row {
                    None => anyhow::bail!("skill \"{name}\" not found in trust database"),
                    Some(r) if r.blake3_hash != current_hash => {
                        anyhow::bail!(
                            "hash mismatch for \"{name}\" — run `zeph skill verify {name}` first"
                        );
                    }
                    Some(_) => {}
                }

                let updated = store
                    .set_skill_trust_level(&name, trust_level)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                if updated {
                    println!("Trust level for \"{name}\" set to {trust_level}.");
                } else {
                    anyhow::bail!("skill \"{name}\" not found in trust database");
                }
            } else {
                let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                    .await
                    .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
                let updated = store
                    .set_skill_trust_level(&name, trust_level)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                if updated {
                    println!("Trust level for \"{name}\" set to {trust_level}.");
                } else {
                    anyhow::bail!("skill \"{name}\" not found in trust database");
                }
            }
        }

        SkillCommand::Block { name } => {
            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
            let updated = store
                .set_skill_trust_level(&name, zeph_common::SkillTrustLevel::Blocked)
                .await
                .map_err(|e| anyhow::anyhow!("{e}"))?;
            if updated {
                println!("Skill \"{name}\" blocked.");
            } else {
                anyhow::bail!("skill \"{name}\" not found in trust database");
            }
        }

        SkillCommand::Unblock { name } => {
            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
            let updated = store
                .set_skill_trust_level(&name, zeph_common::SkillTrustLevel::Quarantined)
                .await
                .map_err(|e| anyhow::anyhow!("{e}"))?;
            if updated {
                println!("Skill \"{name}\" unblocked (set to quarantined).");
            } else {
                anyhow::bail!("skill \"{name}\" not found in trust database");
            }
        }

        SkillCommand::Invoke { name, args } => {
            use zeph_common::SkillTrustLevel;
            use zeph_skills::prompt::{sanitize_skill_text, wrap_quarantined};

            let registry = zeph_skills::registry::SkillRegistry::load(&[managed_dir]);

            // Resolve persisted trust from SQLite. No trust row → Quarantined (fail-closed,
            // matches `SkillTrustLevel::default`).
            let trust = {
                let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                    .await
                    .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;
                store
                    .load_skill_trust(&name)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?
                    .map(|r| r.trust_level)
                    .unwrap_or_default()
            };

            if trust == SkillTrustLevel::Blocked {
                anyhow::bail!("skill is blocked by policy: {name}");
            }

            let raw = registry
                .body(&name)
                .map_err(|e| anyhow::anyhow!("{e}"))?
                .to_owned();

            let sanitized = if trust == SkillTrustLevel::Trusted {
                raw
            } else {
                sanitize_skill_text(&raw)
            };
            let body = if trust == SkillTrustLevel::Quarantined {
                wrap_quarantined(&name, &sanitized)
            } else {
                sanitized
            };

            match args {
                Some(a) => {
                    let args_safe = sanitize_skill_text(&a);
                    println!("{body}\n\n<args>\n{args_safe}\n</args>");
                }
                None => println!("{body}"),
            }
        }

        SkillCommand::PromoteHeuristics { skill } => {
            use zeph_skills::promoter::{build_promotion_prompt, compute_batch_hash};

            let store = zeph_memory::store::SqliteStore::new(&sqlite_path)
                .await
                .map_err(|e| anyhow::anyhow!("failed to open SQLite: {e}"))?;

            let erl_min_confidence = config.skills.learning.erl_min_confidence;
            let threshold = config.skills.learning.heuristic_promotion_threshold;

            let candidates: Vec<(String, i64)> = if let Some(ref name) = skill {
                // Single skill: load count directly.
                let texts = store
                    .load_heuristic_texts_for_promotion(name, erl_min_confidence)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                let count = u32::try_from(texts.len()).unwrap_or(u32::MAX);
                if count < threshold {
                    println!(
                        "Skill \"{name}\" has {} heuristics (threshold: {threshold}), skipping.",
                        texts.len()
                    );
                    return Ok(());
                }
                vec![(name.clone(), i64::try_from(texts.len()).unwrap_or(i64::MAX))]
            } else {
                store
                    .count_heuristics_by_skill(erl_min_confidence, threshold)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?
            };

            if candidates.is_empty() {
                println!("No skills qualify for heuristic promotion (threshold: {threshold}).");
                return Ok(());
            }

            println!("Qualifying skills: {}", candidates.len());
            for (skill_name, count) in &candidates {
                let heuristics = store
                    .load_heuristic_texts_for_promotion(skill_name, erl_min_confidence)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;
                let batch_hash = compute_batch_hash(&heuristics);

                let already = store
                    .promotion_already_evaluated(skill_name, &batch_hash)
                    .await
                    .map_err(|e| anyhow::anyhow!("{e}"))?;

                if already {
                    println!(
                        "  {skill_name}: already evaluated (batch_hash={batch_hash:.8}…), skipping."
                    );
                    continue;
                }

                let skill_md_path = managed_dir.join(skill_name).join("SKILL.md");
                let parent_body = match tokio::fs::read_to_string(&skill_md_path).await {
                    Ok(b) => b,
                    Err(e) => {
                        println!("  {skill_name}: skill file not found ({e}), skipping.");
                        continue;
                    }
                };

                let prompt = build_promotion_prompt(&parent_body, &heuristics);
                println!(
                    "  {skill_name}: {count} heuristics, batch_hash={batch_hash:.8}\n  Prompt preview (first 200 chars): {}",
                    &prompt[..prompt.len().min(200)]
                );

                // Dry-run: show what would be evaluated. A live LLM call requires
                // the agent (use `zeph run` with `heuristic_promotion_enabled = true`).
                println!(
                    "  → Use `zeph run` with heuristic_promotion_enabled=true to trigger live LLM evaluation."
                );
            }
        }
    }

    Ok(())
}