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.
@@ -0,0 +1,355 @@
1
+ import {
2
+ existsSync,
3
+ mkdirSync,
4
+ readdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ writeFileSync,
8
+ } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { getHomeDir, loadConfig } from '../core/config.mjs';
12
+ import { readAllEvents } from '../core/store.mjs';
13
+ import { scanInventory } from '../inventory/scan.mjs';
14
+ import { aggregateStats } from '../report/aggregate.mjs';
15
+ import { backupFile, readJsonObject, writeJsonAtomic } from './runtime.mjs';
16
+
17
+ function normalizePluginName(raw) {
18
+ const s = String(raw || '').trim();
19
+ if (!s) return '';
20
+ return s.startsWith('plugin:') ? s.slice(7) : s;
21
+ }
22
+
23
+ function findCodexPluginKeysInCache(homeDir, pluginName) {
24
+ const cacheRoot = join(homeDir, '.codex', 'plugins', 'cache');
25
+ const keys = [];
26
+ if (!existsSync(cacheRoot)) return keys;
27
+ try {
28
+ for (const mkt of readdirSync(cacheRoot, { withFileTypes: true })) {
29
+ if (!mkt.isDirectory() && !mkt.isSymbolicLink()) continue;
30
+ if (existsSync(join(cacheRoot, mkt.name, pluginName))) {
31
+ keys.push(`${pluginName}@${mkt.name}`);
32
+ }
33
+ }
34
+ } catch {}
35
+ return keys;
36
+ }
37
+
38
+ function disableCodexPluginInToml(tomlRaw, pluginName, cacheKeys) {
39
+ const lines = tomlRaw ? tomlRaw.split(/\r?\n/) : [];
40
+ const escaped = pluginName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
41
+ const secRe = new RegExp(`^\\[plugins\\.(?:"${escaped}@[^"]+"|'${escaped}@[^']+'|${escaped})\\]$`);
42
+
43
+ let matchedSection = false;
44
+ let inTargetSection = false;
45
+ let sawEnabledLine = false;
46
+ const out = [];
47
+
48
+ for (let i = 0; i < lines.length; i++) {
49
+ const rawLine = lines[i];
50
+ const clean = rawLine.replace(/#.*$/, '').trim();
51
+ if (clean.startsWith('[')) {
52
+ if (inTargetSection && !sawEnabledLine) {
53
+ out.push('enabled = false');
54
+ }
55
+ inTargetSection = secRe.test(clean);
56
+ if (inTargetSection) {
57
+ matchedSection = true;
58
+ sawEnabledLine = false;
59
+ }
60
+ out.push(rawLine);
61
+ continue;
62
+ }
63
+
64
+ if (inTargetSection && /^enabled\s*=/.test(clean)) {
65
+ sawEnabledLine = true;
66
+ out.push('enabled = false');
67
+ continue;
68
+ }
69
+
70
+ out.push(rawLine);
71
+ }
72
+ if (inTargetSection && !sawEnabledLine) {
73
+ out.push('enabled = false');
74
+ }
75
+
76
+ if (matchedSection) {
77
+ return out.join('\n').replace(/\n*$/, '\n');
78
+ }
79
+
80
+ if (cacheKeys.length > 0) {
81
+ const prefix = tomlRaw && !tomlRaw.endsWith('\n') ? tomlRaw + '\n' : tomlRaw;
82
+ const additions = cacheKeys.map((k) => `[plugins."${k}"]\nenabled = false`).join('\n\n');
83
+ return `${prefix}${prefix ? '\n' : ''}${additions}\n`;
84
+ }
85
+
86
+ return null;
87
+ }
88
+
89
+ function hasCodexDisabledSkillPath(tomlRaw, canonPath) {
90
+ if (!tomlRaw) return false;
91
+ let inSkillCfg = false;
92
+ let pathVal = null;
93
+ let enabledVal = null;
94
+
95
+ const check = () =>
96
+ inSkillCfg && pathVal && pathVal.replace(/\\/g, '/') === canonPath && enabledVal === false;
97
+
98
+ for (const rawLine of tomlRaw.split(/\r?\n/)) {
99
+ const line = rawLine.replace(/#.*$/, '').trim();
100
+ if (!line) continue;
101
+ if (line === '[[skills.config]]') {
102
+ if (check()) return true;
103
+ inSkillCfg = true;
104
+ pathVal = null;
105
+ enabledVal = null;
106
+ continue;
107
+ }
108
+ if (line.startsWith('[')) {
109
+ if (check()) return true;
110
+ inSkillCfg = false;
111
+ pathVal = null;
112
+ enabledVal = null;
113
+ continue;
114
+ }
115
+ if (inSkillCfg) {
116
+ const pm = line.match(/^path\s*=\s*(?:"([^"]+)"|'([^']+)')/);
117
+ if (pm) pathVal = pm[1] || pm[2];
118
+ const em = line.match(/^enabled\s*=\s*(true|false)\b/);
119
+ if (em) enabledVal = em[1] === 'true';
120
+ }
121
+ }
122
+ return check();
123
+ }
124
+
125
+ function appendCodexDisabledSkill(tomlRaw, canonPath) {
126
+ if (hasCodexDisabledSkillPath(tomlRaw, canonPath)) return null;
127
+ const escaped = canonPath.replace(/\\/g, '/').replace(/"/g, '\\"');
128
+ const prefix = tomlRaw ? (tomlRaw.endsWith('\n') ? tomlRaw : tomlRaw + '\n') : '';
129
+ return `${prefix}${prefix ? '\n' : ''}[[skills.config]]\npath = "${escaped}"\nenabled = false\n`;
130
+ }
131
+
132
+ function writeTextAtomic(filePath, text, mode = 0o600) {
133
+ mkdirSync(dirname(filePath), { recursive: true });
134
+ const tmp = `${filePath}.tmp.${process.pid}`;
135
+ writeFileSync(tmp, text, { mode });
136
+ renameSync(tmp, filePath);
137
+ }
138
+
139
+ /**
140
+ * Safely disable 100%-unused plugins or explicitly specified unused skills
141
+ * across Antigravity and Codex with automatic config backups.
142
+ */
143
+ export function runPrune({
144
+ homeDir = homedir(),
145
+ dataHome = getHomeDir(),
146
+ cwd = process.cwd(),
147
+ since = '90d',
148
+ host = 'all',
149
+ plugins = [],
150
+ skills = [],
151
+ dryRun = false,
152
+ now = new Date(),
153
+ } = {}) {
154
+ const { events } = readAllEvents(dataHome);
155
+ const config = loadConfig(dataHome);
156
+ const inventory = scanInventory({ homeDir, cwd, includeProject: false });
157
+ const filterHost = !host || host === 'all' ? null : host;
158
+ const report = aggregateStats({
159
+ events,
160
+ inventory,
161
+ config,
162
+ since,
163
+ host: filterHost,
164
+ now,
165
+ });
166
+
167
+ const enabledBySource = new Map();
168
+ for (const s of inventory.skills) {
169
+ if (!s.enabled) continue;
170
+ let list = enabledBySource.get(s.source);
171
+ if (!list) {
172
+ list = [];
173
+ enabledBySource.set(s.source, list);
174
+ }
175
+ list.push(s);
176
+ }
177
+
178
+ const reqPlugins = new Set(plugins.map(normalizePluginName).filter(Boolean));
179
+ const reqSkills = new Set(skills.map((s) => String(s || '').trim()).filter(Boolean));
180
+ const targetPluginsOnly = reqPlugins.size > 0;
181
+ const targetSkillsOnly = reqSkills.size > 0 && reqPlugins.size === 0;
182
+
183
+ // Qualifying 100% unused plugins
184
+ const qualifyingPlugins = [];
185
+ if (!targetSkillsOnly) {
186
+ for (const group of report.unused.bySource) {
187
+ if (!group.source.startsWith('plugin:')) continue;
188
+ const pluginName = group.source.slice(7);
189
+ if (targetPluginsOnly && !reqPlugins.has(pluginName)) continue;
190
+
191
+ const totalEnabledInSource = (enabledBySource.get(group.source) || []).length;
192
+ if (totalEnabledInSource === 0 || group.skillCount < totalEnabledInSource) {
193
+ continue;
194
+ }
195
+
196
+ const hostsSet = new Set();
197
+ for (const s of group.skills) {
198
+ for (const h of s.hosts || []) hostsSet.add(h);
199
+ }
200
+
201
+ qualifyingPlugins.push({
202
+ source: group.source,
203
+ plugin: pluginName,
204
+ skillCount: group.skillCount,
205
+ estTokens: group.estTokens,
206
+ descChars: group.descChars,
207
+ hosts: [...hostsSet],
208
+ });
209
+ }
210
+ }
211
+
212
+ const allowAntigravity = !filterHost || filterHost === 'antigravity';
213
+ const allowCodex = !filterHost || filterHost === 'codex';
214
+
215
+ const disabledPlugins = [];
216
+ const disabledSkills = [];
217
+ const backups = [];
218
+
219
+ // 1. Disable Antigravity plugins via ~/.gemini/config/config.json
220
+ if (allowAntigravity && qualifyingPlugins.length > 0) {
221
+ const agyCfgPath = join(homeDir, '.gemini', 'config', 'config.json');
222
+ const agyTargets = qualifyingPlugins.filter((p) => {
223
+ if (!p.hosts.includes('antigravity')) return false;
224
+ return (
225
+ existsSync(join(homeDir, '.gemini', 'config', 'plugins', p.plugin)) ||
226
+ existsSync(join(homeDir, '.gemini', 'antigravity', 'builtin', 'plugins', p.plugin))
227
+ );
228
+ });
229
+
230
+ if (agyTargets.length > 0) {
231
+ const doc = existsSync(agyCfgPath) ? readJsonObject(agyCfgPath) : {};
232
+ const pluginsObj =
233
+ doc.plugins && typeof doc.plugins === 'object' && !Array.isArray(doc.plugins)
234
+ ? { ...doc.plugins }
235
+ : {};
236
+ let agyChanged = false;
237
+
238
+ for (const p of agyTargets) {
239
+ const cur = pluginsObj[p.plugin];
240
+ if (!cur || cur.enabled !== false) {
241
+ pluginsObj[p.plugin] = { ...(cur && typeof cur === 'object' ? cur : {}), enabled: false };
242
+ agyChanged = true;
243
+ disabledPlugins.push({
244
+ source: p.source,
245
+ plugin: p.plugin,
246
+ host: 'antigravity',
247
+ skillCount: p.skillCount,
248
+ estTokens: p.estTokens,
249
+ descChars: p.descChars,
250
+ });
251
+ }
252
+ }
253
+
254
+ if (agyChanged) {
255
+ doc.plugins = pluginsObj;
256
+ const bak = backupFile(agyCfgPath, dataHome, 'antigravity-config-prune', dryRun);
257
+ if (bak) backups.push(bak);
258
+ if (!dryRun) {
259
+ writeJsonAtomic(agyCfgPath, doc, 0o600);
260
+ }
261
+ }
262
+ }
263
+ }
264
+
265
+ // 2. Disable Codex plugins & explicitly requested Codex skills via ~/.codex/config.toml
266
+ if (allowCodex) {
267
+ const codexTomlPath = join(homeDir, '.codex', 'config.toml');
268
+ let tomlRaw = existsSync(codexTomlPath) ? readFileSync(codexTomlPath, 'utf8') : '';
269
+ let codexChanged = false;
270
+
271
+ for (const p of qualifyingPlugins) {
272
+ if (!p.hosts.includes('codex')) continue;
273
+ const cacheKeys = findCodexPluginKeysInCache(homeDir, p.plugin);
274
+ const updated = disableCodexPluginInToml(tomlRaw, p.plugin, cacheKeys);
275
+ if (updated !== null && updated !== tomlRaw) {
276
+ tomlRaw = updated;
277
+ codexChanged = true;
278
+ disabledPlugins.push({
279
+ source: p.source,
280
+ plugin: p.plugin,
281
+ host: 'codex',
282
+ skillCount: p.skillCount,
283
+ estTokens: p.estTokens,
284
+ descChars: p.descChars,
285
+ });
286
+ }
287
+ }
288
+
289
+ if (reqSkills.size > 0) {
290
+ const unusedSkillSet = new Set();
291
+ for (const g of report.unused.bySource) {
292
+ for (const s of g.skills) unusedSkillSet.add(s.path);
293
+ }
294
+
295
+ for (const s of inventory.skills) {
296
+ if (!s.enabled) continue;
297
+ if (!reqSkills.has(s.name) && !reqSkills.has(s.dir_name)) continue;
298
+ if (!s.hosts.includes('codex')) continue;
299
+ // Prefer disabling only unused skills unless explicitly absent from used rows
300
+ if (!unusedSkillSet.has(s.path) && report.rows.some((r) => r.skill === s.name)) {
301
+ continue;
302
+ }
303
+ const updated = appendCodexDisabledSkill(tomlRaw, s.path);
304
+ if (updated !== null && updated !== tomlRaw) {
305
+ tomlRaw = updated;
306
+ codexChanged = true;
307
+ disabledSkills.push({
308
+ name: s.name,
309
+ source: s.source,
310
+ host: 'codex',
311
+ path: s.path,
312
+ est_tokens: s.est_tokens || 0,
313
+ desc_chars: s.desc_chars || 0,
314
+ });
315
+ }
316
+ }
317
+ }
318
+
319
+ if (codexChanged) {
320
+ const bak = backupFile(codexTomlPath, dataHome, 'codex-config-prune', dryRun);
321
+ if (bak) backups.push(bak);
322
+ if (!dryRun) {
323
+ writeTextAtomic(codexTomlPath, tomlRaw, 0o600);
324
+ }
325
+ }
326
+ }
327
+
328
+ // Deduplicate savings across hosts if the same plugin appeared on multiple hosts
329
+ const seenSavingsKeys = new Set();
330
+ let savedTokensPerSession = 0;
331
+ let savedDescChars = 0;
332
+
333
+ for (const p of disabledPlugins) {
334
+ if (seenSavingsKeys.has(p.source)) continue;
335
+ seenSavingsKeys.add(p.source);
336
+ savedTokensPerSession += p.estTokens || 0;
337
+ savedDescChars += p.descChars || 0;
338
+ }
339
+ for (const s of disabledSkills) {
340
+ if (seenSavingsKeys.has(s.path)) continue;
341
+ seenSavingsKeys.add(s.path);
342
+ savedTokensPerSession += s.est_tokens || 0;
343
+ savedDescChars += s.desc_chars || 0;
344
+ }
345
+
346
+ return {
347
+ dryRun,
348
+ window: report.window,
349
+ disabledPlugins,
350
+ disabledSkills,
351
+ savedTokensPerSession,
352
+ savedKb: Number((savedDescChars / 1024).toFixed(1)),
353
+ backups,
354
+ };
355
+ }
@@ -285,15 +285,17 @@ export function scanInventory({ homeDir = homedir(), cwd = process.cwd(), includ
285
285
  }
286
286
 
287
287
  const descChars = fm.description.length;
288
+ const bytes = Buffer.byteLength(md, 'utf8');
288
289
  byCanonPath.set(canon, {
289
290
  name: fm.name || dirName,
290
291
  dir_name: dirName,
291
292
  path: canon,
292
293
  source: source || resolveSource(canon, cwd, homeDir),
293
294
  hosts: [host],
294
- bytes: Buffer.byteLength(md, 'utf8'),
295
+ bytes,
295
296
  desc_chars: descChars,
296
297
  est_tokens: descChars > 0 ? Math.ceil(descChars / 4) : 0,
298
+ body_tokens: bytes > 0 ? Math.ceil(bytes / 4) : 0,
297
299
  enabled,
298
300
  });
299
301
  };