-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.cjs
More file actions
214 lines (196 loc) · 8.07 KB
/
Copy pathhandler.cjs
File metadata and controls
214 lines (196 loc) · 8.07 KB
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
#!/usr/bin/env node
'use strict';
/**
* libroforge — hook handler para Claude Code (proyecto destino).
*
* Stdin: JSON con datos del hook (tool_name, tool_input, tool_response, etc.).
* Stdout (no-block): cualquier texto se inyecta como contexto al modelo.
* Stdout (block): JSON `{ "decision": "block", "reason": "…" }` → Claude reescribe sin pedir permiso.
*
* Este archivo se copia al proyecto destino como `.claude/hooks/handler.cjs`. ES EDITABLE.
*
* Para que la lógica de validación viva centralizada y reciba updates al actualizar `libroforge`,
* los helpers se importan desde el paquete: `require('libroforge/lib/...')`. Si quieres
* desacoplarte completamente, sustituye los imports por implementaciones inline.
*/
const fs = require('fs');
const path = require('path');
const PROJECT_DIR = process.env.CLAUDE_PROJECT_DIR || process.cwd();
let lib;
try {
lib = {
sectionCheck: require('libroforge/lib/section-check').sectionCheck,
countVerificarMarkers: require('libroforge/lib/section-check').countVerificarMarkers,
apaCheck: require('libroforge/lib/apa-check').apaCheck,
loadProfile: require('libroforge/lib/profile').loadProfile,
listAll: require('libroforge/lib/audit-report').listAll,
};
} catch (e) {
// libroforge no está instalado en el proyecto. Salimos sin bloquear pero avisamos.
emitContext(`⚠ libroforge no está en node_modules/. Ejecuta "npm install" en ${PROJECT_DIR} para activar la verificación automática.`);
process.exit(0);
}
const verb = process.argv[2];
let payload = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (chunk) => (payload += chunk));
process.stdin.on('end', () => {
let input = {};
try {
input = payload ? JSON.parse(payload) : {};
} catch (e) {
// Hooks pueden recibir payload inválido en algunos contextos; tratamos como vacío.
}
try {
if (verb === 'post-write') return handlePostWrite(input);
if (verb === 'pre-stop') return handlePreStop(input);
process.exit(0);
} catch (e) {
// Nunca dejamos que un fallo del handler bloquee a Claude — informamos y salimos.
emitContext(`(libroforge handler error: ${e.message})`);
process.exit(0);
}
});
function handlePostWrite(input) {
const filePath = (input.tool_input && (input.tool_input.file_path || input.tool_input.path)) || '';
if (!filePath) return process.exit(0);
const rel = path.relative(PROJECT_DIR, filePath);
// chapter file
if (/^capitulos\/\d+[\-_].+\.md$/.test(rel) || /^capitulos\/\d+\.md$/.test(rel)) {
return checkChapter(filePath);
}
if (rel === 'bibliografia.md') {
return checkBibliografia(filePath);
}
if (rel === 'indice.md') {
return checkIndice(filePath);
}
// Otros archivos: no validamos.
process.exit(0);
}
function checkChapter(file) {
if (!fs.existsSync(file)) process.exit(0);
const md = fs.readFileSync(file, 'utf8');
const profile = lib.loadProfile(PROJECT_DIR);
const sc = lib.sectionCheck(md, profile);
const verificar = lib.countVerificarMarkers(md);
const maxVerificar = (profile.quality && profile.quality.max_verificar_markers) || Infinity;
// Solo bloqueamos si el capítulo está "cerrado" (todas las secciones presentes y total cerca del mínimo).
if (sc.state === 'closed') {
const reasons = [...sc.blocking];
if (verificar > maxVerificar) {
reasons.push(`${verificar} marcadores [VERIFICAR] presentes — máximo permitido: ${maxVerificar}.`);
}
if (reasons.length) {
return emitBlock(
`Capítulo ${path.basename(file)} no cumple las reglas del perfil "${profile.id}":\n - ` +
reasons.join('\n - ') +
'\n\nReescribe el capítulo cumpliendo TODAS las reglas. Recuerda: cada sección H2 debe estar dentro de su rango. Total: entre ' +
profile.chapter.min_words +
' y ' +
(profile.chapter.max_words || '∞') +
' palabras.'
);
}
// Pasa: dejamos contexto informativo (visible al modelo).
return emitContext(
`[libroforge] ✓ ${path.basename(file)} pasa hook (${sc.total} palabras, ${sc.sections.filter((s) => s.found).length}/${sc.sections.length} secciones, ${verificar} [VERIFICAR]).`
);
}
// draft: no bloqueamos, pero avisamos qué falta.
if (sc.warnings.length) {
return emitContext(
`[libroforge] ${path.basename(file)} aún en borrador. Pendiente:\n - ` +
sc.warnings.slice(0, 5).join('\n - ')
);
}
process.exit(0);
}
function checkBibliografia(file) {
if (!fs.existsSync(file)) process.exit(0);
const md = fs.readFileSync(file, 'utf8');
const r = lib.apaCheck(md);
if (r.ok || r.total === 0) {
return emitContext(`[libroforge] ✓ bibliografia.md (${r.total} entradas) pasa heurística APA.`);
}
// Solo bloqueamos si hay ≥3 entradas con problemas (evita falsos positivos en borradores)
if (r.issues.length >= 3) {
const summary = r.issues
.slice(0, 5)
.map((i) => ` - L${i.line}: ${i.problems.join(' / ')}`)
.join('\n');
return emitBlock(
`bibliografia.md tiene ${r.issues.length} entradas con problemas APA:\n${summary}\n\n` +
'Corrige el formato APA 7. Cada entrada debe tener: Apellido, X. (YYYY). Título. Editorial. (terminado en punto).'
);
}
return emitContext(
`[libroforge] ⚠ bibliografia.md: ${r.issues.length} entradas con problemas APA menores. Revisa antes del cierre.`
);
}
function checkIndice(file) {
if (!fs.existsSync(file)) process.exit(0);
const md = fs.readFileSync(file, 'utf8');
// Heurística: contamos líneas tipo "1. Título" o "## Capítulo N — Título"
const numberedLines = (md.match(/^\s*\d+\.\s+\S+/gm) || []).length;
const chapterHeadings = (md.match(/^\s*##\s+(Cap[íi]tulo|Tema|Unidad)/gmi) || []).length;
const total = Math.max(numberedLines, chapterHeadings);
return emitContext(`[libroforge] ✓ indice.md detectado con ${total} entradas.`);
}
function handlePreStop(input) {
// Verificar completitud: cada entrada del índice tiene su capítulo, cada capítulo tiene 3 audit-reports PASS.
const profile = (() => {
try {
return lib.loadProfile(PROJECT_DIR);
} catch (_) {
return null;
}
})();
const indicePath = path.join(PROJECT_DIR, 'indice.md');
if (!fs.existsSync(indicePath)) process.exit(0);
const indiceMd = fs.readFileSync(indicePath, 'utf8');
const expectedCount = countIndiceEntries(indiceMd);
if (expectedCount === 0) process.exit(0);
const capitulosDir = path.join(PROJECT_DIR, 'capitulos');
const chapters = fs.existsSync(capitulosDir)
? fs.readdirSync(capitulosDir).filter((f) => /^\d{2}[\-_].+\.md$/.test(f) || /^\d{2}\.md$/.test(f))
: [];
if (chapters.length < expectedCount) {
return emitContext(
`[libroforge] STOP bloqueado: faltan ${expectedCount - chapters.length} de ${expectedCount} capítulos. ` +
`Continúa con el siguiente capítulo. (No cedas turno hasta completar.)`
);
}
const reports = lib.listAll(PROJECT_DIR);
const blocked = [];
for (let n = 1; n <= expectedCount; n++) {
const r = reports[n] || {};
const allPass = ['quality', 'factual', 'biblio'].every((a) => r[a] && r[a].status === 'PASS');
if (!allPass) blocked.push(n);
}
if (blocked.length) {
return emitContext(
`[libroforge] STOP bloqueado: capítulos sin auditoría completa: ${blocked.join(', ')}. ` +
`Lanza los auditores faltantes (quality/factual/biblio) y, si fallan, revision-editor.`
);
}
// libro-final.md
if (!fs.existsSync(path.join(PROJECT_DIR, 'libro-final.md'))) {
return emitContext(`[libroforge] STOP: falta libro-final.md. Invoca a integration-compositor.`);
}
process.exit(0);
}
function countIndiceEntries(md) {
const numbered = (md.match(/^\s*\d+\.\s+\S+/gm) || []).length;
const chapterHeadings = (md.match(/^\s*##\s+(Cap[íi]tulo|Tema|Unidad)/gmi) || []).length;
return Math.max(numbered, chapterHeadings);
}
function emitBlock(reason) {
process.stdout.write(JSON.stringify({ decision: 'block', reason }));
process.exit(0);
}
function emitContext(text) {
// Stdout no-JSON se trata como contexto adicional al modelo.
process.stdout.write(text + '\n');
process.exit(0);
}