skilltally 1.0.3 → 1.2.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.
@@ -10,7 +10,7 @@
10
10
  {
11
11
  "name": "skilltally",
12
12
  "description": "Track skill activations and identify unused skills eating context.",
13
- "version": "1.0.3",
13
+ "version": "1.2.0",
14
14
  "source": "./",
15
15
  "category": "productivity"
16
16
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skilltally",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Real-time skill usage tracking via hooks for Antigravity, Claude Code, Codex & Gemini CLI.",
5
5
  "author": {
6
6
  "name": "112516101106",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skilltally",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Real-time skill usage tracking via hooks for Antigravity, Claude Code, Codex & Gemini CLI.",
5
5
  "author": {
6
6
  "name": "112516101106",
package/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.0] - 2026-11-20
9
+
10
+ ### Added
11
+ - **Runtime Token Usage & Prompt Cache Efficiency Telemetry**: Live hooks (`bin/track.mjs`) and all 4 backfill parsers extract normalized `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_creation_tokens`, and `total_tokens` from transcripts, exposing `totals.tokens` (`cacheHitRate`, `lifetimeTokens`, `peakSessionTokens`, `activeBodyTokens`).
12
+ - **Skill Task Duration Tracking**: Computes `duration_seconds` across turns in backfill and live hooks, reporting `totals.duration` (`totalSeconds`, `avgSeconds`, `longestTaskSeconds`) and `insights.slowestSkills`.
13
+ - **Heavy `SKILL.md` Body Detection**: Scans full `body_tokens` in `scanInventory` and flags `>= 1,500`-token skill files (`insights.heavyBodySkills`) that should be split into `references/`.
14
+ - **Opt-In Redacted Prompt Triggers (`store_prompts: true`)**: Sanitizes and strips skill tags, secrets, emails, and absolute paths via `sanitizePromptPreview` to surface `insights.promptPatterns`.
15
+ - **Profile Dashboard Updates**: Upgraded the 5-metric pill bar to `Lifetime tokens`, `Peak tokens`, `Longest task`, `Longest streak`, and `Current streak`, plus cache hit rate, active body tokens, automated duration, and heavy-body pruning cards.
16
+
17
+ ## [1.1.0] - 2026-11-20
18
+
19
+ ### Added
20
+ - **Interactive HTML Dashboard (`skilltally dashboard`)**: Self-contained, offline zero-dependency HTML report featuring an interactive SVG Treemap (Context Tax vs. Activations), Timeline chart, Trigger/Host/Project/Model distribution charts, SVG workflow transition diagram, optimization tabs, sortable/filterable skills explorer, and Mermaid snippet generator (`pie`, `xychart-beta`, `flowchart LR`).
21
+ - **Skill Chains & Co-occurrence (`skilltally chains`)**: Session-level analysis of ordered skill transitions (`A -> B` with conditional probability and average gap), 3-step workflows, and co-occurring pairs with Jaccard similarity.
22
+ - **Optimization Insights (`skilltally insights`) & Enriched `stats`/`unused`**:
23
+ - 14-day Unicode sparklines (`▁▂▃▄▅▆▇█`) in `stats` rows and a Context Tax meter bar in `unused`.
24
+ - Trigger mode (`via`) auto vs. manual breakdown and identification of manual-only skills needing sharper `SKILL.md` descriptions.
25
+ - Project-affinity analysis flagging global/plugin skills used exclusively in a single project.
26
+ - Cumulative context ROI (`tokenCostPerActivation`) and per-model usage breakdown.
27
+ - **Safe Actionable Pruning (`skilltally prune`)**: Disable 100%-unused plugins or specific unused skills in Antigravity (`~/.gemini/config/config.json`) and Codex (`~/.codex/config.toml`) with `--dry-run` preview and automatic backups.
28
+ - **Zero-Dependency Stdio MCP Server (`skilltally mcp`)**: Exposes `skilltally_stats`, `skilltally_unused`, `skilltally_timeline`, `skilltally_chains`, and `skilltally_insights` over newline-delimited or `Content-Length`-framed JSON-RPC 2.0.
29
+
8
30
  ## [1.0.3] - 2026-11-19
9
31
 
10
32
  ### Fixed
package/README.md CHANGED
@@ -71,11 +71,12 @@ If you prefer native plugin managers over `npx skilltally install`:
71
71
  ```text
72
72
  skilltally — last 30d (2026-10-20 -> 2026-11-19)
73
73
  hosts: antigravity 35 · codex 12
74
+ triggers: auto 38 · manual 9
74
75
 
75
- # skill activations reads last used hosts
76
- 1 requesting-code-review 8 10 2026-11-12 14:03 antigravity, codex
77
- 2 systematic-debugging 5 9 2026-11-10 09:41 codex
78
- 3 agent-browser 3 4 2026-11-05 12:18 antigravity, codex
76
+ # skill activations reads last used hosts trend (14d)
77
+ 1 requesting-code-review 8 10 2026-11-12 14:03 antigravity, codex ··▁·▃·█··▃·▁··
78
+ 2 systematic-debugging 5 9 2026-11-10 09:41 codex ····▁··█··▁···
79
+ 3 agent-browser 3 4 2026-11-05 12:18 antigravity, codex ··█···········
79
80
 
80
81
  installed: 214 · used: 22 · unused: 192 -> run `skilltally unused`
81
82
  ```
@@ -84,6 +85,7 @@ installed: 214 · used: 22 · unused: 192 -> run `skilltally unused`
84
85
 
85
86
  ```text
86
87
  Unused enabled skills — last 90d (2026-08-21 -> 2026-11-19): 192 (48.2 KB ≈ ~12,340 tok/session)
88
+ context tax: [████████████░░░░] 76% unused (~12,340 / ~16,200 tok/session)
87
89
 
88
90
  plugin:science 47 skills 14.8 KB ~ 3818 tok/session
89
91
  alphagenome-atlas-website-links, alphagenome-single-variant-analysis, … (+41)
@@ -101,18 +103,23 @@ Tip: disabling an unused plugin removes all of its skill descriptions from every
101
103
  | `uninstall` | Remove `skilltally` hooks (preserves all other user hooks) | `--host ...`, `--purge`, `--dry-run`, `--json` |
102
104
  | `doctor` | Check Node version, hook paths, Codex trust, events, and live self-test | `--json` |
103
105
  | `backfill` | Import historical skill reads/invocations from local logs | `--host ...`, `--since DATE`, `--dry-run`, `--json` |
104
- | `stats` | Usage table sorted by `activations` (unique `session × skill`) | `--since 30d\|all\|YYYY-MM-DD`, `--host`, `--project`, `--by-source`, `--metric reads`, `--json` |
106
+ | `stats` | Usage table sorted by `activations` with 14-day sparklines and trigger ratio | `--since 30d\|all\|YYYY-MM-DD`, `--host`, `--project`, `--by-source`, `--metric reads`, `--json` |
105
107
  | `top` | Top `N` skills | `-n 20`, plus `stats` flags |
106
108
  | `unused` | Enabled installed skills with 0 activations and Context Tax breakdown | `--since 90d`, `--host`, `--all`, `--json` |
107
109
  | `timeline` | ASCII usage bar chart over time | `--skill <name>`, `--by day\|week\|month`, `--since`, `--host`, `--project`, `--json` |
110
+ | `chains` | Skill transition chains (`A -> B`), 3-step workflows, and co-occurring pairs | `--since`, `--host`, `--project`, `-n 20`, `--json` |
111
+ | `insights` | Context ROI, manual-only triggers, single-project scoping candidates, model stats | `--since`, `--host`, `--project`, `--json` |
112
+ | `dashboard` | Generate self-contained offline HTML dashboard (SVG Treemap, chains, Mermaid) | `-o <file>`, `--since`, `--host`, `--project`, `--open`, `--json` |
113
+ | `prune` | Safely disable 100%-unused plugins or specific unused skills (with backups) | `--since 90d`, `--host all\|antigravity\|codex`, `--plugin <name>`, `--skill <name>`, `--dry-run`, `--json` |
108
114
  | `export` | Export deduplicated events as JSON or RFC-4180 CSV | `--format json\|csv`, `-o <file>`, `--since`, `--host`, `--project`, `--include-failed` |
109
115
  | `inventory` | List installed skills, sources, hosts, enabled state, and description sizes | `--no-project`, `--json` |
116
+ | `mcp` | Start zero-dependency stdio MCP server (`skilltally_*` tools) | — |
110
117
  | `debug` | Toggle opt-in raw stdin logging (`on \| off \| status`) | `--json` |
111
118
 
112
119
  ## Privacy, Performance & Reliability
113
120
 
114
121
  - **100% local, zero telemetry**: Zero network requests, zero third-party runtime dependencies.
115
- - **No raw arguments stored**: Only the matched `SKILL.md` path (or `Skill`/`activate_skill` name) and `basename(cwd)` are written to `~/.skilltally/` (`0700` dir, `0600` files). Full `cwd` is omitted unless `store_cwd: true` is set in `~/.skilltally/config.json`.
122
+ - **No raw arguments or prompts stored**: Only the matched `SKILL.md` path (or `Skill`/`activate_skill` name) and `basename(cwd)` are written to `~/.skilltally/` (`0700` dir, `0600` files). Full `cwd` is omitted unless `store_cwd: true` is set, and redacted prompt previews (`80` chars, secrets/emails/paths stripped) are omitted unless `store_prompts: true` is set in `~/.skilltally/config.json`.
116
123
  - **Safe by contract**: `track.mjs` never throws, always exits `0`, and always writes `{}` to `stdout` so hooks never interrupt an agent turn.
117
124
  - **Automatic rotation**: When `events.jsonl` exceeds 20 MB, it rotates automatically to `events-YYYY-MM.jsonl` while reports transparently read all archives.
118
125
  - **Config backups**: `install` and `uninstall` back up modified host configs to `~/.skilltally/backups/`.
@@ -124,7 +131,8 @@ Tip: disabling an unused plugin removes all of its skill descriptions from every
124
131
  "exclude_skills": ["skilltally"],
125
132
  "exclude_sources": [],
126
133
  "aliases": { "native_swarm": "swarm" },
127
- "store_cwd": false
134
+ "store_cwd": false,
135
+ "store_prompts": false
128
136
  }
129
137
  ```
130
138
 
package/bin/cli.mjs CHANGED
@@ -9,15 +9,22 @@ import { getDebugStatus, setDebugMode } from '../src/core/debug.mjs';
9
9
  import { readAllEvents } from '../src/core/store.mjs';
10
10
  import { runDoctor } from '../src/install/doctor.mjs';
11
11
  import { runInstall, runUninstall } from '../src/install/index.mjs';
12
+ import { runPrune } from '../src/install/prune.mjs';
12
13
  import { scanInventory } from '../src/inventory/scan.mjs';
14
+ import { startMcpServer } from '../src/mcp/server.mjs';
13
15
  import { aggregateStats, parseSince } from '../src/report/aggregate.mjs';
16
+ import { buildChains } from '../src/report/chains.mjs';
17
+ import { generateDashboardHtml, openInBrowser } from '../src/report/dashboard.mjs';
14
18
  import { exportEvents } from '../src/report/export.mjs';
15
19
  import {
16
20
  formatBackfill,
21
+ formatChains,
17
22
  formatDebug,
18
23
  formatDoctor,
24
+ formatInsights,
19
25
  formatInstall,
20
26
  formatInventory,
27
+ formatPrune,
21
28
  formatStats,
22
29
  formatTimeline,
23
30
  formatUninstall,
@@ -32,7 +39,7 @@ function getVersion() {
32
39
  try {
33
40
  return JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8')).version;
34
41
  } catch {
35
- return '1.0.3';
42
+ return '1.1.0';
36
43
  }
37
44
  }
38
45
 
@@ -47,9 +54,14 @@ Usage:
47
54
  skilltally top [-n 20] [--since 30d] [--host <h>] [--project <p>] [--by-source] [--metric activations|reads] [--json]
48
55
  skilltally unused [--since 90d] [--host <h>] [--all] [--json]
49
56
  skilltally timeline [--skill <name>] [--by day|week|month] [--since 30d|all] [--host <h>] [--project <p>] [--json]
57
+ skilltally chains [--since 30d|all] [--host <h>] [--project <p>] [-n 20] [--json]
58
+ skilltally insights [--since 30d|all] [--host <h>] [--project <p>] [--json]
59
+ skilltally dashboard [-o <file>] [--since 30d|all] [--host <h>] [--project <p>] [--open] [--json]
60
+ skilltally prune [--since 90d] [--host all|antigravity|codex] [--plugin <name>] [--skill <name>] [--dry-run] [--json]
50
61
  skilltally export [--format json|csv] [-o <file>] [--since all|30d] [--host <h>] [--project <p>] [--include-failed]
51
62
  skilltally backfill [--host all|antigravity|codex|claude|gemini] [--since DATE] [--dry-run] [--json]
52
63
  skilltally inventory [--no-project] [--json]
64
+ skilltally mcp
53
65
  skilltally debug [on|off|status] [--json]
54
66
  skilltally track --host <antigravity|claude|codex|gemini|auto>
55
67
 
@@ -70,6 +82,7 @@ function parseCliFlags(argv) {
70
82
  host: { type: 'string' },
71
83
  project: { type: 'string' },
72
84
  skill: { type: 'string' },
85
+ plugin: { type: 'string', multiple: true },
73
86
  by: { type: 'string' },
74
87
  format: { type: 'string' },
75
88
  output: { type: 'string', short: 'o' },
@@ -78,6 +91,7 @@ function parseCliFlags(argv) {
78
91
  'by-source': { type: 'boolean', default: false },
79
92
  json: { type: 'boolean', default: false },
80
93
  'dry-run': { type: 'boolean', default: false },
94
+ open: { type: 'boolean', default: false },
81
95
  all: { type: 'boolean', default: false },
82
96
  'no-project': { type: 'boolean', default: false },
83
97
  'include-failed': { type: 'boolean', default: false },
@@ -308,6 +322,154 @@ function run() {
308
322
  return;
309
323
  }
310
324
 
325
+ if (sub === 'chains') {
326
+ const since = values.since ?? '30d';
327
+ const limit = values.limit !== undefined ? Number(values.limit) : 20;
328
+ if (!Number.isFinite(limit) || limit < 1) {
329
+ throw new Error(`Invalid -n/--limit value: "${values.limit}"`);
330
+ }
331
+ const { events } = readAllEvents(dataHome);
332
+ const inventory = scanInventory({ includeProject: true });
333
+ const chains = buildChains({
334
+ events,
335
+ inventory,
336
+ config,
337
+ since,
338
+ host: values.host || null,
339
+ project: values.project || null,
340
+ limit,
341
+ });
342
+ if (values.json) {
343
+ console.log(JSON.stringify(chains, null, 2));
344
+ } else {
345
+ console.log(formatChains(chains));
346
+ }
347
+ return;
348
+ }
349
+
350
+ if (sub === 'insights') {
351
+ const since = values.since ?? '30d';
352
+ const { events } = readAllEvents(dataHome);
353
+ const inventory = scanInventory({ includeProject: true });
354
+ const report = aggregateStats({
355
+ events,
356
+ inventory,
357
+ config,
358
+ since,
359
+ host: values.host || null,
360
+ project: values.project || null,
361
+ });
362
+ if (values.json) {
363
+ console.log(
364
+ JSON.stringify(
365
+ {
366
+ window: report.window,
367
+ totals: report.totals,
368
+ inventory: report.inventory,
369
+ insights: report.insights,
370
+ },
371
+ null,
372
+ 2
373
+ )
374
+ );
375
+ } else {
376
+ console.log(formatInsights(report));
377
+ }
378
+ return;
379
+ }
380
+
381
+ if (sub === 'dashboard') {
382
+ const since = values.since ?? '30d';
383
+ const by = values.by ?? 'day';
384
+ const { events } = readAllEvents(dataHome);
385
+ const inventory = scanInventory({ includeProject: true });
386
+ const stats = aggregateStats({
387
+ events,
388
+ inventory,
389
+ config,
390
+ since,
391
+ host: values.host || null,
392
+ project: values.project || null,
393
+ });
394
+ const timeline = buildTimeline({
395
+ events,
396
+ inventory,
397
+ config,
398
+ by,
399
+ since,
400
+ host: values.host || null,
401
+ project: values.project || null,
402
+ });
403
+ const dailyTimeline = buildTimeline({
404
+ events,
405
+ inventory,
406
+ config,
407
+ by: 'day',
408
+ since: '365d',
409
+ host: values.host || null,
410
+ project: values.project || null,
411
+ });
412
+ const chains = buildChains({
413
+ events,
414
+ inventory,
415
+ config,
416
+ since,
417
+ host: values.host || null,
418
+ project: values.project || null,
419
+ });
420
+ const outPath = values.output || join(dataHome, 'dashboard.html');
421
+ const html = generateDashboardHtml({ stats, timeline, dailyTimeline, chains, inventory });
422
+ mkdirSync(dirname(outPath), { recursive: true });
423
+ writeFileSync(outPath, html, { encoding: 'utf8', mode: 0o600 });
424
+ const opened = values.open ? openInBrowser(outPath) : { opened: false };
425
+ if (values.json) {
426
+ console.log(
427
+ JSON.stringify({ path: outPath, bytes: Buffer.byteLength(html, 'utf8'), opened: opened.opened }, null, 2)
428
+ );
429
+ } else {
430
+ console.log(`Dashboard written to: ${outPath}`);
431
+ if (values.open) {
432
+ console.log(
433
+ opened.opened
434
+ ? 'Opened in browser.'
435
+ : 'Could not open browser automatically; open the file above manually.'
436
+ );
437
+ }
438
+ }
439
+ return;
440
+ }
441
+
442
+ if (sub === 'prune') {
443
+ const since = values.since ?? '90d';
444
+ const plugins = (Array.isArray(values.plugin) ? values.plugin : values.plugin ? [values.plugin] : [])
445
+ .flatMap((p) => String(p).split(','))
446
+ .map((p) => p.trim())
447
+ .filter(Boolean);
448
+ const skills = (values.skill ? [values.skill] : [])
449
+ .flatMap((s) => String(s).split(','))
450
+ .map((s) => s.trim())
451
+ .filter(Boolean);
452
+ const res = runPrune({
453
+ dataHome,
454
+ since,
455
+ host: values.host || 'all',
456
+ plugins,
457
+ skills,
458
+ dryRun: Boolean(values['dry-run']),
459
+ });
460
+ if (values.json) {
461
+ console.log(JSON.stringify(res, null, 2));
462
+ } else {
463
+ console.log(formatPrune(res));
464
+ }
465
+ return;
466
+ }
467
+
468
+ if (sub === 'mcp') {
469
+ startMcpServer({ dataHome, pkgVersion: getVersion() });
470
+ return;
471
+ }
472
+
311
473
  console.error(`Unknown command: "${sub}"\n`);
312
474
  printHelp();
313
475
  process.exitCode = 1;
package/bin/track.mjs CHANGED
@@ -3,9 +3,12 @@
3
3
  // Contract when executed directly: NEVER throw, ALWAYS exit 0, ALWAYS print "{}".
4
4
  import {
5
5
  appendFileSync,
6
+ closeSync,
6
7
  existsSync,
7
8
  mkdirSync,
9
+ openSync,
8
10
  readFileSync,
11
+ readSync,
9
12
  realpathSync,
10
13
  renameSync,
11
14
  statSync,
@@ -130,8 +133,59 @@ export function resolveHost(hostFlag, payload, env = process.env) {
130
133
  return 'unknown';
131
134
  }
132
135
 
136
+ export function sanitizePromptPreview(rawPrompt, maxLen = 80) {
137
+ if (typeof rawPrompt !== 'string' || !rawPrompt.trim()) return '';
138
+ let text = rawPrompt
139
+ .replace(/<SKILL>[\s\S]*?<\/SKILL>/gi, ' ')
140
+ .replace(/<skill>[\s\S]*?<\/skill>/gi, ' ')
141
+ .replace(/\[[\$@\/]?[A-Za-z0-9._-]+\]\([^()\s]*SKILL\.md\)/gi, ' ')
142
+ .replace(/Base directory for this skill:[^\r\n]*/gi, ' ')
143
+ .replace(/<[^>]+>/g, ' ')
144
+ .replace(/\b(?:sk|pk|rk|ghp|gho|github_pat|xox[baprs]|AIza)[A-Za-z0-9_-]{10,}\b/g, '[REDACTED]')
145
+ .replace(/\b[A-Za-z0-9_-]{36,}\b/g, '[REDACTED]')
146
+ .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[EMAIL]')
147
+ .replace(/(?:\/Users\/|\/home\/|[A-Za-z]:\\)[^\s"'`)]+/g, '[PATH]')
148
+ .replace(/\s+/g, ' ')
149
+ .trim();
150
+ if (!text) return '';
151
+ return text.length > maxLen ? text.slice(0, maxLen) : text;
152
+ }
153
+
154
+ export function extractUsageMetrics(usage) {
155
+ if (!usage || typeof usage !== 'object') return null;
156
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null);
157
+ const input = num(usage.input_tokens ?? usage.promptTokenCount) ?? 0;
158
+ const output = num(usage.output_tokens ?? usage.candidatesTokenCount) ?? 0;
159
+ const cacheRead =
160
+ num(
161
+ usage.cache_read_tokens ??
162
+ usage.cache_read_input_tokens ??
163
+ usage.cached_input_tokens ??
164
+ usage.cachedContentTokenCount
165
+ ) ?? 0;
166
+ const cacheCreate = num(usage.cache_creation_tokens ?? usage.cache_creation_input_tokens) ?? 0;
167
+ const rawTotal = num(usage.total_tokens ?? usage.totalTokenCount);
168
+ const computedTotal = input + output + cacheRead + cacheCreate;
169
+ const total = rawTotal !== null && rawTotal > 0 ? rawTotal : computedTotal;
170
+ if (total <= 0) return null;
171
+ return {
172
+ input_tokens: input,
173
+ output_tokens: output,
174
+ cache_read_tokens: cacheRead,
175
+ cache_creation_tokens: cacheCreate,
176
+ total_tokens: total,
177
+ };
178
+ }
179
+
133
180
  export function normalizeHookPayload(host, payload) {
134
181
  const p = payload && typeof payload === 'object' ? payload : {};
182
+ const transcriptPath = p.transcript_path ?? p.transcriptPath;
183
+ const payloadUsage = extractUsageMetrics(
184
+ p.usage ?? p.message?.usage ?? p.tool_response?.usage ?? p.usageMetadata
185
+ );
186
+ const rawDur = Number(p.duration_seconds);
187
+ const durationSeconds = Number.isFinite(rawDur) && rawDur >= 0 ? Math.round(rawDur) : undefined;
188
+
135
189
  if (String(host).startsWith('antigravity') || p.toolCall) {
136
190
  const cwd = p.cwd ?? (Array.isArray(p.workspacePaths) ? p.workspacePaths[0] : undefined);
137
191
  return {
@@ -142,6 +196,9 @@ export function normalizeHookPayload(host, payload) {
142
196
  cwd,
143
197
  model: p.modelName,
144
198
  failed: Boolean(p.error),
199
+ transcriptPath,
200
+ ...(payloadUsage ? { usage: payloadUsage } : {}),
201
+ ...(durationSeconds !== undefined ? { durationSeconds } : {}),
145
202
  };
146
203
  }
147
204
  const resp = p.tool_response;
@@ -169,6 +226,9 @@ export function normalizeHookPayload(host, payload) {
169
226
  cwd: p.cwd,
170
227
  model: p.model,
171
228
  failed,
229
+ transcriptPath,
230
+ ...(payloadUsage ? { usage: payloadUsage } : {}),
231
+ ...(durationSeconds !== undefined ? { durationSeconds } : {}),
172
232
  };
173
233
  }
174
234
 
@@ -353,12 +413,106 @@ export function detectSkillCalls({
353
413
  return hits;
354
414
  }
355
415
 
356
- function readStoreCwdFlag(home) {
416
+ function readConfigFlags(home) {
357
417
  try {
358
418
  const cfg = JSON.parse(readFileSync(join(home, 'config.json'), 'utf8'));
359
- return cfg?.store_cwd === true;
419
+ return {
420
+ storeCwd: cfg?.store_cwd === true,
421
+ storePrompts: cfg?.store_prompts === true,
422
+ };
360
423
  } catch {
361
- return false;
424
+ return { storeCwd: false, storePrompts: false };
425
+ }
426
+ }
427
+
428
+ function extractUserTextFromRecord(obj) {
429
+ if (!obj || typeof obj !== 'object') return null;
430
+ if (obj.type === 'USER_INPUT' && typeof obj.content === 'string') {
431
+ return obj.content;
432
+ }
433
+ if (obj.type === 'user' || obj.role === 'user') {
434
+ const content = obj.message?.content ?? obj.content;
435
+ if (typeof content === 'string') return content;
436
+ if (Array.isArray(content)) {
437
+ const parts = content
438
+ .filter((b) => b?.type === 'text' && typeof b.text === 'string')
439
+ .map((b) => b.text);
440
+ if (parts.length > 0) return parts.join(' ');
441
+ }
442
+ }
443
+ if (obj.type === 'response_item' && obj.payload?.type === 'message' && obj.payload?.role === 'user') {
444
+ const content = obj.payload.content;
445
+ if (Array.isArray(content)) {
446
+ const parts = content.filter((b) => typeof b?.text === 'string').map((b) => b.text);
447
+ if (parts.length > 0) return parts.join(' ');
448
+ }
449
+ }
450
+ return null;
451
+ }
452
+
453
+ function readTranscriptTailContext(transcriptPath, nowMs) {
454
+ if (!transcriptPath || typeof transcriptPath !== 'string') return {};
455
+ try {
456
+ if (!existsSync(transcriptPath)) return {};
457
+ const size = statSync(transcriptPath).size;
458
+ if (size <= 0) return {};
459
+ const maxRead = 24 * 1024;
460
+ const offset = Math.max(0, size - maxRead);
461
+ const len = size - offset;
462
+ const buf = Buffer.allocUnsafe(len);
463
+ const fd = openSync(transcriptPath, 'r');
464
+ try {
465
+ readSync(fd, buf, 0, len, offset);
466
+ } finally {
467
+ closeSync(fd);
468
+ }
469
+ let text = buf.toString('utf8');
470
+ if (offset > 0) {
471
+ const nl = text.indexOf('\n');
472
+ if (nl !== -1) text = text.slice(nl + 1);
473
+ }
474
+ const lines = text.split('\n');
475
+ let usage = null;
476
+ let promptText = null;
477
+ let durationSeconds;
478
+
479
+ for (let i = lines.length - 1; i >= 0; i--) {
480
+ const line = lines[i].trim();
481
+ if (!line) continue;
482
+ let obj;
483
+ try {
484
+ obj = JSON.parse(line);
485
+ } catch {
486
+ continue;
487
+ }
488
+ if (!usage) {
489
+ usage = extractUsageMetrics(
490
+ obj.message?.usage ??
491
+ obj.usage ??
492
+ obj.usageMetadata ??
493
+ obj.payload?.usage ??
494
+ obj.payload?.info?.last_token_usage
495
+ );
496
+ }
497
+ if (promptText === null) {
498
+ const uText = extractUserTextFromRecord(obj);
499
+ if (uText !== null) {
500
+ promptText = uText;
501
+ const tsVal = obj.timestamp ?? obj.created_at;
502
+ if (tsVal && Number.isFinite(nowMs)) {
503
+ const startMs = Date.parse(tsVal);
504
+ if (Number.isFinite(startMs) && nowMs >= startMs && nowMs - startMs <= 86400_000) {
505
+ durationSeconds = Math.round((nowMs - startMs) / 1000);
506
+ }
507
+ }
508
+ }
509
+ }
510
+ if (usage && promptText !== null) break;
511
+ }
512
+
513
+ return { usage, promptText, durationSeconds };
514
+ } catch {
515
+ return {};
362
516
  }
363
517
  }
364
518
 
@@ -441,7 +595,14 @@ export function main() {
441
595
  if (uniqueHits.length === 0) return;
442
596
 
443
597
  mkdirSync(home, { recursive: true, mode: 0o700 });
444
- const storeCwd = readStoreCwdFlag(home);
598
+ const { storeCwd, storePrompts } = readConfigFlags(home);
599
+
600
+ const needsTail = !n.usage || n.durationSeconds === undefined || (storePrompts && !n.prompt);
601
+ const tailCtx = needsTail && n.transcriptPath ? readTranscriptTailContext(n.transcriptPath, nowMs) : {};
602
+ const usage = n.usage ?? tailCtx.usage ?? null;
603
+ const durationSeconds = n.durationSeconds ?? tailCtx.durationSeconds;
604
+ const rawPromptText = n.prompt ?? tailCtx.promptText;
605
+ const promptPreview = storePrompts && rawPromptText ? sanitizePromptPreview(rawPromptText) : '';
445
606
 
446
607
  const lines = uniqueHits.map((h, idx) =>
447
608
  JSON.stringify({
@@ -459,6 +620,9 @@ export function main() {
459
620
  ...(n.cwd ? { project: basename(n.cwd) } : {}),
460
621
  ...(storeCwd && n.cwd ? { cwd: n.cwd } : {}),
461
622
  ...(n.model ? { model: n.model } : {}),
623
+ ...(durationSeconds !== undefined ? { duration_seconds: durationSeconds } : {}),
624
+ ...(usage ? usage : {}),
625
+ ...(promptPreview ? { prompt_preview: promptPreview } : {}),
462
626
  origin: 'hook',
463
627
  ok: !n.failed,
464
628
  })
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "skilltally",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Real-time skill usage tracking via hooks for Antigravity, Claude Code, Codex & Gemini CLI."
5
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skilltally",
3
- "version": "1.0.3",
3
+ "version": "1.2.0",
4
4
  "description": "Real-time skill usage tracking via hooks for Antigravity, Claude Code, Codex & Gemini CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "skilltally",
3
3
  "displayName": "SkillTally",
4
4
  "description": "Real-time skill usage tracking via hooks for Antigravity, Claude Code, Codex & Gemini CLI. See which skills you actually use and which eat context.",
5
- "version": "1.0.3",
5
+ "version": "1.2.0",
6
6
  "author": {
7
7
  "name": "112516101106",
8
8
  "url": "https://github.com/112516101106"
@@ -20,11 +20,11 @@ Prefer the fastest available invocation:
20
20
 
21
21
  ## Common commands
22
22
 
23
- 1. **Overall usage & top skills** (default 30 days):
23
+ 1. **Overall usage, sparklines & top skills** (default 30 days):
24
24
  ```bash
25
25
  skilltally stats --since 30d
26
26
  ```
27
- Add `--json` for structured output, `--host <name>` to filter by host, or `--by-source` to separate duplicate skill names across sources.
27
+ Add `--json` for structured output (includes 14d `sparkline`, `via` trigger ratio, `tokenCostPerActivation`, and `insights`), `--host <name>` to filter by host, or `--by-source` to separate duplicate skill names across sources.
28
28
  2. **Top N skills**:
29
29
  ```bash
30
30
  skilltally top -n 20 --since 30d --metric activations
@@ -33,27 +33,42 @@ Prefer the fastest available invocation:
33
33
  ```bash
34
34
  skilltally unused --since 90d
35
35
  ```
36
- Shows enabled installed skills with zero activations in the window, grouped by source with estimated `KB` and `~tokens/session` saved by disabling unused plugins.
37
- 4. **Timeline & export**:
36
+ Shows enabled installed skills with zero activations in the window, Context Tax meter, and estimated `KB` / `~tokens/session` saved by disabling unused plugins.
37
+ 4. **Actionable optimization insights & workflow chains**:
38
+ ```bash
39
+ skilltally insights --since 30d
40
+ skilltally chains --since 30d
41
+ ```
42
+ - `insights` surfaces Context ROI (`~tok/activation`), runtime token & prompt cache hit rate, task duration (`Longest task`), heavy `SKILL.md` body alerts (`>=1,500` tokens), manual-only skills (`0%` auto-match — sharpen `SKILL.md` descriptions), single-project global skills (move to `.agents/skills` or `.claude/skills`), prompt trigger patterns (when `store_prompts: true`), and per-model breakdown.
43
+ - `chains` reveals `A -> B` transitions, 3-step workflows, and co-occurring skill pairs within sessions.
44
+ 5. **Interactive HTML Dashboard & visualizations**:
45
+ ```bash
46
+ skilltally dashboard --since 30d --open
47
+ ```
48
+ Generates a self-contained, zero-dependency HTML report (`~/.skilltally/dashboard.html` or `-o <file>`) with an interactive Context Tax Treemap, timeline, workflow flow diagram, filterable table, and Mermaid diagram snippets (`pie`, `xychart-beta`, `flowchart LR`).
49
+ When presenting analytics directly in chat, you can also run `--json` subcommands and render **Mermaid diagrams** (`pie`, `xychart-beta`, `flowchart LR`) or interactive HTML widgets from the JSON output.
50
+ 6. **Timeline & export**:
38
51
  ```bash
39
52
  skilltally timeline --skill <name> --by week
40
53
  skilltally export --format csv -o skilltally-events.csv
41
54
  ```
42
- 5. **Import history from local logs** (Antigravity, Codex, Claude Code, Gemini CLI):
55
+ 7. **Preview safe plugin/skill pruning**:
43
56
  ```bash
44
- skilltally backfill
57
+ skilltally prune --since 90d --dry-run
45
58
  ```
46
- 6. **Inspect installed inventory & verify hooks**:
59
+ 8. **Import history, inspect inventory, verify hooks & MCP server**:
47
60
  ```bash
61
+ skilltally backfill
48
62
  skilltally inventory --json
49
63
  skilltally doctor
64
+ skilltally mcp
50
65
  ```
51
66
 
52
67
  If `stats` shows zero events, run `skilltally doctor` to check hook installation, then suggest `skilltally install` and `skilltally backfill`.
53
68
 
54
69
  ## Rules
55
70
 
56
- - **Never delete, uninstall, or disable skills or plugins yourself**; present the findings and let the user decide.
71
+ - **Never delete, uninstall, or disable skills or plugins yourself** (never run `skilltally prune` without `--dry-run`) unless the user explicitly asks you to disable specific items; present the findings and let the user decide.
57
72
  - Report **activations** (unique `session × skill` pairs) as the primary metric and **reads** (total invocations) as secondary.
58
73
  - When reporting unused skills or plugins, include the **Context Tax** (`KB` and `~tokens/session`) so the user knows the context benefit of disabling a plugin.
59
74
  - Always state the time window (`--since`) and which hosts contributed data.