v1.31.0
hookSessionStart[*]informa

skill-guard

Verifica el invariante "un workflow nunca se dispara solo" en las skills instaladas

SessionStartevento
*matcher
informapolítica
5 stimeout
2026-09-22último cambio

Qué comprueba

Motivo (ADR-022): la garantia de que las skills de workflow (commits, despliegues, scaffolding) solo las lanza el usuario descansa en el flag disable-model-invocation: true de su frontmatter y en que metadata.kind lo declare. Si una version del runtime, una edicion local o una copia parcial del plugin deja un workflow sin el flag, nada mas lo detectaria. Este hook recorre las skills del plugin instalado (o de .claude/skills en modo en-repo) y avisa en stdout (contexto de Claude) si alguna declara kind: workflow sin el flag, o si kind y flags no coinciden. Se ejecuta como mucho una vez al dia por proyecto (cache en _hilo/.skill-guard.json). Silencioso si todo esta bien.

Códigos de salida

ExitSignificado
0siempre (informa; nunca bloquea)

Política

Informa: nunca bloquea.

ClaveTipoDefaultQué hace
hooks.policystring"warn"WARN-first por defecto (avisan sin bloquear); 'block' eleva todos los hooks defensivos a bloqueo. Los hooks intrinsecamente BLOCK (bash-guard, protect-files certs/keys, hilo-json-guard) no se degradan nunca.
hooks.blockListarray[]Hooks concretos elevados a BLOCK aunque policy=warn (ej. ['secret-scanner']).

Código fuente

skill-guard.js · 83 líneas
#!/usr/bin/env node
// skill-guard.js - Verifica el invariante "un workflow nunca se dispara solo" en las skills instaladas
// Evento: SessionStart
// Exit 0 = siempre (informa; nunca bloquea)
//
// Motivo (ADR-022): la garantia de que las skills de workflow (commits, despliegues, scaffolding) solo las lanza el
// usuario descansa en el flag `disable-model-invocation: true` de su frontmatter y en que `metadata.kind` lo declare.
// Si una version del runtime, una edicion local o una copia parcial del plugin deja un workflow sin el flag, nada mas lo
// detectaria. Este hook recorre las skills del plugin instalado (o de .claude/skills en modo en-repo) y avisa en stdout
// (contexto de Claude) si alguna declara `kind: workflow` sin el flag, o si kind y flags no coinciden.
// Se ejecuta como mucho una vez al dia por proyecto (cache en _hilo/.skill-guard.json). Silencioso si todo esta bien.

'use strict';

const fs = require('fs');
const path = require('path');
const h = require(path.join(__dirname, 'lib', 'helpers'));

const KINDS = ['knowledge', 'workflow', 'rule'];

function frontmatter(md) {
  const m = md.replace(/\r\n/g, '\n').match(/^---\n([\s\S]*?)\n---/);
  const fm = {}, metadata = {};
  if (!m) return { fm, metadata };
  let cur = null, inMeta = false;
  for (const line of m[1].split('\n')) {
    const top = line.match(/^([A-Za-z_-]+):\s*(.*)$/);
    if (top) { cur = top[1]; inMeta = cur === 'metadata'; fm[cur] = top[2].trim(); continue; }
    const nested = line.match(/^  ([A-Za-z_-]+):\s*(.*)$/);
    if (inMeta && nested) { metadata[nested[1]] = nested[2].replace(/^["']|["']$/g, '').trim(); continue; }
    // valor multilinea (lista YAML como `paths:` o bloque `description: |`): se acumula en la clave abierta
    if (cur && !inMeta && /^\s+\S/.test(line)) fm[cur] = (fm[cur] ? fm[cur] + ' ' : '') + line.trim();
  }
  return { fm, metadata };
}

function skillsRoot(projectDir) {
  // plugin instalado (CLAUDE_PLUGIN_ROOT lo fija el runtime al ejecutar hooks del plugin); si no, modo en-repo
  const candidates = [process.env.CLAUDE_PLUGIN_ROOT && path.join(process.env.CLAUDE_PLUGIN_ROOT, 'skills'), path.join(__dirname, '..', 'skills'), path.join(projectDir, '.claude', 'skills')].filter(Boolean);
  return candidates.find(p => fs.existsSync(p)) || null;
}

function main() {
  const projectDir = h.projectDir();
  const cacheFile = path.join(projectDir, '_hilo', '.skill-guard.json');
  const cache = h.readJsonSafe(cacheFile);
  if (cache && cache.ultimaVerificacion) {
    const last = new Date(cache.ultimaVerificacion);
    if (!Number.isNaN(last.getTime()) && Date.now() < last.getTime() + 24 * 3600000 && !cache.problemas) return 0;
  }
  const root = skillsRoot(projectDir);
  if (!root) return 0;
  const problems = [];
  let workflows = 0;
  for (const d of fs.readdirSync(root, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name).sort()) {
    const f = path.join(root, d, 'SKILL.md');
    if (!fs.existsSync(f)) continue;
    let text; try { text = fs.readFileSync(f, 'utf8'); } catch { continue; }
    const { fm, metadata } = frontmatter(text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text);
    const userOnly = /^(true|yes|on|1)$/i.test(fm['disable-model-invocation'] || '');
    const porRuta = typeof fm.paths === 'string' && fm.paths !== '' && fm.paths !== '[]';
    const implied = userOnly ? 'workflow' : porRuta ? 'rule' : 'knowledge';
    const declared = metadata.kind || null;
    if (declared === 'workflow') workflows++;
    if (declared === 'workflow' && !userOnly) problems.push(d + ': declara kind workflow pero NO lleva disable-model-invocation: true (el modelo podria lanzarla)');
    else if (declared && KINDS.includes(declared) && declared !== implied) problems.push(d + ': kind ' + declared + ' pero los flags implican ' + implied);
    else if (declared && !KINDS.includes(declared)) problems.push(d + ': kind "' + declared + '" desconocido');
    if (fm.globs !== undefined) problems.push(d + ': usa globs: (inerte); el scoping por ruta es paths:');
  }
  if (problems.length) {
    console.log('[hv] skill-guard: ' + problems.length + h.txt(' skill(s) rompen el invariante "un workflow nunca se dispara solo" (',
                                                                  ' skill(s) break the invariant "a workflow never fires on its own" (') + path.relative(projectDir, root) + '):');
    for (const p of problems.slice(0, 10)) console.log('[hv]   - ' + p);
    if (problems.length > 10) console.log('[hv]   ' + h.txt('... y ', '... and ') + (problems.length - 10) + h.txt(' mas', ' more'));
    console.log(h.txt('[hv]   Revisa el frontmatter o reinstala el plugin (claude plugin update hv@ovillo).',
                      '[hv]   Check the frontmatter or reinstall the plugin (claude plugin update hv@ovillo).'));
  }
  if (fs.existsSync(path.join(projectDir, '_hilo'))) h.writeHiloJson({ ultimaVerificacion: new Date().toISOString(), skills: root, workflows, problemas: problems.length || undefined }, cacheFile);
  return 0;
}

try { process.exit(main()); } catch (e) { process.exit(0); }

Historial

3 cambios · 2026-09-08 → 2026-09-22. Último cambio: fix(higiene): lo que nadie mira no esta bien (ADR-076).

Ovillo v1.31.0tag v1.31.0 (2026-10-06) · sin decisiones posteriores69 skills · 19 agents · 22 hooks · 3 reglas · 15 tools · 103 decisionesfuente: ovillo/.claude/hooks/skill-guard.jsCopyright 2026 Hugo Valer Rojas · Apache-2.0