specbox 6.29.1 → 6.30.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.
Files changed (57) hide show
  1. package/README.md +5 -3
  2. package/bin/specbox.mjs +38 -2
  3. package/hooks/app-docs-sync-guard.mjs +326 -0
  4. package/hooks/branch-guard.mjs +79 -0
  5. package/hooks/checkpoint-freshness-guard.mjs +56 -0
  6. package/hooks/commit-spec-guard.mjs +61 -0
  7. package/hooks/context-budget-guard.mjs +130 -0
  8. package/hooks/design-gate.mjs +144 -0
  9. package/hooks/design-review-gate.mjs +102 -0
  10. package/hooks/design-system-gate.mjs +134 -0
  11. package/hooks/e2e-gate.mjs +86 -0
  12. package/hooks/file-ownership-guard.mjs +163 -0
  13. package/hooks/freeform-fragment.mjs +160 -0
  14. package/hooks/freeform-path-guard.mjs +172 -0
  15. package/hooks/healing-budget-guard.mjs +83 -0
  16. package/hooks/hooks-history.json +176 -0
  17. package/hooks/hooks-manifest.json +51 -0
  18. package/hooks/implement-checkpoint.mjs +46 -0
  19. package/hooks/implement-healing.mjs +38 -0
  20. package/hooks/lib/autopilot.mjs +240 -0
  21. package/hooks/lib/config.mjs +117 -0
  22. package/hooks/lib/decisiones.mjs +58 -0
  23. package/hooks/lib/design-gaps.mjs +272 -0
  24. package/hooks/lib/execution-context.mjs +69 -0
  25. package/hooks/lib/freeform-fragment.mjs +379 -0
  26. package/hooks/lib/freeform-path.mjs +115 -0
  27. package/hooks/lib/handoff-builder.mjs +388 -0
  28. package/hooks/lib/heartbeat-send.mjs +91 -0
  29. package/hooks/lib/heartbeat.mjs +110 -0
  30. package/hooks/lib/mcp-client-io.mjs +210 -0
  31. package/hooks/lib/mcp-client.mjs +91 -0
  32. package/hooks/lib/native-reservation-revalidate.mjs +80 -0
  33. package/hooks/lib/output.mjs +70 -0
  34. package/hooks/lib/ownership-map.mjs +162 -0
  35. package/hooks/lib/token-counter.mjs +81 -0
  36. package/hooks/lib/utils.mjs +235 -0
  37. package/hooks/no-bypass-guard.mjs +57 -0
  38. package/hooks/on-session-end.mjs +163 -0
  39. package/hooks/pipeline-phase-guard.mjs +140 -0
  40. package/hooks/post-implement-validate.mjs +61 -0
  41. package/hooks/pre-commit-lint.mjs +76 -0
  42. package/hooks/pre-prd-discovery-check.mjs +242 -0
  43. package/hooks/pre-read-budget-guard.mjs +83 -0
  44. package/hooks/quality-first-guard.mjs +85 -0
  45. package/hooks/read-tracker.mjs +33 -0
  46. package/hooks/session-heartbeat.mjs +113 -0
  47. package/hooks/session-start.mjs +159 -0
  48. package/hooks/settings-hooks.json +363 -0
  49. package/hooks/spec-guard.mjs +152 -0
  50. package/hooks/stripe-safety-guard.mjs +262 -0
  51. package/hooks/uc-lifecycle-guard.mjs +87 -0
  52. package/lib/hooks.mjs +156 -0
  53. package/lib/install.mjs +9 -0
  54. package/lib/internal.mjs +26 -3
  55. package/lib/mcp-headers.mjs +31 -3
  56. package/lib/messages.mjs +41 -0
  57. package/package.json +5 -3
