longtable 0.1.34 → 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,8 +1,9 @@
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
+ import { fileURLToPath } from "node:url";
6
7
  import { home, log } from "./store.mjs";
7
8
 
8
9
  // Git never stops to ask for a name or password here: if this computer's saved sign-in cannot reach a repository,
@@ -19,26 +20,108 @@ export function canReach(source) {
19
20
  }
20
21
  }
21
22
 
22
- // Given a folder or a git address, find where to copy from. For a folder: its origin when this computer can reach
23
- // it, else the folder's own history, which is still only committed work. An address that cannot be reached is an
24
- // 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.
25
27
  export function resolveSource(repo) {
26
28
  if (!repo) return null;
27
- if (/^(https?:|git@|ssh:)/.test(repo)) {
29
+ if (isAddress(repo)) {
28
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.`);
29
31
  return repo;
30
32
  }
31
33
  const folder = resolve(repo);
32
34
  if (!existsSync(join(folder, ".git"))) throw new Error(`${folder} is not a git repository`);
33
- try {
34
- const origin = git(["-C", folder, "remote", "get-url", "origin"]);
35
- if (origin && canReach(origin)) return origin;
36
- } catch {
37
- // No origin: fall through to the folder itself.
38
- }
39
35
  return "file:///" + folder.replace(/\\/g, "/");
40
36
  }
41
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
+
42
125
  // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
43
126
  // repository can never point the AI at a file outside the copy.
44
127
  export function freshCopy(tableId, source) {
@@ -314,10 +397,62 @@ export function realRepo(seat) {
314
397
  try { return existsSync(join(folder, ".git")) ? resolve(folder) : null; } catch { return null; }
315
398
  }
316
399
 
317
- function originDefault(repo) {
318
- try { return tgit(repo, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]); } catch {}
319
- for (const b of ["origin/main", "origin/master"]) { try { tgit(repo, ["rev-parse", "--verify", "--quiet", b]); return b; } catch {} }
320
- return "HEAD";
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
+
435
+ // Where the team's code lives is the table's source (what the locked mode reads too), never whatever the person's own
436
+ // repository happens to call origin: that can be somebody else's repository (a client's), which work must never reach.
437
+ // When the source is this very repository, work stays in it as a local branch and nothing is pushed anywhere.
438
+ function sameRepo(source, repo) {
439
+ if (!source) return true;
440
+ let p = String(source);
441
+ if (/^file:/i.test(p)) { try { p = fileURLToPath(p); } catch { return false; } }
442
+ else if (!/^([A-Za-z]:[\\/]|[\\/])/.test(p)) return false;
443
+ const norm = (x) => resolve(x).replace(/[\\/]+$/, "").toLowerCase();
444
+ return norm(p) === norm(repo) || norm(p) === norm(join(repo, ".git"));
445
+ }
446
+
447
+ // The tip of a branch (or of the source's default branch) at the source, fetched under a private name of the
448
+ // connection's and read back as a commit: nothing of the person's own refs or remotes changes.
449
+ function sourceTip(repo, url, ref) {
450
+ const tmp = `refs/longtable-src/tip-${process.pid}-${Date.now()}`;
451
+ try {
452
+ tgit(repo, ["fetch", "--quiet", "--no-tags", url, `+${ref}:${tmp}`]);
453
+ return tgit(repo, ["rev-parse", tmp]);
454
+ } catch { return null; }
455
+ finally { try { tgit(repo, ["update-ref", "-d", tmp]); } catch {} }
321
456
  }
322
457
 
323
458
  // Only files git ignores are copied, as Claude Code does: something tracked is already in the worktree, and something
@@ -347,26 +482,35 @@ export function openTree(seat, branch, { doing = false, job = "read" } = {}) {
347
482
  const repo = realRepo(seat) || join(home, "copies", table);
348
483
  const dir = doing ? join(home, "trees", table, `work-${branch.slice("longtable/".length)}`)
349
484
  : join(home, "trees", table, `read-${String(job).replace(/[^A-Za-z0-9-]/g, "").slice(0, 36) || "job"}`);
350
- try { tgit(repo, ["fetch", "--quiet", "origin"]); } catch (e) { log(`fetch before a worktree failed: ${String(e.message).split(/\r?\n/)[0]}`); }
485
+ // The table's code: this repository itself, or the address the table reads from (never "origin" by name).
486
+ const local = sameRepo(seat.source, repo);
487
+ const url = local ? null : seat.source;
351
488
  let onRemote = false;
352
- if (branch) { try { tgit(repo, ["rev-parse", "--verify", "--quiet", `origin/${branch}`]); onRemote = true; } catch {} }
353
- const base = onRemote ? `origin/${branch}` : originDefault(repo);
489
+ let base = null;
490
+ if (local) {
491
+ if (branch) { try { base = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); onRemote = true; } catch {} }
492
+ base ??= tgit(repo, ["rev-parse", "HEAD"]);
493
+ } else {
494
+ if (branch) { base = sourceTip(repo, url, `refs/heads/${branch}`); onRemote = !!base; }
495
+ base ??= sourceTip(repo, url, "HEAD");
496
+ if (!base) throw new Error("the project's code could not be fetched from where the table reads it");
497
+ }
354
498
  const fresh = !existsSync(join(dir, ".git"));
355
499
  if (fresh) {
356
500
  mkdirSync(join(home, "trees", table), { recursive: true });
357
501
  // A worktree of ours whose folder is gone is let go by name; the person's own worktrees are never touched.
358
502
  try { tgit(repo, ["worktree", "remove", "--force", dir]); } catch {}
359
- if (doing) {
503
+ if (doing && !local) {
360
504
  // Their own local branch of the same name is never reset over work that is not on the server.
361
- let local = null;
362
- try { local = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); } catch {}
363
- if (local) {
364
- try { tgit(repo, ["merge-base", "--is-ancestor", local, base]); }
505
+ let mine = null;
506
+ try { mine = tgit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]); } catch {}
507
+ if (mine) {
508
+ try { tgit(repo, ["merge-base", "--is-ancestor", mine, base]); }
365
509
  catch { throw new Error(`a branch named ${branch} on this computer has work that is not on the server, so it was left as it is`); }
366
510
  }
367
511
  }
368
512
  tgit(repo, ["worktree", "add", "--quiet", ...(doing ? ["-B", branch, dir, base] : ["--detach", dir, base])]);
369
- } else if (doing && onRemote) {
513
+ } else if (doing && onRemote && !local) {
370
514
  // Work picked up again starts from what is on the server (another AI's part may have landed there since), unless
371
515
  // this computer holds commits the server does not have yet.
372
516
  try { tgit(dir, ["merge-base", "--is-ancestor", "HEAD", base]); tgit(dir, ["reset", "--quiet", "--hard", base]); } catch {}
@@ -380,7 +524,7 @@ export function openTree(seat, branch, { doing = false, job = "read" } = {}) {
380
524
  const NL = String.fromCharCode(10);
381
525
  if (!now.split(/\r?\n/).includes(".longtable-yours/")) writeFileSync(exclude, `${now}${now && !now.endsWith(NL) ? NL : ""}.longtable-yours/${NL}`);
382
526
  if (fresh && realRepo(seat)) copyIncluded(repo, dir);
383
- return { dir, repo, base: tgit(dir, ["rev-parse", "HEAD"]), continued: onRemote, tree: true };
527
+ return { dir, repo, url, base: tgit(dir, ["rev-parse", "HEAD"]), continued: onRemote, tree: true };
384
528
  }
385
529
 
386
530
  // What changed in the worktree since it was opened, committed or not.
@@ -410,13 +554,16 @@ export function landTree(tree, branch, message, who) {
410
554
  const commit = land(["rev-parse", "--short", "HEAD"]);
411
555
  let pushed = false;
412
556
  let landed = branch;
413
- const push = (to) => land(["push", "--quiet", "--no-verify", "origin", `HEAD:refs/heads/${to}`]);
557
+ // Work on the table's own repository is already on its branch there: nothing is pushed anywhere.
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 };
560
+ const push = (to) => land(["push", "--quiet", "--no-verify", tree.url, `HEAD:refs/heads/${to}`]);
414
561
  try { push(branch); pushed = true; } catch (e) {
415
562
  log(`push of ${branch} failed: ${String(e.message).split(/\r?\n/)[0]}`);
416
563
  // Another part landed on the branch first (two people's work on one task): put the two together and try again;
417
564
  // when they touch the same lines, this part goes on a branch of its own beside it, as the other work does.
418
565
  try {
419
- land(["fetch", "--quiet", "origin", branch]);
566
+ land(["fetch", "--quiet", "--no-tags", tree.url, `refs/heads/${branch}`]);
420
567
  land(["merge", "--quiet", "--no-edit", "--no-verify", "FETCH_HEAD"]);
421
568
  push(branch);
422
569
  pushed = true;