@prave/cli 1.2.0 → 1.2.1

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.
@@ -1,9 +1,47 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
1
3
  import chalk from 'chalk';
2
4
  import ora from 'ora';
3
5
  import { track } from '../lib/analytics.js';
4
6
  import { api, ApiError } from '../lib/api.js';
7
+ import { CONFIG } from '../lib/config.js';
5
8
  import { requireAuth } from '../lib/credentials.js';
9
+ import { checkboxPrompt } from '../lib/prompt.js';
10
+ import { isValidSlug } from '../lib/slug.js';
6
11
  import { log } from '../utils/logger.js';
12
+ import { uninstallCommand } from './uninstall.js';
13
+ /**
14
+ * Resolve a `skill_metadata` row back to its on-disk slug, mirroring
15
+ * the canonical `~/.claude/skills/<slug>/SKILL.md` layout used by
16
+ * `prave optimize --remove-unused`. Returns `null` when the slug
17
+ * fails the registry regex (defence against `..` injection via a
18
+ * malformed `file_path`).
19
+ */
20
+ function slugOf(s) {
21
+ const segs = s.file_path?.split('/').filter(Boolean) ?? [];
22
+ let candidate = null;
23
+ if (segs.length >= 2) {
24
+ const last = segs[segs.length - 1];
25
+ const parent = segs[segs.length - 2];
26
+ if (last.toLowerCase().endsWith('skill.md'))
27
+ candidate = parent;
28
+ }
29
+ if (!candidate && s.name) {
30
+ candidate = s.name.trim().toLowerCase().replace(/\s+/g, '-');
31
+ }
32
+ if (!candidate)
33
+ return null;
34
+ return isValidSlug(candidate) ? candidate : null;
35
+ }
36
+ async function existsOnDisk(slug) {
37
+ try {
38
+ const st = await stat(join(CONFIG.skillsDir, slug));
39
+ return st.isDirectory();
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
7
45
  function describe(c) {
8
46
  const a = c.skill_a_name ?? c.skill_a_id;
9
47
  const b = c.skill_b_name ?? c.skill_b_id;
@@ -44,8 +82,70 @@ export async function conflictsCommand(opts = {}) {
44
82
  console.log(`${chalk.yellow('⚠️ ')} ${describe(c)}`);
45
83
  }
46
84
  if (opts.fix) {
85
+ // Interactive resolution: the most common (and safest) fix for a
86
+ // conflict is uninstalling one of the two competing Skills. We
87
+ // build a checkbox list of the unique slugs that appear in the
88
+ // conflict set, restricted to ones we can resolve back to a real
89
+ // on-disk folder (so we never offer to "uninstall" something the
90
+ // user hasn't actually got installed).
91
+ let metadata = [];
92
+ try {
93
+ const { data } = await api.get('/api/v1/intelligence/skills', true);
94
+ metadata = data;
95
+ }
96
+ catch (err) {
97
+ log.warn(`Could not fetch skill metadata — ${err.message}`);
98
+ }
99
+ // Tally how many conflicts each Skill participates in. Heuristic:
100
+ // a skill that conflicts with two others is the strongest fix
101
+ // candidate (uninstalling it resolves multiple rows at once), so
102
+ // we surface it first.
103
+ const conflictCount = new Map();
104
+ for (const c of conflicts) {
105
+ conflictCount.set(c.skill_a_id, (conflictCount.get(c.skill_a_id) ?? 0) + 1);
106
+ conflictCount.set(c.skill_b_id, (conflictCount.get(c.skill_b_id) ?? 0) + 1);
107
+ }
108
+ const candidates = [];
109
+ const seen = new Set();
110
+ for (const m of metadata) {
111
+ if (!conflictCount.has(m.id))
112
+ continue;
113
+ const slug = slugOf(m);
114
+ if (!slug || seen.has(slug))
115
+ continue;
116
+ if (!(await existsOnDisk(slug)))
117
+ continue;
118
+ seen.add(slug);
119
+ candidates.push({
120
+ slug,
121
+ name: m.name ?? slug,
122
+ count: conflictCount.get(m.id) ?? 1,
123
+ });
124
+ }
125
+ candidates.sort((a, b) => b.count - a.count || a.slug.localeCompare(b.slug));
126
+ if (candidates.length === 0) {
127
+ console.log();
128
+ log.dim('Nothing to auto-fix — no conflicting Skills are installed under ~/.claude/skills/. ' +
129
+ 'Run `prave whatdoes <skill>` to inspect frontmatter and resolve manually.');
130
+ return;
131
+ }
132
+ console.log();
133
+ const picks = await checkboxPrompt('Select Skills to uninstall:', candidates.map((c) => ({
134
+ value: c.slug,
135
+ label: c.name,
136
+ hint: c.count > 1
137
+ ? `${c.count} conflicts · ${c.slug}`
138
+ : `1 conflict · ${c.slug}`,
139
+ })));
140
+ if (!picks || picks.length === 0) {
141
+ log.dim('Aborted — nothing removed.');
142
+ return;
143
+ }
144
+ for (const slug of picks) {
145
+ await uninstallCommand(slug);
146
+ }
47
147
  console.log();
48
- log.dim('Interactive fix coming soon — for now run `prave whatdoes <skill>` and adjust frontmatter manually.');
148
+ log.dim(`Removed ${picks.length} skill(s). Run ${chalk.cyan('prave sync')} to refresh server-side metadata.`);
49
149
  }
50
150
  }
51
151
  catch (err) {
@@ -1,9 +1,13 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import readline from 'node:readline/promises';
1
4
  import chalk from 'chalk';
2
5
  import ora from 'ora';
3
- import readline from 'node:readline/promises';
4
6
  import { track } from '../lib/analytics.js';
5
7
  import { api, ApiError } from '../lib/api.js';
8
+ import { CONFIG } from '../lib/config.js';
6
9
  import { requireAuth } from '../lib/credentials.js';
10
+ import { checkboxPrompt } from '../lib/prompt.js';
7
11
  import { isValidSlug } from '../lib/slug.js';
8
12
  import { log } from '../utils/logger.js';
9
13
  import { uninstallCommand } from './uninstall.js';
@@ -40,6 +44,15 @@ function slugOf(s) {
40
44
  // injected via a malformed `file_path`.
41
45
  return isValidSlug(candidate) ? candidate : null;
42
46
  }
47
+ async function existsOnDisk(slug) {
48
+ try {
49
+ const st = await stat(join(CONFIG.skillsDir, slug));
50
+ return st.isDirectory();
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
43
56
  async function confirmYesNo(question) {
44
57
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
45
58
  try {
@@ -121,10 +134,57 @@ export async function optimizeCommand(opts = {}) {
121
134
  log.dim(`Removed ${candidates.length} skill(s). Run ${chalk.cyan('prave sync')} to update server-side metadata.`);
122
135
  }
123
136
  else if (opts.apply) {
137
+ // `--apply` is the unified interactive cleanup: pick from the
138
+ // *underused* + *heavy* lists at once and uninstall whatever the
139
+ // user agrees to. This is strictly safer than blanket-deleting
140
+ // because every selection is opt-in.
141
+ //
142
+ // Merge candidates are intentionally NOT auto-actionable — merging
143
+ // two Skills is a content-rewrite that the user has to do by hand.
144
+ // We surface them above and leave them for the suggestions panel.
145
+ const offer = [];
146
+ const seen = new Set();
147
+ const push = (skill, bucket) => {
148
+ const slug = slugOf(skill);
149
+ if (!slug || seen.has(slug))
150
+ return;
151
+ seen.add(slug);
152
+ offer.push({ slug, skill, bucket });
153
+ };
154
+ for (const s of data.underused)
155
+ push(s, 'underused');
156
+ for (const s of data.heavy)
157
+ push(s, 'heavy');
158
+ // Filter to ones actually present on disk — the API returns
159
+ // metadata for slug-keyed self-heal stubs that may not have a
160
+ // matching folder.
161
+ const installed = [];
162
+ for (const item of offer) {
163
+ if (await existsOnDisk(item.slug))
164
+ installed.push(item);
165
+ }
166
+ if (installed.length === 0) {
167
+ console.log();
168
+ log.dim('Nothing on disk to clean up — every flagged skill is either uninstalled already or only relevant to merge candidates (which need a manual rewrite).');
169
+ return;
170
+ }
171
+ console.log();
172
+ const picks = await checkboxPrompt('Pick skills to uninstall:', installed.map((i) => ({
173
+ value: i.slug,
174
+ label: nameOf(i.skill),
175
+ hint: i.bucket === 'underused'
176
+ ? `underused · ${formatTokens(i.skill.estimated_tokens)} · ${i.slug}`
177
+ : `heavy · ${formatTokens(i.skill.estimated_tokens)} · ${i.slug}`,
178
+ })));
179
+ if (!picks || picks.length === 0) {
180
+ log.dim('Aborted — nothing removed.');
181
+ return;
182
+ }
183
+ for (const slug of picks) {
184
+ await uninstallCommand(slug);
185
+ }
124
186
  console.log();
125
- log.dim('Auto-apply not available use ' +
126
- chalk.cyan('prave optimize --remove-unused') +
127
- ' to delete underused skills, or review the suggestions and adjust manually.');
187
+ log.dim(`Removed ${picks.length} skill(s). Run ${chalk.cyan('prave sync')} to refresh server-side metadata.`);
128
188
  }
129
189
  }
130
190
  catch (err) {
@@ -104,45 +104,59 @@ export async function usageScanCommand(opts) {
104
104
  }
105
105
  }
106
106
  /**
107
- * `prave usage report` — invoked by the Claude Code `PostToolUse` hook.
107
+ * `prave usage report` — invoked by the Claude Code `PostToolUse` hook
108
+ * (and, when `--source=prompt`, the companion `UserPromptSubmit` hook).
108
109
  * Reads the hook payload from stdin, extracts the Skill name, and fires
109
110
  * a single-event POST against the slug-keyed self-healing endpoint.
110
111
  * Errors are silent (we never want a hook failure to disturb the user's
111
- * workflow); set `PRAVE_DEBUG=1` to see what's happening in
112
- * `~/.prave/usage.log`.
112
+ * workflow); a rotated `~/.prave/hook.log` always captures the last 200
113
+ * fires so users can verify telemetry without flipping `PRAVE_DEBUG=1`.
114
+ *
115
+ * Hook discipline:
116
+ * - reads stdin with a 250 ms cap so we never block Claude Code
117
+ * - one POST attempt with a hard 4 s deadline (background-friendly)
118
+ * - on auth/network failure we log + bail; never throw
113
119
  */
114
- export async function usageReportCommand() {
120
+ export async function usageReportCommand(opts = {}) {
115
121
  const debug = process.env.PRAVE_DEBUG === '1' || process.env.PRAVE_DEBUG === 'true';
122
+ const source = opts.source === 'prompt' ? 'prompt' : 'tool';
123
+ await rotateHookLog();
116
124
  const stdinPayload = await readStdin();
117
125
  if (!stdinPayload) {
126
+ await hookLog(`${source}:no-stdin`);
118
127
  if (debug)
119
128
  await debugLog('no stdin payload');
120
129
  return;
121
130
  }
122
131
  if (debug)
123
- await debugLog(`stdin len=${stdinPayload.length}`);
132
+ await debugLog(`stdin len=${stdinPayload.length} source=${source}`);
124
133
  // Claude Code's PostToolUse payload is documented as `{tool_name,
125
- // tool_input, tool_response, ...}`, but we still defend against
126
- // alternate shapes (capitalisation, future schema drift) so the hook
127
- // doesn't silently break on a single field rename.
134
+ // tool_input, tool_response, ...}`. UserPromptSubmit ships
135
+ // `{ prompt, ... }`. We defend against alternate shapes (capitalisation,
136
+ // future schema drift) so the hook doesn't silently break on a single
137
+ // field rename.
128
138
  let parsed = {};
129
139
  try {
130
140
  parsed = JSON.parse(stdinPayload);
131
141
  }
132
142
  catch {
143
+ await hookLog(`${source}:bad-json`);
133
144
  if (debug)
134
145
  await debugLog('payload is not valid JSON');
135
146
  return;
136
147
  }
137
- const rawSlug = extractSkillSlug(parsed);
148
+ const rawSlug = source === 'prompt' ? extractSlashCommand(parsed) : extractSkillSlug(parsed);
138
149
  if (!rawSlug) {
150
+ await hookLog(`${source}:no-slug`);
139
151
  if (debug)
140
152
  await debugLog(`no skill slug in payload: ${stdinPayload.slice(0, 200)}`);
141
153
  return;
142
154
  }
143
155
  const slug = rawSlug.toLowerCase().split(':').pop()?.trim().replace(/[^a-z0-9_-]+/g, '-');
144
- if (!slug)
156
+ if (!slug) {
157
+ await hookLog(`${source}:empty-slug`);
145
158
  return;
159
+ }
146
160
  if (debug)
147
161
  await debugLog(`slug=${slug}`);
148
162
  const session = await requireAuthSilent();
@@ -183,18 +197,46 @@ export async function usageReportCommand() {
183
197
  slug,
184
198
  agent_type: 'claude',
185
199
  triggered_at: new Date().toISOString(),
186
- meta,
200
+ meta: { ...meta, source },
187
201
  }, true);
202
+ await hookLog(`${source}:ok slug=${slug} recorded=${data.recorded} stub=${data.created_stub}`);
188
203
  if (debug) {
189
204
  await debugLog(`ok recorded=${data.recorded} stub=${data.created_stub} meta=${JSON.stringify(meta)}`);
190
205
  }
191
206
  }
192
207
  catch (err) {
208
+ const msg = err.message;
209
+ await hookLog(`${source}:err slug=${slug} ${msg.slice(0, 120)}`);
193
210
  if (debug)
194
- await debugLog(`error: ${err.message}`);
211
+ await debugLog(`error: ${msg}`);
195
212
  /* silent — never break the host shell */
196
213
  }
197
214
  }
215
+ /**
216
+ * Extract a slash-command name from a UserPromptSubmit payload. Claude
217
+ * Code ships `{ prompt: '/graphify ...' }` (and tolerates leading
218
+ * whitespace). We treat the first whitespace-separated token after `/`
219
+ * as the slug. Returns `null` for non-slash prompts so we don't waste
220
+ * an API hop on every keystroke.
221
+ */
222
+ function extractSlashCommand(payload) {
223
+ const candidates = [
224
+ payload.prompt,
225
+ payload.user_prompt,
226
+ payload.input,
227
+ ];
228
+ for (const c of candidates) {
229
+ if (typeof c !== 'string')
230
+ continue;
231
+ const trimmed = c.trimStart();
232
+ if (!trimmed.startsWith('/'))
233
+ continue;
234
+ const token = trimmed.slice(1).split(/[\s\n\r]/, 1)[0] ?? '';
235
+ if (token)
236
+ return token;
237
+ }
238
+ return null;
239
+ }
198
240
  /**
199
241
  * Walk the hook payload looking for the invoked Skill's slug. Tries the
200
242
  * documented Claude Code path first, then several plausible aliases so
@@ -226,6 +268,45 @@ async function debugLog(line) {
226
268
  /* swallow — debug is best-effort */
227
269
  }
228
270
  }
271
+ /**
272
+ * Always-on per-fire breadcrumb log so users can answer "did the hook
273
+ * run?" without flipping `PRAVE_DEBUG=1`. Capped at 200 lines (rotated
274
+ * lazily by `rotateHookLog`). Lives at `~/.prave/hook.log`.
275
+ */
276
+ async function hookLog(line) {
277
+ try {
278
+ const { mkdir, appendFile } = await import('node:fs/promises');
279
+ const { join } = await import('node:path');
280
+ await mkdir(CONFIG.praveDir, { recursive: true });
281
+ const stamp = new Date().toISOString();
282
+ await appendFile(join(CONFIG.praveDir, 'hook.log'), `${stamp} ${line}\n`);
283
+ }
284
+ catch {
285
+ /* swallow */
286
+ }
287
+ }
288
+ const HOOK_LOG_MAX_LINES = 200;
289
+ async function rotateHookLog() {
290
+ try {
291
+ const { stat, readFile, writeFile } = await import('node:fs/promises');
292
+ const { join } = await import('node:path');
293
+ const path = join(CONFIG.praveDir, 'hook.log');
294
+ const info = await stat(path).catch(() => null);
295
+ // Only do the read-rewrite dance occasionally — when the file gets
296
+ // big enough that we suspect overflow. 32 KB ≈ 200 short lines.
297
+ if (!info || info.size < 32 * 1024)
298
+ return;
299
+ const raw = await readFile(path, 'utf8');
300
+ const lines = raw.split('\n');
301
+ if (lines.length <= HOOK_LOG_MAX_LINES)
302
+ return;
303
+ const trimmed = lines.slice(-HOOK_LOG_MAX_LINES).join('\n');
304
+ await writeFile(path, trimmed, 'utf8');
305
+ }
306
+ catch {
307
+ /* swallow */
308
+ }
309
+ }
229
310
  export async function usageHookInstallCommand() {
230
311
  track('cli_usage_hook_install');
231
312
  const session = await requireAuth('prave usage hook install');
@@ -269,16 +350,22 @@ export async function usageStatusCommand() {
269
350
  const { readFile } = await import('node:fs/promises');
270
351
  const { join } = await import('node:path');
271
352
  const { homedir } = await import('node:os');
272
- // 1. Hook installed?
353
+ // 1. Hook installed? Check both channels we manage.
273
354
  const settingsPath = join(homedir(), '.claude', 'settings.json');
274
- let hookInstalled = false;
355
+ let toolHookInstalled = false;
356
+ let promptHookInstalled = false;
275
357
  try {
276
358
  const raw = await readFile(settingsPath, 'utf8');
277
- hookInstalled = raw.includes('__prave_managed') && raw.includes('Skill');
359
+ const parsed = JSON.parse(raw);
360
+ toolHookInstalled =
361
+ (parsed.hooks?.PostToolUse ?? []).some((b) => b.matcher === 'Skill' && (b.hooks ?? []).some((h) => h.__prave_managed === true));
362
+ promptHookInstalled =
363
+ (parsed.hooks?.UserPromptSubmit ?? []).some((b) => (b.hooks ?? []).some((h) => h.__prave_managed === true));
278
364
  }
279
365
  catch {
280
366
  /* no settings.json yet */
281
367
  }
368
+ const hookInstalled = toolHookInstalled && promptHookInstalled;
282
369
  // 2. Last 7 days of recorded events from the API.
283
370
  let recent7 = 0;
284
371
  let topSlugs = [];
@@ -300,14 +387,33 @@ export async function usageStatusCommand() {
300
387
  catch {
301
388
  /* never scanned */
302
389
  }
303
- // 4. Debug log tail.
304
- const logPath = join(CONFIG.praveDir, 'usage.log');
305
- const debugAvailable = existsSync(logPath);
390
+ // 4. Debug log + hook log tails.
391
+ const debugLogPath = join(CONFIG.praveDir, 'usage.log');
392
+ const hookLogPath = join(CONFIG.praveDir, 'hook.log');
393
+ const debugAvailable = existsSync(debugLogPath);
394
+ const hookLogAvailable = existsSync(hookLogPath);
395
+ // 5. API reachability — token-validating ping. We already passed
396
+ // `requireAuth` above so the credentials file exists; this round-trip
397
+ // just confirms the access_token is still accepted server-side. If the
398
+ // hook has been silently 401-ing for a week, this is the only way the
399
+ // user finds out without flipping `PRAVE_DEBUG=1`.
400
+ let apiReachable = false;
401
+ let apiMessage = '';
402
+ try {
403
+ await api.get('/api/v1/intelligence/usage/recent?days=1', true);
404
+ apiReachable = true;
405
+ }
406
+ catch (err) {
407
+ apiMessage =
408
+ err instanceof ApiError ? `${err.status} ${err.message}` : err.message;
409
+ }
306
410
  // Render.
307
- const checkmark = (ok) => (ok ? chalk.green('✓') : chalk.dim(''));
411
+ const checkmark = (ok) => (ok ? chalk.green('✓') : chalk.red(''));
308
412
  log.info(chalk.bold('Usage tracking status'));
309
413
  console.log();
310
- console.log(` ${checkmark(hookInstalled)} Real-time hook (Claude Code): ${hookInstalled ? chalk.green('installed') : chalk.yellow('not installed — `prave usage hook install`')}`);
414
+ console.log(` ${checkmark(toolHookInstalled)} PostToolUse hook (Skill tool fires): ${toolHookInstalled ? chalk.green('installed') : chalk.yellow('missing — `prave usage hook install`')}`);
415
+ console.log(` ${checkmark(promptHookInstalled)} UserPromptSubmit hook (slash commands like /graphify): ${promptHookInstalled ? chalk.green('installed') : chalk.yellow('missing — `prave usage hook install`')}`);
416
+ console.log(` ${checkmark(apiReachable)} API reachable + auth valid: ${apiReachable ? chalk.green('yes') : chalk.red(apiMessage || 'no')}`);
311
417
  console.log(` ${checkmark(Boolean(lastScanAt))} Transcript scanner watermark: ${lastScanAt ?? chalk.dim('never run — `prave sync` includes it')}`);
312
418
  console.log(` ${checkmark(recent7 > 0)} Events in last 7 days: ${chalk.cyan(String(recent7))}`);
313
419
  if (topSlugs.length) {
@@ -317,20 +423,41 @@ export async function usageStatusCommand() {
317
423
  console.log(` ${chalk.cyan(s.count.toString().padStart(4))} ${s.name}`);
318
424
  }
319
425
  }
320
- console.log();
321
- if (debugAvailable) {
322
- log.dim(`Debug log: ${logPath}`);
323
- log.dim('Set PRAVE_DEBUG=1 in your shell to enable verbose hook logging.');
324
- }
325
- else {
326
- log.dim('No debug log yet. Set PRAVE_DEBUG=1 to capture every hook fire to ~/.prave/usage.log');
426
+ // Last 5 hook fires — the breadcrumb trail that answers "did the hook
427
+ // even run when I typed /graphify?". Read the bottom of hook.log.
428
+ if (hookLogAvailable) {
429
+ try {
430
+ const raw = await readFile(hookLogPath, 'utf8');
431
+ const tail = raw.trimEnd().split('\n').slice(-5);
432
+ if (tail.length) {
433
+ console.log();
434
+ console.log(chalk.dim(' Last hook fires:'));
435
+ for (const line of tail)
436
+ console.log(` ${chalk.dim(line)}`);
437
+ }
438
+ }
439
+ catch {
440
+ /* swallow */
441
+ }
327
442
  }
328
- if (recent7 === 0) {
443
+ console.log();
444
+ log.dim(`Hook breadcrumb log: ${hookLogPath}`);
445
+ if (debugAvailable)
446
+ log.dim(`Verbose debug log: ${debugLogPath}`);
447
+ log.dim('Set PRAVE_DEBUG=1 in your shell to enable verbose hook logging.');
448
+ if (!hookInstalled || !apiReachable || recent7 === 0) {
329
449
  console.log();
330
- log.warn('No events recorded yet. Quick checks:');
331
- log.dim(' 1. Is the hook installed? See checkmarks above.');
332
- log.dim(' 2. Run a Skill in Claude Code, then `tail ~/.prave/usage.log` (with PRAVE_DEBUG=1)');
333
- log.dim(' 3. Or run `prave usage scan --since 7d` to backfill from transcripts.');
450
+ log.warn('Telemetry may be incomplete. Suggested fixes:');
451
+ if (!toolHookInstalled || !promptHookInstalled) {
452
+ log.dim(' Run `prave usage hook install` to wire BOTH PostToolUse and UserPromptSubmit.');
453
+ }
454
+ if (!apiReachable) {
455
+ log.dim(' • Run `prave login` — your access token may have expired (silently 401-ing).');
456
+ }
457
+ if (recent7 === 0 && hookInstalled && apiReachable) {
458
+ log.dim(' • Run a Skill in Claude Code, then re-run `prave usage status`.');
459
+ log.dim(' • Or run `prave usage scan --since 7d` to backfill from transcripts.');
460
+ }
334
461
  }
335
462
  }
336
463
  async function fetchEnabledAgents() {
@@ -414,13 +541,37 @@ function parseSinceFlag(raw) {
414
541
  async function readStdin() {
415
542
  if (process.stdin.isTTY)
416
543
  return '';
417
- const chunks = [];
418
- for await (const chunk of process.stdin) {
419
- chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
420
- if (Buffer.concat(chunks).length > 1_000_000)
421
- break;
422
- }
423
- return Buffer.concat(chunks).toString('utf8');
544
+ // Hard 1.5 s cap so a stuck pipe never blocks Claude Code's tool flow.
545
+ // 1 MB payload cap so a runaway stream can't OOM the hook either.
546
+ return new Promise((resolve) => {
547
+ const chunks = [];
548
+ let total = 0;
549
+ let settled = false;
550
+ const finish = () => {
551
+ if (settled)
552
+ return;
553
+ settled = true;
554
+ resolve(Buffer.concat(chunks).toString('utf8'));
555
+ };
556
+ const timer = setTimeout(finish, 1500);
557
+ process.stdin.on('data', (chunk) => {
558
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
559
+ chunks.push(buf);
560
+ total += buf.length;
561
+ if (total > 1_000_000) {
562
+ clearTimeout(timer);
563
+ finish();
564
+ }
565
+ });
566
+ process.stdin.once('end', () => {
567
+ clearTimeout(timer);
568
+ finish();
569
+ });
570
+ process.stdin.once('error', () => {
571
+ clearTimeout(timer);
572
+ finish();
573
+ });
574
+ });
424
575
  }
425
576
  /**
426
577
  * Auth check with no UX side-effects. Used by the hook so a logged-out
package/dist/index.js CHANGED
@@ -119,12 +119,12 @@ program
119
119
  program
120
120
  .command('conflicts')
121
121
  .description('Detect overlap, collisions, and missing dependencies')
122
- .option('--fix', 'placeholder for interactive fix flow')
122
+ .option('--fix', 'after listing conflicts, interactively pick installed Skills to uninstall to resolve them')
123
123
  .action(conflictsCommand);
124
124
  program
125
125
  .command('optimize')
126
126
  .description('Recommendations: underused, mergeable, and heavy skills')
127
- .option('--apply', 'placeholder for auto-apply')
127
+ .option('--apply', 'after listing recommendations, interactively pick underused + heavy skills to uninstall')
128
128
  .option('--remove-unused', 'interactively delete skills that have not fired in 30+ days from ~/.claude/skills/')
129
129
  .option('--yes', 'with --remove-unused: skip the confirmation prompt')
130
130
  .action(optimizeCommand);
@@ -143,8 +143,9 @@ usage
143
143
  .action(usageStatusCommand);
144
144
  usage
145
145
  .command('report')
146
- .description('Internal: invoked by the Claude Code PostToolUse hook (reads stdin)')
147
- .action(usageReportCommand);
146
+ .description('Internal: invoked by the Claude Code PostToolUse / UserPromptSubmit hook (reads stdin)')
147
+ .option('--source <kind>', 'hook channel that fired this report ("tool" or "prompt")', 'tool')
148
+ .action((opts) => usageReportCommand(opts));
148
149
  const hook = usage.command('hook').description('Install/uninstall the Claude Code real-time usage hook');
149
150
  hook
150
151
  .command('install')
package/dist/lib/hook.js CHANGED
@@ -22,25 +22,50 @@ const HOOK_MARKER = '__prave_managed';
22
22
  */
23
23
  export const HOOK_SUPPORTED = ['claude'];
24
24
  const HOOK_COMMAND = 'prave usage report';
25
+ // Companion command for the UserPromptSubmit channel so a typed-slash
26
+ // `/graphify` is captured even when the Skill tool path doesn't fire a
27
+ // matching PostToolUse with a populated `tool_input.skill` field.
28
+ const PROMPT_HOOK_COMMAND = 'prave usage report --source=prompt';
29
+ /**
30
+ * Install on BOTH `PostToolUse` (matcher `Skill`) and `UserPromptSubmit`
31
+ * (catches slash commands like `/graphify` before tool dispatch). The two
32
+ * channels are deduped server-side by per-minute bucket, so double-fires
33
+ * for the same Skill in the same minute land as a single row — but every
34
+ * additional minute of activity is preserved. Idempotent + atomic.
35
+ */
25
36
  export async function installSkillHook() {
26
37
  const settings = await readSettings();
27
38
  settings.hooks ??= {};
28
39
  settings.hooks.PostToolUse ??= [];
29
- const blocks = settings.hooks.PostToolUse;
30
- const existingIdx = blocks.findIndex((b) => b.matcher === 'Skill' && b.hooks?.some((h) => h[HOOK_MARKER]));
31
- const fresh = {
40
+ settings.hooks.UserPromptSubmit ??= [];
41
+ const postBlocks = settings.hooks.PostToolUse;
42
+ const promptBlocks = settings.hooks.UserPromptSubmit;
43
+ const postFresh = {
32
44
  matcher: 'Skill',
33
45
  hooks: [{ type: 'command', command: HOOK_COMMAND, [HOOK_MARKER]: true }],
34
46
  };
35
- if (existingIdx >= 0) {
36
- const existingCmd = blocks[existingIdx]?.hooks?.[0]?.command;
37
- if (existingCmd === HOOK_COMMAND) {
38
- return { installed: false, alreadyPresent: true, settingsPath: SETTINGS_PATH };
47
+ const promptFresh = {
48
+ // UserPromptSubmit has no matcher concept in Claude Code today — the
49
+ // hook script itself filters for `prompt.startsWith('/')` before
50
+ // doing any work.
51
+ hooks: [{ type: 'command', command: PROMPT_HOOK_COMMAND, [HOOK_MARKER]: true }],
52
+ };
53
+ const upsert = (blocks, fresh, expectedCmd) => {
54
+ const idx = blocks.findIndex((b) => b.matcher === fresh.matcher && b.hooks?.some((h) => h[HOOK_MARKER]));
55
+ if (idx >= 0) {
56
+ const existingCmd = blocks[idx]?.hooks?.[0]?.command;
57
+ if (existingCmd === expectedCmd)
58
+ return false;
59
+ blocks[idx] = fresh;
60
+ return true;
39
61
  }
40
- blocks[existingIdx] = fresh;
41
- }
42
- else {
43
62
  blocks.push(fresh);
63
+ return true;
64
+ };
65
+ const changedPost = upsert(postBlocks, postFresh, HOOK_COMMAND);
66
+ const changedPrompt = upsert(promptBlocks, promptFresh, PROMPT_HOOK_COMMAND);
67
+ if (!changedPost && !changedPrompt) {
68
+ return { installed: false, alreadyPresent: true, settingsPath: SETTINGS_PATH };
44
69
  }
45
70
  await writeSettings(settings);
46
71
  return { installed: true, alreadyPresent: false, settingsPath: SETTINGS_PATH };
@@ -93,25 +118,35 @@ export async function uninstallHooksForAgents(agents) {
93
118
  }
94
119
  export async function uninstallSkillHook() {
95
120
  const settings = await readSettings();
96
- const blocks = settings.hooks?.PostToolUse;
97
- if (!blocks?.length)
121
+ if (!settings.hooks)
98
122
  return { removed: false, settingsPath: SETTINGS_PATH };
99
- const before = blocks.length;
100
- const filtered = blocks
101
- .map((b) => ({
102
- ...b,
103
- hooks: b.hooks?.filter((h) => !h[HOOK_MARKER]),
104
- }))
105
- .filter((b) => (b.hooks?.length ?? 0) > 0);
106
- if (filtered.length === before && filtered.every((b, i) => b.hooks?.length === blocks[i]?.hooks?.length)) {
123
+ let touched = false;
124
+ const stripChannel = (channel) => {
125
+ const blocks = settings.hooks?.[channel];
126
+ if (!blocks?.length)
127
+ return;
128
+ const beforeCounts = blocks.map((b) => b.hooks?.length ?? 0);
129
+ const filtered = blocks
130
+ .map((b) => ({ ...b, hooks: b.hooks?.filter((h) => !h[HOOK_MARKER]) }))
131
+ .filter((b) => (b.hooks?.length ?? 0) > 0);
132
+ const lengthChanged = filtered.length !== blocks.length;
133
+ const innerChanged = !lengthChanged &&
134
+ filtered.some((b, i) => (b.hooks?.length ?? 0) !== beforeCounts[i]);
135
+ if (!lengthChanged && !innerChanged)
136
+ return;
137
+ touched = true;
138
+ if (settings.hooks) {
139
+ settings.hooks[channel] = filtered.length ? filtered : undefined;
140
+ if (!filtered.length)
141
+ delete settings.hooks[channel];
142
+ }
143
+ };
144
+ stripChannel('PostToolUse');
145
+ stripChannel('UserPromptSubmit');
146
+ if (!touched)
107
147
  return { removed: false, settingsPath: SETTINGS_PATH };
108
- }
109
- if (settings.hooks) {
110
- settings.hooks.PostToolUse = filtered;
111
- if (!filtered.length)
112
- delete settings.hooks.PostToolUse;
113
- if (Object.keys(settings.hooks).length === 0)
114
- delete settings.hooks;
148
+ if (settings.hooks && Object.keys(settings.hooks).length === 0) {
149
+ delete settings.hooks;
115
150
  }
116
151
  await writeSettings(settings);
117
152
  return { removed: true, settingsPath: SETTINGS_PATH };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prave/cli",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Prave CLI — discover, install, version, test, and ship Claude Skills. The developer platform for the complete Skill lifecycle.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -51,7 +51,7 @@
51
51
  "open": "^10.1.0",
52
52
  "ora": "^8.0.1",
53
53
  "undici": "^6.18.0",
54
- "@prave/shared": "1.2.0"
54
+ "@prave/shared": "1.2.1"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/node": "^20.12.7",