@@ -0,0 +1,159 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * session-start.mjs — SessionStart hook: injects continuity context into the new session.
4
+ *
5
+ * Reads, in order of priority:
6
+ * 1. .quality/handoff.md (if fresh) — full content, capped at MAX_CHARS
7
+ * 2. .quality/active_uc.json — UC en progreso
8
+ * 3. doc/app/app_spec.md — auto-zones (tracking_backend, autopilot)
9
+ * 4. .quality/evidence/<feature>/checkpoint.json — last phase
10
+ * 5. Board native: decisions a person resolved from the panel, the app or another session
11
+ * (take_resolved_decisions, US-99 · UC-9902), first in the context; 2.5 s cap, never fails.
12
+ *
13
+ * Output: JSON to stdout with hookSpecificOutput.additionalContext
14
+ * If nothing relevant exists, exits silently (no context injection).
15
+ */
16
+
17
+ import { readFileSync, statSync, existsSync } from 'fs';
18
+ import { findFiles, readJsonFile, fileExists } from './lib/utils.mjs';
19
+ import { getProjectConfig } from './lib/config.mjs';
20
+ import { recogerDecisiones, textoDeDecisiones } from './lib/decisiones.mjs';
21
+
22
+ const HANDOFF_PATH = '.quality/handoff.md';
23
+ const APP_SPEC_PATH = 'doc/app/app_spec.md';
24
+ const ACTIVE_UC_PATH = '.quality/active_uc.json';
25
+ const MAX_CHARS = 14000;
26
+ const STALE_TTL_MIN = 1440;
27
+
28
+ function fileAgeMinutes(path) {
29
+ if (!existsSync(path)) return Infinity;
30
+ try {
31
+ return (Date.now() - statSync(path).mtimeMs) / 60000;
32
+ } catch {
33
+ return Infinity;
34
+ }
35
+ }
36
+
37
+ function readHandoff() {
38
+ if (!fileExists(HANDOFF_PATH)) return null;
39
+ try {
40
+ const content = readFileSync(HANDOFF_PATH, 'utf-8');
41
+ const ageMin = fileAgeMinutes(HANDOFF_PATH);
42
+ const stale = ageMin > STALE_TTL_MIN;
43
+ return { content, ageMin: Math.round(ageMin), stale };
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function readActiveUC() {
50
+ const data = readJsonFile(ACTIVE_UC_PATH);
51
+ if (!data) return null;
52
+ return {
53
+ uc_id: data.uc_id || data.feature || 'unknown',
54
+ started_at: data.started_at || null,
55
+ };
56
+ }
57
+
58
+ function readLatestCheckpoint() {
59
+ const files = findFiles('.quality/evidence', /^checkpoint\.json$/);
60
+ if (files.length === 0) return null;
61
+ let latest = null;
62
+ let latestMtime = 0;
63
+ for (const f of files) {
64
+ try {
65
+ const m = statSync(f).mtimeMs;
66
+ if (m > latestMtime) { latestMtime = m; latest = f; }
67
+ } catch { /* ignore */ }
68
+ }
69
+ return latest ? readJsonFile(latest) : null;
70
+ }
71
+
72
+ function extractAutoZones(specPath) {
73
+ if (!fileExists(specPath)) return null;
74
+ let content;
75
+ try {
76
+ content = readFileSync(specPath, 'utf-8');
77
+ } catch {
78
+ return null;
79
+ }
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
+ }
89
+ return Object.keys(zones).length > 0 ? zones : null;
90
+ }
91
+
92
+ function buildContext(decisiones = []) {
93
+ const parts = [];
94
+
95
+ const resueltas = textoDeDecisiones(decisiones);
96
+ if (resueltas) parts.push(resueltas);
97
+
98
+ const handoff = readHandoff();
99
+ if (handoff) {
100
+ const tag = handoff.stale ? '[STALE]' : '[FRESH]';
101
+ parts.push(`## SpecBox Handoff ${tag} (age: ${handoff.ageMin}min)\n\nFrom previous session — ${handoff.stale ? 'WARNING: older than 24h, may be outdated.' : 'this is the recovered state.'}\n\n${handoff.content}`);
102
+ }
103
+
104
+ if (!handoff || handoff.stale) {
105
+ const activeUC = readActiveUC();
106
+ const checkpoint = readLatestCheckpoint();
107
+ if (activeUC || checkpoint) {
108
+ const lines = ['## SpecBox Live State (no fresh handoff)'];
109
+ if (activeUC) {
110
+ lines.push(`- Active UC: **${activeUC.uc_id}**${activeUC.started_at ? ` (started ${activeUC.started_at})` : ''}`);
111
+ }
112
+ if (checkpoint) {
113
+ lines.push(`- Last checkpoint: feature=${checkpoint.feature}, phase=${checkpoint.phase} (${checkpoint.phase_name}), branch=${checkpoint.branch}, status=${checkpoint.status}`);
114
+ }
115
+ lines.push('');
116
+ lines.push('Consider running `/handoff` to restore richer context, or check `git log` and `.quality/evidence/` for state.');
117
+ parts.push(lines.join('\n'));
118
+ }
119
+ }
120
+
121
+ const zones = extractAutoZones(APP_SPEC_PATH);
122
+ if (zones) {
123
+ const lines = ['## SpecBox Canonical (from doc/app/app_spec.md)'];
124
+ if (zones.stack) lines.push(`### Stack\n${zones.stack}`);
125
+ if (zones.tracking_backend) lines.push(`### Tracking backend\n${zones.tracking_backend}`);
126
+ if (zones.autopilot) lines.push(`### Autopilot\n${zones.autopilot}`);
127
+ parts.push(lines.join('\n\n'));
128
+ }
129
+
130
+ if (parts.length === 0) return null;
131
+
132
+ let combined = parts.join('\n\n---\n\n');
133
+ if (combined.length > MAX_CHARS) {
134
+ combined = combined.slice(0, MAX_CHARS - 100) + '\n\n_(truncated by session-start hook to fit budget)_\n';
135
+ }
136
+ return combined;
137
+ }
138
+
139
+ async function main() {
140
+ const { boardId, backendType } = getProjectConfig();
141
+ const decisiones = backendType === 'native' && boardId ? await recogerDecisiones({ proyecto: boardId }) : [];
142
+ const ctx = buildContext(decisiones);
143
+ if (!ctx) {
144
+ process.exit(0);
145
+ }
146
+ const out = {
147
+ hookSpecificOutput: {
148
+ hookEventName: 'SessionStart',
149
+ additionalContext: ctx,
150
+ },
151
+ };
152
+ process.stdout.write(JSON.stringify(out));
153
+ process.exit(0);
154
+ }
155
+
156
+ main().catch((e) => {
157
+ console.error(`[session-start] error: ${e.message}`);
158
+ process.exit(0);
159
+ });
@@ -0,0 +1,363 @@
1
+ {
2
+ "Notification": [
3
+ {
4
+ "hooks": [
5
+ {
6
+ "type": "command",
7
+ "command": "node .claude/hooks/session-heartbeat.mjs",
8
+ "timeout": 3
9
+ }
10
+ ]
11
+ }
12
+ ],
13
+ "UserPromptSubmit": [
14
+ {
15
+ "hooks": [
16
+ {
17
+ "type": "command",
18
+ "command": "node .claude/hooks/session-heartbeat.mjs",
19
+ "timeout": 3
20
+ }
21
+ ]
22
+ }
23
+ ],
24
+ "SessionEnd": [
25
+ {
26
+ "hooks": [
27
+ {
28
+ "type": "command",
29
+ "command": "node .claude/hooks/session-heartbeat.mjs",
30
+ "timeout": 3
31
+ }
32
+ ]
33
+ }
34
+ ],
35
+ "PreToolUse": [
36
+ {
37
+ "matcher": "Write",
38
+ "hooks": [
39
+ {
40
+ "type": "command",
41
+ "command": "node .claude/hooks/quality-first-guard.mjs",
42
+ "timeout": 5
43
+ },
44
+ {
45
+ "type": "command",
46
+ "command": "node .claude/hooks/healing-budget-guard.mjs",
47
+ "timeout": 5
48
+ },
49
+ {
50
+ "type": "command",
51
+ "command": "node .claude/hooks/pipeline-phase-guard.mjs",
52
+ "timeout": 5
53
+ },
54
+ {
55
+ "type": "command",
56
+ "command": "node .claude/hooks/file-ownership-guard.mjs",
57
+ "timeout": 5
58
+ },
59
+ {
60
+ "type": "command",
61
+ "command": "node .claude/hooks/stripe-safety-guard.mjs",
62
+ "timeout": 5
63
+ }
64
+ ]
65
+ },
66
+ {
67
+ "matcher": "Edit",
68
+ "hooks": [
69
+ {
70
+ "type": "command",
71
+ "command": "node .claude/hooks/quality-first-guard.mjs",
72
+ "timeout": 5
73
+ },
74
+ {
75
+ "type": "command",
76
+ "command": "node .claude/hooks/healing-budget-guard.mjs",
77
+ "timeout": 5
78
+ },
79
+ {
80
+ "type": "command",
81
+ "command": "node .claude/hooks/pipeline-phase-guard.mjs",
82
+ "timeout": 5
83
+ },
84
+ {
85
+ "type": "command",
86
+ "command": "node .claude/hooks/file-ownership-guard.mjs",
87
+ "timeout": 5
88
+ },
89
+ {
90
+ "type": "command",
91
+ "command": "node .claude/hooks/stripe-safety-guard.mjs",
92
+ "timeout": 5
93
+ }
94
+ ]
95
+ },
96
+ {
97
+ "matcher": "Bash",
98
+ "hooks": [
99
+ {
100
+ "type": "command",
101
+ "if": "Bash(*--no-verify*)",
102
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
103
+ "timeout": 5
104
+ },
105
+ {
106
+ "type": "command",
107
+ "if": "Bash(*push*--force*)",
108
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
109
+ "timeout": 5
110
+ },
111
+ {
112
+ "type": "command",
113
+ "if": "Bash(*push*-f *)",
114
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
115
+ "timeout": 5
116
+ },
117
+ {
118
+ "type": "command",
119
+ "if": "Bash(*reset --hard*)",
120
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
121
+ "timeout": 5
122
+ },
123
+ {
124
+ "type": "command",
125
+ "if": "Bash(*push* -f)",
126
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
127
+ "timeout": 5
128
+ },
129
+ {
130
+ "type": "command",
131
+ "if": "Bash(*push* +*)",
132
+ "command": "node .claude/hooks/no-bypass-guard.mjs",
133
+ "timeout": 5
134
+ },
135
+ {
136
+ "type": "command",
137
+ "if": "Bash(*git commit*)",
138
+ "command": "node .claude/hooks/commit-spec-guard.mjs",
139
+ "timeout": 10
140
+ },
141
+ {
142
+ "type": "command",
143
+ "if": "Bash(*git commit*)",
144
+ "command": "node .claude/hooks/pre-commit-lint.mjs",
145
+ "timeout": 60
146
+ },
147
+ {
148
+ "type": "command",
149
+ "if": "Bash(*git commit*)",
150
+ "command": "node .claude/hooks/e2e-gate.mjs",
151
+ "timeout": 15
152
+ },
153
+ {
154
+ "type": "command",
155
+ "if": "Bash(*git commit*)",
156
+ "command": "node .claude/hooks/app-docs-sync-guard.mjs",
157
+ "timeout": 10
158
+ },
159
+ {
160
+ "type": "command",
161
+ "if": "Bash(*gh pr create*)",
162
+ "command": "node .claude/hooks/design-system-gate.mjs",
163
+ "timeout": 20
164
+ },
165
+ {
166
+ "type": "command",
167
+ "if": "Bash(*gh pr create*)",
168
+ "command": "node .claude/hooks/design-review-gate.mjs",
169
+ "timeout": 20
170
+ }
171
+ ]
172
+ },
173
+ {
174
+ "matcher": "mcp__SpecBox-MCP__(move_uc|complete_uc)",
175
+ "hooks": [
176
+ {
177
+ "type": "command",
178
+ "command": "node .claude/hooks/design-system-gate.mjs",
179
+ "timeout": 20
180
+ },
181
+ {
182
+ "type": "command",
183
+ "command": "node .claude/hooks/design-review-gate.mjs",
184
+ "timeout": 20
185
+ }
186
+ ]
187
+ },
188
+ {
189
+ "matcher": "Task",
190
+ "hooks": [
191
+ {
192
+ "type": "command",
193
+ "command": "node .claude/hooks/context-budget-guard.mjs",
194
+ "timeout": 3
195
+ }
196
+ ]
197
+ },
198
+ {
199
+ "matcher": "Read",
200
+ "hooks": [
201
+ {
202
+ "type": "command",
203
+ "command": "node .claude/hooks/pre-read-budget-guard.mjs",
204
+ "timeout": 3
205
+ }
206
+ ]
207
+ },
208
+ {
209
+ "matcher": "mcp__SpecBox-MCP__(set_auth_token|onboard_project)",
210
+ "hooks": [
211
+ {
212
+ "type": "command",
213
+ "command": "node .claude/hooks/freeform-path-guard.mjs",
214
+ "timeout": 3
215
+ }
216
+ ]
217
+ },
218
+ {
219
+ "matcher": "mcp__SpecBox-MCP__.*",
220
+ "hooks": [
221
+ {
222
+ "type": "command",
223
+ "command": "node .claude/hooks/freeform-fragment.mjs",
224
+ "timeout": 15
225
+ }
226
+ ]
227
+ },
228
+ {
229
+ "matcher": "Skill",
230
+ "hooks": [
231
+ {
232
+ "type": "command",
233
+ "command": "node .claude/hooks/pre-prd-discovery-check.mjs",
234
+ "timeout": 8
235
+ }
236
+ ]
237
+ }
238
+ ],
239
+ "PostToolUse": [
240
+ {
241
+ "matcher": "mcp__SpecBox-MCP__.*",
242
+ "hooks": [
243
+ {
244
+ "type": "command",
245
+ "command": "node .claude/hooks/freeform-fragment.mjs",
246
+ "timeout": 15
247
+ }
248
+ ]
249
+ },
250
+ {
251
+ "matcher": "Bash|Write|Edit|mcp__.*",
252
+ "hooks": [
253
+ {
254
+ "type": "command",
255
+ "command": "node .claude/hooks/session-heartbeat.mjs",
256
+ "timeout": 3
257
+ }
258
+ ]
259
+ },
260
+ {
261
+ "matcher": "Read",
262
+ "hooks": [
263
+ {
264
+ "type": "command",
265
+ "command": "node .claude/hooks/read-tracker.mjs",
266
+ "timeout": 3
267
+ }
268
+ ]
269
+ },
270
+ {
271
+ "matcher": "Bash",
272
+ "hooks": [
273
+ {
274
+ "type": "command",
275
+ "if": "Bash(*git commit*)",
276
+ "command": "node .claude/hooks/checkpoint-freshness-guard.mjs",
277
+ "timeout": 5
278
+ },
279
+ {
280
+ "type": "command",
281
+ "if": "Bash(*git push*)",
282
+ "command": "node .claude/hooks/uc-lifecycle-guard.mjs",
283
+ "timeout": 10
284
+ }
285
+ ]
286
+ },
287
+ {
288
+ "matcher": "Write",
289
+ "hooks": [
290
+ {
291
+ "type": "command",
292
+ "if": "Write(src/**)",
293
+ "command": "node .claude/hooks/spec-guard.mjs",
294
+ "timeout": 10
295
+ },
296
+ {
297
+ "type": "command",
298
+ "if": "Write(lib/**)",
299
+ "command": "node .claude/hooks/spec-guard.mjs",
300
+ "timeout": 10
301
+ },
302
+ {
303
+ "type": "command",
304
+ "command": "node .claude/hooks/design-gate.mjs",
305
+ "timeout": 10
306
+ }
307
+ ]
308
+ },
309
+ {
310
+ "matcher": "Edit",
311
+ "hooks": [
312
+ {
313
+ "type": "command",
314
+ "if": "Edit(src/**)",
315
+ "command": "node .claude/hooks/spec-guard.mjs",
316
+ "timeout": 10
317
+ },
318
+ {
319
+ "type": "command",
320
+ "if": "Edit(lib/**)",
321
+ "command": "node .claude/hooks/spec-guard.mjs",
322
+ "timeout": 10
323
+ },
324
+ {
325
+ "type": "command",
326
+ "command": "node .claude/hooks/design-gate.mjs",
327
+ "timeout": 10
328
+ }
329
+ ]
330
+ }
331
+ ],
332
+ "Stop": [
333
+ {
334
+ "hooks": [
335
+ {
336
+ "type": "command",
337
+ "command": "node .claude/hooks/on-session-end.mjs",
338
+ "timeout": 10
339
+ }
340
+ ]
341
+ }
342
+ ],
343
+ "SessionStart": [
344
+ {
345
+ "hooks": [
346
+ {
347
+ "type": "command",
348
+ "command": "node .claude/hooks/session-heartbeat.mjs",
349
+ "timeout": 3
350
+ }
351
+ ]
352
+ },
353
+ {
354
+ "hooks": [
355
+ {
356
+ "type": "command",
357
+ "command": "node .claude/hooks/session-start.mjs",
358
+ "timeout": 5
359
+ }
360
+ ]
361
+ }
362
+ ]
363
+ }
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * spec-guard.mjs — PostToolUse hook for Write/Edit on source files (src/, lib/)
4
+ *
5
+ * After the write (PostToolUse cannot undo it), in a spec-driven project:
6
+ * - code on main/master, or under a native reservation that is no longer yours → exit 2: the
7
+ * agent gets the reason and has to move the work (US-93/UC-9302; it exited 1, unseen);
8
+ * - code with no active UC (or a stale marker) → a note to the agent (additionalContext).
9
+ *
10
+ * This hook enforces the SpecBox Engine contract:
11
+ * "No code without traceability. No implementation without an active UC."
12
+ *
13
+ * v5.7.0 — Pipeline Integrity Enforcement
14
+ */
15
+
16
+ import { execFileSync } from 'node:child_process';
17
+ import { readStdin, fileExists, fileAge, git } from './lib/utils.mjs';
18
+ import { blockWith, noteWith } from './lib/output.mjs';
19
+ import { dirname, isAbsolute } from 'node:path';
20
+ import { getProjectConfig, getActiveUC, getActiveUCReservation, getStaleUC } from './lib/config.mjs';
21
+ import { decideNativeReservation } from './lib/native-reservation-revalidate.mjs';
22
+
23
+ /**
24
+ * Best-effort revalidation of a native reservation against the MCP. Returns
25
+ * { reachable, reservation } for decideNativeReservation. Never throws — any
26
+ * failure (no URL, network error, timeout, bad JSON) yields reachable:false
27
+ * so the cache is trusted [AC-21]. Online conflicts are surfaced for AC-22.
28
+ *
29
+ * Endpoint: GET /api/native/reservation-status?uc_id=...
30
+ * Expected response: { uc_id, reservation: { developer_id } | null }
31
+ *
32
+ * Wire-protocol compat (v5.35-v5.36): if the MCP returns the legacy shape
33
+ * { uc_id, claim: {…} | null } we pass `claim` through too, and the pure
34
+ * decision module accepts both. UC-612 removes the fallback in v5.37.0.
35
+ */
36
+ function probeNativeReservation(reservation) {
37
+ const mcpUrl = process.env.SPECBOX_ENGINE_MCP_URL || process.env.DEV_ENGINE_MCP_URL || '';
38
+ if (!mcpUrl) return { reachable: false };
39
+ try {
40
+ const url = `${mcpUrl.replace(/\/$/, '')}/api/native/reservation-status`;
41
+ const out = execFileSync(
42
+ 'curl',
43
+ [
44
+ '-fsS', '--max-time', '3',
45
+ '-L', // follow redirects so a server still serving the legacy URL
46
+ // with a 301 to /reservation-status works transparently
47
+ '-G', url,
48
+ '--data-urlencode', `uc_id=${reservation.ucId}`,
49
+ ],
50
+ { encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'] },
51
+ );
52
+ const data = JSON.parse(out);
53
+ return {
54
+ reachable: true,
55
+ reservation: data.reservation ?? null,
56
+ // Forward the legacy `claim` field too so the pure decision module
57
+ // can fall back if the server has not yet upgraded.
58
+ claim: data.claim ?? undefined,
59
+ };
60
+ } catch {
61
+ return { reachable: false };
62
+ }
63
+ }
64
+
65
+ const input = readStdin();
66
+
67
+ // Extract file path
68
+ let filePath = '';
69
+ try {
70
+ const parsed = JSON.parse(input);
71
+ // Claude Code sends the tool's arguments in tool_input; the top level is the old test format.
72
+ filePath = (parsed.tool_input ?? parsed).file_path || '';
73
+ } catch {
74
+ const match = input.match(/"file_path"\s*:\s*"([^"]*)"/);
75
+ filePath = match ? match[1] : '';
76
+ }
77
+
78
+ if (!filePath) {
79
+ process.exit(0);
80
+ }
81
+
82
+ // Only guard source code files (src/, lib/), not tests, docs, config, etc.
83
+ if (!/(^|\/)(?:src|lib)\//.test(filePath)) {
84
+ process.exit(0);
85
+ }
86
+
87
+ // Skip test files, config files, generated files
88
+ if (/(test\/|tests\/|\.test\.|\.spec\.|_test\.dart|\.g\.dart|\.freezed\.dart|\.config\.|\.json$|\.yaml$|\.md$)/.test(filePath)) {
89
+ process.exit(0);
90
+ }
91
+
92
+ // The repo the file lives in (a write to another worktree is checked against that worktree).
93
+ if (isAbsolute(filePath)) {
94
+ try {
95
+ const top = execFileSync('git', ['-C', dirname(filePath), 'rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
96
+ if (top) process.chdir(top);
97
+ } catch { /* not in a git repo: keep the session's directory */ }
98
+ }
99
+
100
+ // --- Check if project is spec-driven ---
101
+ const { boardId, backendType, isSpecDriven } = getProjectConfig();
102
+
103
+ // If no board and no backend configured → not spec-driven, allow
104
+ if (!isSpecDriven) {
105
+ process.exit(0);
106
+ }
107
+
108
+ // --- Spec-driven project: verify branch discipline ---
109
+ const currentBranch = git('branch --show-current');
110
+
111
+ if (currentBranch === 'main' || currentBranch === 'master') {
112
+ blockWith(`SPEC GUARD: código escrito en ${currentBranch}`, [
113
+ `Fichero: ${filePath}`,
114
+ 'Es un proyecto spec-driven: el código va en una rama de la UC, nunca en main ni en master.',
115
+ 'La escritura ya está hecha. Antes de seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo).',
116
+ ]);
117
+ }
118
+
119
+ // --- Spec-driven project: verify active UC ---
120
+ const activeUC = getActiveUC();
121
+ if (activeUC) {
122
+ // Native reservation revalidation (UC-304, renamed in UC-613): the marker is
123
+ // a cache of the remote reservation. Offline → trust it [AC-21]. Online →
124
+ // revalidate; block if the reservation was released or taken over by another
125
+ // dev [AC-22].
126
+ const reservation = getActiveUCReservation();
127
+ if (reservation) {
128
+ const decision = decideNativeReservation(reservation, probeNativeReservation(reservation));
129
+ if (!decision.allow) {
130
+ const actual = decision.conflict?.actual;
131
+ blockWith('SPEC GUARD: la reserva de la UC ya no es tuya', [
132
+ `Fichero: ${filePath}`,
133
+ `UC: ${reservation.ucId}`,
134
+ decision.reason === 'reservation-released'
135
+ ? `La reserva se liberó en remoto (eras ${reservation.developerId}). Vuelve a llamar a start_uc antes de seguir escribiendo.`
136
+ : `Ahora la tiene '${actual}' (tú eres '${reservation.developerId}'). Coordínate con esa persona o elige otra UC.`,
137
+ ]);
138
+ }
139
+ }
140
+ // Active UC exists and is fresh (and reservation still valid / offline) → allow
141
+ process.exit(0);
142
+ }
143
+
144
+ // No active UC (or a stale marker) → a note: the agent should start the UC.
145
+ const staleUC = getStaleUC();
146
+ noteWith('PostToolUse', staleUC ? 'SPEC GUARD: la UC activa lleva más de 24 h sin tocarse' : 'SPEC GUARD: código sin UC activa', [
147
+ `Fichero: ${filePath} · board ${boardId}`,
148
+ staleUC
149
+ ? 'El marcador .quality/active_uc.json tiene más de 24 h: la sesión anterior terminó sin cerrar la UC.'
150
+ : 'En un proyecto spec-driven todo código va asociado a una UC.',
151
+ 'Recorrido: find_next_uc → start_uc → implementar → mark_ac_batch → complete_uc (o /implement).',
152
+ ]);