specbox 6.35.0 → 6.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * app-docs-fragment.mjs — PostToolUse: la zona «roadmap» de app_prd.md sigue al tablero (UC-12203).
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.
10
+ *
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.
14
+ */
15
+
16
+ import { execFileSync } from 'node:child_process';
17
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18
+ import { isAbsolute, join, resolve } from 'node:path';
19
+ import { parseToolName, withoutFields } from './lib/freeform-fragment.mjs';
20
+ import { readHookInput } from './lib/utils.mjs';
21
+ import { render, replaceZone, rowsFromItems } from './lib/roadmap.mjs';
22
+ import { topObject } from './lib/uc-state.mjs';
23
+
24
+ const TOOLS = new Set(['complete_uc', 'move_uc', 'add_uc', 'delete_uc', 'mark_ac_batch']);
25
+ const DOC = join('doc', 'app', 'app_prd.md');
26
+
27
+ const { event, toolName, cwd, payload } = readHookInput();
28
+ const parsed = parseToolName(toolName);
29
+ if (event !== 'PostToolUse' || !parsed || !TOOLS.has(parsed.tool)) process.exit(0);
30
+
31
+ const git = (dir, args) => {
32
+ try {
33
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
34
+ } catch {
35
+ return '';
36
+ }
37
+ };
38
+ const readJson = (path) => {
39
+ try {
40
+ return JSON.parse(readFileSync(path, 'utf-8'));
41
+ } catch {
42
+ return null;
43
+ }
44
+ };
45
+
46
+ 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
+ const settings = readJson(join(root, '.claude', 'settings.local.json')) || {};
53
+ const projectConfig = readJson(join(root, '.claude', 'project-config.json')) || {};
54
+ const mr = settings.multirepo || projectConfig.multirepo;
55
+ const canonRoot =
56
+ mr?.enabled && mr?.role === 'satellite' && mr?.orchestrator
57
+ ? isAbsolute(mr.orchestrator) ? mr.orchestrator : resolve(root, mr.orchestrator)
58
+ : root;
59
+ const docPath = join(canonRoot, DOC);
60
+
61
+ const hide = () => {
62
+ if (typeof sync.roadmap_body !== 'string') return;
63
+ process.stdout.write(
64
+ JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', updatedToolOutput: withoutFields(response, ['roadmap_body']) } }),
65
+ );
66
+ };
67
+
68
+ try {
69
+ const branch = git(canonRoot, ['branch', '--show-current']);
70
+ if (!existsSync(docPath) || !['main', 'master'].includes(branch)) {
71
+ hide();
72
+ process.exit(0);
73
+ }
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);
88
+ }
89
+ }
90
+ } catch {
91
+ // el canon es una ayuda: nunca la razón de que falle una tool
92
+ }
93
+ hide();
94
+ process.exit(0);
@@ -3,7 +3,12 @@
3
3
  * commit-spec-guard.mjs — PreToolUse hook for `git commit`
4
4
  *
5
5
  * BLOCKING (exit 2, before the commit exists):
6
- * 1. Commit on main/master in a spec-driven project.
6
+ * 1. Commit on main/master in a spec-driven project, with the EP-20 measure `commit_on_main`
7
+ * in «block» (UC-12215): a project recognized by its usual configuration (first-level keys)
8
+ * keeps the block it always had; one recognized for the first time by the `specbox` block of
9
+ * settings.local.json takes the board's mode, «warn» unless a person changed it. A mode a
10
+ * person set with set_enforcement_mode wins in both cases. In «warn» it is a note; in «off»,
11
+ * nothing.
7
12
  * NOTE to the agent (additionalContext, the commit goes ahead):
8
13
  * 2. No active UC.
9
14
  * 3. No checkpoint saved for the active feature.
@@ -19,6 +24,7 @@
19
24
  import { readHookInput, gitDirForCommand, git, fileExists, readJsonFile } from './lib/utils.mjs';
20
25
  import { getProjectConfig } from './lib/config.mjs';
21
26
  import { blockWith, noteWith } from './lib/output.mjs';
27
+ import { leerPolitica, modoDe } from './lib/enforcement-policy.mjs';
22
28
 
23
29
  const { toolInput, cwd } = readHookInput();
24
30
  const command = String(toolInput.command || '');
@@ -29,19 +35,32 @@ try {
29
35
  process.exit(0);
30
36
  }
31
37
 
32
- const { boardId, isSpecDriven } = getProjectConfig();
38
+ const { boardId, backendType, isSpecDriven, recognizedBy, freeformRoot } = getProjectConfig();
33
39
  if (!isSpecDriven) process.exit(0);
34
40
 
41
+ const notes = [];
35
42
  const branch = git('branch --show-current');
