longtable 0.1.13 → 0.1.15

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/repo.mjs CHANGED
@@ -1,237 +1,262 @@
1
- // The connection's own clean copy of the team's code: the latest main, never the person's work folder.
2
-
3
- import { execFileSync } from "node:child_process";
4
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
- import { join, resolve } from "node:path";
6
- import { home } from "./store.mjs";
7
-
8
- // Git never stops to ask for a name or password here: if this computer's saved sign-in cannot reach a repository,
9
- // the command fails and the connection says so.
10
- const quiet = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
11
- const git = (args, cwdOrEnv) => execFileSync("git", args, { cwd: typeof cwdOrEnv === "string" ? cwdOrEnv : undefined, env: typeof cwdOrEnv === "object" && cwdOrEnv ? cwdOrEnv : quiet, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000 }).toString().trim();
12
-
13
- export function canReach(source) {
14
- try {
15
- git(["ls-remote", "--exit-code", source, "HEAD"]);
16
- return true;
17
- } catch {
18
- return false;
19
- }
20
- }
21
-
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.
25
- export function resolveSource(repo) {
26
- if (!repo) return null;
27
- if (/^(https?:|git@|ssh:)/.test(repo)) {
28
- 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
- return repo;
30
- }
31
- const folder = resolve(repo);
32
- 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
- return "file:///" + folder.replace(/\\/g, "/");
40
- }
41
-
42
- // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
43
- // repository can never point the AI at a file outside the copy.
44
- export function freshCopy(tableId, source) {
45
- const dir = join(home, "copies", tableId);
46
- if (!source) {
47
- mkdirSync(dir, { recursive: true });
48
- return { dir, read: "no code connected" };
49
- }
50
- if (!existsSync(join(dir, ".git"))) {
51
- mkdirSync(join(home, "copies"), { recursive: true });
52
- git(["clone", "--quiet", "--depth", "1", "--no-tags", "-c", "core.symlinks=false", source, dir]);
53
- } else {
54
- git(["-C", dir, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", "HEAD"]);
55
- git(["-C", dir, "reset", "--quiet", "--hard", "FETCH_HEAD"]);
56
- git(["-C", dir, "clean", "-qfdx"]);
57
- }
58
- const branch = git(["-C", dir, "rev-parse", "--abbrev-ref", "HEAD"]);
59
- const head = git(["-C", dir, "rev-parse", "--short", "HEAD"]);
60
- return { dir, read: `${branch === "HEAD" ? "main" : branch} @ ${head}` };
61
- }
62
-
63
- export function copyIsClean(tableId) {
64
- const dir = join(home, "copies", tableId);
65
- if (!existsSync(join(dir, ".git"))) return true;
66
- return git(["-C", dir, "status", "--porcelain"]) === "";
67
- }
68
-
69
- // Work the team asked for happens in a second folder that holds the files and nothing else: no .git inside it, so
70
- // nothing the AI writes there can change what git itself runs. Git reaches it from outside, with its own index.
71
- const places = (tableId, name = "work") => ({ G: join(home, "copies", tableId, ".git"), W: join(home, name, tableId), I: join(home, name, `${tableId}.index`) });
72
- const wgit = (p, args, env = {}) => execFileSync("git", ["--git-dir", p.G, "--work-tree", p.W, ...args],
73
- { cwd: p.W, env: { ...quiet, GIT_INDEX_FILE: p.I, ...env }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000 }).toString().trim();
74
-
75
- // Whatever the table names, the connection only ever writes to a plain branch under longtable/. Never the default
76
- // branch, never anything that is not a simple name: this holds even if the server it talks to is not the real one.
77
- export function safeBranch(b) {
78
- if (typeof b !== "string" || !/^longtable\/[a-z0-9][a-z0-9-]{0,79}$/.test(b)) throw new Error("the table named a branch this connection will not write to");
79
- return b;
80
- }
81
-
82
- export const workBranch = (chatName) => "longtable/" + (String(chatName || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "work");
83
-
84
- // A folder laid beside the code for the AI to read, and never to be committed: the repository's own exclude list says so.
85
- export function neverCommit(tableId, name) {
86
- const file = join(home, "copies", tableId, ".git", "info", "exclude");
87
- try {
88
- const now = existsSync(file) ? readFileSync(file, "utf8") : "";
89
- if (!now.split(/\r?\n/).includes(`${name}/`)) writeFileSync(file, `${now}${now.endsWith(String.fromCharCode(10)) || !now ? "" : String.fromCharCode(10)}${name}/${String.fromCharCode(10)}`);
90
- } catch {}
91
- }
92
-
93
- // Lay out the files to work on: the chat's own branch when it already exists, so one request builds on the last,
94
- // else the latest default branch.
95
- export function openWork(tableId, branch, name = "work", { refresh = false } = {}) {
96
- safeBranch(branch);
97
- const p = places(tableId, name);
98
- rmSync(p.W, { recursive: true, force: true });
99
- rmSync(p.I, { force: true });
100
- mkdirSync(p.W, { recursive: true });
101
- let base = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
102
- let continued = false;
103
- // "There is no such branch yet" and "the repository could not be reached" are different things. Only the first
104
- // means start from the default branch; the second stops the job, or a follow-up would be built on the wrong code.
105
- let exists = false;
106
- try {
107
- git(["--git-dir", p.G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
108
- exists = true;
109
- } catch (e) {
110
- if (e.status !== 2) throw new Error("this computer could not reach the project's repository");
111
- }
112
- if (exists) {
113
- git(["--git-dir", p.G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
114
- base = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
115
- continued = true;
116
- }
117
- // A client's sandbox lives a long time, so each time it is opened it takes in what the team has shipped since.
118
- // If the two no longer fit together it stays as it is and says so: the team's work is never bent to fit it.
119
- let stale = false;
120
- if (refresh && continued) {
121
- const main = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
122
- try {
123
- git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", "HEAD", `refs/heads/${branch}`]);
124
- const common = git(["--git-dir", p.G, "merge-base", main, base]);
125
- if (common !== main) {
126
- const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${common}`, base, main]).split(/\r?\n/)[0];
127
- base = git(["--git-dir", p.G, "commit-tree", both, "-p", base, "-p", main, "-m", "Take in the team's latest"],
128
- { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "longtable@users.noreply.github.com", GIT_COMMITTER_NAME: "Longtable", GIT_COMMITTER_EMAIL: "longtable@users.noreply.github.com" });
129
- }
130
- } catch {
131
- stale = true;
132
- }
133
- }
134
- wgit(p, ["read-tree", base]);
135
- // -u records each file's size and time in the index, so finding what changed later does not reread every file.
136
- wgit(p, ["checkout-index", "-a", "-f", "-u"]);
137
- return { dir: p.W, base, continued, stale };
138
- }
139
-
140
- // What was changed in the work folder, before anything is committed: every file touched (a rename counts as both
141
- // names), and the whole of each one as it now stands. If any of it cannot be read, that is said, and the caller
142
- // treats it as a refusal: this check fails closed.
143
- export function changedSoFar(tableId, work) {
144
- const p = places(tableId);
145
- wgit(p, ["add", "-A"]);
146
- const files = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
147
- const gone = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", "--diff-filter=D", work.base]).split(/\r?\n/).filter(Boolean);
148
- let text = "";
149
- let unread = false;
150
- for (const f of files) {
151
- if (gone.includes(f)) continue;
152
- try {
153
- const body = readFileSync(join(p.W, f));
154
- if (body.length > 2 * 1024 * 1024 || body.includes(0)) { unread = true; continue; }
155
- text += String.fromCharCode(10) + body.toString("utf8");
156
- } catch { unread = true; }
157
- }
158
- return { files, gone, text, unread };
159
- }
160
-
161
- // Make the place for a copy: its branch, pushed with one empty commit of its own on top of the latest default branch,
162
- // so the hosting sees something new and puts it up. If the branch is already there, it is left as it is.
163
- export function openBranch(tableId, branch) {
164
- safeBranch(branch);
165
- const G = join(home, "copies", tableId, ".git");
166
- try {
167
- git(["--git-dir", G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
168
- git(["--git-dir", G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
169
- return git(["--git-dir", G, "rev-parse", "FETCH_HEAD"]);
170
- } catch (e) {
171
- if (e.status !== 2) throw new Error("this computer could not reach the project's repository");
172
- }
173
- const head = git(["--git-dir", G, "rev-parse", "HEAD"]);
174
- const tree = git(["--git-dir", G, "rev-parse", `${head}^{tree}`]);
175
- const who = { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "longtable@users.noreply.github.com", GIT_COMMITTER_NAME: "Longtable", GIT_COMMITTER_EMAIL: "longtable@users.noreply.github.com" };
176
- const commit = git(["--git-dir", G, "commit-tree", tree, "-p", head, "-m", "A copy of its own"], who);
177
- git(["--git-dir", G, "push", "--quiet", "origin", `${commit}:refs/heads/${branch}`]);
178
- return commit;
179
- }
180
-
181
- // One commit of a sandbox, as a patch the team's AI can read to see what the client ended up with.
182
- export function patchOf(tableId, branch, commit) {
183
- safeBranch(branch);
184
- if (!/^[0-9a-f]{7,40}$/.test(String(commit || ""))) return "";
185
- const G = join(home, "copies", tableId, ".git");
186
- try {
187
- // The commit itself, by its full name; a host that will not serve one commit gets the branch asked for instead.
188
- try { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "2", "origin", commit]); }
189
- catch { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", `refs/heads/${branch}`]); }
190
- return execFileSync("git", ["--git-dir", G, "show", "--format=", "--stat", "--patch", commit],
191
- { env: quiet, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000, maxBuffer: 64 * 1024 * 1024 }).toString().slice(0, 80000);
192
- } catch {
193
- return "";
194
- }
195
- }
196
-
197
- // Whatever changed becomes one commit on the chat's branch, pushed for the team to look at. Never the default branch.
198
- export function landWork(tableId, work, branch, message, who) {
199
- safeBranch(branch);
200
- const p = places(tableId);
201
- wgit(p, ["add", "-A"]);
202
- const files = wgit(p, ["diff", "--cached", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
203
- if (!files.length) return null;
204
- const tree = wgit(p, ["write-tree"]);
205
- let name = "";
206
- let email = "";
207
- try { name = git(["--git-dir", p.G, "config", "user.name"]); email = git(["--git-dir", p.G, "config", "user.email"]); } catch {}
208
- const id = { GIT_AUTHOR_NAME: name || who, GIT_AUTHOR_EMAIL: email || "longtable@users.noreply.github.com" };
209
- const commit = wgit(p, ["commit-tree", tree, "-p", work.base, "-m", message],
210
- { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL });
211
- const env = { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL };
212
- const push = (sha, to) => { try { git(["--git-dir", p.G, "push", "--quiet", "origin", `${sha}:refs/heads/${to}`]); return true; } catch { return false; } };
213
- if (push(commit, branch)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch };
214
- // Refused: another AI landed its part of the same task first. Put the two together when they do not touch the
215
- // same lines; when they do, this part goes to a branch of its own beside it and says so.
216
- for (let i = 0; i < 3; i++) {
217
- let theirs;
218
- try {
219
- git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "origin", `refs/heads/${branch}`]);
220
- theirs = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
221
- } catch { break; }
222
- let merged;
223
- try {
224
- // Putting two parts together is only right when the other part was built on the same starting point. If it
225
- // was not, a merge would quietly undo what is on the branch, so this part goes beside it instead.
226
- git(["--git-dir", p.G, "merge-base", "--is-ancestor", work.base, theirs]);
227
- const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${work.base}`, theirs, commit]).split(/\r?\n/)[0];
228
- merged = wgit(p, ["commit-tree", both, "-p", theirs, "-p", commit, "-m", `Put together: ${message}`], env);
229
- } catch { break; }
230
- if (push(merged, branch)) return { files, commit: merged.slice(0, 7), sha: merged, pushed: true, branch };
231
- }
232
- const side = `${branch}-${String(who || "part").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20)}`;
233
- if (push(commit, side)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch: side, apart: true };
234
- // Nothing could be pushed. Keep the commit findable on this computer, so the work is not lost with the folder.
235
- try { git(["--git-dir", p.G, "update-ref", `refs/longtable/${branch.slice(10)}`, commit]); } catch {}
236
- return { files, commit: commit.slice(0, 7), pushed: false, branch };
237
- }
1
+ // The connection's own clean copy of the team's code: the latest main, never the person's work folder.
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { home, log } from "./store.mjs";
7
+
8
+ // Git never stops to ask for a name or password here: if this computer's saved sign-in cannot reach a repository,
9
+ // the command fails and the connection says so.
10
+ const quiet = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
11
+ const git = (args, cwdOrEnv) => execFileSync("git", args, { cwd: typeof cwdOrEnv === "string" ? cwdOrEnv : undefined, env: typeof cwdOrEnv === "object" && cwdOrEnv ? cwdOrEnv : quiet, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000 }).toString().trim();
12
+
13
+ export function canReach(source) {
14
+ try {
15
+ git(["ls-remote", "--exit-code", source, "HEAD"]);
16
+ return true;
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+
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.
25
+ export function resolveSource(repo) {
26
+ if (!repo) return null;
27
+ if (/^(https?:|git@|ssh:)/.test(repo)) {
28
+ 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
+ return repo;
30
+ }
31
+ const folder = resolve(repo);
32
+ 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
+ return "file:///" + folder.replace(/\\/g, "/");
40
+ }
41
+
42
+ // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
43
+ // repository can never point the AI at a file outside the copy.
44
+ export function freshCopy(tableId, source) {
45
+ const dir = join(home, "copies", tableId);
46
+ if (!source) {
47
+ mkdirSync(dir, { recursive: true });
48
+ return { dir, read: "no code connected" };
49
+ }
50
+ if (!existsSync(join(dir, ".git"))) {
51
+ mkdirSync(join(home, "copies"), { recursive: true });
52
+ git(["clone", "--quiet", "--depth", "1", "--no-tags", "-c", "core.symlinks=false", source, dir]);
53
+ } else {
54
+ // The address may have changed since the copy was made (connected again after fixing git's sign-in, or the
55
+ // repository moved): fetch from, and later push to, where the project is now.
56
+ git(["-C", dir, "remote", "set-url", "origin", source]);
57
+ git(["-C", dir, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", "HEAD"]);
58
+ git(["-C", dir, "reset", "--quiet", "--hard", "FETCH_HEAD"]);
59
+ // The folder laid beside the code for an AI to read stays: a job that only reads may be in the middle of it
60
+ // while the copy is refreshed for long work in the other lane. Each job clears and lays it for itself.
61
+ git(["-C", dir, "clean", "-qfdx", "-e", ".longtable-yours"]);
62
+ }
63
+ const branch = git(["-C", dir, "rev-parse", "--abbrev-ref", "HEAD"]);
64
+ const head = git(["-C", dir, "rev-parse", "--short", "HEAD"]);
65
+ return { dir, read: `${branch === "HEAD" ? "main" : branch} @ ${head}` };
66
+ }
67
+
68
+ export function copyIsClean(tableId) {
69
+ const dir = join(home, "copies", tableId);
70
+ if (!existsSync(join(dir, ".git"))) return true;
71
+ return git(["-C", dir, "status", "--porcelain"]) === "";
72
+ }
73
+
74
+ // Work the team asked for happens in a second folder that holds the files and nothing else: no .git inside it, so
75
+ // nothing the AI writes there can change what git itself runs. Git reaches it from outside, with its own index.
76
+ const places = (tableId, name = "work") => ({ G: join(home, "copies", tableId, ".git"), W: join(home, name, tableId), I: join(home, name, `${tableId}.index`) });
77
+ // File names come back as they are. Left to itself git writes a name with letters outside plain English in quotes
78
+ // with numbers for the letters, and then the name is neither a file that can be read nor one a rule can match.
79
+ const wgit = (p, args, env = {}) => execFileSync("git", ["-c", "core.quotePath=false", "--git-dir", p.G, "--work-tree", p.W, ...args],
80
+ { cwd: p.W, env: { ...quiet, GIT_INDEX_FILE: p.I, ...env }, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000 }).toString().trim();
81
+
82
+ // Whatever the table names, the connection only ever writes to a plain branch under longtable/. Never the default
83
+ // branch, never anything that is not a simple name: this holds even if the server it talks to is not the real one.
84
+ export function safeBranch(b) {
85
+ if (typeof b !== "string" || !/^longtable\/[a-z0-9][a-z0-9-]{0,79}$/.test(b)) throw new Error("the table named a branch this connection will not write to");
86
+ return b;
87
+ }
88
+
89
+ export const workBranch = (chatName) => "longtable/" + (String(chatName || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "work");
90
+
91
+ // A folder laid beside the code for the AI to read, and never to be committed: the repository's own exclude list says so.
92
+ export function neverCommit(tableId, name) {
93
+ const file = join(home, "copies", tableId, ".git", "info", "exclude");
94
+ // Git does not always make the info folder (a person's own template may leave it out). If the list cannot be
95
+ // written this throws and the job stops: better no answer than their own notes pushed to the team's branch.
96
+ try {
97
+ mkdirSync(join(home, "copies", tableId, ".git", "info"), { recursive: true });
98
+ const now = existsSync(file) ? readFileSync(file, "utf8") : "";
99
+ if (!now.split(/\r?\n/).includes(`${name}/`)) writeFileSync(file, `${now}${now.endsWith(String.fromCharCode(10)) || !now ? "" : String.fromCharCode(10)}${name}/${String.fromCharCode(10)}`);
100
+ } catch (e) {
101
+ // The table is sent one plain sentence. What the system said names folders on this person's computer, so that
102
+ // stays in the log here, where they can read it.
103
+ log(`could not write the list of what is never committed for ${tableId}: ${e.message}`);
104
+ throw new Error("could not set aside what is this person's alone on their computer, so nothing was done; the connection's log there says why");
105
+ }
106
+ }
107
+
108
+ // Lay out the files to work on: the chat's own branch when it already exists, so one request builds on the last,
109
+ // else the latest default branch.
110
+ export function openWork(tableId, branch, name = "work", { refresh = false } = {}) {
111
+ safeBranch(branch);
112
+ const p = places(tableId, name);
113
+ rmSync(p.W, { recursive: true, force: true });
114
+ rmSync(p.I, { force: true });
115
+ mkdirSync(p.W, { recursive: true });
116
+ let base = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
117
+ let continued = false;
118
+ // "There is no such branch yet" and "the repository could not be reached" are different things. Only the first
119
+ // means start from the default branch; the second stops the job, or a follow-up would be built on the wrong code.
120
+ let exists = false;
121
+ try {
122
+ git(["--git-dir", p.G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
123
+ exists = true;
124
+ } catch (e) {
125
+ if (e.status !== 2) throw new Error("this computer could not reach the project's repository");
126
+ }
127
+ if (exists) {
128
+ git(["--git-dir", p.G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
129
+ base = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
130
+ continued = true;
131
+ }
132
+ // A client's sandbox lives a long time, so each time it is opened it takes in what the team has shipped since.
133
+ // If the two no longer fit together it stays as it is and says so: the team's work is never bent to fit it.
134
+ let stale = false;
135
+ if (refresh && continued) {
136
+ const main = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
137
+ try {
138
+ git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", "HEAD", `refs/heads/${branch}`]);
139
+ const common = git(["--git-dir", p.G, "merge-base", main, base]);
140
+ if (common !== main) {
141
+ const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${common}`, base, main]).split(/\r?\n/)[0];
142
+ base = git(["--git-dir", p.G, "commit-tree", both, "-p", base, "-p", main, "-m", "Take in the team's latest"],
143
+ { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "longtable@users.noreply.github.com", GIT_COMMITTER_NAME: "Longtable", GIT_COMMITTER_EMAIL: "longtable@users.noreply.github.com" });
144
+ }
145
+ } catch {
146
+ stale = true;
147
+ }
148
+ }
149
+ wgit(p, ["read-tree", base]);
150
+ // -u records each file's size and time in the index, so finding what changed later does not reread every file.
151
+ wgit(p, ["checkout-index", "-a", "-f", "-u"]);
152
+ return { dir: p.W, base, continued, stale };
153
+ }
154
+
155
+ // What was changed in the work folder, before anything is committed: every file touched (a rename counts as both
156
+ // names), and the whole of each one as it now stands. If any of it cannot be read, that is said, and the caller
157
+ // treats it as a refusal: this check fails closed.
158
+ export function changedSoFar(tableId, work) {
159
+ const p = places(tableId);
160
+ wgit(p, ["add", "-A"]);
161
+ const files = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
162
+ const gone = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", "--diff-filter=D", work.base]).split(/\r?\n/).filter(Boolean);
163
+ let text = "";
164
+ let unread = false;
165
+ for (const f of files) {
166
+ if (gone.includes(f)) continue;
167
+ try {
168
+ const body = readFileSync(join(p.W, f));
169
+ if (body.length > 2 * 1024 * 1024 || body.includes(0)) { unread = true; continue; }
170
+ text += String.fromCharCode(10) + body.toString("utf8");
171
+ } catch { unread = true; }
172
+ }
173
+ return { files, gone, text, unread };
174
+ }
175
+
176
+ // Make the place for a copy: its branch, pushed with one empty commit of its own on top of the latest default branch,
177
+ // so the hosting sees something new and puts it up. If the branch is already there, it is left as it is.
178
+ // With fresh, a copy that already exists is put back to the product as it stands: one more commit on top, holding the
179
+ // default branch's files, so whatever was tried in it before is gone from what the hosting puts up.
180
+ export function openBranch(tableId, branch, fresh = false) {
181
+ safeBranch(branch);
182
+ const G = join(home, "copies", tableId, ".git");
183
+ try {
184
+ git(["--git-dir", G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
185
+ git(["--git-dir", G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
186
+ const tip = git(["--git-dir", G, "rev-parse", "FETCH_HEAD"]);
187
+ if (!fresh) return tip;
188
+ const clean = git(["--git-dir", G, "rev-parse", "HEAD^{tree}"]);
189
+ if (git(["--git-dir", G, "rev-parse", `${tip}^{tree}`]) === clean) return tip;
190
+ const as = { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "longtable@users.noreply.github.com", GIT_COMMITTER_NAME: "Longtable", GIT_COMMITTER_EMAIL: "longtable@users.noreply.github.com" };
191
+ const again = git(["--git-dir", G, "commit-tree", clean, "-p", tip, "-m", "A clean copy"], as);
192
+ git(["--git-dir", G, "push", "--quiet", "origin", `${again}:refs/heads/${branch}`]);
193
+ return again;
194
+ } catch (e) {
195
+ if (e.status !== 2) throw new Error("this computer could not reach the project's repository");
196
+ }
197
+ const head = git(["--git-dir", G, "rev-parse", "HEAD"]);
198
+ const tree = git(["--git-dir", G, "rev-parse", `${head}^{tree}`]);
199
+ const who = { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "longtable@users.noreply.github.com", GIT_COMMITTER_NAME: "Longtable", GIT_COMMITTER_EMAIL: "longtable@users.noreply.github.com" };
200
+ const commit = git(["--git-dir", G, "commit-tree", tree, "-p", head, "-m", "A copy of its own"], who);
201
+ git(["--git-dir", G, "push", "--quiet", "origin", `${commit}:refs/heads/${branch}`]);
202
+ return commit;
203
+ }
204
+
205
+ // One commit of a sandbox, as a patch the team's AI can read to see what the client ended up with.
206
+ export function patchOf(tableId, branch, commit) {
207
+ safeBranch(branch);
208
+ if (!/^[0-9a-f]{7,40}$/.test(String(commit || ""))) return "";
209
+ const G = join(home, "copies", tableId, ".git");
210
+ try {
211
+ // The commit itself, by its full name; a host that will not serve one commit gets the branch asked for instead.
212
+ try { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "2", "origin", commit]); }
213
+ catch { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", `refs/heads/${branch}`]); }
214
+ return execFileSync("git", ["--git-dir", G, "show", "--format=", "--stat", "--patch", commit],
215
+ { env: quiet, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000, maxBuffer: 64 * 1024 * 1024 }).toString().slice(0, 80000);
216
+ } catch {
217
+ return "";
218
+ }
219
+ }
220
+
221
+ // Whatever changed becomes one commit on the chat's branch, pushed for the team to look at. Never the default branch.
222
+ export function landWork(tableId, work, branch, message, who) {
223
+ safeBranch(branch);
224
+ const p = places(tableId);
225
+ wgit(p, ["add", "-A"]);
226
+ const files = wgit(p, ["diff", "--cached", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
227
+ if (!files.length) return null;
228
+ const tree = wgit(p, ["write-tree"]);
229
+ let name = "";
230
+ let email = "";
231
+ try { name = git(["--git-dir", p.G, "config", "user.name"]); email = git(["--git-dir", p.G, "config", "user.email"]); } catch {}
232
+ const id = { GIT_AUTHOR_NAME: name || who, GIT_AUTHOR_EMAIL: email || "longtable@users.noreply.github.com" };
233
+ const commit = wgit(p, ["commit-tree", tree, "-p", work.base, "-m", message],
234
+ { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL });
235
+ const env = { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL };
236
+ const push = (sha, to) => { try { git(["--git-dir", p.G, "push", "--quiet", "origin", `${sha}:refs/heads/${to}`]); return true; } catch { return false; } };
237
+ if (push(commit, branch)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch };
238
+ // Refused: another AI landed its part of the same task first. Put the two together when they do not touch the
239
+ // same lines; when they do, this part goes to a branch of its own beside it and says so.
240
+ for (let i = 0; i < 3; i++) {
241
+ let theirs;
242
+ try {
243
+ git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "origin", `refs/heads/${branch}`]);
244
+ theirs = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
245
+ } catch { break; }
246
+ let merged;
247
+ try {
248
+ // Putting two parts together is only right when the other part was built on the same starting point. If it
249
+ // was not, a merge would quietly undo what is on the branch, so this part goes beside it instead.
250
+ git(["--git-dir", p.G, "merge-base", "--is-ancestor", work.base, theirs]);
251
+ const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${work.base}`, theirs, commit]).split(/\r?\n/)[0];
252
+ merged = wgit(p, ["commit-tree", both, "-p", theirs, "-p", commit, "-m", `Put together: ${message}`], env);
253
+ } catch { break; }
254
+ if (push(merged, branch)) return { files, commit: merged.slice(0, 7), sha: merged, pushed: true, branch };
255
+ }
256
+ // A name with no Latin letters in it leaves nothing to name the branch by, so it is just "part".
257
+ const side = `${branch}-${String(who || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20).replace(/^-+|-+$/g, "") || "part"}`;
258
+ if (push(commit, side)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch: side, apart: true };
259
+ // Nothing could be pushed. Keep the commit findable on this computer, so the work is not lost with the folder.
260
+ try { git(["--git-dir", p.G, "update-ref", `refs/longtable/${branch.slice(10)}`, commit]); } catch {}
261
+ return { files, commit: commit.slice(0, 7), pushed: false, branch };
262
+ }