longtable 0.1.35 → 0.1.37

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/src/procs.mjs ADDED
@@ -0,0 +1,152 @@
1
+ // Programs a person's Claude starts and leaves running (a dev server, a test run in the background) live as long as
2
+ // the chat's session that started them, as they do in a Claude Code session at home, and are stopped when that session
3
+ // ends. Only ever what its own Claude started through its command shell, and only programs that serve or run code
4
+ // (node, python and the like): never a browser, an editor or anything else on the person's computer. Each one is known
5
+ // by its process number AND the moment it started, so a number since given to another program is never touched, and
6
+ // each is stopped on its own, never with whatever happens to sit below it by then.
7
+
8
+ import { execFile, spawnSync } from "node:child_process";
9
+ import { mkdirSync, readFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { home, log, writeWhole } from "./store.mjs";
12
+
13
+ const win = process.platform === "win32";
14
+ // The command shells Claude Code's Bash tool runs commands in. What sits below one of these is what Claude ran.
15
+ const SHELLS = /^(bash|sh|zsh|dash|cmd|powershell|pwsh)(\.exe)?$/i;
16
+ // What may be stopped: programs that run or serve code, and the shells that hold them. Nothing else, ever.
17
+ const RUNS_CODE = /^(node|nodejs|deno|bun|python[0-9.]*|py|pythonw|ruby|php|java|dotnet|go|cargo|uvicorn|gunicorn|flask|rails|npm|npx|pnpm|yarn|vite|esbuild|tsx|ts-node|nodemon|bash|sh|zsh|dash|cmd|powershell|pwsh)(\.exe|\.cmd)?$/i;
18
+
19
+ const WIN_LIST = "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToFileTimeUtc()) $($_.Name)\" }";
20
+ // On Mac and Linux each line is: pid ppid pgid, the start (five words, in UTC so a clock change never alters it), name.
21
+ const PS_ARGS = ["-A", "-o", "pid=,ppid=,pgid=,lstart=,comm="];
22
+ const PS_ENV = { ...process.env, TZ: "UTC", LC_ALL: "C" };
23
+
24
+ export function parse(out, onWindows = win) {
25
+ const list = [];
26
+ for (const raw of String(out).split(/\r?\n/)) {
27
+ const l = raw.trim();
28
+ if (!l) continue;
29
+ if (onWindows) {
30
+ const m = l.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
31
+ if (m) list.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: null, start: m[3], ms: Number(m[3]) / 10000 - 11644473600000, name: m[4].trim() });
32
+ } else {
33
+ const m = l.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/);
34
+ if (m) list.push({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]), start: m[4], ms: Date.parse(`${m[4]} UTC`), name: m[5].trim().split("/").pop() });
35
+ }
36
+ }
37
+ return list;
38
+ }
39
+ function listAll() {
40
+ return new Promise((resolve) => {
41
+ const done = (e, out) => resolve(e ? null : parse(out));
42
+ if (win) execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WIN_LIST], { windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: 20000 }, done);
43
+ else execFile("ps", PS_ARGS, { env: PS_ENV, maxBuffer: 16 * 1024 * 1024, timeout: 20000 }, done);
44
+ });
45
+ }
46
+ function listAllNow() {
47
+ const r = win
48
+ ? spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WIN_LIST], { windowsHide: true, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 20000 })
49
+ : spawnSync("ps", PS_ARGS, { env: PS_ENV, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, timeout: 20000 });
50
+ return r.status === 0 && r.stdout ? parse(r.stdout) : null;
51
+ }
52
+
53
+ // What a Claude (process `root`, started at `rootMs`) ran through its shells and left running, found in a listing.
54
+ // A process counts as another's child only if it started after it: on Windows a program whose parent has gone keeps
55
+ // naming that parent's old number, which the system may since have given to a new process. Its own MCP servers and
56
+ // anything they start are not below a shell, so they are left alone. On Mac and Linux, what it started keeps its
57
+ // process group (the connection makes each Claude the leader of its own), so it is found even after its parent has
58
+ // gone and it was handed to the system.
59
+ export function pick(all, root, rootMs, onWindows = win) {
60
+ if (!all) return [];
61
+ const byPid = new Map(all.map((p) => [p.pid, p]));
62
+ const kids = new Map();
63
+ for (const p of all) { if (!kids.has(p.ppid)) kids.set(p.ppid, []); kids.get(p.ppid).push(p); }
64
+ const out = new Map();
65
+ const take = (p) => { if (RUNS_CODE.test(p.name) && p.pid !== process.pid) out.set(`${p.pid}|${p.start}`, { pid: p.pid, start: p.start }); };
66
+ const walk = (p, depth) => {
67
+ if (depth > 30) return;
68
+ for (const k of kids.get(p.pid) || []) {
69
+ if (k.pid === p.pid || !(k.ms >= p.ms - 1000)) continue;
70
+ take(k);
71
+ walk(k, depth + 1);
72
+ }
73
+ };
74
+ const self = byPid.get(root) || { pid: root, ms: rootMs };
75
+ for (const shell of (kids.get(root) || []).filter((k) => SHELLS.test(k.name) && k.ms >= self.ms - 1000)) { take(shell); walk(shell, 1); }
76
+ if (!onWindows) for (const p of all) if (p.pgid === root && p.pid !== root && p.ms >= rootMs - 1000) take(p);
77
+ return [...out.values()];
78
+ }
79
+
80
+ export async function below(root, rootMs) {
81
+ return pick(await listAll(), root, rootMs);
82
+ }
83
+
84
+ // Stop each that is still the same program (same number, same start), on its own. Returns how many were stopped, or
85
+ // null when the system could not be asked, so nothing is forgotten that was not really stopped.
86
+ export function stopProcs(list, all = undefined) {
87
+ if (!list?.length) return 0;
88
+ if (all === undefined) all = listAllNow();
89
+ if (!all) return null;
90
+ const still = new Set(all.map((p) => `${p.pid}|${p.start}`));
91
+ let stopped = 0;
92
+ for (const p of list) {
93
+ if (!still.has(`${p.pid}|${p.start}`) || p.pid === process.pid) continue;
94
+ try {
95
+ if (win) spawnSync("taskkill", ["/PID", String(p.pid), "/F"], { windowsHide: true, stdio: "ignore" });
96
+ else process.kill(p.pid, "SIGTERM");
97
+ stopped++;
98
+ } catch {}
99
+ }
100
+ return stopped;
101
+ }
102
+
103
+ // What each chat's session has running, kept on disk too: a connection that restarts (an update, a crash) stops what
104
+ // the one before it left, rather than leaving it running with nobody to stop it.
105
+ const FILE = () => join(home, "sessions", "running.json");
106
+ const running = new Map();
107
+ const save = () => {
108
+ try { mkdirSync(dirname(FILE()), { recursive: true }); writeWhole(FILE(), JSON.stringify(Object.fromEntries(running))); }
109
+ catch (e) { log(`could not note what is running: ${e.message}`); }
110
+ };
111
+
112
+ export function keepForSession(key, list) {
113
+ if (!list?.length) return;
114
+ const was = running.get(key) || { procs: [], at: 0 };
115
+ const seen = new Set(was.procs.map((p) => `${p.pid}|${p.start}`));
116
+ running.set(key, { procs: [...was.procs, ...list.filter((p) => !seen.has(`${p.pid}|${p.start}`))].slice(-500), at: Date.now() });
117
+ save();
118
+ }
119
+ export function touchSession(key) {
120
+ const was = running.get(key);
121
+ if (was) { was.at = Date.now(); save(); }
122
+ }
123
+ function endKeys(keys, why) {
124
+ const procs = keys.flatMap((k) => running.get(k)?.procs || []);
125
+ if (!procs.length) { for (const k of keys) running.delete(k); if (keys.length) save(); return; }
126
+ const n = stopProcs(procs);
127
+ // The system could not be asked: kept, to be stopped next time, never forgotten while still running.
128
+ if (n === null) { log(`could not list programs to stop (${why}); will try again`); return; }
129
+ for (const k of keys) running.delete(k);
130
+ save();
131
+ if (n) log(`stopped ${n} program(s) a session had left running (${why})`);
132
+ }
133
+ export function endSession(key, why) { if (running.has(key)) endKeys([key], why); }
134
+ // A session nobody has used for this long has ended, as a Claude Code session closed at home would have.
135
+ export const SESSION_IDLE_MS = Number(process.env.LONGTABLE_SESSION_IDLE_MS || 2 * 3600 * 1000);
136
+ export function endIdleSessions(inUse = () => false) {
137
+ // A session with a request running right now is not quiet, however long ago it started its programs.
138
+ const quiet = [...running].filter(([key, v]) => Date.now() - v.at > SESSION_IDLE_MS && !inUse(key)).map(([key]) => key);
139
+ if (quiet.length) endKeys(quiet, "the session went quiet");
140
+ }
141
+ export function endAllSessions(why) { if (running.size) endKeys([...running.keys()], why); }
142
+ // At start: whatever a connection before this one left running is stopped.
143
+ export function stopLeftovers() {
144
+ let left = {};
145
+ try { left = JSON.parse(readFileSync(FILE(), "utf8")); } catch { return; }
146
+ const procs = Object.values(left || {}).flatMap((v) => v?.procs || []);
147
+ if (!procs.length) return;
148
+ const n = stopProcs(procs);
149
+ if (n === null) { log("could not list programs an earlier connection left running; they stay noted"); return; }
150
+ try { writeWhole(FILE(), "{}"); } catch {}
151
+ if (n) log(`stopped ${n} program(s) an earlier connection's sessions had left running`);
152
+ }
package/src/repo.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // The connection's own clean copy of the team's code: the latest main, never the person's work folder.
2
2
 
