specbox 6.34.0 → 6.36.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.
@@ -1,24 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * context-budget-guard.mjs — PreToolUse hook for Task (v5.32.0).
3
+ * context-budget-guard.mjs — PreToolUse hook for subagent launches (v5.32.0, UC-12208).
4
4
  *
5
- * Estimates tokens for the prompt of a Task spawned by /implement
5
+ * Estimates tokens for the prompt of a subagent spawned by /implement
6
6
  * (or any other skill that delegates to a sub-agent) and reports
7
- * a WARNING (default) or BLOCKS (strict mode) when the budget is
8
- * exceeded.
7
+ * a note (default) or BLOCKS (strict mode) when the budget is exceeded.
8
+ *
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).
9
12
  *
10
13
  * Behaviour:
11
- * - mode=warn (default) → stderr WARNING, exit 0
14
+ * - mode=warn (default) → note to the agent (additionalContext), exit 0
12
15
  * - mode=strict → stderr BLOCKED, exit 2
13
16
  * - mode=off → no-op, exit 0
14
17
  *
15
- * Settings (from .claude/settings.local.json):
16
- * specbox.implement.task_isolation.task_budget_tokens (default 16000)
17
- * specbox.implement.task_isolation.task_budget_mode (default "warn")
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
18
23
  *
19
24
  * Side-effects:
20
- * Updates .quality/task_isolation.json counters for local inspection
21
- * and external consumers (specbox_cloud, ad-hoc scripts).
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).
22
28
  */
23
29
 
24
30
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
@@ -28,8 +34,11 @@ import { noteWith } from './lib/output.mjs';
28
34
 
29
35
  const DEFAULT_BUDGET = 16000;
30
36
  const DEFAULT_MODE = 'warn';
31
- const SETTINGS_PATH = '.claude/settings.local.json';
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'];
32
39
  const TASK_ISOLATION_CACHE = '.quality/task_isolation.json';
40
+ // The names Claude Code uses to launch a subagent: «Agent» today, «Task» before.
41
+ const SUBAGENT_TOOLS = new Set(['Agent', 'Task']);
33
42
 
34
43
  // ── Read stdin payload ─────────────────────────────────────────────────
35
44
 
@@ -38,7 +47,7 @@ let payload = {};
38
47
  try { payload = JSON.parse(raw); } catch { /* ignore */ }
39
48
 
40
49
  const toolName = payload?.tool_name || payload?.toolName || '';
41
- if (toolName !== 'Task') {
50
+ if (!SUBAGENT_TOOLS.has(toolName)) {
42
51
  process.exit(0);
43
52
  }
44
53
 
@@ -70,11 +79,11 @@ const overshoot = total - budget;
70
79
 
71
80
  if (mode === 'strict') {
72
81
  console.error(
73
- `[context-budget-guard] BLOCKED — Task prompt is ~${total} tokens ` +
82
+ `[context-budget-guard] BLOCKED — the subagent prompt (${toolName}) is ~${total} tokens ` +
74
83
  `(budget ${budget}, overshoot ${overshoot}). Breakdown: ${breakdownStr}. ` +
75
84
  `Reduce the prompt body, move shared context to ` +
76
85
  `.quality/evidence/{feature}/execution_context.json, or split the work ` +
77
- `into multiple Tasks.`
86
+ `into several subagents.`
78
87
  );
79
88
  process.exit(2);
80
89
  }
@@ -95,19 +104,22 @@ function readStdinSync() {
95
104
  }
96
105
  }
97
106
 
107
+ function taskIsolationOf(settings) {
108
+ return settings?.specbox?.implement?.task_isolation ?? settings?.implement?.task_isolation ?? null;
109
+ }
110
+
98
111
  function readSettings() {
99
- let budget = DEFAULT_BUDGET;
100
- let mode = DEFAULT_MODE;
101
- if (!existsSync(SETTINGS_PATH)) {
102
- return { budget, mode };
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 */ }
103
121
  }
104
- try {
105
- const settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8'));
106
- const ti = settings?.specbox?.implement?.task_isolation;
107
- if (typeof ti?.task_budget_tokens === 'number') budget = ti.task_budget_tokens;
108
- if (typeof ti?.task_budget_mode === 'string') mode = ti.task_budget_mode;
109
- } catch { /* ignore */ }
110
- return { budget, mode };
122
+ return { budget: budget ?? DEFAULT_BUDGET, mode: mode ?? DEFAULT_MODE };
111
123
  }
