next-issue 2.21.1 → 3.0.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.
Files changed (73) hide show
  1. package/README.md +89 -124
  2. package/dist/agent-reply.mjs +13 -0
  3. package/dist/agent-session.mjs +56 -0
  4. package/dist/agents.mjs +47 -88
  5. package/dist/args.mjs +26 -31
  6. package/dist/base-checks.mjs +37 -0
  7. package/dist/budget.mjs +16 -0
  8. package/dist/check-poll.mjs +73 -0
  9. package/dist/checks.mjs +67 -0
  10. package/dist/children.mjs +52 -0
  11. package/dist/cli.mjs +25 -15
  12. package/dist/command-records.mjs +15 -0
  13. package/dist/config-fields.mjs +32 -0
  14. package/dist/config.mjs +36 -71
  15. package/dist/conflict.mjs +43 -42
  16. package/dist/durations.mjs +37 -0
  17. package/dist/enter-review.mjs +13 -0
  18. package/dist/errors.mjs +20 -0
  19. package/dist/exec.mjs +71 -107
  20. package/dist/files.mjs +28 -0
  21. package/dist/fix.mjs +61 -50
  22. package/dist/gate.mjs +31 -43
  23. package/dist/gh.mjs +55 -0
  24. package/dist/git-commit.mjs +36 -0
  25. package/dist/git-land.mjs +30 -0
  26. package/dist/git-merge.mjs +42 -0
  27. package/dist/git.mjs +42 -166
  28. package/dist/github.mjs +32 -386
  29. package/dist/gitignore.mjs +13 -0
  30. package/dist/hand-over-comments.mjs +81 -0
  31. package/dist/handover.mjs +62 -103
  32. package/dist/implement.mjs +32 -0
  33. package/dist/interrupt.mjs +6 -19
  34. package/dist/job.mjs +28 -17
  35. package/dist/labels.mjs +65 -0
  36. package/dist/land.mjs +66 -0
  37. package/dist/lock.mjs +54 -0
  38. package/dist/logs.mjs +84 -62
  39. package/dist/loop.mjs +12 -37
  40. package/dist/observe.mjs +24 -98
  41. package/dist/open-job.mjs +39 -0
  42. package/dist/pending.mjs +46 -0
  43. package/dist/pipeline.mjs +34 -217
  44. package/dist/poll.mjs +20 -0
  45. package/dist/ports.mjs +18 -3
  46. package/dist/progress.mjs +36 -22
  47. package/dist/prompts.mjs +31 -36
  48. package/dist/protocol.mjs +17 -11
  49. package/dist/prune-runs.mjs +33 -0
  50. package/dist/pull-requests.mjs +60 -0
  51. package/dist/questions.mjs +45 -0
  52. package/dist/records.mjs +3 -0
  53. package/dist/render.mjs +19 -0
  54. package/dist/revert.mjs +27 -0
  55. package/dist/review.mjs +63 -83
  56. package/dist/run-logs.mjs +23 -0
  57. package/dist/run.mjs +59 -58
  58. package/dist/serve.mjs +46 -214
  59. package/dist/setup.mjs +2 -5
  60. package/dist/skip.mjs +54 -0
  61. package/dist/state.mjs +27 -39
  62. package/dist/summary.mjs +11 -7
  63. package/dist/text.mjs +15 -0
  64. package/dist/usage.mjs +45 -0
  65. package/dist/verdict.mjs +20 -13
  66. package/dist/watch.mjs +38 -0
  67. package/dist/worker-paths.mjs +16 -0
  68. package/dist/worker-run.mjs +56 -0
  69. package/dist/worker-server.mjs +56 -0
  70. package/dist/worktree-setup.mjs +25 -0
  71. package/dist/worktree.mjs +58 -0
  72. package/package.json +1 -1
  73. package/dist/merge.mjs +0 -75
package/dist/serve.mjs CHANGED
@@ -1,83 +1,22 @@
1
1
  import { rmSync } from 'node:fs';
