@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.
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/claude-leftovers-cleanup.mjs — the command line for the cleanup of
4
+ * what Claude sessions leave on disk. The rules live in
5
+ * src/claude-leftovers.mjs and the start logic in src/triggers.mjs; this file
6
+ * only reads the command.
7
+ *
8
+ * node scripts/claude-leftovers-cleanup.mjs report only
9
+ * node scripts/claude-leftovers-cleanup.mjs run start one cleanup now, by hand
10
+ * node scripts/claude-leftovers-cleanup.mjs run --only <chrome|worktrees|scratch>
11
+ * node scripts/claude-leftovers-cleanup.mjs run --by <tool> name who asked (saved in the history)
12
+ * node scripts/claude-leftovers-cleanup.mjs run --limit <n> remove at most n test folders in this run
13
+ * node scripts/claude-leftovers-cleanup.mjs tick look once; start a cleanup if a trigger says so
14
+ * node scripts/claude-leftovers-cleanup.mjs session-start the SessionStart hook
15
+ * node scripts/claude-leftovers-cleanup.mjs setup install the scheduled tick and the hook
16
+ * node scripts/claude-leftovers-cleanup.mjs remove take both out again
17
+ * node scripts/claude-leftovers-cleanup.mjs config metrics [on|off] anonymous metrics (src/metrics.mjs)
18
+ * node scripts/claude-leftovers-cleanup.mjs config <key> [value] show or set one setting (src/settings.mjs)
19
+ * node scripts/claude-leftovers-cleanup.mjs app on|off add or remove only the Mac app's login item (src/setup.mjs)
20
+ * node scripts/claude-leftovers-cleanup.mjs watch the live screen (src/tui/watch.mjs); reads only
21
+ * node scripts/claude-leftovers-cleanup.mjs watch --demo <idle|running|critical|in-charge|preview|empty>
22
+ * node scripts/claude-leftovers-cleanup.mjs stats [--since 7d] [--json] what the records add up to (src/records.mjs)
23
+ * node scripts/claude-leftovers-cleanup.mjs diagnose [--json] errors, checks with no answer, the job and the hook
24
+ * node scripts/claude-leftovers-cleanup.mjs update install the newest version (src/update.mjs)
25
+ * node scripts/claude-leftovers-cleanup.mjs --version print this version
26
+ *
27
+ * After a command a person runs in a terminal, a notice names a newer version
28
+ * when there is one. `update` exits 0 when done or already the newest, 1 when
29
+ * it failed, and 3 when a cleanup or another update runs. `_check` is the
30
+ * internal command an update runs on the new copy before it swaps.
31
+ *
32
+ * Preview is on by default: every start, --apply included, only reports what
33
+ * it would remove until ~/.trash-panda/settings.json holds `"preview": false`
34
+ * (src/settings.mjs). Only the person sets it.
35
+ *
36
+ * `run` exits 0 when a cleanup started, 3 when one is already running, 4 when
37
+ * an automatic trigger waits for the tool in charge, 1 when it could not start,
38
+ * and 2 for a bad --limit. `--apply` and `--session-start` are the old spellings
39
+ * of `run` and `session-start`. `tick` and `session-start` always exit 0: a
40
+ * cleanup never delays or fails a session. The internal `_metrics` command
41
+ * sends one opt-in event in its own process. The internal `_cleanup` command is
42
+ * the child that `run` starts in its own process session, so it outlives
43
+ * whoever started it.
44
+ */
45
+
46
+ import { homedir } from "node:os";
47
+ import { fileURLToPath } from "node:url";
48
+ import { askMetrics, maybeSendDaily, metricsStatus, send, setMetrics, shouldAsk } from "../src/metrics.mjs";
49
+ import { buildDiagnosis, buildStats, diagnosisLines, parseSince, readHookInput, recordError, sessionName, statsLines } from "../src/records.mjs";
50
+ import { getSetting, readSettings, setSetting, settingsPath, trashPandaDir } from "../src/settings.mjs";
51
+ import { SESSION_ENV, defaultScriptPath, reportOnly, runOnce, sessionStart, startRun, tick } from "../src/triggers.mjs";
52
+ import { maybeAutoUpdate, readPackage, showNotice, update } from "../src/update.mjs";
53
+
54
+ export { acquireRunLock, isDue, nextState, readState, releaseRunLock, runOnce, sessionStart } from "../src/triggers.mjs";
55
+
56
+ const USAGE = "Usage: claude-leftovers-cleanup.mjs [run [--only chrome|worktrees|scratch] [--by tool] [--limit n] | tick | session-start | setup | remove | config metrics [on|off] | config <key> [value] | app on|off | watch [--demo state] | stats [--since 7d] [--json] | diagnose [--json] | update | --version]";
57
+ const STOPPED = { 1: "Could not start a cleanup.", 3: "A cleanup is already running.", 4: "Another tool is in charge; not starting." };
58
+ const OLD_SPELLINGS = { "--apply": "run", "--session-start": "session-start" };
59
+ const BAD_LIMIT = "bad limit";
60
+
61
+ /**
62
+ * `{ by, only, limit }` from `--by <x>`, `--only <x>` and `--limit <n>` pairs;
63
+ * null when anything else is there, BAD_LIMIT when the limit is not a positive whole number.
64
+ */
65
+ function parseOptions(args) {
66
+ const out = { by: null, only: null, limit: null };
67
+ for (let i = 0; i < args.length; i += 2) {
68
+ const key = { "--by": "by", "--only": "only", "--limit": "limit" }[args[i]];
69
+ if (key === "limit") {
70
+ if (!/^[1-9]\d*$/.test(args[i + 1] ?? "")) return BAD_LIMIT;
71
+ out.limit = Number(args[i + 1]);
72
+ continue;
73
+ }
74
+ if (!key || args[i + 1] === undefined) return null;
75
+ out[key] = args[i + 1];
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /** The cleanup child must say nothing after its first line: its starter may be gone. */
81
+ function goQuiet() {
82
+ process.on("SIGHUP", () => {});
83
+ process.stdout.on("error", () => {});
84
+ }
85
+
86
+ /** Save the metrics choice and say it; returns the exit code. */
87
+ function saveMetrics(on, d) {
88
+ try {
89
+ setMetrics(d.dir, on);
90
+ } catch (e) {
91
+ d.err(e.message);
92
+ return 1;
93
+ }
94
+ d.log(metricsStatus(d.dir));
95
+ return 0;
96
+ }
97
+
98
+ /** Run the command in `argv`, then the update notice; returns the exit code. `deps` replaces any piece, for tests. */
99
+ export async function main(argv, deps = {}) {
100
+ const d = { log: (l) => process.stdout.write(`${l}\n`), err: (l) => process.stderr.write(`${l}\n`), out: (l) => process.stdout.write(`${l}\n`), stdin: process.stdin, stdout: process.stdout, scriptPath: defaultScriptPath, dir: trashPandaDir(), startRun, tick, sessionStart, runOnce, reportOnly, update, autoUpdate: maybeAutoUpdate, notice: showNotice, readHookInput, askMetrics, dailyMetrics: maybeSendDaily, sendMetrics: send, ...deps };
101
+ const code = await runCommand(argv, d);
102
+ await d.notice({ argv, dir: d.dir });
103
+ return code;
104
+ }
105
+
106
+ async function runCommand(argv, d) {
107
+ if (argv.length === 1 && argv[0] === "--version") {
108
+ d.log(readPackage().version);
109
+ return 0;
110
+ }
111
+ let [command, ...rest] = argv;
112
+ // Options with no command first (`--limit 3`) are the report's options.
113
+ if (command?.startsWith("--") && !OLD_SPELLINGS[command]) {
114
+ rest = argv;
115
+ command = undefined;
116
+ }
117
+ command = OLD_SPELLINGS[command] ?? command;
118
+ const usage = () => {
119
+ d.err(USAGE);
120
+ return 1;
121
+ };
122
+ const options = () => {
123
+ const opts = parseOptions(rest);
124
+ if (opts === BAD_LIMIT) d.err("--limit needs a positive whole number");
125
+ return opts;
126
+ };
127
+ if (command === undefined || command === "run" || command === "_cleanup") {
128
+ const opts = options();
129
+ if (opts === BAD_LIMIT) return 2;
130
+ if (!opts) return usage();
131
+ if (command === undefined) {
132
+ await d.reportOnly({ log: d.log, only: opts.only, limit: opts.limit });
133
+ return 0;
134
+ }
135
+ if (command === "run") {
136
+ const code = await d.startRun({ by: opts.by ?? "hand", only: opts.only, limit: opts.limit, scriptPath: d.scriptPath });
137
+ if (code !== 0) d.err(STOPPED[code]);
138
+ if (code === 1) recordError(d.dir, `run by ${opts.by ?? "hand"}`, STOPPED[1]);
139
+ return code;
140
+ }
141
+ goQuiet();
142
+ // Read once and dropped, so no script the cleanup starts sees the session's name.
143
+ const session = process.env[SESSION_ENV] ?? null;
144
+ delete process.env[SESSION_ENV];
145
+ try {
146
+ await d.runOnce({ by: opts.by ?? "hand", only: opts.only, limit: opts.limit, session, report: d.out });
147
+ return 0;
148
+ } catch (e) {
149
+ recordError(d.dir, `cleanup by ${opts.by ?? "hand"}`, e);
150
+ return 1;
151
+ }
152
+ }
153
+ if (command === "session-start") {
154
+ d.sessionStart({ log: d.log, session: sessionName(await d.readHookInput()), scriptPath: d.scriptPath });
155
+ return 0;
156
+ }
157
+ if (command === "stats" || command === "diagnose") {
158
+ const json = rest.at(-1) === "--json";
159
+ const args = json ? rest.slice(0, -1) : rest;
160
+ let report;
161
+ if (command === "diagnose") {
162
+ if (args.length) return usage();
163
+ report = buildDiagnosis({ dir: d.dir, home: d.home ?? homedir(), uid: process.getuid(), now: Date.now(), launchctl: d.launchctl });
164
+ } else {
165
+ const sinceMs = parseSince(args.length === 0 ? "7d" : args.length === 2 && args[0] === "--since" ? args[1] : "");
166
+ if (sinceMs === null) return usage();
167
+ report = buildStats(d.dir, { sinceMs, now: Date.now() });
168
+ }
169
+ for (const line of json ? [JSON.stringify(report, null, 2)] : command === "stats" ? statsLines(report) : diagnosisLines(report)) d.log(line);
170
+ return 0;
171
+ }
172
+ if (command === "tick" && rest.length === 0) {
173
+ try {
174
+ d.dailyMetrics({ dir: d.dir });
175
+ const ticked = await d.tick({ startOptions: { scriptPath: d.scriptPath } });
176
+ // An automatic update never starts beside a cleanup.
177
+ if (!ticked.by) d.autoUpdate({ dir: d.dir, scriptPath: d.scriptPath });
178
+ if (ticked.code === 1) recordError(d.dir, `tick by ${ticked.by}`, STOPPED[1]);
179
+ } catch (e) {
180
+ // a tick never fails the scheduled job
181
+ recordError(d.dir, "tick", e);
182
+ }
183
+ return 0;
184
+ }
185
+ if (command === "watch") {
186
+ // Loaded here so the other commands never load the screen's packages.
187
+ const { watch } = await import("../src/tui/watch.mjs");
188
+ return watch(rest, { dir: d.dir, stdout: d.stdout, err: d.err });
189
+ }
190
+ if ((command === "setup" || command === "remove") && rest.length === 0) {
191
+ const setup = d[command] ?? (await import("../src/setup.mjs"))[command];
192
+ const result = await setup({ home: homedir(), dir: d.dir, scriptPath: d.scriptPath, uid: process.getuid(), tickSec: readSettings(settingsPath(d.dir)).settings.tickSec });
193
+ for (const problem of result.problems) d.err(problem);
194
+ // Asked once, only in a terminal; an update's setup and a headless one stay off.
195
+ if (command === "setup" && result.ok && d.stdin.isTTY && d.stdout.isTTY && shouldAsk(d.dir)) {
196
+ const answer = await d.askMetrics();
197
+ if (answer !== null) saveMetrics(answer, d);
198
+ }
199
+ return result.ok ? 0 : 1;
200
+ }
201
+ if (command === "config" && rest[0] === "metrics" && rest.length <= 2) {
202
+ if (rest.length === 1) {
203
+ d.log(metricsStatus(d.dir));
204
+ return 0;
205
+ }
206
+ if (rest[1] === "on" || rest[1] === "off") return saveMetrics(rest[1] === "on", d);
207
+ }
208
+ if (command === "app" && rest.length === 1 && (rest[0] === "on" || rest[0] === "off")) {
209
+ const { appLogin } = await import("../src/setup.mjs");
210
+ const result = await appLogin({ on: rest[0] === "on", home: d.home ?? homedir(), launchctl: d.launchctl, appDirs: d.appDirs });
211
+ for (const problem of result.problems) d.err(problem);
212
+ if (result.ok) d.log(rest[0] === "on" ? "The app opens at login." : "The app no longer opens at login. The engine keeps running.");
213
+ return result.ok ? 0 : 1;
214
+ }
215
+ if (command === "config" && rest[0] !== "metrics" && (rest.length === 1 || rest.length === 2)) {
216
+ const [name, text] = rest;
217
+ try {
218
+ d.log(`${name} ${JSON.stringify(text === undefined ? getSetting(d.dir, name) : setSetting(d.dir, name, text))}`);
219
+ return 0;
220
+ } catch (e) {
221
+ d.err(e.message);
222
+ return 1;
223
+ }
224
+ }
225
+ if (command === "_metrics") {
226
+ await d.sendMetrics({ dir: d.dir, name: rest[0], props: JSON.parse(rest[1] ?? "{}") });
227
+ return 0;
228
+ }
229
+ if (command === "update" && (rest.length === 0 || (rest.length === 1 && rest[0] === "--auto"))) {
230
+ return d.update({ dir: d.dir, auto: rest[0] === "--auto", log: d.log, err: d.err });
231
+ }
232
+ if (command === "_check" && rest.length === 0) {
233
+ d.log(JSON.stringify({ version: readPackage().version, problems: readSettings(settingsPath(d.dir)).problems, setup: true }));
234
+ return 0;
235
+ }
236
+ return usage();
237
+ }
238
+
239
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
240
+ // exitCode, not exit(): a long report written to a pipe is never cut short.
241
+ process.exitCode = await main(process.argv.slice(2));
242
+ }