specbox 6.35.0 → 6.37.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.
@@ -326,52 +326,76 @@ export function mergeFragment(local, sent, returned) {
326
326
 
327
327
  // ── The tool's answer ──────────────────────────────────────────────────
328
328
 
329
- /** The `items_content` string inside an MCP tool response, whatever its shape. */
330
- export function extractItemsContent(response, depth = 0) {
329
+ /** The string field `key` inside an MCP tool response, whatever its shape. */
330
+ export function extractField(response, key, depth = 0) {
331
331
  if (depth > 6 || response == null) return null;
332
332
  if (typeof response === 'string') {
333
333
  const text = response.trim();
334
- return text.startsWith('{') ? extractItemsContent(safeJson(text), depth + 1) : null;
334
+ return text.startsWith('{') ? extractField(safeJson(text), key, depth + 1) : null;
335
335
  }
336
336
  if (Array.isArray(response)) {
337
337
  for (const part of response) {
338
- const found = extractItemsContent(part, depth + 1);
338
+ const found = extractField(part, key, depth + 1);
339
339
  if (found != null) return found;
340
340
  }
341
341
  return null;
342
342
  }
343
343
  if (typeof response === 'object') {
344
- if (typeof response.items_content === 'string') return response.items_content;
344
+ if (typeof response[key] === 'string') return response[key];
345
345
  for (const value of Object.values(response)) {
346
- const found = extractItemsContent(value, depth + 1);
346
+ const found = extractField(value, key, depth + 1);
347
347
  if (found != null) return found;
348
348
  }
349
349
  }
350
350
  return null;
351
351
  }
352
352
 
353
- /** The same response without any `items_content` (what the model needs to see). */
354
- export function withoutItemsContent(response, depth = 0) {
353
+ /** The same response without any field in `keys` (what the model needs to see). */
354
+ export function withoutFields(response, keys, depth = 0) {
355
355
  if (depth > 6 || response == null) return response;
356
356
  if (typeof response === 'string') {
357
357
  const text = response.trim();
358
358
  if (!text.startsWith('{')) return response;
359
359
  const parsed = safeJson(text);
360
- if (parsed == null || extractItemsContent(parsed) == null) return response;
361
- return JSON.stringify(withoutItemsContent(parsed, depth + 1));
360
+ if (parsed == null || keys.every((k) => extractField(parsed, k) == null)) return response;
361
+ return JSON.stringify(withoutFields(parsed, keys, depth + 1));
362
362
  }
363
- if (Array.isArray(response)) return response.map((part) => withoutItemsContent(part, depth + 1));
363
+ if (Array.isArray(response)) return response.map((part) => withoutFields(part, keys, depth + 1));
364
364
  if (typeof response === 'object') {
365
365
  const out = {};
366
366
  for (const [key, value] of Object.entries(response)) {
367
- if (key === 'items_content') continue;
368
- out[key] = withoutItemsContent(value, depth + 1);
367
+ if (keys.includes(key)) continue;
368
+ out[key] = withoutFields(value, keys, depth + 1);
369
369
  }
370
370
  return out;
371
371
  }
372
372
  return response;
373
373
  }
374
374
 
375
+ /** The `items_content` string inside an MCP tool response, whatever its shape. */
376
+ export function extractItemsContent(response) {
377
+ return extractField(response, 'items_content');
378
+ }
379
+
380
+ /** The same response without any `items_content` (nor `policy_content` or `event_line`, UC-12212/12213). */
381
+ export function withoutItemsContent(response) {
382
+ return withoutFields(response, ['items_content', 'policy_content', 'event_line']);
383
+ }
384
+
385
+ // ── The EP-20 policy, doc/tracking/policy.json (UC-12212) ─────────────
386
+
387
+ /** The tools that read or change the policy: they get the file as `policy_content`. */
388
+ export const POLICY_TOOLS = new Set([
389
+ 'get_enforcement_policy', 'set_enforcement_mode', 'skip_enforcement',
390
+ 'get_enforcement_impact', 'record_enforcement_event',
391
+ ]);
392
+ /** Of those, the ones whose answer is the new file. */
393
+ export const POLICY_WRITERS = new Set(['set_enforcement_mode', 'skip_enforcement']);
394
+ /** The ones that measure the board: they also get items.json and the events (UC-12213). */
395
+ export const POLICY_BOARD_TOOLS = new Set(['set_enforcement_mode', 'get_enforcement_impact']);
396
+ /** The ones whose answer carries an `event_line` for doc/tracking/enforcement_events.jsonl. */
397
+ export const POLICY_EVENT_TOOLS = new Set(['skip_enforcement', 'record_enforcement_event']);
398
+
375
399
  // ── Files: pending calls, the lock and atomic writes ───────────────────
376
400
 
377
401
  function sleep(ms) {
@@ -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
+ }
@@ -244,6 +244,16 @@
244
244
  "type": "command",
245
245
  "command": "node .claude/hooks/freeform-fragment.mjs",
246
246
  "timeout": 15
247
+ },
248
+ {
249
+ "type": "command",
250
+ "command": "node .claude/hooks/uc-state-marker.mjs",
251
+ "timeout": 5
252
+ },
253
+ {
254
+ "type": "command",
255
+ "command": "node .claude/hooks/app-docs-fragment.mjs",
256
+ "timeout": 5
247
257
  }
248
258
  ]
249
259
  },