2
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { mkdir, rm } from 'node:fs/promises';
3
3
  import { createServer } from 'node:http';
4
- import { dirname, join } from 'node:path';
4
+ import { dirname } from 'node:path';
5
5
  import { WebSocketServer } from 'ws';
6
6
  import { parseArgs } from './args.mjs';
7
- import { loadConfig } from './config.mjs';
8
- import { stopChildren } from './exec.mjs';
9
- import { detectRepo } from './git.mjs';
10
- import { waitingQuestions } from './handover.mjs';
11
- import { message } from './observe.mjs';
12
- import { applyEvent, startProgress } from './progress.mjs';
13
- import { PORTS } from './ports.mjs';
14
- import { isNewer, } from './protocol.mjs';
7
+ import { stopChildren } from './children.mjs';
8
+ import { message } from './errors.mjs';
9
+ import { lock } from './lock.mjs';
10
+ import { startProgress } from './progress.mjs';
11
+ import { isNewer } from './protocol.mjs';
12
+ import { listQuestions, questionSender, send } from './questions.mjs';
15
13
  import { runRepo } from './run.mjs';
16
- import { STATE_DIR } from './state.mjs';
17
14
  import { packageVersion } from './version.mjs';
15
+ import { checkSocketPath, workerPaths } from './worker-paths.mjs';
16
+ import { active, endStatus, requestStop, runControls, runsMessage, startRefusal, } from './worker-run.mjs';
17
+ import { broadcast, closer, listen, parseMessage, shutdown, } from './worker-server.mjs';
18
18
  const LOCK_WAIT_MS = 5_000;
19
- const LOCK_POLL_MS = 100;
20
19
  const IDLE_MS = 30_000;
