@saulwade/swl-ses 2.6.1 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +14 -2
- package/README.md +65 -18
- package/agentes/_intent-spec.md +73 -73
- package/agentes/_propose-step.md +90 -90
- package/bin/swl-ses.js +10 -0
- package/comandos/swl/brainstorm.md +1 -0
- package/comandos/swl/briefing.md +119 -119
- package/comandos/swl/contribuir.md +233 -233
- package/comandos/swl/deuda-codigo.md +97 -97
- package/comandos/swl/mcp-status.md +1 -0
- package/gateway/lib/event-channel.js +191 -191
- package/habilidades/agent-deep-links/SKILL.md +148 -148
- package/habilidades/backend-async-postgres-testing/SKILL.md +216 -216
- package/habilidades/backend-error-design/SKILL.md +221 -221
- package/habilidades/backend-production-resilience/SKILL.md +288 -288
- package/habilidades/calidad-anti-patrones-universales/SKILL.md +105 -1
- package/habilidades/calidad-contract-testing/SKILL.md +165 -165
- package/habilidades/calidad-mutation-testing/SKILL.md +25 -1
- package/habilidades/checklist-seguridad/recursos/stride-cobertura.md +60 -60
- package/habilidades/ci-cd-pipelines/SKILL.md +5 -1
- package/habilidades/css-moderno/SKILL.md +7 -1
- package/habilidades/diagrama-arquitectura/assets/template.html +276 -276
- package/habilidades/doubt-driven-review/recursos/EXAMPLES.md +130 -130
- package/habilidades/estructura-proyecto-claude/recursos/mcp-json-template.json +57 -57
- package/habilidades/extractor-de-aprendizajes/SKILL.md +5 -1
- package/habilidades/feynman-auditor-swl/recursos/preguntas-language-agnostic.md +108 -108
- package/habilidades/harness-claude-code/SKILL.md +3 -2
- package/habilidades/meta-skills-estandar/recursos/convencion-examples.md +93 -93
- package/habilidades/patrones-python/recursos/patrones-avanzados.md +469 -469
- package/habilidades/perfil-usuario/SKILL.md +200 -200
- package/habilidades/prevencion-sobreingenieria/recursos/EXAMPLES.md +580 -580
- package/habilidades/prevencion-sobreingenieria/recursos/soluciones-nativas.md +166 -166
- package/habilidades/prevencion-sobreingenieria/recursos/variables-residuales-post-refactor.md +85 -85
- package/habilidades/proceso-ddia-streaming/SKILL.md +231 -231
- package/habilidades/proceso-discovery-machote/SKILL.md +157 -157
- package/habilidades/proceso-dynamic-workflows/SKILL.md +60 -0
- package/habilidades/proceso-dynamic-workflows/recursos/template-adversarial-verify.js +65 -65
- package/habilidades/proceso-dynamic-workflows/recursos/template-triage.js +65 -65
- package/habilidades/proceso-intent-engineering/SKILL.md +269 -269
- package/habilidades/proceso-modular-split/SKILL.md +256 -256
- package/habilidades/state-inconsistency-auditor-swl/recursos/coupled-state-patterns.md +147 -147
- package/habilidades/swl-claudemd/recursos/contrato-aprender.md +83 -83
- package/habilidades/swl-claudemd/recursos/duplicacion-reglas-globales.md +85 -85
- package/habilidades/swl-claudemd/recursos/plantillas-init.md +94 -94
- package/habilidades/tdd-workflow/recursos/gherkin-bdd.md +111 -111
- package/hooks/calidad-pre-commit.js +159 -10
- package/hooks/ciclo-evolucion-subagente.js +26 -26
- package/hooks/ciclo-evolucion.js +26 -26
- package/hooks/contexto-subagente.js +68 -68
- package/hooks/lib/auto-consolidator.js +335 -335
- package/hooks/lib/ciclo-evolucion.js +47 -47
- package/hooks/lib/deep-links.js +185 -185
- package/hooks/lib/error-classifier.js +308 -308
- package/hooks/lib/notificacion-formato.js +45 -11
- package/hooks/lib/provenance-tracker.js +191 -191
- package/hooks/lib/raiz-proyecto.js +35 -4
- package/hooks/lib/resource-quota.js +122 -122
- package/hooks/lib/retry-jitter.js +165 -165
- package/hooks/lib/security-net.js +201 -201
- package/hooks/lib/skill-auditor.js +588 -588
- package/hooks/lib/sync-status.js +228 -228
- package/hooks/lib/taint-tracker.js +107 -107
- package/hooks/lib/text-similarity.js +241 -241
- package/hooks/lib/toon-compressor.js +245 -245
- package/hooks/notificacion-telegram.js +5 -11
- package/hooks/session-briefing.js +12 -4
- package/instintos/autonomia.yaml +27 -27
- package/instintos/prompt-appendices.yaml +57 -57
- package/llms.txt +1 -1
- package/manifiestos/agent-output-schemas.json +57 -57
- package/manifiestos/canonical-hashes.json +662 -0
- package/manifiestos/harness-ir.json +47536 -0
- package/manifiestos/hooks-config.json +469 -469
- package/manifiestos/invariantes-criticos.json +30 -30
- package/manifiestos/policy-bundle.json +2065 -0
- package/manifiestos/policy-corpus-w2.json +3926 -0
- package/manifiestos/runtime-adapters-core3.json +208 -0
- package/manifiestos/runtime-conformance.json +139 -0
- package/manifiestos/skills-lock.json +43 -43
- package/package.json +2 -2
- package/plantillas/auditor-veto-template.md +105 -105
- package/plantillas/github-workflows/release-please.yml +44 -44
- package/plantillas/github-workflows/swl-ci.yml +107 -107
- package/plantillas/github-workflows/swl-security.yml +51 -51
- package/plugin.json +2 -2
- package/reglas/accesibilidad.md +10 -10
- package/reglas/auditorias-documentales-estructurales.md +7 -7
- package/reglas/cloud-infra.md +8 -8
- package/reglas/consultar-vault-primero.md +195 -195
- package/reglas/git-workflow.md +1 -0
- package/reglas/hooks.md +6 -6
- package/reglas/intent-engineering.md +218 -218
- package/reglas/markitdown.md +8 -8
- package/reglas/monitor-ci.md +12 -0
- package/reglas/patrones.md +6 -6
- package/reglas/testing.md +7 -7
- package/reglas/tests-cleanup.md +224 -224
- package/schemas/agent-message.schema.json +73 -73
- package/schemas/agent-output-implementacion.schema.json +114 -114
- package/schemas/agent-output-planificacion.schema.json +150 -150
- package/schemas/agent-output-review.schema.json +98 -98
- package/schemas/diary-entry.schema.json +112 -112
- package/schemas/gate-state.schema.json +76 -0
- package/schemas/harness-ir.schema.json +369 -0
- package/schemas/hook-profiles.schema.json +54 -54
- package/schemas/hooks-config.schema.json +89 -89
- package/schemas/legacy-gates.schema.json +45 -0
- package/schemas/modulos.schema.json +38 -38
- package/schemas/perfiles.schema.json +36 -36
- package/schemas/plugin.schema.json +77 -77
- package/schemas/policy-bundle.schema.json +140 -0
- package/schemas/policy-enforcement.schema.json +117 -0
- package/schemas/policy-operation.schema.json +261 -0
- package/schemas/runtime-adapter.schema.json +176 -0
- package/schemas/runtime-build-attestation.schema.json +100 -0
- package/schemas/runtime-conformance.schema.json +239 -0
- package/schemas/runtime-diagnostic.schema.json +395 -0
- package/schemas/skill-evals.schema.json +119 -119
- package/schemas/skill-frontmatter.schema.json +245 -245
- package/schemas/w4-certification-request.schema.json +72 -0
- package/schemas/w4-certification-verdict.schema.json +224 -0
- package/schemas/w4-corpus.schema.json +172 -0
- package/schemas/w4-mutation-report.schema.json +116 -0
- package/schemas/w4-replay-result.schema.json +164 -0
- package/schemas/w4-scoring-report.schema.json +89 -0
- package/scripts/audit-tools/audit-history.js +330 -330
- package/scripts/audit-tools/bundle-tracker.js +290 -290
- package/scripts/audit-tools/canary-monitor.js +352 -352
- package/scripts/audit-tools/code-profiler.js +605 -605
- package/scripts/audit-tools/dep-doctor.js +320 -320
- package/scripts/audit-tools/env-validator.js +206 -206
- package/scripts/audit-tools/lib/fs-walk.js +48 -48
- package/scripts/audit-tools/lib/output.js +23 -23
- package/scripts/audit-tools/migration-checker.js +392 -392
- package/scripts/audit-tools/pentest-scanner.js +1436 -1436
- package/scripts/bootstrap-instintos.js +3 -0
- package/scripts/cli/aprobar-plan.js +73 -73
- package/scripts/cli/briefing.js +23 -23
- package/scripts/cli/ciclo-evolucion.js +26 -26
- package/scripts/cli/derivar-feature-list.js +25 -25
- package/scripts/cli/detectar-host.js +27 -27
- package/scripts/cli/diary-entry.js +69 -69
- package/scripts/cli/execution-state.js +18 -18
- package/scripts/cli/gateway-notify.js +41 -41
- package/scripts/cli/liberar-fase.js +42 -42
- package/scripts/cli/mark-evolved.js +56 -56
- package/scripts/cli/metricas-dora.js +26 -26
- package/scripts/cli/near-duplicate.js +55 -55
- package/scripts/cli/notificaciones.js +123 -123
- package/scripts/cli/propose-step.js +29 -29
- package/scripts/cli/schedule-parse.js +19 -19
- package/scripts/cli/sugerir-modelo.js +20 -20
- package/scripts/cli/verificar-plan.js +36 -36
- package/scripts/cli/verificar-trazabilidad.js +35 -35
- package/scripts/comandos/install-asistido.js +8 -7
- package/scripts/configurar-branch-protection.js +418 -418
- package/scripts/detectar-aprendizajes-duplicados.js +151 -151
- package/scripts/doctor.js +61 -36
- package/scripts/generar-checklists-consolidados.js +273 -273
- package/scripts/generar-claims-runtime.js +1342 -0
- package/scripts/generar-harness-ir.js +257 -0
- package/scripts/generar-inventario.js +52 -54
- package/scripts/generar-policy-bundle.js +202 -0
- package/scripts/instalador.js +26 -7
- package/scripts/lib/approval-receipts.js +190 -0
- package/scripts/lib/artefactos-python.js +43 -43
- package/scripts/lib/benchmark-metrics.js +160 -160
- package/scripts/lib/budget-enforcer.js +252 -252
- package/scripts/lib/certificacion-loop-state.js +421 -0
- package/scripts/lib/ci-reader.js +193 -193
- package/scripts/lib/ciclo-autonomo/yaml-instintos.js +56 -0
- package/scripts/lib/clasificar-directorio.js +92 -0
- package/scripts/lib/contadores-inventario.js +217 -217
- package/scripts/lib/detectar-host-swl.js +175 -175
- package/scripts/lib/detectar-runtime.js +29 -20
- package/scripts/lib/detectar-stack-detallado.js +307 -307
- package/scripts/lib/detector-autoduplicacion-intra-archivo.js +234 -234
- package/scripts/lib/detector-reglas-duplicadas.js +220 -220
- package/scripts/lib/eval-metrics-store.js +218 -218
- package/scripts/lib/eval-quality.js +171 -171
- package/scripts/lib/eval-schemas.js +144 -144
- package/scripts/lib/eval-self-correct.js +106 -106
- package/scripts/lib/eval-validator.js +185 -185
- package/scripts/lib/evidence-verifier.js +192 -0
- package/scripts/lib/evidencia-release.js +322 -322
- package/scripts/lib/frontmatter-canonico.js +509 -0
- package/scripts/lib/gate-engine.js +871 -0
- package/scripts/lib/gate-hooks-requires.js +249 -249
- package/scripts/lib/gate-licencias.js +212 -212
- package/scripts/lib/git-config-preflight.js +48 -0
- package/scripts/lib/git-metricas.js +257 -257
- package/scripts/lib/harness-ir.js +778 -0
- package/scripts/lib/harness-source-snapshot.js +309 -0
- package/scripts/lib/integrity-ledger.js +1147 -0
- package/scripts/lib/jaccard-similarity.js +98 -98
- package/scripts/lib/legacy-gate-migration.js +324 -0
- package/scripts/lib/limpiar-basura-global.js +45 -2
- package/scripts/lib/longmemeval-runner.js +125 -125
- package/scripts/lib/metricas-dora.js +204 -204
- package/scripts/lib/notificaciones-telegram.js +1 -0
- package/scripts/lib/npm-version.js +1 -0
- package/scripts/lib/paquetes-conocidos.js +50 -50
- package/scripts/lib/plan-lock.js +61 -13
- package/scripts/lib/policy-broker.js +338 -0
- package/scripts/lib/policy-bundle.js +342 -0
- package/scripts/lib/policy-context-provider.js +310 -0
- package/scripts/lib/policy-contract.js +479 -0
- package/scripts/lib/policy-verifier-utils.js +65 -0
- package/scripts/lib/pr-analyzer.js +399 -399
- package/scripts/lib/principal-verifier.js +178 -0
- package/scripts/lib/prompt-builder.js +264 -264
- package/scripts/lib/resolver-plan-fase.js +37 -37
- package/scripts/lib/rrf-fusion.js +175 -175
- package/scripts/lib/runtime-adapter-contract.js +267 -0
- package/scripts/lib/runtime-artifact-verifier.js +426 -0
- package/scripts/lib/runtime-build-attestation.js +127 -0
- package/scripts/lib/runtime-bundle-installer.js +586 -0
- package/scripts/lib/runtime-compiler.js +327 -0
- package/scripts/lib/runtime-conformance.js +202 -0
- package/scripts/lib/runtime-doctor-core3.js +567 -0
- package/scripts/lib/runtime-doctor-input.js +59 -0
- package/scripts/lib/runtime-operation-adapter.js +267 -0
- package/scripts/lib/schema-version.js +164 -164
- package/scripts/lib/semantic-search.js +252 -252
- package/scripts/lib/signed-envelope.js +545 -0
- package/scripts/lib/single-use-store.js +359 -0
- package/scripts/lib/skills-externas.js +31 -0
- package/scripts/lib/transformadores/codex.js +15 -8
- package/scripts/lib/transformadores/gemini.js +79 -5
- package/scripts/lib/w4-attestation-adapter.js +158 -0
- package/scripts/lib/w4-canario.js +337 -0
- package/scripts/lib/w4-claims.js +182 -0
- package/scripts/lib/w4-corpus-generador.js +542 -0
- package/scripts/lib/w4-gate-c5.js +115 -0
- package/scripts/lib/w4-harness-bajo-prueba.js +155 -0
- package/scripts/lib/w4-matriz-combos.js +55 -0
- package/scripts/lib/w4-motor-mutacion.js +1348 -0
- package/scripts/lib/w4-motor-replay.js +735 -0
- package/scripts/lib/w4-pin-origen.js +54 -0
- package/scripts/lib/w4-publicar-request.js +132 -0
- package/scripts/lib/w4-revocacion.js +62 -0
- package/scripts/lib/w4-runtimes-core3.js +38 -0
- package/scripts/lib/w4-scorer-certificacion.js +692 -0
- package/scripts/lib/w4-superficie-candidato.js +49 -0
- package/scripts/lib/w4-veredicto.js +452 -0
- package/scripts/lib/w4-verificar-veredicto.js +302 -0
- package/scripts/limpiar-artefactos-python.js +131 -131
- package/scripts/migrar-csv-a-array.js +168 -168
- package/scripts/migrar-fase-dominio.js +200 -200
- package/scripts/migrar-gates-legacy.js +108 -0
- package/scripts/publicar-certification-request.js +115 -0
- package/scripts/runtime-doctor.js +107 -0
- package/scripts/tui/componentes/selector-multi.js +189 -189
- package/scripts/tui/componentes/selector-unico.js +158 -158
- package/scripts/tui/ejecutores.js +375 -375
- package/scripts/tui/lib/colores.js +129 -129
- package/scripts/tui/lib/render.js +264 -264
- package/scripts/tui/lib/teclas.js +113 -113
- package/scripts/tui/pantallas/install-wizard.js +12 -7
- package/scripts/tui/pantallas/menu-principal.js +52 -52
- package/scripts/tui/pantallas/progreso.js +274 -274
- package/scripts/tui/pantallas/resumen.js +132 -132
- package/scripts/validar-userland-vacio.js +110 -110
- package/scripts/verificar-aislamiento-swl-eval.js +87 -0
- package/scripts/verificar-empaquetado-downstream.js +375 -0
- package/scripts/verificar-loop-constructor.js +215 -0
- package/scripts/verificar-trazabilidad.js +13 -6
- package/scripts/verificar-veredicto-real.js +84 -0
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Compilador diagnóstico del Harness IR sobre fuentes tracked y confinadas.
|
|
5
|
+
* La normalización semántica se incorpora en la siguiente oleada de la Fase 29.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const SCHEMA = require('../../schemas/harness-ir.schema.json');
|
|
9
|
+
const crypto = require('node:crypto');
|
|
10
|
+
|
|
11
|
+
const { capturarHarnessSourceSnapshot } = require('./harness-source-snapshot');
|
|
12
|
+
const { CENTINELA_TODOS, SKILLS_EXTERNAS_SET } = require('./skills-externas');
|
|
13
|
+
|
|
14
|
+
const HOOKS_CONFIG = 'manifiestos/hooks-config.json';
|
|
15
|
+
const TIPOS = Object.freeze(['agent', 'command', 'skill', 'rule']);
|
|
16
|
+
const CAPABILITIES = Object.freeze([
|
|
17
|
+
'delegate',
|
|
18
|
+
'filesystem.mutate',
|
|
19
|
+
'filesystem.read',
|
|
20
|
+
'memory.read',
|
|
21
|
+
'memory.write',
|
|
22
|
+
'network.access',
|
|
23
|
+
'shell.exec',
|
|
24
|
+
'skill.invoke',
|
|
25
|
+
]);
|
|
26
|
+
const TOOL_MAP = Object.freeze({
|
|
27
|
+
Agent: 'delegate',
|
|
28
|
+
Bash: 'shell.exec',
|
|
29
|
+
Edit: 'filesystem.mutate',
|
|
30
|
+
Glob: 'filesystem.read',
|
|
31
|
+
Grep: 'filesystem.read',
|
|
32
|
+
MultiEdit: 'filesystem.mutate',
|
|
33
|
+
Read: 'filesystem.read',
|
|
34
|
+
Skill: 'skill.invoke',
|
|
35
|
+
Task: 'delegate',
|
|
36
|
+
WebFetch: 'network.access',
|
|
37
|
+
WebSearch: 'network.access',
|
|
38
|
+
Write: 'filesystem.mutate',
|
|
39
|
+
});
|
|
40
|
+
const EVENT_MAP = Object.freeze({
|
|
41
|
+
PostToolUse: 'after_tool',
|
|
42
|
+
PreToolUse: 'before_tool',
|
|
43
|
+
SessionStart: 'session_start',
|
|
44
|
+
Stop: 'stop',
|
|
45
|
+
SubagentStart: 'before_agent',
|
|
46
|
+
SubagentStop: 'after_agent',
|
|
47
|
+
});
|
|
48
|
+
const EVENTOS_FUERA_V1 = new Set(['Notification', 'PreCompact', 'UserPromptSubmit']);
|
|
49
|
+
const RISK_MAP = Object.freeze({ ALTO: 'high', BAJO: 'low', MEDIO: 'medium' });
|
|
50
|
+
const TIER_MAP = Object.freeze({
|
|
51
|
+
fable: 'frontier',
|
|
52
|
+
haiku: 'light',
|
|
53
|
+
opus: 'critical',
|
|
54
|
+
sonnet: 'standard',
|
|
55
|
+
});
|
|
56
|
+
const TIER_DEFINITIONS = Object.freeze([
|
|
57
|
+
{
|
|
58
|
+
id: 'critical',
|
|
59
|
+
requirements: [
|
|
60
|
+
{ key: 'reasoning', value: 'strong' },
|
|
61
|
+
{ key: 'structuredOutput', value: 'required' },
|
|
62
|
+
{ key: 'errorTolerance', value: 'low' },
|
|
63
|
+
],
|
|
64
|
+
unresolvedDisposition: 'stop',
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'frontier',
|
|
68
|
+
requirements: [
|
|
69
|
+
{ key: 'reasoning', value: 'maximum_available' },
|
|
70
|
+
{ key: 'toolUse', value: 'required' },
|
|
71
|
+
{ key: 'context', value: 'wide' },
|
|
72
|
+
],
|
|
73
|
+
unresolvedDisposition: 'stop',
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: 'light',
|
|
77
|
+
requirements: [
|
|
78
|
+
{ key: 'latency', value: 'low' },
|
|
79
|
+
{ key: 'cost', value: 'low' },
|
|
80
|
+
{ key: 'outputSchema', value: 'simple' },
|
|
81
|
+
],
|
|
82
|
+
unresolvedDisposition: 'unresolved_in_w1',
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
id: 'standard',
|
|
86
|
+
requirements: [
|
|
87
|
+
{ key: 'toolUse', value: 'reliable' },
|
|
88
|
+
{ key: 'costLatency', value: 'balanced' },
|
|
89
|
+
],
|
|
90
|
+
unresolvedDisposition: 'unresolved_in_w1',
|
|
91
|
+
},
|
|
92
|
+
]);
|
|
93
|
+
const ALLOWLISTS = Object.freeze({
|
|
94
|
+
agent: new Set([
|
|
95
|
+
'color', 'description', 'dominio', 'evolvable', 'evolvable_scope', 'exclusiones',
|
|
96
|
+
'fase', 'fragmentos', 'hardGuardrails', 'healthMetrics', 'invariantes', 'maxTurnos',
|
|
97
|
+
'model', 'modeloAlterno', 'name', 'nivelRiesgo', 'permisosComandos',
|
|
98
|
+
'permisosEscritura', 'permisosRed', 'permissionMode', 'skillsInvocables',
|
|
99
|
+
'skillsRestringidos', 'steering', 'strategy', 'toolBudget', 'tools',
|
|
100
|
+
'ventanaContexto', 'version',
|
|
101
|
+
]),
|
|
102
|
+
command: new Set([
|
|
103
|
+
'allowed-tools', 'allowed_tools', 'argument-hint', 'description', 'name', 'tipo',
|
|
104
|
+
'user-invocable', 'version',
|
|
105
|
+
]),
|
|
106
|
+
rule: new Set(['paths']),
|
|
107
|
+
skill: new Set([
|
|
108
|
+
'atlas_techniques', 'attack_techniques', 'author', 'd3fend_techniques',
|
|
109
|
+
'dependencias', 'deprecated', 'deprecated-reason', 'deprecated-replacement',
|
|
110
|
+
'deprecated-since', 'description', 'domain', 'evolvable', 'evolvable_scope',
|
|
111
|
+
'evolved', 'exclusiones', 'fuente', 'herramientasPermitidas', 'license', 'name',
|
|
112
|
+
'nist_ai_rmf', 'nist_csf', 'nivelRiesgo', 'provenance', 'skillsInvocables',
|
|
113
|
+
'tags', 'toolsRequeridos', 'user-invocable', 'version', 'when_to_use',
|
|
114
|
+
]),
|
|
115
|
+
});
|
|
116
|
+
const LOCATOR_ONLY = Object.freeze({
|
|
117
|
+
agent: new Set([...ALLOWLISTS.agent].filter((clave) => ![
|
|
118
|
+
'description', 'model', 'name', 'nivelRiesgo', 'skillsInvocables', 'tools',
|
|
119
|
+
].includes(clave))),
|
|
120
|
+
command: new Set(['tipo', 'user-invocable', 'version']),
|
|
121
|
+
rule: new Set([]),
|
|
122
|
+
skill: new Set([...ALLOWLISTS.skill].filter((clave) => !['description', 'name'].includes(clave))),
|
|
123
|
+
});
|
|
124
|
+
const TAINT_TERMS_V1 = Object.freeze([
|
|
125
|
+
'anthropic', 'claude', 'claude-code', 'claude-api', 'openai', 'codex', 'gemini',
|
|
126
|
+
'google', 'cursor', 'copilot', 'github-copilot', 'opencode', 'openclaude',
|
|
127
|
+
'fable', 'opus', 'sonnet', 'haiku', 'read', 'write', 'edit', 'multiedit', 'bash',
|
|
128
|
+
'grep', 'glob', 'agent', 'task', 'skill', 'websearch', 'webfetch', 'sessionstart',
|
|
129
|
+
'pretooluse', 'posttooluse', 'subagentstart', 'subagentstop', 'stop',
|
|
130
|
+
'userpromptsubmit', 'precompact', 'notification',
|
|
131
|
+
]);
|
|
132
|
+
const CONFUSABLES_V1 = Object.freeze({
|
|
133
|
+
'Α': 'a', 'Β': 'b', 'Ε': 'e', 'Η': 'h', 'Ι': 'i', 'Κ': 'k', 'Μ': 'm', 'Ν': 'n',
|
|
134
|
+
'Ο': 'o', 'Ρ': 'p', 'Τ': 't', 'Χ': 'x', 'а': 'a', 'с': 'c', 'е': 'e', 'і': 'i',
|
|
135
|
+
'ι': 'i', 'о': 'o', 'ο': 'o', 'р': 'p', 'ρ': 'p', 'ѕ': 's', 'х': 'x', 'χ': 'x',
|
|
136
|
+
'у': 'y', 'υ': 'y',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
function resolverRef(referencia) {
|
|
140
|
+
return referencia.slice(2).split('/').reduce((actual, token) => {
|
|
141
|
+
const clave = token.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
142
|
+
return actual[clave];
|
|
143
|
+
}, SCHEMA);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function coincideTipo(tipo, valor) {
|
|
147
|
+
if (tipo === 'null') return valor === null;
|
|
148
|
+
if (tipo === 'array') return Array.isArray(valor);
|
|
149
|
+
if (tipo === 'object') {
|
|
150
|
+
return valor !== null && typeof valor === 'object' && !Array.isArray(valor);
|
|
151
|
+
}
|
|
152
|
+
if (tipo === 'integer') return Number.isInteger(valor);
|
|
153
|
+
return typeof valor === tipo;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function error(errores, ruta, codigo) {
|
|
157
|
+
errores.push({ path: ruta, code: codigo });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function validarObjeto(definicion, valor, ruta, errores) {
|
|
161
|
+
const propiedades = definicion.properties;
|
|
162
|
+
for (const requerida of definicion.required) {
|
|
163
|
+
if (!Object.hasOwn(valor, requerida)) error(errores, `${ruta}/${requerida}`, 'required');
|
|
164
|
+
}
|
|
165
|
+
for (const clave of Object.keys(valor)) {
|
|
166
|
+
if (!Object.hasOwn(propiedades, clave)) error(errores, `${ruta}/${clave}`, 'additional');
|
|
167
|
+
}
|
|
168
|
+
for (const [clave, hija] of Object.entries(propiedades)) {
|
|
169
|
+
if (Object.hasOwn(valor, clave)) validar(hija, valor[clave], `${ruta}/${clave}`, errores);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function validarLimites(definicion, valor, ruta, errores) {
|
|
174
|
+
if (definicion.minimum !== undefined && valor < definicion.minimum) {
|
|
175
|
+
error(errores, ruta, 'minimum');
|
|
176
|
+
}
|
|
177
|
+
if (definicion.maximum !== undefined && valor > definicion.maximum) {
|
|
178
|
+
error(errores, ruta, 'maximum');
|
|
179
|
+
}
|
|
180
|
+
if (definicion.maxItems !== undefined && valor.length > definicion.maxItems) {
|
|
181
|
+
error(errores, ruta, 'maxItems');
|
|
182
|
+
}
|
|
183
|
+
if (definicion.minItems !== undefined && valor.length < definicion.minItems) {
|
|
184
|
+
error(errores, ruta, 'minItems');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function validarRestricciones(definicion, valor, ruta, errores) {
|
|
189
|
+
if (definicion.const !== undefined && valor !== definicion.const) error(errores, ruta, 'const');
|
|
190
|
+
if (definicion.enum && !definicion.enum.includes(valor)) error(errores, ruta, 'enum');
|
|
191
|
+
if (definicion.pattern) {
|
|
192
|
+
if (!new RegExp(definicion.pattern, 'u').test(valor)) error(errores, ruta, 'pattern');
|
|
193
|
+
}
|
|
194
|
+
validarLimites(definicion, valor, ruta, errores);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function validarOneOf(opciones, valor, ruta, errores) {
|
|
198
|
+
const coincidencias = opciones.filter((opcion) => {
|
|
199
|
+
const locales = [];
|
|
200
|
+
validar(opcion, valor, ruta, locales);
|
|
201
|
+
return locales.length === 0;
|
|
202
|
+
});
|
|
203
|
+
if (coincidencias.length !== 1) error(errores, ruta, 'oneOf');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function validar(definicion, valor, ruta, errores) {
|
|
207
|
+
if (definicion.$ref) return validar(resolverRef(definicion.$ref), valor, ruta, errores);
|
|
208
|
+
if (definicion.oneOf) {
|
|
209
|
+
validarOneOf(definicion.oneOf, valor, ruta, errores);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (definicion.type && !coincideTipo(definicion.type, valor)) {
|
|
213
|
+
error(errores, ruta, 'type');
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
validarRestricciones(definicion, valor, ruta, errores);
|
|
217
|
+
if (definicion.type === 'object') validarObjeto(definicion, valor, ruta, errores);
|
|
218
|
+
if (definicion.type === 'array') {
|
|
219
|
+
valor.forEach((item, indice) => validar(definicion.items, item, `${ruta}/${indice}`, errores));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function validarContrato(valor) {
|
|
224
|
+
const errors = [];
|
|
225
|
+
validar(SCHEMA, valor, '$', errors);
|
|
226
|
+
return { ok: errors.length === 0, errors };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function crearErrorHarness(codigo, mensaje, extras = {}) {
|
|
230
|
+
const excepcion = new Error(mensaje);
|
|
231
|
+
Object.assign(excepcion, { codigo, ...extras });
|
|
232
|
+
return excepcion;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function sha256(valor) {
|
|
236
|
+
return crypto.createHash('sha256').update(valor).digest('hex');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function clavesExactas(valor, requeridas, opcionales = []) {
|
|
240
|
+
if (!valor || typeof valor !== 'object' || Array.isArray(valor)) return false;
|
|
241
|
+
const permitidas = new Set([...requeridas, ...opcionales]);
|
|
242
|
+
return requeridas.every((clave) => Object.hasOwn(valor, clave))
|
|
243
|
+
&& Object.keys(valor).every((clave) => permitidas.has(clave));
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function validarObjetoTipos(valor, tipos) {
|
|
247
|
+
return Object.entries(tipos).every(([clave, tipo]) => {
|
|
248
|
+
if (tipo === 'array:string') {
|
|
249
|
+
return Array.isArray(valor[clave]) && valor[clave].every((item) => typeof item === 'string');
|
|
250
|
+
}
|
|
251
|
+
if (tipo === 'integer') return Number.isInteger(valor[clave]);
|
|
252
|
+
return typeof valor[clave] === tipo;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function validarRaizHooks(config) {
|
|
257
|
+
const claves = [
|
|
258
|
+
'descripcion',
|
|
259
|
+
'prioridad_hooks',
|
|
260
|
+
'opciones_avanzadas_hooks',
|
|
261
|
+
'riskThresholds',
|
|
262
|
+
'costBudget',
|
|
263
|
+
'circuitBreaker',
|
|
264
|
+
'hooks',
|
|
265
|
+
];
|
|
266
|
+
return clavesExactas(config, claves)
|
|
267
|
+
&& typeof config.descripcion === 'string'
|
|
268
|
+
&& clavesExactas(config.prioridad_hooks, ['descripcion', 'orden', 'regla'])
|
|
269
|
+
&& validarObjetoTipos(config.prioridad_hooks, {
|
|
270
|
+
descripcion: 'string',
|
|
271
|
+
orden: 'array:string',
|
|
272
|
+
regla: 'string',
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function validarOpcionesHooks(config) {
|
|
277
|
+
const opciones = config.opciones_avanzadas_hooks;
|
|
278
|
+
const thresholds = config.riskThresholds;
|
|
279
|
+
const budget = config.costBudget;
|
|
280
|
+
const breaker = config.circuitBreaker;
|
|
281
|
+
return clavesExactas(opciones, ['descripcion', 'timeout', 'async', 'once'])
|
|
282
|
+
&& validarObjetoTipos(opciones, {
|
|
283
|
+
descripcion: 'string', timeout: 'string', async: 'string', once: 'string',
|
|
284
|
+
})
|
|
285
|
+
&& clavesExactas(thresholds, ['allow', 'review', 'confirm'])
|
|
286
|
+
&& validarObjetoTipos(thresholds, { allow: 'number', review: 'number', confirm: 'number' })
|
|
287
|
+
&& clavesExactas(budget, ['maxUsd', 'maxTokens', 'alertAt'])
|
|
288
|
+
&& validarObjetoTipos(budget, { maxUsd: 'number', maxTokens: 'integer', alertAt: 'number' })
|
|
289
|
+
&& clavesExactas(breaker, ['maxConsecutiveFailures', 'halfOpenCooldownMs', 'auditThreshold'])
|
|
290
|
+
&& validarObjetoTipos(breaker, {
|
|
291
|
+
maxConsecutiveFailures: 'integer',
|
|
292
|
+
halfOpenCooldownMs: 'integer',
|
|
293
|
+
auditThreshold: 'integer',
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function validarEntradaHook(entrada) {
|
|
298
|
+
const requeridas = ['event', 'matcher', 'description', 'blocking'];
|
|
299
|
+
const opcionales = ['async', 'optIn', 'maxConsecutiveFailures', 'degradeOnFailure'];
|
|
300
|
+
if (!clavesExactas(entrada, requeridas, opcionales)) return false;
|
|
301
|
+
if (!validarObjetoTipos(entrada, {
|
|
302
|
+
event: 'string', matcher: 'string', description: 'string', blocking: 'boolean',
|
|
303
|
+
})) return false;
|
|
304
|
+
const tiposOpcionales = {
|
|
305
|
+
async: 'boolean',
|
|
306
|
+
optIn: 'string',
|
|
307
|
+
maxConsecutiveFailures: 'integer',
|
|
308
|
+
degradeOnFailure: 'string',
|
|
309
|
+
};
|
|
310
|
+
return Object.entries(tiposOpcionales).every(([clave, tipo]) => (
|
|
311
|
+
entrada[clave] === undefined || validarObjetoTipos(entrada, { [clave]: tipo })
|
|
312
|
+
));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function validarHooksParseados(parsed) {
|
|
316
|
+
const config = parsed.valor;
|
|
317
|
+
const hooksValidos = validarRaizHooks(config)
|
|
318
|
+
&& validarOpcionesHooks(config)
|
|
319
|
+
&& clavesExactas(config.hooks, [], Object.keys(config.hooks))
|
|
320
|
+
&& Object.values(config.hooks).every(validarEntradaHook);
|
|
321
|
+
if (!hooksValidos) throw crearErrorHarness('HOOKS_CONFIG_INVALID', 'Shape de hooks inválido');
|
|
322
|
+
return { config, propiedades: parsed.propiedades };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function locatorArchivo(texto) {
|
|
326
|
+
return {
|
|
327
|
+
kind: 'line-range',
|
|
328
|
+
startLine: 1,
|
|
329
|
+
endLine: Math.max(1, texto.split('\n').length),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function fuenteNodo(snapshot, locator) {
|
|
334
|
+
return { path: snapshot.path, sha256: snapshot.sha256, locator };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function fuenteCampo(registro, clave) {
|
|
338
|
+
const metadata = registro.parsed.campos[clave];
|
|
339
|
+
if (!metadata) return registro.node.source;
|
|
340
|
+
return fuenteNodo(registro.snapshot, {
|
|
341
|
+
kind: 'frontmatter-key',
|
|
342
|
+
keyHash: sha256(metadata.claveFuente),
|
|
343
|
+
startLine: metadata.locator.startLine,
|
|
344
|
+
endLine: metadata.locator.endLine,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function fuenteCuerpo(registro) {
|
|
349
|
+
const { cuerpo } = registro.parsed;
|
|
350
|
+
if (!cuerpo) return registro.node.source;
|
|
351
|
+
const prefijo = registro.snapshot.texto.slice(0, -cuerpo.length);
|
|
352
|
+
return fuenteNodo(registro.snapshot, {
|
|
353
|
+
kind: 'line-range',
|
|
354
|
+
startLine: prefijo.split('\n').length,
|
|
355
|
+
endLine: Math.max(1, registro.snapshot.texto.split('\n').length),
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function crearDiagnostico(code, severity, nodeId, source) {
|
|
360
|
+
return { code, severity, blocksConsumption: true, nodeId, source };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function diagnosticar(registro, code, severity, source = registro.node.source) {
|
|
364
|
+
registro.diagnostics.push(crearDiagnostico(code, severity, registro.node.nodeId, source));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function escaparRegex(texto) {
|
|
368
|
+
return texto.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function limpiarTaint(texto) {
|
|
372
|
+
return String(texto)
|
|
373
|
+
.replace(/\x1B\[[0-?]*[ -/]*[@-~]/gu, '')
|
|
374
|
+
.replace(/[\u200B-\u200D\u2060\uFEFF]/gu, '')
|
|
375
|
+
.normalize('NFKC')
|
|
376
|
+
.replace(/[`*_~]/gu, '');
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function contieneTermino(texto) {
|
|
380
|
+
return TAINT_TERMS_V1.some((term) => new RegExp(
|
|
381
|
+
`(?<![\\p{L}\\p{N}])${escaparRegex(term)}(?![\\p{L}\\p{N}])`,
|
|
382
|
+
'iu'
|
|
383
|
+
).test(texto));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function crearSkeleton(texto) {
|
|
387
|
+
return [...texto].map((caracter) => CONFUSABLES_V1[caracter] || caracter).join('');
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function detectarTaint(texto) {
|
|
391
|
+
const limpio = limpiarTaint(texto);
|
|
392
|
+
const directo = contieneTermino(limpio);
|
|
393
|
+
const porSkeleton = contieneTermino(crearSkeleton(limpio));
|
|
394
|
+
return { tainted: directo || porSkeleton, obfuscated: !directo && porSkeleton };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function clasificarLegacy(registro, payloads) {
|
|
398
|
+
const detecciones = payloads.map((payload) => ({ ...payload, ...detectarTaint(payload.text) }));
|
|
399
|
+
const detectada = detecciones.find((payload) => payload.tainted);
|
|
400
|
+
registro.node.legacyStatus = detectada ? 'tainted' : 'neutrality_unproven';
|
|
401
|
+
registro.node.providerTainted = Boolean(detectada);
|
|
402
|
+
diagnosticar(
|
|
403
|
+
registro,
|
|
404
|
+
detectada ? 'PROVIDER_TAINT_DETECTED' : 'LEGACY_NEUTRALITY_UNPROVEN',
|
|
405
|
+
'warning',
|
|
406
|
+
detectada ? detectada.source : payloads[0].source
|
|
407
|
+
);
|
|
408
|
+
const ofuscada = detecciones.find((payload) => payload.obfuscated);
|
|
409
|
+
if (ofuscada) diagnosticar(
|
|
410
|
+
registro,
|
|
411
|
+
'OBFUSCATED_NATIVE_REFERENCE',
|
|
412
|
+
'warning',
|
|
413
|
+
ofuscada.source
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function payloadsArchivo(registro, claves) {
|
|
418
|
+
const payloads = claves
|
|
419
|
+
.filter((clave) => registro.parsed.valor?.[clave] !== undefined)
|
|
420
|
+
.map((clave) => ({ text: registro.parsed.valor[clave], source: fuenteCampo(registro, clave) }));
|
|
421
|
+
payloads.push({ text: registro.parsed.cuerpo, source: fuenteCuerpo(registro) });
|
|
422
|
+
return payloads;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function validarAllowlist(registro) {
|
|
426
|
+
const permitidas = ALLOWLISTS[registro.node.kind];
|
|
427
|
+
for (const clave of Object.keys(registro.parsed.valor)) {
|
|
428
|
+
if (!permitidas.has(clave)) diagnosticar(
|
|
429
|
+
registro,
|
|
430
|
+
'SOURCE_PROPERTY_UNKNOWN',
|
|
431
|
+
'error',
|
|
432
|
+
fuenteCampo(registro, clave)
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function registrarPropiedadesLegacy(registro) {
|
|
438
|
+
const locatorOnly = LOCATOR_ONLY[registro.node.kind];
|
|
439
|
+
for (const clave of Object.keys(registro.parsed.valor)) {
|
|
440
|
+
if (locatorOnly.has(clave)) diagnosticar(
|
|
441
|
+
registro,
|
|
442
|
+
'LEGACY_PROPERTY_UNMAPPED',
|
|
443
|
+
'warning',
|
|
444
|
+
fuenteCampo(registro, clave)
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function mapearTools(registro, aliases, source) {
|
|
450
|
+
if (!Array.isArray(aliases)) {
|
|
451
|
+
diagnosticar(registro, 'TOOL_MAPPING_UNKNOWN', 'error', source);
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
const capabilities = new Set();
|
|
455
|
+
let esValido = true;
|
|
456
|
+
for (const alias of aliases) {
|
|
457
|
+
const capability = TOOL_MAP[alias];
|
|
458
|
+
if (!capability) {
|
|
459
|
+
esValido = false;
|
|
460
|
+
diagnosticar(registro, 'TOOL_MAPPING_UNKNOWN', 'error', source);
|
|
461
|
+
}
|
|
462
|
+
else capabilities.add(capability);
|
|
463
|
+
}
|
|
464
|
+
registro.node.capabilities = [...capabilities].sort();
|
|
465
|
+
return esValido ? registro.node.capabilities : null;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function mapearAgente(registro) {
|
|
469
|
+
const valor = registro.parsed.valor;
|
|
470
|
+
mapearTools(registro, valor.tools, fuenteCampo(registro, 'tools'));
|
|
471
|
+
registro.node.tier = TIER_MAP[valor.model] || null;
|
|
472
|
+
if (!registro.node.tier) diagnosticar(
|
|
473
|
+
registro,
|
|
474
|
+
'MODEL_TIER_MAPPING_UNKNOWN',
|
|
475
|
+
'error',
|
|
476
|
+
fuenteCampo(registro, 'model')
|
|
477
|
+
);
|
|
478
|
+
registro.node.risk = RISK_MAP[valor.nivelRiesgo] || null;
|
|
479
|
+
if (!registro.node.risk) diagnosticar(
|
|
480
|
+
registro,
|
|
481
|
+
'RISK_MAPPING_UNKNOWN',
|
|
482
|
+
'error',
|
|
483
|
+
fuenteCampo(registro, 'nivelRiesgo')
|
|
484
|
+
);
|
|
485
|
+
if (valor.modeloAlterno !== undefined) diagnosticar(
|
|
486
|
+
registro,
|
|
487
|
+
'LEGACY_ALTERNATE_MODEL_DECLARED',
|
|
488
|
+
'warning',
|
|
489
|
+
fuenteCampo(registro, 'modeloAlterno')
|
|
490
|
+
);
|
|
491
|
+
clasificarLegacy(registro, payloadsArchivo(registro, ['name', 'description']));
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function toolsComando(registro) {
|
|
495
|
+
const valor = registro.parsed.valor;
|
|
496
|
+
const snake = Object.hasOwn(valor, 'allowed_tools');
|
|
497
|
+
const kebab = Object.hasOwn(valor, 'allowed-tools');
|
|
498
|
+
if (snake && kebab) {
|
|
499
|
+
diagnosticar(registro, 'COMMAND_TOOL_FIELD_CONFLICT', 'error', registro.node.source);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (!snake && !kebab) {
|
|
503
|
+
diagnosticar(registro, 'COMMAND_TOOL_FIELD_MISSING', 'error', registro.node.source);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
const clave = snake ? 'allowed_tools' : 'allowed-tools';
|
|
507
|
+
mapearTools(registro, valor[clave], fuenteCampo(registro, clave));
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function mapearComando(registro) {
|
|
511
|
+
toolsComando(registro);
|
|
512
|
+
diagnosticar(registro, 'COMMAND_SEMANTICS_UNSTRUCTURED', 'warning', fuenteCuerpo(registro));
|
|
513
|
+
clasificarLegacy(
|
|
514
|
+
registro,
|
|
515
|
+
payloadsArchivo(registro, ['name', 'description', 'argument-hint'])
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function mapearRecurso(registro) {
|
|
520
|
+
const claves = registro.node.kind === 'skill' ? ['name', 'description'] : [];
|
|
521
|
+
clasificarLegacy(registro, payloadsArchivo(registro, claves));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function aplicarSemanticaArchivo(registro) {
|
|
525
|
+
validarAllowlist(registro);
|
|
526
|
+
registrarPropiedadesLegacy(registro);
|
|
527
|
+
if (registro.node.kind === 'agent') mapearAgente(registro);
|
|
528
|
+
else if (registro.node.kind === 'command') mapearComando(registro);
|
|
529
|
+
else mapearRecurso(registro);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function nodoBase(kind, nodeId, source) {
|
|
533
|
+
return {
|
|
534
|
+
nodeId,
|
|
535
|
+
kind,
|
|
536
|
+
consumable: false,
|
|
537
|
+
legacyStatus: 'neutrality_unproven',
|
|
538
|
+
providerTainted: false,
|
|
539
|
+
sourceDigest: sha256(JSON.stringify(source)),
|
|
540
|
+
source,
|
|
541
|
+
selector: null,
|
|
542
|
+
capabilities: [],
|
|
543
|
+
events: [],
|
|
544
|
+
tier: null,
|
|
545
|
+
risk: null,
|
|
546
|
+
references: [],
|
|
547
|
+
policyReferences: [],
|
|
548
|
+
gates: [],
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function compilarArchivo(entry) {
|
|
553
|
+
const descriptor = entry;
|
|
554
|
+
const snapshot = entry.source;
|
|
555
|
+
const parsed = entry.parsed;
|
|
556
|
+
const nodeId = `${descriptor.kind}:${sha256(descriptor.path)}`;
|
|
557
|
+
const node = nodoBase(
|
|
558
|
+
descriptor.kind,
|
|
559
|
+
nodeId,
|
|
560
|
+
fuenteNodo(snapshot, locatorArchivo(snapshot.texto))
|
|
561
|
+
);
|
|
562
|
+
const registro = { node, snapshot, parsed, diagnostics: [] };
|
|
563
|
+
aplicarSemanticaArchivo(registro);
|
|
564
|
+
return registro;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function mapearMatcher(registro, matcher) {
|
|
568
|
+
if (matcher === '') {
|
|
569
|
+
registro.node.selector = { kind: 'all_tools' };
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
if (!/^[A-Za-z]+(?:\|[A-Za-z]+)*$/u.test(matcher)) {
|
|
573
|
+
diagnosticar(registro, 'HOOK_MATCHER_UNKNOWN', 'error');
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
const capabilities = mapearTools(registro, matcher.split('|'), registro.node.source);
|
|
577
|
+
if (!capabilities) {
|
|
578
|
+
registro.diagnostics = registro.diagnostics.filter(
|
|
579
|
+
({ code }) => code !== 'TOOL_MAPPING_UNKNOWN'
|
|
580
|
+
);
|
|
581
|
+
diagnosticar(registro, 'HOOK_MATCHER_UNKNOWN', 'error');
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
registro.node.selector = { kind: 'capabilities', anyOf: capabilities };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function mapearEvento(registro, event) {
|
|
588
|
+
if (EVENT_MAP[event]) registro.node.events = [EVENT_MAP[event]];
|
|
589
|
+
else if (EVENTOS_FUERA_V1.has(event)) diagnosticar(
|
|
590
|
+
registro,
|
|
591
|
+
'SOURCE_EVENT_OUTSIDE_IR_V1',
|
|
592
|
+
'warning'
|
|
593
|
+
);
|
|
594
|
+
else diagnosticar(registro, 'EVENT_MAPPING_UNKNOWN', 'error');
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function mapearHook(registro, entrada, clave) {
|
|
598
|
+
mapearEvento(registro, entrada.event);
|
|
599
|
+
mapearMatcher(registro, entrada.matcher);
|
|
600
|
+
clasificarLegacy(registro, [
|
|
601
|
+
{ text: clave, source: registro.node.source },
|
|
602
|
+
{ text: entrada.description, source: registro.node.source },
|
|
603
|
+
]);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function compilarHooks(captura) {
|
|
607
|
+
const snapshot = captura.source;
|
|
608
|
+
const { config, propiedades } = validarHooksParseados(captura.parsed);
|
|
609
|
+
return Object.keys(config.hooks).map((clave) => {
|
|
610
|
+
const pointer = `/hooks/${clave.replaceAll('~', '~0').replaceAll('/', '~1')}`;
|
|
611
|
+
const nodeId = `hook:${sha256(`${HOOKS_CONFIG}\0${pointer}`)}`;
|
|
612
|
+
const locator = propiedades[pointer].locator;
|
|
613
|
+
const node = nodoBase('hook', nodeId, fuenteNodo(snapshot, locator));
|
|
614
|
+
const registro = { node, snapshot, parsed: null, diagnostics: [] };
|
|
615
|
+
mapearHook(registro, config.hooks[clave], clave);
|
|
616
|
+
return registro;
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function normalizarReferencia(valor) {
|
|
621
|
+
return String(valor).normalize('NFKC').toLowerCase();
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function indiceSkills(registros) {
|
|
625
|
+
const porPath = new Map();
|
|
626
|
+
const basenames = new Map();
|
|
627
|
+
for (const registro of registros.filter(({ node }) => node.kind === 'skill')) {
|
|
628
|
+
porPath.set(registro.node.source.path, registro);
|
|
629
|
+
const basename = registro.node.source.path.split('/')[1];
|
|
630
|
+
const normalizado = normalizarReferencia(basename);
|
|
631
|
+
basenames.set(normalizado, (basenames.get(normalizado) || 0) + 1);
|
|
632
|
+
}
|
|
633
|
+
return { porPath, basenames };
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function referenciaHash(registro, referencia, code) {
|
|
637
|
+
const source = fuenteCampo(registro, 'skillsInvocables');
|
|
638
|
+
registro.node.policyReferences.push({ refHash: sha256(referencia), source });
|
|
639
|
+
diagnosticar(registro, code, 'warning', source);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function resolverReferenciaLocal(registro, referencia, skills) {
|
|
643
|
+
const sourcePath = `habilidades/${referencia}/SKILL.md`;
|
|
644
|
+
const destino = skills.porPath.get(sourcePath);
|
|
645
|
+
if (!destino) return false;
|
|
646
|
+
const basename = normalizarReferencia(referencia);
|
|
647
|
+
const nombre = normalizarReferencia(destino.parsed.valor.name);
|
|
648
|
+
if (skills.basenames.get(basename) !== 1 || nombre !== basename) return false;
|
|
649
|
+
registro.node.references.push(destino.node.nodeId);
|
|
650
|
+
return true;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function resolverReferencias(registros) {
|
|
654
|
+
const skills = indiceSkills(registros);
|
|
655
|
+
for (const registro of registros.filter(({ node }) => node.kind === 'agent')) {
|
|
656
|
+
const referencias = registro.parsed.valor.skillsInvocables;
|
|
657
|
+
if (!Array.isArray(referencias)) {
|
|
658
|
+
diagnosticar(
|
|
659
|
+
registro,
|
|
660
|
+
'SKILL_REFERENCE_UNKNOWN',
|
|
661
|
+
'error',
|
|
662
|
+
fuenteCampo(registro, 'skillsInvocables')
|
|
663
|
+
);
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
for (const referencia of referencias) {
|
|
667
|
+
if (resolverReferenciaLocal(registro, referencia, skills)) continue;
|
|
668
|
+
if (SKILLS_EXTERNAS_SET.has(referencia)) {
|
|
669
|
+
referenciaHash(registro, referencia, 'EXTERNAL_SKILL_REFERENCE');
|
|
670
|
+
} else if (referencia === CENTINELA_TODOS) {
|
|
671
|
+
referenciaHash(registro, referencia, 'LEGACY_SKILL_WILDCARD');
|
|
672
|
+
} else diagnosticar(
|
|
673
|
+
registro,
|
|
674
|
+
'SKILL_REFERENCE_UNKNOWN',
|
|
675
|
+
'error',
|
|
676
|
+
fuenteCampo(registro, 'skillsInvocables')
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
registro.node.references.sort();
|
|
680
|
+
registro.node.policyReferences.sort((a, b) => a.refHash.localeCompare(b.refHash));
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function ordenarValor(valor) {
|
|
685
|
+
if (Array.isArray(valor)) return valor.map(ordenarValor);
|
|
686
|
+
if (!valor || typeof valor !== 'object') return valor;
|
|
687
|
+
return Object.fromEntries(
|
|
688
|
+
Object.keys(valor).sort().map((clave) => [clave, ordenarValor(valor[clave])])
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function serializarVista(vista) {
|
|
693
|
+
return `${JSON.stringify(ordenarValor(vista), null, 2)}\n`;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
function contarNodos(nodos, diagnostics) {
|
|
697
|
+
const counts = Object.fromEntries(TIPOS.map((tipo) => [tipo, 0]));
|
|
698
|
+
counts.hook = 0;
|
|
699
|
+
for (const nodo of nodos) counts[nodo.kind] += 1;
|
|
700
|
+
return {
|
|
701
|
+
agents: counts.agent,
|
|
702
|
+
commands: counts.command,
|
|
703
|
+
skills: counts.skill,
|
|
704
|
+
rules: counts.rule,
|
|
705
|
+
hooks: counts.hook,
|
|
706
|
+
total: nodos.length,
|
|
707
|
+
errors: diagnostics.filter(({ severity }) => severity === 'error').length,
|
|
708
|
+
warnings: diagnostics.filter(({ severity }) => severity === 'warning').length,
|
|
709
|
+
consumable: 0,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function catalogar(nodos, propiedad, ids) {
|
|
714
|
+
return ids.map((id) => ({
|
|
715
|
+
id,
|
|
716
|
+
declaredBy: nodos
|
|
717
|
+
.filter((nodo) => nodo[propiedad].includes(id))
|
|
718
|
+
.map(({ nodeId }) => nodeId)
|
|
719
|
+
.sort(),
|
|
720
|
+
}));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function compararDiagnosticos(a, b) {
|
|
724
|
+
return [a.code, a.nodeId, a.source.path, JSON.stringify(a.source.locator)]
|
|
725
|
+
.join('\0')
|
|
726
|
+
.localeCompare([b.code, b.nodeId, b.source.path, JSON.stringify(b.source.locator)].join('\0'));
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function construirIR(nodos) {
|
|
730
|
+
return {
|
|
731
|
+
kind: 'harness-ir',
|
|
732
|
+
schemaVersion: '1.0.0',
|
|
733
|
+
nodes: [...nodos].sort((a, b) => a.nodeId.localeCompare(b.nodeId)),
|
|
734
|
+
capabilities: catalogar(nodos, 'capabilities', CAPABILITIES),
|
|
735
|
+
events: catalogar(nodos, 'events', Object.values(EVENT_MAP).sort()),
|
|
736
|
+
tiers: TIER_DEFINITIONS,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function construirVista(registros) {
|
|
741
|
+
const nodos = registros.map(({ node }) => node);
|
|
742
|
+
const diagnostics = registros
|
|
743
|
+
.flatMap((registro) => registro.diagnostics)
|
|
744
|
+
.sort(compararDiagnosticos);
|
|
745
|
+
const counts = contarNodos(nodos, diagnostics);
|
|
746
|
+
const compilado = construirIR(nodos);
|
|
747
|
+
const ir = counts.errors > 0 ? null : compilado;
|
|
748
|
+
const vista = {
|
|
749
|
+
kind: 'diagnostic-view',
|
|
750
|
+
schemaVersion: '1.0.0',
|
|
751
|
+
shadowStatus: 'diagnostic_only',
|
|
752
|
+
ir,
|
|
753
|
+
counts,
|
|
754
|
+
diagnostics,
|
|
755
|
+
corpusDigest: sha256(serializarVista({ ir, diagnostics })),
|
|
756
|
+
};
|
|
757
|
+
const validacion = validarContrato(vista);
|
|
758
|
+
if (!validacion.ok) throw crearErrorHarness(
|
|
759
|
+
'HARNESS_CONTRACT_INVALID',
|
|
760
|
+
'La vista generada viola el contrato',
|
|
761
|
+
{ errors: validacion.errors }
|
|
762
|
+
);
|
|
763
|
+
return vista;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
function compilarHarnessIR() {
|
|
767
|
+
const snapshot = capturarHarnessSourceSnapshot();
|
|
768
|
+
const registros = snapshot.entries.map(compilarArchivo);
|
|
769
|
+
registros.push(...compilarHooks(snapshot.hooks));
|
|
770
|
+
resolverReferencias(registros);
|
|
771
|
+
return construirVista(registros);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
module.exports = {
|
|
775
|
+
compilarHarnessIR,
|
|
776
|
+
serializarVista,
|
|
777
|
+
validarContrato,
|
|
778
|
+
};
|