specbox 6.29.0 → 6.29.2
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.
- package/README.md +5 -3
- package/bin/specbox.mjs +38 -2
- package/hooks/app-docs-sync-guard.mjs +326 -0
- package/hooks/branch-guard.mjs +79 -0
- package/hooks/checkpoint-freshness-guard.mjs +56 -0
- package/hooks/commit-spec-guard.mjs +61 -0
- package/hooks/context-budget-guard.mjs +130 -0
- package/hooks/design-gate.mjs +144 -0
- package/hooks/design-review-gate.mjs +102 -0
- package/hooks/design-system-gate.mjs +134 -0
- package/hooks/e2e-gate.mjs +86 -0
- package/hooks/file-ownership-guard.mjs +163 -0
- package/hooks/freeform-fragment.mjs +160 -0
- package/hooks/freeform-path-guard.mjs +172 -0
- package/hooks/healing-budget-guard.mjs +83 -0
- package/hooks/hooks-history.json +176 -0
- package/hooks/hooks-manifest.json +51 -0
- package/hooks/implement-checkpoint.mjs +46 -0
- package/hooks/implement-healing.mjs +38 -0
- package/hooks/lib/autopilot.mjs +240 -0
- package/hooks/lib/config.mjs +117 -0
- package/hooks/lib/decisiones.mjs +58 -0
- package/hooks/lib/design-gaps.mjs +272 -0
- package/hooks/lib/execution-context.mjs +69 -0
- package/hooks/lib/freeform-fragment.mjs +379 -0
- package/hooks/lib/freeform-path.mjs +115 -0
- package/hooks/lib/handoff-builder.mjs +388 -0
- package/hooks/lib/heartbeat-send.mjs +91 -0
- package/hooks/lib/heartbeat.mjs +110 -0
- package/hooks/lib/mcp-client-io.mjs +210 -0
- package/hooks/lib/mcp-client.mjs +91 -0
- package/hooks/lib/native-reservation-revalidate.mjs +80 -0
- package/hooks/lib/output.mjs +70 -0
- package/hooks/lib/ownership-map.mjs +162 -0
- package/hooks/lib/token-counter.mjs +81 -0
- package/hooks/lib/utils.mjs +235 -0
- package/hooks/no-bypass-guard.mjs +57 -0
- package/hooks/on-session-end.mjs +163 -0
- package/hooks/pipeline-phase-guard.mjs +140 -0
- package/hooks/post-implement-validate.mjs +61 -0
- package/hooks/pre-commit-lint.mjs +76 -0
- package/hooks/pre-prd-discovery-check.mjs +242 -0
- package/hooks/pre-read-budget-guard.mjs +83 -0
- package/hooks/quality-first-guard.mjs +85 -0
- package/hooks/read-tracker.mjs +33 -0
- package/hooks/session-heartbeat.mjs +113 -0
- package/hooks/session-start.mjs +159 -0
- package/hooks/settings-hooks.json +363 -0
- package/hooks/spec-guard.mjs +152 -0
- package/hooks/stripe-safety-guard.mjs +262 -0
- package/hooks/uc-lifecycle-guard.mjs +87 -0
- package/lib/hooks.mjs +156 -0
- package/lib/install.mjs +9 -0
- package/lib/internal.mjs +26 -3
- package/lib/mcp-headers.mjs +31 -3
- package/lib/messages.mjs +41 -0
- package/package.json +4 -2
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* context-budget-guard.mjs — PreToolUse hook for Task (v5.32.0).
|
|
4
|
+
*
|
|
5
|
+
* Estimates tokens for the prompt of a Task spawned by /implement
|
|
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.
|
|
9
|
+
*
|
|
10
|
+
* Behaviour:
|
|
11
|
+
* - mode=warn (default) → stderr WARNING, exit 0
|
|
12
|
+
* - mode=strict → stderr BLOCKED, exit 2
|
|
13
|
+
* - mode=off → no-op, exit 0
|
|
14
|
+
*
|
|
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
|
+
*
|
|
19
|
+
* Side-effects:
|
|
20
|
+
* Updates .quality/task_isolation.json counters for local inspection
|
|
21
|
+
* and external consumers (specbox_cloud, ad-hoc scripts).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
25
|
+
import { dirname } from 'node:path';
|
|
26
|
+
import { estimatePromptTokens } from './lib/token-counter.mjs';
|
|
27
|
+
import { noteWith } from './lib/output.mjs';
|
|
28
|
+
|
|
29
|
+
const DEFAULT_BUDGET = 16000;
|
|
30
|
+
const DEFAULT_MODE = 'warn';
|
|
31
|
+
const SETTINGS_PATH = '.claude/settings.local.json';
|
|
32
|
+
const TASK_ISOLATION_CACHE = '.quality/task_isolation.json';
|
|
33
|
+
|
|
34
|
+
// ── Read stdin payload ─────────────────────────────────────────────────
|
|
35
|
+
|
|
36
|
+
const raw = readStdinSync();
|
|
37
|
+
let payload = {};
|
|
38
|
+
try { payload = JSON.parse(raw); } catch { /* ignore */ }
|
|
39
|
+
|
|
40
|
+
const toolName = payload?.tool_name || payload?.toolName || '';
|
|
41
|
+
if (toolName !== 'Task') {
|
|
42
|
+
process.exit(0);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ── Resolve settings ───────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
const { budget, mode } = readSettings();
|
|
48
|
+
if (mode === 'off') {
|
|
49
|
+
process.exit(0);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ── Estimate ──────────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
const { total, breakdown } = estimatePromptTokens(payload);
|
|
55
|
+
|
|
56
|
+
if (total <= budget) {
|
|
57
|
+
// Under budget → bump tasks_run_total counter and pass through.
|
|
58
|
+
bumpCounter('tasks_run_total');
|
|
59
|
+
process.exit(0);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ── Over budget ───────────────────────────────────────────────────────
|
|
63
|
+
|
|
64
|
+
bumpCounter('tasks_failed_budget');
|
|
65
|
+
|
|
66
|
+
const breakdownStr = Object.entries(breakdown)
|
|
67
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
68
|
+
.join(', ');
|
|
69
|
+
const overshoot = total - budget;
|
|
70
|
+
|
|
71
|
+
if (mode === 'strict') {
|
|
72
|
+
console.error(
|
|
73
|
+
`[context-budget-guard] BLOCKED — Task prompt is ~${total} tokens ` +
|
|
74
|
+
`(budget ${budget}, overshoot ${overshoot}). Breakdown: ${breakdownStr}. ` +
|
|
75
|
+
`Reduce the prompt body, move shared context to ` +
|
|
76
|
+
`.quality/evidence/{feature}/execution_context.json, or split the work ` +
|
|
77
|
+
`into multiple Tasks.`
|
|
78
|
+
);
|
|
79
|
+
process.exit(2);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// warn: a note to the agent (US-93/UC-9302: stderr with exit 0 reaches nobody).
|
|
83
|
+
noteWith('PreToolUse', '[context-budget-guard] El encargo del subagente se pasa de presupuesto', [
|
|
84
|
+
`~${total} tokens (presupuesto ${budget}, ${overshoot} de más). Reparto: ${breakdownStr}.`,
|
|
85
|
+
'Recórtalo o pasa el contexto común a .quality/evidence/{feature}/execution_context.json. La tarea sigue.',
|
|
86
|
+
]);
|
|
87
|
+
|
|
88
|
+
// ── Helpers ───────────────────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
function readStdinSync() {
|
|
91
|
+
try {
|
|
92
|
+
return readFileSync(0, 'utf-8');
|
|
93
|
+
} catch {
|
|
94
|
+
return '';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function readSettings() {
|
|
99
|
+
let budget = DEFAULT_BUDGET;
|
|
100
|
+
let mode = DEFAULT_MODE;
|
|
101
|
+
if (!existsSync(SETTINGS_PATH)) {
|
|
102
|
+
return { budget, mode };
|
|
103
|
+
}
|
|
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 };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function bumpCounter(key) {
|
|
114
|
+
try {
|
|
115
|
+
let cache = {};
|
|
116
|
+
if (existsSync(TASK_ISOLATION_CACHE)) {
|
|
117
|
+
try {
|
|
118
|
+
cache = JSON.parse(readFileSync(TASK_ISOLATION_CACHE, 'utf-8'));
|
|
119
|
+
} catch { cache = {}; }
|
|
120
|
+
}
|
|
121
|
+
cache[key] = (cache[key] || 0) + 1;
|
|
122
|
+
cache.last_event_at = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
123
|
+
mkdirSync(dirname(TASK_ISOLATION_CACHE), { recursive: true });
|
|
124
|
+
writeFileSync(
|
|
125
|
+
TASK_ISOLATION_CACHE,
|
|
126
|
+
JSON.stringify(cache, null, 2),
|
|
127
|
+
'utf-8'
|
|
128
|
+
);
|
|
129
|
+
} catch { /* best-effort */ }
|
|
130
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* design-gate.mjs — PostToolUse hook for Write/Edit on UI page files (US-91 · UC-9103).
|
|
4
|
+
*
|
|
5
|
+
* When an agent writes a UI page and its feature has no design in doc/design/{feature}/ (at least
|
|
6
|
+
* one HTML), the agent gets the warning in the same session: exit 2 with the message on stderr,
|
|
7
|
+
* which Claude Code feeds back to the model. PostToolUse cannot undo the write; the warning says
|
|
8
|
+
* what to do before going on with that screen.
|
|
9
|
+
*
|
|
10
|
+
* With a design, a page without its traceability comment gets a note through `additionalContext`
|
|
11
|
+
* (exit 0: informs, does not block).
|
|
12
|
+
*
|
|
13
|
+
* Claude Design (US-92 · UC-9202): what counts as a design is the frozen view `/design-review import`
|
|
14
|
+
* leaves (`{artboard}.html`), not the canvas source (`canvas/*.dc.html`), which needs the canvas
|
|
15
|
+
* engine to render. A page that carries pieces of that engine (`support.js`, `<x-dc>`, `DCLogic`,
|
|
16
|
+
* `<sc-for>`, `<sc-if>`, `<dc-import>`, `<x-import>`, `/_blob/`) gets exit 2: the design-to-code has
|
|
17
|
+
* to start from the frozen view and produce code of the stack.
|
|
18
|
+
*
|
|
19
|
+
* Registered without `if`: the path filter lives here. `if` takes permission-rule globs, not
|
|
20
|
+
* regexes, so the old `Write(src/pages/.*)` only matched dotfiles and the gate never ran. The input
|
|
21
|
+
* is Claude Code's PostToolUse payload: the path comes absolute in `tool_input.file_path`.
|
|
22
|
+
*
|
|
23
|
+
* Pages detected (path relative to the project root):
|
|
24
|
+
* Flutter lib/presentation/features/{feature}/(page|pages|layouts)/*.dart
|
|
25
|
+
* presentation/pages/[{feature}/]*.dart
|
|
26
|
+
* Web src/pages/[{feature}/]*.{tsx,jsx,ts,js,astro,vue,svelte}
|
|
27
|
+
* Next.js app/**\/page.{tsx,jsx,ts,js} (feature = first segment that is not a group or param)
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { readStdin, fileExists, findFiles } from './lib/utils.mjs';
|
|
31
|
+
import { getProjectConfig } from './lib/config.mjs';
|
|
32
|
+
import { readFileSync } from 'fs';
|
|
33
|
+
import { basename, extname, isAbsolute, join, relative, resolve, sep } from 'path';
|
|
34
|
+
|
|
35
|
+
let payload = {};
|
|
36
|
+
try {
|
|
37
|
+
payload = JSON.parse(readStdin() || '{}');
|
|
38
|
+
} catch {
|
|
39
|
+
process.exit(0);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const toolInput = payload.tool_input ?? payload.toolInput ?? {};
|
|
43
|
+
const filePath = toolInput.file_path || payload.file_path || '';
|
|
44
|
+
if (!filePath) process.exit(0);
|
|
45
|
+
|
|
46
|
+
const root = resolve(payload.cwd || process.cwd());
|
|
47
|
+
const rel = (isAbsolute(filePath) ? relative(root, filePath) : filePath).split(sep).join('/');
|
|
48
|
+
if (!rel || rel.startsWith('../')) process.exit(0);
|
|
49
|
+
|
|
50
|
+
/** The feature a UI page belongs to, or '' when the file is not a page. */
|
|
51
|
+
function pageFeature(path) {
|
|
52
|
+
const stem = (p) => basename(p, extname(p));
|
|
53
|
+
let m = path.match(/(?:^|\/)presentation\/features\/([^/]+)\/(?:page|pages|layouts)\/[^/]+\.dart$/);
|
|
54
|
+
if (m) return m[1];
|
|
55
|
+
m = path.match(/(?:^|\/)presentation\/pages\/(?:([^/]+)\/)?([^/]+)\.dart$/);
|
|
56
|
+
if (m) return m[1] || stem(m[2]);
|
|
57
|
+
m = path.match(/(?:^|\/)src\/pages\/(?:([^/]+)\/)?([^/]+)\.(?:tsx|jsx|ts|js|astro|vue|svelte)$/);
|
|
58
|
+
if (m) return m[1] || stem(m[2]);
|
|
59
|
+
m = path.match(/(?:^|\/)app\/((?:[^/]+\/)*)page\.(?:tsx|jsx|ts|js)$/);
|
|
60
|
+
if (m) {
|
|
61
|
+
const segment = m[1].split('/').find((s) => s && !/^[([@]/.test(s));
|
|
62
|
+
return segment || 'index';
|
|
63
|
+
}
|
|
64
|
+
return '';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const feature = pageFeature(rel);
|
|
68
|
+
if (!feature) process.exit(0);
|
|
69
|
+
|
|
70
|
+
// Pieces of the Claude Design canvas engine: the page would not work outside the canvas.
|
|
71
|
+
const ENGINE_TRACES = [
|
|
72
|
+
['support.js', /\bsupport\.js\b/],
|
|
73
|
+
['<x-dc>', /<x-dc[\s>]/i],
|
|
74
|
+
['DCLogic', /\bDCLogic\b/],
|
|
75
|
+
['<sc-for>', /<sc-for[\s>]/i],
|
|
76
|
+
['<sc-if>', /<sc-if[\s>]/i],
|
|
77
|
+
['<dc-import>', /<dc-import[\s>]/i],
|
|
78
|
+
['<x-import>', /<x-import[\s>]/i],
|
|
79
|
+
['/_blob/', /\/_blob\/[0-9a-f]{8,}/],
|
|
80
|
+
];
|
|
81
|
+
const written = resolve(root, rel);
|
|
82
|
+
if (fileExists(written)) {
|
|
83
|
+
let text = '';
|
|
84
|
+
try { text = readFileSync(written, 'utf-8'); } catch { /* unreadable: nothing to say */ }
|
|
85
|
+
const traces = ENGINE_TRACES.filter(([, re]) => re.test(text)).map(([name]) => name);
|
|
86
|
+
if (traces.length) {
|
|
87
|
+
process.stderr.write(
|
|
88
|
+
[
|
|
89
|
+
`PUERTA DE DISEÑO: ${rel} lleva piezas del motor del lienzo de Claude Design (${traces.join(', ')}).`,
|
|
90
|
+
'Esa página solo funciona dentro del lienzo. El design-to-code parte de la vista congelada',
|
|
91
|
+
`(doc/design/${feature}/{artboard}.html, de /design-review import) y produce código del stack,`,
|
|
92
|
+
'con los valores de los tokens del sistema. Quita esas piezas antes de seguir.',
|
|
93
|
+
'',
|
|
94
|
+
].join('\n'),
|
|
95
|
+
);
|
|
96
|
+
process.exit(2);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Multi-repo: the designs may live in the orchestrator repo.
|
|
101
|
+
const { orchestratorRoot } = getProjectConfig();
|
|
102
|
+
const designDir = resolve(root, orchestratorRoot, 'doc', 'design', feature);
|
|
103
|
+
const shownDir = relative(root, designDir).split(sep).join('/') || '.';
|
|
104
|
+
// `page.tsx` and `index.tsx` say nothing: the screen is then named after its feature.
|
|
105
|
+
const stem = basename(rel, extname(rel));
|
|
106
|
+
const screen = ['page', 'index'].includes(stem) ? feature : stem;
|
|
107
|
+
|
|
108
|
+
// A canvas source (`.dc.html`) is not a design on its own: it needs the canvas engine.
|
|
109
|
+
if (findFiles(designDir, /\.html$/).filter((f) => !f.endsWith('.dc.html')).length === 0) {
|
|
110
|
+
process.stderr.write(
|
|
111
|
+
[
|
|
112
|
+
`PUERTA DE DISEÑO: ${rel} es una página de interfaz y la feature «${feature}» no tiene diseño`,
|
|
113
|
+
`(no hay ningún HTML en ${shownDir}/).`,
|
|
114
|
+
'La escritura ya está hecha. Antes de seguir con esta pantalla:',
|
|
115
|
+
` 1. /design-review brief ${screen} y /design-review direction ${screen}: para quién es y qué dirección toma.`,
|
|
116
|
+
' 2. Genera el candidato con la cadena de /plan (Paso 6); dentro de /implement, con su Paso 3.3.',
|
|
117
|
+
' 3. Implementa desde ese diseño, con colores, tipografía y espaciado de los tokens del sistema (D18).',
|
|
118
|
+
'Si esta página no necesita diseño (un cambio menor en una pantalla que ya existe), dilo al usuario.',
|
|
119
|
+
'',
|
|
120
|
+
].join('\n'),
|
|
121
|
+
);
|
|
122
|
+
process.exit(2);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Design exists: the page should say which design it comes from (AG-08 Check 6). A note, not a block.
|
|
126
|
+
if (fileExists(written)) {
|
|
127
|
+
try {
|
|
128
|
+
const head = readFileSync(written, 'utf-8').split('\n').slice(0, 10).join('\n');
|
|
129
|
+
if (!head.includes('Generated from: doc/design/')) {
|
|
130
|
+
process.stdout.write(
|
|
131
|
+
JSON.stringify({
|
|
132
|
+
hookSpecificOutput: {
|
|
133
|
+
hookEventName: 'PostToolUse',
|
|
134
|
+
additionalContext:
|
|
135
|
+
`Trazabilidad de diseño: ${rel} no dice de qué diseño sale. Añade en sus 10 primeras líneas ` +
|
|
136
|
+
`«// Generated from: doc/design/${feature}/{pantalla}.html» (AG-08, Check 6).`,
|
|
137
|
+
},
|
|
138
|
+
}),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
} catch { /* unreadable: nothing to say */ }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
process.exit(0);
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* design-review-gate.mjs — PreToolUse hook before an implementation goes to review
|
|
4
|
+
* (US-91 · UC-9102).
|
|
5
|
+
*
|
|
6
|
+
* Triggers:
|
|
7
|
+
* - mcp__SpecBox-MCP__move_uc with target "review" or "done"
|
|
8
|
+
* - mcp__SpecBox-MCP__complete_uc
|
|
9
|
+
* - Bash `gh pr create`
|
|
10
|
+
*
|
|
11
|
+
* Reads the verdict of each screen verification changed on the branch
|
|
12
|
+
* (doc/design/{feature}/{screen}.verify.md, written by /design-review verify and /implement
|
|
13
|
+
* Paso 6.5) and applies the project's mode:
|
|
14
|
+
*
|
|
15
|
+
* `.claude/settings.local.json` → `specbox.design_review.mode`
|
|
16
|
+
* warn — (default) the verdict goes to the PR and the evidence; nothing stops here
|
|
17
|
+
* block — a «Block» verdict stops the transition (exit 2) with the screens and their
|
|
18
|
+
* three priority problems
|
|
19
|
+
* off — no check
|
|
20
|
+
*
|
|
21
|
+
* Changing the mode never requires touching the skill.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { existsSync, readFileSync } from 'fs';
|
|
25
|
+
import { join } from 'path';
|
|
26
|
+
import { readStdin, git, readJsonFile } from './lib/utils.mjs';
|
|
27
|
+
|
|
28
|
+
let payload = {};
|
|
29
|
+
try {
|
|
30
|
+
payload = JSON.parse(readStdin() || '{}');
|
|
31
|
+
} catch {
|
|
32
|
+
process.exit(0);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const toolName = payload.tool_name || payload.toolName || '';
|
|
36
|
+
const toolInput = payload.tool_input ?? payload.toolInput ?? {};
|
|
37
|
+
|
|
38
|
+
function goesToReview() {
|
|
39
|
+
if (/move_uc$/.test(toolName)) return ['review', 'done'].includes(String(toolInput.target || '').toLowerCase());
|
|
40
|
+
if (/complete_uc$/.test(toolName)) return true;
|
|
41
|
+
if (toolName === 'Bash') return /\bgh\s+pr\s+create\b/.test(String(toolInput.command || ''));
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (!goesToReview()) process.exit(0);
|
|
46
|
+
|
|
47
|
+
const root = git('rev-parse --show-toplevel') || payload.cwd || process.cwd();
|
|
48
|
+
const settings = readJsonFile(join(root, '.claude', 'settings.local.json')) || {};
|
|
49
|
+
const mode = settings?.specbox?.design_review?.mode;
|
|
50
|
+
if (mode !== 'block') process.exit(0);
|
|
51
|
+
|
|
52
|
+
function changedVerifications() {
|
|
53
|
+
const run = (args) => git(`-C "${root}" ${args}`);
|
|
54
|
+
let base = '';
|
|
55
|
+
for (const ref of ['origin/main', 'origin/master', 'main', 'master']) {
|
|
56
|
+
base = run(`merge-base HEAD ${ref}`);
|
|
57
|
+
if (base) break;
|
|
58
|
+
}
|
|
59
|
+
const names = new Set();
|
|
60
|
+
const add = (out) => out.split('\n').map((s) => s.trim()).filter(Boolean).forEach((f) => names.add(f));
|
|
61
|
+
if (base) add(run(`diff --name-only --diff-filter=ACMR ${base}...HEAD`));
|
|
62
|
+
add(run('diff --name-only --diff-filter=ACMR HEAD'));
|
|
63
|
+
add(run('ls-files --others --exclude-standard'));
|
|
64
|
+
return [...names].filter((f) => /(^|\/)doc\/design\/.+\.verify\.md$/.test(f));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Verdict and priority problems of a {screen}.verify.md. */
|
|
68
|
+
function readVerification(rel) {
|
|
69
|
+
const abs = join(root, rel);
|
|
70
|
+
if (!existsSync(abs)) return null;
|
|
71
|
+
const text = readFileSync(abs, 'utf-8');
|
|
72
|
+
const verdict = text.match(/Veredicto:\s*(Block|Needs changes|Approve)\b/i)?.[1] ?? null;
|
|
73
|
+
const section = text.split(/^##\s+Tres problemas prioritarios\s*$/m)[1] ?? '';
|
|
74
|
+
const problems = section.split(/^##\s/m)[0].split('\n').filter((l) => /^\s*\d+\.\s/.test(l)).map((l) => l.trim());
|
|
75
|
+
return { rel, verdict, problems };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const blocked = changedVerifications().map(readVerification).filter((v) => v && /^block$/i.test(v.verdict || ''));
|
|
79
|
+
if (blocked.length === 0) process.exit(0);
|
|
80
|
+
|
|
81
|
+
const lines = [
|
|
82
|
+
'',
|
|
83
|
+
'============================================================',
|
|
84
|
+
' DESIGN REVIEW: hay pantallas con veredicto «Block» — paso a revisión bloqueado',
|
|
85
|
+
'============================================================',
|
|
86
|
+
' El proyecto está en modo bloqueante (specbox.design_review.mode = "block").',
|
|
87
|
+
'',
|
|
88
|
+
];
|
|
89
|
+
for (const v of blocked) {
|
|
90
|
+
lines.push(` ${v.rel}`);
|
|
91
|
+
for (const p of v.problems.slice(0, 3)) lines.push(` ${p}`);
|
|
92
|
+
}
|
|
93
|
+
lines.push(
|
|
94
|
+
'',
|
|
95
|
+
' Qué hacer: aplica la ronda de corrección del Paso 6.5 de /implement (una sola, sin',
|
|
96
|
+
' inventar datos), vuelve a medir con --previous y --sources y actualiza el .verify.md.',
|
|
97
|
+
' Para entregar con el veredicto a la vista, el modo "warn" lo lleva a la PR sin bloquear.',
|
|
98
|
+
'============================================================',
|
|
99
|
+
'',
|
|
100
|
+
);
|
|
101
|
+
process.stderr.write(lines.join('\n'));
|
|
102
|
+
process.exit(2);
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* design-system-gate.mjs — PreToolUse hook before an implementation goes to review
|
|
4
|
+
* (US-49 · UC-4902). BLOCKING in autopilot.
|
|
5
|
+
*
|
|
6
|
+
* Triggers:
|
|
7
|
+
* - mcp__SpecBox-MCP__move_uc with target "review" or "done"
|
|
8
|
+
* - mcp__SpecBox-MCP__complete_uc
|
|
9
|
+
* - Bash `gh pr create`
|
|
10
|
+
*
|
|
11
|
+
* When the project has system tokens (design-system.tokens.json), it scans the
|
|
12
|
+
* UI files changed on the branch (committed since the base branch, plus
|
|
13
|
+
* uncommitted and untracked) for design gaps: colours written directly, fonts
|
|
14
|
+
* outside the system, weights above the system maximum and gradients
|
|
15
|
+
* (lib/design-gaps.mjs, same rules as the engine's get_visual_gap_report).
|
|
16
|
+
*
|
|
17
|
+
* Mode — `.claude/settings.local.json` → `specbox.design_gate.mode`:
|
|
18
|
+
* block — gaps stop the transition (exit 2) with what was found and what to do
|
|
19
|
+
* warn — the same report, without stopping
|
|
20
|
+
* off — no check
|
|
21
|
+
* Default: `block` when `specbox.autopilot.level` is set to anything but `low`
|
|
22
|
+
* (autopilot mode), `warn` otherwise.
|
|
23
|
+
*
|
|
24
|
+
* Without system tokens there is nothing to compare against: the hook passes.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, readFileSync } from 'fs';
|
|
28
|
+
import { join } from 'path';
|
|
29
|
+
import { readStdin, git, readJsonFile } from './lib/utils.mjs';
|
|
30
|
+
import { findSystemTokens, fixFor, isUiSource, scanFiles } from './lib/design-gaps.mjs';
|
|
31
|
+
import { blockWith, noteWith } from './lib/output.mjs';
|
|
32
|
+
|
|
33
|
+
const MAX_LISTED = 40;
|
|
34
|
+
const KIND_LABELS = {
|
|
35
|
+
direct_color: 'color escrito',
|
|
36
|
+
font_outside: 'fuente fuera del sistema',
|
|
37
|
+
weight_above: 'peso por encima del máximo',
|
|
38
|
+
gradient: 'gradiente',
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
let payload = {};
|
|
42
|
+
try {
|
|
43
|
+
payload = JSON.parse(readStdin() || '{}');
|
|
44
|
+
} catch {
|
|
45
|
+
process.exit(0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const toolName = payload.tool_name || payload.toolName || '';
|
|
49
|
+
const toolInput = payload.tool_input ?? payload.toolInput ?? {};
|
|
50
|
+
|
|
51
|
+
function goesToReview() {
|
|
52
|
+
if (/move_uc$/.test(toolName)) return ['review', 'done'].includes(String(toolInput.target || '').toLowerCase());
|
|
53
|
+
if (/complete_uc$/.test(toolName)) return true;
|
|
54
|
+
if (toolName === 'Bash') return /\bgh\s+pr\s+create\b/.test(String(toolInput.command || ''));
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!goesToReview()) process.exit(0);
|
|
59
|
+
|
|
60
|
+
const root = git('rev-parse --show-toplevel') || process.cwd();
|
|
61
|
+
const settings = readJsonFile(join(root, '.claude', 'settings.local.json')) || {};
|
|
62
|
+
|
|
63
|
+
function resolveMode() {
|
|
64
|
+
const mode = settings?.specbox?.design_gate?.mode;
|
|
65
|
+
if (['block', 'warn', 'off'].includes(mode)) return mode;
|
|
66
|
+
const level = settings?.specbox?.autopilot?.level;
|
|
67
|
+
return level && level !== 'low' ? 'block' : 'warn';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const mode = resolveMode();
|
|
71
|
+
if (mode === 'off') process.exit(0);
|
|
72
|
+
|
|
73
|
+
const system = findSystemTokens(root);
|
|
74
|
+
if (!system) process.exit(0);
|
|
75
|
+
if (!system.rules) {
|
|
76
|
+
noteWith('PreToolUse', 'DESIGN GATE (aviso): no se puede comprobar el diseño', [
|
|
77
|
+
`${system.path} no es JSON válido. Arréglalo para que el gate compare la UI con el sistema.`,
|
|
78
|
+
]);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function changedFiles() {
|
|
82
|
+
const run = (args) => git(`-C "${root}" ${args}`);
|
|
83
|
+
let base = '';
|
|
84
|
+
for (const ref of ['origin/main', 'origin/master', 'main', 'master']) {
|
|
85
|
+
base = run(`merge-base HEAD ${ref}`);
|
|
86
|
+
if (base) break;
|
|
87
|
+
}
|
|
88
|
+
const names = new Set();
|
|
89
|
+
const add = (out) => out.split('\n').map((s) => s.trim()).filter(Boolean).forEach((f) => names.add(f));
|
|
90
|
+
if (base) add(run(`diff --name-only --diff-filter=ACMR ${base}...HEAD`));
|
|
91
|
+
add(run('diff --name-only --diff-filter=ACMR HEAD'));
|
|
92
|
+
add(run('ls-files --others --exclude-standard'));
|
|
93
|
+
return [...names];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const files = {};
|
|
97
|
+
for (const rel of changedFiles()) {
|
|
98
|
+
if (!isUiSource(rel)) continue;
|
|
99
|
+
const abs = join(root, rel);
|
|
100
|
+
if (!existsSync(abs)) continue;
|
|
101
|
+
try {
|
|
102
|
+
files[rel] = readFileSync(abs, 'utf-8');
|
|
103
|
+
} catch {
|
|
104
|
+
/* unreadable: skip */
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const gaps = scanFiles(files, system.rules);
|
|
109
|
+
if (gaps.length === 0) process.exit(0);
|
|
110
|
+
|
|
111
|
+
const kinds = [...new Set(gaps.map((g) => g.kind))];
|
|
112
|
+
const lines = [
|
|
113
|
+
`${gaps.length} brecha(s) de diseño en ${Object.keys(files).length} fichero(s) de UI cambiados,`,
|
|
114
|
+
`comparados con los tokens del sistema (${system.path}):`,
|
|
115
|
+
'',
|
|
116
|
+
...gaps.slice(0, MAX_LISTED).map((g) => `${g.location} ${KIND_LABELS[g.kind]}: ${g.value}`),
|
|
117
|
+
];
|
|
118
|
+
if (gaps.length > MAX_LISTED) lines.push(`… y ${gaps.length - MAX_LISTED} más`);
|
|
119
|
+
lines.push('', 'Qué hacer:');
|
|
120
|
+
for (const kind of kinds) lines.push(`- ${KIND_LABELS[kind]}: ${fixFor(kind, system.rules)}`);
|
|
121
|
+
lines.push(
|
|
122
|
+
'- Si un valor es deliberado, marca la línea con `design-gate:ignore` y el motivo;',
|
|
123
|
+
' un fichero de terceros entero, con `design-gate:disable-file`.',
|
|
124
|
+
'- Corrige y vuelve a intentar el paso a revisión: el gate se ejecuta de nuevo.',
|
|
125
|
+
);
|
|
126
|
+
|
|
127
|
+
const title =
|
|
128
|
+
mode === 'block'
|
|
129
|
+
? 'DESIGN GATE: la implementación se sale del sistema — paso a revisión bloqueado'
|
|
130
|
+
: 'DESIGN GATE (aviso): la implementación se sale del sistema';
|
|
131
|
+
// Block: the transition does not happen and the agent gets the reason. Warn: a note to the agent
|
|
132
|
+
// (it was written to stdout, which nobody sees — US-93/UC-9302).
|
|
133
|
+
if (mode === 'block') blockWith(title, lines);
|
|
134
|
+
noteWith('PreToolUse', title, lines);
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* e2e-gate.mjs — PreToolUse hook for `git commit`
|
|
4
|
+
* BLOCKING (exit 2, before the commit exists): acceptance tests or evidence go into the commit and
|
|
5
|
+
* the evidence does not meet the contract:
|
|
6
|
+
* 1. results.json exists and passes schema validation
|
|
7
|
+
* 2. e2e-evidence-report.html exists and has real content
|
|
8
|
+
* 3. Evidence files referenced in results.json actually exist
|
|
9
|
+
* Acceptance tests committed before running them (no evidence yet) pass.
|
|
10
|
+
*
|
|
11
|
+
* v5.12.0 — E2E Evidence Quality Gate · US-93/UC-9302: runs before the commit (after it, the
|
|
12
|
+
* staging area was empty and the gate never acted) and its reason reaches the agent.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { readHookInput, gitDirForCommand, git, commitFiles, fileExists, findFiles, readJsonFile } from './lib/utils.mjs';
|
|
16
|
+
import { getProjectConfig } from './lib/config.mjs';
|
|
17
|
+
import { blockWith } from './lib/output.mjs';
|
|
18
|
+
import { spawnSync } from 'child_process';
|
|
19
|
+
import { dirname, join } from 'path';
|
|
20
|
+
import { readFileSync } from 'fs';
|
|
21
|
+
|
|
22
|
+
const { toolInput, cwd } = readHookInput();
|
|
23
|
+
const command = String(toolInput.command || '');
|
|
24
|
+
if (command && !/\bgit\b[^;&|]*\bcommit\b/.test(command)) process.exit(0);
|
|
25
|
+
try {
|
|
26
|
+
process.chdir(gitDirForCommand(command, cwd));
|
|
27
|
+
} catch {
|
|
28
|
+
process.exit(0);
|
|
29
|
+
}
|
|
30
|
+
if (!git('rev-parse --show-toplevel')) process.exit(0);
|
|
31
|
+
|
|
32
|
+
const files = commitFiles(command);
|
|
33
|
+
const hasAcceptanceFiles = files.some((f) => /(test\/acceptance\/|tests\/acceptance\/|e2e\/acceptance\/|e2e\/.*\.spec\.)/.test(f));
|
|
34
|
+
const hasEvidenceFiles = files.some((f) => /\.quality\/evidence\/.*\/acceptance\//.test(f));
|
|
35
|
+
if (!hasAcceptanceFiles && !hasEvidenceFiles) process.exit(0);
|
|
36
|
+
|
|
37
|
+
const activeUC = readJsonFile('.quality/active_uc.json')?.uc_id || '';
|
|
38
|
+
const resultsFiles = findFiles('.quality/evidence', /^results\.json$/, 'acceptance');
|
|
39
|
+
|
|
40
|
+
if (resultsFiles.length === 0) {
|
|
41
|
+
// Only acceptance tests, no evidence yet (AG-09a writing tests before running them): allowed.
|
|
42
|
+
if (!hasEvidenceFiles) process.exit(0);
|
|
43
|
+
blockWith('E2E GATE: evidencia sin results.json', [
|
|
44
|
+
'El commit lleva ficheros de evidencia pero no hay ningún results.json.',
|
|
45
|
+
'Se espera: .quality/evidence/{feature}/acceptance/results.json',
|
|
46
|
+
'Para arreglarlo: ejecuta las pruebas de aceptación (Playwright lo genera solo; Patrol y Python,',
|
|
47
|
+
'con patrol-evidence-generator.js o api-evidence-generator.js).',
|
|
48
|
+
]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Multi-repo: the validator may live in the orchestrator repo.
|
|
52
|
+
const { orchestratorRoot } = getProjectConfig();
|
|
53
|
+
const VALIDATOR = ['.quality/scripts/validate-results-json.js', join(orchestratorRoot, '.quality/scripts/validate-results-json.js')]
|
|
54
|
+
.find((p) => fileExists(p));
|
|
55
|
+
if (!VALIDATOR) {
|
|
56
|
+
blockWith('E2E GATE: no está el validador', [
|
|
57
|
+
'Falta .quality/scripts/validate-results-json.js: ejecuta install.sh o cópialo del engine.',
|
|
58
|
+
]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const errors = [];
|
|
62
|
+
for (const resultsFile of resultsFiles) {
|
|
63
|
+
const evidenceDir = dirname(resultsFile);
|
|
64
|
+
let relevant = files.some((f) => f.includes(evidenceDir));
|
|
65
|
+
if (!relevant && activeUC) {
|
|
66
|
+
try {
|
|
67
|
+
relevant = readFileSync(resultsFile, 'utf-8').includes(activeUC);
|
|
68
|
+
} catch { /* unreadable: not relevant */ }
|
|
69
|
+
}
|
|
70
|
+
if (!relevant) continue;
|
|
71
|
+
const res = spawnSync(process.execPath, [VALIDATOR, resultsFile, '--check-evidence'], { encoding: 'utf-8' });
|
|
72
|
+
if (res.status !== 0) errors.push(`${resultsFile}:`, ...`${res.stdout || ''}${res.stderr || ''}`.trim().split('\n').slice(-15).map((l) => ` ${l}`));
|
|
73
|
+
const htmlReport = join(evidenceDir, 'e2e-evidence-report.html');
|
|
74
|
+
if (!fileExists(htmlReport)) errors.push(`Falta el HTML Evidence Report: ${htmlReport}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (errors.length) {
|
|
78
|
+
blockWith('E2E GATE: la evidencia de aceptación no es válida', [
|
|
79
|
+
...errors,
|
|
80
|
+
'',
|
|
81
|
+
'Para arreglarlo: results.json según doc/specs/results-json-spec.md, e2e-evidence-report.html presente',
|
|
82
|
+
'y los ficheros de evidencia que cita results.json existentes. Comprueba con:',
|
|
83
|
+
'node .quality/scripts/validate-results-json.js <results.json> --check-evidence',
|
|
84
|
+
]);
|
|
85
|
+
}
|
|
86
|
+
process.exit(0);
|