36
43
  if (branch === 'main' || branch === 'master') {
37
- blockWith(`COMMIT BLOQUEADO: no se hace commit en ${branch}`, [
38
- 'Es un proyecto spec-driven: el trabajo va en una rama de la UC, nunca en main ni en master.',
39
- 'Para seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo) y haz el commit ahí.',
40
- ]);
44
+ // UC-12215: el modo de commit_on_main. Lo que puso una persona manda; si no, los proyectos de
45
+ // siempre conservan el bloqueo y los reconocidos por primera vez toman el modo del tablero.
46
+ const politica = await leerPolitica({ root: process.cwd(), backendType, boardId, trackingDir: freeformRoot });
47
+ const puesto = politica.explicitas?.includes('commit_on_main');
48
+ const modo = puesto || recognizedBy !== 'legacy' ? modoDe(politica, 'commit_on_main') : 'block';
49
+ if (modo === 'block') {
50
+ blockWith(`COMMIT BLOQUEADO: no se hace commit en ${branch}`, [
51
+ 'Es un proyecto spec-driven: el trabajo va en una rama de la UC, nunca en main ni en master.',
52
+ 'Para seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo) y haz el commit ahí.',
53
+ ]);
54
+ }
55
+ if (modo === 'warn') {
56
+ notes.push(
57
+ `- Commit en ${branch}: en un proyecto spec-driven el trabajo va en una rama de la UC. La medida commit_on_main ` +
58
+ 'está en «warn», así que el commit se hace. Para que bloquee: set_enforcement_mode(measure="commit_on_main", mode="block").',
59
+ );
60
+ }
41
61
  }
42
62
 
