specbox 6.37.0 → 6.38.1

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.
@@ -1,32 +1,37 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * app-docs-fragment.mjs — PostToolUse: la zona «roadmap» de app_prd.md sigue al tablero (UC-12203).
3
+ * app-docs-fragment.mjs — la zona «roadmap» de app_prd.md sigue al tablero (UC-12203, UC-12218).
4
4
  *
5
- * Tras complete_uc, move_uc, add_uc, delete_uc y mark_ac_batch el servidor devuelve
6
- * `app_docs_sync.roadmap_body` (el cuerpo de la zona calculado con el tablero). Este hook lo escribe
7
- * en doc/app/app_prd.md del repositorio que lo tiene: el orquestador en un proyecto multirepo (el
8
- * satélite no guarda copia). Con FreeForm por fragmentos (`render: "client"`) calcula el mismo
9
- * cuerpo con su items.json.
5
+ * Tools: complete_uc, move_uc, add_uc, delete_uc y mark_ac_batch.
10
6
  *
11
- * Solo escribe si ese repositorio está en su rama principal (main o master): la zona sale del
12
- * tablero, así que en una rama de trabajo se deja para el siguiente cambio en main y dos ramas no
13
- * chocan al fusionar. Oculta el cuerpo de la respuesta que ve el modelo. Nunca bloquea.
7
+ * PreToolUse: pide la zona al servidor (`with_roadmap: true`) solo si hace falta: el repositorio que
8
+ * guarda el canon (el orquestador en multirepo; el satélite no guarda copia) tiene
9
+ * doc/app/app_prd.md y está en su rama principal. Sin pedirla, el servidor responde como antes y la
10
+ * zona no gasta contexto (UC-12218). En FreeForm no se pide: la calcula este hook.
11
+ *
12
+ * PostToolUse: escribe en esa zona el cuerpo que devolvió el servidor (`app_docs_sync.roadmap_body`)
13
+ * y lo quita de la respuesta que ve el modelo. En FreeForm espera a que freeform-fragment haya
14
+ * fusionado items.json y calcula el mismo cuerpo con él (lib/roadmap.mjs).
15
+ *
16
+ * Solo en main o master: la zona sale del tablero, así que en una rama de trabajo se deja para el
17
+ * siguiente cambio en main y dos ramas no chocan al fusionar. Nunca bloquea.
14
18
  */
15
19
 
16
20
  import { execFileSync } from 'node:child_process';
17
21
  import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18
22
  import { isAbsolute, join, resolve } from 'node:path';
19
- import { parseToolName, withoutFields } from './lib/freeform-fragment.mjs';
23
+ import { parseToolName, pendingPath, withoutFields } from './lib/freeform-fragment.mjs';
20
24
  import { readHookInput } from './lib/utils.mjs';
21
25
  import { render, replaceZone, rowsFromItems } from './lib/roadmap.mjs';
22
26
  import { topObject } from './lib/uc-state.mjs';
23
27
 
24
28
  const TOOLS = new Set(['complete_uc', 'move_uc', 'add_uc', 'delete_uc', 'mark_ac_batch']);
25
29
  const DOC = join('doc', 'app', 'app_prd.md');
30
+ const MERGE_WAIT_MS = 4000;
26
31
 
27
- const { event, toolName, cwd, payload } = readHookInput();
32
+ const { event, toolName, toolInput, cwd, payload } = readHookInput();
28
33
  const parsed = parseToolName(toolName);
29
- if (event !== 'PostToolUse' || !parsed || !TOOLS.has(parsed.tool)) process.exit(0);
34
+ if (!parsed || !TOOLS.has(parsed.tool)) process.exit(0);
30
35
 
31
36
  const git = (dir, args) => {
32
37
  try {
@@ -44,47 +49,67 @@ const readJson = (path) => {
44
49
  };
45
50
 
46
51
  const root = git(cwd, ['rev-parse', '--show-toplevel']) || cwd;
47
- const response = payload.tool_response;
48
- const sync = topObject(response)?.app_docs_sync;
49
- if (!sync || sync.ok !== true || sync.zone !== 'roadmap') process.exit(0);
50
-
51
- // El repositorio que guarda el canon: el orquestador en un satélite multirepo.
52
52
  const settings = readJson(join(root, '.claude', 'settings.local.json')) || {};
53
53
  const projectConfig = readJson(join(root, '.claude', 'project-config.json')) || {};
54
+ const backendType = projectConfig.backend_type || settings.backend_type || settings.specbox?.backend_type || '';
55
+ const freeform = backendType === 'freeform';
54
56
  const mr = settings.multirepo || projectConfig.multirepo;
55
57
  const canonRoot =
56
58
  mr?.enabled && mr?.role === 'satellite' && mr?.orchestrator
57
59
  ? isAbsolute(mr.orchestrator) ? mr.orchestrator : resolve(root, mr.orchestrator)
58
60
  : root;
59
61
  const docPath = join(canonRoot, DOC);
62
+ const wanted = () => existsSync(docPath) && ['main', 'master'].includes(git(canonRoot, ['branch', '--show-current']));
63
+
64
+ if (event === 'PreToolUse') {
65
+ // FreeForm: la zona la calcula el hook; además, freeform-fragment ya cambia la entrada.
66
+ if (!freeform && toolInput.with_roadmap !== true && wanted()) {
67
+ process.stdout.write(
68
+ JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput: { ...toolInput, with_roadmap: true } } }),
69
+ );
70
+ }
71
+ process.exit(0);
72
+ }
73
+ if (event !== 'PostToolUse') process.exit(0);
74
+
75
+ const response = payload.tool_response;
76
+ const top = topObject(response);
77
+ const sync = top?.app_docs_sync;
60
78
 
