longtable 0.1.16 → 0.1.18

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/pointed.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  // C:\Users\me\notes\plan.md". Their AI may read them, the way it would if they had said so at their own keyboard.
3
3
  // Nobody else's message can do this, and some places are never opened whoever asks.
4
4
 
5
- import { cpSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
5
+ import { createHash } from "node:crypto";
6
+ import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
8
  import { basename, isAbsolute, join, parse, resolve, sep } from "node:path";
8
9
 
@@ -29,7 +30,10 @@ const NEVER = [
29
30
  /[\\/]Library[\\/](Keychains|Application Support[\\/](Google|BraveSoftware|Firefox))([\\/]|$)/i,
30
31
  /^[\\/](etc[\\/](shadow|sudoers)|proc|sys|dev)([\\/]|$)/i,
31
32
  ];
32
- const refused = (p) => NEVER.some((r) => r.test(p));
33
+ // On Windows a colon after the drive names one of a file's streams (".env::$DATA" reads the .env itself), and no
34
+ // ordinary file name holds one there, so a path with one is never opened.
35
+ const refused = (p) => NEVER.some((r) => r.test(p)) || (process.platform === "win32" && String(p).replace(/^(\\\\[?.]\\)?[A-Za-z]:/, "").includes(":"));
36
+ const isLink = (p) => { try { return lstatSync(p).isSymbolicLink(); } catch { return true; } };
33
37
  // A whole drive, a whole home folder or the system's own folders are not "a place someone pointed at".
34
38
  function tooWide(p) {
35
39
  const { root } = parse(p);
@@ -58,7 +62,9 @@ export function pointedPaths(text) {
58
62
  const p = tidy(raw);
59
63
  if (!p || !isAbsolute(p) || found.length >= 5) return;
60
64
  let real;
61
- try { real = realpathSync(p); } catch { return; }
65
+ // The system's own answer, which also turns an old short name ("ENV~1") into the long one it stands for, so the
66
+ // check below sees ".env" and not a name that only means it.
67
+ try { real = realpathSync.native(p); } catch { return; }
62
68
  if (seen.has(real.toLowerCase())) return;
63
69
  seen.add(real.toLowerCase());
64
70
  if (refused(p) || refused(real)) { found.push({ path: p, refused: "that place is never opened from the table" }); return; }
@@ -96,8 +102,10 @@ export function pointedPaths(text) {
96
102
  }
97
103
 
98
104
  const FILE_CAP = 40 * 1024 * 1024;
99
- const DIR_FILES = 400;
100
- const DIR_BYTES = 30 * 1024 * 1024;
105
+ // A folder that cannot be read where it is comes as a filtered copy, kept between jobs, up to this size (his choice,
106
+ // 16 Oct 2026; it was 400 files and 30 MB, so most whole projects were refused).
107
+ const DIR_FILES = 5000;
108
+ const DIR_BYTES = 300 * 1024 * 1024;
101
109
  // How much is in a folder, stopping as soon as it is clearly too much to bring along.
102
110
  function weigh(dir) {
103
111
  let files = 0;
@@ -107,7 +115,7 @@ function weigh(dir) {
107
115
  if (files > DIR_FILES || bytes > DIR_BYTES) return;
108
116
  if (e.name === "node_modules" || e.name === ".git") continue;
109
117
  const p = join(d, e.name);
110
- if (refused(p)) continue;
118
+ if (refused(p) || e.isSymbolicLink()) continue;
111
119
  if (e.isDirectory()) walk(p);
112
120
  else if (e.isFile()) { files++; try { bytes += statSync(p).size; } catch {} }
113
121
  }
@@ -129,6 +137,8 @@ function whyNotInPlace(dir) {
129
137
  if (e.name === "node_modules" || e.name === ".git") continue;
130
138
  const p = join(d, e.name);
131
139
  if (refused(p)) return "secret";
140
+ // A link (or a Windows junction) leads out of the folder, to a place nobody looked through.
141
+ if (e.isSymbolicLink()) return "link";
132
142
  if (++looked > 20000) return "many";
133
143
  const why = e.isDirectory() ? walk(p) : "";
134
144
  if (why) return why;
@@ -138,16 +148,61 @@ function whyNotInPlace(dir) {
138
148
  return walk(dir);
139
149
  }
140
150
  const NOT_IN_PLACE = {
141
- secret: "the folder has a key or a sign-in file inside it and is too big to bring along without them; point at a folder or a file inside it",
151
+ secret: "the folder has a key or a sign-in file inside it and is too big (more than about 5,000 files or 300 MB) to bring along without them; point at a folder or a file inside it",
142
152
  many: "the folder is too big to look through for keys and sign-in files before opening it; point at a folder or a file inside it",
143
- unreadable: "part of the folder could not be looked through for keys and sign-in files, and it is too big to bring along as a copy; point at a folder or a file inside it",
153
+ link: "the folder has a link inside it to somewhere else and is too big (more than about 5,000 files or 300 MB) to bring along without it; point at a folder or a file inside it",
154
+ unreadable: "part of the folder could not be looked through for keys and sign-in files, and it is too big (more than about 5,000 files or 300 MB) to bring along as a copy; point at a folder or a file inside it",
144
155
  };
145
156
 
157
+ // What may come along in a copy of a folder: never a link, a key or sign-in file, node_modules or .git.
158
+ // On Windows Node's copy hands its filter paths that start with \\?\ (seen 16 Oct 2026), so a path never matched the
159
+ // folder it was copied from and every file in a folder inside node_modules was left out.
160
+ const plainPath = (p) => String(p).replace(/^\\\\\?\\/, "");
161
+ const comesAlong = (src, root) => {
162
+ const s = plainPath(src);
163
+ const r = root ? plainPath(root) : "";
164
+ if (isLink(src) || refused(s)) return false;
165
+ const below = r && s.startsWith(r) ? s.slice(r.length) : s;
166
+ return !/[\\/](node_modules|\.git)([\\/]|$)/.test(below);
167
+ };
168
+
169
+ // The filtered copy of a folder, kept in the connection's own folder between jobs and brought up to date each time:
170
+ // a file that changed (by size or time) is copied again, one that is gone from the folder goes from the copy. So a
171
+ // big project is copied once, not on every question.
172
+ export function keptCopy(real, home) {
173
+ const at = join(home, "pointed", createHash("sha256").update(real).digest("hex").slice(0, 24));
174
+ const seen = new Set();
175
+ const bring = (from, to) => {
176
+ mkdirSync(to, { recursive: true });
177
+ for (const e of readdirSync(from, { withFileTypes: true })) {
178
+ const src = join(from, e.name);
179
+ if (!comesAlong(src, real)) continue;
180
+ const dst = join(to, e.name);
181
+ seen.add(dst);
182
+ if (e.isDirectory()) { bring(src, dst); continue; }
183
+ if (!e.isFile()) continue;
184
+ let same = false;
185
+ try { const a = statSync(src), b = statSync(dst); same = a.size === b.size && b.mtimeMs >= a.mtimeMs; } catch {}
186
+ if (!same) copyFileSync(src, dst);
187
+ }
188
+ };
189
+ const prune = (dir) => {
190
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
191
+ const p = join(dir, e.name);
192
+ if (!seen.has(p)) { rmSync(p, { recursive: true, force: true }); continue; }
193
+ if (e.isDirectory()) prune(p);
194
+ }
195
+ };
196
+ bring(real, at);
197
+ prune(at);
198
+ return at;
199
+ }
200
+
146
201
  // Puts what was pointed at where the AI can read it. A file is copied beside the work, into a folder that is never
147
202
  // committed. A folder is read where it is when the job only reads and nothing inside it is a key or a sign-in; when
148
203
  // the job may change files, or something inside must stay out, it is copied instead without those, if it is small,
149
204
  // so nothing on the person's own disk can be changed from the table and no key comes along.
150
- export function layPointed(into, paths, { reading }) {
205
+ export function layPointed(into, paths, { reading, home: keep }) {
151
206
  const dest = join(into, "pointed");
152
207
  try { rmSync(dest, { recursive: true, force: true }); } catch {}
153
208
  const out = { files: [], dirs: [], copied: [], skipped: [] };
@@ -167,14 +222,21 @@ export function layPointed(into, paths, { reading }) {
167
222
  } else {
168
223
  const w = weigh(p.real);
169
224
  if (w.files > DIR_FILES || w.bytes > DIR_BYTES) {
170
- out.skipped.push({ path: p.path, why: reading ? NOT_IN_PLACE[why] : "the folder is too big to bring into a job that changes files; ask about it as a question first" });
225
+ out.skipped.push({ path: p.path, why: reading ? NOT_IN_PLACE[why] : "the folder is too big (more than about 5,000 files or 300 MB) to bring into a job that changes files; point at a folder inside it" });
171
226
  continue;
172
227
  }
173
- const at = join(dest, `${++n}-${basename(p.real)}`);
174
228
  try {
175
- mkdirSync(dest, { recursive: true });
176
- cpSync(p.real, at, { recursive: true, filter: (src) => !refused(src) && !/[\\/](node_modules|\.git)([\\/]|$)/.test(src) });
177
- out.copied.push({ path: p.path, at });
229
+ if (keep) {
230
+ // Kept between jobs, beside the connection's other folders; the job is given it as a folder to read.
231
+ const at = keptCopy(p.real, keep);
232
+ out.copied.push({ path: p.path, at, kept: true });
233
+ out.dirs.push(at);
234
+ } else {
235
+ const at = join(dest, `${++n}-${basename(p.real)}`);
236
+ mkdirSync(dest, { recursive: true });
237
+ cpSync(p.real, at, { recursive: true, filter: (src) => plainPath(src) === plainPath(p.real) || comesAlong(src, p.real) });
238
+ out.copied.push({ path: p.path, at });
239
+ }
178
240
  } catch { out.skipped.push({ path: p.path, why: "it could not be read" }); }
179
241
  }
180
242
  }
@@ -186,8 +248,8 @@ export function pointedSystem(me, laid, base) {
186
248
  const rel = (at) => at.slice(base.length).replace(/^[\\/]+/, "").split(sep).join("/");
187
249
  const lines = [
188
250
  ...laid.files.map((f) => `- the file ${f.path} is here for you as ${rel(f.at)}`),
189
- ...laid.copied.map((f) => `- the folder ${f.path} is here for you as ${rel(f.at)}/`),
190
- ...laid.dirs.map((d) => `- the folder ${d} (read it where it is)`),
251
+ ...laid.copied.map((f) => f.kept ? `- the folder ${f.path} is here for you, without its keys, sign-in files and node_modules, at ${f.at}` : `- the folder ${f.path} is here for you as ${rel(f.at)}/`),
252
+ ...laid.dirs.filter((d) => !laid.copied.some((f) => f.at === d)).map((d) => `- the folder ${d} (read it where it is)`),
191
253
  ...laid.skipped.map((s) => `- ${s.path} was NOT opened: ${s.why}. Say so plainly if it matters.`),
192
254
  ];
193
255
  if (!lines.length) return [];
package/src/repo.mjs CHANGED
@@ -42,7 +42,7 @@ export function resolveSource(repo) {
42
42
  // Bring the copy up to the latest default branch. Symlinks are checked out as plain files, so a link in the
43
43
  // repository can never point the AI at a file outside the copy.
44
44
  export function freshCopy(tableId, source) {
45
- const dir = join(home, "copies", tableId);
45
+ const dir = join(home, "copies", safeTable(tableId));
46
46
  if (!source) {
47
47
  mkdirSync(dir, { recursive: true });
48
48
  return { dir, read: "no code connected" };
@@ -66,14 +66,14 @@ export function freshCopy(tableId, source) {
66
66
  }
67
67
 
68
68
  export function copyIsClean(tableId) {
69
- const dir = join(home, "copies", tableId);
69
+ const dir = join(home, "copies", safeTable(tableId));
70
70
  if (!existsSync(join(dir, ".git"))) return true;
71
71
  return git(["-C", dir, "status", "--porcelain"]) === "";
72
72
  }
73
73
 
74
74
  // Work the team asked for happens in a second folder that holds the files and nothing else: no .git inside it, so
75
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`) });
76
+ const places = (tableId, name = "work") => ({ G: join(home, "copies", safeTable(tableId), ".git"), W: join(home, name, safeTable(tableId)), I: join(home, name, `${safeTable(tableId)}.index`) });
77
77
  // File names come back as they are. Left to itself git writes a name with letters outside plain English in quotes
78
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
79
  const wgit = (p, args, env = {}) => execFileSync("git", ["-c", "core.quotePath=false", "--git-dir", p.G, "--work-tree", p.W, ...args],
@@ -86,15 +86,22 @@ export function safeBranch(b) {
86
86
  return b;
87
87
  }
88
88
 
89
+ // A table's id becomes a folder name on this computer, so it must be one: a server that is not the real one could
90
+ // otherwise name "../../somewhere" and have that folder written to or wiped.
91
+ export function safeTable(t) {
92
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(t))) throw new Error("the table named itself in a way this connection will not use as a folder");
93
+ return t;
94
+ }
95
+
89
96
  export const workBranch = (chatName) => "longtable/" + (String(chatName || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "work");
90
97
 
91
98
  // 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
99
  export function neverCommit(tableId, name) {
93
- const file = join(home, "copies", tableId, ".git", "info", "exclude");
100
+ const file = join(home, "copies", safeTable(tableId), ".git", "info", "exclude");
94
101
  // Git does not always make the info folder (a person's own template may leave it out). If the list cannot be
95
102
  // written this throws and the job stops: better no answer than their own notes pushed to the team's branch.
96
103
  try {
97
- mkdirSync(join(home, "copies", tableId, ".git", "info"), { recursive: true });
104
+ mkdirSync(join(home, "copies", safeTable(tableId), ".git", "info"), { recursive: true });
98
105
  const now = existsSync(file) ? readFileSync(file, "utf8") : "";
99
106
  if (!now.split(/\r?\n/).includes(`${name}/`)) writeFileSync(file, `${now}${now.endsWith(String.fromCharCode(10)) || !now ? "" : String.fromCharCode(10)}${name}/${String.fromCharCode(10)}`);
100
107
  } catch (e) {
@@ -107,6 +114,30 @@ export function neverCommit(tableId, name) {
107
114
 
108
115
  // Lay out the files to work on: the chat's own branch when it already exists, so one request builds on the last,
109
116
  // else the latest default branch.
117
+ // Whether this computer's git can put two parts of work together on one branch (merge-tree --write-tree, git 2.38
118
+ // and later). An older git still works: a part goes on its own branch beside the other, as when two parts touch the
119
+ // same lines. "version" is what git says of itself, for the person to be told.
120
+ export function gitCanJoin(said) {
121
+ let version = said;
122
+ try { version ??= execFileSync("git", ["--version"], { encoding: "utf8", windowsHide: true }).trim(); } catch { return { ok: false, version: "no git found" }; }
123
+ const m = String(version).match(/(\d+)\.(\d+)/);
124
+ const ok = !!m && (Number(m[1]) > 2 || (Number(m[1]) === 2 && Number(m[2]) >= 38));
125
+ return { ok, version };
126
+ }
127
+
128
+ // Everything the connection keeps of these tables' code on this computer: the clean copies, the work and reading
129
+ // folders, and the kept copies of folders a person pointed at. Done after the connection has stopped; a file still
130
+ // held for a moment is tried again.
131
+ export function forgetCopies(tableIds) {
132
+ const gone = (p) => { try { rmSync(p, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }); } catch (e) { log(`could not remove ${p}: ${e.message}`); } };
133
+ for (const t of tableIds) {
134
+ let safe;
135
+ try { safe = safeTable(t); } catch { continue; }
136
+ for (const place of ["copies", "work", "look"]) gone(join(home, place, safe));
137
+ }
138
+ gone(join(home, "pointed"));
139
+ }
140
+
110
141
  export function openWork(tableId, branch, name = "work", { refresh = false } = {}) {
111
142
  safeBranch(branch);
112
143
  const p = places(tableId, name);
@@ -179,7 +210,7 @@ export function changedSoFar(tableId, work) {
179
210
  // default branch's files, so whatever was tried in it before is gone from what the hosting puts up.
180
211
  export function openBranch(tableId, branch, fresh = false) {
181
212
  safeBranch(branch);
182
- const G = join(home, "copies", tableId, ".git");
213
+ const G = join(home, "copies", safeTable(tableId), ".git");
183
214
  try {
184
215
  git(["--git-dir", G, "ls-remote", "--exit-code", "origin", `refs/heads/${branch}`]);
185
216
  git(["--git-dir", G, "fetch", "--quiet", "--depth", "1", "--no-tags", "origin", `refs/heads/${branch}`]);
@@ -206,7 +237,7 @@ export function openBranch(tableId, branch, fresh = false) {
206
237
  export function patchOf(tableId, branch, commit) {
207
238
  safeBranch(branch);
208
239
  if (!/^[0-9a-f]{7,40}$/.test(String(commit || ""))) return "";
209
- const G = join(home, "copies", tableId, ".git");
240
+ const G = join(home, "copies", safeTable(tableId), ".git");
210
241
  try {
211
242
  // The commit itself, by its full name; a host that will not serve one commit gets the branch asked for instead.
212
243
  try { git(["--git-dir", G, "fetch", "--quiet", "--no-tags", "--depth", "2", "origin", commit]); }
@@ -255,6 +286,9 @@ export function landWork(tableId, work, branch, message, who) {
255
286
  }
256
287
  // A name with no Latin letters in it leaves nothing to name the branch by, so it is just "part".
257
288
  const side = `${branch}-${String(who || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 20).replace(/^-+|-+$/g, "") || "part"}`;
289
+ // A tripwire, written to this computer's log and nothing more: a side branch from a long branch name can be longer
290
+ // than the connection's own rule for branches, and a later job handed it could not write to it.
291
+ try { safeBranch(side); } catch { try { log("tripwire: a side branch came out longer than the connection's own branch rule"); } catch {} }
258
292
  if (push(commit, side)) return { files, commit: commit.slice(0, 7), sha: commit, pushed: true, branch: side, apart: true };
259
293
  // Nothing could be pushed. Keep the commit findable on this computer, so the work is not lost with the folder.
260
294
  try { git(["--git-dir", p.G, "update-ref", `refs/longtable/${branch.slice(10)}`, commit]); } catch {}
package/src/run.mjs CHANGED
@@ -5,15 +5,16 @@
5
5
 
6
6
  import { layPointed, pointedPaths, pointedSystem } from "./pointed.mjs";
7
7
  import { attachedPrompt, commandPrompt, fetchAttachments, loadCommand, materialsPrompt, scanCommands, shareable } from "./extras.mjs";
8
+ import { spawnSync } from "node:child_process";
8
9
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
9
10
  import { homedir, uptime } from "node:os";
10
11
  import { isAbsolute, join, normalize, relative, resolve } from "node:path";
11
12
  import { client } from "./api.mjs";
12
- import { ask, findClaude } from "./claude.mjs";
13
+ import { ask, findClaude, stopAll } from "./claude.mjs";
13
14
  import { askCodex, codexLimits, findCodex } from "./codex.mjs";
14
15
  import { packCode } from "./pack.mjs";
15
- import { changedSoFar, freshCopy, landWork, neverCommit, openBranch, openWork, patchOf, workBranch } from "./repo.mjs";
16
- import { hideSecrets, home, loadSecret, log, readConfig } from "./store.mjs";
16
+ import { changedSoFar, freshCopy, landWork, neverCommit, openBranch, openWork, patchOf, safeTable, workBranch } from "./repo.mjs";
17
+ import { cut, hideSecrets, home, loadSecret, log, readConfig, writeWhole } from "./store.mjs";
17
18
 
18
19
  const SOURCES = {
19
20
  type: "array",
@@ -107,11 +108,18 @@ export const KINDS = {
107
108
  };
108
109
 
109
110
  const NL = String.fromCharCode(10);
110
- // Text from the table, a file or another AI is fenced so it reads as information. Nothing inside may close a fence.
111
- const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)\b|\b(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
111
+ // Text from the table, a file or another AI is fenced so it reads as information. Nothing inside may close a fence,
112
+ // and a marker glued to a letter ("xTABLE>>>") is still a marker to whoever reads it, so no word edge is asked for.
113
+ export const inert = (t) => String(t ?? "").replace(/<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)|(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/g, "[marker]");
114
+ // A tripwire: something that should never happen, written to this computer's log in one fixed sentence (never a
115
+ // path, a name or anything from a file) and nothing more. It never stops or changes the job. sweep-notes/rules.md
116
+ // lists each one.
117
+ export function trip(what) { try { log(`tripwire: ${what}`); } catch {} }
118
+ const MARKER = /<<<(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)|(TABLE|CODE|YOURS|PART|SHARED|COMMAND|CLIENT)>>>/;
119
+ const fenced = (inner) => { if (MARKER.test(inner)) trip("a fence marker was still in the table's text after cleaning"); return inner; };
112
120
  // The conversation as it is, newest kept: every message whole, back to wherever a generous size runs out. There is
113
121
  // no count of messages: a long talk between people is all there.
114
- function recent(history, room) {
122
+ export function recent(history, room) {
115
123
  const out = [];
116
124
  let used = 0;
117
125
  for (const m of [...(history || [])].reverse()) {
@@ -133,10 +141,10 @@ const fence = (job) => {
133
141
  const who = (m) => (m.by_ai ? `${m.name}'s AI` : m.client ? `${m.name} (the client, asking)` : m.name);
134
142
  const parts = [];
135
143
  if (job.people?.length) parts.push(facts(job));
136
- if (job.pinned?.length) parts.push("Pinned notes:\n" + job.pinned.map((n) => `(${n.title || n.kind}) ${n.body}`).join("\n"));
137
- if (job.related?.length) parts.push("Related earlier messages from other chats:\n" + job.related.map((m) => `[${m.chat}] ${who(m)}: ${m.body}`).join("\n"));
144
+ if (job.pinned?.length) parts.push("Pinned notes:\n" + job.pinned.map((n) => `(${n.title || n.kind}) ${n.body ?? ""}`).join("\n"));
145
+ if (job.related?.length) parts.push("Related earlier messages from other chats:\n" + job.related.map((m) => `[${m.chat}] ${who(m)}: ${m.body ?? ""}`).join("\n"));
138
146
  const talk = recent(job.history, 120000);
139
- parts.push(talk.length ? `The conversation in "${job.chat_name}"${talk.length < (job.history || []).length ? " (its start is left out for length)" : ""}:\n` + talk.map((m) => `${who(m)}: ${m.body}`).join("\n") : `No earlier messages in "${job.chat_name}".`);
147
+ parts.push(talk.length ? `The conversation in "${job.chat_name}"${talk.length < (job.history || []).length ? " (its start is left out for length)" : ""}:\n` + talk.map((m) => `${who(m)}: ${m.body ?? ""}`).join("\n") : `No earlier messages in "${job.chat_name}".`);
140
148
  if (job.kind === "plan") {
141
149
  parts.push("What the other AIs said before the work:" + NL + (job.views?.length ? job.views.map((v) => `${v.name}'s AI: ${v.view}`).join(NL) : "Nothing."));
142
150
  }
@@ -145,7 +153,7 @@ const fence = (job) => {
145
153
  parts.push("The back room so far, oldest first:" + NL + (job.views?.length ? job.views.map((v) => `${v.name}'s AI (${label(v)}): ${v.view}`).join(NL) : "Nothing yet."));
146
154
  } else if (job.kind === "combine") parts.push("Back-room views:\n" + (job.views?.length ? job.views.map((v) => `${v.name}'s AI (${v.meta?.confidence ?? "unsure"}): ${v.view}`).join("\n") : "None came in."));
147
155
  if (job.question) parts.push(`Question from ${job.asker}:\n${job.question}`);
148
- return ["<<<TABLE", inert(parts.join("\n\n")), "TABLE>>>"].join("\n");
156
+ return ["<<<TABLE", fenced(inert(parts.join("\n\n"))), "TABLE>>>"].join("\n");
149
157
  };
150
158
 
151
159
  // What a client's AI sees: only that client's own requests, what they were told, and their chat with it.
@@ -157,9 +165,9 @@ const fenceClient = (job) => {
157
165
  if (job.told?.length) parts.push("What the team told them, newest first:\n" + job.told.map((u) => `- ${u.words}${u.their_answer ? ` (they answered: ${u.their_answer})` : ""}`).join("\n"));
158
166
  if (job.work?.length) parts.push("What the team's AIs have taken on, newest first (titles only; \"finished\" means built and waiting for the team to check, not yet live):\n"
159
167
  + job.work.map((w) => `- "${w.title}": ${w.status === "done" ? "finished" : "under way"}`).join("\n"));
160
- if (job.history?.length) parts.push("Your chat with them so far:\n" + job.history.map((l) => `${l.who === "client" ? job.me : "You"}: ${l.body}`).join("\n"));
168
+ if (job.history?.length) parts.push("Your chat with them so far:\n" + job.history.map((l) => `${l.who === "client" ? job.me : "You"}: ${l.body ?? ""}`).join("\n"));
161
169
  parts.push(`Their latest message:\n${job.question}`);
162
- return ["<<<TABLE", inert(parts.join("\n\n")), "TABLE>>>"].join("\n");
170
+ return ["<<<TABLE", fenced(inert(parts.join("\n\n"))), "TABLE>>>"].join("\n");
163
171
  };
164
172
 
165
173
  // What the table's answer is told when it may also do the work.
@@ -216,14 +224,14 @@ export function systemFor(job) {
216
224
 
217
225
  // The listener: the cheapest thing at the table. It sees the last few messages and nothing else, and decides
218
226
  // whether the AIs are wanted at all. No code, no tools, the smallest model.
219
- const short = (t, n) => (String(t).length > n ? String(t).slice(0, n) + "…" : String(t));
227
+ const short = (t, n) => (String(t ?? "").length > n ? cut(t, n) + "…" : String(t ?? ""));
220
228
  export function listenPrompt(job) {
221
229
  const who = (m) => (m.by_ai ? `${m.name}'s AI` : m.client ? `${m.name} (the client)` : m.name);
222
230
  // The conversation as far back as a generous size reaches, never a fixed number of messages.
223
231
  const before = recent(job.history, 48000).map((m) => `${who(m)}: ${short(m.body, 3000)}`).join(NL);
224
232
  const tasks = (job.tasks || []).map((t, i) => `T${i + 1}: "${t.title}" (${t.status === "working" ? "being worked on now" : t.status}, asked by ${t.asked_by || "someone"}, in ${t.chat})`).join(NL);
225
- return ["<<<TABLE", inert([facts(job), "", `Work the AIs have taken on lately:${NL}${tasks || "(none)"}`, "", before || "(nothing earlier)", `${job.asker}: ${short(job.question, 6000)}`,
226
- ...(job.command ? ["", `That message runs ${job.asker}'s own AI command /${job.command.name}${job.command.about ? `, which is for: ${job.command.about}` : ""}. Running a command is asking for it to be done: choose look, or work when the command is about changing the project. Never silent, never reply.`] : [])].join(NL)), "TABLE>>>"].join(NL);
233
+ return ["<<<TABLE", fenced(inert([facts(job), "", `Work the AIs have taken on lately:${NL}${tasks || "(none)"}`, "", before || "(nothing earlier)", `${job.asker}: ${short(job.question, 6000)}`,
234
+ ...(job.command ? ["", `That message runs ${job.asker}'s own AI command /${job.command.name}${job.command.about ? `, which is for: ${job.command.about}` : ""}. Running a command is asking for it to be done: choose look, or work when the command is about changing the project. Never silent, never reply.`] : [])].join(NL))), "TABLE>>>"].join(NL);
227
235
  }
228
236
  export function listenSystem(job) {
229
237
  return [
@@ -269,8 +277,11 @@ export function knows(seat) {
269
277
  // The end of their own conversation about this project comes first: it is what the two of them were just doing.
270
278
  let talk = "";
271
279
  if (folder) { try { talk = recentSession(folder, 16000); } catch {} }
272
- const rest = parts.join(NL + NL).slice(0, 34000);
273
- return (talk ? `## The latest of your own conversation with them about this project (newest last)${NL}${talk}${NL}${NL}` : "") + rest;
280
+ // The rest has what room the conversation leaves, so the whole stays within 36,000 characters.
281
+ const head = talk ? `## The latest of your own conversation with them about this project (newest last)${NL}${talk}${NL}${NL}` : "";
282
+ const out = head + parts.join(NL + NL).slice(0, Math.max(0, 36000 - head.length));
283
+ if (out.length > 36000) trip("what a person's Claude knows came out over its 36,000 characters");
284
+ return out;
274
285
  }
275
286
 
276
287
  // Everything this person's Claude knows on their own computer, whole, laid in a folder beside the code for it to
@@ -306,6 +317,8 @@ export function recentSession(folder, room = 90000) {
306
317
  for (let i = lines.length - 1; i >= 0 && used < room; i--) {
307
318
  let e;
308
319
  try { e = JSON.parse(lines[i]); } catch { continue; }
320
+ // A line that is valid JSON but not a turn ("null", left by a crash) is skipped, not allowed to stop the rest.
321
+ if (!e || typeof e !== "object") continue;
309
322
  if (e.isSidechain || (e.type !== "user" && e.type !== "assistant")) continue;
310
323
  const words = said(e.message?.content).trim();
311
324
  // Reminders the app adds to a message are not something either of them said.
@@ -354,16 +367,16 @@ export function layYours(seat, dir) {
354
367
 
355
368
  // Each person's AI keeps its own short notes on that person's computer. They are what makes one person's AI differ
356
369
  // from another's on the same model: what it has learned here, in its own words. They never leave this computer.
357
- const mindFile = (tableId) => join(home, "minds", `${tableId}.md`);
370
+ const mindFile = (tableId) => join(home, "minds", `${safeTable(tableId)}.md`);
358
371
  export function mind(tableId) {
359
372
  try { return readFileSync(mindFile(tableId), "utf8").trim(); } catch { return ""; }
360
373
  }
361
374
  export function remember(tableId, text) {
362
- const line = hideSecrets(String(text || "")).replace(/\s+/g, " ").trim().slice(0, 300);
375
+ const line = cut(hideSecrets(String(text || "")).replace(/\s+/g, " ").trim(), 300);
363
376
  if (line.length < 12) return;
364
377
  mkdirSync(join(home, "minds"), { recursive: true });
365
378
  const kept = mind(tableId).split(NL).filter(Boolean).slice(-39);
366
- writeFileSync(mindFile(tableId), [...kept, `- ${new Date().toISOString().slice(0, 10)}: ${line}`].join(NL) + NL);
379
+ writeWhole(mindFile(tableId), [...kept, `- ${new Date().toISOString().slice(0, 10)}: ${line}`].join(NL) + NL);
367
380
  }
368
381
 
369
382
  // Keep only sources that are real files inside the copy, written relative to it.
@@ -374,7 +387,8 @@ export function cleanSources(dir, sources) {
374
387
  let p = s.trim().replace(/^\.\//, "");
375
388
  if (isAbsolute(p)) p = relative(dir, p);
376
389
  p = normalize(p).replace(/\\/g, "/");
377
- if (p.startsWith("..") || isAbsolute(p) || p.startsWith(YOURS)) continue;
390
+ // On Windows and macOS ".LONGTABLE-YOURS" is the same folder, so the person's own is matched in any letter case.
391
+ if (p.startsWith("..") || isAbsolute(p) || p.toLowerCase().startsWith(YOURS)) continue;
378
392
  if (existsSync(join(dir, p)) && !out.includes(p)) out.push(p);
379
393
  }
380
394
  return out.slice(0, 6);
@@ -529,12 +543,15 @@ const NOT_IN_A_SANDBOX = new RegExp([
529
543
  // what runs on the server, at build time, or decides who may do what
530
544
  "(^|/)(scripts?|migrations?|supabase|prisma|drizzle|db|database|server|functions|workers?|lambda|infra|deploy|ops|bin|tools)/",
531
545
  "(^|/)(api|trpc|actions?)/", "(^|/)(route|middleware|instrumentation|proxy|actions?|server)[.][cm]?[jt]sx?$",
532
- "(^|[/._-])(auth|login|signin|sign-in|session|permissions?|polic(y|ies)|rls|guard|roles?|admin|secrets?|credentials?|tokens?|keys?)([/._-]|$)",
546
+ "(^|[/._-])(auth|login|signin|sign-in|session|permissions?|polic(y|ies)|rls|guard|admin|secrets?|credentials?)([/._-]|$)",
547
+ // Words that are also ordinary parts of a name ("role-picker", "token-list") only count as a whole folder or file.
548
+ "(^|/)(roles?|tokens?|keys?)([/.]|$)",
533
549
  // tests, so one cannot be changed to pass
534
550
  "(^|/)(tests?|__tests__|e2e|spec|cypress|playwright)/", "[.](test|spec)[.]",
535
551
  ].join("|"), "i");
536
552
  const NOT_A_SANDBOX_WORD = new RegExp([
537
- "\\bprocess\\s*\\??\\.[A-Za-z_$]", "\\bprocess\\s*\\[", "[=(,:]\\s*process\\s*[;),}\\]]", "\\bprocess\\s*$", "import\\s*[.]\\s*meta", "\\b(Deno|Bun)\\s*[.]", "\\benv\\s*[\\[.})]", "\\bgetenv\\b", "os[.]environ", "\\bENV\\s*[\\[.]",
553
+ "\\bprocess\\s*\\??\\.[A-Za-z_$]", "\\bprocess\\s*\\[", "[=(,:]\\s*process\\s*[;),}\\]]", "[=(,:]\\s*process\\s*$", "import\\s*[.]\\s*meta", "\\b(Deno|Bun)\\s*[.]",
554
+ "\\benv\\s*\\[", "\\benv\\s*\\??\\.[A-Za-z_$]", "[{,]\\s*env\\s*[,})]", "\\bgetenv\\b", "os[.]environ", "\\bENV\\s*[\\[.]",
538
555
  "\\b(readFile|readFileSync|readdir|readdirSync|createReadStream|child_process|execSync|spawn)\\b", "[\"'`](node:)?(fs|fs/promises|vm|net|dns|child_process|worker_threads)[\"'`]",
539
556
  // The server's other ways out, named where a module is asked for, so "http" in an ordinary sentence is left alone.
540
557
  "\\b(require|import)\\s*\\(\\s*[\"'`](node:)?(https?|http2|os|tls|dgram|module)[\"'`]", "\\bfrom\\s*[\"'`](node:)?(https?|http2|os|tls|dgram|module)[\"'`]",
@@ -573,7 +590,7 @@ async function workSandbox(rpc, seat, engines, job) {
573
590
  const control = {};
574
591
  const tell = async () => {
575
592
  told = Date.now();
576
- try { if ((await rpc("runner_beat", { token: seat.token, job: job.job_id, note })) === false) control.kill?.(); } catch {}
593
+ try { if ((await rpc("runner_beat", { token: seat.token, job: job.job_id, note })) === false) control.kill?.(); } catch (e) { if (/connection was removed/i.test(e.message)) control.kill?.(); }
577
594
  };
578
595
  const beat = setInterval(tell, 20000);
579
596
  try {
@@ -616,7 +633,8 @@ function planText(job, s) {
616
633
 
617
634
  // Why a job failed, as the table may see it: the last line of the error, with no sign-in from a repository address
618
635
  // and nothing shaped like a key.
619
- const plain = (e) => hideSecrets(String(e?.message || e).split(/\r?\n/).filter(Boolean).pop() || "it failed").replace(/\/\/[^/@\s]+@/g, "//").slice(0, 300);
636
+ // The sign-in runs to the LAST @ before the host: a name or a password may hold an @ of its own ("a@b:p@ss@host").
637
+ export const plain = (e) => hideSecrets(String(e?.message || e).split(/\r?\n/).filter(Boolean).pop() || "it failed").replace(/\/\/[^/\s]*@/g, "//").slice(0, 300);
620
638
 
621
639
  // The listener's one small request. Its only output is what to do next; the table does the rest.
622
640
  async function workListen(rpc, seat, engines, job) {
@@ -645,7 +663,19 @@ async function workListen(rpc, seat, engines, job) {
645
663
  log(`listen job ${job.job_id}: ${act}`);
646
664
  }
647
665
 
648
- async function work(rpc, seat, engines, job) {
666
+ // People's and tables' names come from the table like any other words, and go into the AI's own instructions: a
667
+ // name could carry a fence marker, quotes or line breaks that read as instructions of their own. Each is one plain
668
+ // line before any prompt is built.
669
+ export const oneName = (t) => cut(inert(t).replace(/\s+/g, " ").replace(/"/g, "'").trim(), 80) || "someone";
670
+ export function cleanNames(job) {
671
+ const out = { ...job };
672
+ for (const k of ["me", "asker", "client", "table_name"]) if (typeof out[k] === "string") out[k] = oneName(out[k]);
673
+ if (Array.isArray(out.people)) out.people = out.people.map((p) => ({ ...p, name: oneName(p?.name) }));
674
+ return out;
675
+ }
676
+
677
+ async function work(rpc, seat, engines, raw) {
678
+ const job = cleanNames(raw);
649
679
  log(`${job.kind} job ${job.job_id} for ${job.me}`);
650
680
  if (job.kind === "sandbox") {
651
681
  try {
@@ -706,7 +736,7 @@ async function work(rpc, seat, engines, job) {
706
736
  const control = {};
707
737
  const tell = async () => {
708
738
  told = Date.now();
709
- try { if ((await rpc("runner_beat", { token: seat.token, job: job.job_id, note })) === false) control.kill?.(); } catch {}
739
+ try { if ((await rpc("runner_beat", { token: seat.token, job: job.job_id, note })) === false) control.kill?.(); } catch (e) { if (/connection was removed/i.test(e.message)) control.kill?.(); }
710
740
  };
711
741
  beat = setInterval(tell, 20000);
712
742
  const dir = opened ? opened.dir : copy.dir;
@@ -719,7 +749,7 @@ async function work(rpc, seat, engines, job) {
719
749
  const at = pointedPaths(job.question);
720
750
  if (at.length) {
721
751
  if (seat.source) neverCommit(seat.table_id, YOURS);
722
- laid = layPointed(join(dir, YOURS), at, { reading: !doing });
752
+ laid = layPointed(join(dir, YOURS), at, { reading: !doing, home });
723
753
  log(`job ${job.job_id}: opened ${laid.files.length + laid.dirs.length + laid.copied.length} pointed place(s), left ${laid.skipped.length}`);
724
754
  // And, while their person leaves it on, the text of them for the other AIs on this same request.
725
755
  if (job.share_paths && ["plan", "work", "look", "answer"].includes(job.kind)) {
@@ -758,13 +788,22 @@ async function work(rpc, seat, engines, job) {
758
788
  if (e.message !== "ran out of time" || !doing) throw e;
759
789
  return { structured_output: { answer: "I ran out of time. What I had changed up to then is on the branch. It is not finished, so look at it before building on it.", sources: [] }, usage: {}, modelUsage: {} };
760
790
  });
761
- if (result.is_error) throw new Error(result.result || "Claude Code reported an error");
762
- const s = result.structured_output || {};
763
- const text = job.kind === "view" || job.kind === "review" ? s.view
791
+ const s = result.is_error ? {} : result.structured_output || {};
792
+ let text = job.kind === "view" || job.kind === "review" ? s.view
764
793
  : job.kind === "plan" ? planText(job, s)
765
794
  : job.kind === "intro" ? `${s.knows}\n\nI can check: ${s.can_check}`
766
795
  : s.answer;
767
- if (!text || !String(text).trim()) throw new Error("Claude Code came back empty");
796
+ const unfinished = result.is_error ? String(result.result || "Claude Code reported an error")
797
+ : !text || !String(text).trim() ? "Claude Code came back empty" : null;
798
+ if (unfinished) {
799
+ // Work that already changed files is not thrown away because its last word went wrong: what it changed lands
800
+ // on the branch, and the answer says plainly that it is not finished. Anything else fails as before.
801
+ let changed = 0;
802
+ try { changed = opened && doing ? changedSoFar(seat.table_id, opened).files.length : 0; } catch {}
803
+ if (!changed) throw new Error(unfinished);
804
+ log(`${job.kind} job ${job.job_id} ended without an answer (${unfinished.slice(0, 120)}); landing the ${changed} file(s) it changed`);
805
+ text = "I could not finish my answer. What I had changed up to then is on the branch. It is not finished, so look at it before building on it.";
806
+ }
768
807
  if (s.learned) remember(seat.table_id, s.learned);
769
808
  const landed = opened && doing ? landWork(seat.table_id, opened, branch, String(job.question || "Work from the table").split(/\r?\n/)[0].slice(0, 72), job.me) : null;
770
809
  const said = landed && !landed.pushed ? `${text}\n\nI made the change, but git on ${job.me}'s computer could not push the branch ${branch}, so nobody else can see it yet. It is kept there as commit ${landed.commit}.`
@@ -809,6 +848,16 @@ async function work(rpc, seat, engines, job) {
809
848
  }
810
849
  }
811
850
 
851
+ // End another running connection and every program it started. On Windows a plain kill ends only the connection
852
+ // itself and its Claude carries on, so the whole tree is ended there; elsewhere the connection's own signal handler
853
+ // ends its Claudes before it goes.
854
+ export function endConnection(pid) {
855
+ try {
856
+ if (process.platform === "win32") spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" });
857
+ else process.kill(pid, "SIGTERM");
858
+ } catch (e) { log(`could not end connection ${pid}: ${e.message}`); }
859
+ }
860
+
812
861
  // The connection that is running on this computer right now, if its note can be trusted: written since this computer
813
862
  // last started (a number from before a restart may belong to any program by now), by a process that still exists.
814
863
  export function runningConnection() {
@@ -823,10 +872,12 @@ export function runningConnection() {
823
872
  }
824
873
 
825
874
  // The names of this person's own commands and skills, and a line on each, so "/" at the table can offer them. Never
826
- // what is in them: that stays on this computer and is read only when they run one.
875
+ // what is in them: that stays on this computer and is read only when they run one. A line is the first line of a
876
+ // file the person wrote, which can hold a key, so it is cleaned before it leaves.
877
+ export const toldCommands = (list) => list.map(({ name, about, kind }) => ({ name, about: hideSecrets(about), kind }));
827
878
  async function tellCommands(rpc, seat) {
828
879
  try {
829
- const list = scanCommands(seat).map(({ name, about, kind }) => ({ name, about, kind }));
880
+ const list = toldCommands(scanCommands(seat));
830
881
  const key = JSON.stringify(list);
831
882
  if (seat.told === key) return;
832
883
  await rpc("runner_commands", { token: seat.token, list });
@@ -846,11 +897,11 @@ export async function runLoop({ pollMs = 2000 } = {}) {
846
897
  // Only one connection runs on a computer. A second one would wipe the first one's work folder under it.
847
898
  const lock = join(home, "runner.pid");
848
899
  const old = runningConnection();
849
- if (old && old !== process.pid) { try { process.kill(old); log(`ended the connection that was already running (${old})`); } catch {} }
900
+ if (old && old !== process.pid) { endConnection(old); log(`ended the connection that was already running (${old})`); }
850
901
  writeFileSync(lock, `${process.pid} ${Date.now()}`);
851
902
  const unlock = () => { try { if (runningConnection() === process.pid) rmSync(lock, { force: true }); } catch {} };
852
- process.on("exit", unlock);
853
- for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(sig, () => { unlock(); process.exit(0); });
903
+ process.on("exit", () => { stopAll(); unlock(); });
904
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(sig, () => { stopAll(); unlock(); process.exit(0); });
854
905
  // Starting with no network yet (right after sign-in) is normal: keep trying. A table that took this connection
855
906
  // off is skipped, and the others carry on.
856
907
  for (const s of seats) {