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
package/README.md CHANGED
@@ -19,13 +19,15 @@ The token expires after 90 days and **renews itself** from 14 days before. If a
19
19
  | `specbox login` | Connects this computer (one device = this computer + Claude Code). Signing in again replaces the previous token of this device. |
20
20
  | `specbox status` | Account, device, expiry date, whether the token is still valid and whether Claude Code uses it. |
21
21
  | `specbox logout` | Disconnects this device in the panel and deletes the local credential. |
22
+ | `specbox hooks status` | Lists the project's hooks (`.claude/hooks/`) that differ from the ones this version publishes. |
23
+ | `specbox hooks update` | Lists them, then installs the missing ones and replaces the ones you did not change. A hook you changed is left as it is and the new version is saved next to it as `<hook>.mjs.new`; `--overwrite <hook>` replaces it. Missing registrations are added to `.claude/settings.json` (copy in `settings.json.bak`). |
22
24
 
23
- Options: `--no-browser` (just print the link), `--server <url>` and `--cloud <url>` for self-hosted servers (or `SPECBOX_MCP_URL` / `SPECBOX_CLOUD_API`).
25
+ Options: `--no-browser` (just print the link), `--server <url>` and `--cloud <url>` for self-hosted servers (or `SPECBOX_MCP_URL` / `SPECBOX_CLOUD_API`), `--project <dir>` for `hooks` (default: the current repository).
24
26
 
25
27
  ## What it changes on your computer
26
28
 
27
29
  - **Secure store:** the macOS Keychain, Secret Service on Linux (`secret-tool`) or Windows DPAPI. Without any of them (headless Linux), a `~/.specbox/credentials.json` file with `0600` permissions; `specbox login` says so.
28
- - **`~/.specbox/bin/mcp-headers.mjs`:** a small helper. Claude Code runs it when it connects (and after a `401`) to get the `Authorization` header; it reads the store and renews the token when due. It never prints anything but that header.
30
+ - **`~/.specbox/bin/mcp-headers.mjs`:** a small helper. Claude Code runs it when it connects (and after a `401`) to get the `Authorization` header; it reads the store and renews the token when due. If the project has a Google Stitch key (`STITCH_API_KEY`, or `stitch.apiKey` in the nearest `.claude/settings.local.json`), it also sends it as `X-Stitch-Api-Key`, so the key never goes through the conversation. It never prints anything but those headers.
29
31
  - **Claude Code:** the `SpecBox-MCP` server (user scope) becomes `{"type": "http", "url": …, "headersHelper": "<node> ~/.specbox/bin/mcp-headers.mjs"}` through the official `claude mcp` command, and other entries pointing to the same server get the same helper.
30
32
  - **`~/.specbox/device-id`:** only if the machine id cannot be read. The server only ever sees a SHA-256 of it.
31
33
 
