longtable 0.1.2 → 0.1.7

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,67 +1,208 @@
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 } 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, cwd) => execFileSync("git", args, { cwd, env: 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
- }
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 } 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
+ // Lay out the files to work on: the chat's own branch when it already exists, so one request builds on the last,
85
+ // else the latest default branch.
86
+ export function openWork(tableId, branch, name = "work", { refresh = false } = {}) {
87
+ safeBranch(branch);
88
+ const p = places(tableId, name);
89
+ rmSync(p.W, { recursive: true, force: true });
90
+ rmSync(p.I, { force: true });
91
+ mkdirSync(p.W, { recursive: true });
92
+ let base = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
93
+ let continued = false;
94
+ // "There is no such branch yet" and "the repository could not be reached" are different things. Only the first
95
+ // means start from the default branch; the second stops the job, or a follow-up would be built on the wrong code.
96
+ let exists = false;
97
+ try {
98
+ git(["--git-dir", p.G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
99
+ exists = true;
100
+ } catch (e) {
101
+ if (e.status !== 2) throw new Error("this computer could not reach the project's repository");
102
+ }
103
+ if (exists) {
104
+ git(["--git-dir", p.G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
105
+ base = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
106
+ continued = true;
107
+ }
108
+ // A client's sandbox lives a long time, so each time it is opened it takes in what the team has shipped since.
109
+ // 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.
110
+ let stale = false;
111
+ if (refresh && continued) {
112
+ const main = git(["--git-dir", p.G, "rev-parse", "HEAD"]);
113
+ try {
114
+ git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", "HEAD", `refs/heads/${branch}`]);
115
+ const common = git(["--git-dir", p.G, "merge-base", main, base]);
116
+ if (common !== main) {
117
+ const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${common}`, base, main]).split(/\r?\n/)[0];
118
+ base = git(["--git-dir", p.G, "commit-tree", both, "-p", base, "-p", main, "-m", "Take in the team's latest"],
119
+ { ...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" });
120
+ }
121
+ } catch {
122
+ stale = true;
123
+ }
124
+ }
125
+ wgit(p, ["read-tree", base]);
126
+ // -u records each file's size and time in the index, so finding what changed later does not reread every file.
127
+ wgit(p, ["checkout-index", "-a", "-f", "-u"]);
128
+ return { dir: p.W, base, continued, stale };
129
+ }
130
+
131
+ // What was changed in the work folder, before anything is committed: every file touched (a rename counts as both
132
+ // names), and the whole of each one as it now stands. If any of it cannot be read, that is said, and the caller
133
+ // treats it as a refusal: this check fails closed.
134
+ export function changedSoFar(tableId, work) {
135
+ const p = places(tableId);
136
+ wgit(p, ["add", "-A"]);
137
+ const files = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
138
+ const gone = wgit(p, ["diff", "--cached", "--no-renames", "--name-only", "--diff-filter=D", work.base]).split(/\r?\n/).filter(Boolean);
139
+ let text = "";
140
+ let unread = false;
141
+ for (const f of files) {
142
+ if (gone.includes(f)) continue;
143
+ try {
144
+ const body = readFileSync(join(p.W, f));
145
+ if (body.length > 2 * 1024 * 1024 || body.includes(0)) { unread = true; continue; }
146
+ text += String.fromCharCode(10) + body.toString("utf8");
147
+ } catch { unread = true; }
148
+ }
149
+ return { files, gone, text, unread };
150
+ }
151
+
152
+ // One commit of a sandbox, as a patch the team's AI can read to see what the client ended up with.
153
+ export function patchOf(tableId, branch, commit) {
154
+ safeBranch(branch);
155
+ if (!/^[0-9a-f]{7,40}$/.test(String(commit || ""))) return "";
156
+ const G = join(home, "copies", tableId, ".git");
157
+ try {
158
+ // The commit itself, by its full name; a host that will not serve one commit gets the branch asked for instead.
159
+ try { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "2", "origin", commit]); }
160
+ catch { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "400", "origin", `refs/heads/${branch}`]); }
161
+ return execFileSync("git", ["--git-dir", G, "show", "--format=", "--stat", "--patch", commit],
162
+ { env: quiet, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], timeout: 120000, maxBuffer: 64 * 1024 * 1024 }).toString().slice(0, 80000);
163
+ } catch {
164
+ return "";
165
+ }
166
+ }
167
+
168
+ // Whatever changed becomes one commit on the chat's branch, pushed for the team to look at. Never the default branch.
169
+ export function landWork(tableId, work, branch, message, who) {
170
+ safeBranch(branch);
171
+ const p = places(tableId);
172
+ wgit(p, ["add", "-A"]);
173
+ const files = wgit(p, ["diff", "--cached", "--name-only", work.base]).split(/\r?\n/).filter(Boolean);
174
+ if (!files.length) return null;
175
+ const tree = wgit(p, ["write-tree"]);
176
+ let name = "";
177
+ let email = "";
178
+ try { name = git(["--git-dir", p.G, "config", "user.name"]); email = git(["--git-dir", p.G, "config", "user.email"]); } catch {}
179
+ const id = { GIT_AUTHOR_NAME: name || who, GIT_AUTHOR_EMAIL: email || "longtable@users.noreply.github.com" };
180
+ const commit = wgit(p, ["commit-tree", tree, "-p", work.base, "-m", message],
181
+ { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL });
182
+ const env = { ...id, GIT_COMMITTER_NAME: id.GIT_AUTHOR_NAME, GIT_COMMITTER_EMAIL: id.GIT_AUTHOR_EMAIL };
183
+ const push = (sha, to) => { try { git(["--git-dir", p.G, "push", "--quiet", "origin", `${sha}:refs/heads/${to}`]); return true; } catch { return false; } };
184
+ if (push(commit, branch)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch };
185
+ // Refused: another AI landed its part of the same task first. Put the two together when they do not touch the
186
+ // same lines; when they do, this part goes to a branch of its own beside it and says so.
187
+ for (let i = 0; i < 3; i++) {
188
+ let theirs;
189
+ try {
190
+ git(["--git-dir", p.G, "fetch", "--quiet", "--no-tags", "origin", `refs/heads/${branch}`]);
191
+ theirs = git(["--git-dir", p.G, "rev-parse", "FETCH_HEAD"]);
192
+ } catch { break; }
193
+ let merged;
194
+ try {
195
+ // Putting two parts together is only right when the other part was built on the same starting point. If it
196
+ // was not, a merge would quietly undo what is on the branch, so this part goes beside it instead.
197
+ git(["--git-dir", p.G, "merge-base", "--is-ancestor", work.base, theirs]);
198
+ const both = git(["--git-dir", p.G, "merge-tree", "--write-tree", `--merge-base=${work.base}`, theirs, commit]).split(/\r?\n/)[0];
199
+ merged = wgit(p, ["commit-tree", both, "-p", theirs, "-p", commit, "-m", `Put together: ${message}`], env);
200
+ } catch { break; }
201
+ if (push(merged, branch)) return { files, commit: merged.slice(0, 7), sha: merged, pushed: true, branch };
202
+ }
203
+ const side = `${branch}-${String(who || "part").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20)}`;
204
+ if (push(commit, side)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch: side, apart: true };
205
+ // Nothing could be pushed. Keep the commit findable on this computer, so the work is not lost with the folder.
206
+ try { git(["--git-dir", p.G, "update-ref", `refs/longtable/${branch.slice(10)}`, commit]); } catch {}
207
+ return { files, commit: commit.slice(0, 7), pushed: false, branch };
208
+ }