specbox 6.40.0 → 6.42.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.
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * agent-identity.mjs — PreToolUse de start_uc y record_review_verdict: quién llama (UC-12402).
4
+ *
5
+ * Pone en la llamada el contexto de Claude Code (`client_session_id`, `client_agent_id`,
6
+ * `client_agent_type`) que recibe el hook, para que el tablero sepa quién implementó la UC y rechace un
7
+ * veredicto de revisión del mismo contexto. Lo que mande el modelo en esos campos se sustituye.
8
+ *
9
+ * En FreeForm con el MCP remoto no hace nada: freeform-fragment ya cambia esas llamadas y pone la
10
+ * identidad él mismo (dos hooks no cambian la misma llamada). Nunca bloquea.
11
+ */
12
+
13
+ import { execFileSync } from 'node:child_process';
14
+ import { join } from 'node:path';
15
+ import { IDENTITY_TOOLS, withIdentity } from './lib/agent-identity.mjs';
16
+ import { isRemoteMcp } from './lib/freeform-path.mjs';
17
+ import { parseToolName } from './lib/freeform-fragment.mjs';
18
+ import { readHookInput, readJsonFile } from './lib/utils.mjs';
19
+
20
+ const { event, toolName, toolInput, cwd, payload } = readHookInput();
21
+ const parsed = parseToolName(toolName);
22
+ if (event !== 'PreToolUse' || !parsed || !IDENTITY_TOOLS.has(parsed.tool)) process.exit(0);
23
+
24
+ let root = cwd;
25
+ try {
26
+ root = execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], {
27
+ encoding: 'utf-8',
28
+ stdio: ['ignore', 'pipe', 'ignore'],
29
+ timeout: 5000,
30
+ }).trim() || cwd;
31
+ } catch {
32
+ // fuera de un repositorio: se usa la carpeta actual
33
+ }
34
+ const settings = readJsonFile(join(root, '.claude', 'settings.local.json'))?.specbox ?? {};
35
+ if (settings.backend_type === 'freeform' && isRemoteMcp({ cwd: root })) process.exit(0); // freeform-fragment
36
+
37
+ const updatedInput = withIdentity(toolInput, payload);
38
+ if (!updatedInput.client_session_id) process.exit(0); // sin contexto que poner: la llamada va como está
39
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } }));
@@ -23,6 +23,13 @@
23
23
  * get_enforcement_impact also get items.json (`board_content`) and the blocks
24
24
  * (`events_content`); the `event_line` of skip_enforcement and
25
25
  * record_enforcement_event is appended to doc/tracking/enforcement_events.jsonl.
26
+ *
27
+ * UC-12401: complete_uc gets the policy like start_uc (its measure is closing_evidence) and what
28
+ * both return is saved the same way; mark_ac and mark_ac_batch get the git author as `marked_by`,
29
+ * which FreeForm keeps with the verdict and the receipt of each criterion.
30
+ *
31
+ * UC-12402: start_uc and record_review_verdict get the Claude Code context (lib/agent-identity.mjs);
32
+ * the agent-identity hook leaves these calls to this one.
26
33
  */
27
34
 
28
35
  import { execFileSync } from 'node:child_process';
@@ -47,6 +54,12 @@ import {
47
54
  writeAtomic,
48
55
  } from './lib/freeform-fragment.mjs';
49
56
  import { readHookInput } from './lib/utils.mjs';
57
+ import { IDENTITY_TOOLS, identityFields } from './lib/agent-identity.mjs';
58
+
59
+ /** The tools whose measures read the board's policy and may record a block (UC-12301, UC-12401). */
60
+ const GATE_TOOLS = new Set(['start_uc', 'complete_uc']);
61
+ /** The tools that mark criteria: FreeForm keeps who marked them (UC-12401). */
62
+ const MARK_TOOLS = new Set(['mark_ac', 'mark_ac_batch']);
50
63
 
51
64
  const { event, toolName, toolInput, cwd, payload } = readHookInput();
52
65
  const parsed = parseToolName(toolName);
@@ -187,19 +200,31 @@ function pre() {
187
200
  return result;
188
201
  });
189
202
  const updatedInput = { ...toolInput, items_content: built.itemsContent };
190
- // UC-12211: start_uc marks the UCs that predate a rule; it needs the board's policy.
191
- if (parsed.tool === 'start_uc' && typeof toolInput.policy_content !== 'string' && existsSync(policyPath)) {
203
+ // UC-12211, UC-12401: start_uc and complete_uc check measures of the board's policy.
204
+ if (GATE_TOOLS.has(parsed.tool) && typeof toolInput.policy_content !== 'string' && existsSync(policyPath)) {
192
205
  updatedInput.policy_content = readFileSync(policyPath, 'utf-8');
193
206
  }
207
+ // UC-12401: who marked each criterion, kept with its verdict and its receipt.
208
+ if (MARK_TOOLS.has(parsed.tool) && !toolInput.marked_by) {
209
+ const author = gitAuthor();
210
+ if (author) updatedInput.marked_by = author.slice(0, 100);
211
+ }
212
+ // UC-12402: the Claude Code context that calls (this hook owns the call; agent-identity steps aside).
213
+ if (IDENTITY_TOOLS.has(parsed.tool)) {
214
+ delete updatedInput.client_session_id;
215
+ delete updatedInput.client_agent_id;
216
+ delete updatedInput.client_agent_type;
217
+ Object.assign(updatedInput, identityFields(payload));
218
+ }
194
219
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } }));
195
220
  }
196
221
 
197
222
  /**
198
- * start_uc (UC-12301): a block it records (`event_line`) and a skip it spends (`policy_content`)
199
- * go where the policy tools write them. Returns the note for the agent, or null.
223
+ * start_uc (UC-12301) and complete_uc (UC-12401): a block they record (`event_line`) and a skip they
224
+ * spend (`policy_content`) go where the policy tools write them. Returns the note for the agent, or null.
200
225
  */
