sumo-agents 0.7.0 → 0.7.2

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/ui.mjs CHANGED
@@ -17,7 +17,7 @@ import { elapsed } from './text.mjs';
17
17
  import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
18
18
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
19
19
  import { ASK_TOOL, BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
20
- import { colourEnabled, createRenderer, explained, flow, fold, glyphs, inline, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, statOf, styles, sunset, tilde, toolView, transcript, untab, VERSION, withoutColourCodes, withSpan, wrap } from './tty.mjs';
20
+ import { colourEnabled, createRenderer, explained, flow, fold, glyphs, inline, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, statOf, styles, sunset, tilde, toolView, transcript, untab, VERSION, visible, withoutColourCodes, withSpan, wrap } from './tty.mjs';
21
21
 
22
22
  /**
23
23
  * The chat on a real terminal. What is finished scrolls away above — what
@@ -632,8 +632,13 @@ function Question({ ask, columns }) {
632
632
  );
633
633
  }
634
634
 
635
- /** One line of a reply; the first of a block carries the mark. */
636
- function Reply({ text, first }) {
635
+ /**
636
+ * One line of a reply; the first of a block carries the mark. A line of code stands at the first column, no mark or
637
+ * indent before it, and whole: the terminal wraps one too long for the window, so what is selected and copied is the
638
+ * line as it was written. Ink cuts nothing a box wider than the window holds.
639
+ */
640
+ function Reply({ text, first, code = false }) {
641
+ if (code) return h(Box, { marginTop: first ? 1 : 0, flexShrink: 0, width: Math.max(1, ...String(text).split('\n').map(visible)) }, h(Text, null, text || ' '));
637
642
  const g = useMarks();
638
643
  // The mark keeps its two columns: a line with a word wider than the window must not squeeze it, or every row after it shifts left.
639
644
  return h(Box, { marginTop: first ? 1 : 0 }, h(Box, { flexShrink: 0 }, h(Text, null, first ? `${g.tool} ` : ' ')), h(Text, null, text || ' '));
@@ -1082,7 +1087,11 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1082
1087
  * An item is drawn apart to be counted, and that sets off a draw of the screen that is waiting, if one is: so an item leaves
1083
1088
  * `unmeasured` only once it is counted, and a draw it sets off keeps the room shut rather than one row too tall.
1084
1089
  */
1085
- const rowsOf = (item) => renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns }).split('\n').length;
1090
+ // A line of code wider than the window is the rows the terminal wraps it to.
1091
+ const rowsOf = (item) =>
1092
+ renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns })
1093
+ .split('\n')
1094
+ .reduce((rows, row) => rows + Math.max(1, Math.ceil(visible(row) / state.columns)), 0);
1086
1095
  const measure = () => {
1087
1096
  while (state.unmeasured.length > 0) {
1088
1097
  if (state.used < state.rows) state.used += rowsOf(state.unmeasured[0]);
@@ -1123,15 +1132,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1123
1132
  }
1124
1133
  redraw();
1125
1134
  };
1126
- /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark. */
1135
+ /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark; a line of code whole. */
1127
1136
  const replyTo = (put) =>
1128
1137
  createRenderer(
1129
- (rendered) => {
1130
- put({ kind: 'text', text: rendered.replace(/\n$/, ''), first: state.fresh });
1138
+ (rendered, { code }) => {
1139
+ put({ kind: 'text', text: rendered.replace(/\n$/, ''), first: state.fresh, code });
1131
1140
  state.fresh = false;
1132
1141
  },
1133
1142
  s,
1134
- { width: state.columns - 3 },
1143
+ { width: state.columns - 3, whole: true },
1135
1144
  );
1136
1145
  /** One entry of the log as the lines this window shows for it. */
1137
1146
  function drawn(entry) {
@@ -2203,7 +2212,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
2203
2212
  { flexDirection: 'column', minHeight: room },
2204
2213
  h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })),
2205
2214
  ...reads.map((item, i) => h(Item, { key: `reads-${i}`, item, columns, s })),
