specbox 6.41.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 } }));
@@ -27,6 +27,9 @@
27
27
  * UC-12401: complete_uc gets the policy like start_uc (its measure is closing_evidence) and what
28
28
  * both return is saved the same way; mark_ac and mark_ac_batch get the git author as `marked_by`,
29
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.
30
33
  */
31
34
 
32
35
  import { execFileSync } from 'node:child_process';
@@ -51,6 +54,7 @@ import {
51
54
  writeAtomic,
52
55
  } from './lib/freeform-fragment.mjs';
53
56
  import { readHookInput } from './lib/utils.mjs';
57
+ import { IDENTITY_TOOLS, identityFields } from './lib/agent-identity.mjs';
54
58
 
55
59
  /** The tools whose measures read the board's policy and may record a block (UC-12301, UC-12401). */
56
60
  const GATE_TOOLS = new Set(['start_uc', 'complete_uc']);
@@ -205,6 +209,13 @@ function pre() {
205
209
  const author = gitAuthor();
206
210
  if (author) updatedInput.marked_by = author.slice(0, 100);
207
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
+ }
208
219
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } }));
209
220
  }
210
221
 
@@ -179,12 +179,14 @@
179
179
  "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
180
180
  "c212b004d384feba728e0ee7e955bfb09fafe39112cad7c530620a1e932d169a",
181
181
  "9ab7d65162056498f7c403eff0eb571b914b9d5c70b9bfdcd52b885c7bd20fef",
182
- "ca2a8fa168b42abc8aea497962d0b183372ebdcc91afd4df493f435188009751"
182
+ "ca2a8fa168b42abc8aea497962d0b183372ebdcc91afd4df493f435188009751",
183
+ "e235265d07615981e2fdffe8b24078692b20499c8cf5ebfbe9f5c9bc67fe08e7"
183
184
  ],
184
185
  "lib/freeform-fragment.mjs": [
185
186
  "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
186
187
  "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1",
187
- "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141"
188
+ "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
189
+ "69d42e834d0925154e25d5f79ab849bb48b253cceab16dce92f1d55743d0219b"
188
190
  ],
189
191
  "lib/app-spec-zones.mjs": [
190
192
  "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174"
@@ -225,6 +227,25 @@
225
227
  "eb956a5663a724b2945531cacb2d72f0f7200f17bd420e3e5ec6c1e7bef77f8b"
226
228
  ],
227
229
  "merge-guard.mjs": [
228
- "69d3100e1134fd430db521670c9dc60eeb20985c0b4feeb33f0b5f5700a36646"
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"
229
250
  ]
230
251
  }