@@ -14,53 +14,16 @@
14
14
  */
15
15
 
16
16
  import { execFileSync } from 'node:child_process';
17
- import { readStdin, fileExists, fileAge, git } from './lib/utils.mjs';
17
+ import { readStdin, fileExists, fileAge, git, readJsonFile } from './lib/utils.mjs';
18
18
  import { blockWith, noteWith } from './lib/output.mjs';
19
19
  import { dirname, isAbsolute } from 'node:path';
20
20
  import { getProjectConfig, getActiveUC, getActiveUCReservation, getStaleUC } from './lib/config.mjs';
21
21
  import { decideNativeReservation } from './lib/native-reservation-revalidate.mjs';
22
-
23
- /**
24
- * Best-effort revalidation of a native reservation against the MCP. Returns
25
- * { reachable, reservation } for decideNativeReservation. Never throws — any
26
- * failure (no URL, network error, timeout, bad JSON) yields reachable:false
27
- * so the cache is trusted [AC-21]. Online conflicts are surfaced for AC-22.
28
- *
29
- * Endpoint: GET /api/native/reservation-status?uc_id=...
30
- * Expected response: { uc_id, reservation: { developer_id } | null }
31
- *
32
- * Wire-protocol compat (v5.35-v5.36): if the MCP returns the legacy shape
33
- * { uc_id, claim: {…} | null } we pass `claim` through too, and the pure
34
- * decision module accepts both. UC-612 removes the fallback in v5.37.0.
35
- */
36
- function probeNativeReservation(reservation) {
37
- const mcpUrl = process.env.SPECBOX_ENGINE_MCP_URL || process.env.DEV_ENGINE_MCP_URL || '';
38
- if (!mcpUrl) return { reachable: false };
39
- try {
40
- const url = `${mcpUrl.replace(/\/$/, '')}/api/native/reservation-status`;
41
- const out = execFileSync(
42
- 'curl',
43
- [
44
- '-fsS', '--max-time', '3',
45
- '-L', // follow redirects so a server still serving the legacy URL
46
- // with a 301 to /reservation-status works transparently
47
- '-G', url,
48
- '--data-urlencode', `uc_id=${reservation.ucId}`,
49
- ],
50
- { encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'] },
51
- );
52
- const data = JSON.parse(out);
53
- return {
54
- reachable: true,
55
- reservation: data.reservation ?? null,
56
- // Forward the legacy `claim` field too so the pure decision module
57
- // can fall back if the server has not yet upgraded.
58
- claim: data.claim ?? undefined,
59
- };
60
- } catch {
61
- return { reachable: false };
62
- }
63
- }
22
+ // UC-12217: la reserva se revisa con la tool get_uc_reservation (identidad del dispositivo, 3 s).
23
+ // Antes era un curl a /api/native/reservation-status, que el servidor no tiene: fallaba siempre,
24
+ // se daba la caché por buena y el bloqueo por reserva perdida no saltaba nunca.
25
+ import { probeReservation, shouldNoteOffline } from './lib/reservation-probe.mjs';
26
+ import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
64
27
 
65
28
  const input = readStdin();
66
29
 
@@ -98,7 +61,7 @@ if (isAbsolute(filePath)) {
98
61
  }
99
62
 
100
63
  // --- Check if project is spec-driven ---
101
- const { boardId, backendType, isSpecDriven } = getProjectConfig();
64
+ const { boardId, backendType, isSpecDriven, recognizedBy, freeformRoot } = getProjectConfig();
102
65
 
103
66
  // If no board and no backend configured → not spec-driven, allow
104
67
  if (!isSpecDriven) {
@@ -109,11 +72,26 @@ if (!isSpecDriven) {
109
72
  const currentBranch = git('branch --show-current');
110
73
 
111
74
  if (currentBranch === 'main' || currentBranch === 'master') {
112
- blockWith(`SPEC GUARD: código escrito en ${currentBranch}`, [
113
- `Fichero: ${filePath}`,
114
- 'Es un proyecto spec-driven: el código va en una rama de la UC, nunca en main ni en master.',
115
- 'La escritura ya está hecha. Antes de seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo).',
116
- ]);
75
+ // UC-12215: misma regla que commit-spec-guard con la medida commit_on_main. Los proyectos de
76
+ // siempre conservan el bloqueo; los reconocidos por primera vez toman el modo del tablero
77
+ // («warn» salvo que una persona lo cambie); lo que puso una persona manda.
78
+ const politica = await leerPolitica({ root: process.cwd(), backendType, boardId, trackingDir: freeformRoot });
79
+ const puesto = politica.explicitas?.includes('commit_on_main');
80
+ const modo = puesto || recognizedBy !== 'legacy' ? modoDe(politica, 'commit_on_main') : 'block';
81
+ if (modo === 'block') {
82
+ blockWith(`SPEC GUARD: código escrito en ${currentBranch}`, [
83
+ `Fichero: ${filePath}`,
84
+ 'Es un proyecto spec-driven: el código va en una rama de la UC, nunca en main ni en master.',
85
+ 'La escritura ya está hecha. Antes de seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo).',
86
+ ]);
87
+ }
88
+ if (modo === 'warn') {
89
+ noteWith('PostToolUse', `SPEC GUARD: código escrito en ${currentBranch}`, [
90
+ `Fichero: ${filePath}`,
91
+ 'En un proyecto spec-driven el código va en una rama de la UC. La medida commit_on_main está en «warn»: sigue, pero conviene moverlo:',
92
+ 'git checkout -b feature/{uc}-{nombre} (los cambios se van contigo).',
93
+ ]);
94
+ }
117
95
  }
118
96
 
119
97
  // --- Spec-driven project: verify active UC ---
@@ -125,7 +103,15 @@ if (activeUC) {
125
103
  // dev [AC-22].
126
104
  const reservation = getActiveUCReservation();
127
105
  if (reservation) {
128
- const decision = decideNativeReservation(reservation, probeNativeReservation(reservation));
106
+ const projectId = readJsonFile('.quality/active_uc.json')?.board_id || boardId;
107
+ const probe = await probeReservation({ root: process.cwd(), projectId, reservation });
108
+ const decision = decideNativeReservation(reservation, probe);
109
+ if (decision.reason === 'offline-cache-trusted' && shouldNoteOffline(process.cwd())) {
110
+ noteWith('PostToolUse', 'SPEC GUARD: reserva sin comprobar con el tablero', [
111
+ `UC: ${reservation.ucId} · no se pudo preguntar al tablero (${probe.why || 'sin respuesta'}).`,
112
+ 'Se usa la reserva guardada en .quality/active_uc.json; se vuelve a comprobar en la siguiente escritura.',
113
+ ]);
114
+ }
129
115
  if (!decision.allow) {
130
116
  const actual = decision.conflict?.actual;
131
117
  blockWith('SPEC GUARD: la reserva de la UC ya no es tuya', [
@@ -6,6 +6,11 @@
6
6
  *
7
7
  * Also warns if mark_ac_batch hasn't been called (no ACs marked).
8
8
  *
9
+ * UC-12206: los ficheros que mira (.quality/evidence/<feature>/ac_marked.json y
10
+ * uc_moved_to_review.json) los escribe el hook uc-state-marker con lo que devuelven mark_ac_batch y
11
+ * move_uc; antes no los escribía nadie y el aviso salía en cada push. El aviso nombra lo que falta:
12
+ * los criterios sin marcar (con los de la UC que guarda el marcador) o la UC fuera de revisión.
13
+ *
9
14
  * v5.19.0 — Compliance Enforcement
10
15
  */
11
16
 
@@ -47,32 +52,38 @@ if (!activeUC) {
47
52
  process.exit(0);
48
53
  }
49
54
 
50
- const feature = activeUC.feature;
55
+ const feature = activeUC.feature || activeUC.ucId;
51
56
  const warnings = [];
52
57
 
53
- // Check 1: Has mark_ac_batch been called?
54
- // We detect this by checking if any AC evidence exists
55
- const evidenceDir = `.quality/evidence/${feature}`;
56
- const acMarkerFile = `${evidenceDir}/ac_marked.json`;
57
- if (!fileExists(acMarkerFile)) {
58
- // Also check the audit.json for any AC data
59
- const audit = readJsonFile(`${evidenceDir}/audit.json`);
60
- if (!audit || !audit.ac_results) {
61
- warnings.push(
62
- 'No acceptance criteria have been marked (mark_ac_batch not called). ' +
63
- 'The board will not reflect which ACs passed.'
64
- );
58
+ // Los escribe el hook uc-state-marker con lo que devuelven mark_ac_batch y move_uc (UC-12206).
59
+ const evidenceDir = `.quality/evidence/${String(feature).replace(/[^A-Za-z0-9._-]/g, '_')}`;
60
+
61
+ // Check 1: criterios sin marcar como cumplidos.
62
+ const marked = readJsonFile(`${evidenceDir}/ac_marked.json`);
63
+ const audit = readJsonFile(`${evidenceDir}/audit.json`);
64
+ const marker = readJsonFile('.quality/active_uc.json') || {};
65
+ const acIds = Array.isArray(marker.ac_ids) ? marker.ac_ids : [];
66
+ if (!marked && !audit?.ac_results) {
67
+ warnings.push(
68
+ 'Criterios sin marcar: no consta ningún mark_ac_batch de esta UC, así que el board no dice cuáles se cumplen.' +
69
+ (acIds.length ? ` Faltan ${acIds.join(', ')}.` : '')
70
+ );
71
+ } else if (marked) {
72
+ const passed = new Set(Array.isArray(marked.passed) ? marked.passed : []);
73
+ const missing = acIds.filter((id) => !passed.has(id));
74
+ const failed = Array.isArray(marked.failed) ? marked.failed : [];
75
+ if (missing.length) {
76
+ warnings.push(`Criterios sin marcar como cumplidos: ${missing.join(', ')}.`);
77
+ } else if (failed.length) {
78
+ warnings.push(`Criterios marcados como no cumplidos: ${failed.join(', ')}.`);
65
79
  }
66
80
  }
67
81
 
68
- // Check 2: Has the UC been moved to Review?
69
- // We detect this by checking if a move_uc marker exists
70
- const moveMarkerFile = `${evidenceDir}/uc_moved_to_review.json`;
71
- if (!fileExists(moveMarkerFile)) {
82
+ // Check 2: la UC fuera de revisión.
83
+ if (!fileExists(`${evidenceDir}/uc_moved_to_review.json`)) {
72
84
  warnings.push(
73
- `UC "${activeUC.ucId}" has NOT been moved to Review. ` +
74
- 'Call move_uc(board_id, uc_id, "review") before or after creating the PR. ' +
75
- 'The board must reflect the current state.'
85
+ `UC fuera de revisión: ${activeUC.ucId} no se ha movido a «review». ` +
86
+ 'Llama a move_uc(board_id, uc_id, "review") antes o después de abrir la PR.'
76
87
  );
77
88
  }
78
89