@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,118 @@
1
+ /**
2
+ * src/tui/watch.mjs — `trash-panda watch`: the live screen.
3
+ *
4
+ * It reads ~/.trash-panda/live.json, history.jsonl, settings.json and
5
+ * in-charge.json again every two seconds and draws the frame that
6
+ * src/tui/format.mjs builds. It measures nothing, writes nothing and starts no
7
+ * cleanup. A file that is missing, broken or the wrong shape is "no data"; a
8
+ * live.json older than three ticks is shown as old. With no terminal it prints
9
+ * one plain frame and ends.
10
+ */
11
+
12
+ import { readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { stripVTControlCharacters } from "node:util";
15
+ import { Box, render, renderToString, Text, useApp, useInput, useWindowSize } from "ink";
16
+ import { createElement as h, useEffect, useState } from "react";
17
+ import { readRecords } from "../records.mjs";
18
+ import { readSettings, settingsPath, trashPandaDir } from "../settings.mjs";
19
+ import { inChargeFresh, readInCharge } from "../triggers.mjs";
20
+ import { buildFrame, DEMOS, demoView } from "./format.mjs";
21
+
22
+ const USAGE = `Usage: trash-panda watch [--demo ${Object.keys(DEMOS).join("|")}]`;
23
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
24
+ const readText = (path) => {
25
+ try {
26
+ return readFileSync(path, "utf8");
27
+ } catch {
28
+ return "";
29
+ }
30
+ };
31
+ const parse = (text) => {
32
+ try {
33
+ return JSON.parse(text);
34
+ } catch {
35
+ return null;
36
+ }
37
+ };
38
+
39
+ /** live.json when it is the shape this screen knows, else null. */
40
+ function readLive(dir) {
41
+ const live = parse(readText(join(dir, "live.json")));
42
+ return isObject(live) && live.format === 1 && Number.isFinite(Date.parse(live.at)) && isObject(live.disk) ? live : null;
43
+ }
44
+
45
+ /** Everything the screen shows, read from `dir` at `now`. Reads only. */
46
+ export function readView(dir, { now }) {
47
+ const { settings } = readSettings(settingsPath(dir));
48
+ const live = readLive(dir);
49
+ const sig = readInCharge(dir);
50
+ return {
51
+ live,
52
+ old: live !== null && now - Date.parse(live.at) > 3 * settings.tickSec * 1000,
53
+ settings,
54
+ inCharge: inChargeFresh(sig, { now }) ? sig.tool : null,
55
+ history: readRecords(dir, "history.jsonl", "finishedAt"),
56
+ };
57
+ }
58
+
59
+ const Row = ({ row }) =>
60
+ h(
61
+ Text,
62
+ null,
63
+ row.map((p, i) => h(Text, { key: i, color: p.colour ?? undefined, bold: p.bold }, p.text)),
64
+ );
65
+
66
+ /** The status box with a round border in the colour of the state, then the warning, the history and the hint. */
67
+ function Screen({ frame }) {
68
+ const rows = (list, key) => list.map((row, i) => h(Row, { key: `${key}${i}`, row }));
69
+ return h(
70
+ Box,
71
+ { flexDirection: "column" },
72
+ h(Box, { borderStyle: "round", borderColor: frame.tone, flexDirection: "column", paddingX: 1 }, rows(frame.box, "b")),
73
+ rows([frame.warning, ...frame.history, frame.hint].filter(Boolean), "r"),
74
+ );
75
+ }
76
+
77
+ /** One frame as plain text, for a terminal-less run and for tests. */
78
+ export function frameText(view, { width = 80, height = 24 }) {
79
+ return stripVTControlCharacters(renderToString(h(Screen, { frame: buildFrame(view, { width, height }) }), { columns: width })).trimEnd();
80
+ }
81
+
82
+ /** The live screen: arrow keys scroll the history, q or Escape ends it. */
83
+ function WatchApp({ dir, demo, now, refreshMs }) {
84
+ const { exit } = useApp();
85
+ const { columns, rows } = useWindowSize();
86
+ const load = () => (demo ? demoView(demo, now()) : readView(dir, { now: now() }));
87
+ const [view, setView] = useState(load);
88
+ const [scroll, setScroll] = useState(0);
89
+ useEffect(() => {
90
+ if (demo) return undefined;
91
+ const timer = setInterval(() => setView(load()), refreshMs);
92
+ return () => clearInterval(timer);
93
+ }, []);
94
+ const frame = buildFrame(view, { width: columns, height: rows, scroll, keys: true });
95
+ useInput((input, key) => {
96
+ if (key.downArrow) setScroll(Math.min(frame.scroll + 1, frame.maxScroll));
97
+ else if (key.upArrow) setScroll(Math.max(frame.scroll - 1, 0));
98
+ else if (input === "q" || key.escape) exit();
99
+ });
100
+ return h(Screen, { frame });
101
+ }
102
+
103
+ /** `trash-panda watch [--demo <state>]`; returns the exit code. */
104
+ export async function watch(args, { dir = trashPandaDir(), stdout = process.stdout, stdin = process.stdin, err = (l) => process.stderr.write(`${l}\n`), now = Date.now, refreshMs = 2000 } = {}) {
105
+ const demo = args.length === 2 && args[0] === "--demo" ? args[1] : null;
106
+ if (args.length !== (demo === null ? 0 : 2) || (demo !== null && !Object.hasOwn(DEMOS, demo))) {
107
+ err(USAGE);
108
+ return 1;
109
+ }
110
+ if (!stdout.isTTY) {
111
+ const view = demo ? demoView(demo, now()) : readView(dir, { now: now() });
112
+ stdout.write(`${frameText(view, { width: stdout.columns ?? 80, height: stdout.rows ?? 24 })}\n`);
113
+ return 0;
114
+ }
115
+ const app = render(h(WatchApp, { dir, demo, now, refreshMs }), { stdout, stdin, interactive: true, patchConsole: false });
116
+ await app.waitUntilExit();
117
+ return 0;
118
+ }
package/src/update.mjs ADDED
@@ -0,0 +1,281 @@
1
+ /**
2
+ * src/update.mjs — the update notice, `trash-panda update`, and the opt-in
3
+ * automatic update.
4
+ *
5
+ * The notice comes from update-notifier: at most one background check a day,
6
+ * never waited for, shown last and only in a terminal. `update` installs the
7
+ * new version beside the old one, checks it (its version, how it reads the
8
+ * settings, one report-only run) before it takes the run lock, then swaps the
9
+ * two folders under the run lock and runs the new version's `setup` with the
10
+ * saved Node. Any failure puts the old folder, job and hook back.
11
+ *
12
+ * A copy inside another package's node_modules never checks or updates: that
13
+ * package does. A copy npm did not install says how to update by hand.
14
+ *
15
+ * `<dir>/update.json` holds the last check and the last update; the update
16
+ * never writes settings.json.
17
+ *
18
+ * Network: the notice check (update-notifier), `npm view` and
19
+ * `npm install --global` reach one host, the npm registry registry.npmjs.org
20
+ * (or the registry the person's npm config names).
21
+ */
22
+
23
+ import { execFile, spawn } from "node:child_process";
24
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
25
+ import { basename, dirname, isAbsolute, join } from "node:path";
26
+ import { fileURLToPath } from "node:url";
27
+ import { readSettings, settingsPath, trashPandaDir } from "./settings.mjs";
28
+ import { acquireRunLock, lockHolder, releaseRunLock } from "./triggers.mjs";
29
+
30
+ export const DAY_MS = 24 * 60 * 60 * 1000;
31
+ const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
32
+ const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;
33
+ // Commands that a person does not run in a terminal, or whose output a script reads.
34
+ const QUIET = new Set(["tick", "session-start", "--session-start", "watch", "_cleanup", "_check", "_metrics", "update", "--version"]);
35
+ const BUSY = new Error("busy");
36
+ const RECORD = { checkedAt: null, current: null, latest: null, lastResult: "none", lastAt: null, lastFrom: null, lastTo: null, lastError: null, autoAt: null };
37
+
38
+ const firstLine = (text) => String(text ?? "").trim().split("\n")[0];
39
+ export const readPackage = (root = packageRoot) => JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
40
+ const scriptOf = (root) => join(root, readPackage(root).bin["trash-panda"]);
41
+
42
+ /** True when version `a` is newer than `b` (major, minor, patch). */
43
+ export function isNewer(a, b) {
44
+ const [x, y] = [a, b].map((v) => v.split(/[-+]/)[0].split(".").map(Number));
45
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] > y[i];
46
+ return false;
47
+ }
48
+
49
+ /**
50
+ * How this copy was installed: "global" by npm, "nested" inside another
51
+ * package's node_modules, "manual" otherwise. A global prefix's node_modules
52
+ * has no package.json beside it; a package's node_modules has one.
53
+ */
54
+ export function installKind(root = packageRoot) {
55
+ let parent = dirname(root);
56
+ if (basename(parent).startsWith("@")) parent = dirname(parent); // a scoped package sits one folder deeper
57
+ if (basename(parent) !== "node_modules") return "manual";
58
+ return existsSync(join(dirname(parent), "package.json")) ? "nested" : "global";
59
+ }
60
+
61
+ /** npm run by the given Node when npm sits beside it, so a job with a bare PATH finds it. */
62
+ export function npmCommand(nodePath) {
63
+ const cli = join(dirname(dirname(nodePath)), "lib", "node_modules", "npm", "bin", "npm-cli.js");
64
+ return existsSync(cli) ? [nodePath, cli] : ["npm"];
65
+ }
66
+
67
+ /** Run a program; never throws. `{ code, stdout, stderr }`. */
68
+ export function execRun(cmd, args) {
69
+ const env = { ...process.env, NO_UPDATE_NOTIFIER: "1", PATH: `${dirname(process.execPath)}:${process.env.PATH ?? ""}` };
70
+ return new Promise((resolve) => {
71
+ execFile(cmd, args, { env, maxBuffer: 64 * 1024 * 1024 }, (e, stdout, stderr) => {
72
+ resolve({ code: e ? (Number.isInteger(e.code) ? e.code : 1) : 0, stdout: String(stdout), stderr: String(stderr) });
73
+ });
74
+ });
75
+ }
76
+
77
+ // ── update.json ─────────────────────────────────────────────────────────────
78
+
79
+ const updateJsonPath = (dir) => join(dir, "update.json");
80
+
81
+ /** The saved record, every key present; missing or broken is the empty record. */
82
+ export function readUpdateJson(dir = trashPandaDir()) {
83
+ const out = { ...RECORD };
84
+ try {
85
+ const saved = JSON.parse(readFileSync(updateJsonPath(dir), "utf8"));
86
+ for (const k of Object.keys(RECORD)) if (Object.hasOwn(saved, k)) out[k] = saved[k];
87
+ } catch {
88
+ // none yet, or not an object: the empty record
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** Merge `patch` into update.json, written whole in one rename; returns the new record. */
94
+ export function writeUpdateJson(dir, patch) {
95
+ const next = { ...readUpdateJson(dir), ...patch };
96
+ mkdirSync(dir, { recursive: true });
97
+ const tmp = `${updateJsonPath(dir)}.tmp-${process.pid}`;
98
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`);
99
+ renameSync(tmp, updateJsonPath(dir));
100
+ return next;
101
+ }
102
+
103
+ // ── the notice ──────────────────────────────────────────────────────────────
104
+
105
+ /** A notice only in a terminal, for an npm install, after a command a person runs, and not when switched off. */
106
+ export function noticeAllowed({ argv, env, isTTY, kind }) {
107
+ return Boolean(isTTY) && kind === "global" && !QUIET.has(argv[0]) && !argv.includes("--json") && !("NO_UPDATE_NOTIFIER" in env) && !("CI" in env);
108
+ }
109
+
110
+ /** The notice's lines; no braces, since the notifier fills `{name}` fields. */
111
+ export function noticeText({ current, latest, record }) {
112
+ const lines = [`A new trash-panda is out: ${current} → ${latest}`, "Run trash-panda update to install it."];
113
+ if (record.lastResult === "failed") lines.push(`The last update to ${record.lastTo} failed: ${record.lastError}`);
114
+ return lines.join("\n").replace(/[{}]/g, "");
115
+ }
116
+
117
+ export const loadNotifier = async (options) => (await import("update-notifier")).default(options);
118
+
119
+ /**
120
+ * Print the bordered notice when the last background check found a newer
121
+ * version; start at most one new check a day, never waited for. Returns the
122
+ * text shown, or null. Any failure prints nothing.
123
+ */
124
+ export async function showNotice({ argv = [], root = packageRoot, dir = trashPandaDir(), env = process.env, isTTY = process.stdout.isTTY, notifierImpl = loadNotifier, now = Date.now } = {}) {
125
+ try {
126
+ if (!noticeAllowed({ argv, env, isTTY, kind: installKind(root) })) return null;
127
+ const { name, version } = readPackage(root);
128
+ const notifier = await notifierImpl({ pkg: { name, version }, updateCheckInterval: DAY_MS });
129
+ const found = notifier.update;
130
+ if (!found || !isNewer(found.latest, version)) return null;
131
+ const record = writeUpdateJson(dir, { checkedAt: new Date(now()).toISOString(), current: version, latest: found.latest });
132
+ const message = noticeText({ current: version, latest: found.latest, record });
133
+ notifier.notify({ defer: false, isGlobal: true, message });
134
+ return message;
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+
140
+ // ── the update ──────────────────────────────────────────────────────────────
141
+
142
+ /** The Node that setup saved for the job and the hook, or null. */
143
+ function savedNode(dir) {
144
+ try {
145
+ const node = JSON.parse(readFileSync(join(dir, "setup.json"), "utf8")).command[0];
146
+ return typeof node === "string" && isAbsolute(node) ? node : null;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * `trash-panda update`. Exit codes: 0 updated or already the newest, 1 failed
154
+ * or not possible for this copy, 3 a cleanup or another update is running
155
+ * (nothing changed). `auto` marks the automatic run, which tries again at the
156
+ * next tick when a cleanup was running.
157
+ */
158
+ export async function update({ dir = trashPandaDir(), root = packageRoot, auto = false, exec = execRun, alive, now = Date.now, log = console.log, err = console.error } = {}) {
159
+ const kind = installKind(root);
160
+ if (kind === "nested") {
161
+ err("This copy of trash-panda belongs to another package; update that package.");
162
+ return 1;
163
+ }
164
+ if (kind === "manual") {
165
+ err(`This copy of trash-panda was not installed by npm. To update it by hand, run: npm install --global ${readPackage(root).name}@latest`);
166
+ return 1;
167
+ }
168
+ const updateLock = join(dir, "update");
169
+ if (!acquireRunLock(updateLock, { alive })) {
170
+ err("An update is already running.");
171
+ return 3;
172
+ }
173
+ try {
174
+ return await updateLocked({ dir, root, auto, exec, alive, now, log, err });
175
+ } finally {
176
+ releaseRunLock(updateLock);
177
+ }
178
+ }
179
+
180
+ async function updateLocked({ dir, root, auto, exec, alive, now, log, err }) {
181
+ const stamp = () => new Date(now()).toISOString();
182
+ const busy = () => {
183
+ err("A cleanup is running; nothing was changed.");
184
+ if (auto) writeUpdateJson(dir, { autoAt: null });
185
+ return 3;
186
+ };
187
+ if (lockHolder(dir, { alive })) return busy();
188
+ const { name, version: current } = readPackage(root);
189
+ const nodePath = savedNode(dir) ?? process.execPath;
190
+ const [npm, ...npmArgs] = npmCommand(nodePath);
191
+ const view = await exec(npm, [...npmArgs, "view", `${name}@latest`, "version"]);
192
+ const latest = view.stdout.trim();
193
+ if (view.code !== 0 || !VERSION_RE.test(latest)) {
194
+ writeUpdateJson(dir, { checkedAt: stamp(), current });
195
+ err(`Could not read the newest version: ${firstLine(view.stderr) || "no answer"}`);
196
+ return 1;
197
+ }
198
+ writeUpdateJson(dir, { checkedAt: stamp(), current, latest });
199
+ if (!isNewer(latest, current)) {
200
+ log(`trash-panda ${current} is the newest version.`);
201
+ return 0;
202
+ }
203
+
204
+ const staging = mkdtempSync(join(dirname(root), `.${basename(root)}-update-`));
205
+ const old = join(staging, "old");
206
+ const step = (r, what) => {
207
+ if (r.code !== 0) throw new Error(`${what}: ${firstLine(r.stderr) || `exit ${r.code}`}`);
208
+ return r;
209
+ };
210
+ let locked = false;
211
+ let moved = false; // the installed copy sits in staging
212
+ let swapped = false;
213
+ let setupRan = false;
214
+ let keepStaging = false; // staging holds the only installed copy
215
+ try {
216
+ step(await exec(npm, [...npmArgs, "install", "--global", "--prefix", staging, "--no-audit", "--no-fund", `${name}@${latest}`]), "install");
217
+ const fresh = join(staging, "lib", "node_modules", name);
218
+ const freshScript = scriptOf(fresh);
219
+ const check = JSON.parse(step(await exec(nodePath, [freshScript, "_check"]), "check").stdout);
220
+ if (check.version !== latest) throw new Error(`the new copy says it is ${check.version}`);
221
+ const known = new Set(readSettings(settingsPath(dir)).problems);
222
+ const added = check.problems.filter((p) => !known.has(p));
223
+ if (added.length) throw new Error(`the new version reads the settings differently: ${added.join("; ")}`);
224
+ // The report only: it removes nothing whatever the settings say, and takes no lock.
225
+ step(await exec(nodePath, [freshScript]), "preview run");
226
+ if (!acquireRunLock(dir, { alive })) throw BUSY;
227
+ locked = true;
228
+ renameSync(root, old);
229
+ moved = true;
230
+ renameSync(fresh, root);
231
+ swapped = true;
232
+ if (check.setup && existsSync(join(dir, "setup.json"))) {
233
+ setupRan = true;
234
+ step(await exec(nodePath, [scriptOf(root), "setup"]), "setup");
235
+ }
236
+ writeUpdateJson(dir, { lastResult: "ok", lastAt: stamp(), lastFrom: current, lastTo: latest, lastError: null });
237
+ log(`trash-panda updated: ${current} → ${latest}.`);
238
+ return 0;
239
+ } catch (e) {
240
+ if (e === BUSY) return busy();
241
+ const problems = [e.message];
242
+ if (moved) {
243
+ try {
244
+ if (swapped) renameSync(root, join(staging, "failed"));
245
+ renameSync(old, root);
246
+ } catch (back) {
247
+ keepStaging = true;
248
+ problems.push(`putting the old copy back: ${firstLine(back.message)}`);
249
+ }
250
+ if (setupRan && !keepStaging) {
251
+ const back = await exec(nodePath, [scriptOf(root), "setup"]);
252
+ if (back.code !== 0) problems.push(`putting the old job and hook back: ${firstLine(back.stderr) || `exit ${back.code}`}`);
253
+ }
254
+ }
255
+ writeUpdateJson(dir, { lastResult: "failed", lastAt: stamp(), lastFrom: current, lastTo: latest, lastError: problems.join("; ") });
256
+ const where = keepStaging ? `trash-panda ${current} is kept in ${old}; move it back to ${root}` : `trash-panda ${current} is still in place`;
257
+ err(`The update to ${latest} failed: ${problems.join("; ")}. ${where}.`);
258
+ return 1;
259
+ } finally {
260
+ if (locked) releaseRunLock(dir);
261
+ if (!keepStaging) rmSync(staging, { recursive: true, force: true });
262
+ }
263
+ }
264
+
265
+ // ── the automatic update ────────────────────────────────────────────────────
266
+
267
+ /**
268
+ * From the tick: start `update --auto` in its own process when `autoUpdate` is
269
+ * on, no cleanup runs, and no automatic attempt started in the last day (a
270
+ * failed one counts). True when it started one.
271
+ */
272
+ export function maybeAutoUpdate({ dir = trashPandaDir(), root = packageRoot, now = Date.now, spawnImpl = spawn, alive, scriptPath, nodePath = process.execPath } = {}) {
273
+ if (installKind(root) !== "global") return false;
274
+ if (!readSettings(settingsPath(dir)).settings.autoUpdate) return false;
275
+ if (lockHolder(dir, { alive })) return false;
276
+ const last = Date.parse(readUpdateJson(dir).autoAt);
277
+ if (now() - last < DAY_MS) return false;
278
+ writeUpdateJson(dir, { autoAt: new Date(now()).toISOString() });
279
+ spawnImpl(nodePath, [scriptPath, "update", "--auto"], { detached: true, stdio: "ignore" }).unref();
280
+ return true;
281
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * src/worktree-git.mjs — the git and gh reads the worktree deleter uses:
3
+ * porcelain parsing, clean check, merged-PR lookup, commits beyond the merged
4
+ * head. Node built-ins only, so a script run from a session copy with no
5
+ * installed packages (the session-start leftovers cleanup) can import it.
6
+ */
7
+
8
+ import { execFile } from "node:child_process";
9
+ import { promisify } from "node:util";
10
+
11
+ const execFileP = promisify(execFile);
12
+
13
+ /**
14
+ * The row with the newest usable `mergedAt`, or null when no row has one. A
15
+ * list of pull requests comes newest-created first, which is not newest-merged.
16
+ */
17
+ function pickNewestMerged(rows) {
18
+ let best = null;
19
+ let bestMs = Number.NEGATIVE_INFINITY;
20
+ for (const row of rows) {
21
+ const ms = Date.parse(row?.mergedAt);
22
+ if (Number.isFinite(ms) && ms > bestMs) {
23
+ best = row;
24
+ bestMs = ms;
25
+ }
26
+ }
27
+ return best;
28
+ }
29
+
30
+ /**
31
+ * Parse `git worktree list --porcelain` into records. Pure — no I/O — so the
32
+ * shape can be pinned against real git output without a subprocess.
33
+ * @param {string} text
34
+ * @returns {Array<{path:string, headSha:string|null, branch:string|null, detached:boolean, prunable:boolean, locked:boolean}>}
35
+ */
36
+ export function parseWorktreePorcelain(text) {
37
+ const records = [];
38
+ let cur = null;
39
+ for (const rawLine of String(text ?? "").split("\n")) {
40
+ const line = rawLine.trimEnd();
41
+ if (line.startsWith("worktree ")) {
42
+ if (cur) records.push(cur);
43
+ cur = { path: line.slice("worktree ".length), headSha: null, branch: null, detached: false, prunable: false, locked: false };
44
+ } else if (!cur) {
45
+ // Preamble before the first `worktree ` line — nothing to attach it to.
46
+ } else if (line.startsWith("HEAD ")) {
47
+ cur.headSha = line.slice("HEAD ".length);
48
+ } else if (line.startsWith("branch ")) {
49
+ cur.branch = line.slice("branch refs/heads/".length);
50
+ } else if (line === "detached") {
51
+ cur.detached = true;
52
+ } else if (line.startsWith("prunable")) {
53
+ cur.prunable = true;
54
+ } else if (line === "locked" || line.startsWith("locked ")) {
55
+ cur.locked = true;
56
+ }
57
+ }
58
+ if (cur) records.push(cur);
59
+ return records;
60
+ }
61
+
62
+ /** `true`/`false`/`null` (could not determine — treated as dirty upstream). */
63
+ export async function worktreeIsClean(path, { execImpl = execFileP } = {}) {
64
+ try {
65
+ const { stdout } = await execImpl("git", ["-C", path, "status", "--porcelain"]);
66
+ return String(stdout ?? "").trim().length === 0;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Merge status via `gh pr list --head <branch> --state merged`, plus the
74
+ * merged head SHA the unpushed-commit check measures from. `null` means "could not determine" (a `gh`
75
+ * transport/auth failure) — every caller treats that identically to
76
+ * "not merged": fail safe, never destructive. `count` is how many merged rows
77
+ * the reply held.
78
+ * @returns {Promise<{merged:boolean, count:number, prNumber?:number, mergedAt?:string, headRefOid?:string}|null>}
79
+ */
80
+ export async function mergedPrInfo(branch, { execGh = execFileP } = {}) {
81
+ let stdout;
82
+ try {
83
+ ({ stdout } = await execGh("gh", [
84
+ "pr",
85
+ "list",
86
+ "--head",
87
+ branch,
88
+ "--state",
89
+ "merged",
90
+ "--json",
91
+ "number,mergedAt,headRefOid",
92
+ ]));
93
+ } catch {
94
+ return null;
95
+ }
96
+ let parsed;
97
+ try {
98
+ parsed = JSON.parse(stdout);
99
+ } catch {
100
+ return null;
101
+ }
102
+ if (!Array.isArray(parsed)) return null;
103
+ if (parsed.length === 0) return { merged: false, count: 0 };
104
+ // Newest-MERGED, not parsed[0] (newest-CREATED) — see pickNewestMerged
105
+ // above. A row with no usable mergedAt is skipped by
106
+ // the selector rather than won by default, so `best` can be null here even
107
+ // though PRs exist; the caller's `mergedPr?.mergedAt` check already falls
108
+ // back to the branch's last commit date in that case.
109
+ const best = pickNewestMerged(parsed) || {};
110
+ return { merged: true, count: parsed.length, prNumber: best.number, mergedAt: best.mergedAt, headRefOid: best.headRefOid };
111
+ }
112
+
113
+ /**
114
+ * How many open pull requests have `branch` as their head, or `null` when gh
115
+ * could not say (every caller keeps the worktree then).
116
+ * @returns {Promise<number|null>}
117
+ */
118
+ export async function openPrCount(branch, { execGh = execFileP } = {}) {
119
+ try {
120
+ const { stdout } = await execGh("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number"]);
121
+ const parsed = JSON.parse(stdout);
122
+ return Array.isArray(parsed) ? parsed.length : null;
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * How many commits `branch` holds beyond the head its merged PR carried —
130
+ * work made after the merge, or never pushed, that `git branch -D` would
131
+ * destroy. `null` when it cannot be proven (no PR head SHA, the SHA is not
132
+ * in the local object store, any git failure); every caller reads `null` as
133
+ * "has unpushed work".
134
+ * @returns {Promise<number|null>}
135
+ */
136
+ export async function commitsBeyondMergedHead(branch, headRefOid, { execImpl = execFileP, repoRoot } = {}) {
137
+ if (typeof headRefOid !== "string" || !/^[0-9a-f]{7,64}$/i.test(headRefOid)) return null;
138
+ try {
139
+ const { stdout } = await execImpl("git", ["-C", repoRoot, "rev-list", "--count", `${headRefOid}..${branch}`]);
140
+ const n = Number.parseInt(String(stdout ?? "").trim(), 10);
141
+ return Number.isInteger(n) && n >= 0 ? n : null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * src/worktree-liveness.mjs — "is any live process standing inside this
3
+ * worktree?", asked the one way that sees every session, harness, and shell.
4
+ *
5
+ * WHY THIS EXISTS. A worktree lock is a signal a session has to remember to
6
+ * set; a Claude app session never sets one, and a merged-branch prune has
7
+ * deleted a live session's worktree that way. The kernel already knows which
8
+ * processes have their working directory inside a folder; asking it needs no
9
+ * cooperation from the session. Every deleter checks this before the delete.
10
+ *
11
+ * FAIL CLOSED. `lsof` failing, timing out, or exiting non-zero returns
12
+ * `null` ("could not verify"), and every caller treats `null` exactly like
13
+ * "in use" — an instrument failure is never permission to delete.
14
+ */
15
+
16
+ import { execFile, execFileSync } from "node:child_process";
17
+ import { realpathSync } from "node:fs";
18
+ import { promisify } from "node:util";
19
+
20
+ const execFileP = promisify(execFile);
21
+
22
+ // Every process's current working directory, in lsof's machine-readable
23
+ // field form (`p<pid>` / `fcwd` / `n<path>` records). -n/-P skip DNS and port
24
+ // lookups, -w drops warnings; a clean run exits 0 in ~0.2s.
25
+ export const LSOF_ARGS = ["-n", "-P", "-w", "-d", "cwd", "-F", "pn"];
26
+ // Absolute, because scheduled jobs run with a PATH that has no /usr/sbin: by
27
+ // bare name the lookup failed there and every pass read "could not verify".
28
+ export const LSOF_BIN = "/usr/sbin/lsof";
29
+ const LSOF_OPTS = { maxBuffer: 64 * 1024 * 1024, timeout: 30_000 };
30
+
31
+ // In the C locale of a scheduled job lsof writes a byte it cannot print as \xHH.
32
+ const unescapeBytes = (path) => path.replace(/(?:\\x[0-9a-f]{2})+/gi, (run) => Buffer.from(run.replace(/\\x/gi, ""), "hex").toString("utf8"));
33
+
34
+ /**
35
+ * Pure: the cwd paths in lsof `-F pn` output. An escaped path is listed both as
36
+ * printed and as read back, since a real name can hold the same characters.
37
+ */
38
+ export function parseLsofCwds(stdout) {
39
+ return String(stdout ?? "")
40
+ .split("\n")
41
+ .filter((l) => l.startsWith("n") && l.length > 1)
42
+ .flatMap((l) => {
43
+ const printed = l.slice(1);
44
+ const read = unescapeBytes(printed);
45
+ return read === printed ? [printed] : [printed, read];
46
+ });
47
+ }
48
+
49
+ /** Every live process's cwd, or `null` when lsof could not be run cleanly. */
50
+ export async function liveCwds({ execImpl = execFileP } = {}) {
51
+ try {
52
+ const { stdout } = await execImpl(LSOF_BIN, LSOF_ARGS, LSOF_OPTS);
53
+ return parseLsofCwds(stdout);
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ /** Synchronous twin of liveCwds, for synchronous callers. */
60
+ export function liveCwdsSync({ execFileSyncImpl = execFileSync } = {}) {
61
+ try {
62
+ return parseLsofCwds(execFileSyncImpl(LSOF_BIN, LSOF_ARGS, { ...LSOF_OPTS, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }));
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Pure: `true` when any cwd is `dir` or inside it, `false` when none is,
70
+ * `null` when the cwd list itself is unknown. Compares against both the path
71
+ * as given and its resolved form, since lsof reports resolved paths.
72
+ */
73
+ export function dirHasLiveCwd(cwds, dir, { realpathImpl = realpathSync } = {}) {
74
+ if (!Array.isArray(cwds)) return null;
75
+ const roots = new Set([dir.replace(/\/+$/, "")]);
76
+ try {
77
+ roots.add(realpathImpl(dir).replace(/\/+$/, ""));
78
+ } catch {
79
+ // the folder is gone or unreadable — the literal path is still checked
80
+ }
81
+ for (const cwd of cwds) {
82
+ for (const root of roots) {
83
+ if (cwd === root || cwd.startsWith(`${root}/`)) return true;
84
+ }
85
+ }
86
+ return false;
87
+ }