skilltally 0.0.0-stage → 1.0.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.
@@ -0,0 +1,271 @@
1
+ function padRight(str, len) {
2
+ const s = String(str);
3
+ return s.length >= len ? s : s + ' '.repeat(len - s.length);
4
+ }
5
+
6
+ function padLeft(str, len) {
7
+ const s = String(str);
8
+ return s.length >= len ? s : ' '.repeat(len - s.length) + s;
9
+ }
10
+
11
+ function formatDateCompact(iso) {
12
+ if (!iso) return '—';
13
+ return String(iso).slice(0, 16).replace('T', ' ');
14
+ }
15
+
16
+ function formatWindow(win) {
17
+ if (!win.from) return `all time (up to ${win.to})`;
18
+ return `last ${win.since} (${win.from} -> ${win.to})`;
19
+ }
20
+
21
+ function formatHostLine(hosts) {
22
+ const entries = Object.entries(hosts || {}).sort((a, b) => b[1] - a[1]);
23
+ if (entries.length === 0) return 'none';
24
+ return entries.map(([h, n]) => `${h} ${n}`).join(' · ');
25
+ }
26
+
27
+ export function formatStats(report, { limit = null, heading = 'skilltally', bySource = false } = {}) {
28
+ const lines = [];
29
+ lines.push(`${heading} — ${formatWindow(report.window)}`);
30
+ lines.push(`hosts: ${formatHostLine(report.totals.hosts)}`);
31
+ lines.push('');
32
+
33
+ const displayRows = limit && limit > 0 ? report.rows.slice(0, limit) : report.rows;
34
+ if (displayRows.length === 0) {
35
+ lines.push('No skill events found in this window.');
36
+ lines.push('Tip: run `skilltally backfill` to import historical sessions.');
37
+ } else {
38
+ const skillCol = Math.max(
39
+ 10,
40
+ ...displayRows.map((r) => (bySource ? `${r.skill} (${r.source})` : r.skill).length)
41
+ );
42
+ const rankW = Math.max(2, String(displayRows.length).length + 1);
43
+ lines.push(
44
+ ` ${padLeft('#', rankW)} ${padRight('skill', skillCol)} ${padLeft('activations', 11)} ${padLeft('reads', 5)} ${padRight('last used', 16)} hosts`
45
+ );
46
+ displayRows.forEach((r, idx) => {
47
+ const label = bySource ? `${r.skill} (${r.source})` : r.skill;
48
+ lines.push(
49
+ ` ${padLeft(idx + 1, rankW)} ${padRight(label, skillCol)} ${padLeft(r.activations, 11)} ${padLeft(r.reads, 5)} ${padRight(formatDateCompact(r.last_used), 16)} ${r.hosts.join(', ')}`
50
+ );
51
+ });
52
+ if (limit && report.rows.length > limit) {
53
+ lines.push(` ... and ${report.rows.length - limit} more skills`);
54
+ }
55
+ }
56
+
57
+ if (report.inventory.enabled > 0 || report.inventory.disabled > 0) {
58
+ lines.push('');
59
+ const dis = report.inventory.disabled > 0 ? ` (${report.inventory.disabled} disabled)` : '';
60
+ lines.push(
61
+ `installed: ${report.inventory.enabled}${dis} · used: ${report.inventory.used} · unused: ${report.inventory.unused} -> run \`skilltally unused\``
62
+ );
63
+ }
64
+
65
+ return lines.join('\n');
66
+ }
67
+
68
+ export function formatUnused(report, { showAll = false } = {}) {
69
+ const lines = [];
70
+ const u = report.unused;
71
+ const kb = (u.totalDescChars / 1024).toFixed(1);
72
+ lines.push(
73
+ `Unused enabled skills — ${formatWindow(report.window)}: ${u.total} (${kb} KB ≈ ~${u.totalEstTokens.toLocaleString()} tok/session)`
74
+ );
75
+
76
+ if (u.total === 0) {
77
+ lines.push('All enabled installed skills were used in this window.');
78
+ return lines.join('\n');
79
+ }
80
+
81
+ lines.push('');
82
+ const srcCol = Math.max(12, ...u.bySource.map((g) => g.source.length));
83
+ for (const g of u.bySource) {
84
+ const gKb = (g.descChars / 1024).toFixed(1);
85
+ const header = `${padRight(g.source, srcCol)} ${padLeft(g.skillCount, 3)} skills ${padLeft(gKb + ' KB', 8)} ~${padLeft(g.estTokens, 5)} tok/session`;
86
+ const names = g.skills.map((s) => s.name);
87
+ const preview = showAll || names.length <= 6 ? names.join(', ') : `${names.slice(0, 6).join(', ')}, … (+${names.length - 6})`;
88
+ lines.push(` ${header}`);
89
+ lines.push(` ${preview}`);
90
+ }
91
+
92
+ lines.push('');
93
+ lines.push('Tip: disabling an unused plugin removes all of its skill descriptions from every session context.');
94
+ return lines.join('\n');
95
+ }
96
+
97
+ export function formatInventory(inventory) {
98
+ const lines = [];
99
+ const enabled = inventory.skills.filter((s) => s.enabled);
100
+ const disabled = inventory.skills.filter((s) => !s.enabled);
101
+ const totalTok = enabled.reduce((acc, s) => acc + s.est_tokens, 0);
102
+ const totalKb = (enabled.reduce((acc, s) => acc + s.desc_chars, 0) / 1024).toFixed(1);
103
+
104
+ lines.push(
105
+ `Installed skills: ${enabled.length} enabled (${totalKb} KB ≈ ~${totalTok.toLocaleString()} tok/session), ${disabled.length} disabled`
106
+ );
107
+ lines.push('');
108
+
109
+ const bySrc = new Map();
110
+ for (const s of inventory.skills) {
111
+ let g = bySrc.get(s.source);
112
+ if (!g) {
113
+ g = { source: s.source, enabled: 0, disabled: 0, tokens: 0, hosts: new Set() };
114
+ bySrc.set(s.source, g);
115
+ }
116
+ if (s.enabled) {
117
+ g.enabled += 1;
118
+ g.tokens += s.est_tokens;
119
+ } else {
120
+ g.disabled += 1;
121
+ }
122
+ for (const h of s.hosts) g.hosts.add(h);
123
+ }
124
+
125
+ const rows = [...bySrc.values()].sort((a, b) => b.tokens - a.tokens || b.enabled - a.enabled);
126
+ const srcW = Math.max(10, ...rows.map((r) => r.source.length));
127
+ lines.push(` ${padRight('source', srcW)} ${padLeft('enabled', 7)} ${padLeft('disabled', 8)} ${padLeft('~tokens', 8)} hosts`);
128
+ for (const r of rows) {
129
+ lines.push(
130
+ ` ${padRight(r.source, srcW)} ${padLeft(r.enabled, 7)} ${padLeft(r.disabled, 8)} ${padLeft(r.tokens, 8)} ${[...r.hosts].sort().join(', ')}`
131
+ );
132
+ }
133
+ return lines.join('\n');
134
+ }
135
+
136
+ export function formatBackfill(summary) {
137
+ const lines = [];
138
+ lines.push(
139
+ `Backfill ${summary.dryRun ? '(dry-run) ' : ''}complete: ${summary.totalEvents} events across ${summary.uniqueSkills} skills`
140
+ );
141
+ for (const [host, h] of Object.entries(summary.hosts)) {
142
+ const zstNote = h.skippedZst ? ` (${h.skippedZst} .zst skipped)` : '';
143
+ lines.push(` ${padRight(host, 12)} files: ${padLeft(h.files, 4)} events: ${padLeft(h.events, 4)} skills: ${padLeft(h.uniqueSkills, 3)}${zstNote}`);
144
+ }
145
+ if (summary.outputPath) {
146
+ lines.push(`Written to: ${summary.outputPath}`);
147
+ }
148
+ return lines.join('\n');
149
+ }
150
+
151
+ export function formatInstall(res) {
152
+ const lines = [];
153
+ lines.push(`skilltally install${res.dryRun ? ' (dry-run)' : ''}`);
154
+ lines.push('');
155
+ for (const r of res.results) {
156
+ const detail = r.reason || r.target || '';
157
+ lines.push(` ${padRight(r.host, 12)} ${padRight(r.status, 14)} ${detail}`.trimEnd());
158
+ if (r.backup) lines.push(` backup: ${r.backup}`);
159
+ if (r.note) lines.push(` note: ${r.note}`);
160
+ }
161
+ return lines.join('\n');
162
+ }
163
+
164
+ export function formatUninstall(res) {
165
+ const lines = [];
166
+ lines.push(`skilltally uninstall${res.dryRun ? ' (dry-run)' : ''}`);
167
+ lines.push('');
168
+ for (const r of res.results) {
169
+ const detail = r.target || '';
170
+ lines.push(` ${padRight(r.host, 12)} ${padRight(r.status, 14)} ${detail}`.trimEnd());
171
+ if (r.backup) lines.push(` backup: ${r.backup}`);
172
+ }
173
+ if (res.purgeRequested) {
174
+ lines.push(
175
+ res.purged
176
+ ? ` data ${res.dryRun ? 'would_remove' : 'purged'} ${res.dataHome}`
177
+ : ` data not_found ${res.dataHome}`
178
+ );
179
+ }
180
+ return lines.join('\n');
181
+ }
182
+
183
+ export function formatDoctor(report) {
184
+ const lines = [];
185
+ lines.push(`skilltally doctor — ${report.ok ? 'OK' : 'ISSUES FOUND'}`);
186
+ lines.push('');
187
+ lines.push(
188
+ ` node ${report.node.ok ? 'ok' : 'fail'} v${report.node.version} (zstd native: ${report.node.zstdNative ? 'yes' : 'no'})`
189
+ );
190
+ lines.push(
191
+ ` self-test ${report.selfTest.ok ? 'ok' : 'fail'}${report.selfTest.error ? ` ${report.selfTest.error}` : ''}`
192
+ );
193
+ lines.push(
194
+ ` events ${report.events.total} total (${report.events.hook} hook, ${report.events.backfill} backfill, ${report.events.corruptLines} corrupt)${report.events.latestTs ? ` · latest ${formatDateCompact(report.events.latestTs)}` : ''}`
195
+ );
196
+ lines.push('');
197
+ lines.push('Hosts:');
198
+ for (const [name, h] of Object.entries(report.hosts)) {
199
+ const status = !h.detected
200
+ ? 'not_detected'
201
+ : h.hookPathValid === false
202
+ ? 'broken_path'
203
+ : h.installed
204
+ ? h.disabled
205
+ ? 'disabled'
206
+ : 'active'
207
+ : 'not_installed';
208
+ const extras = [];
209
+ if (h.mode && h.mode !== 'none') extras.push(`mode=${h.mode}`);
210
+ if (h.pluginInstalled) extras.push('plugin=yes');
211
+ if (h.settingsInstalled) extras.push('settings=yes');
212
+ if (h.hooksJsonInstalled) extras.push('hooks.json=yes');
213
+ if (h.trustStatus && h.trustStatus !== 'unknown') extras.push(`trust=${h.trustStatus}`);
214
+ if (h.hooksConfigDisabled) extras.push('WARNING: hooksConfig.enabled=false');
215
+ if (h.duplicateHook) extras.push('WARNING: duplicate hook');
216
+ if (h.hookPathValid === false) extras.push('ERROR: hook target missing on disk');
217
+ lines.push(
218
+ ` ${padRight(name, 12)} ${padRight(status, 14)} ${extras.join(' · ')}`.trimEnd()
219
+ );
220
+ }
221
+ return lines.join('\n');
222
+ }
223
+
224
+ export function formatTimeline(timeline) {
225
+ const lines = [];
226
+ const label = timeline.skill ? `skilltally timeline (${timeline.skill})` : 'skilltally timeline';
227
+ lines.push(`${label} — by ${timeline.by}, ${formatWindow(timeline.window)}`);
228
+ lines.push('');
229
+
230
+ if (timeline.rows.length === 0) {
231
+ lines.push('No skill events found in this window.');
232
+ return lines.join('\n');
233
+ }
234
+
235
+ const maxAct = Math.max(1, ...timeline.rows.map((r) => r.activations));
236
+ const bucketW = Math.max(10, ...timeline.rows.map((r) => r.bucket.length));
237
+ const barWidth = 24;
238
+
239
+ lines.push(
240
+ ` ${padRight('period', bucketW)} ${padRight('bar', barWidth)} ${padLeft('activations', 11)} ${padLeft('reads', 5)} ${padLeft('skills', 6)}`
241
+ );
242
+ for (const r of timeline.rows) {
243
+ const filled = Math.max(1, Math.round((r.activations / maxAct) * barWidth));
244
+ const bar = '#'.repeat(filled);
245
+ lines.push(
246
+ ` ${padRight(r.bucket, bucketW)} ${padRight(bar, barWidth)} ${padLeft(r.activations, 11)} ${padLeft(r.reads, 5)} ${padLeft(r.uniqueSkills, 6)}`
247
+ );
248
+ }
249
+ lines.push('');
250
+ lines.push(
251
+ `totals: ${timeline.totals.activations} activations · ${timeline.totals.reads} reads across ${timeline.totals.buckets} ${timeline.by}(s)`
252
+ );
253
+ return lines.join('\n');
254
+ }
255
+
256
+ export function formatDebug(status) {
257
+ const lines = [];
258
+ lines.push(`skilltally debug: ${status.enabled ? 'on' : 'off'}`);
259
+ lines.push(` marker: ${status.markerPath}`);
260
+ lines.push(
261
+ ` log: ${status.logPath} (${status.logExists ? `${status.logLines} lines, ${status.logBytes} bytes` : 'absent'})`
262
+ );
263
+ if (status.deletedLog) {
264
+ lines.push(' cleaned: removed debug.jsonl');
265
+ }
266
+ if (status.enabled) {
267
+ lines.push('');
268
+ lines.push('Warning: debug mode logs raw hook stdin payloads (may include shell commands). Run `skilltally debug off` when done.');
269
+ }
270
+ return lines.join('\n');
271
+ }
@@ -0,0 +1,117 @@
1
+ import { canonicalizeEvent, dedupeEvents } from '../core/normalize.mjs';
2
+ import { parseSince } from './aggregate.mjs';
3
+
4
+ const VALID_BY = new Set(['day', 'week', 'month']);
5
+
6
+ export function isoWeekBucket(date) {
7
+ const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
8
+ const dayNum = d.getUTCDay() || 7;
9
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
10
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
11
+ const weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
12
+ return `${d.getUTCFullYear()}-W${String(weekNo).padStart(2, '0')}`;
13
+ }
14
+
15
+ export function bucketOf(isoTs, by) {
16
+ const d = new Date(isoTs);
17
+ if (!Number.isFinite(d.getTime())) return null;
18
+ if (by === 'day') return d.toISOString().slice(0, 10);
19
+ if (by === 'month') return d.toISOString().slice(0, 7);
20
+ if (by === 'week') return isoWeekBucket(d);
21
+ throw new Error(`Invalid --by value: "${by}" (expected: day, week, month)`);
22
+ }
23
+
24
+ function hostMatches(eventHost, filterHost) {
25
+ if (!filterHost || filterHost === 'all') return true;
26
+ if (eventHost === filterHost) return true;
27
+ if (filterHost === 'antigravity' && String(eventHost).startsWith('antigravity')) return true;
28
+ return false;
29
+ }
30
+
31
+ export function buildTimeline({
32
+ events = [],
33
+ inventory = null,
34
+ config = {},
35
+ skill = null,
36
+ by = 'day',
37
+ since = '30d',
38
+ host = null,
39
+ project = null,
40
+ now = new Date(),
41
+ } = {}) {
42
+ if (!VALID_BY.has(by)) {
43
+ throw new Error(`Invalid --by value: "${by}" (expected: day, week, month)`);
44
+ }
45
+
46
+ const sinceDate = since === null ? null : parseSince(since, now);
47
+ const sinceMs = sinceDate ? sinceDate.getTime() : null;
48
+ const aliases = config?.aliases || {};
49
+ const exclSkills = new Set(config?.exclude_skills || []);
50
+ const exclSources = new Set(config?.exclude_sources || []);
51
+ const targetSkill = skill
52
+ ? canonicalizeEvent({ skill }, inventory?.index, aliases).skill
53
+ : null;
54
+
55
+ const canonicalized = events.map((ev) => canonicalizeEvent(ev, inventory?.index, aliases));
56
+ const deduped = dedupeEvents(canonicalized);
57
+
58
+ const buckets = new Map();
59
+ let totalReads = 0;
60
+
61
+ for (const ev of deduped) {
62
+ if (ev.ok === false) continue;
63
+ if (!hostMatches(ev.host, host)) continue;
64
+ if (project && ev.project !== project) continue;
65
+ if (exclSkills.has(ev.skill) || exclSources.has(ev.source)) continue;
66
+ if (targetSkill && ev.skill !== targetSkill) continue;
67
+
68
+ const tsMs = Date.parse(ev.ts);
69
+ if (!Number.isFinite(tsMs)) continue;
70
+ if (sinceMs !== null && tsMs < sinceMs) continue;
71
+
72
+ const bKey = bucketOf(ev.ts, by);
73
+ if (!bKey) continue;
74
+
75
+ let bucket = buckets.get(bKey);
76
+ if (!bucket) {
77
+ bucket = {
78
+ bucket: bKey,
79
+ activationsSet: new Set(),
80
+ skillsSet: new Set(),
81
+ reads: 0,
82
+ };
83
+ buckets.set(bKey, bucket);
84
+ }
85
+
86
+ bucket.reads += 1;
87
+ totalReads += 1;
88
+ const sessKey = `${ev.session_id || ev.id || ev.ts}\0${ev.skill}`;
89
+ bucket.activationsSet.add(sessKey);
90
+ bucket.skillsSet.add(ev.skill);
91
+ }
92
+
93
+ const rows = [...buckets.values()]
94
+ .sort((a, b) => a.bucket.localeCompare(b.bucket))
95
+ .map((b) => ({
96
+ bucket: b.bucket,
97
+ activations: b.activationsSet.size,
98
+ reads: b.reads,
99
+ uniqueSkills: b.skillsSet.size,
100
+ }));
101
+
102
+ return {
103
+ window: {
104
+ since: since ?? 'all',
105
+ from: sinceDate ? sinceDate.toISOString().slice(0, 10) : null,
106
+ to: now.toISOString().slice(0, 10),
107
+ },
108
+ by,
109
+ skill: targetSkill,
110
+ totals: {
111
+ buckets: rows.length,
112
+ activations: rows.reduce((acc, r) => acc + r.activations, 0),
113
+ reads: totalReads,
114
+ },
115
+ rows,
116
+ };
117
+ }