61
79
  const hide = () => {
62
- if (typeof sync.roadmap_body !== 'string') return;
80
+ if (typeof sync?.roadmap_body !== 'string') return;
63
81
  process.stdout.write(
64
82
  JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', updatedToolOutput: withoutFields(response, ['roadmap_body']) } }),
65
83
  );
66
84
  };
67
85
 
68
- try {
69
- const branch = git(canonRoot, ['branch', '--show-current']);
70
- if (!existsSync(docPath) || !['main', 'master'].includes(branch)) {
71
- hide();
72
- process.exit(0);
86
+ /** FreeForm: espera a que freeform-fragment fusione lo que cambió la tool en items.json. */
87
+ function waitForMerge() {
88
+ if (!payload.tool_use_id) return;
89
+ const pending = pendingPath(join(root, '.quality', 'freeform-fragments'), payload.tool_use_id);
90
+ const until = Date.now() + MERGE_WAIT_MS;
91
+ while (existsSync(pending) && Date.now() < until) {
92
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
73
93
  }
74
- let body = typeof sync.roadmap_body === 'string' ? sync.roadmap_body : null;
75
- if (body == null && sync.render === 'client') {
76
- const tracking = settings.specbox?.freeform_root_absolute;
77
- const itemsPath = join(typeof tracking === 'string' && isAbsolute(tracking) ? tracking : join(root, 'doc', 'tracking'), 'items.json');
78
- const items = readJson(itemsPath);
79
- if (Array.isArray(items)) body = render(rowsFromItems(items));
80
- }
81
- if (body != null) {
82
- const current = readFileSync(docPath, 'utf-8');
83
- const next = replaceZone(current, 'roadmap', body);
84
- if (next != null && next !== current) {
85
- const tmp = `${docPath}.${process.pid}.tmp`;
86
- writeFileSync(tmp, next, 'utf-8');
87
- renameSync(tmp, docPath);
94
+ }
95
+
96
+ try {
97
+ if (top && !top.error && top.success !== false && wanted()) {
98
+ let body = sync?.ok === true && typeof sync.roadmap_body === 'string' ? sync.roadmap_body : null;
99
+ if (body == null && freeform) {
100
+ waitForMerge();
101
+ const tracking = settings.specbox?.freeform_root_absolute;
102
+ const items = readJson(join(typeof tracking === 'string' && isAbsolute(tracking) ? tracking : join(root, 'doc', 'tracking'), 'items.json'));
103
+ if (Array.isArray(items)) body = render(rowsFromItems(items));
104
+ }
105
+ if (body != null) {
106
+ const current = readFileSync(docPath, 'utf-8');
107
+ const next = replaceZone(current, 'roadmap', body);
108
+ if (next != null && next !== current) {
109
+ const tmp = `${docPath}.${process.pid}.tmp`;
110
+ writeFileSync(tmp, next, 'utf-8');
111
+ renameSync(tmp, docPath);
112
+ }
88
113
  }
89
114
  }
90
115
  } catch {
@@ -1,42 +1,43 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * context-budget-guard.mjs — PreToolUse hook for subagent launches (v5.32.0, UC-12208).
3
+ * context-budget-guard.mjs — PreToolUse hook for subagent launches (v5.32.0, UC-12208, UC-12210).
4
4
  *
5
- * Estimates tokens for the prompt of a subagent spawned by /implement
6
- * (or any other skill that delegates to a sub-agent) and reports
7
- * a note (default) or BLOCKS (strict mode) when the budget is exceeded.
5
+ * Estimates the tokens of the prompt of a subagent (/implement or any skill that delegates) and,
6
+ * when it exceeds the budget, notes it («warn», the default) or does not launch it («block»).
8
7
  *
9
- * Claude Code launches subagents with the «Agent» tool; older versions called
10
- * it «Task». The hook is registered with the matcher «Agent|Task» and accepts
11
- * both (until UC-12208 it only listened to «Task» and never ran).
8
+ * Claude Code launches subagents with the «Agent» tool; older versions called it «Task». The hook is
9
+ * registered with the matcher «Agent|Task» and accepts both (until UC-12208 it only listened to
10
+ * «Task» and never ran).
12
11
  *
13
- * Behaviour:
14
- * - mode=warn (default) → note to the agent (additionalContext), exit 0
15
- * - mode=strict → stderr BLOCKED, exit 2
16
- * - mode=off → no-op, exit 0
17
- *
18
- * Settings — `task_isolation.task_budget_tokens` (default 16000) and
19
- * `task_isolation.task_budget_mode` (default "warn"), read per key from:
20
- * 1. .claude/settings.local.json → specbox.implement.task_isolation (wins)
21
- * 2. .claude/settings.json → implement.task_isolation (where the
22
- * settings template writes it) or specbox.implement.task_isolation
12
+ * Mode (UC-12210) — the EP-20 measure `context_budget`:
13
+ * 1. `task_isolation.task_budget_mode` in .claude/settings.local.json (specbox.implement…) wins;
14
+ * 2. then in .claude/settings.json (implement…), unless it is the template's «warn», which is not
15
+ * a decision of the project;
16
+ * 3. otherwise the board's policy (lib/enforcement-policy.mjs), «warn» unless a person changed it.
17
+ * Values: off | warn | block (`strict`, the old name, means block).
18
+ * Budget: `task_isolation.task_budget_tokens` (default 16000), read the same way.
23
19
  *
24
20
  * Side-effects:
25
- * Updates .quality/task_isolation.json counters, plus `last_tool_name`
26
- * (the tool name the hook received), for local inspection and external
27
- * consumers (specbox_cloud, ad-hoc scripts).
21
+ * - every launch → one line in .quality/logs/context-budget.jsonl (tokens, budget, mode, outcome);
22
+ * - .quality/task_isolation.json counters and `last_tool_name`;
23
+ * - native: a block, and the next launch of that UC within budget, are recorded on the board
24
+ * (record_enforcement_event), so the impact report counts blocks and corrections (UC-12213);
25
+ * FreeForm: the same in doc/tracking/enforcement_events.jsonl.
28
26
  */
29
27
 
30
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
28
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
31
29
  import { dirname } from 'node:path';
32
30
  import { estimatePromptTokens } from './lib/token-counter.mjs';
33
31
  import { noteWith } from './lib/output.mjs';
32
+ import { getProjectConfig } from './lib/config.mjs';
33
+ import { leerPolitica, modoDe, textoDeMedida } from './lib/enforcement-policy.mjs';
34
+ import { recordCorrectionIfBlocked, recordEnforcementEvent } from './lib/enforcement-events.mjs';
34
35
 
35
36
  const DEFAULT_BUDGET = 16000;
36
- const DEFAULT_MODE = 'warn';
37
- // Local first: a key written in settings.local.json wins over settings.json.
38
- const SETTINGS_FILES = ['.claude/settings.local.json', '.claude/settings.json'];
37
+ const TEMPLATE_MODE = 'warn';
38
+ const MEASURE = 'context_budget';
39
39
  const TASK_ISOLATION_CACHE = '.quality/task_isolation.json';
40
+ const LOG = '.quality/logs/context-budget.jsonl';
40
41
  // The names Claude Code uses to launch a subagent: «Agent» today, «Task» before.
41
42
  const SUBAGENT_TOOLS = new Set(['Agent', 'Task']);
42
43
 
@@ -51,9 +52,13 @@ if (!SUBAGENT_TOOLS.has(toolName)) {
51
52
  process.exit(0);
52
53
  }
53
54
 
54
- // ── Resolve settings ───────────────────────────────────────────────────
55
+ // ── Resolve budget and mode ────────────────────────────────────────────
55
56
 
56
- const { budget, mode } = readSettings();
57
+ const local = taskIsolationOf(readJson('.claude/settings.local.json'));
58
+ const shared = taskIsolationOf(readJson('.claude/settings.json'));
59
+ const budget = [local?.task_budget_tokens, shared?.task_budget_tokens].find((v) => typeof v === 'number') ?? DEFAULT_BUDGET;
60
+ const config = getProjectConfig();
61
+ const { mode, source } = await resolveMode();
57
62
  if (mode === 'off') {
58
63
  process.exit(0);
59
64
  }
@@ -61,10 +66,12 @@ if (mode === 'off') {
61
66
  // ── Estimate ──────────────────────────────────────────────────────────
62
67
 
63
68
  const { total, breakdown } = estimatePromptTokens(payload);
69
+ const activeUc = readJson('.quality/active_uc.json')?.uc_id || '';
64
70
 
65
71
  if (total <= budget) {
66
- // Under budget → bump tasks_run_total counter and pass through.
67
72
  bumpCounter('tasks_run_total');
73
+ log('under');
74
+ await recordCorrectionIfBlocked({ config, measure: MEASURE, ucId: activeUc, by: 'context-budget-guard' });
68
75
  process.exit(0);
69
76
  }
70
77
 
@@ -76,22 +83,29 @@ const breakdownStr = Object.entries(breakdown)
76
83
  .map(([k, v]) => `${k}=${v}`)
77
84
  .join(', ');
78
85
  const overshoot = total - budget;
86
+ const how =
87
+ 'Recorta el encargo, pasa el contexto común a .quality/evidence/{feature}/execution_context.json ' +
88
+ 'o divide el trabajo en varios subagentes.';
79
89
 
80
- if (mode === 'strict') {
90
+ if (mode === 'block') {
91
+ log('blocked');
92
+ await recordEnforcementEvent({ config, measure: MEASURE, ucId: activeUc, outcome: 'blocked', by: 'context-budget-guard' });
81
93
  console.error(
82
- `[context-budget-guard] BLOCKED — the subagent prompt (${toolName}) is ~${total} tokens ` +
83
- `(budget ${budget}, overshoot ${overshoot}). Breakdown: ${breakdownStr}. ` +
84
- `Reduce the prompt body, move shared context to ` +
85
- `.quality/evidence/{feature}/execution_context.json, or split the work ` +
86
- `into several subagents.`
94
+ textoDeMedida({
95
+ medida: MEASURE,
96
+ modo: 'block',
97
+ motivo: `el encargo del subagente (${toolName}) tiene ~${total} tokens y el presupuesto es ${budget} (${overshoot} de más). Reparto: ${breakdownStr}.`,
98
+ comoSeguir: `${how} El subagente no se ha lanzado.`,
99
+ }),
87
100
  );
88
101
  process.exit(2);
89
102
  }
90
103
 
91
104
  // warn: a note to the agent (US-93/UC-9302: stderr with exit 0 reaches nobody).
105
+ log('warned');
92
106
  noteWith('PreToolUse', '[context-budget-guard] El encargo del subagente se pasa de presupuesto', [
93
107
  `~${total} tokens (presupuesto ${budget}, ${overshoot} de más). Reparto: ${breakdownStr}.`,
94
- 'Recórtalo o pasa el contexto común a .quality/evidence/{feature}/execution_context.json. La tarea sigue.',
108
+ `${how} La tarea sigue (medida context_budget en «warn»).`,
95
109
  ]);
96
110
 
97
111
  // ── Helpers ───────────────────────────────────────────────────────────
@@ -104,22 +118,44 @@ function readStdinSync() {
104
118
  }
105
119
  }
106
120
 
121
+ function readJson(path) {
122
+ try {
123
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf-8')) : null;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
107
129
  function taskIsolationOf(settings) {
108
130
  return settings?.specbox?.implement?.task_isolation ?? settings?.implement?.task_isolation ?? null;
109
131
  }
110
132
 
111
- function readSettings() {
112
- let budget;
113
- let mode;
114
- for (const file of SETTINGS_FILES) {
115
- if (!existsSync(file)) continue;
116
- try {
117
- const ti = taskIsolationOf(JSON.parse(readFileSync(file, 'utf-8')));
118
- if (budget === undefined && typeof ti?.task_budget_tokens === 'number') budget = ti.task_budget_tokens;
119
- if (mode === undefined && typeof ti?.task_budget_mode === 'string') mode = ti.task_budget_mode;
120
- } catch { /* ignore an unreadable file */ }
121
- }
122
- return { budget: budget ?? DEFAULT_BUDGET, mode: mode ?? DEFAULT_MODE };
133
+ function normal(m) {
134
+ return m === 'strict' ? 'block' : ['off', 'warn', 'block'].includes(m) ? m : null;
135
+ }
136
+
137
+ /** The mode and where it comes from: local setting, the project's setting, or the board's policy. */
138
+ async function resolveMode() {
139
+ const fromLocal = normal(local?.task_budget_mode);
140
+ if (fromLocal) return { mode: fromLocal, source: 'settings.local.json' };
141
+ const fromShared = normal(shared?.task_budget_mode);
142
+ if (fromShared && fromShared !== TEMPLATE_MODE) return { mode: fromShared, source: 'settings.json' };
143
+ const politica = await leerPolitica({
144
+ root: process.cwd(),
145
+ backendType: config.backendType,
146
+ boardId: config.boardId,
147
+ trackingDir: config.freeformRoot,
148
+ });
149
+ return { mode: modoDe(politica, MEASURE), source: `política (${politica.fuente})` };
150
+ }
151
+
152
+ function log(outcome) {
153
+ try {
154
+ mkdirSync(dirname(LOG), { recursive: true });
155
+ const line = { at: new Date().toISOString(), tool: toolName, tokens: total, budget, mode, source, outcome };
156
+ if (activeUc) line.uc_id = activeUc;
157
+ appendFileSync(LOG, `${JSON.stringify(line)}\n`);
158
+ } catch { /* best-effort */ }
123
159
  }
124
160
 
125
161
  function bumpCounter(key) {
@@ -186,14 +186,12 @@ function pre() {
186
186
  );
187
187
  return result;
188
188
  });
189
- process.stdout.write(
190
- JSON.stringify({
191
- hookSpecificOutput: {
192
- hookEventName: 'PreToolUse',
193
- updatedInput: { ...toolInput, items_content: built.itemsContent },
194
- },
195
- }),
196
- );
189
+ 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)) {
192
+ updatedInput.policy_content = readFileSync(policyPath, 'utf-8');
193
+ }
194
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } }));
197
195
  }
198
196
 
199
197
  function post() {
@@ -18,7 +18,8 @@
18
18
  "context-budget-guard.mjs": [
19
19
  "9714985624215ca43f78536b47254dde8f49bb56396a8c4c40740c5fb36a69dd",
20
20
  "a25ec6ccd8c290a8b7e2d2f7c282a57ba5a16aebbe0ce19b3981da3cba803479",
21
- "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3"
21
+ "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3",
22
+ "fa058d626a550d0bc5c72a09ecdc5f38bd213cf46a6f6514492f6defaa5e9ba8"
22
23
  ],
23
24
  "design-gate.mjs": [
24
25
  "82958af64ecbdba19dda1de39c5ebdf7cef5a4489a2269d503628297403af4f7",
@@ -175,7 +176,8 @@
175
176
  ],
176
177
  "freeform-fragment.mjs": [
177
178
  "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
178
- "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4"
179
+ "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
180
+ "c212b004d384feba728e0ee7e955bfb09fafe39112cad7c530620a1e932d169a"
179
181
  ],
180
182
  "lib/freeform-fragment.mjs": [
181
183
  "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
@@ -190,7 +192,8 @@
190
192
  "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a"
191
193
  ],
192
194
  "app-docs-fragment.mjs": [
193
- "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8"
195
+ "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8",
196
+ "4efae124b02c12f87513e48ca6d4f2e96065c05ca6d8c74352592a8edb21695a"
194
197
  ],
195
198
  "lib/reservation-probe.mjs": [
196
199
  "44566d2a92eb145a4a7252cfca8081e2101dc101bbc13faa77da8fa35b06dff0"
@@ -203,5 +206,16 @@
203
206
  ],
204
207
  "uc-state-marker.mjs": [
205
208
  "7c649407416f3837196c9cf8a0caf44b8aeead7e2da9eda55ee5526972630cb2"
209
+ ],
210
+ "lib/enforcement-events.mjs": [
211
+ "5fe963aab5f24c2b50c9991f11dbda48440a98f7394e02c823a276ee1bb2d608"
212
+ ],
213
+ "lib/prd-locate.mjs": [
214
+ "e8456176706e8d70a64f75c5209873881d8f50ac2f8a993ea013b8a5b44cc7aa",
215
+ "d4d7328f92436663cfaf913a76f1a0f8930475680d50f97a235e77d208afc7ec"
216
+ ],
217
+ "prd-sync-guard.mjs": [
218
+ "0a163f99dd8e03d57ff027de2c7f1dd614811caaf63aae6cae1d2989834244c8",
219
+ "959790ef27c79fc4b1603a53ca0f222dc4276aec91ca096c25a34e21cb1b4e96"
206
220
  ]
207
221
  }
@@ -1,18 +1,18 @@
1
1
  {
2
- "version": "6.37.0",
2
+ "version": "6.38.1",
3
3
  "files": {
4
- "app-docs-fragment.mjs": "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8",
4
+ "app-docs-fragment.mjs": "4efae124b02c12f87513e48ca6d4f2e96065c05ca6d8c74352592a8edb21695a",
5
5
  "app-docs-sync-guard.mjs": "71f09545b57c143b013c2e532366bfdd1e1a2ae49c7644c9e12e2ab5324d03d3",
6
6
  "branch-guard.mjs": "2185062de5f8672236a957a1ee4e7a6057c656a105bf886685f9e7bf8025c215",
7
7
  "checkpoint-freshness-guard.mjs": "b8b6f438b6943568682776177bdac6b778df4c464e3317eb2385ed2b1b6afa96",
8
8
  "commit-spec-guard.mjs": "08564e245b86f0e2db189da296db5c54add735bef6930591069cb7699be118c0",
9
- "context-budget-guard.mjs": "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3",
9
+ "context-budget-guard.mjs": "fa058d626a550d0bc5c72a09ecdc5f38bd213cf46a6f6514492f6defaa5e9ba8",
10
10
  "design-gate.mjs": "fef11c431c2f70218a3eca97c255c10585de0dbcfef1d4ec26fad0d4702a8dbb",
11
11
  "design-review-gate.mjs": "b2cc1ba81578102fdab4e559f8f4e8a0c37be41df75ef7ef4f531d766c1362d0",
12
12
  "design-system-gate.mjs": "419018cadb3e0a4fe0def1c423fed7013b76b2f121312acadbc99fc8e30b8ff5",
13
13
  "e2e-gate.mjs": "02e239816cb429f76034088a5370f63a08facce01b4ffd52b338a66acf13028d",
14
14
  "file-ownership-guard.mjs": "d8a84370766966cce70b76811de9dd150d170a79c4cb7b9e6b120cfad86a6932",
15
- "freeform-fragment.mjs": "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
15
+ "freeform-fragment.mjs": "c212b004d384feba728e0ee7e955bfb09fafe39112cad7c530620a1e932d169a",
16
16
  "freeform-path-guard.mjs": "9ded19e96b0738de5aaf43a97eaa1d88ecd3b341efd432c0b32eb312c4bf5e0a",
17
17
  "healing-budget-guard.mjs": "c49c6c34f99545e4009ad88ed9f7eef737e35ce39c11a05d41ad8f976ffae09f",
18
18
  "implement-checkpoint.mjs": "f3f219779a1ac4108bc3aabcc7311e9135d9c7795c126a2b5d659e743f5a5a64",
@@ -21,6 +21,7 @@
21
21
  "on-session-end.mjs": "fd5b7cf3bf2c419fd4125e21b338c4c849a4daaef21d5e15253caed54965b40c",
22
22
  "pipeline-phase-guard.mjs": "761b82c8b0c4884eba54d529e1f726d547003a6efe05425b45a1a0b77b90fe0d",
23
23
  "post-implement-validate.mjs": "25e5ea280c945f707ca8476555fca7a44c93aec1018eef06702c908a071df0cd",
24
+ "prd-sync-guard.mjs": "959790ef27c79fc4b1603a53ca0f222dc4276aec91ca096c25a34e21cb1b4e96",
24
25
  "pre-commit-lint.mjs": "348adbbfd29e52ebc6512a46b19f5e3c8bde4ae2139c013b96659fdc66456eab",
25
26
  "pre-prd-discovery-check.mjs": "2eda49648e31dd8720f70b3dcfca2782df9e950b6628ce0db8948c448253c2be",
26
27
  "pre-read-budget-guard.mjs": "76aeb98026f7fde19bb4d57749ff59b08cdfff0ba6f7188cafc28762773bed34",
@@ -37,6 +38,7 @@
37
38
  "lib/config.mjs": "a4458d02037cbba952a8f2240549859195788307c95b434e6fd9faa1a1591b85",
38
39
  "lib/decisiones.mjs": "6bed3bd37320b6d87f4c77fcac27ed55a6b37776d84a0d4eb2d9cab0c474a520",
39
40
  "lib/design-gaps.mjs": "d356d695d7afbafdc6fc420ed66603f11aa523be245bbd7a717d141a4a00701e",
41
+ "lib/enforcement-events.mjs": "5fe963aab5f24c2b50c9991f11dbda48440a98f7394e02c823a276ee1bb2d608",
40
42
  "lib/enforcement-policy.mjs": "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a",
41
43
  "lib/execution-context.mjs": "953eb7ec86f6893288df4e76c9c63c737c8e8ba4e337271402ce5eaca00330fa",
42
44
  "lib/freeform-fragment.mjs": "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
@@ -49,6 +51,7 @@
49
51
  "lib/native-reservation-revalidate.mjs": "1b394e8eb5d01480b71ac0976d636814483891e9f862edd5ac0216ac0128b023",
50
52
  "lib/output.mjs": "a568c736917720349b2b2527eb5b480bb11059a9253f81473f5b5c2c164b04bc",
51
53
  "lib/ownership-map.mjs": "21946608331a39e8c76eb2ba3860b5ebb351aa154f31801e768703bc4ae66b9a",
54
+ "lib/prd-locate.mjs": "d4d7328f92436663cfaf913a76f1a0f8930475680d50f97a235e77d208afc7ec",
52
55
  "lib/reservation-probe.mjs": "44566d2a92eb145a4a7252cfca8081e2101dc101bbc13faa77da8fa35b06dff0",
53
56
  "lib/roadmap.mjs": "0ff30f9d5707c89b8b43406e76f4870a39dd4f787221c32310ef6f9040879d8a",
54
57
  "lib/token-counter.mjs": "ca637273dcf731c7a951f28b8307d13de06d311cf85741ef56c4e3df9eaa231e",
@@ -0,0 +1,74 @@
1
+ /**
2
+ * lib/enforcement-events.mjs — los bloqueos de las medidas que aplican los hooks quedan en el tablero (UC-12213).
3
+ *
4
+ * native: `record_enforcement_event` con la identidad del dispositivo (2,5 s); FreeForm: una línea en
5
+ * doc/tracking/enforcement_events.jsonl. Un `passed` tras un `blocked` de la misma medida y UC cuenta
6
+ * como corregido. Nunca lanza.
7
+ */
8
+
9
+ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import { dirname, isAbsolute, join } from 'node:path';
11
+ import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './heartbeat-send.mjs';
12
+ import { llamarTool } from './mcp-client.mjs';
13
+
14
+ const STATE = join('.quality', 'enforcement_blocked.json');
15
+
16
+ function readState(root) {
17
+ try {
18
+ return JSON.parse(readFileSync(join(root, STATE), 'utf-8')) || {};
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+
24
+ function writeState(root, state) {
25
+ try {
26
+ mkdirSync(dirname(join(root, STATE)), { recursive: true });
27
+ writeFileSync(join(root, STATE), JSON.stringify(state));
28
+ } catch { /* sin estado, la corrección no se registra */ }
29
+ }
30
+
31
+ /** Registra `blocked` o `passed` de `measure` en `ucId`. `config` = getProjectConfig(). */
32
+ export async function recordEnforcementEvent({ root = process.cwd(), config, measure, ucId, outcome, by, env = process.env }) {
33
+ if (!ucId || !config) return false;
34
+ const state = readState(root);
35
+ if (outcome === 'blocked') state[measure] = ucId;
36
+ else delete state[measure];
37
+ writeState(root, state);
38
+ const at = new Date().toISOString();
39
+ if (config.backendType === 'freeform') {
40
+ try {
41
+ const dir = config.freeformRoot && isAbsolute(config.freeformRoot) ? config.freeformRoot : join(root, 'doc', 'tracking');
42
+ mkdirSync(dir, { recursive: true });
43
+ appendFileSync(join(dir, 'enforcement_events.jsonl'), `${JSON.stringify({ measure, uc_id: ucId, outcome, at, by })}\n`);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+ if (config.backendType !== 'native' || !config.boardId || env.SPECBOX_ENFORCEMENT_POLICY === 'off') return false;
50
+ try {
51
+ const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
52
+ const cabeceras = await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url });
53
+ if (!cabeceras.Authorization) return false;
54
+ const r = await llamarTool({
55
+ url,
56
+ cabeceras,
57
+ nombre: 'record_enforcement_event',
58
+ args: { measure, uc_id: ucId, outcome, board_id: config.boardId },
59
+ topeMs: 2500,
60
+ });
61
+ return !!r?.success;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+
67
+ /** Si la última vez `measure` bloqueó `ucId`, ahora pasa: se registra la corrección. */
68
+ export async function recordCorrectionIfBlocked(args) {
69
+ const state = readState(args.root || process.cwd());
70
+ if (state[args.measure] && state[args.measure] === args.ucId) {
71
+ return recordEnforcementEvent({ ...args, outcome: 'passed' });
72
+ }
73
+ return false;
74
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * lib/prd-locate.mjs — dónde está el PRD de una UC (UC-12211, UC-12219).
3
+ *
4
+ * Mismo orden que `find_prd_path` de server/prd_writer.py (una prueba lo compara):
5
+ * 1. doc/prds/{feature}_prd.md o doc/prds/{feature}.md
6
+ * 2. doc/prds/{us normalizada}_prd.md (US-01 → us_01)
7
+ * 3. doc/prd/{feature}.md o la carpeta de la feature: doc/prd/{feature}/prd.md, PRD.md o
8
+ * {feature}_prd.md
9
+ * 4. el único PRD que define la historia (un encabezado o una línea «>» la nombra), o si no, el
10
+ * único que la nombra (prdCandidates)
11
+ * 5. el único fichero de doc/prds/
12
+ * Devuelve la ruta relativa a `root` con el nombre que tiene en disco (un disco que no distingue
13
+ * mayúsculas también «encuentra» PRD.md al pedir prd.md, y el hook la compara con los ficheros
14
+ * de la PR), o null.
15
+ */
16
+
17
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
18
+ import { basename, dirname, join } from 'node:path';
19
+
20
+ const isFile = (path) => {
21
+ try {
22
+ return statSync(path).isFile();
23
+ } catch {
24
+ return false;
25
+ }
26
+ };
27
+ /** Las entradas de `dir` tal como están en disco, ordenadas; [] si no existe. */
28
+ const names = (dir) => {
29
+ try {
30
+ return readdirSync(dir).sort();
31
+ } catch {
32
+ return [];
33
+ }
34
+ };
35
+ /** `rel` si existe un fichero con ese nombre exacto (mayúsculas incluidas). */
36
+ const exact = (root, rel) => {
37
+ const full = join(root, rel);
38
+ return names(dirname(full)).includes(basename(full)) && isFile(full) ? rel : null;
39
+ };
40
+
41
+ /** Todos los PRD del proyecto, en orden estable (rutas relativas, nombres como en disco). */
42
+ export function prdCandidates(root) {
43
+ const out = [];
44
+ const prdDir = join(root, 'doc', 'prd');
45
+ for (const folder of names(prdDir)) {
46
+ const inside = names(join(prdDir, folder));
47
+ for (const name of ['prd.md', 'PRD.md', `${folder}_prd.md`]) {
48
+ if (inside.includes(name) && isFile(join(prdDir, folder, name))) out.push(`doc/prd/${folder}/${name}`);
49
+ }
50
+ }
51
+ for (const [dir, rel] of [[prdDir, 'doc/prd'], [join(root, 'doc', 'prds'), 'doc/prds']]) {
52
+ for (const name of names(dir)) {
53
+ if (name.endsWith('.md') && isFile(join(dir, name))) out.push(`${rel}/${name}`);
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+
59
+ export function locatePrd({ root, feature = '', usId = '' } = {}) {
60
+ const first = (rels) => rels.map((rel) => exact(root, rel)).find(Boolean) ?? null;
61
+ if (feature) {
62
+ const found = first([`doc/prds/${feature}_prd.md`, `doc/prds/${feature}.md`]);
63
+ if (found) return found;
64
+ }
65
+ if (usId) {
66
+ const found = exact(root, `doc/prds/${usId.toLowerCase().replace(/-/g, '_')}_prd.md`);
67
+ if (found) return found;
68
+ }
69
+ if (feature) {
70
+ const found = first([
71
+ `doc/prd/${feature}.md`,
72
+ `doc/prd/${feature}/prd.md`,
73
+ `doc/prd/${feature}/PRD.md`,
74
+ `doc/prd/${feature}/${feature}_prd.md`,
75
+ ]);
76
+ if (found) return found;
77
+ }
78
+ if (usId) {
79
+ const word = new RegExp(`\\b${usId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
80
+ const texts = prdCandidates(root).map((rel) => {
81
+ try {
82
+ return [rel, readFileSync(join(root, rel), 'utf-8')];
83
+ } catch {
84
+ return [rel, ''];
85
+ }
86
+ });
87
+ // El que define la historia (un encabezado o una línea «>» la nombra) gana al que solo la cita.
88
+ const defining = texts.filter(([, text]) => text.split('\n').some((line) => /^\s*[#>]/.test(line) && word.test(line)));
89
+ if (defining.length === 1) return defining[0][0];
90
+ const named = texts.filter(([, text]) => word.test(text));
91
+ if (named.length === 1) return named[0][0];
92
+ }
93
+ const prds = names(join(root, 'doc', 'prds')).filter((n) => n.endsWith('.md') && isFile(join(root, 'doc', 'prds', n)));
94
+ if (prds.length === 1) return `doc/prds/${prds[0]}`;
95
+ return null;
96
+ }
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * prd-sync-guard.mjs — PreToolUse de `gh pr merge`: el PRD cambia en la misma PR que el código (UC-12211).
4
+ *
5
+ * La medida `spec_in_pr` de EP-20. Antes de fusionar la PR de la UC activa comprueba que:
6
+ * - la PR toca el PRD de su historia (lib/prd-locate.mjs, también en el orquestador si el
7
+ * proyecto es satélite), o
8
+ * - su descripción enlaza una PR del orquestador que lo toca, o
9
+ * - la UC está marcada «sin PRD» con un motivo (update_uc no_prd_reason; va en el marcador).
10
+ * Si no se cumple: en «warn» (por defecto) avisa y deja fusionar; en «block» detiene la fusión y dice
11
+ * el PRD esperado y cómo seguir. Una UC anterior a la regla no se detiene. El modo sale de la
12
+ * política del tablero (lib/enforcement-policy.mjs). Sin `gh` o sin respuesta, no detiene nada.
13
+ */
14
+
15
+ import { execFileSync } from 'node:child_process';
16
+ import { isAbsolute, join, relative, resolve } from 'node:path';
17
+ import { readHookInput, readJsonFile } from './lib/utils.mjs';
18
+ import { getProjectConfig } from './lib/config.mjs';
19
+ import { blockWith, noteWith } from './lib/output.mjs';
20
+ import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
21
+ import { recordCorrectionIfBlocked, recordEnforcementEvent } from './lib/enforcement-events.mjs';
22
+ import { locatePrd } from './lib/prd-locate.mjs';
23
+
24
+ const MEASURE = 'spec_in_pr';
25
+ const { toolInput, cwd } = readHookInput();
26
+ const command = String(toolInput.command || '');
27
+ const merge = /\bgh\s+pr\s+merge\b(.*)$/m.exec(command);
28
+ if (!merge) process.exit(0);
29
+
30
+ const run = (cmd, args, dir) => {
31
+ try {
32
+ return execFileSync(cmd, args, { cwd: dir, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).trim();
33
+ } catch {
34
+ return null;
35
+ }
36
+ };
37
+
38
+ const root = run('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], cwd) || cwd;
39
+ process.chdir(root);
40
+ const config = getProjectConfig();
41
+ if (!config.isSpecDriven) process.exit(0);
42
+ const marker = readJsonFile('.quality/active_uc.json');
43
+ if (!marker?.uc_id) process.exit(0);
44
+ if (Array.isArray(marker.predates_rule) && marker.predates_rule.includes(MEASURE)) process.exit(0);
45
+ if (typeof marker.no_prd_reason === 'string' && marker.no_prd_reason.trim()) process.exit(0);
46
+
47
+ const politica = await leerPolitica({ root, backendType: config.backendType, boardId: config.boardId, trackingDir: config.freeformRoot });
48
+ const mode = modoDe(politica, MEASURE);
49
+ if (mode === 'off') process.exit(0);
50
+
51
+ // El PRD esperado: en el orquestador si el proyecto es satélite.
52
+ const settings = readJsonFile('.claude/settings.local.json') || {};
53
+ const mr = settings.multirepo || readJsonFile('.claude/project-config.json')?.multirepo;
54
+ const satellite = mr?.enabled && mr?.role === 'satellite' && mr?.orchestrator;
55
+ const canonRoot = satellite ? (isAbsolute(mr.orchestrator) ? mr.orchestrator : resolve(root, mr.orchestrator)) : root;
56
+ const prd = locatePrd({ root: canonRoot, feature: marker.feature || '', usId: marker.us_id || '' });
57
+
58
+ // La PR que se va a fusionar: el argumento de `gh pr merge` (número, URL o rama) y su -R.
59
+ const tokens = merge[1].trim().split(/\s+/).filter(Boolean);
60
+ let selector = '';
61
+ let repoFlag = [];
62
+ for (let i = 0; i < tokens.length; i++) {
63
+ if (tokens[i] === '-R' || tokens[i] === '--repo') {
64
+ repoFlag = ['-R', tokens[i + 1] || ''];
65
+ i++;
66
+ } else if (!tokens[i].startsWith('-') && !selector && !/[;&|]/.test(tokens[i])) {
67
+ selector = tokens[i];
68
+ } else if (/[;&|]/.test(tokens[i])) {
69
+ break;
70
+ }
71
+ }
72
+ const view = (args) => {
73
+ const out = run('gh', ['pr', 'view', ...args, '--json', 'files,body'], root);
74
+ try {
75
+ return out ? JSON.parse(out) : null;
76
+ } catch {
77
+ return null;
78
+ }
79
+ };
80
+ const pr = view([...(selector ? [selector] : []), ...repoFlag]);
81
+ if (!pr) process.exit(0); // sin gh o sin respuesta: no se detiene nada
82
+
83
+ const touches = (files, rel) => Array.isArray(files) && files.some((f) => (f?.path || f) === rel);
84
+ let ok = false;
85
+ if (prd) {
86
+ const relToRepo = satellite ? null : prd;
87
+ if (relToRepo && touches(pr.files, relToRepo)) ok = true;
88
+ // Una PR del orquestador enlazada desde la descripción que toca el PRD.
89
+ if (!ok && satellite) {
90
+ const remote = run('git', ['-C', canonRoot, 'remote', 'get-url', 'origin'], canonRoot) || '';
91
+ const slug = /github\.com[:/]([^/]+\/[^/.]+?)(?:\.git)?$/.exec(remote)?.[1];
92
+ const links = slug ? [...String(pr.body || '').matchAll(new RegExp(`github\\.com/${slug.replace('/', '\\/')}/pull/(\\d+)`, 'g'))] : [];
93
+ for (const [, number] of links) {
94
+ const other = view([number, '-R', slug]);
95
+ if (other && touches(other.files, prd)) {
96
+ ok = true;
97
+ break;
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ if (ok) {
104
+ await recordCorrectionIfBlocked({ root, config, measure: MEASURE, ucId: marker.uc_id, by: 'prd-sync-guard' });
105
+ process.exit(0);
106
+ }
107
+
108
+ const where = prd
109
+ ? `${satellite ? `${relative(root, canonRoot) || '.'}/` : ''}${prd}`
110
+ : `un PRD de ${marker.us_id || 'la historia'} (doc/prd/<slug>/prd.md, PRD.md o <slug>_prd.md, doc/prd/<feature>.md o doc/prds/; con la historia en un encabezado o una línea «>»)`;
111
+ const reason = prd
112
+ ? `la PR de ${marker.uc_id} no cambia el PRD de su historia (${where})${satellite ? ' ni enlaza una PR del orquestador que lo cambie' : ''}.`
113
+ : `no se encontró ${where}.`;
114
+ const how = [
115
+ satellite
116
+ ? `Actualiza ${prd || 'el PRD'} en una PR del orquestador y enlázala en la descripción de esta PR.`
117
+ : `Actualiza ${prd || 'el PRD de la historia'} en esta misma PR (por ejemplo, su estado de implementación).`,
118
+ `Si la UC no tiene PRD, márcala: update_uc(board_id, "${marker.uc_id}", no_prd_reason="por qué").`,
119
+ ];
120
+
121
+ if (mode === 'block') {
122
+ await recordEnforcementEvent({ root, config, measure: MEASURE, ucId: marker.uc_id, outcome: 'blocked', by: 'prd-sync-guard' });
123
+ blockWith('SPEC GUARD: el PRD no cambia en la misma PR', [
124
+ `SpecBox detuvo la fusión por la medida ${MEASURE}. Motivo: ${reason}`,
125
+ ...how.map((h) => `Cómo seguir: ${h}`),
126
+ ]);
127
+ }
128
+ noteWith('PreToolUse', 'SPEC GUARD: el PRD no cambia en la misma PR (aviso)', [
129
+ `Medida ${MEASURE} en «warn»: la fusión sigue. Motivo: ${reason}`,
130
+ ...how,
131
+ ]);
@@ -138,6 +138,12 @@
138
138
  "command": "node .claude/hooks/commit-spec-guard.mjs",
139
139
  "timeout": 10
140
140
  },
141
+ {
142
+ "type": "command",
143
+ "if": "Bash(*gh pr merge*)",
144
+ "command": "node .claude/hooks/prd-sync-guard.mjs",
145
+ "timeout": 20
146
+ },
141
147
  {
142
148
  "type": "command",
143
149
  "if": "Bash(*git commit*)",
@@ -222,6 +228,11 @@
222
228
  "type": "command",
223
229
  "command": "node .claude/hooks/freeform-fragment.mjs",
224
230
  "timeout": 15
231
+ },
232
+ {
233
+ "type": "command",
234
+ "command": "node .claude/hooks/app-docs-fragment.mjs",
235
+ "timeout": 5
225
236
  }
226
237
  ]
227
238
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specbox",
3
- "version": "6.37.0",
3
+ "version": "6.38.1",
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": {