201
- function saveStartUcEnforcement(response) {
202
- if (parsed.tool !== 'start_uc') return null;
226
+ function saveGateEnforcement(response) {
227
+ if (!GATE_TOOLS.has(parsed.tool)) return null;
203
228
  const saved = [];
204
229
  try {
205
230
  const lines = (extractField(response, 'event_line') || '').split('\n').filter((l) => l.trim());
@@ -217,7 +242,7 @@ function saveStartUcEnforcement(response) {
217
242
  }
218
243
  } catch (err) {
219
244
  process.stderr.write(
220
- `SpecBox freeform-fragment: no se pudo guardar lo que devolvió start_uc (${err.message}). ` +
245
+ `SpecBox freeform-fragment: no se pudo guardar lo que devolvió ${parsed.tool} (${err.message}). ` +
221
246
  'Repite la llamada antes de seguir.\n',
222
247
  );
223
248
  process.exit(2);
@@ -228,11 +253,11 @@ function saveStartUcEnforcement(response) {
228
253
  function post() {
229
254
  if (!existsSync(pending)) return;
230
255
  const response = payload.tool_response;
231
- const startNote = saveStartUcEnforcement(response);
256
+ const startNote = saveGateEnforcement(response);
232
257
  const content = extractItemsContent(response);
233
258
  if (content == null) {
234
259
  unlinkSync(pending); // a read, or an error: nothing to merge
235
- if (startNote) writeHidden(response, startNote); // a start_uc that a measure stopped
260
+ if (startNote) writeHidden(response, startNote); // a start_uc or complete_uc that a measure stopped
236
261
  return;
237
262
  }
238
263
  try {
@@ -178,19 +178,23 @@
178
178
  "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
179
179
  "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
180
180
  "c212b004d384feba728e0ee7e955bfb09fafe39112cad7c530620a1e932d169a",
181
- "9ab7d65162056498f7c403eff0eb571b914b9d5c70b9bfdcd52b885c7bd20fef"
181
+ "9ab7d65162056498f7c403eff0eb571b914b9d5c70b9bfdcd52b885c7bd20fef",
182
+ "ca2a8fa168b42abc8aea497962d0b183372ebdcc91afd4df493f435188009751",
183
+ "e235265d07615981e2fdffe8b24078692b20499c8cf5ebfbe9f5c9bc67fe08e7"
182
184
  ],
183
185
  "lib/freeform-fragment.mjs": [
184
186
  "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
185
187
  "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1",
186
- "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141"
188
+ "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
189
+ "69d42e834d0925154e25d5f79ab849bb48b253cceab16dce92f1d55743d0219b"
187
190
  ],
188
191
  "lib/app-spec-zones.mjs": [
189
192
  "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174"
190
193
  ],
191
194
  "lib/enforcement-policy.mjs": [
192
195
  "3fe25cc63c99d8afbc4dac8a34e142c44bd2d594efa89979993a97b8f48fe688",
193
- "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a"
196
+ "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a",
197
+ "7aa258be02a1f0a284698ac4c91fc3841db326250550ba0832cf9988b10bb2aa"
194
198
  ],
195
199
  "app-docs-fragment.mjs": [
196
200
  "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8",
@@ -218,5 +222,30 @@
218
222
  "prd-sync-guard.mjs": [
219
223
  "0a163f99dd8e03d57ff027de2c7f1dd614811caaf63aae6cae1d2989834244c8",
220
224
  "959790ef27c79fc4b1603a53ca0f222dc4276aec91ca096c25a34e21cb1b4e96"
225
+ ],
226
+ "lib/closing-evidence.mjs": [
227
+ "eb956a5663a724b2945531cacb2d72f0f7200f17bd420e3e5ec6c1e7bef77f8b"
228
+ ],
229
+ "merge-guard.mjs": [
230
+ "69d3100e1134fd430db521670c9dc60eeb20985c0b4feeb33f0b5f5700a36646",
231
+ "21ae9b085b8cd76d4e1310fba37e2c2ee22bf65c572f9dbd0e1616fa416bc9be"
232
+ ],
233
+ "agent-identity.mjs": [
234
+ "b8034fa92adde9b9ef11ec32be2fbd33c0d8c18bd657137c842757b17536890a"
235
+ ],
236
+ "lib/agent-identity.mjs": [
237
+ "e3a1fbc8b8f67725b33d84ea15c7403e6e0570ca6f811acde5a34f636cdbac47"
238
+ ],
239
+ "lib/independent-review.mjs": [
240
+ "6bf0e83f526649a5c1af7d6f01998a8ea06891420831ec85098279436de2bf2b"
241
+ ],
242
+ "lib/uc-usage-send.mjs": [
243
+ "3d5b2e60a53cc3ffff0bee8c716a45ff8f7db02b59ff323860a3d5ab5e6e57a2"
244
+ ],
245
+ "lib/uc-usage.mjs": [
246
+ "ee793a46a527726ffdff7785fcb8be347d29ed00bc3fd1356a865211cfde87f5"
247
+ ],
248
+ "uc-usage.mjs": [
249
+ "db90605adcea2138a72b7e73eade12a8978801c789099ad8c1a6468206ff7499"
221
250
  ]
222
251
  }
@@ -1,6 +1,7 @@
1
1
  {
2
- "version": "6.40.0",
2
+ "version": "6.42.0",
3
3
  "files": {
4
+ "agent-identity.mjs": "b8034fa92adde9b9ef11ec32be2fbd33c0d8c18bd657137c842757b17536890a",
4
5
  "app-docs-fragment.mjs": "4efae124b02c12f87513e48ca6d4f2e96065c05ca6d8c74352592a8edb21695a",
5
6
  "app-docs-sync-guard.mjs": "71f09545b57c143b013c2e532366bfdd1e1a2ae49c7644c9e12e2ab5324d03d3",
6
7
  "branch-guard.mjs": "2185062de5f8672236a957a1ee4e7a6057c656a105bf886685f9e7bf8025c215",
@@ -12,11 +13,12 @@
12
13
  "design-system-gate.mjs": "419018cadb3e0a4fe0def1c423fed7013b76b2f121312acadbc99fc8e30b8ff5",
13
14
  "e2e-gate.mjs": "02e239816cb429f76034088a5370f63a08facce01b4ffd52b338a66acf13028d",
14
15
  "file-ownership-guard.mjs": "d8a84370766966cce70b76811de9dd150d170a79c4cb7b9e6b120cfad86a6932",
15
- "freeform-fragment.mjs": "9ab7d65162056498f7c403eff0eb571b914b9d5c70b9bfdcd52b885c7bd20fef",
16
+ "freeform-fragment.mjs": "e235265d07615981e2fdffe8b24078692b20499c8cf5ebfbe9f5c9bc67fe08e7",
16
17
  "freeform-path-guard.mjs": "9ded19e96b0738de5aaf43a97eaa1d88ecd3b341efd432c0b32eb312c4bf5e0a",
17
18
  "healing-budget-guard.mjs": "c49c6c34f99545e4009ad88ed9f7eef737e35ce39c11a05d41ad8f976ffae09f",
18
19
  "implement-checkpoint.mjs": "f3f219779a1ac4108bc3aabcc7311e9135d9c7795c126a2b5d659e743f5a5a64",
19
20
  "implement-healing.mjs": "75392f7de628c3d1d88bf882007bd3281cfedaf0b73940999698daa68ff02411",
21
+ "merge-guard.mjs": "21ae9b085b8cd76d4e1310fba37e2c2ee22bf65c572f9dbd0e1616fa416bc9be",
20
22
  "no-bypass-guard.mjs": "d7a31ac193edb8dedda2d9d696aa747612f7348ee475e57653ae0813f9b36189",
21
23
  "on-session-end.mjs": "fd5b7cf3bf2c419fd4125e21b338c4c849a4daaef21d5e15253caed54965b40c",
22
24
  "pipeline-phase-guard.mjs": "761b82c8b0c4884eba54d529e1f726d547003a6efe05425b45a1a0b77b90fe0d",
@@ -33,19 +35,23 @@
33
35
  "stripe-safety-guard.mjs": "5d7c0a9524657fe47e6ec4ea0eeb055d238f133eeac488c145cb1d5ae88b96de",
34
36
  "uc-lifecycle-guard.mjs": "606c4397200ffbc3b2c89c9af68c340692e6d48f6c792da1d6531b5215fb16e9",
35
37
  "uc-state-marker.mjs": "7c649407416f3837196c9cf8a0caf44b8aeead7e2da9eda55ee5526972630cb2",
38
+ "uc-usage.mjs": "db90605adcea2138a72b7e73eade12a8978801c789099ad8c1a6468206ff7499",
39
+ "lib/agent-identity.mjs": "e3a1fbc8b8f67725b33d84ea15c7403e6e0570ca6f811acde5a34f636cdbac47",
36
40
  "lib/app-spec-zones.mjs": "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174",
37
41
  "lib/autopilot.mjs": "317eabaed8dead40f3d55e642b7465a3ba4e884523e0ae7b933e197153fc6f95",
42
+ "lib/closing-evidence.mjs": "eb956a5663a724b2945531cacb2d72f0f7200f17bd420e3e5ec6c1e7bef77f8b",
38
43
  "lib/config.mjs": "a4458d02037cbba952a8f2240549859195788307c95b434e6fd9faa1a1591b85",
39
44
  "lib/decisiones.mjs": "6bed3bd37320b6d87f4c77fcac27ed55a6b37776d84a0d4eb2d9cab0c474a520",
40
45
  "lib/design-gaps.mjs": "d356d695d7afbafdc6fc420ed66603f11aa523be245bbd7a717d141a4a00701e",
41
46
  "lib/enforcement-events.mjs": "5fe963aab5f24c2b50c9991f11dbda48440a98f7394e02c823a276ee1bb2d608",
42
- "lib/enforcement-policy.mjs": "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a",
47
+ "lib/enforcement-policy.mjs": "7aa258be02a1f0a284698ac4c91fc3841db326250550ba0832cf9988b10bb2aa",
43
48
  "lib/execution-context.mjs": "953eb7ec86f6893288df4e76c9c63c737c8e8ba4e337271402ce5eaca00330fa",
44
- "lib/freeform-fragment.mjs": "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
49
+ "lib/freeform-fragment.mjs": "69d42e834d0925154e25d5f79ab849bb48b253cceab16dce92f1d55743d0219b",
45
50
  "lib/freeform-path.mjs": "9ea85781821ae911873d1dbd13d58811a6c88e50480d2b3b378725ce2872be0c",
46
51
  "lib/handoff-builder.mjs": "2f7ffd554484d9560f525ab2548c240bac65b23bbe6eb8907e64c66bd818e22d",
47
52
  "lib/heartbeat-send.mjs": "739d4fe4b573e99fffdad2252a75cb7dcf18526dda72f1db6cff25b16f76383a",
48
53
  "lib/heartbeat.mjs": "0da0045e6a350f71c54fe972dc2a97880b8eab0aaeaab83595ff3ef3ac0fdae6",
54
+ "lib/independent-review.mjs": "6bf0e83f526649a5c1af7d6f01998a8ea06891420831ec85098279436de2bf2b",
49
55
  "lib/mcp-client-io.mjs": "e863d22434fd9a1abf57804291b38e72d2236a0b7ff39460150ac883b2a7b780",
50
56
  "lib/mcp-client.mjs": "02610127d29b4c001a5a44ad3bff74d954808f8e13b1a20a378a1da03274abbd",
51
57
  "lib/native-reservation-revalidate.mjs": "1b394e8eb5d01480b71ac0976d636814483891e9f862edd5ac0216ac0128b023",
@@ -56,6 +62,8 @@
56
62
  "lib/roadmap.mjs": "0ff30f9d5707c89b8b43406e76f4870a39dd4f787221c32310ef6f9040879d8a",
57
63
  "lib/token-counter.mjs": "ca637273dcf731c7a951f28b8307d13de06d311cf85741ef56c4e3df9eaa231e",
58
64
  "lib/uc-state.mjs": "699786c91e83ad5b35b42f0ef812728e951be28a12ae0c037d1790795adc9e90",
65
+ "lib/uc-usage-send.mjs": "3d5b2e60a53cc3ffff0bee8c716a45ff8f7db02b59ff323860a3d5ab5e6e57a2",
66
+ "lib/uc-usage.mjs": "ee793a46a527726ffdff7785fcb8be347d29ed00bc3fd1356a865211cfde87f5",
59
67
  "lib/utils.mjs": "4c21939aac114a11a68e2519d5d99f7f0bf482f08af0dc9e51ac715cc93ddfa2"
60
68
  }
61
69
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * lib/agent-identity.mjs — el contexto de Claude Code que llama a una tool (US-124 · UC-12402).
3
+ *
4
+ * Claude Code da a cada hook `session_id` y, dentro de un subagente, `agent_id` y `agent_type`. Esos
5
+ * valores los pone Claude Code, no el modelo: con ellos el tablero sabe quién implementó una UC
6
+ * (`start_uc`) y si quien la revisa es otro contexto (`record_review_verdict`). Los ponen en la
7
+ * llamada el hook agent-identity o, en FreeForm con el MCP remoto, freeform-fragment (un solo hook
8
+ * cambia cada llamada). Lo que mande el modelo en esos campos se sustituye.
9
+ */
10
+
11
+ /** Las tools que reciben la identidad del contexto. */
12
+ export const IDENTITY_TOOLS = new Set(['start_uc', 'record_review_verdict']);
13
+
14
+ const ID_RE = /^[A-Za-z0-9_.:@/-]{1,128}$/;
15
+
16
+ /** `{ client_session_id, client_agent_id?, client_agent_type? }` de la entrada del hook ({} si no hay). */
17
+ export function identityFields(payload) {
18
+ const out = {};
19
+ const pairs = [
20
+ ['client_session_id', payload?.session_id],
21
+ ['client_agent_id', payload?.agent_id],
22
+ ['client_agent_type', payload?.agent_type],
23
+ ];
24
+ for (const [key, value] of pairs) {
25
+ if (typeof value === 'string' && ID_RE.test(value.trim())) out[key] = value.trim();
26
+ }
27
+ return out;
28
+ }
29
+
30
+ /** La entrada de la tool con la identidad del contexto encima (sin los campos que mandó el modelo). */
31
+ export function withIdentity(toolInput, payload) {
32
+ const { client_session_id: _s, client_agent_id: _a, client_agent_type: _t, ...rest } = toolInput || {};
33
+ return { ...rest, ...identityFields(payload) };
34
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * lib/closing-evidence.mjs — qué criterios de una UC no están demostrados (UC-12401).
3
+ *
4
+ * La misma regla que `closing_evidence_result` de server/coordination/enforcement.py (una prueba
5
+ * compara las dos): un criterio está demostrado si está hecho y tiene al menos un recibo con
6
+ * `passed: true`. Cuentan todos los criterios; una UC sin criterios no tiene nada demostrado. Un
7
+ * criterio cuya evidencia no se conoce (`evidence: null`) cuenta solo por «hecho».
8
+ */
9
+
10
+ export const CLOSING_REASONS = {
11
+ not_done: 'sin marcar',
12
+ no_evidence: 'sin evidencia',
13
+ failing_evidence: 'con evidencia que falla',
14
+ };
15
+
16
+ /** `{ total, missing: [{ ac_id, reason }], ok }` de los criterios `[{ ac_id, done, evidence }]`. */
17
+ export function closingEvidence(acs) {
18
+ const list = Array.isArray(acs) ? acs : [];
19
+ const missing = [];
20
+ if (list.length === 0) missing.push({ ac_id: null, reason: 'no_criteria' });
21
+ for (const ac of list) {
22
+ const acId = String(ac?.ac_id ?? '?');
23
+ const evidence = ac?.evidence;
24
+ if (!ac?.done) missing.push({ ac_id: acId, reason: 'not_done' });
25
+ else if (evidence === null || evidence === undefined) continue;
26
+ else if (!Array.isArray(evidence) || evidence.length === 0) missing.push({ ac_id: acId, reason: 'no_evidence' });
27
+ else if (!evidence.some((e) => e && typeof e === 'object' && e.passed === true)) {
28
+ missing.push({ ac_id: acId, reason: 'failing_evidence' });
29
+ }
30
+ }
31
+ return { total: list.length, missing, ok: missing.length === 0 };
32
+ }
33
+
34
+ /** El motivo en una frase, como `closing_evidence_reason` del servidor; null si está todo demostrado. */
35
+ export function closingReason(result) {
36
+ if (result.ok) return null;
37
+ if (result.missing.some((m) => m.reason === 'no_criteria')) return 'La UC no tiene criterios: no hay nada demostrado.';
38
+ const detail = result.missing.map((m) => `${m.ac_id} (${CLOSING_REASONS[m.reason] ?? m.reason})`).join(', ');
39
+ return `${result.missing.length} de ${result.total} criterios sin demostrar: ${detail}.`;
40
+ }
41
+
42
+ /** True si la UC empezó antes de que la medida pasara a «block» (UC-12401 AC-06). */
43
+ export function startedBeforeBlock(startedAt, blockSince) {
44
+ const started = Date.parse(startedAt ?? '');
45
+ const since = Date.parse(blockSince ?? '');
46
+ return Number.isFinite(started) && Number.isFinite(since) && started < since;
47
+ }
48
+
49
+ /** Los criterios de una UC de items.json de FreeForm, con su evidencia (null si no consta). */
50
+ export function freeformCriteria(items, ucId) {
51
+ const list = Array.isArray(items) ? items : [];
52
+ const uc = list.find((i) => Array.isArray(i?.labels) && i.labels.includes('UC') && i?.meta?.uc_id === ucId);
53
+ if (!uc) return null;
54
+ return list
55
+ .filter((i) => i?.parent_id === uc.id && Array.isArray(i?.labels) && i.labels.includes('AC'))
56
+ .map((i) => {
57
+ const meta = i.meta && typeof i.meta === 'object' ? i.meta : {};
58
+ const known = Array.isArray(meta.evidence) || (meta.verdict && typeof meta.verdict === 'object');
59
+ return {
60
+ ac_id: meta.ac_id || (/^\[(AC-[^\]]+)\]/.exec(String(i.name || ''))?.[1] ?? '?'),
61
+ done: i.state === 'done',
62
+ evidence: known ? (Array.isArray(meta.evidence) ? meta.evidence : []) : null,
63
+ };
64
+ });
65
+ }
@@ -46,6 +46,7 @@ export function modosDe(raw, backendType) {
46
46
  const guardadas = raw && typeof raw.measures === 'object' && raw.measures ? raw.measures : {};
47
47
  const modos = {};
48
48
  const explicitas = [];
49
+ const bloqueaDesde = {};
49
50
  for (const [clave, nuevo] of Object.entries(MEASURES)) {
50
51
  const entrada = guardadas[clave];
51
52
  const guardada = !!entrada && MODES.includes(entrada.mode);
@@ -54,8 +55,10 @@ export function modosDe(raw, backendType) {
54
55
  modos[clave] = modo;
55
56
  // UC-12215: la puso una persona (no es el valor por defecto del tablero).
56
57
  if (guardada && entrada.source !== 'default') explicitas.push(clave);
58
+ // UC-12401: desde cuándo bloquea, para saber si una UC empezó antes de la regla.
59
+ if (modo === 'block' && typeof entrada?.block_since === 'string') bloqueaDesde[clave] = entrada.block_since;
57
60
  }
58
- return { origin, backendType, modos, explicitas };
61
+ return { origin, backendType, modos, explicitas, bloqueaDesde };
59
62
  }
60
63
 
61
64
  /** El modo de una medida en una política leída con leerPolitica («warn» si no la conoce). */
@@ -125,7 +128,10 @@ export async function leerPolitica({
125
128
  const policy = {
126
129
  origin: r.policy.origin,
127
130
  measures: Object.fromEntries(
128
- Object.entries(r.policy.measures || {}).map(([k, v]) => [k, { mode: v?.mode, source: v?.source }]),
131
+ Object.entries(r.policy.measures || {}).map(([k, v]) => [
132
+ k,
133
+ { mode: v?.mode, source: v?.source, ...(v?.block_since ? { block_since: v.block_since } : {}) },
134
+ ]),
129
135
  ),
130
136
  };
131
137
  try {
@@ -24,6 +24,7 @@ export const CONTENT_TOOLS = new Set([
24
24
  'get_board_status', 'get_cross_repo_dependencies', 'get_delivery_report', 'get_epic', 'get_evidence',
25
25
  'get_satellite_queue', 'get_sprint_status', 'get_uc', 'get_us', 'get_us_progress', 'import_spec',
26
26
  'link_uc_parent', 'list_epics', 'list_uc', 'list_us', 'mark_ac', 'mark_ac_batch', 'move_uc', 'move_us',
27
+ 'record_review_verdict',
27
28
  'set_ac_internal', 'set_ac_metadata', 'set_auth_token_placeholder', 'set_uc_satellite', 'set_us_epic',
28
29
  'setup_board', 'start_uc', 'sync_multirepo_state', 'update_ac', 'update_ac_batch', 'update_epic',
29
30
  'update_uc', 'update_uc_batch', 'update_us', 'validate_ac_quality',
@@ -53,6 +54,7 @@ export const FRAGMENT_TOOLS = {
53
54
  set_uc_satellite: 'uc+siblings',
54
55
  move_uc: 'uc+siblings',
55
56
  complete_uc: 'uc+siblings',
57
+ record_review_verdict: 'uc+siblings',
56
58
  get_us: 'story',
57
59
  move_us: 'story',
58
60
  update_us: 'story',
@@ -0,0 +1,54 @@
1
+ /**
2
+ * lib/independent-review.mjs — si la revisión deja fusionar una UC (UC-12402).
3
+ *
4
+ * La misma regla que `independent_review_result` de server/review.py (una prueba compara las dos):
5
+ * - una UC devuelta después de su último visto bueno no se fusiona;
6
+ * - la aceptación de una persona (el panel) basta en cualquier nivel de autopilot;
7
+ * - en «agresivo», y en FreeForm (sin panel), basta el último veredicto «aceptada» de un contexto
8
+ * independiente del que implementó;
9
+ * - fuera de «agresivo», en native, hace falta la persona;
10
+ * - solo cuentan los veredictos vigentes: caducan (`voided_at`) cuando la UC vuelve a trabajo;
11
+ * - el «aceptada» de una persona solo cuenta mientras su aceptación sigue en pie (UC-12404).
12
+ */
13
+
14
+ export const AGGRESSIVE = 'agresivo';
15
+ const VERDICTS = new Set(['accepted', 'returned']);
16
+
17
+ function counts(v, human) {
18
+ if (!v || !VERDICTS.has(v.verdict) || v.voided_at) return false;
19
+ return human || !(v.by_kind === 'person' && v.verdict === 'accepted');
20
+ }
21
+
22
+ function latest(verdicts, human = false) {
23
+ const valid = (Array.isArray(verdicts) ? verdicts : []).filter((v) => counts(v, human));
24
+ if (!valid.length) return null;
25
+ return valid.reduce((a, b) => (String(b.at ?? '') >= String(a.at ?? '') ? b : a));
26
+ }
27
+
28
+ /** `{ ok, reason_code?, reason? }` con los mismos códigos y textos que el servidor. */
29
+ export function independentReview({ humanAcceptance = null, verdicts = [], level = '', backendType = '' } = {}) {
30
+ const last = latest(verdicts, Boolean(humanAcceptance));
31
+ if (last && last.verdict === 'returned') {
32
+ return { ok: false, reason_code: 'returned', reason: `La UC fue devuelta: ${last.reason || 'sin motivo'}.` };
33
+ }
34
+ if (humanAcceptance) return { ok: true };
35
+ const agentOk = !!last && last.verdict === 'accepted' && !!last.independent;
36
+ if ((level === AGGRESSIVE || backendType === 'freeform') && agentOk) return { ok: true };
37
+ if (level !== AGGRESSIVE && backendType !== 'freeform') {
38
+ return {
39
+ ok: false,
40
+ reason_code: 'no_person_acceptance',
41
+ reason: 'Falta que una persona acepte la UC en el panel (fuera del autopilot «agresivo»).',
42
+ };
43
+ }
44
+ return {
45
+ ok: false,
46
+ reason_code: 'no_independent_verdict',
47
+ reason: 'Falta el veredicto «aceptada» de un evaluador en un contexto distinto del que implementó.',
48
+ };
49
+ }
50
+
51
+ export const INDEPENDENT_HOW_TO =
52
+ 'En autopilot «agresivo», lanza un evaluador aislado (subagente AG-09b) que revise los criterios y sus ' +
53
+ 'recibos y registre su veredicto con record_review_verdict. En los demás niveles, una persona acepta la ' +
54
+ 'UC en revisión desde el panel.';
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lib/uc-usage-send.mjs — envía los tokens nuevos de una UC al board, en su propio proceso
4
+ * (US-124 · UC-12403).
5
+ *
6
+ * Lo lanza uc-usage.mjs sin esperarlo: la sesión nunca espera al board. Usa la credencial del
7
+ * dispositivo (como el latido) y llama a `report_uc_usage`. Solo si el board lo acepta escribe el
8
+ * cursor nuevo: si falla, el siguiente envío lleva también estas cifras. El fallo se anota en
9
+ * .quality/logs/uc-usage.log como mucho una vez por minuto, sin credenciales ni cifras. Al
10
+ * terminar borra la marca de envío en curso.
11
+ *
12
+ * Uso: node uc-usage-send.mjs <raíz> '<informe JSON>' <fichero del cursor> '<cursor JSON>'
13
+ */
14
+
15
+ import { appendFileSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+ import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './heartbeat-send.mjs';
19
+ import { llamarTool } from './mcp-client.mjs';
20
+
21
+ export const REGISTRO = '.quality/logs/uc-usage.log';
22
+ const MARCA = '.quality/uc_usage_error.json';
23
+
24
+ function anotarFallo(raiz, motivo, ahora = Date.now()) {
25
+ const marca = join(raiz, MARCA);
26
+ let ultimo = 0;
27
+ try {
28
+ ultimo = JSON.parse(readFileSync(marca, 'utf8')).at || 0;
29
+ } catch {
30
+ ultimo = 0;
31
+ }
32
+ if (ahora - ultimo < 60_000) return;
33
+ try {
34
+ mkdirSync(join(raiz, '.quality/logs'), { recursive: true });
35
+ appendFileSync(join(raiz, REGISTRO), `${new Date(ahora).toISOString()} tokens de la UC no enviados: ${motivo}\n`);
36
+ writeFileSync(marca, JSON.stringify({ at: ahora }));
37
+ } catch {
38
+ // solo lectura: no pasa nada
39
+ }
40
+ }
41
+
42
+ /** Manda el informe y, si el board lo acepta, guarda el cursor. Nunca lanza. */
43
+ export async function enviarUso({ raiz, informe, cursorRuta, cursor, env = process.env, fetchImpl = fetch, cabeceras }) {
44
+ try {
45
+ const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
46
+ const h = cabeceras ?? (await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url }));
47
+ if (!h.Authorization) {
48
+ anotarFallo(raiz, 'este equipo no tiene credencial de SpecBox (specbox login)');
49
+ return false;
50
+ }
51
+ const r = await llamarTool({ url, cabeceras: h, nombre: 'report_uc_usage', args: informe, fetchImpl });
52
+ if (r?.success === false) {
53
+ anotarFallo(raiz, `el board lo rechazó (${r.code || 'sin código'})`);
54
+ // Un rechazo por los datos no se arregla reenviando: el cursor avanza.
55
+ if (r.code === 'INVALID_USAGE' || r.code === 'UC_NOT_FOUND') writeFileSync(cursorRuta, JSON.stringify(cursor));
56
+ return false;
57
+ }
58
+ writeFileSync(cursorRuta, JSON.stringify(cursor));
59
+ return true;
60
+ } catch (err) {
61
+ anotarFallo(raiz, err?.message || 'fallo');
62
+ return false;
63
+ } finally {
64
+ rmSync(`${cursorRuta}.pending`, { force: true });
65
+ }
66
+ }
67
+
68
+ const directo = (() => {
69
+ try {
70
+ return Boolean(process.argv[1]) && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
71
+ } catch {
72
+ return false;
73
+ }
74
+ })();
75
+ if (directo) {
76
+ let informe = null;
77
+ let cursor = null;
78
+ try {
79
+ informe = JSON.parse(process.argv[3] || 'null');
80
+ cursor = JSON.parse(process.argv[5] || 'null');
81
+ } catch {
82
+ informe = null;
83
+ }
84
+ const raiz = process.argv[2] || process.cwd();
85
+ const cursorRuta = process.argv[4];
86
+ (informe && cursor && cursorRuta ? enviarUso({ raiz, informe, cursorRuta, cursor }) : Promise.resolve(false)).finally(
87
+ () => process.exit(0),
88
+ );
89
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * lib/uc-usage.mjs — los tokens nuevos de una transcripción de Claude Code (US-124 · UC-12403).
3
+ *
4
+ * Claude Code guarda cada sesión en un JSONL; cada respuesta del modelo lleva `message.usage`
5
+ * (`input_tokens`, `output_tokens`, `cache_creation_input_tokens`, `cache_read_input_tokens`) y
6
+ * puede aparecer en varias líneas con el mismo `message.id`: se cuenta una vez, con su último uso.
7
+ * Las de los subagentes van en `<sesión>/subagents/agent-<id>.jsonl`. El formato no está
8
+ * documentado: una línea que no se reconoce no cuenta, y si nada se reconoce no se envía nada
9
+ * (la UC queda «estimado»). De la transcripción solo salen esas cuatro cifras: nunca texto.
10
+ *
11
+ * Puro salvo `leerDesde` (lee el fichero). Lo usan el hook `uc-usage.mjs` y sus pruebas.
12
+ */
13
+
14
+ import { createHash } from 'node:crypto';
15
+ import { closeSync, openSync, readSync, statSync } from 'node:fs';
16
+ import { dirname, join } from 'node:path';
17
+
18
+ export const CAMPOS = ['input_tokens', 'output_tokens', 'cache_creation_input_tokens', 'cache_read_input_tokens'];
19
+ /** Ids de respuesta ya contados que guarda el cursor (los últimos). */
20
+ export const MAX_IDS = 500;
21
+ /** Lo más que se lee de una vez: con más atraso, solo la cola. */
22
+ export const MAX_LECTURA = 32 * 1024 * 1024;
23
+
24
+ const AGENTE = /^[A-Za-z0-9_.:-]{1,128}$/;
25
+
26
+ /** Qué transcripción leer: la del subagente si el evento es suyo; si no, la de la sesión. */
27
+ export function transcriptDe(entrada = {}) {
28
+ const agente = typeof entrada.agent_id === 'string' && AGENTE.test(entrada.agent_id) ? entrada.agent_id : '';
29
+ if (agente) {
30
+ if (typeof entrada.agent_transcript_path === 'string' && entrada.agent_transcript_path) {
31
+ return { ruta: entrada.agent_transcript_path, agente, principal: false };
32
+ }
33
+ if (typeof entrada.transcript_path === 'string' && entrada.transcript_path && entrada.session_id) {
34
+ const ruta = join(dirname(entrada.transcript_path), String(entrada.session_id), 'subagents', `agent-${agente}.jsonl`);
35
+ return { ruta, agente, principal: false };
36
+ }
37
+ return null;
38
+ }
39
+ if (typeof entrada.transcript_path === 'string' && entrada.transcript_path) {
40
+ return { ruta: entrada.transcript_path, agente: '', principal: true };
41
+ }
42
+ return null;
43
+ }
44
+
45
+ /** El fichero del cursor de una transcripción, dentro de `dir`. */
46
+ export function rutaCursor(dir, ruta) {
47
+ return join(dir, `${createHash('sha1').update(ruta).digest('hex').slice(0, 16)}.json`);
48
+ }
49
+
50
+ /**
51
+ * Las líneas completas desde `offset` y el offset nuevo (en bytes). Si el fichero encogió, desde
52
+ * el principio; con más de `tope` bytes pendientes, solo la cola, desde un principio de línea.
53
+ */
54
+ export function leerDesde(ruta, offset = 0, tope = MAX_LECTURA) {
55
+ const tam = statSync(ruta).size;
56
+ let inicio = Number.isInteger(offset) && offset >= 0 && offset <= tam ? offset : 0;
57
+ let saltarPrimera = false;
58
+ if (tam - inicio > tope) {
59
+ inicio = tam - tope;
60
+ saltarPrimera = true;
61
+ }
62
+ if (tam === inicio) return { lineas: [], offset: inicio };
63
+ const buf = Buffer.alloc(tam - inicio);
64
+ const fd = openSync(ruta, 'r');
65
+ try {
66
+ readSync(fd, buf, 0, buf.length, inicio);
67
+ } finally {
68
+ closeSync(fd);
69
+ }
70
+ const ultimo = buf.lastIndexOf(0x0a);
71
+ if (ultimo < 0) return { lineas: [], offset: inicio };
72
+ let desde = 0;
73
+ if (saltarPrimera) desde = buf.indexOf(0x0a) + 1;
74
+ const lineas = buf.subarray(desde, ultimo).toString('utf8').split('\n');
75
+ return { lineas, offset: inicio + ultimo + 1 };
76
+ }
77
+
78
+ /**
79
+ * Los tokens de `lineas`: cada respuesta (`message.id`) una vez, con el último uso que trae, sin
80
+ * las ya contadas (`vistos`), sin las de los subagentes en la transcripción principal y sin las
81
+ * anteriores a `desde` (cuando empezó la UC). Devuelve las cuatro cifras, `messages` (respuestas
82
+ * contadas) e `ids` (las nuevas, para el cursor). Nada más sale de la transcripción.
83
+ */
84
+ export function sumarUso(lineas, vistos = [], { principal = false, desde = null } = {}) {
85
+ const previos = new Set(vistos);
86
+ const limite = desde ? Date.parse(desde) : NaN;
87
+ const ultimos = new Map();
88
+ for (const linea of lineas) {
89
+ if (!linea || !linea.trim()) continue;
90
+ let d;
91
+ try {
92
+ d = JSON.parse(linea);
93
+ } catch {
94
+ continue;
95
+ }
96
+ if (principal && d?.isSidechain === true) continue;
97
+ const m = d?.message;
98
+ const uso = m?.usage;
99
+ if (!uso || typeof uso !== 'object' || typeof m.id !== 'string' || !m.id) continue;
100
+ if (previos.has(m.id)) continue;
101
+ if (!Number.isNaN(limite) && typeof d.timestamp === 'string') {
102
+ const t = Date.parse(d.timestamp);
103
+ if (!Number.isNaN(t) && t < limite) continue;
104
+ }
105
+ ultimos.set(m.id, uso);
106
+ }
107
+ const totales = Object.fromEntries(CAMPOS.map((c) => [c, 0]));
108
+ for (const uso of ultimos.values()) {
109
+ for (const c of CAMPOS) {
110
+ const n = uso[c];
111
+ if (Number.isSafeInteger(n) && n >= 0) totales[c] += n;
112
+ }
113
+ }
114
+ return { ...totales, messages: ultimos.size, ids: [...ultimos.keys()] };
115
+ }
116
+
117
+ /** Lo que se envía a `report_uc_usage`: identificadores y cifras, nada más (AC-04). */
118
+ export function informe({ proyecto, uc, sesion, agente, uso }) {
119
+ return {
120
+ project_id: proyecto,
121
+ uc_id: uc,
122
+ session_id: sesion,
123
+ agent_id: agente || '',
124
+ ...Object.fromEntries(CAMPOS.map((c) => [c, uso[c]])),
125
+ messages: uso.messages,
126
+ };
127
+ }
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * merge-guard.mjs — PreToolUse de `gh pr merge`: lo que se fusiona está demostrado y revisado.
4
+ *
5
+ * Dos medidas de EP-20 sobre la UC activa, con los datos del tablero:
6
+ *
7
+ * - `closing_evidence` (UC-12401): cada criterio está hecho y tiene al menos un recibo que pasa (la
8
+ * regla de complete_uc, en lib/closing-evidence.mjs). /implement marca los criterios y pasa la UC a
9
+ * revisión antes de fusionar, así que una prueba de aceptación que falla no llega a fusionarse.
10
+ * - `independent_review` (UC-12402): la UC tiene el visto bueno de alguien que no la implementó
11
+ * (lib/independent-review.mjs). Fuera del autopilot «agresivo» hace falta una persona (el panel); en
12
+ * «agresivo», o en FreeForm, basta un evaluador en un contexto independiente.
13
+ *
14
+ * En «warn» (por defecto) avisa con lo que falta y deja fusionar; en «block» detiene la fusión y dice
15
+ * cómo seguir. Una UC anterior a la regla (en el marcador, o empezada antes de que la medida
16
+ * bloqueara) no se detiene. Sin datos (sin UC activa, sin red) no detiene nada.
17
+ *
18
+ * Los datos salen de doc/tracking/items.json en FreeForm y de `get_uc` con la identidad del dispositivo
19
+ * en native. El nivel de autopilot, de `specbox.autopilot.level` en .claude/settings.local.json.
20
+ */
21
+
22
+ import { execFileSync } from 'node:child_process';
23
+ import { isAbsolute, join } from 'node:path';
24
+ import { readHookInput, readJsonFile } from './lib/utils.mjs';
25
+ import { getProjectConfig } from './lib/config.mjs';
26
+ import { blockWith, noteWith } from './lib/output.mjs';
27
+ import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
28
+ import { recordCorrectionIfBlocked, recordEnforcementEvent } from './lib/enforcement-events.mjs';
29
+ import { closingEvidence, closingReason, freeformCriteria, startedBeforeBlock } from './lib/closing-evidence.mjs';
30
+ import { INDEPENDENT_HOW_TO, independentReview } from './lib/independent-review.mjs';
31
+ import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './lib/heartbeat-send.mjs';
32
+ import { llamarTool } from './lib/mcp-client.mjs';
33
+
34
+ const { toolInput, cwd } = readHookInput();
35
+ if (!/\bgh\s+pr\s+merge\b/m.test(String(toolInput.command || ''))) process.exit(0);
36
+
37
+ let root = cwd;
38
+ try {
39
+ root = execFileSync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], {
40
+ encoding: 'utf-8',
41
+ stdio: ['ignore', 'pipe', 'ignore'],
42
+ timeout: 5000,
43
+ }).trim() || cwd;
44
+ } catch {
45
+ // fuera de un repositorio: se usa la carpeta actual
46
+ }
47
+ process.chdir(root);
48
+ const config = getProjectConfig();
49
+ if (!config.isSpecDriven) process.exit(0);
50
+ const marker = readJsonFile('.quality/active_uc.json');
51
+ if (!marker?.uc_id) process.exit(0);
52
+
53
+ const politica = await leerPolitica({
54
+ root,
55
+ backendType: config.backendType,
56
+ boardId: config.boardId,
57
+ trackingDir: config.freeformRoot,
58
+ });
59
+ const MEASURES = ['closing_evidence', 'independent_review'].filter((m) => modoDe(politica, m) !== 'off');
60
+ if (!MEASURES.length) process.exit(0);
61
+ const level = readJsonFile('.claude/settings.local.json')?.specbox?.autopilot?.level || '';
62
+
63
+ /** `{ acs, humanAcceptance, verdicts }` de la UC activa, o null si no se puede leer. */
64
+ async function datosDeLaUc() {
65
+ if (config.backendType === 'freeform') {
66
+ const dir = config.freeformRoot
67
+ ? (isAbsolute(config.freeformRoot) ? config.freeformRoot : join(root, config.freeformRoot))
68
+ : join(root, 'doc', 'tracking');
69
+ const items = readJsonFile(join(dir, 'items.json'));
70
+ const acs = freeformCriteria(items, marker.uc_id);
71
+ if (acs === null) return null;
72
+ const uc = items.find((i) => Array.isArray(i?.labels) && i.labels.includes('UC') && i?.meta?.uc_id === marker.uc_id);
73
+ const verdicts = Array.isArray(uc?.meta?.review_verdicts) ? uc.meta.review_verdicts : [];
74
+ return { acs, humanAcceptance: null, verdicts };
75
+ }
76
+ if (config.backendType !== 'native' || !config.boardId || process.env.SPECBOX_ENFORCEMENT_POLICY === 'off') return null;
77
+ try {
78
+ const url = process.env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
79
+ const cabeceras = await cabecerasDelDispositivo({ ...process.env, CLAUDE_CODE_MCP_SERVER_URL: url });
80
+ if (!cabeceras.Authorization) return null;
81
+ const uc = await llamarTool({
82
+ url,
83
+ cabeceras,
84
+ nombre: 'get_uc',
85
+ args: { board_id: config.boardId, uc_id: marker.uc_id },
86
+ topeMs: 4000,
87
+ });
88
+ if (!Array.isArray(uc?.acceptance_criteria)) return null;
89
+ return {
90
+ acs: uc.acceptance_criteria.map((ac) => ({ ac_id: ac.id, done: !!ac.done, evidence: Array.isArray(ac.evidence) ? ac.evidence : [] })),
91
+ humanAcceptance: uc.human_acceptance || null,
92
+ verdicts: Array.isArray(uc.review_verdicts) ? uc.review_verdicts : [],
93
+ };
94
+ } catch {
95
+ return null; // sin red o con el tablero caído: no se detiene nada
96
+ }
97
+ }
98
+
99
+ const datos = await datosDeLaUc();
100
+ if (datos === null) process.exit(0);
101
+
102
+ const evaluar = {
103
+ closing_evidence: () => {
104
+ const r = closingEvidence(datos.acs);
105
+ return r.ok
106
+ ? null
107
+ : {
108
+ motivo: closingReason(r),
109
+ como: [
110
+ 'Marca cada criterio con mark_ac (o mark_ac_batch) y un recibo que pase: una prueba, una captura, un enlace o una nota escrita si se comprobó a mano.',
111
+ 'Si una prueba de aceptación falla, corrige el código, vuelve a pasarla y márcala antes de fusionar.',
112
+ ],
113
+ };
114
+ },
115
+ independent_review: () => {
116
+ const r = independentReview({
117
+ humanAcceptance: datos.humanAcceptance,
118
+ verdicts: datos.verdicts,
119
+ level,
120
+ backendType: config.backendType,
121
+ });
122
+ return r.ok ? null : { motivo: r.reason, como: [INDEPENDENT_HOW_TO] };
123
+ },
124
+ };
125
+
126
+ const bloqueos = [];
127
+ const avisos = [];
128
+ for (const measure of MEASURES) {
129
+ const fallo = evaluar[measure]();
130
+ if (!fallo) {
131
+ await recordCorrectionIfBlocked({ root, config, measure, ucId: marker.uc_id, by: 'merge-guard' });
132
+ continue;
133
+ }
134
+ const predates =
135
+ (Array.isArray(marker.predates_rule) && marker.predates_rule.includes(measure)) ||
136
+ startedBeforeBlock(marker.started_at, politica.bloqueaDesde?.[measure]);
137
+ const motivo = `${marker.uc_id}: ${fallo.motivo}`;
138
+ if (modoDe(politica, measure) === 'block' && !predates) {
139
+ await recordEnforcementEvent({ root, config, measure, ucId: marker.uc_id, outcome: 'blocked', by: 'merge-guard' });
140
+ bloqueos.push(`SpecBox detuvo la fusión por la medida ${measure}. Motivo: ${motivo}`, ...fallo.como.map((c) => `Cómo seguir: ${c}`));
141
+ } else {
142
+ avisos.push(
143
+ predates
144
+ ? `La UC es anterior a la regla ${measure}: la fusión sigue. Motivo: ${motivo}`
145
+ : `Medida ${measure} en «warn»: la fusión sigue. Motivo: ${motivo}`,
146
+ ...fallo.como,
147
+ );
148
+ }
149
+ }
150
+
151
+ if (bloqueos.length) blockWith('SPEC GUARD: la UC no está lista para fusionarse', [...bloqueos, ...avisos]);
152
+ if (avisos.length) noteWith('PreToolUse', 'SPEC GUARD: la UC no está lista para fusionarse (aviso)', avisos);
@@ -144,6 +144,12 @@
144
144
  "command": "node .claude/hooks/prd-sync-guard.mjs",
145
145
  "timeout": 20
146
146
  },
147
+ {
148
+ "type": "command",
149
+ "if": "Bash(*gh pr merge*)",
150
+ "command": "node .claude/hooks/merge-guard.mjs",
151
+ "timeout": 20
152
+ },
147
153
  {
148
154
  "type": "command",
149
155
  "if": "Bash(*git commit*)",
@@ -176,6 +182,26 @@
176
182
  }
177
183
  ]
178
184
  },
185
+ {
186
+ "matcher": "mcp__SpecBox-MCP__(start_uc|record_review_verdict)",
187
+ "hooks": [
188
+ {
189
+ "type": "command",
190
+ "command": "node .claude/hooks/agent-identity.mjs",
191
+ "timeout": 5
192
+ }
193
+ ]
194
+ },
195
+ {
196
+ "matcher": "mcp__SpecBox-MCP__complete_uc",
197
+ "hooks": [
198
+ {
199
+ "type": "command",
200
+ "command": "node .claude/hooks/uc-usage.mjs",
201
+ "timeout": 5
202
+ }
203
+ ]
204
+ },
179
205
  {
180
206
  "matcher": "mcp__SpecBox-MCP__(move_uc|complete_uc)",
181
207
  "hooks": [
@@ -357,6 +383,22 @@
357
383
  "type": "command",
358
384
  "command": "node .claude/hooks/on-session-end.mjs",
359
385
  "timeout": 10
386
+ },
387
+ {
388
+ "type": "command",
389
+ "command": "node .claude/hooks/uc-usage.mjs",
390
+ "timeout": 5
391
+ }
392
+ ]
393
+ }
394
+ ],
395
+ "SubagentStop": [
396
+ {
397
+ "hooks": [
398
+ {
399
+ "type": "command",
400
+ "command": "node .claude/hooks/uc-usage.mjs",
401
+ "timeout": 5
360
402
  }
361
403
  ]
362
404
  }
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * uc-usage.mjs — el coste real de la UC activa en tokens (US-124 · UC-12403).
4
+ * NO BLOQUEA y es silencioso: nunca escribe nada para el agente ni sale con error.
5
+ *
6
+ * Eventos: Stop (al terminar cada turno de la sesión), SubagentStop (al terminar cada subagente) y
7
+ * PreToolUse de complete_uc (lo último antes de cerrar, que después ya no hay UC activa). Lee de la
8
+ * transcripción lo nuevo desde su cursor (`.quality/uc_usage/`), suma `message.usage` contando cada
9
+ * respuesta una vez y solo desde que empezó la UC, y lo manda a la UC activa con `report_uc_usage`
10
+ * en un proceso aparte que no se espera (lib/uc-usage-send.mjs). Solo cifras, nunca texto (AC-04).
11
+ * Solo en proyectos con board native; si el formato de la transcripción no se reconoce, no manda
12
+ * nada y la UC queda «estimado».
13
+ *
14
+ * SPECBOX_UC_USAGE=off lo apaga. SPECBOX_UC_USAGE_DRY_RUN=<fichero> escribe el informe en ese
15
+ * fichero (y avanza el cursor) en vez de enviarlo (pruebas).
16
+ */
17
+
18
+ import { spawn } from 'node:child_process';
19
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
20
+ import { dirname, join } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { getProjectConfig } from './lib/config.mjs';
23
+ import { MAX_IDS, informe, leerDesde, rutaCursor, sumarUso, transcriptDe } from './lib/uc-usage.mjs';
24
+ import { fileAge, mkdir, readHookInput, readJsonFile } from './lib/utils.mjs';
25
+
26
+ const DIR = '.quality/uc_usage';
27
+ /** Un envío en curso más reciente que esto hace esperar al siguiente evento (sin contar doble). */
28
+ const EN_CURSO_MS = 10_000;
29
+ const IGNORADOS = ['uc_usage/', 'uc_usage_error.json', 'logs/uc-usage.log'];
30
+
31
+ function asegurarIgnorados() {
32
+ const ruta = '.quality/.gitignore';
33
+ let actual = '';
34
+ try {
35
+ actual = readFileSync(ruta, 'utf8');
36
+ } catch {
37
+ actual = '';
38
+ }
39
+ const faltan = IGNORADOS.filter((l) => !actual.split('\n').includes(l));
40
+ if (faltan.length === 0) return;
41
+ try {
42
+ appendFileSync(ruta, `${actual && !actual.endsWith('\n') ? '\n' : ''}${faltan.join('\n')}\n`);
43
+ } catch {
44
+ // solo lectura: no pasa nada
45
+ }
46
+ }
47
+
48
+ try {
49
+ if (process.env.SPECBOX_UC_USAGE === 'off') process.exit(0);
50
+ const { event, toolInput, payload } = readHookInput();
51
+ const { boardId, backendType } = getProjectConfig();
52
+ if (backendType !== 'native' || !boardId) process.exit(0);
53
+
54
+ const marcador = fileAge('.quality/active_uc.json') < 86400 ? readJsonFile('.quality/active_uc.json') : null;
55
+ const uc = marcador?.uc_id;
56
+ // Antes de complete_uc, solo si cierra la UC activa.
57
+ if (!uc || (event === 'PreToolUse' && toolInput.uc_id && toolInput.uc_id !== uc)) process.exit(0);
58
+ const sesion = typeof payload.session_id === 'string' ? payload.session_id : '';
59
+ const t = transcriptDe(payload);
60
+ if (!sesion || !t || !existsSync(t.ruta)) process.exit(0);
61
+
62
+ mkdir(DIR);
63
+ asegurarIgnorados();
64
+ const cursorRuta = rutaCursor(DIR, t.ruta);
65
+ if (fileAge(`${cursorRuta}.pending`) * 1000 < EN_CURSO_MS) process.exit(0);
66
+ const cursor = readJsonFile(cursorRuta) || {};
67
+ const previo = cursor.ruta === t.ruta ? cursor : {};
68
+ const { lineas, offset } = leerDesde(t.ruta, previo.offset ?? 0);
69
+ const uso = sumarUso(lineas, previo.ids || [], { principal: t.principal, desde: marcador.started_at || null });
70
+ const nuevo = { ruta: t.ruta, offset, ids: [...(previo.ids || []), ...uso.ids].slice(-MAX_IDS) };
71
+
72
+ if (uso.messages === 0) {
73
+ // Nada nuevo, o un formato que no se reconoce: se avanza sin enviar.
74
+ writeFileSync(cursorRuta, JSON.stringify(nuevo));
75
+ process.exit(0);
76
+ }
77
+ const datos = informe({ proyecto: boardId, uc, sesion, agente: t.agente, uso });
78
+ if (process.env.SPECBOX_UC_USAGE_DRY_RUN) {
79
+ appendFileSync(process.env.SPECBOX_UC_USAGE_DRY_RUN, `${JSON.stringify(datos)}\n`);
80
+ writeFileSync(cursorRuta, JSON.stringify(nuevo));
81
+ } else {
82
+ writeFileSync(`${cursorRuta}.pending`, String(Date.now()));
83
+ const enviar = join(dirname(fileURLToPath(import.meta.url)), 'lib', 'uc-usage-send.mjs');
84
+ const hijo = spawn(
85
+ process.execPath,
86
+ [enviar, process.cwd(), JSON.stringify(datos), cursorRuta, JSON.stringify(nuevo)],
87
+ { detached: true, stdio: 'ignore' },
88
+ );
89
+ hijo.unref();
90
+ }
91
+ } catch {
92
+ // El coste nunca molesta a la sesión.
93
+ }
94
+ process.exit(0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specbox",
3
- "version": "6.40.0",
3
+ "version": "6.42.0",
4
4
  "description": "Conecta este ordenador a SpecBox sin copiar tokens (specbox login, status y logout) y actualiza los hooks del proyecto sin pisar los tuyos (specbox hooks).",
5
5
  "type": "module",
6
6
  "bin": {