pre-cicd-init
Validacion pre-flight antes de ejecutar /cicd-init
Qué comprueba
Trigger: prompt del usuario que invoque "/cicd-init" o "/hv:cicd-init" (plugin) Parametrizacion FASE 2: - La URL de instalacion sale de ecosystem.config -> distribution.baseUrl (placeholder '<distribution.baseUrl>' si esta vacio, como el texto original). - La conectividad al servidor CI/CD (antes hardcodeada a un host Azure DevOps) se deriva de cicd.platform / ESTADO_PROYECTO.infraestructura.cicd: plataforma != 'azure-pipelines' -> sin pre-flight de conectividad (skip informativo) URL del servidor: ESTADO_PROYECTO.infraestructura.cicd.serverUrl > ecosystem.config cicd.serverUrl; sin URL -> skip informativo (nunca bloquear contra un host placeholder). Logica (identica al .ps1): 1. Solo se activa si el prompt contiene "/cicd-init" 2. Verifica que la version instalada de la plantilla sea >= 1.0.0 (si se detecta) 3. Detecta builds Classic (XAML) (aborta delegando al migrador) 4. Si la fase no es 0: verifica conectividad al servidor CI/CD configurado
Códigos de salida
| Exit | Significado |
|---|---|
0 | continuar (stdout se inyecta como contexto adicional) |
2 | bloquear con mensaje accionable EN STDERR (R14: idempotencia + pre-flight) |
Política
Bloquea solo en el caso que documenta su cabecera; en el resto continúa.
| Clave | Tipo | Default | Qué hace |
|---|---|---|---|
hooks.policy | string | "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.blockList | array | [] | Hooks concretos elevados a BLOCK aunque policy=warn (ej. ['secret-scanner']). |
Código fuente
pre-cicd-init.js · 273 líneas
#!/usr/bin/env node
// pre-cicd-init.js - Validacion pre-flight antes de ejecutar /cicd-init
// Evento: UserPromptSubmit
// Trigger: prompt del usuario que invoque "/cicd-init" o "/hv:cicd-init" (plugin)
// Exit 0 = continuar (stdout se inyecta como contexto adicional)
// Exit 2 = bloquear con mensaje accionable EN STDERR (R14: idempotencia + pre-flight)
//
// Parametrizacion FASE 2:
// - La URL de instalacion sale de ecosystem.config -> distribution.baseUrl
// (placeholder '<distribution.baseUrl>' si esta vacio, como el texto original).
// - La conectividad al servidor CI/CD (antes hardcodeada a un host Azure DevOps) se deriva de
// cicd.platform / ESTADO_PROYECTO.infraestructura.cicd:
// * plataforma != 'azure-pipelines' -> sin pre-flight de conectividad (skip informativo)
// * URL del servidor: ESTADO_PROYECTO.infraestructura.cicd.serverUrl >
// ecosystem.config cicd.serverUrl; sin URL -> skip informativo (nunca bloquear
// contra un host placeholder).
//
// Logica (identica al .ps1):
// 1. Solo se activa si el prompt contiene "/cicd-init"
// 2. Verifica que la version instalada de la plantilla sea >= 1.0.0 (si se detecta)
// 3. Detecta builds Classic (XAML) (aborta delegando al migrador)
// 4. Si la fase no es 0: verifica conectividad al servidor CI/CD configurado
'use strict';
const fs = require('fs');
const path = require('path');
const h = require(path.join(__dirname, 'lib', 'helpers'));
const configLib = require(path.join(__dirname, 'lib', 'config'));
function writeBlock(lines) {
for (const l of lines) console.error(l);
}
/** Compara 'a.b.c' vs 'x.y.z'. Devuelve <0, 0, >0 o null si no parsea. */
function compareVersions(a, b) {
const pa = String(a).split('.').map((n) => parseInt(n, 10));
const pb = String(b).split('.').map((n) => parseInt(n, 10));
if (pa.some(Number.isNaN) || pb.some(Number.isNaN) || pa.length === 0) return null;
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const x = pa[i] ?? 0;
const y = pb[i] ?? 0;
if (x !== y) return x - y;
}
return 0;
}
function relPath(full, root) {
// path.relative es robusto ante mezcla de separadores / y \ en root (ej. env vars)
const rel = path.relative(root, full);
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
return full.replace(root, '').replace(/^[\\/]+/, '');
}
async function main() {
const hookData = h.readHookInput();
if (!hookData) return 0;
// Solo dispara si el prompt menciona /cicd-init
let prompt = null;
if (typeof hookData.prompt === 'string') prompt = hookData.prompt;
else if (hookData.prompt) prompt = String(hookData.prompt).trim();
// /cicd-init en modo fallback en-repo, /hv:cicd-init instalado como plugin
if (!prompt || !/\/(?:hv:)?cicd-init\b/.test(prompt)) return 0;
// Localizar repo root + config de organizacion
const repoRoot = h.projectDir();
const cfg = configLib.load(repoRoot);
const baseUrl = String(configLib.get(cfg, 'distribution.baseUrl', '') || '').trim().replace(/\/+$/, '');
const installCmd = `irm ${baseUrl || '<distribution.baseUrl>'}/install.ps1 | iex`;
// ------------------------------------------------------------------------
// Check 1: version instalada de la plantilla >= 1.0.0
// Fuente: h.versionEcosistema() (ADR-063), la misma que el banner. Tenia su propia precedencia, que
// ademas no miraba el plugin: en modo plugin caia al dato congelado del Hilo y podia bloquear el
// wizard por una version que hacia trece releases que no era la que corria.
// Si no se detecta: WARN (NO bloquear; el wizard maneja el resto).
// ------------------------------------------------------------------------
let installedVersion = null;
try {
installedVersion = h.versionEcosistema(repoRoot).version;
} catch (e) {
console.log(h.txt(`[!] pre-cicd-init: no se pudo leer la version instalada (${e.message}). Continuando.`,
`[!] pre-cicd-init: could not read the installed version (${e.message}). Continuing.`));
}
if (installedVersion) {
// Strip pre-release suffix (-beta, -rc1...) antes de comparar
const clean = String(installedVersion).replace(/-.*$/, '');
const cmp = compareVersions(clean, '1.0.0');
if (cmp === null) {
console.log(h.txt(`[!] pre-cicd-init: version '${installedVersion}' no parseable. Continuando.`,
`[!] pre-cicd-init: version '${installedVersion}' is not parseable. Continuing.`));
} else if (cmp < 0) {
writeBlock([
`[X] pre-cicd-init: version de plantilla insuficiente (actual ${installedVersion}, requerida >= 1.0.0).`,
' /cicd-init con 3 fases de adopcion necesita Ovillo >= 1.0.0.',
` Actualizar: ${installCmd}`,
]);
return 2;
}
} else {
console.log(h.txt('[!] pre-cicd-init: no se detecto que version de Ovillo corre (ni plugin, ni VERSION.json, ni Hilo). Continuando bajo riesgo.',
'[!] pre-cicd-init: could not tell which Ovillo version is running (no plugin, no VERSION.json, no Hilo). Continuing at your own risk.'));
}
// ------------------------------------------------------------------------
// Check 2: fase explicita (--fase 0 no necesita servidor CI/CD)
// ------------------------------------------------------------------------
const mFase = prompt.match(/--fase\s+(\d)/);
if (mFase && parseInt(mFase[1], 10) === 0) {
console.log(h.txt('[i] pre-cicd-init: Fase 0 detectada (solo Ovillo local, cero infra Azure DevOps). Saltando validacion Azure DevOps.',
'[i] pre-cicd-init: phase 0 detected (Ovillo local only, no Azure DevOps infrastructure). Skipping the Azure DevOps check.'));
return 0;
}
// Plataforma CI/CD efectiva (proyecto > organizacion > default) via la superficie unica (ADR-023).
const platform = configLib.resolve('cicd.platform', { startDir: repoRoot, fallback: 'none' });
const esAzureDevOps = String(platform).toLowerCase() === 'azure-pipelines';
// ------------------------------------------------------------------------
// Check 3: builds Classic (XAML) -> abortar. Solo tiene sentido en Azure DevOps Server; en otras
// plataformas no se recorre el repo.
// ------------------------------------------------------------------------
const classicXaml = [];
const classicXoml = [];
const classicDirs = [];
const skipDirs = new Set(['.git', 'node_modules']);
function walk(dir) {
if (classicXaml.length >= 3 && classicXoml.length >= 3 && classicDirs.length >= 1) return;
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const e of entries) {
const full = path.join(dir, e.name);
if (e.isDirectory()) {
if (skipDirs.has(e.name)) continue;
if (e.name === 'BuildProcessTemplates' && classicDirs.length < 1) classicDirs.push(full);
walk(full);
} else if (e.isFile()) {
const lower = e.name.toLowerCase();
if (lower.endsWith('.xaml') && classicXaml.length < 3 && /TfsBuild|BuildProcessTemplates/i.test(full)) {
classicXaml.push(full);
} else if (lower.endsWith('.xoml') && classicXoml.length < 3) {
classicXoml.push(full);
}
}
}
}
if (esAzureDevOps) {
try { walk(repoRoot); } catch { /* scan best-effort */ }
}
const classicFiles = classicXaml.concat(classicXoml);
if (classicFiles.length > 0 || classicDirs.length > 0) {
const msg = ['[X] pre-cicd-init: detectado pipeline Classic (XAML) (.xaml/.xoml/BuildProcessTemplates).', ''];
if (classicFiles.length > 0) {
msg.push(' Archivos Classic:');
for (const f of classicFiles.slice(0, 3)) msg.push(` - ${relPath(f, repoRoot)}`);
}
if (classicDirs.length > 0) msg.push(` Directorio: ${relPath(classicDirs[0], repoRoot)}`);
msg.push(
'',
' /cicd-init es para GREENFIELD. Migracion Classic -> YAML: guia manual en',
' .claude/skills/cicd-architect/references/classic-migration.md.'
);
writeBlock(msg);
return 2;
}
// ------------------------------------------------------------------------
// Check 4: conectividad al servidor CI/CD (solo fase >= 1, implicita o explicita).
// Derivado de cicd.platform + ESTADO_PROYECTO.
// Node negocia TLS 1.2+ por defecto (equivalente al fix R2/h9 de PS 5.1).
// ------------------------------------------------------------------------
if (String(platform).toLowerCase() === 'github-actions') {
// Pre-flight GitHub, WARN-first: gh instalado y autenticado. Nunca bloquea: el wizard genera los
// workflows igual; sin gh, environments y secretos habra que crearlos a mano (FASE 2.5-gh).
const { spawnSync } = require('child_process');
const gh = spawnSync('gh', ['auth', 'status'], { encoding: 'utf8', timeout: 8000 });
if (gh.error || gh.status === null) {
console.log(h.txt('[!] pre-cicd-init: gh (GitHub CLI) no esta instalado o no responde. El wizard generara los workflows; para crear environments y secretos por API instala gh (https://cli.github.com) y ejecuta gh auth login.',
'[!] pre-cicd-init: gh (GitHub CLI) is not installed or not responding. The wizard will still generate the workflows; to create environments and secrets through the API, install gh (https://cli.github.com) and run gh auth login.'));
} else if (gh.status !== 0) {
console.log(h.txt('[!] pre-cicd-init: gh auth status falla (sin sesion). Ejecuta gh auth login para que ' + h.cmd('cicd-init') + ' pueda crear environments y secretos por API.',
'[!] pre-cicd-init: gh auth status fails (no session). Run gh auth login so ' + h.cmd('cicd-init') + ' can create environments and secrets through the API.'));
} else {
console.log(h.txt('[i] pre-cicd-init: gh autenticado. Pre-flight GitHub OK.',
'[i] pre-cicd-init: gh is authenticated. GitHub pre-flight OK.'));
}
return 0;
}
if (!esAzureDevOps) {
console.log(h.txt(`[i] pre-cicd-init: plataforma CI/CD '${platform}' sin pre-flight de conectividad especifico. Continuando.`,
`[i] pre-cicd-init: CI/CD platform '${platform}' has no specific connectivity pre-flight. Continuing.`));
return 0;
}
const estado = configLib.loadEstado(repoRoot);
let serverBase =
(estado && estado.infraestructura && estado.infraestructura.cicd && estado.infraestructura.cicd.serverUrl) ||
configLib.get(cfg, 'cicd.serverUrl', '') ||
'';
serverBase = String(serverBase).trim().replace(/\/+$/, '');
if (!serverBase) {
console.log(h.txt('[i] pre-cicd-init: sin URL de servidor CI/CD configurada (infraestructura.cicd.serverUrl o ecosystem.config cicd.serverUrl). Saltando validacion de conectividad.',
'[i] pre-cicd-init: no CI/CD server URL configured (infraestructura.cicd.serverUrl or ecosystem.config cicd.serverUrl). Skipping the connectivity check.'));
return 0;
}
let host;
try {
host = new URL(serverBase).host;
} catch (e) {
console.log(h.txt(`[!] pre-cicd-init: error inesperado validando Azure DevOps (${e.message}). Continuando bajo riesgo.`,
`[!] pre-cicd-init: unexpected error checking Azure DevOps (${e.message}). Continuing at your own risk.`));
return 0;
}
const tfsUrl = `${serverBase}/_apis/connectionData?api-version=6.0`;
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 5000);
let resp;
try {
resp = await fetch(tfsUrl, { method: 'HEAD', signal: ctrl.signal, redirect: 'manual' });
} finally {
clearTimeout(timer);
}
const status = resp.status;
if (status === 200) {
console.log(h.txt('[OK] pre-cicd-init: Azure DevOps accesible (HTTP 200). Pre-flight OK.',
'[OK] pre-cicd-init: Azure DevOps reachable (HTTP 200). Pre-flight OK.'));
return 0;
}
if (status === 401 || status === 403) {
console.log(h.txt(`[!] pre-cicd-init: Azure DevOps accesible pero auth fallida (HTTP ${status}). Continuando bajo riesgo.`,
`[!] pre-cicd-init: Azure DevOps reachable but authentication failed (HTTP ${status}). Continuing at your own risk.`));
return 0;
}
// HTTP 405 Method Not Allowed: el servidor rechaza HEAD pero el endpoint EXISTE (accesible)
if (status === 405) {
console.log(h.txt('[OK] pre-cicd-init: Azure DevOps accesible (HTTP 405 a HEAD; el endpoint existe). Pre-flight OK.',
'[OK] pre-cicd-init: Azure DevOps reachable (HTTP 405 to HEAD; the endpoint exists). Pre-flight OK.'));
return 0;
}
console.log(h.txt(`[!] pre-cicd-init: Azure DevOps respondio HTTP ${status}. Continuando bajo riesgo.`,
`[!] pre-cicd-init: Azure DevOps answered HTTP ${status}. Continuing at your own risk.`));
return 0;
} catch (e) {
writeBlock([
`[X] pre-cicd-init: sin conectividad a ${host}.`,
` Error: ${e.message}`,
` Verificar: estas en red corporativa o VPN? ${host} responde en tu navegador?`,
' Si solo quieres Fase 0 (sin Azure DevOps), ejecuta: /cicd-init --fase 0',
]);
return 2;
}
}
main()
.then((code) => process.exit(code ?? 0))
.catch((e) => {
console.error(h.txt(`[pre-cicd-init] error no fatal: ${e.message}`,
`[pre-cicd-init] non-fatal error: ${e.message}`));
process.exit(0);
});
Historial
11 cambios · 2026-09-07 → 2026-09-22. Último cambio: fix(vocabulario): no hay comandos (ADR-077).