112
124
 
113
125
  function bumpCounter(key) {
@@ -119,6 +131,7 @@ function bumpCounter(key) {
119
131
  } catch { cache = {}; }
120
132
  }
121
133
  cache[key] = (cache[key] || 0) + 1;
134
+ cache.last_tool_name = toolName;
122
135
  cache.last_event_at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
123
136
  mkdirSync(dirname(TASK_ISOLATION_CACHE), { recursive: true });
124
137
  writeFileSync(
@@ -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
  }),
@@ -16,7 +16,8 @@
16
16
  ],
17
17
  "context-budget-guard.mjs": [
18
18
  "9714985624215ca43f78536b47254dde8f49bb56396a8c4c40740c5fb36a69dd",
19
- "a25ec6ccd8c290a8b7e2d2f7c282a57ba5a16aebbe0ce19b3981da3cba803479"
19
+ "a25ec6ccd8c290a8b7e2d2f7c282a57ba5a16aebbe0ce19b3981da3cba803479",
20
+ "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3"
20
21
  ],
21
22
  "design-gate.mjs": [
22
23
  "82958af64ecbdba19dda1de39c5ebdf7cef5a4489a2269d503628297403af4f7",
@@ -133,7 +134,8 @@
133
134
  ],
134
135
  "session-start.mjs": [
135
136
  "2203a5e07360c1c725807bb2b86fd516e68f19adca8533b26ac36e95afc4aea7",
136
- "0e141afe55e00591b2a09848be4930785947566f6688102fe02cfa9c8e5d0a85"
137
+ "0e141afe55e00591b2a09848be4930785947566f6688102fe02cfa9c8e5d0a85",
138
+ "0f49298cec92141c9aa1748784080d0fd630643ab5827ae4313dab3036eee78c"
137
139
  ],
138
140
  "spec-guard.mjs": [
139
141
  "8dccc74b4cf1986497c1db3b32ec52a5a842267e1ce3372b3d6fc10ba0c402e8",
@@ -168,9 +170,18 @@
168
170
  "6aece1e95c2ef4dcb7e0f7699f5d1e75537857b863b34be108ed0fe67112781a"
169
171
  ],
170
172
  "freeform-fragment.mjs": [
171
- "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061"
173
+ "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
174
+ "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4"
172
175
  ],
173
176
  "lib/freeform-fragment.mjs": [
174
- "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12"
177
+ "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
178
+ "344f1d55608ec6f39696e6c01a58b7a8f11428887445e153ee5e5d2085a209a1",
179
+ "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141"
180
+ ],
181
+ "lib/app-spec-zones.mjs": [
182
+ "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174"
183
+ ],
184
+ "lib/enforcement-policy.mjs": [
185
+ "3fe25cc63c99d8afbc4dac8a34e142c44bd2d594efa89979993a97b8f48fe688"
175
186
  ]
176
187
  }