3
3
  import { execFileSync } from "node:child_process";
4
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
5
5
  import { join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { home, log } from "./store.mjs";
@@ -20,26 +20,108 @@ export function canReach(source) {
20
20
  }
21
21
  }
22
22
 
23
- // Given a folder or a git address, find where to copy from. For a folder: its origin when this computer can reach
24
- // it, else the folder's own history, which is still only committed work. An address that cannot be reached is an
25
- // error, said before anything else happens.
23
+ // Given a folder or a git address, find where to copy from. For a folder: the folder's own history, which is still
24
+ // only committed work. Never whatever the folder happens to call origin: that can be somebody else's repository (a
25
+ // client's), and the team's work must never land there. Where the team shares its code is the table's repository,
26
+ // set once in Longtable. An address that cannot be reached is an error, said before anything else happens.
26
27
  export function resolveSource(repo) {
27
28
  if (!repo) return null;
28
- if (/^(https?:|git@|ssh:)/.test(repo)) {
29
+ if (isAddress(repo)) {
29
30
  if (!canReach(repo)) throw new Error(`This computer's git cannot open ${repo}. Sign in to git for it, or open your AI in the project's own folder and connect from there.`);
30
31
  return repo;
31
32
  }
32
33
  const folder = resolve(repo);
33
34
  if (!existsSync(join(folder, ".git"))) throw new Error(`${folder} is not a git repository`);
34
- try {
35
- const origin = git(["-C", folder, "remote", "get-url", "origin"]);
36
- if (origin && canReach(origin)) return origin;
37
- } catch {
38
- // No origin: fall through to the folder itself.
39
- }
40
35
  return "file:///" + folder.replace(/\\/g, "/");
41
36
  }
42
37
 
38
+ export const isAddress = (s) => /^(https?:|git@|ssh:|file:)/i.test(String(s || ""));
39
+
40
+ // One repository written two ways is still one: https and ssh, with or without .git, any case in the host.
41
+ export function addressKey(a) {
42
+ let s = String(a || "").trim();
43
+ // A repository on this computer, as a file:// address or a plain path (what git writes for a clone of one).
44
+ if (/^file:/i.test(s) || /^([A-Za-z]:[\\/]|\/)/.test(s)) {
45
+ let p = s;
46
+ if (/^file:/i.test(p)) { try { p = fileURLToPath(p); } catch { return null; } }
47
+ // Windows paths are the same in any case; elsewhere a path's case is part of it.
48
+ const key = resolve(p).replace(/\\/g, "/").replace(/\/+$/, "").replace(/\.git$/i, "");
49
+ return "file:" + (process.platform === "win32" ? key.toLowerCase() : key);
50
+ }
51
+ if (!isAddress(s)) return null;
52
+ s = s.replace(/^ssh:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\//i, "$1/").replace(/^git@([^:]+):/i, "$1/").replace(/^https?:\/\/(?:[^@/]+@)?/i, "");
53
+ s = s.replace(/\/+$/, "").replace(/\.git$/i, "");
54
+ const [host, ...rest] = s.split("/");
55
+ return rest.length ? `${host.toLowerCase()}/${rest.join("/").toLowerCase()}` : null;
56
+ }
57
+ export const sameAddress = (a, b) => { const x = addressKey(a); return !!x && x === addressKey(b); };
58
+
59
+ // The remotes a folder's git knows: name, address, and whether it has a push address of its own.
60
+ // Addresses as git itself resolves them, the person's own url.*.insteadOf shortcuts applied (gh:team/app).
61
+ // Read again only when the folder's git config has changed since: every job asks, some twice.
62
+ const remotesSeen = new Map();
63
+ export function remotesOf(folder) {
64
+ let stamp = null;
65
+ try { const st = statSync(join(folder, ".git", "config")); stamp = `${st.mtimeMs}:${st.size}`; } catch {}
66
+ const seen = remotesSeen.get(folder);
67
+ if (stamp && seen?.stamp === stamp) return seen.list;
68
+ const list = readRemotes(folder);
69
+ if (stamp) remotesSeen.set(folder, { stamp, list });
70
+ return list;
71
+ }
72
+ function readRemotes(folder) {
73
+ let names = [];
74
+ try { names = git(["-C", folder, "remote"]).split(/\r?\n/).filter(Boolean); } catch { return []; }
75
+ return names.map((name) => {
76
+ const list = (args) => { try { return git(["-C", folder, "remote", "get-url", ...args, name]).split(/\r?\n/).filter(Boolean); } catch { return []; } };
77
+ let pushurl = false;
78
+ try { pushurl = git(["-C", folder, "config", "--get-all", `remote.${name}.pushurl`]) !== ""; } catch {}
79
+ return { name, urls: [...new Set([...list(["--all"]), ...list(["--push", "--all"])])], pushurl };
80
+ });
81
+ }
82
+
83
+ // Where a run in the person's own folder may push: only to the table's repository (any of the folder's remotes that is
84
+ // it), unless they let it push anywhere. With no table repository, nowhere. A remote with a push address of its own is
85
+ // outside git's rewrite, so when one points anywhere else, pushing is refused outright (noPush).
86
+ export function pushPlan(folder, repo, anywhere) {
87
+ if (anywhere) return { pushTo: null, noPush: false };
88
+ const remotes = remotesOf(folder);
89
+ const ok = (u) => !!repo && sameAddress(u, repo);
90
+ // Each address with and without its .git, since git is given exact addresses and refuses anything longer.
91
+ const twins = (u) => { const bare = u.replace(/\/+$/, "").replace(/\.git$/i, ""); return [bare, `${bare}.git`]; };
92
+ const pushTo = repo ? [...new Set([repo, ...remotes.flatMap((r) => r.urls.filter(ok))].flatMap(twins))] : [];
93
+ return { pushTo, noPush: remotes.some((r) => r.pushurl && !r.urls.every(ok)) };
94
+ }
95
+
96
+ // The folder a connection keeps as its person's own: the one it was connected from. Connected with an address, the
97
+ // folder it ran in is kept only when it is that same project (one of its remotes is the address): an AI opened
98
+ // anywhere else has no folder of its person's to work in.
99
+ export function folderFor(repo, cwd) {
100
+ if (!isAddress(repo)) return resolve(repo || cwd);
101
+ try {
102
+ if (!existsSync(join(cwd, ".git"))) return null;
103
+ return remotesOf(cwd).some((r) => r.urls.some((u) => sameAddress(u, repo))) ? resolve(cwd) : null;
104
+ } catch { return null; }
105
+ }
106
+
107
+ // The table's repository, when this person's connection may use it: they connected with that address, or they said
108
+ // yes to exactly that address in their AI's window (`agreed`) and their own folder's git knows it. Never on the
109
+ // table's word alone: anyone who may change settings could otherwise send this person's AI's work to any repository
110
+ // their folder can reach (a client's, named as origin). A changed address needs their yes again.
111
+ export function trustedRepo(seat, repo, agreed) {
112
+ if (!repo || !isAddress(repo) || !addressKey(repo) || /^(https|ssh):\/\/[^/]*@/i.test(repo)) return null;
113
+ if (sameAddress(seat.source, repo)) return repo;
114
+ if (agreed === repo && seat.folder && remotesOf(seat.folder).some((r) => r.urls.some((u) => sameAddress(u, repo)))) return repo;
115
+ return null;
116
+ }
117
+
118
+ // Where this job reads the team's code from and lands its branches: the trusted table repository, else what this
119
+ // connection was connected with. Changing the table's repository takes effect without connecting again.
120
+ export function sourceFor(seat, repo, agreed) {
121
+ const t = trustedRepo(seat, repo, agreed);
122
+ return t && !sameAddress(seat.source, t) ? t : seat.source;
123
+ }
124
+
43
125
  // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
44
126
  // repository can never point the AI at a file outside the copy.
45
127
  export function freshCopy(tableId, source) {
@@ -315,6 +397,41 @@ export function realRepo(seat) {
315
397
  try { return existsSync(join(folder, ".git")) ? resolve(folder) : null; } catch { return null; }
316
398
  }
317
399
 
400
+ // The folder they connected from, as their own Claude Code at home would open it: their own requests work there by
401
+ // default ("Work in my folder"), git repository or not.
402
+ export function ownFolder(seat) {
403
+ const folder = seat?.folder;
404
+ if (!folder) return null;
405
+ try { return statSync(folder).isDirectory() ? resolve(folder) : null; } catch { return null; }
406
+ }
407
+
408
+ // What git sees as changed in their folder right now, each path with its status and the file's size and time, so a
409
+ // job can say which files it changed even in a folder that already had work in progress.
410
+ export function folderState(folder) {
411
+ const out = new Map();
412
+ let raw = "";
413
+ try { raw = execFileSync("git", ["-c", "core.quotePath=false", "status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: folder, env: quiet, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], timeout: 60000, maxBuffer: 64 * 1024 * 1024 }).toString(); }
414
+ catch { return null; }
415
+ const parts = raw.split("\0");
416
+ for (let i = 0; i < parts.length; i++) {
417
+ const p = parts[i];
418
+ if (p.length < 4) continue;
419
+ const code = p.slice(0, 2);
420
+ const path = p.slice(3);
421
+ // A rename carries the old name next; it is not a file of its own.
422
+ if (code[0] === "R" || code[0] === "C") i++;
423
+ let seen = "gone";
424
+ try { const s = statSync(join(folder, path)); seen = `${s.size}:${s.mtimeMs}`; } catch {}
425
+ out.set(path, `${code}|${seen}`);
426
+ }
427
+ return out;
428
+ }
429
+ export function folderChanges(before, after) {
430
+ if (!before || !after) return [];
431
+ const all = new Set([...before.keys(), ...after.keys()]);
432
+ return [...all].filter((p) => before.get(p) !== after.get(p)).sort();
433
+ }
434
+
318
435
  // Where the team's code lives is the table's source (what the locked mode reads too), never whatever the person's own
319
436
  // repository happens to call origin: that can be somebody else's repository (a client's), which work must never reach.
320
437
  // When the source is this very repository, work stays in it as a local branch and nothing is pushed anywhere.
@@ -438,7 +555,8 @@ export function landTree(tree, branch, message, who) {
438
555
  let pushed = false;
439
556
  let landed = branch;
440
557
  // Work on the table's own repository is already on its branch there: nothing is pushed anywhere.
441
- if (!tree.url) return { files, commit, branch, pushed: true, apart: false };
558
+ // Kept as a branch in their own repository, pushed nowhere: it is there, on their computer only.
559
+ if (!tree.url) return { files, commit, branch, pushed: true, apart: false, local: true };
442
560
  const push = (to) => land(["push", "--quiet", "--no-verify", tree.url, `HEAD:refs/heads/${to}`]);
443
561
  try { push(branch); pushed = true; } catch (e) {
444
562
  log(`push of ${branch} failed: ${String(e.message).split(/\r?\n/)[0]}`);