@@ -1,6 +1,7 @@
1
1
  {
2
- "version": "6.41.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,12 +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": "ca2a8fa168b42abc8aea497962d0b183372ebdcc91afd4df493f435188009751",
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",
20
- "merge-guard.mjs": "69d3100e1134fd430db521670c9dc60eeb20985c0b4feeb33f0b5f5700a36646",
21
+ "merge-guard.mjs": "21ae9b085b8cd76d4e1310fba37e2c2ee22bf65c572f9dbd0e1616fa416bc9be",
21
22
  "no-bypass-guard.mjs": "d7a31ac193edb8dedda2d9d696aa747612f7348ee475e57653ae0813f9b36189",
22
23
  "on-session-end.mjs": "fd5b7cf3bf2c419fd4125e21b338c4c849a4daaef21d5e15253caed54965b40c",
23
24
  "pipeline-phase-guard.mjs": "761b82c8b0c4884eba54d529e1f726d547003a6efe05425b45a1a0b77b90fe0d",
@@ -34,6 +35,8 @@
34
35
  "stripe-safety-guard.mjs": "5d7c0a9524657fe47e6ec4ea0eeb055d238f133eeac488c145cb1d5ae88b96de",
35
36
  "uc-lifecycle-guard.mjs": "606c4397200ffbc3b2c89c9af68c340692e6d48f6c792da1d6531b5215fb16e9",
36
37
  "uc-state-marker.mjs": "7c649407416f3837196c9cf8a0caf44b8aeead7e2da9eda55ee5526972630cb2",
38
+ "uc-usage.mjs": "db90605adcea2138a72b7e73eade12a8978801c789099ad8c1a6468206ff7499",
39
+ "lib/agent-identity.mjs": "e3a1fbc8b8f67725b33d84ea15c7403e6e0570ca6f811acde5a34f636cdbac47",
37
40
  "lib/app-spec-zones.mjs": "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174",
38
41
  "lib/autopilot.mjs": "317eabaed8dead40f3d55e642b7465a3ba4e884523e0ae7b933e197153fc6f95",
39
42
  "lib/closing-evidence.mjs": "eb956a5663a724b2945531cacb2d72f0f7200f17bd420e3e5ec6c1e7bef77f8b",
@@ -43,11 +46,12 @@
43
46
  "lib/enforcement-events.mjs": "5fe963aab5f24c2b50c9991f11dbda48440a98f7394e02c823a276ee1bb2d608",
44
47
  "lib/enforcement-policy.mjs": "7aa258be02a1f0a284698ac4c91fc3841db326250550ba0832cf9988b10bb2aa",
45
48
  "lib/execution-context.mjs": "953eb7ec86f6893288df4e76c9c63c737c8e8ba4e337271402ce5eaca00330fa",
46
- "lib/freeform-fragment.mjs": "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
49
+ "lib/freeform-fragment.mjs": "69d42e834d0925154e25d5f79ab849bb48b253cceab16dce92f1d55743d0219b",
47
50
  "lib/freeform-path.mjs": "9ea85781821ae911873d1dbd13d58811a6c88e50480d2b3b378725ce2872be0c",
48
51
  "lib/handoff-builder.mjs": "2f7ffd554484d9560f525ab2548c240bac65b23bbe6eb8907e64c66bd818e22d",
49
52
  "lib/heartbeat-send.mjs": "739d4fe4b573e99fffdad2252a75cb7dcf18526dda72f1db6cff25b16f76383a",
50
53
  "lib/heartbeat.mjs": "0da0045e6a350f71c54fe972dc2a97880b8eab0aaeaab83595ff3ef3ac0fdae6",
54
+ "lib/independent-review.mjs": "6bf0e83f526649a5c1af7d6f01998a8ea06891420831ec85098279436de2bf2b",
51
55
  "lib/mcp-client-io.mjs": "e863d22434fd9a1abf57804291b38e72d2236a0b7ff39460150ac883b2a7b780",
52
56
  "lib/mcp-client.mjs": "02610127d29b4c001a5a44ad3bff74d954808f8e13b1a20a378a1da03274abbd",
53
57
  "lib/native-reservation-revalidate.mjs": "1b394e8eb5d01480b71ac0976d636814483891e9f862edd5ac0216ac0128b023",
@@ -58,6 +62,8 @@
58
62
  "lib/roadmap.mjs": "0ff30f9d5707c89b8b43406e76f4870a39dd4f787221c32310ef6f9040879d8a",
59
63
  "lib/token-counter.mjs": "ca637273dcf731c7a951f28b8307d13de06d311cf85741ef56c4e3df9eaa231e",
60
64
  "lib/uc-state.mjs": "699786c91e83ad5b35b42f0ef812728e951be28a12ae0c037d1790795adc9e90",
65
+ "lib/uc-usage-send.mjs": "3d5b2e60a53cc3ffff0bee8c716a45ff8f7db02b59ff323860a3d5ab5e6e57a2",
66
+ "lib/uc-usage.mjs": "ee793a46a527726ffdff7785fcb8be347d29ed00bc3fd1356a865211cfde87f5",
61
67
  "lib/utils.mjs": "4c21939aac114a11a68e2519d5d99f7f0bf482f08af0dc9e51ac715cc93ddfa2"
62
68
  }
63
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
+ }
@@ -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
+ }
@@ -1,20 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * merge-guard.mjs — PreToolUse de `gh pr merge`: lo que se fusiona está demostrado (UC-12401).
3
+ * merge-guard.mjs — PreToolUse de `gh pr merge`: lo que se fusiona está demostrado y revisado.
4
4
  *
5
- * La medida `closing_evidence` de EP-20, antes de fusionar la PR de la UC activa: cada criterio de la
6
- * UC está hecho y tiene al menos un recibo que pasa (la misma regla que complete_uc, en
7
- * lib/closing-evidence.mjs). /implement marca los criterios y pasa la UC a revisión antes de fusionar,
8
- * así que una prueba de aceptación que falla deja su criterio sin recibo que pase y la fusión no sigue.
5
+ * Dos medidas de EP-20 sobre la UC activa, con los datos del tablero:
9
6
  *
10
- * - En «warn» (por defecto) avisa con cada criterio y su motivo, y deja fusionar.
11
- * - En «block» detiene la fusión y dice cómo seguir.
12
- * - Una UC anterior a la regla (en el marcador, o empezada antes de que la medida bloqueara) no se
13
- * detiene: avisa.
14
- * - Sin datos (sin UC activa, sin red, un backend sin recibos) no detiene nada.
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.
15
13
  *
16
- * Los criterios salen de doc/tracking/items.json en FreeForm y de `get_uc` con la identidad del
17
- * dispositivo en native. US-124 añade aquí `independent_review` (UC-12402).
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.
18
20
  */
19
21
 
20
22
  import { execFileSync } from 'node:child_process';
@@ -25,10 +27,10 @@ import { blockWith, noteWith } from './lib/output.mjs';
25
27
  import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
