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,262 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * stripe-safety-guard.mjs — PreToolUse hook for Write/Edit on Stripe billing files
4
+ * BLOCKING: Detects and blocks 5 common Stripe anti-patterns that cause production bugs.
5
+ *
6
+ * Scope: files under src/billing/, lib/billing/, supabase/functions/stripe-*,
7
+ * supabase/functions/create-*-subscription/, supabase/functions/*-webhook/
8
+ *
9
+ * Detected anti-patterns (each with exit code 2 + actionable message):
10
+ * 1. sk_live_* hardcoded in code (not in .env* or .md)
11
+ * 2. Webhook handler without constructEvent/constructEventAsync (no signature verification)
12
+ * 3. Webhook handler without stripe_processed_events reference (no idempotency)
13
+ * 4. redirectToCheckout import or ui_mode: 'hosted' (hosted Checkout breaks embedded UX)
14
+ * 5. Payment Link URL (https://buy.stripe.com/) — same reason as #4
15
+ *
16
+ * Escape hatch: place `// stripe-safety-guard:ignore` on the line ABOVE the offending pattern
17
+ * to skip the check. Use sparingly, document why.
18
+ *
19
+ * v5.25.0 — Stripe Connect skill
20
+ * v5.27.0 — Reused unchanged by /stripe-standard (Stripe non-Connect accounts).
21
+ * The same anti-patterns apply: sk_live_*, missing signature
22
+ * verification, missing idempotency, hosted checkout, Payment Links.
23
+ * Standard mode has 1 webhook endpoint instead of 2 — still scanned.
24
+ */
25
+
26
+ import { readFileSync, existsSync } from 'fs';
27
+ import { readStdin } from './lib/utils.mjs';
28
+ import { blockWith } from './lib/output.mjs';
29
+
30
+ const input = readStdin();
31
+
32
+ // --- Extract file path and file content from tool input ---
33
+ let filePath = '';
34
+ let fileContent = '';
35
+ try {
36
+ const parsed = JSON.parse(input);
37
+ filePath = parsed.file_path || parsed.tool_input?.file_path || '';
38
+ // For Write: full content is in `content` or `tool_input.content`
39
+ // For Edit: the new content is in `new_string` — we need to scan that + existing file
40
+ fileContent =
41
+ parsed.content ||
42
+ parsed.tool_input?.content ||
43
+ parsed.new_string ||
44
+ parsed.tool_input?.new_string ||
45
+ '';
46
+ } catch {
47
+ // Permissive fallback — still try to extract file_path
48
+ const pathMatch = input.match(/"file_path"\s*:\s*"([^"]*)"/);
49
+ filePath = pathMatch ? pathMatch[1] : '';
50
+ }
51
+
52
+ if (!filePath) process.exit(0);
53
+
54
+ // --- Only guard billing-related files ---
55
+ const BILLING_PATH_RE =
56
+ /(^|\/)(src\/billing|lib\/billing|supabase\/functions\/(stripe-|create-.*-subscription|cancel-.*-subscription|.*-webhook))/;
57
+
58
+ if (!BILLING_PATH_RE.test(filePath)) process.exit(0);
59
+
60
+ // --- Skip files that are legitimately allowed to contain these patterns ---
61
+ // .env* files: CAN contain sk_test_/sk_live_ references (though we still flag sk_live_ hardcoded in .env.example)
62
+ // .md files: documentation, allowed to reference everything
63
+ // test files: may reference patterns intentionally
64
+ if (/(\.env(\..*)?$|\.md$|\.test\.|\.spec\.|(^|\/)tests?\/)/.test(filePath)) process.exit(0);
65
+
66
+ // --- Build the content to scan ---
67
+ // Prefer the new content being written; fall back to existing file if empty
68
+ let content = fileContent;
69
+ if (!content && existsSync(filePath)) {
70
+ try {
71
+ content = readFileSync(filePath, 'utf-8');
72
+ } catch {
73
+ content = '';
74
+ }
75
+ }
76
+
77
+ if (!content) process.exit(0);
78
+
79
+ // --- Check for escape hatch marker to disable the hook entirely for this file ---
80
+ // (Line-level escapes are handled per-rule below.)
81
+ if (/\/\/\s*stripe-safety-guard:disable-file/i.test(content)) process.exit(0);
82
+
83
+ // --- Helper: line-by-line scan with escape-hatch awareness ---
84
+ const lines = content.split('\n');
85
+
86
+ function lineIsIgnored(lineIdx) {
87
+ if (lineIdx <= 0) return false;
88
+ const prev = lines[lineIdx - 1] || '';
89
+ return /\/\/\s*stripe-safety-guard:ignore/i.test(prev);
90
+ }
91
+
92
+ function findLineMatches(regex) {
93
+ const hits = [];
94
+ for (let i = 0; i < lines.length; i++) {
95
+ if (regex.test(lines[i]) && !lineIsIgnored(i)) {
96
+ hits.push({ line: i + 1, text: lines[i].trim() });
97
+ }
98
+ }
99
+ return hits;
100
+ }
101
+
102
+ // --- Anti-pattern #1: sk_live_* hardcoded ---
103
+ const SK_LIVE_RE = /sk_live_[A-Za-z0-9]{10,}/;
104
+ const skLiveHits = findLineMatches(SK_LIVE_RE);
105
+ if (skLiveHits.length > 0) {
106
+ block(
107
+ 'sk_live_* hardcoded in code',
108
+ [
109
+ `Found Stripe LIVE secret key hardcoded in ${filePath}:`,
110
+ ...skLiveHits.slice(0, 3).map(h => ` L${h.line}: ${h.text.slice(0, 120)}`),
111
+ '',
112
+ 'Why this is blocked:',
113
+ ' Live secret keys in code leak via git history, CI logs, build artifacts',
114
+ ' and distributed bundles. A leaked sk_live_* gives full API access to',
115
+ ' your Stripe account (move money, refund, read all customer data).',
116
+ '',
117
+ 'Correct pattern:',
118
+ ' const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!, { ... });',
119
+ ' // Set STRIPE_SECRET_KEY in .env (never committed) or Supabase project secrets',
120
+ ].join('\n'),
121
+ );
122
+ }
123
+
124
+ // --- Anti-pattern #2: Webhook handler without constructEvent / constructEventAsync ---
125
+ // Trigger only on files whose path identifies them as webhook handlers
126
+ const IS_WEBHOOK_HANDLER = /(^|\/)supabase\/functions\/.*-webhook\/index\.(ts|js)$|(^|\/)(src|lib)\/billing\/.*webhook.*\.(ts|js|dart)$/i.test(
127
+ filePath,
128
+ );
129
+ if (IS_WEBHOOK_HANDLER) {
130
+ const hasSignatureVerification =
131
+ /constructEvent(Async)?\s*\(/.test(content) ||
132
+ /\/\/\s*stripe-safety-guard:ignore-signature/i.test(content);
133
+ if (!hasSignatureVerification) {
134
+ block(
135
+ 'Webhook handler without signature verification',
136
+ [
137
+ `File ${filePath} looks like a Stripe webhook handler but never calls`,
138
+ ' stripe.webhooks.constructEvent(...) or constructEventAsync(...).',
139
+ '',
140
+ 'Why this is blocked:',
141
+ ' Without signature verification, anyone who discovers your webhook URL can',
142
+ ' send forged events (fake invoice.paid, fake subscription.deleted) and',
143
+ ' manipulate your database. Verification is mandatory per Stripe docs.',
144
+ '',
145
+ 'Correct pattern (Deno / Edge Function):',
146
+ ' const signature = req.headers.get("stripe-signature")!;',
147
+ ' const event = await stripe.webhooks.constructEventAsync(',
148
+ ' await req.text(),',
149
+ ' signature,',
150
+ ' Deno.env.get("STRIPE_WEBHOOK_SECRET")!,',
151
+ ' );',
152
+ ].join('\n'),
153
+ );
154
+ }
155
+
156
+ // --- Anti-pattern #3: Webhook handler without idempotency table reference ---
157
+ const hasIdempotencyRef =
158
+ /stripe_processed_events/.test(content) ||
159
+ /\/\/\s*stripe-safety-guard:ignore-idempotency/i.test(content);
160
+ if (!hasIdempotencyRef) {
161
+ block(
162
+ 'Webhook handler without idempotency check',
163
+ [
164
+ `File ${filePath} is a webhook handler but never references the`,
165
+ ' stripe_processed_events table.',
166
+ '',
167
+ 'Why this is blocked:',
168
+ ' Stripe retries webhooks on non-2xx responses and on network timeouts.',
169
+ ' Without idempotency, the same event (e.g. invoice.paid) can be processed',
170
+ ' multiple times → double provisioning, double emails, double side effects.',
171
+ ' This is the #1 cause of billing bugs in production Stripe integrations.',
172
+ '',
173
+ 'Correct pattern:',
174
+ ' // Check BEFORE processing',
175
+ ' const { data: existing } = await supabase',
176
+ ' .from("stripe_processed_events")',
177
+ ' .select("event_id").eq("event_id", event.id).maybeSingle();',
178
+ ' if (existing) return new Response("OK", { status: 200 });',
179
+ ' // ... process event ...',
180
+ ' await supabase.from("stripe_processed_events").insert({',
181
+ ' event_id: event.id, event_type: event.type, received_at: new Date().toISOString(),',
182
+ ' });',
183
+ ].join('\n'),
184
+ );
185
+ }
186
+ }
187
+
188
+ // --- Anti-pattern #4: redirectToCheckout / hosted Checkout mode ---
189
+ const HOSTED_CHECKOUT_PATTERNS = [
190
+ /\bredirectToCheckout\s*\(/,
191
+ /ui_mode\s*:\s*['"]hosted['"]/,
192
+ /mode\s*:\s*['"]hosted['"].*checkout/i,
193
+ ];
194
+ for (const re of HOSTED_CHECKOUT_PATTERNS) {
195
+ const hits = findLineMatches(re);
196
+ if (hits.length > 0) {
197
+ block(
198
+ 'Hosted Checkout redirect detected (embedded-only policy)',
199
+ [
200
+ `Found hosted Checkout pattern in ${filePath}:`,
201
+ ...hits.slice(0, 3).map(h => ` L${h.line}: ${h.text.slice(0, 120)}`),
202
+ '',
203
+ 'Why this is blocked:',
204
+ ' /stripe-connect generates embedded-only integrations by design:',
205
+ ' Payment Element (React) / Payment Sheet (Flutter) + Apple/Google Pay.',
206
+ ' Redirecting the user out of your app to stripe.com breaks UX, prevents',
207
+ ' native payment methods (Apple Pay sheet), and shows Stripe branding',
208
+ ' in the browser URL during checkout. Direct charges + embedded also',
209
+ ' give you full control over error handling and retry UX.',
210
+ '',
211
+ 'Correct pattern (React):',
212
+ ' <Elements stripe={stripePromise} options={{ clientSecret }}>',
213
+ ' <PaymentElement />',
214
+ ' <ExpressCheckoutElement />',
215
+ ' </Elements>',
216
+ ' // submit via stripe.confirmPayment({ elements, ... })',
217
+ ].join('\n'),
218
+ );
219
+ }
220
+ }
221
+
222
+ // --- Anti-pattern #5: Payment Link URL hardcoded ---
223
+ const PAYMENT_LINK_RE = /https:\/\/buy\.stripe\.com\/[A-Za-z0-9_]+/;
224
+ const paymentLinkHits = findLineMatches(PAYMENT_LINK_RE);
225
+ if (paymentLinkHits.length > 0) {
226
+ block(
227
+ 'Payment Link URL detected (embedded-only policy)',
228
+ [
229
+ `Found Stripe Payment Link in ${filePath}:`,
230
+ ...paymentLinkHits.slice(0, 3).map(h => ` L${h.line}: ${h.text.slice(0, 120)}`),
231
+ '',
232
+ 'Why this is blocked:',
233
+ ' Payment Links are hosted checkout — same UX problem as redirectToCheckout.',
234
+ ' They also bypass your own subscription/fee logic (no application_fee_percent,',
235
+ ' no Direct charge routing to connected accounts). They are the wrong tool',
236
+ ' for a marketplace integration.',
237
+ '',
238
+ 'Correct pattern:',
239
+ ' Create a Subscription or PaymentIntent on your backend with:',
240
+ ' application_fee_percent: rider.fee_percent,',
241
+ ' transfer_data: { destination: rider.stripe_account_id }, // if destination charges',
242
+ ' // OR pass Stripe-Account header for Direct charges',
243
+ ' Then confirm payment with PaymentElement on the client.',
244
+ ].join('\n'),
245
+ );
246
+ }
247
+
248
+ // All checks passed
249
+ process.exit(0);
250
+
251
+ // ===== helpers =====
252
+ function block(title, body) {
253
+ // stderr + exit 2: the write does not happen and the agent gets the reason (US-93/UC-9302: the
254
+ // reason went to stdout, so the agent was blocked without knowing why).
255
+ blockWith(`STRIPE SAFETY GUARD: ${title}`, [
256
+ ...String(body).split('\n'),
257
+ '',
258
+ 'Escape hatch (use sparingly, document why):',
259
+ ' Add `// stripe-safety-guard:ignore` on the line ABOVE the pattern',
260
+ ' Or `// stripe-safety-guard:disable-file` at the top of the file',
261
+ ]);
262
+ }
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * uc-lifecycle-guard.mjs — PostToolUse hook for git push
4
+ * NOTE to the agent (additionalContext, US-93/UC-9302): pushing a feature branch without having
5
+ * called move_uc to move the UC to Review. Ensures the board stays in sync.
6
+ *
7
+ * Also warns if mark_ac_batch hasn't been called (no ACs marked).
8
+ *
9
+ * v5.19.0 — Compliance Enforcement
10
+ */
11
+
12
+ import { readHookInput, gitDirForCommand, git, fileExists, readJsonFile } from './lib/utils.mjs';
13
+ import { getProjectConfig, getActiveUC } from './lib/config.mjs';
14
+ import { noteWith } from './lib/output.mjs';
15
+
16
+ const { toolInput, cwd } = readHookInput();
17
+ const command = String(toolInput.command || '');
18
+
19
+ // Only check git push commands
20
+ if (!command.includes('git push')) {
21
+ process.exit(0);
22
+ }
23
+ // The repo the push comes from (`cd <dir> && git push`, `git -C <dir> push`).
24
+ try {
25
+ process.chdir(gitDirForCommand(command, cwd, 'push'));
26
+ } catch {
27
+ process.exit(0);
28
+ }
29
+
30
+ // Only check spec-driven projects
31
+ const { isSpecDriven } = getProjectConfig();
32
+ if (!isSpecDriven) {
33
+ process.exit(0);
34
+ }
35
+
36
+ // Only check feature branches
37
+ const branch = git('branch --show-current');
38
+ if (!branch || !branch.startsWith('feature/')) {
39
+ process.exit(0);
40
+ }
41
+
42
+ // Check if there's an active UC
43
+ const activeUC = getActiveUC();
44
+ if (!activeUC) {
45
+ // No active UC but pushing feature branch — unusual but not necessarily wrong
46
+ // (could be pushing after complete_uc was already called)
47
+ process.exit(0);
48
+ }
49
+
50
+ const feature = activeUC.feature;
51
+ const warnings = [];
52
+
53
+ // Check 1: Has mark_ac_batch been called?
54
+ // We detect this by checking if any AC evidence exists
55
+ const evidenceDir = `.quality/evidence/${feature}`;
56
+ const acMarkerFile = `${evidenceDir}/ac_marked.json`;
57
+ if (!fileExists(acMarkerFile)) {
58
+ // Also check the audit.json for any AC data
59
+ const audit = readJsonFile(`${evidenceDir}/audit.json`);
60
+ if (!audit || !audit.ac_results) {
61
+ warnings.push(
62
+ 'No acceptance criteria have been marked (mark_ac_batch not called). ' +
63
+ 'The board will not reflect which ACs passed.'
64
+ );
65
+ }
66
+ }
67
+
68
+ // Check 2: Has the UC been moved to Review?
69
+ // We detect this by checking if a move_uc marker exists
70
+ const moveMarkerFile = `${evidenceDir}/uc_moved_to_review.json`;
71
+ if (!fileExists(moveMarkerFile)) {
72
+ warnings.push(
73
+ `UC "${activeUC.ucId}" has NOT been moved to Review. ` +
74
+ 'Call move_uc(board_id, uc_id, "review") before or after creating the PR. ' +
75
+ 'The board must reflect the current state.'
76
+ );
77
+ }
78
+
79
+ if (warnings.length > 0) {
80
+ noteWith('PostToolUse', 'UC LIFECYCLE: el board puede no reflejar lo que hay', [
81
+ `Feature: ${feature} · UC: ${activeUC.ucId} · rama: ${branch}`,
82
+ ...warnings.map((w) => `- ${w}`),
83
+ 'El push ya está hecho; pon el board al día ahora.',
84
+ ]);
85
+ }
86
+
87
+ process.exit(0);
package/lib/hooks.mjs ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * UC-11201 — actualizar los hooks de un proyecto sin pisar lo que se cambió en local.
3
+ *
4
+ * Cada proyecto ejecuta su copia de los hooks (`node .claude/hooks/<hook>.mjs`).
5
+ * El paquete trae los hooks publicados con su huella (hooks-manifest.json) y las
6
+ * huellas de las versiones anteriores (hooks-history.json); el proyecto guarda
7
+ * en `.claude/hooks/.specbox-hooks.json` qué instaló. Con eso cada fichero queda en:
8
+ *
9
+ * current igual que el publicado
10
+ * updatable sin retocar (huella de una versión publicada o de lo instalado): se sustituye
11
+ * modified retocado en local: no se toca; la versión nueva queda al lado (<hook>.mjs.new)
12
+ * salvo que se pida sobrescribirlo
13
+ * missing no está en el proyecto: se instala
14
+ * retired lo instaló una versión anterior y ya no se publica: se lista, no se borra
15
+ *
16
+ * `.claude/settings.json` solo gana registros: los hooks de la plantilla que no estén.
17
+ */
18
+ import { createHash } from "node:crypto";
19
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+
23
+ export const REGISTRY = ".specbox-hooks.json";
24
+ const LIB_DIR = dirname(fileURLToPath(import.meta.url));
25
+
26
+ function sha256(content) {
27
+ return createHash("sha256").update(content).digest("hex");
28
+ }
29
+
30
+ function readJson(path, fallback = null) {
31
+ try {
32
+ return JSON.parse(readFileSync(path, "utf8"));
33
+ } catch {
34
+ return fallback;
35
+ }
36
+ }
37
+
38
+ function writeAtomic(path, content) {
39
+ mkdirSync(dirname(path), { recursive: true });
40
+ const tmp = `${path}.${process.pid}.tmp`;
41
+ writeFileSync(tmp, content);
42
+ renameSync(tmp, path);
43
+ }
44
+
45
+ /** Los hooks que trae este paquete (o null si se ejecuta desde un clon sin empaquetar). */
46
+ export function loadPackaged(dir = join(LIB_DIR, "..", "hooks")) {
47
+ const manifest = readJson(join(dir, "hooks-manifest.json"));
48
+ if (!manifest?.files) return null;
49
+ return {
50
+ dir,
51
+ version: manifest.version,
52
+ files: manifest.files,
53
+ history: readJson(join(dir, "hooks-history.json"), {}),
54
+ settingsHooks: readJson(join(dir, "settings-hooks.json"), {}),
55
+ };
56
+ }
57
+
58
+ function registrations(hooks) {
59
+ const out = [];
60
+ for (const [event, groups] of Object.entries(hooks ?? {})) {
61
+ for (const group of groups ?? []) {
62
+ for (const hook of group.hooks ?? []) out.push({ event, matcher: group.matcher, hook });
63
+ }
64
+ }
65
+ return out;
66
+ }
67
+
68
+ /** Los registros de la plantilla que faltan en el settings.json del proyecto. */
69
+ export function missingRegistrations(settings, settingsHooks) {
70
+ const present = new Set(registrations(settings?.hooks).map((r) => `${r.event}\u0000${r.hook.command}`));
71
+ return registrations(settingsHooks).filter((r) => !present.has(`${r.event}\u0000${r.hook.command}`));
72
+ }
73
+
74
+ /** El estado de cada hook del proyecto frente a los publicados (AC-01). */
75
+ export function hooksStatus({ projectRoot, packaged }) {
76
+ const hooksDir = join(projectRoot, ".claude", "hooks");
77
+ const registry = readJson(join(hooksDir, REGISTRY), {});
78
+ const hooks = [];
79
+ for (const [path, published] of Object.entries(packaged.files)) {
80
+ const local = join(hooksDir, path);
81
+ if (!existsSync(local)) {
82
+ hooks.push({ path, state: "missing" });
83
+ continue;
84
+ }
85
+ const hash = sha256(readFileSync(local));
86
+ let state = "modified";
87
+ if (hash === published) state = "current";
88
+ else if (hash === registry.files?.[path] || (packaged.history[path] ?? []).includes(hash)) state = "updatable";
89
+ hooks.push({ path, state });
90
+ }
91
+ for (const path of Object.keys(registry.files ?? {})) {
92
+ if (!(path in packaged.files) && existsSync(join(hooksDir, path))) hooks.push({ path, state: "retired" });
93
+ }
94
+ const settings = readJson(join(projectRoot, ".claude", "settings.json"), {});
95
+ const settingsMissing = missingRegistrations(settings, packaged.settingsHooks).map((r) => ({
96
+ event: r.event,
97
+ matcher: r.matcher ?? null,
98
+ command: r.hook.command,
99
+ }));
100
+ return {
101
+ version: packaged.version,
102
+ installed_version: registry.version ?? null,
103
+ hooks,
104
+ settings_missing: settingsMissing,
105
+ differs: hooks.some((h) => h.state !== "current") || settingsMissing.length > 0,
106
+ };
107
+ }
108
+
109
+ const matches = (path, wanted) => wanted.some((w) => w === path || w === path.replace(/\.mjs$/, "") || `lib/${w}` === path || `lib/${w}.mjs` === path);
110
+
111
+ /**
112
+ * Aplica la actualización (AC-02/AC-03). `overwrite`: hooks retocados que sí se
113
+ * sustituyen (nombre o ruta, con o sin .mjs). Devuelve qué se hizo.
114
+ */
115
+ export function updateHooks({ projectRoot, packaged, overwrite = [], now = () => new Date().toISOString() }) {
116
+ const status = hooksStatus({ projectRoot, packaged });
117
+ const hooksDir = join(projectRoot, ".claude", "hooks");
118
+ const result = { version: packaged.version, written: [], kept: [], retired: [], settings_added: 0, settings_backup: null };
119
+ for (const { path, state } of status.hooks) {
120
+ const source = join(packaged.dir, path);
121
+ const local = join(hooksDir, path);
122
+ if (state === "missing" || state === "updatable" || (state === "modified" && matches(path, overwrite))) {
123
+ writeAtomic(local, readFileSync(source));
124
+ result.written.push(path);
125
+ } else if (state === "modified") {
126
+ writeAtomic(`${local}.new`, readFileSync(source));
127
+ result.kept.push({ path, new: `.claude/hooks/${path}.new` });
128
+ } else if (state === "retired") {
129
+ result.retired.push(path);
130
+ }
131
+ }
132
+ // A retired hook stays in the registry while it is on disk, so it keeps being listed.
133
+ const previous = readJson(join(hooksDir, REGISTRY), {}).files ?? {};
134
+ const files = { ...packaged.files };
135
+ for (const path of result.retired) files[path] = previous[path];
136
+ writeAtomic(join(hooksDir, REGISTRY), `${JSON.stringify({ version: packaged.version, updated_at: now(), files }, null, 2)}\n`);
137
+
138
+ const settingsPath = join(projectRoot, ".claude", "settings.json");
139
+ if (status.settings_missing.length) {
140
+ const settings = readJson(settingsPath, {});
141
+ if (existsSync(settingsPath)) {
142
+ result.settings_backup = ".claude/settings.json.bak";
143
+ copyFileSync(settingsPath, `${settingsPath}.bak`);
144
+ }
145
+ settings.hooks ??= {};
146
+ for (const r of missingRegistrations(settings, packaged.settingsHooks)) {
147
+ const groups = (settings.hooks[r.event] ??= []);
148
+ const group = groups.find((g) => (g.matcher ?? null) === (r.matcher ?? null));
149
+ if (group) (group.hooks ??= []).push(r.hook);
150
+ else groups.push(r.matcher === undefined ? { hooks: [r.hook] } : { matcher: r.matcher, hooks: [r.hook] });
151
+ result.settings_added += 1;
152
+ }
153
+ writeAtomic(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
154
+ }
155
+ return result;
156
+ }
package/lib/install.mjs CHANGED
@@ -20,6 +20,15 @@ export function packageVersion() {
20
20
  }
21
21
  }
22
22
 
23
+ /** La versión del ayudante instalado en `~/.specbox/bin`, o null si no hay. */
24
+ export function installedHelperVersion(home) {
25
+ try {
26
+ return JSON.parse(readFileSync(join(home, "bin", "package.json"), "utf8")).specbox_helper_version ?? null;
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
23
32
  export function installHelper(home, { sourceDir = LIB_DIR, version = packageVersion() } = {}) {
24
33
  const bin = join(home, "bin");
25
34
  mkdirSync(bin, { recursive: true, mode: 0o700 });
package/lib/internal.mjs CHANGED
@@ -8,8 +8,8 @@
8
8
  * stdout; la entrada, si la hay, por stdin) y no aparecen en `--help`.
9
9
  *
10
10
  * _device id y nombre del dispositivo (los mismos que usa `specbox login`)
11
- * _status ¿hay credencial? dispositivo, caducidad y si Claude Code usa el ayudante
12
- * (nunca el token: solo su huella)
11
+ * _status ¿hay credencial? dispositivo, caducidad, si Claude Code usa el ayudante y
12
+ * si el ayudante instalado es el de esta versión (nunca el token: solo su huella)
13
13
  * _connect guarda la credencial que trae la extensión, instala el ayudante y
14
14
  * configura Claude Code
15
15
  * _configure instala el ayudante y configura Claude Code, sin credencial
@@ -18,12 +18,15 @@
18
18
  * pegado en otros sitios) y lo conecta como `_connect`
19
19
  * _renew renueva si toca y devuelve el token vigente (para la extensión)
20
20
  * _disconnect /devices/logout y borra la credencial local
21
+ * _hooks_status {project_root} → el estado de cada hook frente a los publicados (UC-11201)
22
+ * _hooks_update {project_root, overwrite} → actualiza sin pisar los retocados
21
23
  */
22
24
  import { createHash } from "node:crypto";
23
25
  import { claudeUsesHelper, configureClaudeCode, helperCommand, stableNodePath } from "./claude.mjs";
24
26
  import { CLIENT } from "./config.mjs";
25
27
  import { deviceId, hostLabel } from "./device.mjs";
26
- import { installHelper } from "./install.mjs";
28
+ import { hooksStatus, loadPackaged, updateHooks } from "./hooks.mjs";
29
+ import { installHelper, installedHelperVersion, packageVersion } from "./install.mjs";
27
30
  import { credentialFromResponse, renewCredential, renewDue } from "./renew.mjs";
28
31
 
29
32
  export async function readStdinJson(stream = process.stdin) {
@@ -86,6 +89,9 @@ export async function runInternal(command, ctx) {
86
89
  store: store.kind,
87
90
  ...(credential?.token ? credentialMeta(credential) : {}),
88
91
  claude_helper: usesHelper(),
92
+ // UC-11301: an older helper in ~/.specbox/bin does not send the Stitch key;
93
+ // the extension reinstalls it with `_configure` when this is false.
94
+ helper_current: installedHelperVersion(home) === (deps.packageVersion ?? packageVersion()),
89
95
  });
90
96
  return 0;
91
97
  }
@@ -184,6 +190,23 @@ export async function runInternal(command, ctx) {
184
190
  return 0;
185
191
  }
186
192
 
193
+ case "_hooks_status":
194
+ case "_hooks_update": {
195
+ const { project_root: projectRoot, overwrite = [] } = await readInput();
196
+ const packaged = (deps.loadPackaged ?? loadPackaged)();
197
+ if (!projectRoot || !packaged) {
198
+ out({ ok: false, reason: projectRoot ? "not_packaged" : "missing_project_root" });
199
+ return 1;
200
+ }
201
+ const status = hooksStatus({ projectRoot, packaged });
202
+ if (command === "_hooks_status") {
203
+ out({ ok: true, ...status });
204
+ return 0;
205
+ }
206
+ out({ ok: true, ...updateHooks({ projectRoot, packaged, overwrite }) });
207
+ return 0;
208
+ }
209
+
187
210
  default:
188
211
  out({ ok: false, reason: "unknown_command" });
189
212
  return 1;
@@ -13,28 +13,56 @@
13
13
  * conectarse). Nunca imprime otra cosa por stdout ni falla: un error de
14
14
  * Claude Code aquí dejaría a la persona sin MCP.
15
15
  *
16
+ * UC-11301: también manda la clave de Stitch del proyecto (`X-Stitch-Api-Key`),
17
+ * para que llegue al servidor sin pasar por la conversación.
18
+ *
16
19
  * Se instala en ~/.specbox/bin junto a los módulos que importa.
17
20
  */
18
- import { realpathSync } from "node:fs";
21
+ import { readFileSync, realpathSync } from "node:fs";
22
+ import { dirname, join, resolve } from "node:path";
19
23
  import { pathToFileURL } from "node:url";
20
24
  import { DEFAULT_MCP_URL, accountFor, specboxHome } from "./config.mjs";
21
25
  import { renewCredential, renewDue } from "./renew.mjs";
22
26
  import { createStore } from "./store.mjs";
23
27
 
28
+ export const STITCH_HEADER = "X-Stitch-Api-Key";
29
+
30
+ /**
31
+ * La clave de Stitch: `STITCH_API_KEY` del entorno o `stitch.apiKey` del
32
+ * `.claude/settings.local.json` más cercano subiendo desde la carpeta del
33
+ * proyecto (donde la deja /visual-setup). null si no hay.
34
+ */
35
+ export function stitchKeyFor({ env = process.env, cwd = env.CLAUDE_PROJECT_DIR || process.cwd() } = {}) {
36
+ const fromEnv = (env.STITCH_API_KEY || "").trim();
37
+ if (fromEnv) return fromEnv;
38
+ for (let dir = resolve(cwd); ; dir = dirname(dir)) {
39
+ try {
40
+ const key = JSON.parse(readFileSync(join(dir, ".claude", "settings.local.json"), "utf8"))?.stitch?.apiKey;
41
+ if (typeof key === "string" && key.trim()) return key.trim();
42
+ } catch {
43
+ // sin fichero o con JSON roto: se sigue subiendo
44
+ }
45
+ if (dirname(dir) === dir) return null;
46
+ }
47
+ }
48
+
24
49
  export async function headersFor({
25
50
  env = process.env,
26
51
  store = createStore({ home: specboxHome(env) }),
27
52
  fetchImpl = fetch,
28
53
  now = Date.now(),
54
+ cwd,
29
55
  } = {}) {
30
56
  const url = env.CLAUDE_CODE_MCP_SERVER_URL || env.SPECBOX_MCP_URL || DEFAULT_MCP_URL;
31
57
  const account = accountFor(url);
58
+ const stitchKey = stitchKeyFor(cwd ? { env, cwd } : { env });
59
+ const headers = stitchKey ? { [STITCH_HEADER]: stitchKey } : {};
32
60
  let credential = store.read(account);
33
- if (!credential?.token) return {};
61
+ if (!credential?.token) return headers;
34
62
  if (renewDue(credential, now)) {
35
63
  credential = await renewCredential({ store, account, credential, fetchImpl, lockDir: specboxHome(env) });
36
64
  }
37
- return { Authorization: `Bearer ${credential.token}` };
65
+ return { Authorization: `Bearer ${credential.token}`, ...headers };
38
66
  }
39
67
 
40
68
  // Por `npx`/npm el script se ejecuta a través de un enlace simbólico: se