sumo-agents 0.0.0-stage → 0.3.0
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/AGENTS.md +38 -0
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/bin/sumo.mjs +33 -0
- package/guides/delegation.md +33 -0
- package/guides/feature.md +14 -0
- package/guides/fix.md +14 -0
- package/guides/memory.md +23 -0
- package/guides/projects.md +27 -0
- package/guides/review.md +16 -0
- package/guides/workflows.md +26 -0
- package/logo.txt +19 -0
- package/package.json +42 -4
- package/prompts/agent.md +7 -0
- package/prompts/dream.md +13 -0
- package/prompts/scribe.md +21 -0
- package/spinner.txt +90 -0
- package/src/advisor.mjs +59 -0
- package/src/apply.mjs +368 -0
- package/src/auth.mjs +80 -0
- package/src/card.mjs +72 -0
- package/src/catalog.mjs +167 -0
- package/src/chat.mjs +1162 -0
- package/src/cli.mjs +815 -0
- package/src/cost.mjs +128 -0
- package/src/db.mjs +384 -0
- package/src/dream.mjs +97 -0
- package/src/editor.mjs +198 -0
- package/src/export.mjs +132 -0
- package/src/guard.mjs +121 -0
- package/src/guides.mjs +86 -0
- package/src/herdr.mjs +117 -0
- package/src/hooks.mjs +270 -0
- package/src/images.mjs +89 -0
- package/src/jobs.mjs +1184 -0
- package/src/jobtools.mjs +82 -0
- package/src/local-server.mjs +169 -0
- package/src/lock.mjs +45 -0
- package/src/loop.mjs +838 -0
- package/src/mcp.mjs +604 -0
- package/src/memory.mjs +400 -0
- package/src/model.mjs +270 -0
- package/src/page.html +304 -0
- package/src/page.mjs +135 -0
- package/src/paths.mjs +33 -0
- package/src/prime.mjs +177 -0
- package/src/projects.mjs +232 -0
- package/src/recall.mjs +45 -0
- package/src/redact.mjs +173 -0
- package/src/render.mjs +45 -0
- package/src/route.mjs +287 -0
- package/src/sandbox.mjs +173 -0
- package/src/scan.mjs +204 -0
- package/src/scribe.mjs +349 -0
- package/src/sessions.mjs +371 -0
- package/src/setup.mjs +528 -0
- package/src/sqlite.mjs +66 -0
- package/src/text.mjs +97 -0
- package/src/tools.mjs +987 -0
- package/src/transcript.mjs +106 -0
- package/src/tty.mjs +529 -0
- package/src/ui.mjs +1363 -0
- package/src/verify.mjs +369 -0
- package/src/web.mjs +49 -0
- package/src/workflows.mjs +270 -0
- package/src/worktree.mjs +128 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { createContext, Script } from 'node:vm';
|
|
2
|
+
import { head, stem, words } from './text.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A taught workflow is worth nothing if it is only remembered when someone
|
|
6
|
+
* thinks to look. These are the two moments it has to show up by itself, both
|
|
7
|
+
* decided by plain word matching — no model, no tokens until one fires:
|
|
8
|
+
*
|
|
9
|
+
* the user asks for the thing → the steps ride in with their message
|
|
10
|
+
* the agent is about to do the thing → the command is held back until the
|
|
11
|
+
* steps are in front of it
|
|
12
|
+
*
|
|
13
|
+
* A workflow says which commands it comes before in one of two ways. Stated: a
|
|
14
|
+
* `gate`, a regular expression written when the workflow was taught — precise,
|
|
15
|
+
* and the only thing consulted when present. Guessed: failing that, every word
|
|
16
|
+
* of its cue turning up in the command — crude, so it needs two words to count.
|
|
17
|
+
*
|
|
18
|
+
* The second moment exists because of a real failure: an agent that had been
|
|
19
|
+
* taught "before creating a PR, do X and Y" committed, pushed and reached for
|
|
20
|
+
* `pr create` deep in a long task, with the workflow listed at the top of its
|
|
21
|
+
* context the whole time. A line in a prompt is a request. A gate is not.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const BODY_MAX = 3000;
|
|
25
|
+
/** One word ("ship") turns up in commands by accident; two ("create", "pr") do not. */
|
|
26
|
+
const MIN_WORDS_TO_GATE_A_COMMAND = 2;
|
|
27
|
+
|
|
28
|
+
/** "PR" and "pull request" are one thing said two ways, and either may be in the cue or the message. */
|
|
29
|
+
const stemsOf = (text) => new Set(words(text.replace(/pull[\s-]+requests?/gi, 'pr')).map(stem));
|
|
30
|
+
|
|
31
|
+
/** The words that mean "this workflow": its cue, or its title when it has none. */
|
|
32
|
+
function triggerStems(workflow) {
|
|
33
|
+
return [...stemsOf(workflow.cue || workflow.title)];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function key(workflow, agentId) {
|
|
37
|
+
// A sub-agent has its own context: steps shown to the main agent were never shown to it.
|
|
38
|
+
return `workflow:m${workflow.id}${agentId ? `@${agentId}` : ''}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Active workflows in scope whose trigger words all appear in `text`, and whose
|
|
43
|
+
* steps this agent has not been given yet in this session. Marks them as given.
|
|
44
|
+
*/
|
|
45
|
+
export function claim(db, { sessionId, agentId = null, text, scopes, forCommand = false, now }) {
|
|
46
|
+
const have = stemsOf(text);
|
|
47
|
+
const given = new Set(db.prepare('SELECT slug FROM session_injections WHERE session_id = ?').all(sessionId).map((r) => r.slug));
|
|
48
|
+
const rows = db
|
|
49
|
+
.prepare(`SELECT * FROM memories WHERE type = 'procedure' AND state = 'active' AND scope IN (${scopes.map(() => '?').join(', ')}) ORDER BY id`)
|
|
50
|
+
.all(...scopes);
|
|
51
|
+
|
|
52
|
+
const found = rows.filter((w) => !given.has(key(w, agentId)) && (forCommand && w.gate ? gateMatches(w.gate, text) : cueMatches(w, have, forCommand)));
|
|
53
|
+
|
|
54
|
+
for (const w of found) {
|
|
55
|
+
db.prepare('INSERT OR REPLACE INTO session_injections (session_id, slug, ts) VALUES (?, ?, ?)').run(sessionId, key(w, agentId), now);
|
|
56
|
+
db.prepare('UPDATE memories SET hits = hits + 1, last_hit_at = ? WHERE id = ?').run(now, w.id);
|
|
57
|
+
}
|
|
58
|
+
return found;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function cueMatches(workflow, have, forCommand) {
|
|
62
|
+
const need = triggerStems(workflow);
|
|
63
|
+
return need.length >= (forCommand ? MIN_WORDS_TO_GATE_A_COMMAND : 1) && need.every((s) => have.has(s));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const escaped = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
67
|
+
|
|
68
|
+
/** Where an unquoted word ends for the shell. */
|
|
69
|
+
const WORD_END = /[\s;|&<>()]/;
|
|
70
|
+
const SUMO_CALL = /^\s*(\S*\/)?sumo(\s|$)/;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The delimiter a heredoc opener names: the word after `<<` or `<<-` with its quotes removed, as the shell reads it,
|
|
74
|
+
* so `E"O"F`, `E\OF` and `"EOF"x` mean EOF, EOF and EOFx. null when there is no word, or a quote in it never closes
|
|
75
|
+
* on the line — then the opener is no heredoc, and its characters are read as any others.
|
|
76
|
+
*/
|
|
77
|
+
function heredocOpener(command, at) {
|
|
78
|
+
let i = at + /^<<-?[\t ]*/.exec(command.slice(at))[0].length;
|
|
79
|
+
let delimiter = '';
|
|
80
|
+
// Any quoting of the delimiter keeps the body as written; without it the shell expands the body's substitutions.
|
|
81
|
+
let quoted = false;
|
|
82
|
+
while (i < command.length && !WORD_END.test(command[i])) {
|
|
83
|
+
const ch = command[i];
|
|
84
|
+
if (ch === "'" || ch === '"') {
|
|
85
|
+
const close = command.indexOf(ch, i + 1);
|
|
86
|
+
if (close === -1 || command.slice(i, close).includes('\n')) return null;
|
|
87
|
+
delimiter += command.slice(i + 1, close);
|
|
88
|
+
quoted = true;
|
|
89
|
+
i = close + 1;
|
|
90
|
+
} else if (ch === '\\') {
|
|
91
|
+
delimiter += command[i + 1] ?? '';
|
|
92
|
+
quoted = true;
|
|
93
|
+
i += 2;
|
|
94
|
+
} else {
|
|
95
|
+
delimiter += ch;
|
|
96
|
+
i++;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return delimiter ? { delimiter, quoted, length: i - at } : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The span of the substitution or arithmetic opening at `at` (`$(`, `((` or a backtick): where it ends — a quote
|
|
104
|
+
* inside it is skipped, so a `)` in one does not close it — and, for a command substitution, the command inside.
|
|
105
|
+
*/
|
|
106
|
+
function substitution(command, at) {
|
|
107
|
+
if (command[at] === '`') {
|
|
108
|
+
let j = at + 1;
|
|
109
|
+
for (; j < command.length && command[j] !== '`'; j++) if (command[j] === '\\') j++;
|
|
110
|
+
return { end: Math.min(j, command.length - 1), inner: command.slice(at + 1, j) };
|
|
111
|
+
}
|
|
112
|
+
const arithmetic = command.startsWith('$((', at) || command.startsWith('((', at);
|
|
113
|
+
const open = command.indexOf('(', at);
|
|
114
|
+
let depth = 0;
|
|
115
|
+
let quote = null;
|
|
116
|
+
let j = open;
|
|
117
|
+
for (; j < command.length; j++) {
|
|
118
|
+
const ch = command[j];
|
|
119
|
+
if (quote) {
|
|
120
|
+
if (ch === '\\' && quote === '"') j++;
|
|
121
|
+
else if (ch === quote) quote = null;
|
|
122
|
+
} else if (ch === "'" || ch === '"') quote = ch;
|
|
123
|
+
else if (ch === '\\') j++;
|
|
124
|
+
else if (ch === '(') depth++;
|
|
125
|
+
else if (ch === ')' && --depth === 0) break;
|
|
126
|
+
}
|
|
127
|
+
const end = Math.min(j, command.length - 1);
|
|
128
|
+
return { end, inner: arithmetic ? null : command.slice(open + 1, end) };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The commands an unquoted heredoc body substitutes in: `$(…)` and backticks, not ones escaped with a backslash. */
|
|
132
|
+
function substitutionsIn(body) {
|
|
133
|
+
const found = [];
|
|
134
|
+
for (let i = 0; i < body.length; i++) {
|
|
135
|
+
if (body[i] === '\\') i++;
|
|
136
|
+
else if (body.startsWith('$(', i) && !body.startsWith('$((', i)) {
|
|
137
|
+
const { end, inner } = substitution(body, i);
|
|
138
|
+
if (inner !== null) found.push(inner);
|
|
139
|
+
i = end;
|
|
140
|
+
} else if (body[i] === '`') {
|
|
141
|
+
const { end, inner } = substitution(body, i);
|
|
142
|
+
found.push(inner);
|
|
143
|
+
i = end;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return found;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* What is left of a shell command once its calls to `sumo` are taken out. Teaching or reading a workflow names
|
|
151
|
+
* its own cue, so `sumo` is never held back by what it manages — but only `sumo` is let through: in
|
|
152
|
+
* `sumo help; gh pr create` the second command is still judged. The command is cut where the shell would start
|
|
153
|
+
* another one (; | & and a new line), outside quotes; a heredoc stays with the call that opens it. What a sumo
|
|
154
|
+
* call substitutes in (`$(…)` or backticks, inside double quotes too) is run by the shell, so it is judged on its
|
|
155
|
+
* own; what the call merely quotes is not.
|
|
156
|
+
*/
|
|
157
|
+
export function withoutSumoCalls(command) {
|
|
158
|
+
const parts = [];
|
|
159
|
+
let part = '';
|
|
160
|
+
let subs = [];
|
|
161
|
+
let quote = null; // "'", '"', or "$'" — ANSI-C quoting, where a backslash escapes the quote
|
|
162
|
+
let heredocs = [];
|
|
163
|
+
let opened = null;
|
|
164
|
+
const flush = () => {
|
|
165
|
+
parts.push({ text: part, subs });
|
|
166
|
+
part = '';
|
|
167
|
+
subs = [];
|
|
168
|
+
};
|
|
169
|
+
const takeSubstitution = (i) => {
|
|
170
|
+
const { end, inner } = substitution(command, i);
|
|
171
|
+
if (inner !== null) subs.push(inner);
|
|
172
|
+
part += command.slice(i, end + 1);
|
|
173
|
+
return end;
|
|
174
|
+
};
|
|
175
|
+
for (let i = 0; i < command.length; i++) {
|
|
176
|
+
const ch = command[i];
|
|
177
|
+
if (quote) {
|
|
178
|
+
if (quote === '"' && (command.startsWith('$(', i) || ch === '`')) {
|
|
179
|
+
i = takeSubstitution(i); // still run by the shell inside double quotes
|
|
180
|
+
} else {
|
|
181
|
+
part += ch;
|
|
182
|
+
if (ch === '\\' && quote !== "'") part += command[++i] ?? '';
|
|
183
|
+
else if (ch === quote.at(-1)) quote = null;
|
|
184
|
+
}
|
|
185
|
+
} else if (ch === '\\') {
|
|
186
|
+
part += ch + (command[++i] ?? '');
|
|
187
|
+
} else if (command.startsWith("$'", i)) {
|
|
188
|
+
quote = "$'";
|
|
189
|
+
part += "$'";
|
|
190
|
+
i++;
|
|
191
|
+
} else if (ch === "'" || ch === '"') {
|
|
192
|
+
quote = ch;
|
|
193
|
+
part += ch;
|
|
194
|
+
} else if (command.startsWith('$(', i) || command.startsWith('((', i) || ch === '`' || ((ch === '<' || ch === '>') && command[i + 1] === '(')) {
|
|
195
|
+
// `<(…)` and `>(…)` are run by the shell as surely as `$(…)` is.
|
|
196
|
+
// A substitution or arithmetic: a `<<` inside is a shift, or the substitution's own, never this command's heredoc.
|
|
197
|
+
i = takeSubstitution(i);
|
|
198
|
+
} else if (command.startsWith('$[', i)) {
|
|
199
|
+
// The old spelling of arithmetic: opaque to its closing bracket.
|
|
200
|
+
const close = command.indexOf(']', i + 1);
|
|
201
|
+
const end = close === -1 ? command.length - 1 : close;
|
|
202
|
+
part += command.slice(i, end + 1);
|
|
203
|
+
i = end;
|
|
204
|
+
} else if (ch === '#' && (i === 0 || /[\s;&|(]/.test(command[i - 1]))) {
|
|
205
|
+
// A comment runs to the end of its line, and a `<<` in it opens nothing; the line's end is still read below.
|
|
206
|
+
const close = command.indexOf('\n', i);
|
|
207
|
+
const end = close === -1 ? command.length : close;
|
|
208
|
+
part += command.slice(i, end);
|
|
209
|
+
i = end - 1;
|
|
210
|
+
} else if (ch === '<' && command[i + 1] === '<' && command[i + 2] !== '<' && command[i - 1] !== '<' && (opened = heredocOpener(command, i))) {
|
|
211
|
+
heredocs.push(opened);
|
|
212
|
+
part += command.slice(i, i + opened.length);
|
|
213
|
+
i += opened.length - 1;
|
|
214
|
+
} else if (ch === '\n' && heredocs.length > 0) {
|
|
215
|
+
// Each body runs to a line that is its delimiter alone, and belongs to the call that opened it.
|
|
216
|
+
let at = i;
|
|
217
|
+
for (const { delimiter: end, quoted } of heredocs) {
|
|
218
|
+
const rest = command.slice(at + 1);
|
|
219
|
+
const close = new RegExp(`^[\\t ]*${escaped(end)}[\\t ]*$`, 'm').exec(rest);
|
|
220
|
+
const last = at + (close ? close.index + close[0].length : rest.length);
|
|
221
|
+
if (!quoted) subs.push(...substitutionsIn(rest.slice(0, close ? close.index : rest.length)));
|
|
222
|
+
part += command.slice(at, last + 1);
|
|
223
|
+
at = last + 1;
|
|
224
|
+
if (at >= command.length) break;
|
|
225
|
+
}
|
|
226
|
+
heredocs = [];
|
|
227
|
+
i = at - 1;
|
|
228
|
+
} else if (ch === ';' || ch === '|' || ch === '\n' || (ch === '&' && !'<>'.includes(command[i - 1] ?? '') && command[i + 1] !== '>')) {
|
|
229
|
+
flush();
|
|
230
|
+
} else {
|
|
231
|
+
part += ch;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
flush();
|
|
235
|
+
// A sumo call is judged only by what it runs: the commands it substitutes in, which may hold sumo calls of their own.
|
|
236
|
+
return parts
|
|
237
|
+
.flatMap((p) => (SUMO_CALL.test(p.text) ? p.subs.map(withoutSumoCalls) : [p.text]))
|
|
238
|
+
.filter((text) => text.trim())
|
|
239
|
+
.join('\n');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** How long one pattern may take over one command. A regular expression can take minutes over forty characters; a turn must not wait for it. */
|
|
243
|
+
const MATCH_MS = 50;
|
|
244
|
+
const matcher = createContext({});
|
|
245
|
+
const matching = new Script('pattern.test(text)');
|
|
246
|
+
|
|
247
|
+
/** Whether the pattern matches the text: true, false, or null when it ran out of time. */
|
|
248
|
+
export function matchWithin(pattern, text, ms = MATCH_MS) {
|
|
249
|
+
matcher.pattern = pattern;
|
|
250
|
+
matcher.text = text;
|
|
251
|
+
try {
|
|
252
|
+
return matching.runInContext(matcher, { timeout: ms });
|
|
253
|
+
} catch {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function gateMatches(gate, command) {
|
|
259
|
+
try {
|
|
260
|
+
// A gate that runs out of time, like one that cannot be read, holds nothing back.
|
|
261
|
+
return matchWithin(new RegExp(gate, 'i'), command) === true;
|
|
262
|
+
} catch {
|
|
263
|
+
return false; // checked when it was saved; if it is somehow bad, a gate that cannot be read holds nothing back
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function renderWorkflow(w) {
|
|
268
|
+
const body = w.body.length > BODY_MAX ? `${head(w.body, BODY_MAX)}\n… (the rest: sumo show m${w.id})` : w.body;
|
|
269
|
+
return `<workflow m${w.id} "${w.title}">\n${body}\n</workflow>`;
|
|
270
|
+
}
|
package/src/worktree.mjs
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
|
+
import { copyFileSync, cpSync, lstatSync, mkdirSync, rmSync, statSync, symlinkSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { DIFF } from './verify.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A worker's own git worktree, for when another worker already has the project's tree to itself. It is made from the
|
|
8
|
+
* project as it stands — uncommitted edits and untracked files included — without touching the user's files, index or
|
|
9
|
+
* branches, and what the work changed is brought back to the project at the end. Nothing here knows about jobs.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Sumo's own git calls: no hook of the user's runs, nothing is signed, and a commit has an author where git has no identity. */
|
|
13
|
+
const OWN = ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', '-c', 'user.name=sumo', '-c', 'user.email=sumo@localhost'];
|
|
14
|
+
|
|
15
|
+
const git = (root, args) => execFileSync('git', ['-C', root, ...OWN, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024 }).trim();
|
|
16
|
+
/** How a git command that reads a patch on stdin went: whether it succeeded, and the first lines of what it said, on one line. */
|
|
17
|
+
const fed = (root, args, patch, env = {}) => {
|
|
18
|
+
const run = spawnSync('git', ['-C', root, ...OWN, ...args], { input: patch, env: { ...process.env, ...env }, stdio: ['pipe', 'ignore', 'pipe'], encoding: 'utf8' });
|
|
19
|
+
return { ok: run.status === 0, said: (run.stderr ?? '').split('\n').map((l) => l.trim()).filter(Boolean).slice(0, 3).join('; ') };
|
|
20
|
+
};
|
|
21
|
+
/** The paths a NUL-separated git listing names. */
|
|
22
|
+
const listed = (out) => out.split('\0').filter(Boolean);
|
|
23
|
+
|
|
24
|
+
/** The folders at a project's top level its installed dependencies live in — git ignores them, so a tree is made without them. */
|
|
25
|
+
const DEPENDENCIES = ['node_modules', '.venv', 'venv'];
|
|
26
|
+
|
|
27
|
+
const isDir = (path) => {
|
|
28
|
+
try {
|
|
29
|
+
return statSync(path).isDirectory();
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/** Whether anything is at a path, a link to nothing included. */
|
|
35
|
+
const taken = (path) => {
|
|
36
|
+
try {
|
|
37
|
+
return Boolean(lstatSync(path));
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Makes the tree at `top`: `git stash create` captures the tracked edits in a commit nobody points at (none: the head),
|
|
45
|
+
* the tree is checked out from it detached, and what git does not track is copied in and committed there, on the tree's
|
|
46
|
+
* own head — so the change brought back is the work's, and nothing the user already had. A project in a subdirectory of
|
|
47
|
+
* its repository works in the same subdirectory of the tree: that is `path`. The project's installed dependencies that
|
|
48
|
+
* exist are linked in, not copied, so its checks run there: `linked` names them.
|
|
49
|
+
*/
|
|
50
|
+
export function makeTree(root, top) {
|
|
51
|
+
const prefix = git(root, ['rev-parse', '--show-prefix']).replace(/\/$/, '');
|
|
52
|
+
const start = git(root, ['stash', 'create']) || git(root, ['rev-parse', 'HEAD']);
|
|
53
|
+
git(root, ['worktree', 'add', '--detach', top, start]);
|
|
54
|
+
const path = join(top, prefix);
|
|
55
|
+
// An untracked repository inside the project is listed as `dir/`: it is not part of this one, and is left out.
|
|
56
|
+
const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter((f) => f && !f.endsWith('/'));
|
|
57
|
+
for (const file of untracked) {
|
|
58
|
+
mkdirSync(dirname(join(path, file)), { recursive: true });
|
|
59
|
+
cpSync(join(root, file), join(path, file), { verbatimSymlinks: true });
|
|
60
|
+
}
|
|
61
|
+
// A link to the project's own folder: the sandbox follows it out of the job's roots, so the job reads the user's packages and cannot change them.
|
|
62
|
+
const linked = DEPENDENCIES.filter((name) => isDir(join(root, name)) && !taken(join(path, name)));
|
|
63
|
+
for (const name of linked) symlinkSync(join(root, name), join(path, name));
|
|
64
|
+
if (untracked.length > 0 || linked.length > 0) {
|
|
65
|
+
git(top, ['add', '-A']);
|
|
66
|
+
// `node_modules/` in a .gitignore does not match a link of that name, and info/exclude is the user's own, shared by every
|
|
67
|
+
// worktree: the links are committed on the tree's head instead, and marked in its own index as never changing — so whatever
|
|
68
|
+
// the job does to one, an install that puts a folder in its place included, no `git add -A` stages it and no diff shows it.
|
|
69
|
+
const links = linked.map((name) => join(prefix, name));
|
|
70
|
+
if (links.length > 0) git(top, ['add', '-f', '--', ...links]);
|
|
71
|
+
git(top, ['commit', '-q', '--no-verify', '-m', 'what the project held outside git, as it was']);
|
|
72
|
+
if (links.length > 0) git(top, ['update-index', '--skip-worktree', '--', ...links]);
|
|
73
|
+
}
|
|
74
|
+
return { top, path, prefix, base: git(top, ['rev-parse', 'HEAD']), linked };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Everything changed in the tree since it was made, new files included, as git itself writes a diff: with `binary`, whole enough to apply. */
|
|
78
|
+
export function treeDiff({ top, prefix, base }, { binary = false } = {}) {
|
|
79
|
+
git(top, ['add', '-A']);
|
|
80
|
+
return execFileSync('git', ['-C', top, ...DIFF, '--cached', ...(binary ? ['--binary'] : []), base, '--', prefix || '.'], {
|
|
81
|
+
encoding: binary ? 'buffer' : 'utf8',
|
|
82
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
83
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Brings the tree's change back to the project. Straight onto the files first: it applies whole or not at all, touches no
|
|
89
|
+
* index, and the user's uncommitted edits are the very start the work was made from. Where the project has moved since, a
|
|
90
|
+
* three-way merge — tried first on a copy of the index, since one that conflicts leaves its markers in the user's files —
|
|
91
|
+
* unless a file it touches has edits not staged in the project: git refuses a three-way merge over those, whatever the trial
|
|
92
|
+
* said. `scratch` is a folder of sumo's own for that copy. Not applied, `why` is what git said.
|
|
93
|
+
*/
|
|
94
|
+
export function bringBack(root, tree, scratch) {
|
|
95
|
+
const patch = treeDiff(tree, { binary: true });
|
|
96
|
+
if (patch.length === 0) return { applied: false, empty: true };
|
|
97
|
+
const at = git(root, ['rev-parse', '--show-toplevel']);
|
|
98
|
+
const plain = fed(at, ['apply', '--whitespace=nowarn'], patch);
|
|
99
|
+
if (plain.ok) return { applied: true, merged: false };
|
|
100
|
+
const unstaged = new Set(listed(git(at, ['diff', '--name-only', '-z'])));
|
|
101
|
+
const edited = listed(git(tree.top, ['diff', '--cached', '--name-only', '--no-renames', '-z', tree.base, '--', tree.prefix || '.'])).filter((f) => unstaged.has(f));
|
|
102
|
+
if (edited.length > 0) {
|
|
103
|
+
const named = `${edited.slice(0, 5).join(', ')}${edited.length > 5 ? ` and ${edited.length - 5} more` : ''}`;
|
|
104
|
+
return { applied: false, why: `${plain.said} — and ${named} ${edited.length === 1 ? 'has' : 'have'} edits in ${at} not staged, so a three-way merge could not be tried` };
|
|
105
|
+
}
|
|
106
|
+
const index = join(scratch, 'index.try');
|
|
107
|
+
try {
|
|
108
|
+
copyFileSync(git(at, ['rev-parse', '--path-format=absolute', '--git-path', 'index']), index);
|
|
109
|
+
const trial = fed(at, ['apply', '--whitespace=nowarn', '--3way', '--cached'], patch, { GIT_INDEX_FILE: index });
|
|
110
|
+
if (!trial.ok) return { applied: false, why: trial.said };
|
|
111
|
+
const merged = fed(at, ['apply', '--whitespace=nowarn', '--3way'], patch);
|
|
112
|
+
return merged.ok ? { applied: true, merged: true } : { applied: false, why: merged.said };
|
|
113
|
+
} finally {
|
|
114
|
+
rmSync(index, { force: true });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Removes the tree, and git's record of it; a tree git will not let go of is deleted all the same. Neither way follows a
|
|
120
|
+
* link: the project's dependencies linked in (`makeTree`) stay as they are.
|
|
121
|
+
*/
|
|
122
|
+
export function dropTree(root, top) {
|
|
123
|
+
try {
|
|
124
|
+
git(root, ['worktree', 'remove', '--force', top]);
|
|
125
|
+
} catch {
|
|
126
|
+
rmSync(top, { recursive: true, force: true });
|
|
127
|
+
}
|
|
128
|
+
}
|