26
28
  import { recordCorrectionIfBlocked, recordEnforcementEvent } from './lib/enforcement-events.mjs';
27
29
  import { closingEvidence, closingReason, freeformCriteria, startedBeforeBlock } from './lib/closing-evidence.mjs';
30
+ import { INDEPENDENT_HOW_TO, independentReview } from './lib/independent-review.mjs';
28
31
  import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './lib/heartbeat-send.mjs';
29
32
  import { llamarTool } from './lib/mcp-client.mjs';
30
33
 
31
- const MEASURE = 'closing_evidence';
32
34
  const { toolInput, cwd } = readHookInput();
33
35
  if (!/\bgh\s+pr\s+merge\b/m.test(String(toolInput.command || ''))) process.exit(0);
34
36
 
@@ -54,16 +56,22 @@ const politica = await leerPolitica({
54
56
  boardId: config.boardId,
55
57
  trackingDir: config.freeformRoot,
56
58
  });
57
- const mode = modoDe(politica, MEASURE);
58
- if (mode === 'off') process.exit(0);
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 || '';
59
62
 
60
- /** Los criterios de la UC activa con sus recibos, o null si no se pueden leer. */
61
- async function criterios() {
63
+ /** `{ acs, humanAcceptance, verdicts }` de la UC activa, o null si no se puede leer. */
64
+ async function datosDeLaUc() {
62
65
  if (config.backendType === 'freeform') {
63
66
  const dir = config.freeformRoot
64
67
  ? (isAbsolute(config.freeformRoot) ? config.freeformRoot : join(root, config.freeformRoot))
65
68
  : join(root, 'doc', 'tracking');
66
- return freeformCriteria(readJsonFile(join(dir, 'items.json')), marker.uc_id);
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 };
67
75
  }
68
76
  if (config.backendType !== 'native' || !config.boardId || process.env.SPECBOX_ENFORCEMENT_POLICY === 'off') return null;
69
77
  try {
@@ -78,39 +86,67 @@ async function criterios() {
78
86
  topeMs: 4000,
79
87
  });
80
88
  if (!Array.isArray(uc?.acceptance_criteria)) return null;
81
- return uc.acceptance_criteria.map((ac) => ({ ac_id: ac.id, done: !!ac.done, evidence: Array.isArray(ac.evidence) ? ac.evidence : [] }));
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
+ };
82
94
  } catch {
83
95
  return null; // sin red o con el tablero caído: no se detiene nada
84
96
  }
85
97
  }
86
98
 
87
- const acs = await criterios();
88
- if (acs === null) process.exit(0);
89
- const result = closingEvidence(acs);
90
- if (result.ok) {
91
- await recordCorrectionIfBlocked({ root, config, measure: MEASURE, ucId: marker.uc_id, by: 'merge-guard' });
92
- process.exit(0);
93
- }
99
+ const datos = await datosDeLaUc();
100
+ if (datos === null) process.exit(0);
94
101
 
95
- const reason = `${marker.uc_id}: ${closingReason(result)}`;
96
- const how = [
97
- '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.',
98
- 'Si una prueba de aceptación falla, corrige el código, vuelve a pasarla y márcala antes de fusionar.',
99
- ];
100
- const predates =
101
- (Array.isArray(marker.predates_rule) && marker.predates_rule.includes(MEASURE)) ||
102
- startedBeforeBlock(marker.started_at, politica.bloqueaDesde?.[MEASURE]);
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
+ };
103
125
 
104
- if (mode === 'block' && !predates) {
105
- await recordEnforcementEvent({ root, config, measure: MEASURE, ucId: marker.uc_id, outcome: 'blocked', by: 'merge-guard' });
106
- blockWith('SPEC GUARD: la UC tiene criterios sin demostrar', [
107
- `SpecBox detuvo la fusión por la medida ${MEASURE}. Motivo: ${reason}`,
108
- ...how.map((h) => `Cómo seguir: ${h}`),
109
- ]);
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
+ }
110
149
  }
111
- noteWith('PreToolUse', 'SPEC GUARD: la UC tiene criterios sin demostrar (aviso)', [
112
- predates
113
- ? `La UC es anterior a la regla ${MEASURE}: la fusión sigue. Motivo: ${reason}`
114
- : `Medida ${MEASURE} en «warn»: la fusión sigue. Motivo: ${reason}`,
115
- ...how,
116
- ]);
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);
@@ -182,6 +182,26 @@
182
182
  }
183
183
  ]
184
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
+ },
185
205
  {
186
206
  "matcher": "mcp__SpecBox-MCP__(move_uc|complete_uc)",
187
207
  "hooks": [
@@ -363,6 +383,22 @@
363
383
  "type": "command",
364
384
  "command": "node .claude/hooks/on-session-end.mjs",
365
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
366
402
  }
367
403
  ]
368
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.41.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": {