2206
- tail ? h(Reply, { text: tail, first: state.fresh }) : null,
2215
+ tail ? h(Reply, { text: tail, first: state.fresh, code: state.reply.fenced }) : null,
2207
2216
  // In one box of their own, so the lines coming and going never move what follows — the working line keeps its clock.
2208
2217
  h(Box, { flexDirection: 'column' }, ...steps.map((step) => h(Tool, step))),
2209
2218
  // The silence that is said is the model's: while a command, a job or a question is in hand, the wait is not on it.
package/src/verify.mjs CHANGED
@@ -129,14 +129,15 @@ function timeoutMs() {
129
129
  }
130
130
 
131
131
  /** The last lines of a check's log, read from its end rather than whole. */
132
- function tailOf(fd) {
132
+ function checkOutput(fd, failed) {
133
133
  const size = fstatSync(fd).size;
134
134
  const start = Math.max(0, size - OUTPUT_TAIL_BYTES);
135
135
  const bytes = Buffer.alloc(size - start);
136
136
  const lines = bytes.subarray(0, readSync(fd, bytes, 0, bytes.length, start)).toString('utf8').trimEnd().split('\n');
137
137
  // Read from inside a line, the first piece is half of one.
138
138
  if (start > 0 && lines.length > 1) lines.shift();
139
- return lines.slice(-OUTPUT_TAIL_LINES).join('\n');
139
+ const failures = failed && start === 0 ? namedFailures(lines) : [];
140
+ return { output: lines.slice(-OUTPUT_TAIL_LINES).join('\n'), failures };
140
141
  }
141
142
 
142
143
  /** The sandbox a job's process hands down for its checks: the wrap's words, or null — none given, or one that is not a list of words. */
@@ -175,10 +176,10 @@ function runChecks(root, commands, dir, prefix) {
175
176
  const timedOut = run.error?.code === 'ETIMEDOUT';
176
177
  // Whatever it left running goes with it, so nothing writes to the file once it is read.
177
178
  killGroup(run.pid);
178
- const output = tailOf(into);
179
+ const { output, failures } = checkOutput(into, run.status !== 0);
179
180
  ftruncateSync(into);
180
181
  writeSync(into, `$ ${command}\n${output}\n${timedOut ? '\n(stopped: it ran past the time limit)\n' : ''}`, 0);
181
- return { name, command, ok: run.status === 0, status: run.status, timedOut, ms: Date.now() - started, file };
182
+ return { name, command, ok: run.status === 0, failures, status: run.status, timedOut, ms: Date.now() - started, file };
182
183
  } finally {
183
184
  closeSync(into);
184
185
  }
@@ -190,6 +191,33 @@ const FAILURE_LINE = /\b(?:fail(?:s|ed|ing|ures?)?|errors?|not ok)\b|[✗✕✖]
190
191
  /** A time a runner prints, which differs from one run to the next when nothing else does. */
191
192
  const TIMING = /\b\d+(?:\.\d+)?\s?m?s\b/g;
192
193
 
194
+ /** Named cases printed by common test reporters. A wrapper's exit message or a failure count alone identifies no test. */
195
+ function namedFailures(lines) {
196
+ const names = [];
197
+ for (const raw of lines) {
198
+ const line = raw.replace(/\x1b\[[0-9;]*m/g, '').trim();
199
+ const match = /^(?:not ok(?: \d+)? - |--- FAIL: |(?:FAIL|FAILED) +|[✗✕✖×●] +)(.+)$/.exec(line)
200
+ ?? /^test (.+?) \.\.\. FAILED$/.exec(line);
201
+ if (match) {
202
+ const name = match[1].replace(/\s*\(\d+(?:\.\d+)?\s?m?s\)$/, '').trim();
203
+ if (name) names.push(createHash('sha256').update(name).digest('hex'));
204
+ }
205
+ }
206
+ return names;
207
+ }
208
+
209
+ /** A new failure must not be forgiven just because the same command was red before. Count duplicate case names as well. */
210
+ function explainedBy(current, previous) {
211
+ if (!previous?.failures?.length || !current.failures.length || current.timedOut || previous.timedOut || previous.status !== current.status) return false;
212
+ const counts = new Map();
213
+ for (const name of previous.failures) counts.set(name, (counts.get(name) ?? 0) + 1);
214
+ for (const name of current.failures) {
215
+ if (!counts.get(name)) return false;
216
+ counts.set(name, counts.get(name) - 1);
217
+ }
218
+ return true;
219
+ }
220
+
193
221
  /** How a run of a check ended: its exit status and the lines that name a failure, without their times. Two runs that agree on it failed the same way. */
194
222
  const endedAs = (run) =>
195
223
  `${run.status}\n${[...new Set(readFileSync(run.file, 'utf8').split('\n').filter((l) => FAILURE_LINE.test(l)).map((l) => l.replace(TIMING, '').trim()))].sort().join('\n')}`;
@@ -224,7 +252,12 @@ export function takeBaseline(root, snap, dir) {
224
252
  }
225
253
  const checks = runChecks(root, verifyCommands(root), dir, 'baseline');
226
254
  const again = runAgain(root, checks.filter((c) => !c.ok), dir);
227
- return { checks: checks.map((c) => (again.has(c) && endedAs(again.get(c)) !== endedAs(c) ? { ...c, flaky: true, again: again.get(c).file } : c)) };
255
+ return { checks: checks.map((check) => {
256
+ const repeat = again.get(check);
257
+ if (!repeat || endedAs(repeat) === endedAs(check)) return check;
258
+ const { status, failures, timedOut } = repeat;
259
+ return { ...check, flaky: true, again: repeat.file, repeat: { status, failures, timedOut } };
260
+ }) };
228
261
  }
229
262
 
230
263
  /**
@@ -269,6 +302,7 @@ export function verify(root, { snap, baseline, testsMayChange, declared }, dir,
269
302
  const blocking = [];
270
303
  const flags = [];
271
304
  const notes = [];
305
+ const inconclusive = [];
272
306
  const beforeChecks = snap && stillThere(root, snap) ? changesSince(root, snap).fingerprint : null;
273
307
 
274
308
  // The checks that judged the start judge the end: one no longer run, or rewritten, is not part of the change.
@@ -286,11 +320,15 @@ export function verify(root, { snap, baseline, testsMayChange, declared }, dir,
286
320
  const before = new Map((baseline ?? []).map((c) => [c.command, c]));
287
321
  const ran = runChecks(root, commands, dir, 'verify');
288
322
  // One that passed when the job began and fails now is run once more before it is held against the job: passing then, it is flaky.
289
- // One recorded flaky at the start is not run again: whatever it says, it does not refuse DONE on its own.
323
+ // A baseline failure can explain only failures actually observed in its recorded runs.
290
324
  const again = runAgain(root, ran.filter((c) => !c.ok && before.get(c.command)?.ok), dir);
291
325
  const checks = ran.map((c) => {
292
326
  const was = before.get(c.command);
293
- const state = c.ok ? 'pass' : was?.flaky || again.get(c)?.ok ? 'flaky' : was && !was.ok ? 'already-failing' : 'fail';
327
+ let state = c.ok ? 'pass' : 'fail';
328
+ if (!c.ok && again.get(c)?.ok) state = 'flaky';
329
+ if (!c.ok && was && !was.ok && (explainedBy(c, was) || explainedBy(c, was.repeat))) {
330
+ state = was.flaky ? 'flaky' : 'already-failing';
331
+ }
294
332
  if (state === 'flaky') {
295
333
  flags.push(
296
334
  was.flaky
@@ -298,10 +336,16 @@ export function verify(root, { snap, baseline, testsMayChange, declared }, dir,
298
336
  : `\`${c.command}\` failed, then passed when run again — flaky, so DONE is not refused on it; read ${c.file}`,
299
337
  );
300
338
  }
339
+ if (state === 'fail' && was && !was.ok && !c.timedOut && (!c.failures.length || !was.failures?.length)) {
340
+ state = 'inconclusive';
341
+ inconclusive.push(`\`${c.command}\` failed, but its failing cases could not be compared; see ${was.file} and ${c.file}`);
342
+ }
301
343
  if (state === 'fail') {
302
344
  const why = c.timedOut ? 'ran past the time limit' : 'fails';
303
345
  blocking.push(
304
- was
346
+ was && !was.ok
347
+ ? `\`${c.command}\` ${why} with a new failure or one the baseline cannot identify; compare ${was.file} with ${c.file}`
348
+ : was
305
349
  ? `\`${c.command}\` ${why}, and it passed when this job began — read ${c.file}`
306
350
  : `\`${c.command}\` ${why}, and no baseline was taken before the work, so the failure counts as this job's — read ${c.file}`,
307
351
  );
@@ -310,7 +354,7 @@ export function verify(root, { snap, baseline, testsMayChange, declared }, dir,
310
354
  if (state === 'already-failing') flags.push(`\`${c.command}\` was already failing when this job began; compare ${was.file} with ${c.file} to see nothing new broke`);
311
355
  return { name: c.name, command: c.command, state, file: c.file };
312
356
  });
313
- if (checks.length === 0) notes.push('this project declares no check, test, lint or typecheck command — nothing was run');
357
+ if (checks.length === 0) inconclusive.push('this project declares no check, test, lint or typecheck command — nothing was run');
314
358
 
315
359
  let fingerprint = null;
316
360
  if (snap && !stillThere(root, snap)) {
@@ -338,7 +382,7 @@ export function verify(root, { snap, baseline, testsMayChange, declared }, dir,
338
382
  notes.push('not a git repository — what changed, and whether existing tests were touched, could not be checked');
339
383
  }
340
384
 
341
- return { at: now, ok: blocking.length === 0, fingerprint, checks, blocking, flags, notes };
385
+ return { version: 2, at: now, ok: blocking.length === 0 && inconclusive.length === 0, fingerprint, checks, blocking, inconclusive, flags, notes };
342
386
  }
343
387
 
344
388
  /** git's own summary of what changed in tracked files since the snapshot: a line a file, at most `count` of them, then its totals. Empty when git cannot say. */
@@ -371,9 +415,10 @@ export function writeChanges(root, snap, file) {
371
415
 
372
416
  /** One line per check, for a status line or a report. */
373
417
  export function verdictLines(verdict) {
374
- const words = { pass: 'passed', fail: 'FAILED', 'already-failing': 'was already failing', flaky: 'was flaky' };
418
+ const words = { pass: 'passed', fail: 'FAILED', 'already-failing': 'was already failing', flaky: 'was flaky', inconclusive: 'was inconclusive' };
375
419
  return [
376
420
  ...verdict.checks.map((c) => `\`${c.command}\` ${words[c.state]}`),
421
+ ...(verdict.inconclusive ?? []).map((reason) => `unverified: ${reason}`),
377
422
  ...verdict.blocking.map((b) => `blocking: ${b}`),
378
423
  ...verdict.flags.map((f) => `look at: ${f}`),
379
424
  ...verdict.notes.map((n) => `note: ${n}`),
package/src/worktree.mjs CHANGED
@@ -1,6 +1,7 @@
1
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';
2
+ import { copyFileSync, cpSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { DIFF } from './verify.mjs';
5
6
 
6
7
  /**
@@ -74,6 +75,83 @@ export function makeTree(root, top) {
74
75
  return { top, path, prefix, base: git(top, ['rev-parse', 'HEAD']), linked };
75
76
  }
76
77
 
78
+ const within = (root, path) => {
79
+ const rel = relative(root, path);
80
+ return rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
81
+ };
82
+
83
+ /** Inspect package-manager links, including scoped packages and pnpm's virtual store. */
84
+ function nodeLoadsOriginal(modules, repository, candidate) {
85
+ const installed = realpathSync(modules);
86
+ const queue = [modules];
87
+ const seen = new Set();
88
+ while (queue.length) {
89
+ const dir = queue.pop();
90
+ const real = realpathSync(dir);
91
+ if (seen.has(real)) continue;
92
+ seen.add(real);
93
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
94
+ const path = join(dir, entry.name);
95
+ if (entry.name === '.pnpm' && entry.isDirectory()) {
96
+ for (const name of readdirSync(path)) if (isDir(join(path, name, 'node_modules'))) queue.push(join(path, name, 'node_modules'));
97
+ } else if (entry.name.startsWith('@') && entry.isDirectory()) queue.push(path);
98
+ else if (entry.isSymbolicLink()) {
99
+ const target = realpathSync(path);
100
+ if (within(repository, target) && !within(installed, target) && !within(candidate, target)) return true;
101
+ } else if (entry.isDirectory() && isDir(join(path, 'node_modules'))) queue.push(join(path, 'node_modules'));
102
+ }
103
+ }
104
+ return false;
105
+ }
106
+
107
+ /** Common editable-install formats: PEP 610/660 metadata, path-based .pth files and legacy egg links. */
108
+ function pythonLoadsOriginal(env, repository, candidate, shared) {
109
+ function loadsOriginal(path) {
110
+ const target = realpathSync(path);
111
+ return within(repository, target) && !within(candidate, target);
112
+ }
113
+ const lib = join(env, 'lib');
114
+ const sites = [join(env, 'Lib', 'site-packages')];
115
+ if (isDir(lib)) for (const name of readdirSync(lib)) sites.push(join(lib, name, 'site-packages'));
116
+ for (const site of sites.filter(isDir)) {
117
+ for (const name of readdirSync(site)) {
118
+ const file = join(site, name);
119
+ if (shared && (name.endsWith('.egg-link') || name.startsWith('__editable__'))) return true;
120
+ if (name.endsWith('.egg-link') || name.endsWith('.pth')) {
121
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
122
+ const path = line.trim();
123
+ if (isAbsolute(path) && taken(path) && loadsOriginal(path)) return true;
124
+ }
125
+ }
126
+ if (name.endsWith('.dist-info') && taken(join(file, 'direct_url.json'))) {
127
+ const metadata = JSON.parse(readFileSync(join(file, 'direct_url.json'), 'utf8'));
128
+ if (metadata.dir_info?.editable && (shared || (metadata.url?.startsWith('file:') && loadsOriginal(fileURLToPath(metadata.url))))) return true;
129
+ }
130
+ }
131
+ }
132
+ return false;
133
+ }
134
+
135
+ /** An isolated job cannot be graded using source reached through the original checkout's installed dependencies. */
136
+ export function sharedSourceDependencies(tree, project) {
137
+ if (!tree) return [];
138
+ const shared = [];
139
+ for (const name of DEPENDENCIES) {
140
+ const dependency = join(tree.path, name);
141
+ if (!taken(dependency)) continue;
142
+ try {
143
+ const original = join(project, name);
144
+ const sharedInstall = taken(original) && realpathSync(dependency) === realpathSync(original);
145
+ const candidate = realpathSync(tree.top);
146
+ const repository = realpathSync(git(project, ['rev-parse', '--show-toplevel']));
147
+ if (name === 'node_modules' ? nodeLoadsOriginal(dependency, repository, candidate) : pythonLoadsOriginal(dependency, repository, candidate, sharedInstall)) shared.push(name);
148
+ } catch {
149
+ shared.push(name); // Unreadable installation or link: its source cannot be verified.
150
+ }
151
+ }
152
+ return shared;
153
+ }
154
+
77
155
  /** 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
156
  export function treeDiff({ top, prefix, base }, { binary = false } = {}) {
79
157
  git(top, ['add', '-A']);
@@ -91,8 +169,7 @@ export function treeDiff({ top, prefix, base }, { binary = false } = {}) {
91
169
  * unless a file it touches has edits not staged in the project: git refuses a three-way merge over those, whatever the trial
92
170
  * said. `scratch` is a folder of sumo's own for that copy. Not applied, `why` is what git said.
93
171
  */
94
- export function bringBack(root, tree, scratch) {
95
- const patch = treeDiff(tree, { binary: true });
172
+ export function bringBack(root, tree, scratch, patch = treeDiff(tree, { binary: true })) {
96
173
  if (patch.length === 0) return { applied: false, empty: true };
97
174
  const at = git(root, ['rev-parse', '--show-toplevel']);
98
175
  const plain = fed(at, ['apply', '--whitespace=nowarn'], patch);