21
- export function workerPaths(root) {
22
- return {
23
- socketPath: join(root, STATE_DIR, 'worker.sock'),
24
- lockPath: join(root, STATE_DIR, 'worker.lock'),
25
- };
26
- }
27
- export function checkSocketPath(path, platform = process.platform) {
28
- const size = platform === 'linux' ? 108 : 104;
29
- const length = Buffer.byteLength(path);
30
- if (length >= size) {
31
- throw new Error(`the socket path ${path} is too long for this system: ${length} bytes, at most ${size - 1}`);
32
- }
33
- }
34
- function alive(pid) {
35
- try {
36
- process.kill(pid, 0);
37
- return true;
38
- }
39
- catch (error) {
40
- return error.code === 'EPERM';
41
- }
42
- }
43
- async function holder(lockPath) {
44
- const pid = Number((await readFile(lockPath, 'utf8').catch(() => '')).trim());
45
- return pid > 0 && alive(pid) ? pid : undefined;
46
- }
47
- export async function stopWorker(lockPath) {
48
- const pid = await holder(lockPath);
49
- if (pid !== undefined) {
50
- process.kill(pid, 'SIGTERM');
51
- }
52
- return pid;
53
- }
54
- async function lock(path, waitMs) {
55
- const deadline = Date.now() + waitMs;
56
- for (;;) {
57
- try {
58
- await writeFile(path, `${process.pid}\n`, { flag: 'wx', mode: 0o600 });
59
- return true;
60
- }
61
- catch (error) {
62
- if (error.code !== 'EEXIST') {
63
- throw error;
64
- }
65
- }
66
- if ((await holder(path)) === undefined) {
67
- await rm(path, { force: true });
68
- }
69
- else if (Date.now() >= deadline) {
70
- return false;
71
- }
72
- else {
73
- await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
74
- }
75
- }
76
- }
77
- export async function listQuestions(root) {
78
- const config = await loadConfig(root);
79
- return waitingQuestions(await detectRepo(root, config.remote), config, PORTS);
80
- }
81
20
  export async function startWorker(options) {
82
21
  checkSocketPath(options.socketPath);
83
22
  await mkdir(dirname(options.lockPath), { recursive: true });
@@ -86,178 +25,71 @@ export async function startWorker(options) {
86
25
  }
87
26
  await rm(options.socketPath, { force: true });
88
27
  const runs = new Map();
89
- const reads = new Map();
90
- const delivered = new WeakMap();
91
28
  let restart = false;
92
- let finish = () => undefined;
93
- const closed = new Promise((resolve) => {
94
- finish = resolve;
95
- });
96
29
  const server = createServer();
97
30
  const sockets = new WebSocketServer({ server });
98
- const snapshot = () => ({
99
- type: 'runs',
100
- runs: Object.fromEntries([...runs].map(([root, run]) => [root, run.progress])),
101
- });
102
- const send = (socket, value) => {
103
- socket.send(JSON.stringify(value));
104
- };
105
- const broadcast = () => {
106
- const value = snapshot();
107
- for (const socket of sockets.clients) {
108
- send(socket, value);
109
- }
110
- };
111
- const sendQuestions = async (root, targets, id) => {
112
- const read = (reads.get(root) ?? 0) + 1;
113
- reads.set(root, read);
114
- let value;
115
- try {
116
- value = { type: 'questions', root, questions: await options.questions(root) };
117
- }
118
- catch (error) {
119
- value = { type: 'questions-error', root, message: message(error) };
120
- }
121
- for (const socket of targets()) {
122
- const seen = delivered.get(socket) ?? new Map();
123
- const last = seen.get(root);
124
- if (last === undefined || last.read < read) {
125
- seen.set(root, { read, value });
126
- delivered.set(socket, seen);
127
- send(socket, id === undefined ? value : { ...value, id });
128
- }
129
- else if (id !== undefined) {
130
- send(socket, { ...last.value, id });
131
- }
132
- }
133
- };
134
- const busy = () => [...runs.values()].some((run) => run.progress.status === 'running' || run.progress.status === 'stopping');
135
- let closing;
31
+ const sendQuestions = questionSender(options.questions);
32
+ const busy = () => [...runs.values()].some(active);
136
33
  let idleTimer;
137
- const close = () => {
138
- closing ??= (async () => {
139
- clearTimeout(idleTimer);
140
- for (const socket of sockets.clients) {
141
- socket.terminate();
142
- }
143
- await new Promise((resolve) => sockets.close(() => resolve()));
144
- await new Promise((resolve) => server.close(() => resolve()));
145
- await rm(options.socketPath, { force: true });
146
- await rm(options.lockPath, { force: true });
147
- finish();
148
- })();
149
- return closing;
150
- };
34
+ const { closed, close } = closer(async () => {
35
+ clearTimeout(idleTimer);
36
+ await shutdown(server, sockets, options);
37
+ });
151
38
  const closeWhenIdle = () => {
152
39
  if ((restart || sockets.clients.size === 0) && !busy()) {
153
40
  void close();
154
41
  }
155
42
  };
156
43
  const start = (socket, root, merge) => {
157
- const current = runs.get(root);
158
- if (current?.progress.status === 'running' || current?.progress.status === 'stopping') {
159
- send(socket, { type: 'error', root, message: 'a run is going in this repository already' });
160
- return;
161
- }
162
- if (restart) {
163
- send(socket, { type: 'error', root, message: 'the worker is restarting, try again soon' });
44
+ const refusal = startRefusal(runs.get(root), restart);
45
+ if (refusal !== undefined) {
46
+ send(socket, { type: 'error', root, message: refusal });
164
47
  return;
165
48
  }
166
49
  const run = { progress: startProgress(), stop: false };
167
50
  runs.set(root, run);
168
- const interrupts = {
169
- afterIssue: () => run.stop,
170
- afterRound: () => run.stop,
171
- sleep: (ms) => new Promise((resolve) => {
172
- if (run.stop) {
173
- resolve(false);
174
- return;
175
- }
176
- const timer = setTimeout(() => resolve(true), ms);
177
- run.wake = () => {
178
- clearTimeout(timer);
179
- resolve(false);
180
- };
181
- }),
182
- };
183
51
  const update = (next) => {
184
52
  run.progress = next;
185
- broadcast();
53
+ broadcast(sockets, runs);
186
54
  };
187
- broadcast();
55
+ broadcast(sockets, runs);
188
56
  options
189
- .runRepo(root, { ...parseArgs([]), merge }, {
190
- interrupts,
191
- onEvent: (record) => {
192
- update(applyEvent(run.progress, record));
193
- if (record['kind'] === 'issue.end' || record['kind'] === 'issue.error') {
194
- void sendQuestions(root, () => sockets.clients);
195
- }
196
- },
197
- })
198
- .then(() => {
199
- const status = run.stop
200
- ? 'stopped'
201
- : run.progress.error === undefined
202
- ? 'finished'
203
- : 'failed';
204
- update({ ...run.progress, status });
205
- }, (error) => update({ ...run.progress, status: 'failed', error: message(error) }))
57
+ .runRepo(root, { ...parseArgs([]), merge }, runControls(run, update, () => void sendQuestions(root, () => sockets.clients)))
58
+ .then(() => update({ ...run.progress, status: endStatus(run) }), (error) => update({ ...run.progress, status: 'failed', error: message(error) }))
206
59
  .finally(closeWhenIdle);
207
60
  };
208
- const stop = (root) => {
209
- const run = runs.get(root);
210
- if (run === undefined || run.progress.status !== 'running') {
211
- return;
61
+ const receive = (socket, value) => {
62
+ if (value.type === 'hello') {
63
+ if (isNewer(value.version, options.version)) {
64
+ restart = true;
65
+ closeWhenIdle();
66
+ }
67
+ }
68
+ else if (value.type === 'start') {
69
+ start(socket, value.root, value.merge === true);
70
+ }
71
+ else if (value.type === 'stop') {
72
+ if (requestStop(runs.get(value.root))) {
73
+ broadcast(sockets, runs);
74
+ }
75
+ }
76
+ else if (value.type === 'questions') {
77
+ void sendQuestions(value.root, () => [socket], value.id);
212
78
  }
213
- run.stop = true;
214
- run.wake?.();
215
- run.progress = { ...run.progress, status: 'stopping' };
216
- broadcast();
217
79
  };
218
80
  sockets.on('connection', (socket) => {
219
81
  send(socket, { type: 'hello', version: options.version });
220
- send(socket, snapshot());
82
+ send(socket, runsMessage(runs));
221
83
  void sendQuestions(options.root, () => [socket]);
222
84
  socket.on('close', closeWhenIdle);
223
85
  socket.on('message', (data) => {
224
- let value;
225
- try {
226
- value = JSON.parse(String(data));
227
- }
228
- catch {
229
- return;
230
- }
231
- if (value.type === 'hello') {
232
- if (isNewer(value.version, options.version)) {
233
- restart = true;
234
- closeWhenIdle();
235
- }
236
- }
237
- else if (value.type === 'start') {
238
- start(socket, value.root, value.merge === true);
239
- }
240
- else if (value.type === 'stop') {
241
- stop(value.root);
242
- }
243
- else if (value.type === 'questions') {
244
- void sendQuestions(value.root, () => [socket], value.id);
86
+ const value = parseMessage(String(data));
87
+ if (value !== undefined) {
88
+ receive(socket, value);
245
89
  }
246
90
  });
247
91
  });
248
- await new Promise((resolve, reject) => {
249
- server.once('error', reject);
250
- const umask = process.umask(0o177);
251
- try {
252
- server.listen(options.socketPath, () => {
253
- server.off('error', reject);
254
- resolve();
255
- });
256
- }
257
- finally {
258
- process.umask(umask);
259
- }
260
- });
92
+ await listen(server, options.socketPath);
261
93
  idleTimer = setTimeout(closeWhenIdle, options.idleMs ?? IDLE_MS);
262
94
  return { closed, close };
263
95
  }
package/dist/setup.mjs CHANGED
@@ -15,13 +15,10 @@ const MARKERS = [
15
15
  ];
16
16
  export async function detectSetupCommand(root) {
17
17
  for (const [file, command] of MARKERS) {
18
- try {
19
- await access(join(root, file));
18
+ const found = await access(join(root, file)).then(() => true, () => false);
19
+ if (found) {
20
20
  return command;
21
21
  }
22
- catch {
23
- continue;
24
- }
25
22
  }
26
23
  return undefined;
27
24
  }
package/dist/skip.mjs ADDED
@@ -0,0 +1,54 @@
1
+ import { elapsedMs } from './durations.mjs';
2
+ import { message } from './errors.mjs';
3
+ export function skipReason(issue, config, resuming) {
4
+ const labels = new Set(issue.labels);
5
+ const names = config.labels;
6
+ if (labels.has(names.done) || labels.has(names.needsHuman) || labels.has(names.skip)) {
7
+ return 'stop-label';
8
+ }
9
+ if (resuming) {
10
+ return undefined;
11
+ }
12
+ if (names.ready.length > 0 && !labels.has(names.ready)) {
13
+ return 'not-ready';
14
+ }
15
+ if (labels.has(names.inProgress) || labels.has(names.inReview)) {
16
+ return 'in-flight';
17
+ }
18
+ return undefined;
19
+ }
20
+ export async function skipReport(context, log, issue, saved, started) {
21
+ const skip = skipReason(issue, context.config, saved !== undefined);
22
+ if (skip !== undefined) {
23
+ log.event('issue.skip', { title: issue.title, reason: skip });
24
+ return skipped(issue);
25
+ }
26
+ if (saved !== undefined) {
27
+ return undefined;
28
+ }
29
+ let blockers;
30
+ try {
31
+ blockers = await context.ports.openBlockers(context.repo, issue.number);
32
+ }
33
+ catch (error) {
34
+ return unclaimedError(log, issue, error, started);
35
+ }
36
+ if (blockers.length > 0) {
37
+ log.event('issue.skip', { title: issue.title, reason: 'blocked', blockers });
38
+ return skipped(issue);
39
+ }
40
+ return undefined;
41
+ }
42
+ export function unclaimedError(log, issue, error, started) {
43
+ const { reason, ms } = logIssueError(log, error, started);
44
+ return { ...skipped(issue), outcome: 'error', reason, ms };
45
+ }
46
+ export function logIssueError(log, error, started) {
47
+ const reason = message(error);
48
+ const ms = elapsedMs(started);
49
+ log.event('issue.error', { error: reason, ms }, 'quiet');
50
+ return { reason, ms };
51
+ }
52
+ function skipped(issue) {
53
+ return { issue: issue.number, outcome: 'skipped', ciFixes: 0, reviewRounds: 0, ms: 0 };
54
+ }
package/dist/state.mjs CHANGED
@@ -1,45 +1,39 @@
1
- import { mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises';
1
+ import { mkdir, readdir, rm } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
+ import { parseJson } from './errors.mjs';
4
+ import { readTextIfPresent, unlessMissing, writeJson } from './files.mjs';
5
+ import { isRecord } from './records.mjs';
3
6
  export const STATE_DIR = '.next-issue';
4
- function dir(repo) {
5
- return join(repo.root, STATE_DIR);
7
+ export function stateDir(root) {
8
+ return join(root, STATE_DIR);
9
+ }
10
+ export function runsDir(root) {
11
+ return join(stateDir(root), 'runs');
6
12
  }
7
13
  function file(repo, issue) {
8
- return join(dir(repo), `${issue}.json`);
14
+ return join(stateDir(repo.root), `${issue}.json`);
9
15
  }
10
16
  export async function readState(repo, issue) {
11
17
  const path = file(repo, issue);
12
- let text;
13
- try {
14
- text = await readFile(path, 'utf8');
15
- }
16
- catch (error) {
17
- if (error.code === 'ENOENT') {
18
- return undefined;
19
- }
20
- throw error;
21
- }
22
- let parsed;
23
- try {
24
- parsed = JSON.parse(text);
25
- }
26
- catch {
27
- throw new Error(`the state file ${path} is not valid JSON`);
18
+ const text = await readTextIfPresent(path);
19
+ if (text === undefined) {
20
+ return undefined;
28
21
  }
22
+ return parseState(path, text);
23
+ }
24
+ function parseState(path, text) {
25
+ const parsed = parseJson(text, () => `the state file ${path} is not valid JSON`);
29
26
  if (!isState(parsed)) {
30
27
  throw new Error(`the state file ${path} does not hold a valid state`);
31
28
  }
32
29
  return parsed;
33
30
  }
34
31
  const PHASES = ['claimed', 'implemented', 'review'];
35
- function isRecord(value) {
36
- return typeof value === 'object' && value !== null;
37
- }
38
32
  function isOptional(value, type) {
39
33
  return value === undefined || typeof value === type;
40
34
  }
41
- function isBaseFix(value) {
42
- return isRecord(value) && typeof value.sha === 'string' && typeof value.head === 'string';
35
+ function isLanded(value) {
36
+ return Array.isArray(value) && value.every((sha) => typeof sha === 'string');
43
37
  }
44
38
  function isReviewRound(value) {
45
39
  return (isRecord(value) &&
@@ -56,35 +50,29 @@ function isState(value) {
56
50
  isOptional(value.title, 'string') &&
57
51
  typeof value.ciFixes === 'number' &&
58
52
  isOptional(value.commitFixes, 'number') &&
59
- (value.baseFix === undefined || isBaseFix(value.baseFix)) &&
53
+ (value.landed === undefined || isLanded(value.landed)) &&
60
54
  typeof value.reviewRounds === 'number' &&
61
55
  Array.isArray(value.reviewLog) &&
62
56
  value.reviewLog.every(isReviewRound) &&
63
- (value.handedOver === undefined || typeof value.handedOver === 'boolean'));
57
+ isOptional(value.handedOver, 'boolean'));
64
58
  }
65
59
  export async function savedIssues(repo) {
66
- let names;
67
- try {
68
- names = await readdir(dir(repo));
69
- }
70
- catch (error) {
71
- if (error.code === 'ENOENT') {
72
- return [];
73
- }
74
- throw error;
75
- }
60
+ const names = (await unlessMissing(() => readdir(stateDir(repo.root)))) ?? [];
76
61
  return names.flatMap((name) => {
77
62
  const match = /^(\d+)\.json$/.exec(name);
78
63
  return match === null ? [] : [Number(match[1])];
79
64
  });
80
65
  }
66
+ export function newState(issue, branch) {
67
+ return { issue, phase: 'claimed', branch, ciFixes: 0, reviewRounds: 0, reviewLog: [] };
68
+ }
81
69
  export function resetState(state) {
82
70
  const { handedOver: _handedOver, ...rest } = state;
83
71
  return { ...rest, ciFixes: 0, commitFixes: 0, reviewRounds: 0, reviewLog: [] };
84
72
  }
85
73
  export async function writeState(repo, state) {
86
- await mkdir(dir(repo), { recursive: true });
87
- await writeFile(file(repo, state.issue), `${JSON.stringify(state, null, 2)}\n`);
74
+ await mkdir(stateDir(repo.root), { recursive: true });
75
+ await writeJson(file(repo, state.issue), state);
88
76
  }
89
77
  export async function dropState(repo, issue) {
90
78
  await rm(file(repo, issue), { force: true });
package/dist/summary.mjs CHANGED
@@ -1,17 +1,21 @@
1
1
  const OUTCOMES = ['done', 'needs-human', 'error', 'skipped', 'stopped'];
2
2
  export function formatSummary(summary) {
3
- const tally = OUTCOMES.map((outcome) => `${summary.issues.filter((report) => report.outcome === outcome).length} ${outcome}`).join(', ');
4
- const lines = [`run ${summary.runId}`, `issues ${summary.issues.length}: ${tally}`];
5
- for (const report of summary.issues) {
6
- lines.push(` ${issueLine(report)}`);
7
- }
3
+ const tally = OUTCOMES.map((outcome) => `${count(summary.issues, outcome)} ${outcome}`).join(', ');
8
4
  const roles = Object.entries(summary.roles)
9
5
  .map(([role, totals]) => `${role} ${tokens(totals.total)} in ${totals.calls}`)
10
6
  .join(', ');
11
- lines.push(`tokens ${tokens(summary.total.total)}${roles.length > 0 ? ` (${roles})` : ''}`);
12
- lines.push(`log ${summary.logFile}`);
7
+ const lines = [
8
+ `run ${summary.runId}`,
9
+ `issues ${summary.issues.length}: ${tally}`,
10
+ ...summary.issues.map((report) => ` ${issueLine(report)}`),
11
+ `tokens ${tokens(summary.total.total)}${roles.length > 0 ? ` (${roles})` : ''}`,
12
+ `log ${summary.logFile}`,
13
+ ];
13
14
  return `${lines.join('\n')}\n`;
14
15
  }
16
+ export function count(reports, outcome) {
17
+ return reports.filter((report) => report.outcome === outcome).length;
18
+ }
15
19
  function issueLine(report) {
16
20
  const parts = [`#${report.issue} ${report.outcome.padEnd(11)}`];
17
21
  if (report.pr !== undefined) {
package/dist/text.mjs ADDED
@@ -0,0 +1,15 @@
1
+ export function joinFilled(parts, separator) {
2
+ return parts.filter((part) => part !== '').join(separator);
3
+ }
4
+ export function paragraphs(parts) {
5
+ return joinFilled(parts, '\n\n');
6
+ }
7
+ export function lines(output) {
8
+ return output.split('\n').filter((line) => line.length > 0);
9
+ }
10
+ export function truncate(text, max, ellipsis) {
11
+ return text.length > max ? `${text.slice(0, max - ellipsis.length)}${ellipsis}` : text;
12
+ }
13
+ export function keepTail(text, limit) {
14
+ return limit !== undefined && text.length > limit ? text.slice(-limit) : text;
15
+ }
package/dist/usage.mjs ADDED
@@ -0,0 +1,45 @@
1
+ export function emptyUsage() {
2
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
3
+ }
4
+ export function addUsage(target, source) {
5
+ target.input += source.input;
6
+ target.output += source.output;
7
+ target.cacheRead += source.cacheRead;
8
+ target.cacheWrite += source.cacheWrite;
9
+ target.total += source.total;
10
+ }
11
+ export function emptyRoleTotals() {
12
+ return { ...emptyUsage(), calls: 0, ms: 0 };
13
+ }
14
+ function subtractUsage(target, source) {
15
+ target.input -= source.input;
16
+ target.output -= source.output;
17
+ target.cacheRead -= source.cacheRead;
18
+ target.cacheWrite -= source.cacheWrite;
19
+ target.total -= source.total;
20
+ }
21
+ export function rolesSince(totals, since) {
22
+ const total = emptyUsage();
23
+ const roles = {};
24
+ for (const [role, value] of totals) {
25
+ const earlier = since?.roles[role] ?? emptyRoleTotals();
26
+ if (value.calls === earlier.calls) {
27
+ continue;
28
+ }
29
+ const usage = { ...value, calls: value.calls - earlier.calls, ms: value.ms - earlier.ms };
30
+ subtractUsage(usage, earlier);
31
+ roles[role] = usage;
32
+ addUsage(total, usage);
33
+ }
34
+ return { roles, total };
35
+ }
36
+ export function countsSince(counts, since) {
37
+ const result = {};
38
+ for (const [kind, value] of counts) {
39
+ const count = value - (since?.counts[kind] ?? 0);
40
+ if (count > 0) {
41
+ result[kind] = count;
42
+ }
43
+ }
44
+ return result;
45
+ }
package/dist/verdict.mjs CHANGED
@@ -1,6 +1,20 @@
1
- const SEVERITIES = ['blocking', 'minor'];
1
+ import { isRecord } from './records.mjs';
2
+ import { paragraphs } from './text.mjs';
3
+ function isSeverity(value) {
4
+ return value === 'blocking' || value === 'minor';
5
+ }
6
+ function readFinding(item) {
7
+ if (!isRecord(item)) {
8
+ return undefined;
9
+ }
10
+ const { severity, detail } = item;
11
+ if (!isSeverity(severity) || typeof detail !== 'string') {
12
+ return undefined;
13
+ }
14
+ return { severity, detail };
15
+ }
2
16
  export function readVerdict(value) {
3
- if (typeof value !== 'object' || value === null) {
17
+ if (!isRecord(value)) {
4
18
  return undefined;
5
19
  }
6
20
  const { summary, findings } = value;
@@ -9,16 +23,11 @@ export function readVerdict(value) {
9
23
  }
10
24
  const checked = [];
11
25
  for (const item of findings) {
12
- if (typeof item !== 'object' || item === null) {
13
- return undefined;
14
- }
15
- const { severity, detail } = item;
16
- if (typeof severity !== 'string' ||
17
- !SEVERITIES.includes(severity) ||
18
- typeof detail !== 'string') {
26
+ const finding = readFinding(item);
27
+ if (finding === undefined) {
19
28
  return undefined;
20
29
  }
21
- checked.push({ severity: severity, detail });
30
+ checked.push(finding);
22
31
  }
23
32
  return { summary, findings: checked };
24
33
  }
@@ -47,9 +56,7 @@ export function formatVerdict(verdict, open) {
47
56
  const head = approved ? 'Review: approved' : 'Review: changes requested';
48
57
  const lines = verdict.findings.map((finding) => `- **${finding.severity}** ${finding.detail}`);
49
58
  const note = approved && verdict.findings.length > 0 ? LEFT : '';
50
- return [`### ${head}`, verdict.summary, lines.join('\n'), note]
51
- .filter((part) => part.length > 0)
52
- .join('\n\n');
59
+ return paragraphs([`### ${head}`, verdict.summary, lines.join('\n'), note]);
53
60
  }
54
61
  export function formatFindings(findings) {
55
62
  return findings.map((finding) => `- ${finding.detail}`).join('\n');
package/dist/watch.mjs ADDED
@@ -0,0 +1,38 @@
1
+ import { handled, runIssues } from './loop.mjs';
2
+ const BACK_OFF_MINUTES = [1, 2, 3, 5, 10];
3
+ export async function watchIssues(args, watch) {
4
+ const limit = args.once ? 1 : args.max;
5
+ const reports = [];
6
+ const failed = new Set();
7
+ let step = 0;
8
+ for (;;) {
9
+ const pass = await runIssues({ once: false, max: limit === undefined ? undefined : limit - handled(reports) }, watch, new Set(failed));
10
+ reports.push(...pass.reports);
11
+ recordFailures(failed, pass.reports);
12
+ if (handled(pass.reports) > 0) {
13
+ await watch.passEnd(pass.reports);
14
+ step = 0;
15
+ }
16
+ if (pass.error !== undefined || pass.stoppedAt !== undefined) {
17
+ return { ...pass, reports };
18
+ }
19
+ if ((limit !== undefined && handled(reports) >= limit) || watch.stop()) {
20
+ return { reports };
21
+ }
22
+ const minutes = backOffMinutes(step);
23
+ step += 1;
24
+ if (!(await watch.wait(minutes))) {
25
+ return { reports };
26
+ }
27
+ }
28
+ }
29
+ function recordFailures(failed, reports) {
30
+ for (const report of reports) {
31
+ if (report.outcome === 'error') {
32
+ failed.add(report.issue);
33
+ }
34
+ }
35
+ }
36
+ function backOffMinutes(step) {
37
+ return BACK_OFF_MINUTES[Math.min(step, BACK_OFF_MINUTES.length - 1)];
38
+ }