@oficiallyakshay/trash-panda 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/docs/reference.md +220 -0
- package/examples/in-charge.json +7 -0
- package/examples/live.json +17 -0
- package/package.json +38 -4
- package/scripts/claude-leftovers-cleanup.mjs +242 -0
- package/src/claude-leftovers.mjs +949 -0
- package/src/metrics.mjs +233 -0
- package/src/rebuildables.mjs +491 -0
- package/src/records.mjs +326 -0
- package/src/settings.mjs +205 -0
- package/src/setup.mjs +428 -0
- package/src/temp-entries.mjs +153 -0
- package/src/triggers.mjs +500 -0
- package/src/tui/format.mjs +177 -0
- package/src/tui/watch.mjs +118 -0
- package/src/update.mjs +281 -0
- package/src/worktree-git.mjs +145 -0
- package/src/worktree-liveness.mjs +87 -0
package/src/metrics.mjs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/metrics.mjs — opt-in anonymous metrics, off by default.
|
|
3
|
+
*
|
|
4
|
+
* Two events: one after each run, one a day. Each is sent by a process of its
|
|
5
|
+
* own (the internal `_metrics` command), so a run never waits for the network;
|
|
6
|
+
* that process reads the setting again, sends once with a short timeout and
|
|
7
|
+
* ends. A failed send is dropped and never tried again.
|
|
8
|
+
*
|
|
9
|
+
* EVENTS lists every field and the only values it may hold; `clean` drops
|
|
10
|
+
* anything else, so no path, name or text can leave. docs/telemetry.md lists
|
|
11
|
+
* the same fields and a test compares the two.
|
|
12
|
+
*
|
|
13
|
+
* Network: one host, PostHog Cloud US.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
17
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
18
|
+
import { existsSync, linkSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { homedir } from "node:os";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
import { createInterface } from "node:readline";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
import { CLASSES } from "./claude-leftovers.mjs";
|
|
24
|
+
import { rawSettings, readSettings, settingsPath, trashPandaDir, writeSetting } from "./settings.mjs";
|
|
25
|
+
|
|
26
|
+
export const ENDPOINT = "https://us.i.posthog.com/i/v0/e/";
|
|
27
|
+
// PostHog's public, write-only project key: anyone may read it, and it can only add events.
|
|
28
|
+
export const KEY = "phc_BGLN5bXDwYbwdzkzci7L2tNbyWXtUfwokDRhP6TG5w2Q";
|
|
29
|
+
export const DOC_URL = "https://github.com/oficiallyAkshay/trash-panda/blob/main/docs/telemetry.md";
|
|
30
|
+
export const TIMEOUT_MS = 3000;
|
|
31
|
+
export const DAY_MS = 24 * 60 * 60 * 1000;
|
|
32
|
+
export const APP_NAME = "Trash Panda.app";
|
|
33
|
+
export const COMMON = Object.freeze({ product: "trash-panda", schema_version: 1, $process_person_profile: false, $geoip_disable: true });
|
|
34
|
+
|
|
35
|
+
const TRIGGERS = ["lowDisk", "schedule", "sessionStart", "hand"];
|
|
36
|
+
const isBool = (v) => typeof v === "boolean";
|
|
37
|
+
const isCount = (v) => Number.isInteger(v) && v >= 0;
|
|
38
|
+
const isPct = (v) => typeof v === "number" && v >= 0 && v <= 100;
|
|
39
|
+
// Digits and dots, with a pre-release word and number for a package version.
|
|
40
|
+
const isVersion = (v) => typeof v === "string" && /^\d{1,4}(\.\d{1,4}){0,2}(-[a-z]{1,10}\.\d{1,4})?$/.test(v);
|
|
41
|
+
|
|
42
|
+
/** Every event, each field, and the check its value must pass. */
|
|
43
|
+
export const EVENTS = {
|
|
44
|
+
run_finished: {
|
|
45
|
+
trigger: (v) => TRIGGERS.includes(v) || v === "tool",
|
|
46
|
+
preview: isBool,
|
|
47
|
+
bytes_back: isCount,
|
|
48
|
+
items: isCount,
|
|
49
|
+
...Object.fromEntries(Object.keys(CLASSES).map((c) => [`bytes_${c}`, isCount])),
|
|
50
|
+
free_pct_before: isPct,
|
|
51
|
+
free_pct_after: isPct,
|
|
52
|
+
duration_sec: isCount,
|
|
53
|
+
},
|
|
54
|
+
daily_report: {
|
|
55
|
+
version: isVersion,
|
|
56
|
+
macos: isVersion,
|
|
57
|
+
low_disk_on: isBool,
|
|
58
|
+
schedule_on: isBool,
|
|
59
|
+
session_start_on: isBool,
|
|
60
|
+
low_mark_pct: isPct,
|
|
61
|
+
critical_mark_pct: isPct,
|
|
62
|
+
app_installed: isBool,
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Only the listed fields with listed values; null for an unknown event. */
|
|
67
|
+
export function clean(name, props) {
|
|
68
|
+
if (!Object.hasOwn(EVENTS, name)) return null;
|
|
69
|
+
return Object.fromEntries(Object.entries(EVENTS[name]).flatMap(([field, ok]) => (ok(props[field]) ?[[field, props[field]]] : [])));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const isOn = (dir) => readSettings(settingsPath(dir)).settings.metrics === true;
|
|
73
|
+
|
|
74
|
+
// ── the setting ─────────────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
const idPath = (dir) => join(dir, "metrics-id");
|
|
77
|
+
const dailyPath = (dir) => join(dir, "metrics-daily");
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Save the choice in settings.json, every other key kept, in one rename; off
|
|
81
|
+
* also deletes the install id. Throws when the file cannot be read or written.
|
|
82
|
+
*/
|
|
83
|
+
export function setMetrics(dir, on) {
|
|
84
|
+
writeSetting(dir, "metrics", on);
|
|
85
|
+
if (!on) for (const f of [idPath(dir), dailyPath(dir)]) rmSync(f, { force: true });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** True when nobody answered yet and the settings file can hold an answer. */
|
|
89
|
+
export function shouldAsk(dir) {
|
|
90
|
+
try {
|
|
91
|
+
return !Object.hasOwn(rawSettings(settingsPath(dir)), "metrics");
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Ask once, in a terminal: true, false (the default), or null when the input ended with no answer. */
|
|
98
|
+
export function askMetrics({ input = process.stdin, output = process.stdout } = {}) {
|
|
99
|
+
return new Promise((resolve) => {
|
|
100
|
+
const rl = createInterface({ input, output });
|
|
101
|
+
rl.on("close", () => resolve(null));
|
|
102
|
+
rl.question(`Share anonymous metrics (run sizes and free space, never a path or a name)?\nThe full list: ${DOC_URL}\nShare? [y/N] `, (answer) => {
|
|
103
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
104
|
+
rl.close();
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** What `trash-panda config metrics` prints. */
|
|
110
|
+
export function metricsStatus(dir) {
|
|
111
|
+
if (!isOn(dir)) return "Metrics are off. Turn them on with: trash-panda config metrics on";
|
|
112
|
+
return `Metrics are on. Install id: ${readId(dir) ?? "made at the first send"}. Every field: ${DOC_URL}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ── the install id ──────────────────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
function readId(dir) {
|
|
118
|
+
try {
|
|
119
|
+
const id = readFileSync(idPath(dir), "utf8").trim();
|
|
120
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id) ? id : null;
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The random id of this install, made at the first send. Two senders at once end with one id. */
|
|
127
|
+
export function installId(dir, { linkImpl = linkSync } = {}) {
|
|
128
|
+
const kept = readId(dir);
|
|
129
|
+
if (kept) return kept;
|
|
130
|
+
const tmp = `${idPath(dir)}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
131
|
+
writeFileSync(tmp, randomUUID());
|
|
132
|
+
try {
|
|
133
|
+
linkImpl(tmp, idPath(dir));
|
|
134
|
+
} catch {
|
|
135
|
+
// Another sender's id stays and is read below; a file that is not an id is replaced.
|
|
136
|
+
if (!readId(dir)) renameSync(tmp, idPath(dir));
|
|
137
|
+
} finally {
|
|
138
|
+
rmSync(tmp, { force: true });
|
|
139
|
+
}
|
|
140
|
+
return readId(dir);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ── sending ─────────────────────────────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
/** What the daily report says. */
|
|
146
|
+
export function dailyFacts({ dir = trashPandaDir(), execImpl = execFileSync, appDirs = ["/Applications", join(homedir(), "Applications")] } = {}) {
|
|
147
|
+
const { settings } = readSettings(settingsPath(dir));
|
|
148
|
+
let macos = null;
|
|
149
|
+
try {
|
|
150
|
+
macos = String(execImpl("/usr/bin/sw_vers", ["-productVersion"], { encoding: "utf8", timeout: TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"] })).trim();
|
|
151
|
+
} catch {
|
|
152
|
+
// not known: the field is left out
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
version: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version,
|
|
156
|
+
macos,
|
|
157
|
+
low_disk_on: settings.triggers.lowDisk.on,
|
|
158
|
+
schedule_on: settings.triggers.schedule.on,
|
|
159
|
+
session_start_on: settings.triggers.sessionStart.on,
|
|
160
|
+
low_mark_pct: settings.lowMarkPct,
|
|
161
|
+
critical_mark_pct: settings.criticalMarkPct,
|
|
162
|
+
app_installed: appDirs.some((d) => existsSync(join(d, APP_NAME))),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Send one event now, once; false when off, refused or failed. Never throws. */
|
|
167
|
+
export async function send({ dir = trashPandaDir(), name, props, now = Date.now, fetchImpl = fetch, execImpl, endpoint = ENDPOINT, timeoutMs = TIMEOUT_MS } = {}) {
|
|
168
|
+
try {
|
|
169
|
+
if (!isOn(dir)) return false;
|
|
170
|
+
const properties = clean(name, name === "daily_report" ? dailyFacts({ dir, execImpl }) : props);
|
|
171
|
+
const id = properties && installId(dir);
|
|
172
|
+
if (!id) return false;
|
|
173
|
+
// Turned off while the facts were read: nothing goes, and the id just made is removed.
|
|
174
|
+
if (!isOn(dir)) {
|
|
175
|
+
rmSync(idPath(dir), { force: true });
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const batch = [{ event: name, distinct_id: id, timestamp: new Date(now()).toISOString(), properties: { ...COMMON, ...properties } }];
|
|
179
|
+
const res = await fetchImpl(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ api_key: KEY, batch }), redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
|
|
180
|
+
return res.ok;
|
|
181
|
+
} catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const scriptPath = join(dirname(dirname(fileURLToPath(import.meta.url))), "scripts", "claude-leftovers-cleanup.mjs");
|
|
187
|
+
|
|
188
|
+
/** Start the sender in its own process; false when it could not start. Never throws. */
|
|
189
|
+
function startSender(args, spawnImpl) {
|
|
190
|
+
try {
|
|
191
|
+
const child = spawnImpl(process.execPath, [scriptPath, "_metrics", ...args], { detached: true, stdio: "ignore" });
|
|
192
|
+
child.on("error", () => {});
|
|
193
|
+
child.unref();
|
|
194
|
+
return true;
|
|
195
|
+
} catch {
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The daily report, at most once a day (an attempt that fails counts); true when its sender started. */
|
|
201
|
+
export function maybeSendDaily({ dir = trashPandaDir(), now = Date.now, spawnImpl = spawn } = {}) {
|
|
202
|
+
if (!isOn(dir)) return false;
|
|
203
|
+
try {
|
|
204
|
+
const since = now() - Date.parse(readFileSync(dailyPath(dir), "utf8"));
|
|
205
|
+
if (since >= 0 && since < DAY_MS) return false;
|
|
206
|
+
} catch {
|
|
207
|
+
// none sent yet
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
writeFileSync(dailyPath(dir), new Date(now()).toISOString());
|
|
211
|
+
} catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
return startSender(["daily_report"], spawnImpl);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** After a run: its event, and the daily report when a day has passed. Never waits and never throws. */
|
|
218
|
+
export function afterRun({ dir, last, result, freePctBefore, freePctAfter, now, spawnImpl }) {
|
|
219
|
+
if (!isOn(dir)) return;
|
|
220
|
+
const props = {
|
|
221
|
+
// Another tool's own name never leaves the machine.
|
|
222
|
+
trigger: TRIGGERS.includes(last.by) ? last.by : "tool",
|
|
223
|
+
preview: last.preview,
|
|
224
|
+
bytes_back: last.freedBytes,
|
|
225
|
+
items: last.removed,
|
|
226
|
+
...Object.fromEntries(Object.entries(CLASSES).map(([c, keys]) => [`bytes_${c}`, keys.reduce((n, k) => n + result[k].bytes, 0)])),
|
|
227
|
+
free_pct_before: freePctBefore,
|
|
228
|
+
free_pct_after: freePctAfter,
|
|
229
|
+
duration_sec: Math.round((Date.parse(last.finishedAt) - Date.parse(last.startedAt)) / 1000),
|
|
230
|
+
};
|
|
231
|
+
startSender(["run_finished", JSON.stringify(clean("run_finished", props))], spawnImpl);
|
|
232
|
+
maybeSendDaily({ dir, now, spawnImpl });
|
|
233
|
+
}
|