@@ -1,17 +1,17 @@
1
1
  {
2
- "version": "6.34.0",
2
+ "version": "6.36.0",
3
3
  "files": {
4
4
  "app-docs-sync-guard.mjs": "71f09545b57c143b013c2e532366bfdd1e1a2ae49c7644c9e12e2ab5324d03d3",
5
5
  "branch-guard.mjs": "2185062de5f8672236a957a1ee4e7a6057c656a105bf886685f9e7bf8025c215",
6
6
  "checkpoint-freshness-guard.mjs": "b8b6f438b6943568682776177bdac6b778df4c464e3317eb2385ed2b1b6afa96",
7
7
  "commit-spec-guard.mjs": "b8d79538f6627cb19a224399770a439b4e11cd70ee5c61673dfd6ed59a939395",
8
- "context-budget-guard.mjs": "a25ec6ccd8c290a8b7e2d2f7c282a57ba5a16aebbe0ce19b3981da3cba803479",
8
+ "context-budget-guard.mjs": "9f6f489967ca0093266decdee0880dd1bf08eff8b8fb89d51ffc1d7b8f50cde3",
9
9
  "design-gate.mjs": "fef11c431c2f70218a3eca97c255c10585de0dbcfef1d4ec26fad0d4702a8dbb",
10
10
  "design-review-gate.mjs": "b2cc1ba81578102fdab4e559f8f4e8a0c37be41df75ef7ef4f531d766c1362d0",
11
11
  "design-system-gate.mjs": "419018cadb3e0a4fe0def1c423fed7013b76b2f121312acadbc99fc8e30b8ff5",
12
12
  "e2e-gate.mjs": "02e239816cb429f76034088a5370f63a08facce01b4ffd52b338a66acf13028d",
13
13
  "file-ownership-guard.mjs": "d8a84370766966cce70b76811de9dd150d170a79c4cb7b9e6b120cfad86a6932",
14
- "freeform-fragment.mjs": "fcb1fc9a1494c1c63870bdec08368bf3c815b1372e220a6311535b0431c86061",
14
+ "freeform-fragment.mjs": "c8c507e2bd1bfa11f681a70b0f236bbc0d23447140ee4424a25533669beb17b4",
15
15
  "freeform-path-guard.mjs": "9ded19e96b0738de5aaf43a97eaa1d88ecd3b341efd432c0b32eb312c4bf5e0a",
16
16
  "healing-budget-guard.mjs": "c49c6c34f99545e4009ad88ed9f7eef737e35ce39c11a05d41ad8f976ffae09f",
17
17
  "implement-checkpoint.mjs": "f3f219779a1ac4108bc3aabcc7311e9135d9c7795c126a2b5d659e743f5a5a64",
@@ -26,16 +26,18 @@
26
26
  "quality-first-guard.mjs": "93881ddbf47fdc2a75392815153f755d1c5f0345c6a97586777eaebd1699e62d",
27
27
  "read-tracker.mjs": "5a22248f9d39dcc5c71abb6e2c49b8d7be3860f399023ad59f3c50e92917c298",
28
28
  "session-heartbeat.mjs": "6aece1e95c2ef4dcb7e0f7699f5d1e75537857b863b34be108ed0fe67112781a",
29
- "session-start.mjs": "0e141afe55e00591b2a09848be4930785947566f6688102fe02cfa9c8e5d0a85",
29
+ "session-start.mjs": "0f49298cec92141c9aa1748784080d0fd630643ab5827ae4313dab3036eee78c",
30
30
  "spec-guard.mjs": "3524703693ef53fa3f4f9282b7bfc857ff89ce60212724526b1ed4a1fcd12563",
31
31
  "stripe-safety-guard.mjs": "5d7c0a9524657fe47e6ec4ea0eeb055d238f133eeac488c145cb1d5ae88b96de",
32
32
  "uc-lifecycle-guard.mjs": "2bedf19d5e36d13dff6d8cd95855ca2b5a7f47d662cc3a554c3e2f80ede199fd",
33
+ "lib/app-spec-zones.mjs": "b05b7d9fe747524c7157c8c67979951affa234d771d3bdd038c9b58cc315f174",
33
34
  "lib/autopilot.mjs": "317eabaed8dead40f3d55e642b7465a3ba4e884523e0ae7b933e197153fc6f95",
34
35
  "lib/config.mjs": "bef622d06108aa64ec3c2d0edd1b1c82ad442476a1257b271c81838813ff1d57",
35
36
  "lib/decisiones.mjs": "6bed3bd37320b6d87f4c77fcac27ed55a6b37776d84a0d4eb2d9cab0c474a520",
36
37
  "lib/design-gaps.mjs": "d356d695d7afbafdc6fc420ed66603f11aa523be245bbd7a717d141a4a00701e",
38
+ "lib/enforcement-policy.mjs": "3fe25cc63c99d8afbc4dac8a34e142c44bd2d594efa89979993a97b8f48fe688",
37
39
  "lib/execution-context.mjs": "953eb7ec86f6893288df4e76c9c63c737c8e8ba4e337271402ce5eaca00330fa",
38
- "lib/freeform-fragment.mjs": "d30a15b495cf18cad571e8582b4ce943a75aa4ad8efc5fa11e22420b505dad12",
40
+ "lib/freeform-fragment.mjs": "23be71af8423bf8fa48dc8519734ff2bef084523a33ece555e4f96bb52bc3141",
39
41
  "lib/freeform-path.mjs": "9ea85781821ae911873d1dbd13d58811a6c88e50480d2b3b378725ce2872be0c",
40
42
  "lib/handoff-builder.mjs": "2f7ffd554484d9560f525ab2548c240bac65b23bbe6eb8907e64c66bd818e22d",
41
43
  "lib/heartbeat-send.mjs": "739d4fe4b573e99fffdad2252a75cb7dcf18526dda72f1db6cff25b16f76383a",
@@ -0,0 +1,43 @@
1
+ /**
2
+ * app-spec-zones.mjs — lee las zonas automáticas de `doc/app/app_spec.md` (UC-12205).
3
+ *
4
+ * Un marcador de apertura lleva sus atributos en cualquier orden y puede traer otros
5
+ * además de `kind` e `id` (la plantilla añade `auto_sync_on`, las zonas híbridas `merge`):
6
+ *
7
+ * <!-- @specbox:zone start kind="auto" id="stack" auto_sync_on="lockfile_change" -->
8
+ * …
9
+ * <!-- @specbox:zone end -->
10
+ *
11
+ * Antes la expresión exigía el cierre `-->` justo después del id y no casaba con ninguna
12
+ * zona de la plantilla, así que el arranque de sesión nunca las inyectaba.
13
+ */
14
+
15
+ const ZONE_RE = /<!--\s*@specbox:zone start\b([\s\S]*?)-->([\s\S]*?)<!--\s*@specbox:zone end\s*-->/g;
16
+ const ATTR_RE = /([A-Za-z_][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
17
+
18
+ /** Zonas automáticas que el arranque de sesión inyecta, en este orden. */
19
+ export const SESSION_ZONES = ['stack', 'tracking_backend', 'autopilot'];
20
+
21
+ /** Atributos del marcador de apertura (`kind`, `id`, `auto_sync_on`…), en cualquier orden. */
22
+ export function zoneAttributes(raw) {
23
+ const attrs = {};
24
+ for (const m of String(raw ?? '').matchAll(ATTR_RE)) {
25
+ attrs[m[1]] = m[2] ?? m[3] ?? '';
26
+ }
27
+ return attrs;
28
+ }
29
+
30
+ /**
31
+ * Devuelve `{id: contenido}` de las zonas `kind="auto"` cuyo id está en `wanted`.
32
+ * Ignora las zonas manuales e híbridas y las que no se piden.
33
+ */
34
+ export function parseAutoZones(content, wanted = SESSION_ZONES) {
35
+ const zones = {};
36
+ if (typeof content !== 'string') return zones;
37
+ for (const m of content.matchAll(ZONE_RE)) {
38
+ const attrs = zoneAttributes(m[1]);
39
+ if (attrs.kind !== 'auto' || !wanted.includes(attrs.id)) continue;
40
+ zones[attrs.id] = m[2].trim();
41
+ }
42
+ return zones;
43
+ }
@@ -0,0 +1,148 @@
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
+ };
41
+
42
+ /** El modo de cada medida a partir de lo guardado (o null), como effective_policy del servidor. */
43
+ export function modosDe(raw, backendType) {
44
+ const origin = raw && (raw.origin === 'new' || raw.origin === 'existing') ? raw.origin : 'existing';
45
+ const guardadas = raw && typeof raw.measures === 'object' && raw.measures ? raw.measures : {};
46
+ const modos = {};
47
+ for (const [clave, nuevo] of Object.entries(MEASURES)) {
48
+ const entrada = guardadas[clave];
49
+ let modo = entrada && MODES.includes(entrada.mode) ? entrada.mode : origin === 'new' ? nuevo : 'warn';
50
+ if (CAPPED_BACKENDS.has(backendType) && modo === 'block') modo = 'warn';
51
+ modos[clave] = modo;
52
+ }
53
+ return { origin, backendType, modos };
54
+ }
55
+
56
+ /** El modo de una medida en una política leída con leerPolitica («warn» si no la conoce). */
57
+ export function modoDe(politica, medida) {
58
+ const modo = politica?.modos?.[medida];
59
+ return MODES.includes(modo) ? modo : 'warn';
60
+ }
61
+
62
+ function leerJson(ruta) {
63
+ try {
64
+ return JSON.parse(readFileSync(ruta, 'utf-8'));
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /** La política native de la caché si es de este proyecto (y su edad), o null. */
71
+ function deLaCache(root, proyecto) {
72
+ const copia = leerJson(join(root, CACHE_FILE));
73
+ if (!copia || copia.project_id !== proyecto || typeof copia.fetched_at !== 'number') return null;
74
+ return copia;
75
+ }
76
+
77
+ /**
78
+ * La política del proyecto: { origin, backendType, modos, fuente }.
79
+ * `fuente` dice de dónde salió: policy.json, tablero, caché, caché antigua o por defecto.
80
+ */
81
+ export async function leerPolitica({
82
+ root = process.cwd(),
83
+ backendType = '',
84
+ boardId = '',
85
+ trackingDir = '',
86
+ env = process.env,
87
+ fetchImpl = fetch,
88
+ cabeceras,
89
+ ahora = Date.now(),
90
+ topeMs = 2500,
91
+ } = {}) {
92
+ if (CAPPED_BACKENDS.has(backendType)) return { ...modosDe(null, backendType), fuente: 'por defecto' };
93
+
94
+ if (backendType === 'freeform') {
95
+ const ruta = join(trackingDir || join(root, 'doc', 'tracking'), 'policy.json');
96
+ const raw = existsSync(ruta) ? leerJson(ruta) : null;
97
+ return { ...modosDe(raw, backendType), fuente: raw ? 'policy.json' : 'por defecto' };
98
+ }
99
+
100
+ if (backendType !== 'native' || !boardId) return { ...modosDe(null, backendType), fuente: 'por defecto' };
101
+
102
+ const copia = deLaCache(root, boardId);
103
+ if (copia && ahora - copia.fetched_at < CACHE_MS) return { ...modosDe(copia.policy, 'native'), fuente: 'caché' };
104
+
105
+ if (env.SPECBOX_ENFORCEMENT_POLICY !== 'off') {
106
+ try {
107
+ const url = env.SPECBOX_MCP_URL || URL_POR_DEFECTO;
108
+ const h = cabeceras ?? (await cabecerasDelDispositivo({ ...env, CLAUDE_CODE_MCP_SERVER_URL: url }));
109
+ if (h.Authorization) {
110
+ const r = await llamarTool({
111
+ url,
112
+ cabeceras: h,
113
+ nombre: 'get_enforcement_policy',
114
+ args: { board_id: boardId },
115
+ topeMs,
116
+ fetchImpl,
117
+ });
118
+ if (r?.success && r.policy) {
119
+ // Se guarda lo que el servidor considera guardado: origen y modo de cada medida.
120
+ const policy = {
121
+ origin: r.policy.origin,
122
+ measures: Object.fromEntries(
123
+ Object.entries(r.policy.measures || {}).map(([k, v]) => [k, { mode: v?.mode }]),
124
+ ),
125
+ };
126
+ try {
127
+ const destino = join(root, CACHE_FILE);
128
+ mkdirSync(dirname(destino), { recursive: true });
129
+ writeFileSync(destino, `${JSON.stringify({ project_id: boardId, fetched_at: ahora, policy }, null, 2)}\n`);
130
+ } catch {
131
+ // sin caché la próxima vez se vuelve a preguntar
132
+ }
133
+ return { ...modosDe(policy, 'native'), fuente: 'tablero' };
134
+ }
135
+ }
136
+ } catch {
137
+ // sin red o con el tablero caído: la última copia o «warn»
138
+ }
139
+ }
140
+ if (copia) return { ...modosDe(copia.policy, 'native'), fuente: 'caché antigua' };
141
+ return { ...modosDe(null, 'native'), fuente: 'por defecto' };
142
+ }
143
+
144
+ /** El texto de un aviso o de un bloqueo de una medida: medida, motivo y cómo seguir (AC-06). */
145
+ export function textoDeMedida({ medida, modo, motivo, comoSeguir }) {
146
+ const que = modo === 'block' ? 'SpecBox detuvo la operación' : 'Aviso de SpecBox';
147
+ return `${que} por la medida ${medida}. Motivo: ${motivo} Cómo seguir: ${comoSeguir}`;
148
+ }
@@ -33,8 +33,9 @@ export const CONTENT_TOOLS = new Set([
33
33
  * What each tool needs. `uc`: the UC, its criteria and, as context, its story;
34
34
  * `uc+siblings`: also the story's other UCs as context (a story's state is
35
35
  * derived from all of them); `story`: the story, its UCs and their criteria;
36
- * `parent-story`: only the story, as context; `epics`: every epic; `spec`: what
37
- * an import_spec names. Any other tool gets the whole board, as before.
36
+ * `parent-story`: only the story, as context (add_uc also gets the ids of the story's
37
+ * UCs as skeletons, UC-12214); `epics`: every epic; `spec`: what an import_spec
38
+ * names. Any other tool gets the whole board, as before.
38
39
  */
39
40
  export const FRAGMENT_TOOLS = {
40
41
  add_uc: 'parent-story',
@@ -165,6 +166,17 @@ function safeJson(text) {
165
166
  }
166
167
  }
167
168
 
169
+ /**
170
+ * UC-12214: a UC that only has to say who it is (add_uc numbering): its id, its story and its
171
+ * parent. The merge compares what comes back with what was sent, so a skeleton the server leaves
172
+ * alone changes nothing in items.json.
173
+ */
174
+ export function asSkeleton(item) {
175
+ const meta = {};
176
+ for (const key of ['uc_id', 'us_id']) if (item.meta?.[key]) meta[key] = item.meta[key];
177
+ return { id: item.id, name: item.name, labels: item.labels, parent_id: item.parent_id ?? null, meta };
178
+ }
179
+
168
180
  /** A context item travels without what no fragment tool reads (description, long meta). */
169
181
  export function asContext(item) {
170
182
  const { description: _description, ...rest } = item;
@@ -183,16 +195,75 @@ export function asContext(item) {
183
195
  export function buildItemsContent({ tool, args, items, raw, reserved = {} }) {
184
196
  const selection = selectFragment(tool, args, items);
185
197
  if (!selection) return { itemsContent: raw, sent: items, whole: true, reserves: {} };
186
- const sent = items
187
- .filter((i) => selection.full.has(i.id) || selection.context.has(i.id))
188
- .map((i) => (selection.full.has(i.id) ? i : asContext(i)));
189
198
  const max = maxIds(items);
190
199
  for (const kind of KINDS) for (const n of reserved[kind] ?? []) max[kind] = Math.max(max[kind], n);
191
- const reserves = RESERVES[tool] ? { [RESERVES[tool]]: max[RESERVES[tool]] + 1 } : {};
192
- const itemsContent = JSON.stringify({ format: FRAGMENT_FORMAT, max_ids: max, items: sent });
200
+ let reserves = RESERVES[tool] ? { [RESERVES[tool]]: max[RESERVES[tool]] + 1 } : {};
201
+ const payload = { format: FRAGMENT_FORMAT, max_ids: max };
202
+
203
+ // UC-12214: when the story follows its own series (UC-{story}{NN}), the server needs the ids of
204
+ // the story's UCs to continue it; with correlative numbering the board maximum is enough. It
205
+ // also gets the numbers parallel calls took and any UC elsewhere that already has the id it is
206
+ // about to give, to refuse a conflict instead of creating a duplicate. They travel as skeletons,
207
+ // and only when needed: the cost of creating a UC must not grow with the board (UC-11103).
208
+ const skeletons = new Set();
209
+ if (tool === 'add_uc') {
210
+ const wanted = args?.uc_id || null;
211
+ const next = wanted ? null : nextUcId(items, args?.us_id, reserved.UC ?? []);
212
+ const id = wanted ?? next.id;
213
+ const series = next?.numbering === 'story';
214
+ const storyIds = new Set(items.filter((i) => logicalId(i, 'US') === args?.us_id).map((i) => i.id));
215
+ for (const item of items) {
216
+ const uc = logicalId(item, 'UC');
217
+ if (!uc || selection.full.has(item.id)) continue;
218
+ const sibling = storyIds.has(item.parent_id) || item.meta?.us_id === args?.us_id;
219
+ if ((series && sibling) || uc === id) skeletons.add(item.id);
220
+ }
221
+ reserves = next ? { UC: next.number } : {};
222
+ if ((reserved.UC ?? []).length) payload.reserved = { UC: [...reserved.UC] };
223
+ }
224
+
225
+ const sent = items
226
+ .filter((i) => selection.full.has(i.id) || selection.context.has(i.id) || skeletons.has(i.id))
227
+ .map((i) => (selection.full.has(i.id) ? i : skeletons.has(i.id) ? asSkeleton(i) : asContext(i)));
228
+ payload.items = sent;
229
+ const itemsContent = JSON.stringify(payload);
193
230
  return { itemsContent, sent, whole: false, reserves };
194
231
  }
195
232
 
233
+ const STORY_NUMBER = /^US-(\d+)$/;
234
+
235
+ /**
236
+ * UC-12214: the id add_uc gives a new UC — the same rule as the server (choose_uc_id).
237
+ * When every UC of the story follows `UC-{story number}{NN}`, the next of that series;
238
+ * otherwise the next number of the whole board. `reservedUc`: numbers in-flight calls took.
239
+ */
240
+ export function nextUcId(items, usId, reservedUc = []) {
241
+ const reserved = new Set(reservedUc);
242
+ const byId = new Map(items.map((i) => [i.id, i]));
243
+ const owners = new Map();
244
+ for (const item of items) {
245
+ const uc = logicalId(item, 'UC');
246
+ if (!uc) continue;
247
+ let owner = item.meta?.us_id || '';
248
+ if (!owner) owner = logicalId(byId.get(item.parent_id), 'US') || '';
249
+ owners.set(uc, owner);
250
+ }
251
+ const story = STORY_NUMBER.exec(usId || '');
252
+ const siblings = [...owners].filter(([, owner]) => owner === usId).map(([uc]) => uc);
253
+ if (story && siblings.length) {
254
+ const series = new RegExp(`^UC-${story[1]}(\\d{2,})$`);
255
+ const matches = siblings.map((uc) => series.exec(uc));
256
+ if (matches.every(Boolean)) {
257
+ const pad = (nn) => String(nn).padStart(2, '0');
258
+ let nn = Math.max(...matches.map((m) => Number(m[1]))) + 1;
259
+ while (reserved.has(Number(`${story[1]}${pad(nn)}`))) nn += 1;
260
+ return { id: `UC-${story[1]}${pad(nn)}`, number: Number(`${story[1]}${pad(nn)}`), numbering: 'story' };
261
+ }
262
+ }
263
+ const top = Math.max(0, ...[...owners.keys()].map((uc) => idNumber(uc, 'UC')), ...reserved);
264
+ return { id: `UC-${String(top + 1).padStart(3, '0')}`, number: top + 1, numbering: 'board' };
265
+ }
266
+
196
267
  // ── Merging what comes back ────────────────────────────────────────────
197
268
 
198
269
  function canonical(value) {
@@ -255,52 +326,76 @@ export function mergeFragment(local, sent, returned) {
255
326
 
256
327
  // ── The tool's answer ──────────────────────────────────────────────────
257
328
 
258
- /** The `items_content` string inside an MCP tool response, whatever its shape. */
259
- export function extractItemsContent(response, depth = 0) {
329
+ /** The string field `key` inside an MCP tool response, whatever its shape. */
330
+ export function extractField(response, key, depth = 0) {
260
331
  if (depth > 6 || response == null) return null;
261
332
  if (typeof response === 'string') {
262
333
  const text = response.trim();
263
- return text.startsWith('{') ? extractItemsContent(safeJson(text), depth + 1) : null;
334
+ return text.startsWith('{') ? extractField(safeJson(text), key, depth + 1) : null;
264
335
  }
265
336
  if (Array.isArray(response)) {
266
337
  for (const part of response) {
267
- const found = extractItemsContent(part, depth + 1);
338
+ const found = extractField(part, key, depth + 1);
268
339
  if (found != null) return found;
269
340
  }
270
341
  return null;
271
342
  }
272
343
  if (typeof response === 'object') {
273
- if (typeof response.items_content === 'string') return response.items_content;
344
+ if (typeof response[key] === 'string') return response[key];
274
345
  for (const value of Object.values(response)) {
275
- const found = extractItemsContent(value, depth + 1);
346
+ const found = extractField(value, key, depth + 1);
276
347
  if (found != null) return found;
277
348
  }
278
349
  }
279
350
  return null;
280
351
  }
281
352
 
282
- /** The same response without any `items_content` (what the model needs to see). */
283
- export function withoutItemsContent(response, depth = 0) {
353
+ /** The same response without any field in `keys` (what the model needs to see). */
354
+ export function withoutFields(response, keys, depth = 0) {
284
355
  if (depth > 6 || response == null) return response;
285
356
  if (typeof response === 'string') {
286
357
  const text = response.trim();
287
358
  if (!text.startsWith('{')) return response;
288
359
  const parsed = safeJson(text);
289
- if (parsed == null || extractItemsContent(parsed) == null) return response;
290
- return JSON.stringify(withoutItemsContent(parsed, depth + 1));
360
+ if (parsed == null || keys.every((k) => extractField(parsed, k) == null)) return response;
361
+ return JSON.stringify(withoutFields(parsed, keys, depth + 1));
291
362
  }
292
- if (Array.isArray(response)) return response.map((part) => withoutItemsContent(part, depth + 1));
363
+ if (Array.isArray(response)) return response.map((part) => withoutFields(part, keys, depth + 1));
293
364
  if (typeof response === 'object') {
294
365
  const out = {};
295
366
  for (const [key, value] of Object.entries(response)) {
296
- if (key === 'items_content') continue;
297
- out[key] = withoutItemsContent(value, depth + 1);
367
+ if (keys.includes(key)) continue;
368
+ out[key] = withoutFields(value, keys, depth + 1);
298
369
  }
299
370
  return out;
300
371
  }
301
372
  return response;
302
373
  }
303
374
 
375
+ /** The `items_content` string inside an MCP tool response, whatever its shape. */
376
+ export function extractItemsContent(response) {
377
+ return extractField(response, 'items_content');
378
+ }
379
+
380
+ /** The same response without any `items_content` (nor `policy_content` or `event_line`, UC-12212/12213). */
381
+ export function withoutItemsContent(response) {
382
+ return withoutFields(response, ['items_content', 'policy_content', 'event_line']);
383
+ }
384
+
385
+ // ── The EP-20 policy, doc/tracking/policy.json (UC-12212) ─────────────
386
+
387
+ /** The tools that read or change the policy: they get the file as `policy_content`. */
388
+ export const POLICY_TOOLS = new Set([
389
+ 'get_enforcement_policy', 'set_enforcement_mode', 'skip_enforcement',
390
+ 'get_enforcement_impact', 'record_enforcement_event',
391
+ ]);
392
+ /** Of those, the ones whose answer is the new file. */
393
+ export const POLICY_WRITERS = new Set(['set_enforcement_mode', 'skip_enforcement']);
394
+ /** The ones that measure the board: they also get items.json and the events (UC-12213). */
395
+ export const POLICY_BOARD_TOOLS = new Set(['set_enforcement_mode', 'get_enforcement_impact']);
396
+ /** The ones whose answer carries an `event_line` for doc/tracking/enforcement_events.jsonl. */
397
+ export const POLICY_EVENT_TOOLS = new Set(['skip_enforcement', 'record_enforcement_event']);
398
+
304
399
  // ── Files: pending calls, the lock and atomic writes ───────────────────
305
400
 
306
401
  function sleep(ms) {
@@ -5,7 +5,8 @@
5
5
  * Reads, in order of priority:
6
6
  * 1. .quality/handoff.md (if fresh) — full content, capped at MAX_CHARS
7
7
  * 2. .quality/active_uc.json — UC en progreso
8
- * 3. doc/app/app_spec.md — auto-zones (tracking_backend, autopilot)
8
+ * 3. doc/app/app_spec.md — auto-zones (stack, tracking_backend, autopilot), with the
9
+ * marker attributes in any order (lib/app-spec-zones.mjs, UC-12205)
9
10
  * 4. .quality/evidence/<feature>/checkpoint.json — last phase
10
11
  * 5. Board native: decisions a person resolved from the panel, the app or another session
11
12
  * (take_resolved_decisions, US-99 · UC-9902), first in the context; 2.5 s cap, never fails.
@@ -18,6 +19,7 @@ import { readFileSync, statSync, existsSync } from 'fs';
18
19
  import { findFiles, readJsonFile, fileExists } from './lib/utils.mjs';
19
20
  import { getProjectConfig } from './lib/config.mjs';
20
21
  import { recogerDecisiones, textoDeDecisiones } from './lib/decisiones.mjs';
22
+ import { parseAutoZones } from './lib/app-spec-zones.mjs';
21
23
 
22
24
  const HANDOFF_PATH = '.quality/handoff.md';
23
25
  const APP_SPEC_PATH = 'doc/app/app_spec.md';
@@ -77,15 +79,7 @@ function extractAutoZones(specPath) {
77
79
  } catch {
78
80
  return null;
79
81
  }
80
- const zones = {};
81
- const zoneRegex = /<!--\s*@specbox:zone start kind="auto" id="([^"]+)"\s*-->([\s\S]*?)<!--\s*@specbox:zone end\s*-->/g;
82
- let match;
83
- while ((match = zoneRegex.exec(content)) !== null) {
84
- const id = match[1];
85
- if (id === 'tracking_backend' || id === 'autopilot' || id === 'stack') {
86
- zones[id] = match[2].trim();
87
- }
88
- }
82
+ const zones = parseAutoZones(content);
89
83
  return Object.keys(zones).length > 0 ? zones : null;
90
84
  }
91
85
 
@@ -186,7 +186,7 @@
186
186
  ]
187
187
  },
188
188
  {
189
- "matcher": "Task",
189
+ "matcher": "Agent|Task",
190
190
  "hooks": [
191
191
  {
192
192
  "type": "command",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specbox",
3
- "version": "6.34.0",
3
+ "version": "6.36.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": {