43
- const notes = [];
44
- const activeUC = fileExists('.quality/active_uc.json') ? readJsonFile('.quality/active_uc.json') : null;
63
+ const activeUC =fileExists('.quality/active_uc.json') ? readJsonFile('.quality/active_uc.json') : null;
45
64
  if (!activeUC) {
46
65
  notes.push(`- No hay UC activa (board ${boardId}): llama a start_uc antes de implementar y a mark_ac_batch al terminar.`);
47
66
  } else if (activeUC.feature && !fileExists(`.quality/evidence/${activeUC.feature}/checkpoint.json`)) {
@@ -15,15 +15,28 @@
15
15
  * Never blocks a call: when it cannot act it stays silent and the call goes as
16
16
  * the model wrote it. A failed merge exits 2 with what was not saved; the
17
17
  * fragment stays in .quality/freeform-fragments/ for recovery.
18
+ *
19
+ * The EP-20 policy (UC-12212): the policy tools get doc/tracking/policy.json as
20
+ * `policy_content` (and the git author as `actor`); what set_enforcement_mode and
21
+ * skip_enforcement return is written back. A new board from setup_board writes
22
+ * the policy only when the project has none. UC-12213: set_enforcement_mode and
23
+ * get_enforcement_impact also get items.json (`board_content`) and the blocks
24
+ * (`events_content`); the `event_line` of skip_enforcement and
25
+ * record_enforcement_event is appended to doc/tracking/enforcement_events.jsonl.
18
26
  */
19
27
 
20
28
  import { execFileSync } from 'node:child_process';
21
- import { existsSync, readFileSync, unlinkSync } from 'node:fs';
22
- import { isAbsolute, join } from 'node:path';
29
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
30
+ import { dirname, isAbsolute, join } from 'node:path';
23
31
  import { isRemoteMcp } from './lib/freeform-path.mjs';
24
32
  import {
25
33
  CONTENT_TOOLS,
34
+ POLICY_BOARD_TOOLS,
35
+ POLICY_EVENT_TOOLS,
36
+ POLICY_TOOLS,
37
+ POLICY_WRITERS,
26
38
  buildItemsContent,
39
+ extractField,
27
40
  extractItemsContent,
28
41
  mergeFragment,
29
42
  parseToolName,
@@ -37,7 +50,8 @@ import { readHookInput } from './lib/utils.mjs';
37
50
 
38
51
  const { event, toolName, toolInput, cwd, payload } = readHookInput();
39
52
  const parsed = parseToolName(toolName);
40
- if (!parsed || !CONTENT_TOOLS.has(parsed.tool) || !payload.tool_use_id) process.exit(0);
53
+ const isPolicyTool = !!parsed && POLICY_TOOLS.has(parsed.tool);
54
+ if (!parsed || !(CONTENT_TOOLS.has(parsed.tool) || isPolicyTool) || !payload.tool_use_id) process.exit(0);
41
55
 
42
56
  const root = (() => {
43
57
  try {
@@ -57,13 +71,94 @@ const trackingDir =
57
71
  ? settings.freeform_root_absolute
58
72
  : join(root, 'doc', 'tracking');
59
73
  const itemsPath = join(trackingDir, 'items.json');
74
+ const policyPath = join(trackingDir, 'policy.json');
75
+ const eventsPath = join(trackingDir, 'enforcement_events.jsonl');
60
76
  const stateDir = join(root, '.quality', 'freeform-fragments');
61
77
  const pending = pendingPath(stateDir, payload.tool_use_id);
62
78
 
79
+ if (isPolicyTool) {
80
+ if (event === 'PreToolUse') prePolicy();
81
+ else if (event === 'PostToolUse') postPolicy();
82
+ process.exit(0);
83
+ }
63
84
  if (event === 'PreToolUse') pre();
64
85
  else if (event === 'PostToolUse') post();
65
86
  process.exit(0);
66
87
 
88
+ function gitAuthor() {
89
+ try {
90
+ return execFileSync('git', ['-C', root, 'config', 'user.name'], {
91
+ encoding: 'utf-8',
92
+ stdio: ['ignore', 'pipe', 'ignore'],
93
+ }).trim();
94
+ } catch {
95
+ return '';
96
+ }
97
+ }
98
+
99
+ function prePolicy() {
100
+ if (typeof toolInput.policy_content === 'string') return; // explicit content wins
101
+ const read = (path) => (existsSync(path) ? readFileSync(path, 'utf-8') : '');
102
+ const updatedInput = { ...toolInput, policy_content: read(policyPath) };
103
+ if (POLICY_BOARD_TOOLS.has(parsed.tool)) {
104
+ // UC-12213: the impact report needs the open UCs and the blocks of the last days.
105
+ if (typeof toolInput.board_content !== 'string') updatedInput.board_content = read(itemsPath) || '[]';
106
+ if (typeof toolInput.events_content !== 'string') updatedInput.events_content = read(eventsPath);
107
+ }
108
+ const author = gitAuthor();
109
+ if (author && !toolInput.actor) updatedInput.actor = author.slice(0, 80);
110
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', updatedInput } }));
111
+ }
112
+
113
+ function postPolicy() {
114
+ const response = payload.tool_response;
115
+ const notes = [];
116
+ try {
117
+ const line = POLICY_EVENT_TOOLS.has(parsed.tool) ? extractField(response, 'event_line') : null;
118
+ if (line != null) {
119
+ JSON.parse(line);
120
+ mkdirSync(dirname(eventsPath), { recursive: true });
121
+ appendFileSync(eventsPath, `${line}\n`, 'utf-8');
122
+ notes.push(`el registro en ${eventsPath.replace(`${root}/`, '')}`);
123
+ }
124
+ const content = POLICY_WRITERS.has(parsed.tool) ? extractField(response, 'policy_content') : null;
125
+ if (content != null) {
126
+ JSON.parse(content);
127
+ writeAtomic(policyPath, content.endsWith('\n') ? content : `${content}\n`);
128
+ notes.unshift(`la política en ${policyPath.replace(`${root}/`, '')}`);
129
+ }
130
+ } catch (err) {
131
+ process.stderr.write(
132
+ `SpecBox freeform-fragment: no se pudo guardar lo que devolvió ${parsed.tool} (${err.message}). ` +
133
+ 'Repite la llamada antes de seguir.\n',
134
+ );
135
+ process.exit(2);
136
+ }
137
+ const visible = ['policy_content', 'event_line'].some((k) => extractField(response, k) != null);
138
+ if (!visible && notes.length === 0) return; // a read without anything to hide, or an error
139
+ writeHidden(response, notes.length ? `SpecBox: guardado ${notes.join(' y ')}. No lo escribas a mano.` : null);
140
+ }
141
+
142
+ function writeHidden(response, note) {
143
+ const out = { hookEventName: 'PostToolUse', updatedToolOutput: withoutItemsContent(response) };
144
+ if (note) out.additionalContext = note;
145
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: out }));
146
+ }
147
+
148
+ /** setup_board of a new board: the policy with origin «new», only if the project has none. */
149
+ function savePolicyOfNewBoard(response) {
150
+ if (parsed.tool !== 'setup_board' || existsSync(policyPath)) return false;
151
+ const content = extractField(response, 'policy_content');
152
+ if (content == null) return false;
153
+ try {
154
+ JSON.parse(content);
155
+ writeAtomic(policyPath, content.endsWith('\n') ? content : `${content}\n`);
156
+ return true;
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
67
162
  function pre() {
68
163
  const raw = existsSync(itemsPath) ? readFileSync(itemsPath, 'utf-8') : '[]';
69
164
  const items = parseJson(raw);
@@ -121,6 +216,7 @@ function post() {
121
216
  unlinkSync(pending);
122
217
  return merged.length - local.length;
123
218
  });
219
+ const policySaved = savePolicyOfNewBoard(response);
124
220
  process.stdout.write(
125
221
  JSON.stringify({
126
222
  hookSpecificOutput: {
@@ -129,6 +225,7 @@ function post() {
129
225
  additionalContext:
130
226
  `SpecBox: el tablero ya está guardado en ${itemsPath.replace(`${root}/`, '')}` +
131
227
  (changes ? ` (${changes > 0 ? '+' : ''}${changes} elementos)` : '') +
228
+ (policySaved ? `, con su política en ${policyPath.replace(`${root}/`, '')}` : '') +
132
229
  '. No lo escribas a mano.',
133
230
  },
134
231
  }),
@@ -12,7 +12,8 @@
12
12
  ],
13
13
  "commit-spec-guard.mjs": [
14
14
  "0437bacef5d022512c37d3636bc4a9112b6bb0b13421ba35b3bb77a6eb82d900",
15
- "b8d79538f6627cb19a224399770a439b4e11cd70ee5c61673dfd6ed59a939395"
15
+ "b8d79538f6627cb19a224399770a439b4e11cd70ee5c61673dfd6ed59a939395",
16
+ "08564e245b86f0e2db189da296db5c54add735bef6930591069cb7699be118c0"
16
17
  ],
17
18
  "context-budget-guard.mjs": [
18
19
  "9714985624215ca43f78536b47254dde8f49bb56396a8c4c40740c5fb36a69dd",
@@ -57,7 +58,8 @@
57
58
  "317eabaed8dead40f3d55e642b7465a3ba4e884523e0ae7b933e197153fc6f95"
58
59
  ],
59
60
  "lib/config.mjs": [
60
- "bef622d06108aa64ec3c2d0edd1b1c82ad442476a1257b271c81838813ff1d57"
61
+ "bef622d06108aa64ec3c2d0edd1b1c82ad442476a1257b271c81838813ff1d57",
62
+ "a4458d02037cbba952a8f2240549859195788307c95b434e6fd9faa1a1591b85"
61
63
  ],
62
64
  "lib/design-gaps.mjs": [
63
65
  "d356d695d7afbafdc6fc420ed66603f11aa523be245bbd7a717d141a4a00701e"
@@ -140,7 +142,8 @@
140
142
  "spec-guard.mjs": [
141
143
  "8dccc74b4cf1986497c1db3b32ec52a5a842267e1ce3372b3d6fc10ba0c402e8",
142
144
  "3a0d19ecaf523d5bd220f1ba88902e43e56caa700f115a9d8b276e48b576a5da",
143
- "3524703693ef53fa3f4f9282b7bfc857ff89ce60212724526b1ed4a1fcd12563"
145
+ "3524703693ef53fa3f4f9282b7bfc857ff89ce60212724526b1ed4a1fcd12563",
146
+ "202257a18636597e7a9d1860d8ae160d7e51f9e8b5ccd539c3a5f49543bdbab7"
144
147
  ],
145
148
  "stripe-safety-guard.mjs": [
146
149
  "fd38c72e91c0e74ecb7dc8ccc0fa9a5f9aaa1ceeac583d13f342503f098f718a",
@@ -149,7 +152,8 @@
149
152
  "uc-lifecycle-guard.mjs": [
150
153
  "e5c31e58db639bd304faf244fd3c4ccecfc854beba2182ae6d940f52afc28808",
151
154
  "beca70f275b1974d6609ae47f9acdbc0842d3c21e01fe9852d3a7e536f501103",
152
- "2bedf19d5e36d13dff6d8cd95855ca2b5a7f47d662cc3a554c3e2f80ede199fd"
155
+ "2bedf19d5e36d13dff6d8cd95855ca2b5a7f47d662cc3a554c3e2f80ede199fd",
156
+ "606c4397200ffbc3b2c89c9af68c340692e6d48f6c792da1d6531b5215fb16e9"
153
157
  ],
154
158
  "design-review-gate.mjs": [
155
159
  "b2cc1ba81578102fdab4e559f8f4e8a0c37be41df75ef7ef4f531d766c1362d0"
@@ -170,13 +174,34 @@
170
174
  "6aece1e95c2ef4dcb7e0f7699f5d1e75537857b863b34be108ed0fe67112781a"
171
175
  ],
172
176
  "freeform-fragment.mjs": [
173
- "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061"
177
+ "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
178
+ "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4"
174
179
  ],
175
180
  "lib/freeform-fragment.mjs": [
176
181
  "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
177
- "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1"
182
+ "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1",
183
+ "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141"
178
184
  ],
179
185
  "lib/app-spec-zones.mjs": [
180
186
  "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174"
187
+ ],
188
+ "lib/enforcement-policy.mjs": [
189
+ "3fe25cc63c99d8afbc4dac8a34e142c44bd2d594efa89979993a97b8f48fe688",
190
+ "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a"
191
+ ],
192
+ "app-docs-fragment.mjs": [
193
+ "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8"
194
+ ],
195
+ "lib/reservation-probe.mjs": [
196
+ "44566d2a92eb145a4a7252cfca8081e2101dc101bbc13faa77da8fa35b06dff0"
197
+ ],
198
+ "lib/roadmap.mjs": [
199
+ "0ff30f9d5707c89b8b43406e76f4870a39dd4f787221c32310ef6f9040879d8a"
200
+ ],
201
+ "lib/uc-state.mjs": [
202
+ "699786c91e83ad5b35b42f0ef812728e951be28a12ae0c037d1790795adc9e90"
203
+ ],
204
+ "uc-state-marker.mjs": [
205
+ "7c649407416f3837196c9cf8a0caf44b8aeead7e2da9eda55ee5526972630cb2"
181
206
  ]
182
207
  }
@@ -1,17 +1,18 @@
1
1
  {
2
- "version": "6.35.0",
2
+ "version": "6.37.0",
3
3
  "files": {
4
+ "app-docs-fragment.mjs": "65b82476af664547e732ed0966b07f0126a1b85dbb7f71bfef29b7c04d1115c8",
4
5
  "app-docs-sync-guard.mjs": "71f09545b57c143b013c2e532366bfdd1e1a2ae49c7644c9e12e2ab5324d03d3",
5
6
  "branch-guard.mjs": "2185062de5f8672236a957a1ee4e7a6057c656a105bf886685f9e7bf8025c215",
6
7
  "checkpoint-freshness-guard.mjs": "b8b6f438b6943568682776177bdac6b778df4c464e3317eb2385ed2b1b6afa96",
7
- "commit-spec-guard.mjs": "b8d79538f6627cb19a224399770a439b4e11cd70ee5c61673dfd6ed59a939395",
8
+ "commit-spec-guard.mjs": "08564e245b86f0e2db189da296db5c54add735bef6930591069cb7699be118c0",
8
9
  "context-budget-guard.mjs": "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3",
9
10
  "design-gate.mjs": "fef11c431c2f70218a3eca97c255c10585de0dbcfef1d4ec26fad0d4702a8dbb",
10
11
  "design-review-gate.mjs": "b2cc1ba81578102fdab4e559f8f4e8a0c37be41df75ef7ef4f531d766c1362d0",
11
12
  "design-system-gate.mjs": "419018cadb3e0a4fe0def1c423fed7013b76b2f121312acadbc99fc8e30b8ff5",
12
13
  "e2e-gate.mjs": "02e239816cb429f76034088a5370f63a08facce01b4ffd52b338a66acf13028d",
13
14
  "file-ownership-guard.mjs": "d8a84370766966cce70b76811de9dd150d170a79c4cb7b9e6b120cfad86a6932",
14
- "freeform-fragment.mjs": "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
15
+ "freeform-fragment.mjs": "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
15
16
  "freeform-path-guard.mjs": "9ded19e96b0738de5aaf43a97eaa1d88ecd3b341efd432c0b32eb312c4bf5e0a",
16
17
  "healing-budget-guard.mjs": "c49c6c34f99545e4009ad88ed9f7eef737e35ce39c11a05d41ad8f976ffae09f",
17
18
  "implement-checkpoint.mjs": "f3f219779a1ac4108bc3aabcc7311e9135d9c7795c126a2b5d659e743f5a5a64",
@@ -27,16 +28,18 @@
27
28
  "read-tracker.mjs": "5a22248f9d39dcc5c71abb6e2c49b8d7be3860f399023ad59f3c50e92917c298",
28
29
  "session-heartbeat.mjs": "6aece1e95c2ef4dcb7e0f7699f5d1e75537857b863b34be108ed0fe67112781a",
29
30
  "session-start.mjs": "0f49298cec92141c9aa1748784080d0fd630643ab5827ae4313dab3036eee78c",
30
- "spec-guard.mjs": "3524703693ef53fa3f4f9282b7bfc857ff89ce60212724526b1ed4a1fcd12563",
31
+ "spec-guard.mjs": "202257a18636597e7a9d1860d8ae160d7e51f9e8b5ccd539c3a5f49543bdbab7",
31
32
  "stripe-safety-guard.mjs": "5d7c0a9524657fe47e6ec4ea0eeb055d238f133eeac488c145cb1d5ae88b96de",
32
- "uc-lifecycle-guard.mjs": "2bedf19d5e36d13dff6d8cd95855ca2b5a7f47d662cc3a554c3e2f80ede199fd",
33
+ "uc-lifecycle-guard.mjs": "606c4397200ffbc3b2c89c9af68c340692e6d48f6c792da1d6531b5215fb16e9",
34
+ "uc-state-marker.mjs": "7c649407416f3837196c9cf8a0caf44b8aeead7e2da9eda55ee5526972630cb2",
33
35
  "lib/app-spec-zones.mjs": "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174",
34
36
  "lib/autopilot.mjs": "317eabaed8dead40f3d55e642b7465a3ba4e884523e0ae7b933e197153fc6f95",
35
- "lib/config.mjs": "bef622d06108aa64ec3c2d0edd1b1c82ad442476a1257b271c81838813ff1d57",
37
+ "lib/config.mjs": "a4458d02037cbba952a8f2240549859195788307c95b434e6fd9faa1a1591b85",
36
38
  "lib/decisiones.mjs": "6bed3bd37320b6d87f4c77fcac27ed55a6b37776d84a0d4eb2d9cab0c474a520",
37
39
  "lib/design-gaps.mjs": "d356d695d7afbafdc6fc420ed66603f11aa523be245bbd7a717d141a4a00701e",
40
+ "lib/enforcement-policy.mjs": "eed32e2ed08206d6ed22e47a0f61fb9230198376b03fab0be7fe3f54b0c2478a",
38
41
  "lib/execution-context.mjs": "953eb7ec86f6893288df4e76c9c63c737c8e8ba4e337271402ce5eaca00330fa",
39
- "lib/freeform-fragment.mjs": "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1",
42
+ "lib/freeform-fragment.mjs": "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
40
43
  "lib/freeform-path.mjs": "9ea85781821ae911873d1dbd13d58811a6c88e50480d2b3b378725ce2872be0c",
41
44
  "lib/handoff-builder.mjs": "2f7ffd554484d9560f525ab2548c240bac65b23bbe6eb8907e64c66bd818e22d",
42
45
  "lib/heartbeat-send.mjs": "739d4fe4b573e99fffdad2252a75cb7dcf18526dda72f1db6cff25b16f76383a",
@@ -46,7 +49,10 @@
46
49
  "lib/native-reservation-revalidate.mjs": "1b394e8eb5d01480b71ac0976d636814483891e9f862edd5ac0216ac0128b023",
47
50
  "lib/output.mjs": "a568c736917720349b2b2527eb5b480bb11059a9253f81473f5b5c2c164b04bc",
48
51
  "lib/ownership-map.mjs": "21946608331a39e8c76eb2ba3860b5ebb351aa154f31801e768703bc4ae66b9a",
52
+ "lib/reservation-probe.mjs": "44566d2a92eb145a4a7252cfca8081e2101dc101bbc13faa77da8fa35b06dff0",
53
+ "lib/roadmap.mjs": "0ff30f9d5707c89b8b43406e76f4870a39dd4f787221c32310ef6f9040879d8a",
49
54
  "lib/token-counter.mjs": "ca637273dcf731c7a951f28b8307d13de06d311cf85741ef56c4e3df9eaa231e",
55
+ "lib/uc-state.mjs": "699786c91e83ad5b35b42f0ef812728e951be28a12ae0c037d1790795adc9e90",
50
56
  "lib/utils.mjs": "4c21939aac114a11a68e2519d5d99f7f0bf482f08af0dc9e51ac715cc93ddfa2"
51
57
  }
52
58
  }
@@ -7,17 +7,26 @@ import { readJsonFile, fileAge } from './utils.mjs';
7
7
 
8
8
  /**
9
9
  * Read project configuration from .claude/project-config.json and .claude/settings.local.json.
10
- * Returns { boardId, backendType, orchestratorRoot, isSpecDriven }.
10
+ * Returns { boardId, backendType, orchestratorRoot, isSpecDriven, recognizedBy, freeformRoot }.
11
11
  *
12
12
  * Multi-repo support (v5.20):
13
13
  * If the project declares multirepo.role = "satellite" with an orchestrator path,
14
14
  * orchestratorRoot resolves to that path. Otherwise defaults to '.' (current repo).
15
15
  * Hooks that need cross-repo paths (design-gate, e2e-gate) use orchestratorRoot.
16
+ *
17
+ * UC-12215: `onboard_project` and the VS Code extension write the backend inside the `specbox`
18
+ * block of settings.local.json (`specbox.backend_type`), which the hooks did not read: those
19
+ * projects were not spec-driven for spec-guard, commit-spec-guard and uc-lifecycle-guard.
20
+ * `recognizedBy` says how the project was recognized: 'legacy' (first-level keys, as always) or
21
+ * 'specbox' (only the `specbox` block). A hook that blocks uses it so that a project recognized for
22
+ * the first time starts in «warn» (the EP-20 coexistence rule, UC-12212), not blocked.
16
23
  */
17
24
  export function getProjectConfig() {
18
25
  let boardId = '';
19
26
  let backendType = '';
20
27
  let orchestratorRoot = '.';
28
+ let recognizedBy = '';
29
+ let freeformRoot = '';
21
30
 
22
31
  for (const configFile of ['.claude/project-config.json', '.claude/settings.local.json']) {
23
32
  const config = readJsonFile(configFile);
@@ -36,12 +45,26 @@ export function getProjectConfig() {
36
45
  orchestratorRoot = mr.orchestrator;
37
46
  }
38
47
  }
48
+ if (boardId || backendType) recognizedBy = 'legacy';
49
+
50
+ // UC-12215: the `specbox` block of settings.local.json (what onboard_project writes).
51
+ const specbox = readJsonFile('.claude/settings.local.json')?.specbox;
52
+ if (specbox && typeof specbox === 'object') {
53
+ if (!backendType && typeof specbox.backend_type === 'string') backendType = specbox.backend_type;
54
+ if (!boardId) {
55
+ boardId = specbox.board_id || specbox.trello_board_id || specbox.project_id || specbox.native_project_id || '';
56
+ }
57
+ if (typeof specbox.freeform_root_absolute === 'string') freeformRoot = specbox.freeform_root_absolute;
58
+ if (!recognizedBy && (boardId || backendType)) recognizedBy = 'specbox';
59
+ }
39
60
 
40
61
  return {
41
62
  boardId,
42
63
  backendType,
43
64
  orchestratorRoot,
44
65
  isSpecDriven: !!(boardId || backendType),
66
+ recognizedBy,
67
+ freeformRoot,
45
68
  };
46
69
  }
47
70
 
@@ -0,0 +1,153 @@
1
+ /**
2
+ * lib/enforcement-policy.mjs — el modo de cada medida de EP-20 visto desde los hooks (US-122 · UC-12212).
3
+ *
4
+ * Los hooks y el servidor leen el mismo modo del tablero:
5
+ *
6
+ * - FreeForm: doc/tracking/policy.json, el mismo fichero que el servidor recibe en `policy_content`
7
+ * (MCP remoto) o lee del disco (MCP local).
8
+ * - native: la tool `get_enforcement_policy` con la identidad del dispositivo; la respuesta se guarda
9
+ * en .quality/enforcement_policy.json durante 10 minutos. Sin red se usa la última copia y, sin
10
+ * copia, «warn».
11
+ * - Trello y Plane: «warn» como máximo, como en el servidor.
12
+ *
13
+ * Un tablero sin política es uno que ya existía: todo en «warn». El catálogo es el de
14
+ * server/coordination/enforcement.py; tests/test_enforcement.py comprueba que coinciden.
15
+ * Nunca lanza: una política que no se puede leer se trata como «warn».
16
+ */
17
+
18
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+ import { cabecerasDelDispositivo, URL_POR_DEFECTO } from './heartbeat-send.mjs';
21
+ import { llamarTool } from './mcp-client.mjs';
22
+
23
+ export const MODES = ['off', 'warn', 'block'];
24
+ export const CAPPED_BACKENDS = new Set(['trello', 'plane']);
25
+ export const CACHE_MS = 10 * 60 * 1000;
26
+ export const CACHE_FILE = join('.quality', 'enforcement_policy.json');
27
+
28
+ /** Clave → modo de un proyecto nuevo. Mismo orden y valores que MEASURES en el servidor. */
29
+ export const MEASURES = {
30
+ context_budget: 'warn',
31
+ spec_in_pr: 'warn',
32
+ spec_quality: 'warn',
33
+ pending_decisions: 'warn',
34
+ closing_evidence: 'warn',
35
+ independent_review: 'warn',
36
+ ac_approval: 'warn',
37
+ drift_gate: 'warn',
38
+ impact_radius: 'warn',
39
+ contract_first: 'warn',
40
+ commit_on_main: 'warn',
41
+ };
42
+
43
+ /** El modo de cada medida a partir de lo guardado (o null), como effective_policy del servidor. */
44
+ export function modosDe(raw, backendType) {
45
+ const origin = raw && (raw.origin === 'new' || raw.origin === 'existing') ? raw.origin : 'existing';
46
+ const guardadas = raw && typeof raw.measures === 'object' && raw.measures ? raw.measures : {};
47
+ const modos = {};
48
+ const explicitas = [];
49
+ for (const [clave, nuevo] of Object.entries(MEASURES)) {
50
+ const entrada = guardadas[clave];
51
+ const guardada = !!entrada && MODES.includes(entrada.mode);
52
+ let modo = guardada ? entrada.mode : origin === 'new' ? nuevo : 'warn';
53
+ if (CAPPED_BACKENDS.has(backendType) && modo === 'block') modo = 'warn';
54
+ modos[clave] = modo;
55
+ // UC-12215: la puso una persona (no es el valor por defecto del tablero).
56
+ if (guardada && entrada.source !== 'default') explicitas.push(clave);
57
+ }
58
+ return { origin, backendType, modos, explicitas };
59
+ }
60
+
61
+ /** El modo de una medida en una política leída con leerPolitica («warn» si no la conoce). */
62
+ export function modoDe(politica, medida) {
63
+ const modo = politica?.modos?.[medida];
64
+ return MODES.includes(modo) ? modo : 'warn';
65
+ }
66
+
67
+ function leerJson(ruta) {
68
+ try {
69
+ return JSON.parse(readFileSync(ruta, 'utf-8'));
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** La política native de la caché si es de este proyecto (y su edad), o null. */
76
+ function deLaCache(root, proyecto) {
77
+ const copia = leerJson(join(root, CACHE_FILE));
78
+ if (!copia || copia.project_id !== proyecto || typeof copia.fetched_at !== 'number') return null;
79
+ return copia;
80
+ }
81
+
82
+ /**
83
+ * La política del proyecto: { origin, backendType, modos, fuente }.
84
+ * `fuente` dice de dónde salió: policy.json, tablero, caché, caché antigua o por defecto.
85
+ */
86
+ export async function leerPolitica({
87
+ root = process.cwd(),
88
+ backendType = '',
89
+ boardId = '',
90
+ trackingDir = '',
91
+ env = process.env,
92
+ fetchImpl = fetch,
93
+ cabeceras,
94
+ ahora = Date.now(),
95
+ topeMs = 2500,
96
+ } = {}) {
97
+ if (CAPPED_BACKENDS.has(backendType)) return { ...modosDe(null, backendType), fuente: 'por defecto' };
98
+
99
+ if (backendType === 'freeform') {
100
+ const ruta = join(trackingDir || join(root, 'doc', 'tracking'), 'policy.json');
101
+ const raw = existsSync(ruta) ? leerJson(ruta) : null;
102
+ return { ...modosDe(raw, backendType), fuente: raw ? 'policy.json' : 'por defecto' };
103
+ }
104
+
105
+ if (backendType !== 'native' || !boardId) return { ...modosDe(null, backendType), fuente: 'por defecto' };
106
+
107
+ const copia = deLaCache(root, boardId);
108
+ if (copia && ahora - copia.fetched_at < CACHE_MS) return { ...modosDe(copia.policy, 'native'), fuente: 'caché' };
109
+
110
+ if (env.SPECBOX_ENFORCEMENT_POLICY !== 'off') {
111
+ try {
112
+ const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
113
+ const h = cabeceras ?? (await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url }));
114
+ if (h.Authorization) {
115
+ const r = await llamarTool({
116
+ url,
117
+ cabeceras: h,
118
+ nombre: 'get_enforcement_policy',
119
+ args: { board_id: boardId },
120
+ topeMs,
121
+ fetchImpl,
122
+ });
123
+ if (r?.success && r.policy) {
124
+ // Se guarda lo que el servidor considera guardado: origen y modo de cada medida.
125
+ const policy = {
126
+ origin: r.policy.origin,
127
+ measures: Object.fromEntries(
128
+ Object.entries(r.policy.measures || {}).map(([k, v]) => [k, { mode: v?.mode, source: v?.source }]),
129
+ ),
130
+ };
131
+ try {
132
+ const destino = join(root, CACHE_FILE);
133
+ mkdirSync(dirname(destino), { recursive: true });
134
+ writeFileSync(destino, `${JSON.stringify({ project_id: boardId, fetched_at: ahora, policy }, null, 2)}\n`);
135
+ } catch {
136
+ // sin caché la próxima vez se vuelve a preguntar
137
+ }
138
+ return { ...modosDe(policy, 'native'), fuente: 'tablero' };
139
+ }
140
+ }
141
+ } catch {
142
+ // sin red o con el tablero caído: la última copia o «warn»
143
+ }
144
+ }
145
+ if (copia) return { ...modosDe(copia.policy, 'native'), fuente: 'caché antigua' };
146
+ return { ...modosDe(null, 'native'), fuente: 'por defecto' };
147
+ }
148
+
149
+ /** El texto de un aviso o de un bloqueo de una medida: medida, motivo y cómo seguir (AC-06). */
150
+ export function textoDeMedida({ medida, modo, motivo, comoSeguir }) {
151
+ const que = modo === 'block' ? 'SpecBox detuvo la operación' : 'Aviso de SpecBox';
152
+ return `${que} por la medida ${medida}. Motivo: ${motivo} Cómo seguir: ${comoSeguir}`;
153
+ }