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,76 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pre-commit-lint.mjs — PreToolUse hook for `git commit`
4
+ * BLOCKING (exit 2, before the commit exists): the project's own linter fails on the files that go
5
+ * into the commit. Zero tolerance on those files, not on the whole repo.
6
+ *
7
+ * Files: the staged ones, plus the tracked changes with `git commit -a`, plus what a `git add` in
8
+ * the same command will add (the hook runs before that `git add`).
9
+ * Linters, only if the project or the machine already has them (never `npx`, which can download):
10
+ * .py ruff check (.venv/bin/ruff or ruff on PATH)
11
+ * .ts .tsx .js .jsx .mjs .cjs eslint --max-warnings=0 (node_modules/.bin/eslint of the project)
12
+ * .dart dart analyze (dart or fvm dart; infos no bloquean, avisos sí)
13
+ * Nothing to lint, or no linter for those files → silent.
14
+ *
15
+ * v5.7.0 · US-93/UC-9302: runs before the commit (it ran after it, on an empty staging area) and
16
+ * uses the project's linter on the committed files. GGA, an AI review, is no longer run here: it
17
+ * cost a review per commit attempt; whoever wants it installs it as a git hook (`gga install`).
18
+ */
19
+
20
+ import { spawnSync } from 'child_process';
21
+ import { existsSync } from 'fs';
22
+ import { join } from 'path';
23
+ import { readHookInput, gitDirForCommand, git, commandExists, commitFiles } from './lib/utils.mjs';
24
+ import { blockWith } from './lib/output.mjs';
25
+
26
+ const { toolInput, cwd } = readHookInput();
27
+ const command = String(toolInput.command || '');
28
+ if (command && !/\bgit\b[^;&|]*\bcommit\b/.test(command)) process.exit(0);
29
+ const repo = gitDirForCommand(command, cwd);
30
+ try {
31
+ process.chdir(repo);
32
+ } catch {
33
+ process.exit(0);
34
+ }
35
+ if (!git('rev-parse --show-toplevel')) process.exit(0);
36
+
37
+ const existing = commitFiles(command).filter((f) => existsSync(f));
38
+
39
+ const byExt = (re) => existing.filter((f) => re.test(f));
40
+ const runs = [];
41
+ const py = byExt(/\.py$/);
42
+ if (py.length) {
43
+ const ruff = existsSync('.venv/bin/ruff') ? '.venv/bin/ruff' : commandExists('ruff') ? 'ruff' : null;
44
+ if (ruff) runs.push({ name: 'ruff', cmd: ruff, args: ['check', ...py] });
45
+ }
46
+ const js = byExt(/\.(ts|tsx|js|jsx|mjs|cjs)$/);
47
+ const eslint = join('node_modules', '.bin', 'eslint');
48
+ // UC-11003: with the flat config a committed file that the config ignores gives the warning «File
49
+ // ignored», and --max-warnings=0 turns it into a block. --no-warn-ignored only exists with the flat
50
+ // config (eslint.config.*); with .eslintrc it is an unknown option, so it is passed only then.
51
+ const flatConfig = ['js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].some((ext) => existsSync(`eslint.config.${ext}`));
52
+ const eslintArgs = ['--max-warnings=0', ...(flatConfig ? ['--no-warn-ignored'] : [])];
53
+ if (js.length && existsSync(eslint)) runs.push({ name: 'eslint', cmd: eslint, args: [...eslintArgs, ...js] });
54
+ const dart = byExt(/\.dart$/);
55
+ if (dart.length) {
56
+ if (commandExists('dart')) runs.push({ name: 'dart analyze', cmd: 'dart', args: ['analyze', ...dart] });
57
+ else if (commandExists('fvm')) runs.push({ name: 'dart analyze', cmd: 'fvm', args: ['dart', 'analyze', ...dart] });
58
+ }
59
+
60
+ const failures = [];
61
+ for (const r of runs) {
62
+ const res = spawnSync(r.cmd, r.args, { encoding: 'utf-8', timeout: 50_000 });
63
+ if (res.error || res.status !== 0) {
64
+ const out = `${res.stdout || ''}\n${res.stderr || ''}`.trim().split('\n').filter(Boolean);
65
+ failures.push(`${r.name}:`, ...out.slice(-25).map((l) => ` ${l}`));
66
+ }
67
+ }
68
+
69
+ if (failures.length) {
70
+ blockWith('LINT: el commit no pasa el linter del proyecto', [
71
+ ...failures,
72
+ '',
73
+ 'Corrige estos errores en los ficheros del commit y vuelve a intentarlo. Tolerancia cero: también los avisos.',
74
+ ]);
75
+ }
76
+ process.exit(0);
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pre-prd-discovery-check.mjs — PreToolUse hook for /prd invocation (v6.0.0, UC-D003).
4
+ *
5
+ * Verifies that a Discovery artifact (`doc/discovery/<feature>/icp_jtbd.md`)
6
+ * exists and has verdict READY_FOR_PRD before allowing /prd to proceed.
7
+ *
8
+ * Gate modes (`.claude/settings.local.json` → `specbox.discovery.gate_mode`):
9
+ * - "off" (default in upgraded projects): hook is a no-op.
10
+ * - "warn" (default in fresh-clone v6.0): prints pedagogical warning,
11
+ * exits 0, /prd proceeds.
12
+ * - "block" (opt-in for power users): prints same warning, exits 1,
13
+ * /prd is aborted.
14
+ *
15
+ * How the hook resolves feature_name from the /prd invocation:
16
+ * - Reads the CommandInput from stdin (PreToolUse contract).
17
+ * - Looks for the first positional argument after "/prd" → feature_name.
18
+ * - If feature_name is a US/UC identifier (US-XX, UC-XXX), skip the
19
+ * check (Trello/Plane spec-driven mode doesn't use Discovery).
20
+ *
21
+ * Skipped when:
22
+ * - gate_mode == "off"
23
+ * - feature_name cannot be extracted
24
+ * - The skill being invoked is not /prd
25
+ *
26
+ * Telemetry: every block writes a JSONL entry to
27
+ * `.quality/discovery_gate_events.jsonl`.
28
+ */
29
+
30
+ import { existsSync, readFileSync } from 'fs';
31
+ import { spawnSync } from 'child_process';
32
+ import { appendLine, readJsonFile } from './lib/utils.mjs';
33
+ import { blockWith, noteWith } from './lib/output.mjs';
34
+
35
+ const TELEMETRY_PATH = '.quality/discovery_gate_events.jsonl';
36
+
37
+ function readGateMode() {
38
+ const settings = readJsonFile('.claude/settings.local.json') || {};
39
+ const mode = settings?.specbox?.discovery?.gate_mode;
40
+ if (mode === 'off' || mode === 'warn' || mode === 'block') return mode;
41
+ return 'off'; // safe default for projects without explicit config
42
+ }
43
+
44
+ function readHookInput() {
45
+ // Hooks receive a JSON payload on stdin describing the tool call.
46
+ // For PreToolUse on Skill invocation, the payload includes `tool_input`
47
+ // with the args. Format may vary across Claude Code versions — defensive.
48
+ if (process.stdin.isTTY) return null;
49
+ try {
50
+ const raw = readFileSync(0, 'utf-8');
51
+ if (!raw.trim()) return null;
52
+ return JSON.parse(raw);
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Extract feature_name from a /prd invocation.
60
+ *
61
+ * Heuristic: looks for the first space-separated token after `/prd`
62
+ * that doesn't look like a flag. Returns null if not extractable.
63
+ * Returns a special marker "SPEC_DRIVEN" if the argument is a US/UC id
64
+ * (the hook skips Discovery check for spec-driven mode).
65
+ */
66
+ function extractFeatureName(input) {
67
+ if (!input) return null;
68
+ // Try several places: tool_input.command, tool_input.args, top-level args
69
+ const ti = input?.tool_input || input?.toolInput || input?.input || {};
70
+ const candidates = [
71
+ ti.command,
72
+ ti.args,
73
+ ti.prompt,
74
+ ti.text,
75
+ input.command,
76
+ input.args,
77
+ ].filter(Boolean);
78
+
79
+ for (const c of candidates) {
80
+ const text = typeof c === 'string' ? c : Array.isArray(c) ? c.join(' ') : '';
81
+ if (!text) continue;
82
+
83
+ // Strip leading "/prd "
84
+ const trimmed = text.replace(/^\/prd\s+/, '').trim();
85
+ if (!trimmed) continue;
86
+
87
+ // First non-flag token
88
+ const tokens = trimmed.split(/\s+/).filter((t) => !t.startsWith('-'));
89
+ if (tokens.length === 0) continue;
90
+ const firstArg = tokens[0];
91
+
92
+ // Spec-driven mode: US-XX or UC-XXX or board:ID → skip Discovery check
93
+ if (/^US-[A-Z0-9-]+$/i.test(firstArg)) return 'SPEC_DRIVEN';
94
+ if (/^UC-[A-Z0-9-]+$/i.test(firstArg)) return 'SPEC_DRIVEN';
95
+ if (/^board:/i.test(firstArg)) return 'SPEC_DRIVEN';
96
+
97
+ // Slug-friendly feature name
98
+ if (/^[a-zA-Z0-9_-]+$/.test(firstArg)) return firstArg;
99
+ }
100
+
101
+ return null;
102
+ }
103
+
104
+ const PRD_SKILLS = new Set(['prd', 'prd-generator']);
105
+
106
+ /**
107
+ * UC-11001: the skill being invoked — `tool_input.skill` of the Skill tool, or the slash command at
108
+ * the start of the text (`/plan …`). null when the input names none. The hook is wired to every Skill
109
+ * call, so without this any skill with arguments (`/plan US-01`, `/implement UC-001`) was read as /prd.
110
+ */
111
+ function invokedSkill(input) {
112
+ const ti = input?.tool_input || input?.toolInput || input?.input || {};
113
+ const named = (name) => name.replace(/^\//, '').split(':').pop();
114
+ if (typeof ti.skill === 'string' && ti.skill.trim()) return named(ti.skill.trim());
115
+ for (const c of [ti.command, ti.prompt, ti.text, input?.command]) {
116
+ const slash = typeof c === 'string' ? c.trim().match(/^\/([\w:-]+)/) : null;
117
+ if (slash) return named(slash[1]);
118
+ }
119
+ return null;
120
+ }
121
+
122
+ function recordEvent(entry) {
123
+ try {
124
+ appendLine(TELEMETRY_PATH, JSON.stringify(entry));
125
+ } catch {
126
+ // telemetry must never break the hook
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Run `python3 -c "from server.tools.discovery import _validate_icp_jtbd; ..."`
132
+ * to validate completeness without needing FastMCP running. Falls back to
133
+ * a regex check if the Python invocation fails.
134
+ */
135
+ function validateDiscoveryViaPython(featureName) {
136
+ const code = `
137
+ import json, sys
138
+ from pathlib import Path
139
+ sys.path.insert(0, str(Path.cwd()))
140
+ from server.tools.discovery import _validate_icp_jtbd, _icp_jtbd_path
141
+ artifact = _icp_jtbd_path(Path('.'), '${featureName}')
142
+ if not artifact.exists():
143
+ print(json.dumps({"verdict": "DISCOVERY_INCOMPLETE", "missing": ["artifact_not_found"]}))
144
+ sys.exit(0)
145
+ content = artifact.read_text(encoding='utf-8')
146
+ result = _validate_icp_jtbd(content)
147
+ print(json.dumps(result))
148
+ `;
149
+ const py = spawnSync('python3', ['-c', code], { timeout: 5000, encoding: 'utf-8' });
150
+ if (py.status !== 0 || !py.stdout) {
151
+ return { verdict: 'UNKNOWN', missing: ['validation_subprocess_failed'] };
152
+ }
153
+ try {
154
+ return JSON.parse(py.stdout.trim().split('\n').pop());
155
+ } catch {
156
+ return { verdict: 'UNKNOWN', missing: ['validation_parse_failed'] };
157
+ }
158
+ }
159
+
160
+ function fallbackArtifactExists(featureName) {
161
+ return existsSync(`doc/discovery/${featureName}/icp_jtbd.md`);
162
+ }
163
+
164
+ // ─── Main ────────────────────────────────────────────────────────────
165
+
166
+ const gateMode = readGateMode();
167
+ if (gateMode === 'off') {
168
+ process.exit(0);
169
+ }
170
+
171
+ const input = readHookInput();
172
+ const skill = invokedSkill(input);
173
+ if (skill !== null && !PRD_SKILLS.has(skill)) {
174
+ process.exit(0); // another skill: the discovery gate is only about /prd
175
+ }
176
+ const featureName = extractFeatureName(input);
177
+
178
+ if (!featureName) {
179
+ // Couldn't determine the feature_name — don't block.
180
+ process.exit(0);
181
+ }
182
+
183
+ if (featureName === 'SPEC_DRIVEN') {
184
+ // /prd US-XX or /prd UC-XXX — Trello/Plane spec-driven mode, no Discovery needed.
185
+ process.exit(0);
186
+ }
187
+
188
+ // Validate Discovery
189
+ let validation;
190
+ try {
191
+ validation = validateDiscoveryViaPython(featureName);
192
+ } catch {
193
+ validation = { verdict: 'UNKNOWN', missing: ['validation_threw'] };
194
+ }
195
+
196
+ if (validation.verdict === 'READY_FOR_PRD') {
197
+ process.exit(0); // happy path — Discovery complete
198
+ }
199
+
200
+ if (validation.verdict === 'UNKNOWN') {
201
+ // Validation couldn't run (Python missing, etc.). Fall back to existence
202
+ // check — if the artifact exists, give benefit of the doubt.
203
+ if (fallbackArtifactExists(featureName)) {
204
+ process.exit(0);
205
+ }
206
+ // Otherwise still treat as incomplete and let the gate decide.
207
+ validation = { verdict: 'DISCOVERY_INCOMPLETE', missing: ['artifact_not_found'] };
208
+ }
209
+
210
+ // Build pedagogical message
211
+ const missingList = (validation.missing || []).map((m) => `- ${m}`).join('\n');
212
+ const message =
213
+ `[DISCOVERY-GATE] /prd ${featureName} ${gateMode === 'block' ? 'BLOCKED' : 'WARNED'}: ` +
214
+ `discovery incompleto.\n\n` +
215
+ `Razones:\n${missingList || ' (sin detalles)'}\n\n` +
216
+ `¿Por qué este check importa?\n` +
217
+ ` Sin discovery, los AC del PRD nacen sin justificación trazable.\n` +
218
+ ` 3 de cada 4 features sin discovery requieren ≥2 iteraciones post-shipping.\n\n` +
219
+ `Atajo (15-30 min):\n` +
220
+ ` /discovery ${featureName}\n\n` +
221
+ `O salta este check (registrado para review post-shipping):\n` +
222
+ ` /prd ${featureName} --skip-discovery --reason "..."`;
223
+
224
+ recordEvent({
225
+ type: 'discovery_gate',
226
+ feature_name: featureName,
227
+ gate_mode: gateMode,
228
+ verdict: validation.verdict,
229
+ missing: validation.missing || [],
230
+ action: gateMode === 'block' ? 'blocked' : 'warned',
231
+ detected_at: new Date().toISOString(),
232
+ });
233
+
234
+ // US-93/UC-9302: block with exit 2 (exit 1 did not stop /prd) and warn with a note to the agent.
235
+ if (gateMode === 'block') {
236
+ blockWith('[DISCOVERY-GATE] /prd bloqueado: falta el discovery', message.split('\n'));
237
+ }
238
+ noteWith('PreToolUse', '[DISCOVERY-GATE] /prd sigue, pero falta el discovery', [
239
+ ...message.split('\n'),
240
+ '',
241
+ 'Modo aviso (gate_mode=warn). Con specbox.discovery.gate_mode="block" en .claude/settings.local.json, /prd se para.',
242
+ ]);
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pre-read-budget-guard.mjs — PreToolUse hook for Read tool.
4
+ *
5
+ * NON-BLOCKING. Estimates tokens for the file being read (chars / 4).
6
+ * Emits a warning to stderr if the file would exceed warn_pct of the
7
+ * Claude window. The agent is free to proceed — this just makes the
8
+ * cost visible so the agent can choose Grep/Explore instead of a
9
+ * full Read on a heavy file.
10
+ *
11
+ * Configurable via .claude/settings.local.json:
12
+ * {
13
+ * "specbox": {
14
+ * "context_budget": {
15
+ * "window_tokens": 1000000, // Claude window size
16
+ * "warn_pct": 5, // warn at >= 5% of window
17
+ * "enabled": true // set false to disable warnings
18
+ * }
19
+ * }
20
+ * }
21
+ *
22
+ * v5.30.0 — Session Continuity
23
+ */
24
+
25
+ import { statSync, existsSync } from 'fs';
26
+ import { readStdin, readJsonFile } from './lib/utils.mjs';
27
+ import { noteWith } from './lib/output.mjs';
28
+
29
+ const DEFAULT_CONFIG = {
30
+ window_tokens: 1_000_000,
31
+ warn_pct: 5,
32
+ enabled: true,
33
+ };
34
+
35
+ function loadConfig() {
36
+ const local = readJsonFile('.claude/settings.local.json');
37
+ const cfg = local?.specbox?.context_budget || {};
38
+ return { ...DEFAULT_CONFIG, ...cfg };
39
+ }
40
+
41
+ function main() {
42
+ const cfg = loadConfig();
43
+ if (!cfg.enabled) process.exit(0);
44
+
45
+ const input = readStdin();
46
+ if (!input) process.exit(0);
47
+
48
+ let filePath = '';
49
+ try {
50
+ const parsed = JSON.parse(input);
51
+ filePath = parsed.tool_input?.file_path || parsed.file_path || '';
52
+ } catch {
53
+ const m = input.match(/"file_path"\s*:\s*"([^"]*)"/);
54
+ filePath = m ? m[1] : '';
55
+ }
56
+ if (!filePath || !existsSync(filePath)) process.exit(0);
57
+
58
+ let size;
59
+ try {
60
+ size = statSync(filePath).size;
61
+ } catch {
62
+ process.exit(0);
63
+ }
64
+
65
+ const tokensEst = Math.floor(size / 4);
66
+ const pct = (tokensEst / cfg.window_tokens) * 100;
67
+
68
+ if (pct >= cfg.warn_pct) {
69
+ const pctRounded = pct >= 10 ? Math.round(pct) : pct.toFixed(1);
70
+ // A note to the agent (US-93/UC-9302: stderr with exit 0 reaches nobody).
71
+ noteWith('PreToolUse', `[BUDGET] Lectura pesada: ${filePath}`, [
72
+ `~${tokensEst.toLocaleString()} tokens, ${pctRounded}% de una ventana de ${cfg.window_tokens.toLocaleString()}.`,
73
+ 'Mejor Grep, un agente Explore o Read con offset/limit que leerlo entero.',
74
+ ]);
75
+ }
76
+ process.exit(0);
77
+ }
78
+
79
+ try {
80
+ main();
81
+ } catch {
82
+ process.exit(0);
83
+ }
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * quality-first-guard.mjs — PreToolUse hook for Write and Edit tools
4
+ * BLOCKING (exit 2, before the write): modifying an existing file the agent has not read in this
5
+ * session. A file the agent creates counts as known, so it can edit it afterwards.
6
+ * US-93/UC-9302: it read the path from the top level (so it never checked a real write) and
7
+ * exited 1, which does not block.
8
+ *
9
+ * Philosophy: the LLM brings the speed; SpecBox brings the control and guarantees
10
+ * the quality (UC-7006: the block message no longer says the opposite).
11
+ * The #1 cause of wasted tokens and technical debt is modifying code without
12
+ * understanding what's already there. This hook enforces "read before write."
13
+ *
14
+ * v5.15.0 — Quality First Enforcement
15
+ */
16
+
17
+ import { readHookInput, fileExists, appendLine, mkdir } from './lib/utils.mjs';
18
+ import { blockWith } from './lib/output.mjs';
19
+ import { readFileSync, realpathSync } from 'fs';
20
+ import { resolve } from 'path';
21
+
22
+ const { toolInput } = readHookInput();
23
+ const filePath = String(toolInput.file_path || '');
24
+ if (!filePath) process.exit(0);
25
+
26
+ const TRACKER_FILE = '.quality/read_tracker.jsonl';
27
+
28
+ // A new file: the agent is writing it, so from now on it knows it.
29
+ if (!fileExists(filePath)) {
30
+ try {
31
+ mkdir('.quality');
32
+ appendLine(TRACKER_FILE, JSON.stringify({ file: filePath, ts: Math.floor(Date.now() / 1000), created: true }));
33
+ } catch { /* no .quality: nothing to record */ }
34
+ process.exit(0);
35
+ }
36
+
37
+ // Files that do not need read-before-write: generated, lock files, build output, SpecBox internals.
38
+ if (/(\.g\.dart$|\.freezed\.dart$|\.lock$|package-lock\.json$|pubspec\.lock$|poetry\.lock$|\.min\.js$|\.min\.css$|node_modules\/|\.dart_tool\/|(^|\/)build\/|(^|\/)dist\/|\.next\/)/.test(filePath)) {
39
+ process.exit(0);
40
+ }
41
+ if (/(\.quality\/|\.claude\/|results\.json$|baseline\.json$|active_uc\.json$|hint_counters\.json$)/.test(filePath)) {
42
+ process.exit(0);
43
+ }
44
+
45
+ function block(file, inSession) {
46
+ blockWith('QUALITY FIRST: Read before you write', [
47
+ `File: ${file}`,
48
+ '',
49
+ inSession
50
+ ? 'You are trying to modify an existing file without reading it first in this session.'
51
+ : 'You are trying to modify an existing file without reading it first.',
52
+ 'Reading first avoids breaking what is there, duplicating it or leaving it inconsistent.',
53
+ '',
54
+ 'To proceed:',
55
+ ` 1. Use the Read tool to read '${file}'`,
56
+ ' 2. Understand the existing code',
57
+ ' 3. Then make your changes',
58
+ ]);
59
+ }
60
+
61
+ let tracker = '';
62
+ try {
63
+ tracker = readFileSync(TRACKER_FILE, 'utf-8');
64
+ } catch {
65
+ block(filePath, false);
66
+ }
67
+
68
+ // The same file, whatever the spelling: resolved against the cwd and through symlinks (on macOS
69
+ // /tmp is /private/tmp). No more matching by basename: any README.md read anywhere counted.
70
+ const canonical = (p) => {
71
+ const abs = resolve(process.cwd(), p);
72
+ try { return realpathSync(abs); } catch { return abs; }
73
+ };
74
+ const target = canonical(filePath);
75
+ const wasRead = tracker.split('\n').some((line) => {
76
+ try {
77
+ const entry = JSON.parse(line);
78
+ return entry.file && canonical(entry.file) === target;
79
+ } catch {
80
+ return false;
81
+ }
82
+ });
83
+
84
+ if (!wasRead) block(filePath, true);
85
+ process.exit(0);
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * read-tracker.mjs — PostToolUse hook for the Read tool
4
+ * NON-BLOCKING, silent: records which files the agent has read in the current session, in
5
+ * .quality/read_tracker.jsonl. quality-first-guard.mjs uses it to enforce "read before write".
6
+ *
7
+ * v5.15.0 — Quality First Enforcement · US-93/UC-9302: reads the path from tool_input (it read
8
+ * the top level, so it never recorded a real read) and keeps the tracker out of git with a
9
+ * .quality/.gitignore entry.
10
+ */
11
+
12
+ import { readHookInput, fileExists, fileAge, mkdir, appendLine } from './lib/utils.mjs';
13
+ import { unlinkSync, writeFileSync } from 'fs';
14
+
15
+ const { toolInput } = readHookInput();
16
+ const filePath = String(toolInput.file_path || '');
17
+ if (!filePath) process.exit(0);
18
+
19
+ mkdir('.quality');
20
+ const TRACKER_FILE = '.quality/read_tracker.jsonl';
21
+
22
+ // The tracker is per machine and session: never in git.
23
+ if (!fileExists('.quality/.gitignore')) {
24
+ try { writeFileSync('.quality/.gitignore', 'read_tracker.jsonl\n'); } catch { /* read-only: ignore */ }
25
+ }
26
+
27
+ // Clear stale tracker (older than 24 hours)
28
+ if (fileExists(TRACKER_FILE) && fileAge(TRACKER_FILE) > 86400) {
29
+ try { unlinkSync(TRACKER_FILE); } catch { /* ignore */ }
30
+ }
31
+
32
+ appendLine(TRACKER_FILE, JSON.stringify({ file: filePath, ts: Math.floor(Date.now() / 1000) }));
33
+ process.exit(0);
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * session-heartbeat.mjs — el latido de la sesión al board (US-99 · UC-9901).
4
+ * NO BLOQUEA y es silencioso: nunca escribe nada para el agente ni sale con error.
5
+ *
6
+ * Eventos: SessionStart, PostToolUse, Notification, UserPromptSubmit y SessionEnd. Calcula el
7
+ * latido (UC activa, fase del pipeline, si espera un permiso o una decisión) y, si toca (al empezar,
8
+ * al cerrar, al cambiar algo o cada dos minutos), lo manda en un proceso aparte que no se espera
9
+ * (lib/heartbeat-send.mjs, con tope de 3 s). Solo en proyectos con board native.
10
+ *
11
+ * SPECBOX_HEARTBEAT=off lo apaga. SPECBOX_HEARTBEAT_DRY_RUN=<fichero> escribe el latido en ese
12
+ * fichero en vez de enviarlo (pruebas).
13
+ */
14
+
15
+ import { spawn } from 'node:child_process';
16
+ import { appendFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { getProjectConfig } from './lib/config.mjs';
20
+ import { latido, tocaEnviar } from './lib/heartbeat.mjs';
21
+ import { fileAge, git, mkdir, readHookInput, readJsonFile } from './lib/utils.mjs';
22
+
23
+ const ESTADO = '.quality/heartbeat_state.json';
24
+ /** Lo que el latido deja en el repo y nunca va a git (como read-tracker). */
25
+ const IGNORADOS = ['heartbeat_state.json', 'heartbeat_error.json', 'logs/heartbeat.log'];
26
+
27
+ function asegurarIgnorados() {
28
+ const ruta = '.quality/.gitignore';
29
+ let actual = '';
30
+ try {
31
+ actual = readFileSync(ruta, 'utf8');
32
+ } catch {
33
+ actual = '';
34
+ }
35
+ const faltan = IGNORADOS.filter((l) => !actual.split('\n').includes(l));
36
+ if (faltan.length === 0) return;
37
+ try {
38
+ appendFileSync(ruta, `${actual && !actual.endsWith('\n') ? '\n' : ''}${faltan.join('\n')}\n`);
39
+ } catch {
40
+ // solo lectura: no pasa nada
41
+ }
42
+ }
43
+
44
+ /** El fichero más reciente con ese nombre en .quality/evidence/<feature>/, y su edad en segundos. */
45
+ function masReciente(nombre) {
46
+ const base = '.quality/evidence';
47
+ if (!existsSync(base)) return { datos: null, edad: Infinity };
48
+ let mejor = null;
49
+ for (const feature of readdirSync(base)) {
50
+ const ruta = join(base, feature, nombre);
51
+ try {
52
+ const t = statSync(ruta).mtimeMs;
53
+ if (!mejor || t > mejor.t) mejor = { ruta, t };
54
+ } catch {
55
+ // no existe en esta feature
56
+ }
57
+ }
58
+ if (!mejor) return { datos: null, edad: Infinity };
59
+ return { datos: readJsonFile(mejor.ruta), edad: (Date.now() - mejor.t) / 1000 };
60
+ }
61
+
62
+ /** La rama actual sin lanzar git cuando el repo es normal (.git/HEAD). */
63
+ function ramaActual() {
64
+ try {
65
+ const head = readFileSync('.git/HEAD', 'utf8').trim();
66
+ if (head.startsWith('ref: refs/heads/')) return head.slice('ref: refs/heads/'.length);
67
+ } catch {
68
+ // worktree o sin repo: se pregunta a git
69
+ }
70
+ return git('branch --show-current');
71
+ }
72
+
73
+ try {
74
+ if (process.env.SPECBOX_HEARTBEAT === 'off') process.exit(0);
75
+ const { event, payload } = readHookInput();
76
+ const { boardId, backendType } = getProjectConfig();
77
+ if (backendType !== 'native' || !boardId) process.exit(0);
78
+
79
+ const anterior = readJsonFile(ESTADO);
80
+ const marcador = fileAge('.quality/active_uc.json') < 86400 ? readJsonFile('.quality/active_uc.json') : null;
81
+ const pipeline = masReciente('pipeline_state.json');
82
+ const checkpoint = masReciente('checkpoint.json');
83
+ const nuevo = latido({
84
+ evento: event,
85
+ entrada: payload,
86
+ proyecto: boardId,
87
+ marcador,
88
+ rama: ramaActual(),
89
+ pipeline: pipeline.edad < 2 * 3600 ? pipeline.datos : null,
90
+ checkpoint: checkpoint.datos,
91
+ checkpointEdadS: checkpoint.edad,
92
+ anterior,
93
+ });
94
+ const ahora = Date.now();
95
+ if (tocaEnviar(nuevo, anterior, ahora)) {
96
+ mkdir('.quality');
97
+ asegurarIgnorados();
98
+ writeFileSync(ESTADO, JSON.stringify({ ...nuevo, sent_at: ahora }));
99
+ if (process.env.SPECBOX_HEARTBEAT_DRY_RUN) {
100
+ appendFileSync(process.env.SPECBOX_HEARTBEAT_DRY_RUN, `${JSON.stringify(nuevo)}\n`);
101
+ } else {
102
+ const enviar = join(dirname(fileURLToPath(import.meta.url)), 'lib', 'heartbeat-send.mjs');
103
+ const hijo = spawn(process.execPath, [enviar, process.cwd(), JSON.stringify(nuevo)], {
104
+ detached: true,
105
+ stdio: 'ignore',
106
+ });
107
+ hijo.unref();
108
+ }
109
+ }
110
+ } catch {
111
+ // El latido nunca molesta a la sesión.
112
+ }
113
+ process.exit(0);