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.
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 +4 -2
@@ -0,0 +1,235 @@
1
+ /**
2
+ * lib/utils.mjs — Core utilities for SpecBox Engine hooks (cross-platform)
3
+ * Zero external dependencies. Node.js 18+ built-in modules only.
4
+ */
5
+
6
+ import { readFileSync, existsSync, statSync, mkdirSync, appendFileSync, readdirSync } from 'fs';
7
+ import { basename, join, resolve, dirname } from 'path';
8
+ import { execSync } from 'child_process';
9
+ import { fileURLToPath } from 'url';
10
+
11
+ /**
12
+ * Read all of stdin synchronously (fd 0).
13
+ * Claude Code passes tool input as JSON via stdin.
14
+ */
15
+ export function readStdin() {
16
+ try {
17
+ return readFileSync(0, 'utf-8');
18
+ } catch {
19
+ return '';
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Execute a git command and return trimmed stdout.
25
+ * Returns '' on any error (not a git repo, command fails, etc.)
26
+ */
27
+ /**
28
+ * La entrada de un hook tal como la manda Claude Code: { event, toolName, toolInput, cwd, payload }.
29
+ * Los argumentos de la herramienta van en tool_input; el nivel superior es el formato antiguo de
30
+ * las pruebas de humo y se acepta como respaldo.
31
+ */
32
+ export function readHookInput(raw = readStdin()) {
33
+ let payload = {};
34
+ try {
35
+ payload = JSON.parse(raw || '{}');
36
+ } catch {
37
+ payload = {};
38
+ }
39
+ const toolInput = payload.tool_input ?? payload.toolInput ?? payload;
40
+ return {
41
+ event: payload.hook_event_name || '',
42
+ toolName: payload.tool_name || payload.toolName || '',
43
+ toolInput: toolInput && typeof toolInput === 'object' ? toolInput : {},
44
+ cwd: payload.cwd || process.cwd(),
45
+ payload,
46
+ };
47
+ }
48
+
49
+ /**
50
+ * The repo a git command acts on: the directory of `git -C <dir>` or of the last `cd <dir>` before
51
+ * the git command, resolved against the session's cwd; otherwise the cwd. A hook that checks the
52
+ * branch or the staged files must look there, not at the session's directory.
53
+ */
54
+ export function gitDirForCommand(command, cwd = process.cwd(), gitVerb = 'commit') {
55
+ const unquote = (s) => s.replace(/^["']|["']$/g, '');
56
+ const at = command.search(new RegExp(`\\bgit\\b[^;&|]*\\b${gitVerb}\\b`));
57
+ if (at < 0) return cwd;
58
+ const gitPart = command.slice(at).match(/^git\s+-C\s+("[^"]+"|'[^']+'|\S+)/);
59
+ let dir = cwd;
60
+ const before = command.slice(0, at);
61
+ for (const m of before.matchAll(/(?:^|&&|;|\|\|)\s*cd\s+("[^"]+"|'[^']+'|\S+)/g)) dir = resolve(dir, unquote(m[1]));
62
+ if (gitPart) dir = resolve(dir, unquote(gitPart[1]));
63
+ return dir;
64
+ }
65
+
66
+ /**
67
+ * The files a `git commit` command will commit, seen from a PreToolUse hook (before it runs): the
68
+ * staged ones, the tracked changes with `commit -a`/`--all`, and what a `git add` earlier in the
69
+ * same command will stage. Paths relative to the repo; run it after chdir to the repo.
70
+ */
71
+ export function commitFiles(command) {
72
+ const lines = (out) => out.split('\n').map((s) => s.trim()).filter(Boolean);
73
+ const files = new Set(lines(git('diff --cached --name-only --diff-filter=ACMR')));
74
+ const at = command.search(/\bgit\b[^;&|]*\bcommit\b/);
75
+ const commitPart = at >= 0 ? command.slice(at) : '';
76
+ if (/\scommit\b[^;&|]*\s(-[a-zA-Z]*a[a-zA-Z]*|--all)\b/.test(commitPart)) {
77
+ for (const f of lines(git('diff --name-only --diff-filter=ACMR HEAD'))) files.add(f);
78
+ }
79
+ for (const m of command.matchAll(/\bgit\s+add\s+([^;&|]*)/g)) {
80
+ const args = m[1].trim().split(/\s+/).filter(Boolean);
81
+ if (args.some((a) => ['-A', '--all', '.', '-u', '--update'].includes(a))) {
82
+ for (const f of lines(git('diff --name-only --diff-filter=ACMR HEAD'))) files.add(f);
83
+ for (const f of lines(git('ls-files --others --exclude-standard'))) files.add(f);
84
+ } else {
85
+ for (const a of args.filter((x) => !x.startsWith('-'))) files.add(a.replace(/^["']|["']$/g, ''));
86
+ }
87
+ }
88
+ return [...files];
89
+ }
90
+
91
+ export function git(cmd) {
92
+ try {
93
+ return execSync(`git ${cmd}`, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
94
+ } catch {
95
+ return '';
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Read and parse a JSON file. Returns null if missing or invalid.
101
+ */
102
+ export function readJsonFile(filePath) {
103
+ if (!existsSync(filePath)) return null;
104
+ try {
105
+ return JSON.parse(readFileSync(filePath, 'utf-8'));
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Check if a file exists.
113
+ */
114
+ export function fileExists(filePath) {
115
+ return existsSync(filePath);
116
+ }
117
+
118
+ /**
119
+ * Get file age in seconds. Returns Infinity if file doesn't exist.
120
+ */
121
+ export function fileAge(filePath) {
122
+ if (!existsSync(filePath)) return Infinity;
123
+ try {
124
+ return (Date.now() - statSync(filePath).mtimeMs) / 1000;
125
+ } catch {
126
+ return Infinity;
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Recursively find files matching a name pattern and optional path substring.
132
+ * Cross-platform — no shell commands.
133
+ *
134
+ * @param {string} dir - Root directory to search
135
+ * @param {RegExp|string} namePattern - Regex or string to match filename
136
+ * @param {string} [pathContains] - Optional substring the full path must contain
137
+ * @returns {string[]} Array of matching full paths
138
+ */
139
+ export function findFiles(dir, namePattern, pathContains) {
140
+ const results = [];
141
+ if (!existsSync(dir)) return results;
142
+
143
+ const regex = typeof namePattern === 'string' ? new RegExp(namePattern) : namePattern;
144
+
145
+ function walk(current) {
146
+ let entries;
147
+ try {
148
+ entries = readdirSync(current, { withFileTypes: true });
149
+ } catch {
150
+ return;
151
+ }
152
+ for (const entry of entries) {
153
+ const fullPath = join(current, entry.name);
154
+ if (entry.isDirectory()) {
155
+ walk(fullPath);
156
+ } else if (entry.isFile()) {
157
+ if (regex.test(entry.name)) {
158
+ if (!pathContains || fullPath.includes(pathContains)) {
159
+ results.push(fullPath);
160
+ }
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ walk(dir);
167
+ return results;
168
+ }
169
+
170
+ /**
171
+ * Create directory recursively (like mkdir -p).
172
+ */
173
+ export function mkdir(dir) {
174
+ mkdirSync(dir, { recursive: true });
175
+ }
176
+
177
+ /**
178
+ * Append a line to a file (for JSONL logging).
179
+ * Creates parent directories if needed.
180
+ */
181
+ export function appendLine(filePath, line) {
182
+ const dir = dirname(filePath);
183
+ if (!existsSync(dir)) {
184
+ mkdirSync(dir, { recursive: true });
185
+ }
186
+ appendFileSync(filePath, line + '\n', 'utf-8');
187
+ }
188
+
189
+ /**
190
+ * Get the project name from git root, replacing underscores with hyphens.
191
+ */
192
+ export function getProjectName() {
193
+ const root = git('rev-parse --show-toplevel');
194
+ if (!root) return 'unknown';
195
+ return basename(root).replace(/_/g, '-');
196
+ }
197
+
198
+ /**
199
+ * Current UTC timestamp in ISO 8601 format.
200
+ */
201
+ export function now() {
202
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
203
+ }
204
+
205
+ /**
206
+ * Check if a command exists on the system (cross-platform).
207
+ * Uses 'which' on Unix, 'where' on Windows.
208
+ */
209
+ export function commandExists(cmd) {
210
+ try {
211
+ const checker = process.platform === 'win32' ? 'where' : 'which';
212
+ execSync(`${checker} ${cmd}`, { stdio: ['pipe', 'pipe', 'pipe'] });
213
+ return true;
214
+ } catch {
215
+ return false;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Resolve the engine root directory (two levels up from hooks/).
221
+ */
222
+ export function getEngineRoot() {
223
+ const __filename = fileURLToPath(import.meta.url);
224
+ const __dirname = dirname(__filename);
225
+ return resolve(__dirname, '..', '..', '..');
226
+ }
227
+
228
+ /**
229
+ * Resolve the hooks directory.
230
+ */
231
+ export function getHooksDir() {
232
+ const __filename = fileURLToPath(import.meta.url);
233
+ const __dirname = dirname(__filename);
234
+ return resolve(__dirname, '..');
235
+ }
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * no-bypass-guard.mjs — PreToolUse hook for Bash
4
+ * BLOCKING: stops the agent from skipping the quality checks or rewriting history
5
+ * before the command runs (exit 2: the command does not run and the agent gets the reason).
6
+ *
7
+ * --no-verify skips the git hooks of the project
8
+ * push --force / -f / +ref overwrites the remote branch; --force-with-lease and
9
+ * --force-if-includes are allowed (they refuse to overwrite work
10
+ * the agent has not seen, and the rebase flow needs them)
11
+ * reset --hard throws away uncommitted changes
12
+ *
13
+ * v5.12.0 — Agent Quality Guardrails · US-93/UC-9302: blocks for real (it exited 1, which
14
+ * Claude Code treats as a non-blocking error) and lets --force-with-lease through.
15
+ */
16
+
17
+ import { readHookInput } from './lib/utils.mjs';
18
+ import { blockWith } from './lib/output.mjs';
19
+
20
+ const { toolInput } = readHookInput();
21
+ const command = String(toolInput.command || '');
22
+ if (!command) process.exit(0);
23
+
24
+ /** The arguments of each `git push` in the command (a compound command can have several). */
25
+ function pushArgs(cmd) {
26
+ const out = [];
27
+ for (const m of cmd.matchAll(/\bpush\b([^;&|]*)/g)) out.push(m[1].trim().split(/\s+/).filter(Boolean));
28
+ return out;
29
+ }
30
+
31
+ /** Whether a push rewrites the remote without a safety check. */
32
+ function isForcePush(cmd) {
33
+ return pushArgs(cmd).some((args) =>
34
+ args.some((a) =>
35
+ a === '--force'
36
+ || (a.startsWith('--force') && !/^--force-(with-lease|if-includes)\b/.test(a))
37
+ || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(a)
38
+ || /^\+[^\s]/.test(a)));
39
+ }
40
+
41
+ let reason = '';
42
+ let instead = '';
43
+ if (/(^|\s)--no-verify(\s|$)/.test(command)) {
44
+ reason = '--no-verify se salta las comprobaciones del proyecto (lint, evidencia, guardias de spec).';
45
+ instead = 'Corrige lo que la comprobación señala en vez de saltártela. Si de verdad hay que saltarla, pídeselo a la persona.';
46
+ } else if (isForcePush(command)) {
47
+ reason = 'Un push forzado sobrescribe la rama remota, también el trabajo que otras sesiones han subido.';
48
+ instead = 'Usa --force-with-lease (se niega si el remoto tiene algo que no has visto) o un commit nuevo.';
49
+ } else if (/\breset\s+(.*\s)?--hard\b/.test(command)) {
50
+ reason = 'reset --hard tira los cambios sin guardar y no se pueden recuperar.';
51
+ instead = "Guarda antes con un commit o con 'git stash', o pídele a la persona que lo haga ella.";
52
+ }
53
+
54
+ if (reason) {
55
+ blockWith('GUARDIA DE CALIDAD: orden bloqueada', [`Orden: ${command}`, `Por qué: ${reason}`, `En su lugar: ${instead}`]);
56
+ }
57
+ process.exit(0);
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * on-session-end.mjs — Stop hook: logs session telemetry
4
+ * NON-BLOCKING: Records session metrics and reports to MCP + Engram.
5
+ */
6
+
7
+ import { git, mkdir, now, findFiles, commandExists } from './lib/utils.mjs';
8
+ import { appendLine, fileExists } from './lib/utils.mjs';
9
+ import { spawn } from 'child_process';
10
+ import { readFileSync, statSync } from 'fs';
11
+ import { join, basename, dirname } from 'path';
12
+
13
+ const LOGS_DIR = '.quality/logs';
14
+ mkdir(LOGS_DIR);
15
+
16
+ const timestamp = now();
17
+ const date = timestamp.slice(0, 10); // YYYY-MM-DD
18
+ const LOG_FILE = join(LOGS_DIR, `sessions_${date}.jsonl`);
19
+
20
+ // Count files modified in this session (git-tracked changes)
21
+ const diffOutput = git('diff --name-only HEAD');
22
+ const filesModified = diffOutput ? diffOutput.split('\n').filter(Boolean).length : 0;
23
+
24
+ // Estimate context loaded (sum of modified + staged files in chars)
25
+ let contextChars = 0;
26
+ const allChangedFiles = new Set();
27
+ if (diffOutput) diffOutput.split('\n').filter(Boolean).forEach(f => allChangedFiles.add(f));
28
+ const cachedOutput = git('diff --cached --name-only');
29
+ if (cachedOutput) cachedOutput.split('\n').filter(Boolean).forEach(f => allChangedFiles.add(f));
30
+
31
+ for (const f of allChangedFiles) {
32
+ if (fileExists(f)) {
33
+ try {
34
+ const chars = readFileSync(f, 'utf-8').length;
35
+ contextChars += chars;
36
+ } catch { /* ignore */ }
37
+ }
38
+ }
39
+ const contextTokens = Math.floor(contextChars / 4);
40
+
41
+ // Count healing events if evidence exists
42
+ let healingEvents = 0;
43
+ const healingFiles = findFiles('.quality/evidence', /^healing\.jsonl$/);
44
+ if (healingFiles.length > 0) {
45
+ try {
46
+ const content = readFileSync(healingFiles[0], 'utf-8');
47
+ healingEvents = content.split('\n').filter(Boolean).length;
48
+ } catch { /* ignore */ }
49
+ }
50
+
51
+ // Check for checkpoint (active implementation)
52
+ let activeFeature = '';
53
+ const checkpointFiles = findFiles('.quality/evidence', /^checkpoint\.json$/);
54
+ if (checkpointFiles.length > 0) {
55
+ // Find checkpoints newer than the log file
56
+ const logMtime = fileExists(LOG_FILE) ? statSync(LOG_FILE).mtimeMs : 0;
57
+ for (const cp of checkpointFiles) {
58
+ try {
59
+ if (statSync(cp).mtimeMs > logMtime) {
60
+ activeFeature = basename(dirname(cp));
61
+ break;
62
+ }
63
+ } catch { /* ignore */ }
64
+ }
65
+ }
66
+
67
+ // Write session log
68
+ const logEntry = JSON.stringify({
69
+ event: 'session_end',
70
+ timestamp,
71
+ pwd: process.cwd(),
72
+ files_modified: filesModified,
73
+ context_tokens_est: contextTokens,
74
+ healing_events: healingEvents,
75
+ active_feature: activeFeature,
76
+ });
77
+ appendLine(LOG_FILE, logEntry);
78
+
79
+ console.log(`[TELEMETRY] Session logged to ${LOG_FILE} (est. ${contextTokens} tokens, ${filesModified} files)`);
80
+
81
+ // Persist session summary to Engram (REQUERIDO)
82
+ // v5.30.0: structured JSON payload + branch-scoped topic key, replacing the
83
+ // free-form string used in v5.29.x. Old observations remain readable; new
84
+ // sessions can be filtered with `mem_search "session:<project>:<branch>"`.
85
+ if (commandExists('engram')) {
86
+ const projectSlug = basename(process.cwd()).replace(/_/g, '-');
87
+ const branch = git('branch --show-current') || 'unknown';
88
+ const handoffPath = '.quality/handoff.md';
89
+ const handoffPresent = fileExists(handoffPath);
90
+ const payload = {
91
+ type: 'session_end',
92
+ schema_version: 1,
93
+ project: projectSlug,
94
+ branch,
95
+ ended_at: timestamp,
96
+ files_modified: filesModified,
97
+ context_tokens_est: contextTokens,
98
+ healing_events: healingEvents,
99
+ active_feature: activeFeature,
100
+ handoff_path: handoffPresent ? handoffPath : null,
101
+ };
102
+ const topicKey = `session:${projectSlug}:${branch}`;
103
+ const engramChild = spawn('engram', ['save', topicKey, JSON.stringify(payload)], {
104
+ detached: true,
105
+ stdio: 'ignore',
106
+ });
107
+ engramChild.unref();
108
+ console.log(`[ENGRAM] Session summary persisted (topic: ${topicKey}, handoff: ${handoffPresent ? 'present' : 'none'})`);
109
+ } else {
110
+ // Detect OS and suggest appropriate install method
111
+ console.log('');
112
+ console.log('============================================================');
113
+ console.log(' ERROR: ENGRAM NO INSTALADO');
114
+ console.log('============================================================');
115
+ console.log(' Engram es requerido para la memoria persistente del engine.');
116
+ console.log(' Sin el, las compactaciones de contexto causan perdida de estado.');
117
+ console.log('');
118
+
119
+ switch (process.platform) {
120
+ case 'darwin':
121
+ console.log(' SO detectado: macOS');
122
+ console.log('');
123
+ console.log(' Instalar:');
124
+ console.log(' # Apple Silicon (M1/M2/M3/M4):');
125
+ console.log(' curl -sL https://github.com/Gentleman-Programming/engram/releases/latest/download/engram_1.7.1_darwin_arm64.tar.gz | tar xz');
126
+ console.log(' # Intel:');
127
+ console.log(' curl -sL https://github.com/Gentleman-Programming/engram/releases/latest/download/engram_1.7.1_darwin_amd64.tar.gz | tar xz');
128
+ console.log(' mv engram ~/.local/bin/');
129
+ break;
130
+ case 'linux':
131
+ console.log(' SO detectado: Linux');
132
+ console.log('');
133
+ console.log(' Instalar:');
134
+ console.log(' # x86_64:');
135
+ console.log(' curl -sL https://github.com/Gentleman-Programming/engram/releases/latest/download/engram_1.7.1_linux_amd64.tar.gz | tar xz');
136
+ console.log(' # arm64:');
137
+ console.log(' curl -sL https://github.com/Gentleman-Programming/engram/releases/latest/download/engram_1.7.1_linux_arm64.tar.gz | tar xz');
138
+ console.log(' mv engram ~/.local/bin/');
139
+ break;
140
+ case 'win32':
141
+ console.log(' SO detectado: Windows');
142
+ console.log('');
143
+ console.log(' Instalar:');
144
+ console.log(' Descargar desde: https://github.com/Gentleman-Programming/engram/releases/latest');
145
+ console.log(' Archivo: engram_1.7.1_windows_amd64.zip o engram_1.7.1_windows_arm64.zip');
146
+ console.log(' Descomprimir y mover engram.exe a una carpeta en el PATH');
147
+ break;
148
+ default:
149
+ console.log(` SO detectado: ${process.platform}`);
150
+ console.log('');
151
+ console.log(' Descargar desde: https://github.com/Gentleman-Programming/engram/releases/latest');
152
+ break;
153
+ }
154
+
155
+ console.log('');
156
+ console.log(' Verificar: engram save "test" "hello engram"');
157
+ console.log(' MCP config: .vscode/mcp.json');
158
+ console.log('============================================================');
159
+ console.log('');
160
+ }
161
+
162
+ // v6.1.0 Cloud Cutover: remote heartbeat + mcp-report dispatch removed.
163
+ // Local telemetry (.quality/logs/, Engram) still recorded above.
@@ -0,0 +1,140 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pipeline-phase-guard.mjs — PreToolUse hook for Write/Edit during /implement
4
+ * BLOCKING (exit 2; US-93/UC-9302 — it exited 1 and read the path from the wrong place, so it
5
+ * never blocked): prevents the agent from writing code that belongs to a phase
6
+ * whose dependencies haven't been completed yet.
7
+ *
8
+ * Reads .quality/evidence/{feature}/checkpoint.json to determine current phase.
9
+ * Validates that prerequisite phases are complete before allowing writes
10
+ * that belong to subsequent phases.
11
+ *
12
+ * Phase dependency map (from /implement SKILL.md):
13
+ * Phase 1: DB/Infra → no dependencies
14
+ * Phase 2: Stitch Designs → no dependencies
15
+ * Phase 3: Design-to-Code → requires Phase 2 (if UI project)
16
+ * Phase 4: Feature Code → requires Phase 1 (if DB), Phase 3 (if UI)
17
+ * Phase 5: Apps Script / n8n → requires Phase 4
18
+ * Phase 6: Integration / DI → requires Phase 4
19
+ * Phase 7: Quality / Tests → requires Phase 4
20
+ *
21
+ * v5.19.0 — Mechanical Enforcement
22
+ */
23
+
24
+ import { readHookInput, fileExists, readJsonFile } from './lib/utils.mjs';
25
+ import { blockWith } from './lib/output.mjs';
26
+ import { getActiveUC } from './lib/config.mjs';
27
+
28
+ // Claude Code sends the path in tool_input (US-93/UC-9302: it was read from the top level).
29
+ const filePath = String(readHookInput().toolInput.file_path || '');
30
+
31
+ if (!filePath) {
32
+ process.exit(0);
33
+ }
34
+
35
+ // Get active UC
36
+ const activeUC = getActiveUC();
37
+ if (!activeUC || !activeUC.feature) {
38
+ // No active UC → spec-guard handles this
39
+ process.exit(0);
40
+ }
41
+
42
+ const feature = activeUC.feature;
43
+ const checkpointFile = `.quality/evidence/${feature}/checkpoint.json`;
44
+ const pipelineStateFile = `.quality/evidence/${feature}/pipeline_state.json`;
45
+
46
+ // Read pipeline state (written by implement skill at each phase transition)
47
+ const pipelineState = readJsonFile(pipelineStateFile);
48
+ if (!pipelineState) {
49
+ // No pipeline state yet → first phase, allow
50
+ process.exit(0);
51
+ }
52
+
53
+ const completedPhases = pipelineState.completed_phases || [];
54
+
55
+ // Detect what phase this file write belongs to based on path patterns
56
+ const detectedPhase = detectPhaseFromPath(filePath);
57
+ if (!detectedPhase) {
58
+ // Can't determine phase from path → allow (conservative)
59
+ process.exit(0);
60
+ }
61
+
62
+ // Check dependencies for the detected phase
63
+ const missingDeps = getMissingDependencies(detectedPhase, completedPhases, pipelineState);
64
+
65
+ if (missingDeps.length > 0) {
66
+ blockWith(`PIPELINE PHASE GUARD — Phase "${detectedPhase}" blocked`, [
67
+ `Feature: ${feature}`,
68
+ `File: ${filePath}`,
69
+ `Detected phase: ${detectedPhase}`,
70
+ `Completed phases: ${completedPhases.join(', ') || '(none)'}`,
71
+ '',
72
+ `Missing prerequisites: ${missingDeps.join(', ')}`,
73
+ '',
74
+ 'The SpecBox pipeline requires phases to execute in order.',
75
+ 'Complete the prerequisite phases before proceeding.',
76
+ '',
77
+ 'Phase order: DB/Infra → Designs → Design-to-Code → Features → Integration → Tests',
78
+ ]);
79
+ }
80
+
81
+ process.exit(0);
82
+
83
+ // --- Helper functions ---
84
+
85
+ /**
86
+ * Detect which implementation phase a file belongs to based on its path.
87
+ * Returns phase name or null if can't determine.
88
+ */
89
+ function detectPhaseFromPath(path) {
90
+ // DB/Infra: migrations, schema, SQL, Supabase functions
91
+ if (/(?:migrations?|schema|\.sql|supabase\/functions|prisma|drizzle)/.test(path)) {
92
+ return 'db_infra';
93
+ }
94
+
95
+ // Design-to-code output: presentation layer, pages, widgets, components
96
+ if (/(?:presentation\/(?:pages|widgets|components)|src\/(?:pages|components|views)|app\/.*page\.)/.test(path)) {
97
+ return 'design_to_code';
98
+ }
99
+
100
+ // Feature code: domain, data, services, models, controllers, handlers
101
+ if (/(?:domain\/|data\/|services\/|models\/|controllers\/|handlers\/|internal\/|cmd\/|api\/)/.test(path)) {
102
+ return 'feature_code';
103
+ }
104
+
105
+ // Integration: DI, providers, routing, app config
106
+ if (/(?:injection|providers?\/|routing|app_router|di\.|container\.)/.test(path)) {
107
+ return 'integration';
108
+ }
109
+
110
+ // Tests
111
+ if (/(?:test\/|tests\/|_test\.|\.test\.|\.spec\.|e2e\/|acceptance\/)/.test(path)) {
112
+ return 'tests';
113
+ }
114
+
115
+ return null;
116
+ }
117
+
118
+ /**
119
+ * Given a target phase, check if all its dependencies are in completedPhases.
120
+ * Returns array of missing dependency names.
121
+ */
122
+ function getMissingDependencies(phase, completedPhases, state) {
123
+ const isUI = state.has_ui !== false; // default true if not specified
124
+ const hasDB = state.has_db === true;
125
+
126
+ const deps = {
127
+ 'db_infra': [],
128
+ 'stitch_designs': [],
129
+ 'design_to_code': isUI ? ['stitch_designs'] : [],
130
+ 'feature_code': [
131
+ ...(hasDB ? ['db_infra'] : []),
132
+ ...(isUI ? ['design_to_code'] : []),
133
+ ],
134
+ 'integration': ['feature_code'],
135
+ 'tests': ['feature_code'],
136
+ };
137
+
138
+ const required = deps[phase] || [];
139
+ return required.filter(dep => !completedPhases.includes(dep));
140
+ }
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * post-implement-validate.mjs — Hook: post-implementation validation
4
+ * NON-BLOCKING: Checks that the baseline hasn't regressed.
5
+ */
6
+
7
+ import { fileExists, readJsonFile, findFiles, commandExists } from './lib/utils.mjs';
8
+ import { execSync } from 'child_process';
9
+ import { basename, join } from 'path';
10
+
11
+ const BASELINE_DIR = '.quality/baselines';
12
+ if (!fileExists(BASELINE_DIR)) {
13
+ process.exit(0);
14
+ }
15
+
16
+ // Normalize: replace underscores with hyphens to match MCP registry name
17
+ const projectName = basename(process.cwd()).replace(/_/g, '-');
18
+ const baselineFile = join(BASELINE_DIR, `${projectName}.json`);
19
+
20
+ if (!fileExists(baselineFile)) {
21
+ console.log(`[POST-IMPLEMENT] No baseline found for ${projectName}, skipping validation`);
22
+ process.exit(0);
23
+ }
24
+
25
+ console.log('[POST-IMPLEMENT] Validating against baseline...');
26
+
27
+ // Quick lint check
28
+ let errors = 0;
29
+
30
+ if (fileExists('pubspec.yaml')) {
31
+ try {
32
+ const output = execSync('dart analyze', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
33
+ const matches = output.match(/ error /gi);
34
+ errors = matches ? matches.length : 0;
35
+ } catch (e) {
36
+ const output = (e.stdout || '') + (e.stderr || '');
37
+ const matches = output.match(/ error /gi);
38
+ errors = matches ? matches.length : 0;
39
+ }
40
+ } else if (fileExists('package.json')) {
41
+ try {
42
+ const output = execSync('npx eslint . --format json', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
43
+ const data = JSON.parse(output);
44
+ errors = data.reduce((sum, f) => sum + (f.errorCount || 0), 0);
45
+ } catch { errors = 0; }
46
+ } else if (fileExists('pyproject.toml')) {
47
+ try {
48
+ const output = execSync('ruff check . --output-format json', { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
49
+ const data = JSON.parse(output);
50
+ errors = data.length;
51
+ } catch { errors = 0; }
52
+ }
53
+
54
+ const baseline = readJsonFile(baselineFile);
55
+ const baselineErrors = baseline?.metrics?.lint_errors || 0;
56
+
57
+ if (errors > baselineErrors) {
58
+ console.log(`[POST-IMPLEMENT] Lint errors increased: ${baselineErrors} -> ${errors} (ratchet violation)`);
59
+ } else {
60
+ console.log(`[POST-IMPLEMENT] Lint errors OK: ${errors} (baseline: ${baselineErrors})`);
61
+ }