specbox 6.36.0 → 6.38.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/hooks/app-docs-fragment.mjs +119 -0
- package/hooks/commit-spec-guard.mjs +27 -8
- package/hooks/context-budget-guard.mjs +82 -46
- package/hooks/freeform-fragment.mjs +6 -8
- package/hooks/hooks-history.json +39 -7
- package/hooks/hooks-manifest.json +16 -8
- package/hooks/lib/config.mjs +24 -1
- package/hooks/lib/enforcement-events.mjs +74 -0
- package/hooks/lib/enforcement-policy.mjs +8 -3
- package/hooks/lib/prd-locate.mjs +72 -0
- package/hooks/lib/reservation-probe.mjs +92 -0
- package/hooks/lib/roadmap.mjs +77 -0
- package/hooks/lib/uc-state.mjs +170 -0
- package/hooks/prd-sync-guard.mjs +131 -0
- package/hooks/settings-hooks.json +21 -0
- package/hooks/spec-guard.mjs +36 -50
- package/hooks/uc-lifecycle-guard.mjs +31 -20
- package/hooks/uc-state-marker.mjs +57 -0
- package/package.json +1 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/enforcement-events.mjs — los bloqueos de las medidas que aplican los hooks quedan en el tablero (UC-12213).
|
|
3
|
+
*
|
|
4
|
+
* native: `record_enforcement_event` con la identidad del dispositivo (2,5 s); FreeForm: una línea en
|
|
5
|
+
* doc/tracking/enforcement_events.jsonl. Un `passed` tras un `blocked` de la misma medida y UC cuenta
|
|
6
|
+
* como corregido. Nunca lanza.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
11
|
+
import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './heartbeat-send.mjs';
|
|
12
|
+
import { llamarTool } from './mcp-client.mjs';
|
|
13
|
+
|
|
14
|
+
const STATE = join('.quality', 'enforcement_blocked.json');
|
|
15
|
+
|
|
16
|
+
function readState(root) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(readFileSync(join(root, STATE), 'utf-8')) || {};
|
|
19
|
+
} catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function writeState(root, state) {
|
|
25
|
+
try {
|
|
26
|
+
mkdirSync(dirname(join(root, STATE)), { recursive: true });
|
|
27
|
+
writeFileSync(join(root, STATE), JSON.stringify(state));
|
|
28
|
+
} catch { /* sin estado, la corrección no se registra */ }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Registra `blocked` o `passed` de `measure` en `ucId`. `config` = getProjectConfig(). */
|
|
32
|
+
export async function recordEnforcementEvent({ root = process.cwd(), config, measure, ucId, outcome, by, env = process.env }) {
|
|
33
|
+
if (!ucId || !config) return false;
|
|
34
|
+
const state = readState(root);
|
|
35
|
+
if (outcome === 'blocked') state[measure] = ucId;
|
|
36
|
+
else delete state[measure];
|
|
37
|
+
writeState(root, state);
|
|
38
|
+
const at = new Date().toISOString();
|
|
39
|
+
if (config.backendType === 'freeform') {
|
|
40
|
+
try {
|
|
41
|
+
const dir = config.freeformRoot && isAbsolute(config.freeformRoot) ? config.freeformRoot : join(root, 'doc', 'tracking');
|
|
42
|
+
mkdirSync(dir, { recursive: true });
|
|
43
|
+
appendFileSync(join(dir, 'enforcement_events.jsonl'), `${JSON.stringify({ measure, uc_id: ucId, outcome, at, by })}\n`);
|
|
44
|
+
return true;
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (config.backendType !== 'native' || !config.boardId || env.SPECBOX_ENFORCEMENT_POLICY === 'off') return false;
|
|
50
|
+
try {
|
|
51
|
+
const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
|
|
52
|
+
const cabeceras = await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url });
|
|
53
|
+
if (!cabeceras.Authorization) return false;
|
|
54
|
+
const r = await llamarTool({
|
|
55
|
+
url,
|
|
56
|
+
cabeceras,
|
|
57
|
+
nombre: 'record_enforcement_event',
|
|
58
|
+
args: { measure, uc_id: ucId, outcome, board_id: config.boardId },
|
|
59
|
+
topeMs: 2500,
|
|
60
|
+
});
|
|
61
|
+
return !!r?.success;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Si la última vez `measure` bloqueó `ucId`, ahora pasa: se registra la corrección. */
|
|
68
|
+
export async function recordCorrectionIfBlocked(args) {
|
|
69
|
+
const state = readState(args.root || process.cwd());
|
|
70
|
+
if (state[args.measure] && state[args.measure] === args.ucId) {
|
|
71
|
+
return recordEnforcementEvent({ ...args, outcome: 'passed' });
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
@@ -37,6 +37,7 @@ export const MEASURES = {
|
|
|
37
37
|
drift_gate: 'warn',
|
|
38
38
|
impact_radius: 'warn',
|
|
39
39
|
contract_first: 'warn',
|
|
40
|
+
commit_on_main: 'warn',
|
|
40
41
|
};
|
|
41
42
|
|
|
42
43
|
/** El modo de cada medida a partir de lo guardado (o null), como effective_policy del servidor. */
|
|
@@ -44,13 +45,17 @@ export function modosDe(raw, backendType) {
|
|
|
44
45
|
const origin = raw && (raw.origin === 'new' || raw.origin === 'existing') ? raw.origin : 'existing';
|
|
45
46
|
const guardadas = raw && typeof raw.measures === 'object' && raw.measures ? raw.measures : {};
|
|
46
47
|
const modos = {};
|
|
48
|
+
const explicitas = [];
|
|
47
49
|
for (const [clave, nuevo] of Object.entries(MEASURES)) {
|
|
48
50
|
const entrada = guardadas[clave];
|
|
49
|
-
|
|
51
|
+
const guardada = !!entrada && MODES.includes(entrada.mode);
|
|
52
|
+
let modo = guardada ? entrada.mode : origin === 'new' ? nuevo : 'warn';
|
|
50
53
|
if (CAPPED_BACKENDS.has(backendType) && modo === 'block') modo = 'warn';
|
|
51
54
|
modos[clave] = modo;
|
|
55
|
+
// UC-12215: la puso una persona (no es el valor por defecto del tablero).
|
|
56
|
+
if (guardada && entrada.source !== 'default') explicitas.push(clave);
|
|
52
57
|
}
|
|
53
|
-
return { origin, backendType, modos };
|
|
58
|
+
return { origin, backendType, modos, explicitas };
|
|
54
59
|
}
|
|
55
60
|
|
|
56
61
|
/** El modo de una medida en una política leída con leerPolitica («warn» si no la conoce). */
|
|
@@ -120,7 +125,7 @@ export async function leerPolitica({
|
|
|
120
125
|
const policy = {
|
|
121
126
|
origin: r.policy.origin,
|
|
122
127
|
measures: Object.fromEntries(
|
|
123
|
-
Object.entries(r.policy.measures || {}).map(([k, v]) => [k, { mode: v?.mode }]),
|
|
128
|
+
Object.entries(r.policy.measures || {}).map(([k, v]) => [k, { mode: v?.mode, source: v?.source }]),
|
|
124
129
|
),
|
|
125
130
|
};
|
|
126
131
|
try {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/prd-locate.mjs — dónde está el PRD de una UC (UC-12211).
|
|
3
|
+
*
|
|
4
|
+
* Mismo orden que `find_prd_path` de server/prd_writer.py (una prueba lo compara):
|
|
5
|
+
* 1. doc/prds/{feature}_prd.md o doc/prds/{feature}.md
|
|
6
|
+
* 2. doc/prds/{us normalizada}_prd.md (US-01 → us_01)
|
|
7
|
+
* 3. doc/prd/{feature}.md o doc/prd/{feature}/prd.md
|
|
8
|
+
* 4. el único PRD que nombra la historia (doc/prd/*\/prd.md, doc/prd/*.md, doc/prds/*.md)
|
|
9
|
+
* 5. el único fichero de doc/prds/
|
|
10
|
+
* Devuelve la ruta relativa a `root`, o null.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
|
|
16
|
+
const isFile = (path) => {
|
|
17
|
+
try {
|
|
18
|
+
return statSync(path).isFile();
|
|
19
|
+
} catch {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const list = (dir) => {
|
|
24
|
+
try {
|
|
25
|
+
return readdirSync(dir).sort();
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Todos los PRD del proyecto, en orden estable (rutas relativas). */
|
|
32
|
+
export function prdCandidates(root) {
|
|
33
|
+
const out = [];
|
|
34
|
+
for (const name of list(join(root, 'doc', 'prd'))) {
|
|
35
|
+
if (isFile(join(root, 'doc', 'prd', name, 'prd.md'))) out.push(`doc/prd/${name}/prd.md`);
|
|
36
|
+
}
|
|
37
|
+
for (const name of list(join(root, 'doc', 'prd'))) {
|
|
38
|
+
if (name.endsWith('.md') && isFile(join(root, 'doc', 'prd', name))) out.push(`doc/prd/${name}`);
|
|
39
|
+
}
|
|
40
|
+
for (const name of list(join(root, 'doc', 'prds'))) {
|
|
41
|
+
if (name.endsWith('.md') && isFile(join(root, 'doc', 'prds', name))) out.push(`doc/prds/${name}`);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function locatePrd({ root, feature = '', usId = '' } = {}) {
|
|
47
|
+
const has = (rel) => existsSync(join(root, rel)) && isFile(join(root, rel));
|
|
48
|
+
if (feature) {
|
|
49
|
+
for (const rel of [`doc/prds/${feature}_prd.md`, `doc/prds/${feature}.md`]) if (has(rel)) return rel;
|
|
50
|
+
}
|
|
51
|
+
if (usId) {
|
|
52
|
+
const rel = `doc/prds/${usId.toLowerCase().replace(/-/g, '_')}_prd.md`;
|
|
53
|
+
if (has(rel)) return rel;
|
|
54
|
+
}
|
|
55
|
+
if (feature) {
|
|
56
|
+
for (const rel of [`doc/prd/${feature}.md`, `doc/prd/${feature}/prd.md`]) if (has(rel)) return rel;
|
|
57
|
+
}
|
|
58
|
+
if (usId) {
|
|
59
|
+
const word = new RegExp(`\\b${usId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
|
60
|
+
const named = prdCandidates(root).filter((rel) => {
|
|
61
|
+
try {
|
|
62
|
+
return word.test(readFileSync(join(root, rel), 'utf-8'));
|
|
63
|
+
} catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
if (named.length === 1) return named[0];
|
|
68
|
+
}
|
|
69
|
+
const prds = list(join(root, 'doc', 'prds')).filter((n) => n.endsWith('.md'));
|
|
70
|
+
if (prds.length === 1) return `doc/prds/${prds[0]}`;
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/reservation-probe.mjs — spec-guard pregunta al tablero quién tiene la reserva (UC-12217).
|
|
3
|
+
*
|
|
4
|
+
* Antes pedía GET /api/native/reservation-status, que el servidor no tiene: fallaba siempre, se daba
|
|
5
|
+
* la caché por buena y el bloqueo por reserva perdida no saltaba nunca. Ahora llama a la tool de
|
|
6
|
+
* solo lectura `get_uc_reservation` con la identidad del dispositivo (`llamarTool`, tope de 3 s).
|
|
7
|
+
*
|
|
8
|
+
* - Una respuesta confirmada se guarda 60 s en .quality/reservation_check.json para no preguntar en
|
|
9
|
+
* cada escritura.
|
|
10
|
+
* - Sin credencial, sin red o sin respuesta: `reachable: false` (se usa la reserva guardada) y una
|
|
11
|
+
* nota como mucho cada 10 minutos.
|
|
12
|
+
* Nunca lanza.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { dirname, join } from 'node:path';
|
|
17
|
+
import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './heartbeat-send.mjs';
|
|
18
|
+
import { llamarTool } from './mcp-client.mjs';
|
|
19
|
+
|
|
20
|
+
export const CHECK_FILE = join('.quality', 'reservation_check.json');
|
|
21
|
+
export const CONFIRMED_MS = 60_000;
|
|
22
|
+
export const OFFLINE_NOTE_MS = 10 * 60_000;
|
|
23
|
+
|
|
24
|
+
function readState(root) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(join(root, CHECK_FILE), 'utf-8')) || {};
|
|
27
|
+
} catch {
|
|
28
|
+
return {};
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function writeState(root, state) {
|
|
33
|
+
try {
|
|
34
|
+
const path = join(root, CHECK_FILE);
|
|
35
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
36
|
+
writeFileSync(path, `${JSON.stringify(state)}\n`);
|
|
37
|
+
} catch {
|
|
38
|
+
// sin caché, la próxima escritura vuelve a preguntar
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* { reachable, reservation?, why? } para la reserva guardada `{ ucId, developerId }` del proyecto.
|
|
44
|
+
* `why` explica por qué no se pudo comprobar (para la nota).
|
|
45
|
+
*/
|
|
46
|
+
export async function probeReservation({
|
|
47
|
+
root = process.cwd(),
|
|
48
|
+
projectId,
|
|
49
|
+
reservation,
|
|
50
|
+
env = process.env,
|
|
51
|
+
fetchImpl = fetch,
|
|
52
|
+
cabeceras,
|
|
53
|
+
ahora = Date.now(),
|
|
54
|
+
topeMs = 3000,
|
|
55
|
+
} = {}) {
|
|
56
|
+
if (!projectId || !reservation?.ucId) return { reachable: false, why: 'el marcador no dice de qué proyecto es' };
|
|
57
|
+
const state = readState(root);
|
|
58
|
+
const ok = state.confirmed;
|
|
59
|
+
if (ok && ok.uc_id === reservation.ucId && ok.developer_id === reservation.developerId && ahora - ok.at < CONFIRMED_MS) {
|
|
60
|
+
return { reachable: true, reservation: { developer_id: ok.developer_id }, cached: true };
|
|
61
|
+
}
|
|
62
|
+
if (env.SPECBOX_RESERVATION_CHECK === 'off') return { reachable: false, why: 'la comprobación está apagada' };
|
|
63
|
+
const url = env.SPECBOX_MCP_URL || env.SPECBOX_ENGINE_MCP_URL || URL_POR_DEFECTO;
|
|
64
|
+
try {
|
|
65
|
+
const h = cabeceras ?? (await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url }));
|
|
66
|
+
if (!h.Authorization) return { reachable: false, why: 'este equipo no tiene credencial de SpecBox' };
|
|
67
|
+
const r = await llamarTool({
|
|
68
|
+
url,
|
|
69
|
+
cabeceras: h,
|
|
70
|
+
nombre: 'get_uc_reservation',
|
|
71
|
+
args: { uc_id: reservation.ucId, project_id: projectId },
|
|
72
|
+
topeMs,
|
|
73
|
+
fetchImpl,
|
|
74
|
+
});
|
|
75
|
+
if (!r?.success) return { reachable: false, why: `el tablero no la devolvió (${r?.code || 'sin código'})` };
|
|
76
|
+
const remote = r.reservation ?? null;
|
|
77
|
+
if (remote?.developer_id === reservation.developerId) {
|
|
78
|
+
writeState(root, { ...state, confirmed: { uc_id: reservation.ucId, developer_id: remote.developer_id, at: ahora } });
|
|
79
|
+
}
|
|
80
|
+
return { reachable: true, reservation: remote };
|
|
81
|
+
} catch {
|
|
82
|
+
return { reachable: false, why: 'sin red o sin respuesta en 3 s' };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** True si toca dar la nota de «no se pudo comprobar» (como mucho cada 10 minutos); la apunta. */
|
|
87
|
+
export function shouldNoteOffline(root = process.cwd(), ahora = Date.now()) {
|
|
88
|
+
const state = readState(root);
|
|
89
|
+
if (typeof state.offline_note_at === 'number' && ahora - state.offline_note_at < OFFLINE_NOTE_MS) return false;
|
|
90
|
+
writeState(root, { ...state, offline_note_at: ahora });
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/roadmap.mjs — la zona «roadmap» de app_prd.md con lo que dice el tablero (UC-12203).
|
|
3
|
+
*
|
|
4
|
+
* Copia de `server/app_docs/roadmap.py` para FreeForm por fragmentos: el servidor no ve el tablero
|
|
5
|
+
* entero y el hook calcula el mismo cuerpo con su items.json. tests/test_app_docs_roadmap.py compara
|
|
6
|
+
* las dos salidas. `replaceZone` reemplaza el cuerpo como `replace_zone_body` (por líneas, sin tocar
|
|
7
|
+
* los marcadores ni lo de fuera).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const US_PREFIX = /^\[?US-\d+[a-z]?\]?\s*[:—–-]?\s*/;
|
|
11
|
+
const US_ID = /^\[?(US-\d+[a-z]?)/;
|
|
12
|
+
const US_NUMBER = /^US-(\d+)/;
|
|
13
|
+
|
|
14
|
+
function title(name, usId) {
|
|
15
|
+
const text = usId ? String(name || '').trim().replace(US_PREFIX, '') : String(name || '').trim();
|
|
16
|
+
return text.split(/\s+/).filter(Boolean).join(' ').replace(/\|/g, '\\|');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function order(a, b) {
|
|
20
|
+
const na = US_NUMBER.exec(a.us_id);
|
|
21
|
+
const nb = US_NUMBER.exec(b.us_id);
|
|
22
|
+
const ka = na ? Number(na[1]) : 1e9;
|
|
23
|
+
const kb = nb ? Number(nb[1]) : 1e9;
|
|
24
|
+
if (ka !== kb) return ka - kb;
|
|
25
|
+
return a.us_id < b.us_id ? -1 : a.us_id > b.us_id ? 1 : 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const has = (item, label) => Array.isArray(item?.labels) && item.labels.includes(label);
|
|
29
|
+
|
|
30
|
+
/** Una fila por historia no archivada: id, título, estado y UC hechas/total (sin archivadas). */
|
|
31
|
+
export function rowsFromItems(items) {
|
|
32
|
+
const stories = new Map();
|
|
33
|
+
for (const item of items || []) {
|
|
34
|
+
if (!has(item, 'US') || item.state === 'archived') continue;
|
|
35
|
+
const usId = item.meta?.us_id || US_ID.exec(item.name || '')?.[1] || '';
|
|
36
|
+
if (usId) stories.set(item.id, { us_id: usId, title: title(item.name, usId), state: item.state || '', done: 0, total: 0 });
|
|
37
|
+
}
|
|
38
|
+
for (const item of items || []) {
|
|
39
|
+
if (!has(item, 'UC') || item.state === 'archived' || !stories.has(item.parent_id)) continue;
|
|
40
|
+
const row = stories.get(item.parent_id);
|
|
41
|
+
row.total += 1;
|
|
42
|
+
if (item.state === 'done') row.done += 1;
|
|
43
|
+
}
|
|
44
|
+
return [...stories.values()].sort(order);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** El cuerpo de la zona; mismo texto que `render` del servidor. */
|
|
48
|
+
export function render(rows) {
|
|
49
|
+
const out = [
|
|
50
|
+
'## 5. Roadmap de US',
|
|
51
|
+
'',
|
|
52
|
+
'> Esta zona la mantiene el engine con lo que dice el tablero: se regenera tras complete_uc, ' +
|
|
53
|
+
'move_uc, add_uc, delete_uc y mark_ac_batch. No la edites a mano.',
|
|
54
|
+
'',
|
|
55
|
+
'| US | Título | Estado | UCs |',
|
|
56
|
+
'|----|--------|--------|-----|',
|
|
57
|
+
];
|
|
58
|
+
if (!rows.length) out.push('| (sin historias) | | | |');
|
|
59
|
+
for (const r of rows) out.push(`| ${r.us_id} | ${r.title} | ${r.state} | ${r.done}/${r.total} |`);
|
|
60
|
+
return out.join('\n');
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const START = (id) => new RegExp(`<!--\\s*@specbox:zone start\\b[^>]*\\bid=["']${id}["'][^>]*-->`);
|
|
64
|
+
const END = /<!--\s*@specbox:zone end\s*-->/;
|
|
65
|
+
|
|
66
|
+
/** `content` con el cuerpo de la zona `zoneId` cambiado por `body`, o null si no tiene esa zona. */
|
|
67
|
+
export function replaceZone(content, zoneId, body) {
|
|
68
|
+
const lines = String(content).split('\n');
|
|
69
|
+
const trailing = String(content).endsWith('\n');
|
|
70
|
+
if (trailing) lines.pop();
|
|
71
|
+
const start = lines.findIndex((l) => START(zoneId).test(l));
|
|
72
|
+
if (start < 0) return null;
|
|
73
|
+
const end = lines.findIndex((l, i) => i > start && END.test(l));
|
|
74
|
+
if (end < 0) return null;
|
|
75
|
+
const rebuilt = [...lines.slice(0, start + 1), ...(body ? body.split('\n') : []), ...lines.slice(end)];
|
|
76
|
+
return rebuilt.join('\n') + (trailing ? '\n' : '');
|
|
77
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/uc-state.mjs — lo que el estado de una UC deja en el proyecto (UC-12216).
|
|
3
|
+
*
|
|
4
|
+
* Con el MCP remoto el servidor no ve el disco del proyecto: `start_uc` devuelve el marcador de UC
|
|
5
|
+
* activa (`active_uc_marker`) y el hook uc-state-marker lo escribe en .quality/active_uc.json, que
|
|
6
|
+
* leen spec-guard, commit-spec-guard y uc-lifecycle-guard. Funciones puras y una escritura atómica.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { dirname, join } from 'node:path';
|
|
11
|
+
|
|
12
|
+
export const MARKER_FILE = join('.quality', 'active_uc.json');
|
|
13
|
+
const UC_ID = /^UC-\d{1,6}[a-z]?$/;
|
|
14
|
+
|
|
15
|
+
function parse(text) {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(text);
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** El primer valor de `key` dentro de una respuesta MCP, tenga la forma que tenga. */
|
|
24
|
+
export function findValue(response, key, depth = 0) {
|
|
25
|
+
if (depth > 6 || response == null) return undefined;
|
|
26
|
+
if (typeof response === 'string') {
|
|
27
|
+
const text = response.trim();
|
|
28
|
+
return text.startsWith('{') || text.startsWith('[') ? findValue(parse(text), key, depth + 1) : undefined;
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(response)) {
|
|
31
|
+
for (const part of response) {
|
|
32
|
+
const found = findValue(part, key, depth + 1);
|
|
33
|
+
if (found !== undefined) return found;
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (typeof response === 'object') {
|
|
38
|
+
if (key in response) return response[key];
|
|
39
|
+
for (const value of Object.values(response)) {
|
|
40
|
+
const found = findValue(value, key, depth + 1);
|
|
41
|
+
if (found !== undefined) return found;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** El objeto de primer nivel de una respuesta MCP: structuredContent, el texto JSON o el propio objeto. */
|
|
48
|
+
export function topObject(response, depth = 0) {
|
|
49
|
+
if (depth > 4 || response == null) return null;
|
|
50
|
+
if (typeof response === 'string') {
|
|
51
|
+
const text = response.trim();
|
|
52
|
+
return text.startsWith('{') || text.startsWith('[') ? topObject(parse(text), depth + 1) : null;
|
|
53
|
+
}
|
|
54
|
+
if (Array.isArray(response)) {
|
|
55
|
+
for (const part of response) {
|
|
56
|
+
const found = topObject(part?.type === 'text' ? part.text : part, depth + 1);
|
|
57
|
+
if (found) return found;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
if (typeof response === 'object') {
|
|
62
|
+
if (response.structuredContent && typeof response.structuredContent === 'object') return response.structuredContent;
|
|
63
|
+
if (Array.isArray(response.content)) return topObject(response.content, depth + 1);
|
|
64
|
+
if (response.isError === true) return { error: 'isError' };
|
|
65
|
+
return response;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** True si la respuesta es un error de la tool (no hay nada que apuntar). Solo mira el primer nivel. */
|
|
71
|
+
export function isError(response) {
|
|
72
|
+
const top = topObject(response);
|
|
73
|
+
if (!top) return true; // sin respuesta legible no se toca nada
|
|
74
|
+
const error = top.error;
|
|
75
|
+
return (error !== undefined && error !== null && error !== false && error !== '') || top.success === false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** El marcador que hay que escribir tras start_uc, o null si la respuesta no trae uno válido. */
|
|
79
|
+
export function markerFrom(response) {
|
|
80
|
+
if (isError(response)) return null;
|
|
81
|
+
const marker = topObject(response)?.active_uc_marker;
|
|
82
|
+
if (!marker || typeof marker !== 'object' || !UC_ID.test(String(marker.uc_id || ''))) return null;
|
|
83
|
+
return marker;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function writeAtomic(path, content) {
|
|
87
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
88
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
89
|
+
writeFileSync(tmp, content, 'utf-8');
|
|
90
|
+
renameSync(tmp, path);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Escribe el marcador de UC activa en `root`. Devuelve la ruta escrita. */
|
|
94
|
+
export function writeMarker(root, marker) {
|
|
95
|
+
const path = join(root, MARKER_FILE);
|
|
96
|
+
writeAtomic(path, `${JSON.stringify(marker, null, 2)}\n`);
|
|
97
|
+
return path;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Borra el marcador si es de `ucId` (o si no dice de qué UC es). Devuelve true si lo borró. */
|
|
101
|
+
export function clearMarker(root, ucId) {
|
|
102
|
+
const path = join(root, MARKER_FILE);
|
|
103
|
+
if (!existsSync(path)) return false;
|
|
104
|
+
const current = parse(readFileSync(path, 'utf-8'));
|
|
105
|
+
if (current?.uc_id && ucId && current.uc_id !== ucId) return false; // es de otra UC: se queda
|
|
106
|
+
unlinkSync(path);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ── Lo que mira uc-lifecycle-guard al hacer push (UC-12206) ─────────────
|
|
111
|
+
|
|
112
|
+
export const AC_MARKED = 'ac_marked.json';
|
|
113
|
+
export const MOVED_TO_REVIEW = 'uc_moved_to_review.json';
|
|
114
|
+
|
|
115
|
+
/** Los id de los criterios de la UC según la respuesta de start_uc (para saber cuáles faltan). */
|
|
116
|
+
export function acIdsFrom(response) {
|
|
117
|
+
const acs = topObject(response)?.acceptance_criteria;
|
|
118
|
+
return Array.isArray(acs) ? acs.map((a) => String(a?.id || a?.ac_id || '')).filter(Boolean) : [];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** El marcador de UC activa del proyecto, o null. */
|
|
122
|
+
export function readMarker(root) {
|
|
123
|
+
const path = join(root, MARKER_FILE);
|
|
124
|
+
return existsSync(path) ? parse(readFileSync(path, 'utf-8')) : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** La carpeta de evidencia de una UC: la `feature` del marcador si es la activa; si no, su id. */
|
|
128
|
+
export function evidenceDir(root, ucId) {
|
|
129
|
+
const marker = readMarker(root);
|
|
130
|
+
const feature = marker?.uc_id === ucId && marker.feature ? marker.feature : ucId;
|
|
131
|
+
return join(root, '.quality', 'evidence', String(feature).replace(/[^A-Za-z0-9._-]/g, '_'));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Suma a ac_marked.json lo que marcó mark_ac_batch: los criterios cumplidos y los no cumplidos.
|
|
136
|
+
* Un criterio que pasa después de haber fallado sale de los no cumplidos.
|
|
137
|
+
*/
|
|
138
|
+
export function recordMarkedAcs(root, ucId, response, now = new Date().toISOString()) {
|
|
139
|
+
const details = topObject(response)?.details;
|
|
140
|
+
if (!Array.isArray(details)) return null;
|
|
141
|
+
const path = join(evidenceDir(root, ucId), AC_MARKED);
|
|
142
|
+
const before = existsSync(path) ? parse(readFileSync(path, 'utf-8')) || {} : {};
|
|
143
|
+
const passed = new Set(Array.isArray(before.passed) ? before.passed : []);
|
|
144
|
+
const failed = new Set(Array.isArray(before.failed) ? before.failed : []);
|
|
145
|
+
for (const d of details) {
|
|
146
|
+
const id = String(d?.ac_id || '');
|
|
147
|
+
if (!id) continue;
|
|
148
|
+
if (d.passed) {
|
|
149
|
+
passed.add(id);
|
|
150
|
+
failed.delete(id);
|
|
151
|
+
} else {
|
|
152
|
+
failed.add(id);
|
|
153
|
+
passed.delete(id);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const out = { uc_id: ucId, passed: [...passed].sort(), failed: [...failed].sort(), at: now };
|
|
157
|
+
writeAtomic(path, `${JSON.stringify(out, null, 2)}\n`);
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** move_uc: a revisión deja uc_moved_to_review.json; a cualquier otro estado lo quita. */
|
|
162
|
+
export function recordMove(root, ucId, target, now = new Date().toISOString()) {
|
|
163
|
+
const path = join(evidenceDir(root, ucId), MOVED_TO_REVIEW);
|
|
164
|
+
if (target === 'review') {
|
|
165
|
+
writeAtomic(path, `${JSON.stringify({ uc_id: ucId, at: now }, null, 2)}\n`);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
if (existsSync(path)) unlinkSync(path);
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* prd-sync-guard.mjs — PreToolUse de `gh pr merge`: el PRD cambia en la misma PR que el código (UC-12211).
|
|
4
|
+
*
|
|
5
|
+
* La medida `spec_in_pr` de EP-20. Antes de fusionar la PR de la UC activa comprueba que:
|
|
6
|
+
* - la PR toca el PRD de su historia (lib/prd-locate.mjs, también en el orquestador si el
|
|
7
|
+
* proyecto es satélite), o
|
|
8
|
+
* - su descripción enlaza una PR del orquestador que lo toca, o
|
|
9
|
+
* - la UC está marcada «sin PRD» con un motivo (update_uc no_prd_reason; va en el marcador).
|
|
10
|
+
* Si no se cumple: en «warn» (por defecto) avisa y deja fusionar; en «block» detiene la fusión y dice
|
|
11
|
+
* el PRD esperado y cómo seguir. Una UC anterior a la regla no se detiene. El modo sale de la
|
|
12
|
+
* política del tablero (lib/enforcement-policy.mjs). Sin `gh` o sin respuesta, no detiene nada.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { execFileSync } from 'node:child_process';
|
|
16
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
17
|
+
import { readHookInput, readJsonFile } from './lib/utils.mjs';
|
|
18
|
+
import { getProjectConfig } from './lib/config.mjs';
|
|
19
|
+
import { blockWith, noteWith } from './lib/output.mjs';
|
|
20
|
+
import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
|
|
21
|
+
import { recordCorrectionIfBlocked, recordEnforcementEvent } from './lib/enforcement-events.mjs';
|
|
22
|
+
import { locatePrd } from './lib/prd-locate.mjs';
|
|
23
|
+
|
|
24
|
+
const MEASURE = 'spec_in_pr';
|
|
25
|
+
const { toolInput, cwd } = readHookInput();
|
|
26
|
+
const command = String(toolInput.command || '');
|
|
27
|
+
const merge = /\bgh\s+pr\s+merge\b(.*)$/m.exec(command);
|
|
28
|
+
if (!merge) process.exit(0);
|
|
29
|
+
|
|
30
|
+
const run = (cmd, args, dir) => {
|
|
31
|
+
try {
|
|
32
|
+
return execFileSync(cmd, args, { cwd: dir, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).trim();
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const root = run('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], cwd) || cwd;
|
|
39
|
+
process.chdir(root);
|
|
40
|
+
const config = getProjectConfig();
|
|
41
|
+
if (!config.isSpecDriven) process.exit(0);
|
|
42
|
+
const marker = readJsonFile('.quality/active_uc.json');
|
|
43
|
+
if (!marker?.uc_id) process.exit(0);
|
|
44
|
+
if (Array.isArray(marker.predates_rule) && marker.predates_rule.includes(MEASURE)) process.exit(0);
|
|
45
|
+
if (typeof marker.no_prd_reason === 'string' && marker.no_prd_reason.trim()) process.exit(0);
|
|
46
|
+
|
|
47
|
+
const politica = await leerPolitica({ root, backendType: config.backendType, boardId: config.boardId, trackingDir: config.freeformRoot });
|
|
48
|
+
const mode = modoDe(politica, MEASURE);
|
|
49
|
+
if (mode === 'off') process.exit(0);
|
|
50
|
+
|
|
51
|
+
// El PRD esperado: en el orquestador si el proyecto es satélite.
|
|
52
|
+
const settings = readJsonFile('.claude/settings.local.json') || {};
|
|
53
|
+
const mr = settings.multirepo || readJsonFile('.claude/project-config.json')?.multirepo;
|
|
54
|
+
const satellite = mr?.enabled && mr?.role === 'satellite' && mr?.orchestrator;
|
|
55
|
+
const canonRoot = satellite ? (isAbsolute(mr.orchestrator) ? mr.orchestrator : resolve(root, mr.orchestrator)) : root;
|
|
56
|
+
const prd = locatePrd({ root: canonRoot, feature: marker.feature || '', usId: marker.us_id || '' });
|
|
57
|
+
|
|
58
|
+
// La PR que se va a fusionar: el argumento de `gh pr merge` (número, URL o rama) y su -R.
|
|
59
|
+
const tokens = merge[1].trim().split(/\s+/).filter(Boolean);
|
|
60
|
+
let selector = '';
|
|
61
|
+
let repoFlag = [];
|
|
62
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
63
|
+
if (tokens[i] === '-R' || tokens[i] === '--repo') {
|
|
64
|
+
repoFlag = ['-R', tokens[i + 1] || ''];
|
|
65
|
+
i++;
|
|
66
|
+
} else if (!tokens[i].startsWith('-') && !selector && !/[;&|]/.test(tokens[i])) {
|
|
67
|
+
selector = tokens[i];
|
|
68
|
+
} else if (/[;&|]/.test(tokens[i])) {
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const view = (args) => {
|
|
73
|
+
const out = run('gh', ['pr', 'view', ...args, '--json', 'files,body'], root);
|
|
74
|
+
try {
|
|
75
|
+
return out ? JSON.parse(out) : null;
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const pr = view([...(selector ? [selector] : []), ...repoFlag]);
|
|
81
|
+
if (!pr) process.exit(0); // sin gh o sin respuesta: no se detiene nada
|
|
82
|
+
|
|
83
|
+
const touches = (files, rel) => Array.isArray(files) && files.some((f) => (f?.path || f) === rel);
|
|
84
|
+
let ok = false;
|
|
85
|
+
if (prd) {
|
|
86
|
+
const relToRepo = satellite ? null : prd;
|
|
87
|
+
if (relToRepo && touches(pr.files, relToRepo)) ok = true;
|
|
88
|
+
// Una PR del orquestador enlazada desde la descripción que toca el PRD.
|
|
89
|
+
if (!ok && satellite) {
|
|
90
|
+
const remote = run('git', ['-C', canonRoot, 'remote', 'get-url', 'origin'], canonRoot) || '';
|
|
91
|
+
const slug = /github\.com[:/]([^/]+\/[^/.]+?)(?:\.git)?$/.exec(remote)?.[1];
|
|
92
|
+
const links = slug ? [...String(pr.body || '').matchAll(new RegExp(`github\\.com/${slug.replace('/', '\\/')}/pull/(\\d+)`, 'g'))] : [];
|
|
93
|
+
for (const [, number] of links) {
|
|
94
|
+
const other = view([number, '-R', slug]);
|
|
95
|
+
if (other && touches(other.files, prd)) {
|
|
96
|
+
ok = true;
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (ok) {
|
|
104
|
+
await recordCorrectionIfBlocked({ root, config, measure: MEASURE, ucId: marker.uc_id, by: 'prd-sync-guard' });
|
|
105
|
+
process.exit(0);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const where = prd
|
|
109
|
+
? `${satellite ? `${relative(root, canonRoot) || '.'}/` : ''}${prd}`
|
|
110
|
+
: `un PRD de ${marker.us_id || 'la historia'} (doc/prd/<slug>/prd.md, doc/prd/<feature>.md o doc/prds/)`;
|
|
111
|
+
const reason = prd
|
|
112
|
+
? `la PR de ${marker.uc_id} no cambia el PRD de su historia (${where})${satellite ? ' ni enlaza una PR del orquestador que lo cambie' : ''}.`
|
|
113
|
+
: `no se encontró ${where}.`;
|
|
114
|
+
const how = [
|
|
115
|
+
satellite
|
|
116
|
+
? `Actualiza ${prd || 'el PRD'} en una PR del orquestador y enlázala en la descripción de esta PR.`
|
|
117
|
+
: `Actualiza ${prd || 'el PRD de la historia'} en esta misma PR (por ejemplo, su estado de implementación).`,
|
|
118
|
+
`Si la UC no tiene PRD, márcala: update_uc(board_id, "${marker.uc_id}", no_prd_reason="por qué").`,
|
|
119
|
+
];
|
|
120
|
+
|
|
121
|
+
if (mode === 'block') {
|
|
122
|
+
await recordEnforcementEvent({ root, config, measure: MEASURE, ucId: marker.uc_id, outcome: 'blocked', by: 'prd-sync-guard' });
|
|
123
|
+
blockWith('SPEC GUARD: el PRD no cambia en la misma PR', [
|
|
124
|
+
`SpecBox detuvo la fusión por la medida ${MEASURE}. Motivo: ${reason}`,
|
|
125
|
+
...how.map((h) => `Cómo seguir: ${h}`),
|
|
126
|
+
]);
|
|
127
|
+
}
|
|
128
|
+
noteWith('PreToolUse', 'SPEC GUARD: el PRD no cambia en la misma PR (aviso)', [
|
|
129
|
+
`Medida ${MEASURE} en «warn»: la fusión sigue. Motivo: ${reason}`,
|
|
130
|
+
...how,
|
|
131
|
+
]);
|