@@ -35,4 +37,4 @@ More: [How SpecBox connects](https://cloud.specbox.build/how-to-connect) · [Có
35
37
 
36
38
  ---
37
39
 
38
- **En español.** `npx specbox login` conecta este ordenador: te muestra un código, lo confirmas en el navegador con tu cuenta de GitHub y el token queda en el almacén seguro del sistema; Claude Code lo envía solo y se renueva solo. `specbox status` dice con qué cuenta estás conectado y cuándo caduca; `specbox logout` desconecta el ordenador. Los mensajes salen en español si tu sistema está en español.
40
+ **En español.** `npx specbox login` conecta este ordenador: te muestra un código, lo confirmas en el navegador con tu cuenta de GitHub y el token queda en el almacén seguro del sistema; Claude Code lo envía solo y se renueva solo. Si el proyecto tiene clave de Google Stitch (`STITCH_API_KEY` o `stitch.apiKey` en su `.claude/settings.local.json`), la envía también, en la cabecera `X-Stitch-Api-Key`, sin que pase por la conversación. `specbox status` dice con qué cuenta estás conectado y cuándo caduca; `specbox logout` desconecta el ordenador. `specbox hooks update` pone al día los hooks del proyecto: primero lista los que difieren y no pisa los que cambiaste tú (deja la versión nueva al lado como `<hook>.mjs.new`; `--overwrite <hook>` la sustituye). Los mensajes salen en español si tu sistema está en español.
package/bin/specbox.mjs CHANGED
@@ -6,15 +6,19 @@
6
6
  * ayudante en ~/.specbox/bin → Claude Code lo usa solo
7
7
  * specbox status con qué cuenta y dispositivo, caducidad, si sigue valiendo
8
8
  * specbox logout desconecta el dispositivo y borra la credencial local
9
+ * specbox hooks [status|update] los hooks del proyecto frente a los publicados;
10
+ * update no pisa los retocados (UC-11201)
9
11
  *
10
12
  * Todo se puede inyectar (`run`) para las pruebas.
11
13
  */
12
- import { spawn } from "node:child_process";
14
+ import { execFileSync, spawn } from "node:child_process";
13
15
  import { realpathSync } from "node:fs";
16
+ import { resolve } from "node:path";
14
17
  import { pathToFileURL } from "node:url";
15
18
  import { claudeUsesHelper, configureClaudeCode, helperCommand, stableNodePath } from "../lib/claude.mjs";
16
19
  import { CLIENT, HOW_TO_CONNECT_URL, accountFor, resolveConfig, specboxHome } from "../lib/config.mjs";
17
20
  import { deviceId, hostLabel } from "../lib/device.mjs";
21
+ import { hooksStatus, loadPackaged, updateHooks } from "../lib/hooks.mjs";
18
22
  import { installHelper, packageVersion } from "../lib/install.mjs";
19
23
  import { readStdinJson, runInternal } from "../lib/internal.mjs";
20
24
  import { LoginError, deviceLogin } from "../lib/login.mjs";
@@ -22,19 +26,31 @@ import { messages, pickLang } from "../lib/messages.mjs";
22
26
  import { createStore } from "../lib/store.mjs";
23
27
 
24
28
  export function parseArgs(argv) {
25
- const opts = { command: null, server: null, cloud: null, browser: true };
29
+ const opts = { command: null, server: null, cloud: null, browser: true, args: [], project: null, overwrite: [] };
26
30
  for (let i = 0; i < argv.length; i += 1) {
27
31
  const arg = argv[i];
28
32
  if (arg === "--server") opts.server = argv[(i += 1)];
29
33
  else if (arg === "--cloud") opts.cloud = argv[(i += 1)];
30
34
  else if (arg === "--no-browser") opts.browser = false;
35
+ else if (arg === "--project") opts.project = argv[(i += 1)];
36
+ else if (arg === "--overwrite") opts.overwrite.push(...String(argv[(i += 1)] ?? "").split(",").filter(Boolean));
31
37
  else if (arg === "--version" || arg === "-v") opts.command = "version";
32
38
  else if (arg === "--help" || arg === "-h") opts.command = "help";
33
39
  else if (!opts.command) opts.command = arg;
40
+ else opts.args.push(arg);
34
41
  }
35
42
  return opts;
36
43
  }
37
44
 
45
+ /** La raíz del repositorio donde se ejecuta la orden (o la carpeta, si no es un repo). */
46
+ function projectRootOf(dir) {
47
+ try {
48
+ return execFileSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || dir;
49
+ } catch {
50
+ return dir;
51
+ }
52
+ }
53
+
38
54
  function openInBrowser(url) {
39
55
  const [cmd, args] =
40
56
  process.platform === "darwin"
@@ -172,6 +188,26 @@ export async function run(argv, deps = {}) {
172
188
  print(t.loggedOut(credential.device_name ?? "?", remote));
173
189
  return 0;
174
190
  }
191
+ case "hooks": {
192
+ // UC-11201: los hooks del proyecto frente a los que trae este paquete.
193
+ const action = opts.args[0] ?? "status";
194
+ if (!["status", "update"].includes(action)) {
195
+ printErr(t.usage);
196
+ return 1;
197
+ }
198
+ const packaged = (deps.loadPackaged ?? loadPackaged)();
199
+ if (!packaged) {
200
+ printErr(t.hooksNotPackaged);
201
+ return 1;
202
+ }
203
+ const projectRoot = projectRootOf(resolve(opts.project ?? deps.cwd ?? process.cwd()));
204
+ const status = hooksStatus({ projectRoot, packaged });
205
+ print(t.hooksStatus(status, projectRoot));
206
+ if (action === "status") return 0;
207
+ if (!status.differs) return 0;
208
+ print(t.hooksUpdated(updateHooks({ projectRoot, packaged, overwrite: opts.overwrite })));
209
+ return 0;
210
+ }
175
211
  case "help":
176
212
  case null:
177
213
  print(t.usage);
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * app-docs-sync-guard.mjs — PreToolUse hook for git commit (v5.29.0 PR-13; before the commit
4
+ * since US-93/UC-9302, so `block_on_drift` stops the commit and the warning reaches the agent)
5
+ *
6
+ * Mode: warning-only in v5.29.0.x. Detects drift between canonical docs
7
+ * (doc/app/app_prd.md, app_spec.md, and v6.0 app_market.md) and the
8
+ * recorded signatures in `.quality/app_docs_sync.lock`. Emits a visible
9
+ * warning but does not block the commit. From v5.29.1 onwards the same
10
+ * hook can be promoted to BLOCKING by flipping `BLOCK_ON_DRIFT=true` in
11
+ * the project's `.claude/settings.local.json` under
12
+ * `specbox.app_docs_sync`.
13
+ *
14
+ * v6.0 (UC-D005): the hook iterates over the canonical-docs registry
15
+ * loaded from `templates/canonical_docs.json` (descriptor generated from
16
+ * `server/app_docs/registry.py`). For each doc:
17
+ * - If the file doesn't exist on disk → skip (no warning).
18
+ * - If the doc's `introduced_in` > project's `engine_version_at_onboard`
19
+ * → skip (the project is on a pre-v6.0 version that didn't know
20
+ * about this doc).
21
+ * - If all manual zones carry `status="template-pristine"` → skip
22
+ * (plantilla vacía recién creada por `upgrade_project`).
23
+ * - Otherwise compare current signature vs locked baseline; warn if drift.
24
+ *
25
+ * Backwards compat: when the JSON descriptor is missing (e.g. project on
26
+ * v5.x that never received v6.0), the hook falls back to hardcoded
27
+ * `app_prd` + `app_spec` checks — same behavior as v5.29.x.
28
+ *
29
+ * Skipped when:
30
+ * - doc/app/ does not exist (project on legacy v5.28 flow).
31
+ * - .quality/app_docs_sync.lock does not exist (no baseline yet).
32
+ * - The active UC marker is set (feature in progress takes priority,
33
+ * per Case 7 of the v5.29 migration plan).
34
+ *
35
+ * Telemetry: every detection writes a JSONL entry to
36
+ * `.quality/app_docs_drift.jsonl` so the drift detector (PR-15) can
37
+ * surface it to external consumers (specbox_cloud, ad-hoc scripts).
38
+ */
39
+
40
+ import { existsSync, readFileSync } from 'fs';
41
+ import { join, dirname } from 'path';
42
+ import { fileURLToPath } from 'url';
43
+ import { createHash } from 'crypto';
44
+ import { getActiveUC } from './lib/config.mjs';
45
+ import { blockWith, noteWith } from './lib/output.mjs';
46
+ import { readHookInput, gitDirForCommand } from './lib/utils.mjs';
47
+
48
+ // The repo the commit goes to (`cd <dir> && git commit`, `git -C <dir> commit`).
49
+ {
50
+ const { toolInput, cwd } = readHookInput();
51
+ const command = String(toolInput.command || '');
52
+ if (command && !/\bgit\b[^;&|]*\bcommit\b/.test(command)) process.exit(0);
53
+ try {
54
+ process.chdir(gitDirForCommand(command, cwd));
55
+ } catch {
56
+ process.exit(0);
57
+ }
58
+ }
59
+ import { appendLine, readJsonFile } from './lib/utils.mjs';
60
+
61
+ const LOCK_PATH = '.quality/app_docs_sync.lock';
62
+ const TELEMETRY_PATH = '.quality/app_docs_drift.jsonl';
63
+
64
+ // ─── Canonical docs registry (loaded from JSON descriptor) ────────────
65
+
66
+ const __filename = fileURLToPath(import.meta.url);
67
+ const __dirname = dirname(__filename);
68
+
69
+ /**
70
+ * Locate `templates/canonical_docs.json` relative to the engine repo.
71
+ * The hook runs from the *project* CWD, not the engine repo, so we walk
72
+ * upwards from this script's location until we find the descriptor (the
73
+ * script is in `<engine>/.claude/hooks/`, the descriptor in
74
+ * `<engine>/templates/`).
75
+ *
76
+ * In multirepo satellite mode the hook may run in a project that doesn't
77
+ * have its own templates/ — fall back to looking next to the script's
78
+ * symlink target.
79
+ */
80
+ function locateCanonicalDocsJson() {
81
+ // Try project CWD first (some projects ship the descriptor locally).
82
+ const localTry = join(process.cwd(), 'templates', 'canonical_docs.json');
83
+ if (existsSync(localTry)) return localTry;
84
+ // Walk up from the script's actual location (works through symlinks
85
+ // because install.sh symlinks .claude/hooks/ to the engine repo).
86
+ let dir = __dirname;
87
+ for (let i = 0; i < 6; i += 1) {
88
+ const candidate = join(dir, 'templates', 'canonical_docs.json');
89
+ if (existsSync(candidate)) return candidate;
90
+ const parent = dirname(dir);
91
+ if (parent === dir) break;
92
+ dir = parent;
93
+ }
94
+ return null;
95
+ }
96
+
97
+ const LEGACY_FALLBACK_DOCS = [
98
+ {
99
+ id: 'app_prd',
100
+ path: 'doc/app/app_prd.md',
101
+ introduced_in: '5.29.0',
102
+ },
103
+ {
104
+ id: 'app_spec',
105
+ path: 'doc/app/app_spec.md',
106
+ introduced_in: '5.29.0',
107
+ },
108
+ ];
109
+
110
+ function loadCanonicalDocs() {
111
+ const jsonPath = locateCanonicalDocsJson();
112
+ if (!jsonPath) {
113
+ // Fallback to v5.29 hardcoded behavior — no v6.0 descriptor available.
114
+ return LEGACY_FALLBACK_DOCS;
115
+ }
116
+ try {
117
+ const raw = readFileSync(jsonPath, 'utf-8');
118
+ const data = JSON.parse(raw);
119
+ if (data?.schema_version !== 1 || !Array.isArray(data.docs)) {
120
+ // Unknown schema — fall back to safety.
121
+ return LEGACY_FALLBACK_DOCS;
122
+ }
123
+ return data.docs.map((d) => ({
124
+ id: d.id,
125
+ path: d.path,
126
+ introduced_in: d.introduced_in,
127
+ }));
128
+ } catch {
129
+ return LEGACY_FALLBACK_DOCS;
130
+ }
131
+ }
132
+
133
+ // ─── Version comparison ──────────────────────────────────────────────
134
+
135
+ /**
136
+ * Parse a semver-ish string into a tuple of numbers. '6.0.0' → [6,0,0].
137
+ * Tolerates pre-release suffixes by picking up numeric components only.
138
+ * Mirrors `registry._semver_tuple` in Python so both sides agree.
139
+ */
140
+ function semverTuple(version) {
141
+ if (!version) return [0];
142
+ const parts = String(version).match(/\d+/g);
143
+ if (!parts || parts.length === 0) return [0];
144
+ return parts.map((p) => parseInt(p, 10));
145
+ }
146
+
147
+ function semverLte(a, b) {
148
+ const at = semverTuple(a);
149
+ const bt = semverTuple(b);
150
+ const len = Math.max(at.length, bt.length);
151
+ for (let i = 0; i < len; i += 1) {
152
+ const av = at[i] ?? 0;
153
+ const bv = bt[i] ?? 0;
154
+ if (av < bv) return true;
155
+ if (av > bv) return false;
156
+ }
157
+ return true; // equal
158
+ }
159
+
160
+ function readEngineVersionAtOnboard() {
161
+ const settings = readJsonFile('.claude/settings.local.json') || {};
162
+ const v = settings?.specbox?.engine_version_at_onboard;
163
+ return v || null; // null → "unknown" → conservative policy
164
+ }
165
+
166
+ function docIsEligible(doc, engineVersion) {
167
+ // Conservative when unknown: only docs introduced in <= 5.29.0.
168
+ if (!engineVersion) return semverLte(doc.introduced_in, '5.29.0');
169
+ return semverLte(doc.introduced_in, engineVersion);
170
+ }
171
+
172
+ // ─── Zone signature (mirrors server/app_docs/zones.py) ───────────────
173
+
174
+ const ZONE_RE = /<!--\s*@specbox:zone\s+start\s+([^>]+?)\s*-->([\s\S]*?)<!--\s*@specbox:zone\s+end\s*-->/g;
175
+ const ATTR_RE = /(\w+)\s*=\s*"([^"]*)"/g;
176
+
177
+ function parseZones(content) {
178
+ const zones = [];
179
+ let match;
180
+ while ((match = ZONE_RE.exec(content)) !== null) {
181
+ const attrs = {};
182
+ let am;
183
+ // Reset lastIndex so multiple attr scans on different matches work.
184
+ ATTR_RE.lastIndex = 0;
185
+ while ((am = ATTR_RE.exec(match[1])) !== null) {
186
+ attrs[am[1]] = am[2];
187
+ }
188
+ if (!attrs.id || !attrs.kind) continue;
189
+ const body = match[2].replace(/^\n/, '').replace(/\n$/, '');
190
+ zones.push({
191
+ id: attrs.id,
192
+ kind: attrs.kind,
193
+ status: attrs.status || null,
194
+ body,
195
+ });
196
+ }
197
+ return zones;
198
+ }
199
+
200
+ function computeSignature(content) {
201
+ const zones = parseZones(content);
202
+ zones.sort((a, b) => a.id.localeCompare(b.id));
203
+ const hash = createHash('sha256');
204
+ for (const z of zones) {
205
+ hash.update(z.id);
206
+ hash.update('\x00');
207
+ hash.update(z.kind);
208
+ hash.update('\x00');
209
+ hash.update(z.body);
210
+ hash.update('\x00\x00');
211
+ }
212
+ return hash.digest('hex');
213
+ }
214
+
215
+ function docIsTemplatePristine(zones) {
216
+ const manual = zones.filter((z) => z.kind === 'manual');
217
+ if (manual.length === 0) return false;
218
+ return manual.every((z) => z.status === 'template-pristine');
219
+ }
220
+
221
+ // ─── Settings ────────────────────────────────────────────────────────
222
+
223
+ function readBlockingFlag() {
224
+ const settings = readJsonFile('.claude/settings.local.json') || {};
225
+ return Boolean(settings?.specbox?.app_docs_sync?.block_on_drift);
226
+ }
227
+
228
+ // ─── Detection ───────────────────────────────────────────────────────
229
+
230
+ function recordDrift(entry) {
231
+ try {
232
+ appendLine(TELEMETRY_PATH, JSON.stringify(entry));
233
+ } catch {
234
+ // telemetry must never break the hook
235
+ }
236
+ }
237
+
238
+ function checkDoc(name, path, lockedSig) {
239
+ if (!existsSync(path)) {
240
+ return null; // not present = no drift
241
+ }
242
+ let content;
243
+ try {
244
+ content = readFileSync(path, 'utf-8');
245
+ } catch {
246
+ return null;
247
+ }
248
+ const zones = parseZones(content);
249
+ // v6.0: pristine plantilla doesn't count as drift.
250
+ if (docIsTemplatePristine(zones)) {
251
+ return null;
252
+ }
253
+ const currentSig = computeSignature(content);
254
+ if (!lockedSig) {
255
+ return null; // no baseline yet — ignored
256
+ }
257
+ if (currentSig === lockedSig) {
258
+ return null;
259
+ }
260
+ return {
261
+ document: name,
262
+ path,
263
+ locked_signature: lockedSig,
264
+ current_signature: currentSig,
265
+ detected_at: new Date().toISOString(),
266
+ };
267
+ }
268
+
269
+ // ─── Main ────────────────────────────────────────────────────────────
270
+
271
+ if (!existsSync('doc/app')) {
272
+ process.exit(0); // legacy project — nothing to guard
273
+ }
274
+ if (!existsSync(LOCK_PATH)) {
275
+ process.exit(0); // no baseline yet — first sync hasn't run
276
+ }
277
+
278
+ const activeUC = getActiveUC();
279
+ if (activeUC && activeUC.feature) {
280
+ // Case 7: feature in progress — defer enforcement. Still log telemetry.
281
+ process.exit(0);
282
+ }
283
+
284
+ const lock = readJsonFile(LOCK_PATH) || {};
285
+ const sigs = lock.signatures || {};
286
+ const engineVersion = readEngineVersionAtOnboard();
287
+ const docs = loadCanonicalDocs();
288
+
289
+ const drifts = [];
290
+ for (const doc of docs) {
291
+ if (!docIsEligible(doc, engineVersion)) continue; // doc introduced after project's onboard version
292
+ const drift = checkDoc(doc.id, doc.path, sigs[doc.id]);
293
+ if (drift) drifts.push(drift);
294
+ }
295
+
296
+ if (drifts.length === 0) {
297
+ process.exit(0);
298
+ }
299
+
300
+ for (const d of drifts) {
301
+ recordDrift(d);
302
+ }
303
+
304
+ const blocking = readBlockingFlag();
305
+ const summary = drifts
306
+ .map(
307
+ (d) =>
308
+ ` - ${d.document} (${d.path}): expected ${d.locked_signature.slice(0, 12)}…, ` +
309
+ `actual ${d.current_signature.slice(0, 12)}…`
310
+ )
311
+ .join('\n');
312
+
313
+ const message =
314
+ `[APP-DOCS-SYNC] doc/app/*.md drifted since the last recorded sync:\n` +
315
+ `${summary}\n` +
316
+ `Run \`/app-sync --check\` for details, or \`/app-sync --repair\` to reconcile.\n` +
317
+ `Telemetry: ${TELEMETRY_PATH}`;
318
+
319
+ if (blocking) {
320
+ blockWith('APP-DOCS-SYNC: commit bloqueado por deriva de los documentos canónicos', message.split('\n'));
321
+ }
322
+
323
+ noteWith('PreToolUse', 'APP-DOCS-SYNC: el commit sigue, pero los documentos canónicos se han movido', [
324
+ ...message.split('\n'),
325
+ 'Modo aviso. Con specbox.app_docs_sync.block_on_drift = true en .claude/settings.local.json, bloquea.',
326
+ ]);
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * branch-guard.mjs — PostToolUse hook for Write/Edit on source files (src/, lib/)
4
+ * BLOCKING: Prevents writing source code while on main/master branch.
5
+ *
6
+ * v5.10.0 — Branch Discipline Enforcement
7
+ */
8
+
9
+ import { readStdin, git } from './lib/utils.mjs';
10
+
11
+ const input = readStdin();
12
+
13
+ // Extract file path
14
+ let filePath = '';
15
+ try {
16
+ const parsed = JSON.parse(input);
17
+ filePath = parsed.file_path || '';
18
+ } catch {
19
+ const match = input.match(/"file_path"\s*:\s*"([^"]*)"/);
20
+ filePath = match ? match[1] : '';
21
+ }
22
+
23
+ if (!filePath) {
24
+ process.exit(0);
25
+ }
26
+
27
+ // Only guard source code files (src/, lib/), not tests, docs, config, etc.
28
+ if (!/(^|\/)(?:src|lib)\//.test(filePath)) {
29
+ process.exit(0);
30
+ }
31
+
32
+ // Skip test files, config files, generated files
33
+ if (/(test\/|tests\/|\.test\.|\.spec\.|_test\.dart|\.g\.dart|\.freezed\.dart|\.config\.|\.json$|\.yaml$|\.md$)/.test(filePath)) {
34
+ process.exit(0);
35
+ }
36
+
37
+ // Check if we're in a git repository
38
+ const isGit = git('rev-parse --is-inside-work-tree');
39
+ if (!isGit) {
40
+ process.exit(0);
41
+ }
42
+
43
+ // Get current branch
44
+ const currentBranch = git('branch --show-current');
45
+
46
+ if (!currentBranch) {
47
+ // Detached HEAD or no branch — allow (could be during rebase)
48
+ process.exit(0);
49
+ }
50
+
51
+ // Block if on main or master
52
+ if (currentBranch === 'main' || currentBranch === 'master') {
53
+ console.log('');
54
+ console.log('============================================================');
55
+ console.log(` BRANCH GUARD: Writing source code on ${currentBranch} blocked`);
56
+ console.log('============================================================');
57
+ console.log(` File: ${filePath}`);
58
+ console.log(` Branch: ${currentBranch}`);
59
+ console.log('');
60
+ console.log(' The SpecBox Engine contract requires ALL implementation');
61
+ console.log(' code to be written on a feature branch, never on main.');
62
+ console.log('');
63
+ console.log(' To proceed:');
64
+ console.log(' 1. git checkout -b feature/{nombre-del-feature} main');
65
+ console.log(' 2. Then write your code on the feature branch');
66
+ console.log(' 3. Create a PR when ready to merge');
67
+ console.log('');
68
+ console.log(' If using /implement, this branch is created in Paso 1.');
69
+ console.log(' If implementing manually, create the branch FIRST.');
70
+ console.log('');
71
+ console.log(' This is non-negotiable. Code on main = no PR = no review');
72
+ console.log(' = no acceptance evidence = no traceability.');
73
+ console.log('============================================================');
74
+ console.log('');
75
+ process.exit(1);
76
+ }
77
+
78
+ // Not on main/master → allow
79
+ process.exit(0);
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * checkpoint-freshness-guard.mjs — PostToolUse hook for git commit
4
+ * NOTE to the agent (additionalContext, US-93/UC-9302): active UC with a stale (>30min) or
5
+ * missing checkpoint. Reminds the agent to save checkpoints for recovery.
6
+ *
7
+ * v5.19.0 — Compliance Enforcement
8
+ */
9
+
10
+ import { fileExists, fileAge, readJsonFile } from './lib/utils.mjs';
11
+ import { getActiveUC } from './lib/config.mjs';
12
+ import { noteWith } from './lib/output.mjs';
13
+ import { readHookInput, gitDirForCommand } from './lib/utils.mjs';
14
+
15
+ // The repo the commit went to (`cd <dir> && git commit`, `git -C <dir> commit`).
16
+ {
17
+ const { toolInput, cwd } = readHookInput();
18
+ try {
19
+ process.chdir(gitDirForCommand(String(toolInput.command || ''), cwd));
20
+ } catch {
21
+ process.exit(0);
22
+ }
23
+ }
24
+
25
+ // Only check if there's an active UC (implementation in progress)
26
+ const activeUC = getActiveUC();
27
+ if (!activeUC || !activeUC.feature) {
28
+ process.exit(0);
29
+ }
30
+
31
+ const feature = activeUC.feature;
32
+ const checkpointFile = `.quality/evidence/${feature}/checkpoint.json`;
33
+
34
+ if (!fileExists(checkpointFile)) {
35
+ noteWith('PostToolUse', `[CHECKPOINT] La feature «${feature}» no tiene checkpoint`, [
36
+ 'Si la sesión se corta, el avance se pierde.',
37
+ `Guárdalo: node .claude/hooks/implement-checkpoint.mjs ${feature} {N} {phase_name}`,
38
+ ]);
39
+ }
40
+
41
+ // Check freshness — warn if older than 30 minutes
42
+ const age = fileAge(checkpointFile);
43
+ const MAX_FRESHNESS_SECONDS = 30 * 60; // 30 minutes
44
+
45
+ if (age > MAX_FRESHNESS_SECONDS) {
46
+ const minutesAgo = Math.round(age / 60);
47
+ const checkpoint = readJsonFile(checkpointFile);
48
+ const phase = checkpoint ? `Phase ${checkpoint.phase} (${checkpoint.phase_name || 'unknown'})` : 'unknown phase';
49
+
50
+ noteWith('PostToolUse', `[CHECKPOINT] El último checkpoint de «${feature}» tiene ${minutesAgo} min (${phase})`, [
51
+ 'Guarda uno nuevo para no perder lo hecho desde entonces:',
52
+ `node .claude/hooks/implement-checkpoint.mjs ${feature} {N} {phase_name}`,
53
+ ]);
54
+ }
55
+
56
+ process.exit(0);
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * commit-spec-guard.mjs — PreToolUse hook for `git commit`
4
+ *
5
+ * BLOCKING (exit 2, before the commit exists):
6
+ * 1. Commit on main/master in a spec-driven project.
7
+ * NOTE to the agent (additionalContext, the commit goes ahead):
8
+ * 2. No active UC.
9
+ * 3. No checkpoint saved for the active feature.
10
+ * 4. Large commit (more than 15 staged files).
11
+ *
12
+ * Checks the repo the command acts on (`cd <dir> && git commit`, `git -C <dir> commit`), not the
13
+ * session's directory.
14
+ *
15
+ * v5.10.0 — Branch discipline · US-93/UC-9302: runs before the commit (it ran after it, so its
16
+ * «blocked» commit already existed) and its warnings reach the agent.
17
+ */
18
+
19
+ import { readHookInput, gitDirForCommand, git, fileExists, readJsonFile } from './lib/utils.mjs';
20
+ import { getProjectConfig } from './lib/config.mjs';
21
+ import { blockWith, noteWith } from './lib/output.mjs';
22
+
23
+ const { toolInput, cwd } = readHookInput();
24
+ const command = String(toolInput.command || '');
25
+ if (command && !/\bgit\b[^;&|]*\bcommit\b/.test(command)) process.exit(0);
26
+ try {
27
+ process.chdir(gitDirForCommand(command, cwd));
28
+ } catch {
29
+ process.exit(0);
30
+ }
31
+
32
+ const { boardId, isSpecDriven } = getProjectConfig();
33
+ if (!isSpecDriven) process.exit(0);
34
+
35
+ const branch = git('branch --show-current');
36
+ if (branch === 'main' || branch === 'master') {
37
+ blockWith(`COMMIT BLOQUEADO: no se hace commit en ${branch}`, [
38
+ 'Es un proyecto spec-driven: el trabajo va en una rama de la UC, nunca en main ni en master.',
39
+ 'Para seguir: git checkout -b feature/{uc}-{nombre} (los cambios se van contigo) y haz el commit ahí.',
40
+ ]);
41
+ }
42
+
43
+ const notes = [];
44
+ const activeUC = fileExists('.quality/active_uc.json') ? readJsonFile('.quality/active_uc.json') : null;
45
+ if (!activeUC) {
46
+ notes.push(`- No hay UC activa (board ${boardId}): llama a start_uc antes de implementar y a mark_ac_batch al terminar.`);
47
+ } else if (activeUC.feature && !fileExists(`.quality/evidence/${activeUC.feature}/checkpoint.json`)) {
48
+ notes.push(`- La feature «${activeUC.feature}» no tiene checkpoint: llama a report_checkpoint para poder retomarla.`);
49
+ }
50
+ const staged = git('diff --cached --name-only').split('\n').filter(Boolean).length;
51
+ if (staged > 15) {
52
+ notes.push(`- Commit grande (${staged} ficheros): mejor un commit por UC, para poder seguirlo y deshacerlo.`);
53
+ }
54
+
55
+ if (notes.length) {
56
+ noteWith('PreToolUse', 'SPEC GUARD: el commit sigue, pero conviene arreglar esto', [
57
+ ...notes,
58
+ 'Recorrido: find_next_uc → start_uc → implementar → mark_ac_batch → complete_uc.',
59
+ ]);
60
+ }
61
+ process.exit(0);