next-issue 2.21.2 → 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 -23
  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/logs.mjs CHANGED
@@ -1,98 +1,120 @@
1
1
  import { writeSync } from 'node:fs';
2
- import { open, readdir } from 'node:fs/promises';
2
+ import { open } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { StringDecoder } from 'node:string_decoder';
5
- import { render } from './observe.mjs';
6
- import { STATE_DIR } from './state.mjs';
5
+ import { wakeableSleep } from './durations.mjs';
6
+ import { hasCode } from './errors.mjs';
7
+ import { listOrEmpty } from './files.mjs';
8
+ import { render } from './render.mjs';
9
+ import { runsDir } from './state.mjs';
7
10
  const POLL_MS = 200;
8
11
  export async function newestRunLog(root) {
9
- const dir = join(root, STATE_DIR, 'runs');
10
- let names;
11
- try {
12
- names = await readdir(dir);
13
- }
14
- catch {
15
- return undefined;
16
- }
12
+ const dir = runsDir(root);
13
+ const names = await listOrEmpty(dir);
17
14
  const newest = names
18
15
  .filter((name) => name.endsWith('.jsonl'))
19
16
  .sort()
20
17
  .at(-1);
21
18
  return newest === undefined ? undefined : join(dir, newest);
22
19
  }
23
- export async function followLog(file, options, print) {
24
- const handle = await open(file, 'r');
20
+ function show(line, json) {
21
+ if (json) {
22
+ return `${line}\n`;
23
+ }
24
+ try {
25
+ return render(JSON.parse(line));
26
+ }
27
+ catch {
28
+ return '';
29
+ }
30
+ }
31
+ function completeLines(text, tail) {
32
+ const lines = text.split('\n');
33
+ const rest = lines.pop();
34
+ const filled = lines.filter((line) => line.trim().length > 0);
35
+ return { shown: tail === undefined ? filled : filled.slice(-tail), rest };
36
+ }
37
+ function stdoutOpen() {
38
+ try {
39
+ writeSync(process.stdout.fd, '');
40
+ return true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ async function printLines(lines, json, print) {
47
+ if (lines.length > 0) {
48
+ await print(lines.map((line) => show(line, json)).join(''));
49
+ }
50
+ }
51
+ const CHUNK_BYTES = 64 * 1024;
52
+ async function readChunk(handle, position, decoder) {
53
+ const buffer = Buffer.alloc(CHUNK_BYTES);
54
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
55
+ const text = bytesRead > 0 ? decoder.write(buffer.subarray(0, bytesRead)) : '';
56
+ return { bytesRead, text, full: bytesRead === buffer.length };
57
+ }
58
+ function stopper() {
25
59
  let stopped = false;
26
- let wake;
27
- const stop = () => {
28
- stopped = true;
29
- wake?.();
60
+ const sleeper = {};
61
+ return {
62
+ get stopped() {
63
+ return stopped;
64
+ },
65
+ stop() {
66
+ stopped = true;
67
+ sleeper.wake?.();
68
+ },
69
+ async pause() {
70
+ await wakeableSleep(sleeper, POLL_MS, stopped);
71
+ },
30
72
  };
73
+ }
74
+ function listenForStop(stop) {
31
75
  process.on('SIGINT', stop);
32
76
  process.stdout.on('error', stop);
33
- const show = (line) => {
34
- if (options.json) {
35
- return `${line}\n`;
36
- }
37
- try {
38
- return render(JSON.parse(line));
39
- }
40
- catch {
41
- return '';
42
- }
77
+ return () => {
78
+ process.off('SIGINT', stop);
79
+ process.stdout.off('error', stop);
43
80
  };
81
+ }
82
+ export async function followLog(file, options, print) {
83
+ const handle = await open(file, 'r');
84
+ const control = stopper();
85
+ const unlisten = listenForStop(control.stop);
44
86
  const decoder = new StringDecoder('utf8');
45
87
  let position = 0;
46
88
  let rest = '';
47
89
  let first = true;
48
90
  try {
49
- while (!stopped) {
50
- const buffer = Buffer.alloc(64 * 1024);
51
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
52
- if (bytesRead > 0) {
53
- position += bytesRead;
54
- rest += decoder.write(buffer.subarray(0, bytesRead));
55
- if (bytesRead === buffer.length) {
56
- continue;
57
- }
58
- }
59
- const lines = rest.split('\n');
60
- rest = lines.pop();
61
- let shown = lines.filter((line) => line.trim().length > 0);
62
- if (first && options.tail !== undefined) {
63
- shown = shown.slice(-options.tail);
91
+ while (!control.stopped) {
92
+ const chunk = await readChunk(handle, position, decoder);
93
+ position += chunk.bytesRead;
94
+ rest += chunk.text;
95
+ if (chunk.full) {
96
+ continue;
64
97
  }
98
+ const complete = completeLines(rest, first ? options.tail : undefined);
99
+ rest = complete.rest;
65
100
  first = false;
66
- if (shown.length > 0) {
67
- await print(shown.map(show).join(''));
101
+ await printLines(complete.shown, options.json, print);
102
+ if (!stdoutOpen()) {
103
+ control.stop();
68
104
  }
69
- try {
70
- writeSync(process.stdout.fd, '');
71
- }
72
- catch {
73
- stop();
74
- }
75
- if (stopped) {
105
+ if (control.stopped) {
76
106
  break;
77
107
  }
78
- await new Promise((resolve) => {
79
- const timer = setTimeout(resolve, POLL_MS);
80
- wake = () => {
81
- clearTimeout(timer);
82
- resolve();
83
- };
84
- });
85
- wake = undefined;
108
+ await control.pause();
86
109
  }
87
110
  }
88
111
  catch (error) {
89
- if (!stopped && error.code !== 'EPIPE') {
112
+ if (!control.stopped && !hasCode(error, 'EPIPE')) {
90
113
  throw error;
91
114
  }
92
115
  }
93
116
  finally {
94
- process.off('SIGINT', stop);
95
- process.stdout.off('error', stop);
117
+ unlisten();
96
118
  await handle.close();
97
119
  }
98
120
  return 0;
package/dist/loop.mjs CHANGED
@@ -1,4 +1,3 @@
1
- export const BACK_OFF_MINUTES = [1, 2, 3, 5, 10];
2
1
  export async function runIssues(args, loop, seen = new Set()) {
3
2
  const limit = args.once ? Math.min(1, args.max ?? 1) : args.max;
4
3
  const concurrency = loop.concurrency ?? 1;
@@ -12,14 +11,7 @@ export async function runIssues(args, loop, seen = new Set()) {
12
11
  for (;;) {
13
12
  if (claiming && room()) {
14
13
  try {
15
- const issues = await loop.issues();
16
- for (const issue of issues.filter((candidate) => !seen.has(candidate.number))) {
17
- if (!room()) {
18
- break;
19
- }
20
- seen.add(issue.number);
21
- running.set(issue.number, loop.process(issue).then((report) => ({ issue: issue.number, report }), (failure) => ({ issue: issue.number, failure })));
22
- }
14
+ await claimIssues(loop, seen, running, room);
23
15
  }
24
16
  catch (failure) {
25
17
  error = failure;
@@ -45,40 +37,23 @@ export async function runIssues(args, loop, seen = new Set()) {
45
37
  if (crash !== undefined) {
46
38
  throw crash.failure;
47
39
  }
40
+ return loopResult(reports, stoppedAt, error);
41
+ }
42
+ function loopResult(reports, stoppedAt, error) {
48
43
  return {
49
44
  reports,
50
45
  ...(stoppedAt === undefined ? {} : { stoppedAt }),
51
46
  ...(error === undefined ? {} : { error }),
52
47
  };
53
48
  }
54
- export async function watchIssues(args, watch) {
55
- const limit = args.once ? 1 : args.max;
56
- const reports = [];
57
- const failed = new Set();
58
- let step = 0;
59
- for (;;) {
60
- const pass = await runIssues({ once: false, max: limit === undefined ? undefined : limit - handled(reports) }, watch, new Set(failed));
61
- reports.push(...pass.reports);
62
- for (const report of pass.reports) {
63
- if (report.outcome === 'error') {
64
- failed.add(report.issue);
65
- }
66
- }
67
- if (handled(pass.reports) > 0) {
68
- await watch.passEnd(pass.reports);
69
- step = 0;
70
- }
71
- if (pass.error !== undefined || pass.stoppedAt !== undefined) {
72
- return { ...pass, reports };
73
- }
74
- if ((limit !== undefined && handled(reports) >= limit) || watch.stop()) {
75
- return { reports };
76
- }
77
- const minutes = BACK_OFF_MINUTES[Math.min(step, BACK_OFF_MINUTES.length - 1)];
78
- step += 1;
79
- if (!(await watch.wait(minutes))) {
80
- return { reports };
49
+ async function claimIssues(loop, seen, running, room) {
50
+ const issues = await loop.issues();
51
+ for (const issue of issues.filter((candidate) => !seen.has(candidate.number))) {
52
+ if (!room()) {
53
+ break;
81
54
  }
55
+ seen.add(issue.number);
56
+ running.set(issue.number, loop.process(issue).then((report) => ({ issue: issue.number, report }), (failure) => ({ issue: issue.number, failure })));
82
57
  }
83
58
  }
84
59
  export function exitCode(reports) {
@@ -86,6 +61,6 @@ export function exitCode(reports) {
86
61
  ? 1
87
62
  : 0;
88
63
  }
89
- function handled(reports) {
64
+ export function handled(reports) {
90
65
  return reports.filter((report) => report.outcome !== 'skipped').length;
91
66
  }
package/dist/observe.mjs CHANGED
@@ -1,27 +1,12 @@
1
1
  import { createWriteStream } from 'node:fs';
2
- import { mkdir, readdir, rm, stat } from 'node:fs/promises';
2
+ import { mkdir } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { STATE_DIR } from './state.mjs';
4
+ import { elapsedMs } from './durations.mjs';
5
+ import { message } from './errors.mjs';
6
+ import { render } from './render.mjs';
7
+ import { runsDir } from './state.mjs';
8
+ import { addUsage, countsSince, emptyRoleTotals, rolesSince, } from './usage.mjs';
5
9
  const VISIBILITY = { quiet: 0, normal: 1, verbose: 2 };
6
- export function emptyUsage() {
7
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
8
- }
9
- export function addUsage(target, source) {
10
- target.input += source.input;
11
- target.output += source.output;
12
- target.cacheRead += source.cacheRead;
13
- target.cacheWrite += source.cacheWrite;
14
- target.total += source.total;
15
- }
16
- function negate(usage) {
17
- return {
18
- input: -usage.input,
19
- output: -usage.output,
20
- cacheRead: -usage.cacheRead,
21
- cacheWrite: -usage.cacheWrite,
22
- total: -usage.total,
23
- };
24
- }
25
10
  class Sink {
26
11
  totals = new Map();
27
12
  counts = new Map();
@@ -43,7 +28,7 @@ class Sink {
43
28
  this.counts.set(kind, (this.counts.get(kind) ?? 0) + 1);
44
29
  }
45
30
  add(role, usage, ms) {
46
- const current = this.totals.get(role) ?? { ...emptyUsage(), calls: 0, ms: 0 };
31
+ const current = this.totals.get(role) ?? emptyRoleTotals();
47
32
  addUsage(current, usage);
48
33
  current.calls += 1;
49
34
  current.ms += ms;
@@ -64,7 +49,7 @@ export class Recorder {
64
49
  }
65
50
  static async create(root, level, listener) {
66
51
  const runId = new Date().toISOString().replace(/[:.]/g, '-');
67
- const dir = join(root, STATE_DIR, 'runs');
52
+ const dir = runsDir(root);
68
53
  await mkdir(dir, { recursive: true });
69
54
  const file = join(dir, `${runId}.jsonl`);
70
55
  const sink = new Sink(createWriteStream(file, { flags: 'a' }), level, file, listener);
@@ -73,8 +58,14 @@ export class Recorder {
73
58
  get logFile() {
74
59
  return this.sink.file;
75
60
  }
61
+ get runStem() {
62
+ return this.sink.file.replace(/\.jsonl$/, '');
63
+ }
76
64
  get sessionDir() {
77
- return join(this.sink.file.replace(/\.jsonl$/, ''), 'sessions');
65
+ return join(this.runStem, 'sessions');
66
+ }
67
+ get summaryFile() {
68
+ return `${this.runStem}.summary.json`;
78
69
  }
79
70
  get level() {
80
71
  return this.sink.level;
@@ -98,95 +89,30 @@ export class Recorder {
98
89
  }
99
90
  usage(role, usage, ms, fields = {}) {
100
91
  this.sink.add(role, usage, ms);
101
- this.event('usage', { role, ms, ...usage, ...fields }, 'normal');
92
+ this.event('usage', { role, ms, ...usage, ...fields });
102
93
  }
103
94
  async step(kind, fields, run) {
104
95
  const started = Date.now();
105
96
  this.event(`${kind}.start`, fields, 'verbose');
106
97
  try {
107
98
  const result = await run();
108
- this.event(`${kind}.end`, { ...fields, ms: Date.now() - started });
99
+ this.event(`${kind}.end`, { ...fields, ms: elapsedMs(started) });
109
100
  return result;
110
101
  }
111
102
  catch (error) {
112
- this.event(`${kind}.error`, { ...fields, ms: Date.now() - started, error: message(error) }, 'quiet');
103
+ this.event(`${kind}.error`, { ...fields, ms: elapsedMs(started), error: message(error) }, 'quiet');
113
104
  throw error;
114
105
  }
115
106
  }
116
107
  summary(since) {
117
- const total = emptyUsage();
118
- const roles = {};
119
- for (const [role, value] of this.sink.totals) {
120
- const earlier = since?.roles[role] ?? { ...emptyUsage(), calls: 0, ms: 0 };
121
- if (value.calls === earlier.calls) {
122
- continue;
123
- }
124
- const usage = { ...value, calls: value.calls - earlier.calls, ms: value.ms - earlier.ms };
125
- addUsage(usage, negate(earlier));
126
- roles[role] = usage;
127
- addUsage(total, usage);
128
- }
129
- const counts = {};
130
- for (const [kind, value] of this.sink.counts) {
131
- const count = value - (since?.counts[kind] ?? 0);
132
- if (count > 0) {
133
- counts[kind] = count;
134
- }
135
- }
136
- return { runId: this.runId, logFile: this.sink.file, roles, counts, total };
108
+ return {
109
+ runId: this.runId,
110
+ logFile: this.logFile,
111
+ ...rolesSince(this.sink.totals, since),
112
+ counts: countsSince(this.sink.counts, since),
113
+ };
137
114
  }
138
115
  async close() {
139
116
  await this.sink.close();
140
117
  }
141
118
  }
142
- export async function pruneRuns(root, keepDays) {
143
- if (keepDays <= 0) {
144
- return 0;
145
- }
146
- const dir = join(root, STATE_DIR, 'runs');
147
- let names;
148
- try {
149
- names = await readdir(dir);
150
- }
151
- catch {
152
- return 0;
153
- }
154
- const cutoff = Date.now() - keepDays * 24 * 60 * 60_000;
155
- let dropped = 0;
156
- for (const name of names) {
157
- const path = join(dir, name);
158
- try {
159
- const info = await stat(path);
160
- if (info.mtimeMs < cutoff) {
161
- await rm(path, { force: true, recursive: true });
162
- dropped += 1;
163
- }
164
- }
165
- catch {
166
- continue;
167
- }
168
- }
169
- return dropped;
170
- }
171
- export function message(error) {
172
- return error instanceof Error ? error.message : String(error);
173
- }
174
- export function render(record) {
175
- const time = new Date(String(record.ts)).toTimeString().slice(0, 8);
176
- const issue = record.issue === undefined ? '' : ` #${record.issue}`;
177
- const extras = Object.entries(record)
178
- .filter(([key]) => !['ts', 'runId', 'kind', 'issue'].includes(key))
179
- .map(([key, value]) => `${key}=${short(value)}`)
180
- .join(' ');
181
- return `${time}${issue} ${String(record.kind)}${extras.length > 0 ? ` ${extras}` : ''}\n`;
182
- }
183
- function short(value) {
184
- if (value === undefined || value === null) {
185
- return '-';
186
- }
187
- if (typeof value === 'number') {
188
- return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(6)));
189
- }
190
- const text = String(value).replace(/\s+/g, ' ');
191
- return text.length > 120 ? `${text.slice(0, 117)}...` : text;
192
- }
@@ -0,0 +1,39 @@
1
+ import { handOverReply, writerComments } from './hand-over-comments.mjs';
2
+ import { setStatus } from './job.mjs';
3
+ import { oneAtATime } from './lock.mjs';
4
+ import { writeState } from './state.mjs';
5
+ export async function openJob(context, issue, log, state, start, handedOver) {
6
+ const started = Date.now();
7
+ const { repo, config } = context;
8
+ const branch = state.branch;
9
+ await log.step('claim', { label: config.labels.inProgress }, async () => {
10
+ await setStatus(context, issue.number, state.pr, config.labels.inProgress);
11
+ await writeState(repo, state);
12
+ });
13
+ const comments = await log.step('comments', {}, () => writerComments(context, log, issue.number));
14
+ const reply = handedOver
15
+ ? await log.step('reply', {}, () => handOverReply(context, issue.number, state.pr))
16
+ : [];
17
+ const worktree = await openWorktree(context, issue, log, branch, start);
18
+ return {
19
+ context,
20
+ issue,
21
+ log,
22
+ state,
23
+ branch,
24
+ worktree,
25
+ comments,
26
+ reply,
27
+ started,
28
+ mainBroken: false,
29
+ repairing: false,
30
+ };
31
+ }
32
+ async function openWorktree(context, issue, log, branch, start) {
33
+ const { repo, config, ports } = context;
34
+ const added = await log.step('worktree', { branch }, () => oneAtATime(repo.root, () => ports.addWorktree(repo, issue.number, branch, context.base, config.remote, start)));
35
+ if (!added.baseUpdated) {
36
+ log.event('base.behind', { base: context.base }, 'quiet');
37
+ }
38
+ return added.path;
39
+ }
@@ -0,0 +1,46 @@
1
+ import { message } from './errors.mjs';
2
+ import { readState, savedIssues } from './state.mjs';
3
+ export async function pendingIssues(context) {
4
+ const { repo, config, ports } = context;
5
+ const { ready, inProgress, inReview } = config.labels;
6
+ const labels = ready.length === 0 ? [] : [ready, inProgress, inReview];
7
+ const issues = await ports.openIssues(repo, config.issueLimit, labels);
8
+ const listed = new Set(issues.map((issue) => issue.number));
9
+ let openCount = issues.length;
10
+ for (const number of await savedIssues(repo)) {
11
+ if (listed.has(number)) {
12
+ continue;
13
+ }
14
+ const { open, issue } = await savedIssue(context, number);
15
+ if (open) {
16
+ openCount += 1;
17
+ }
18
+ if (issue !== undefined) {
19
+ issues.push(issue);
20
+ }
21
+ }
22
+ context.recorder.event('issues', { open: openCount }, 'quiet');
23
+ return issues.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
24
+ }
25
+ async function savedIssue(context, number) {
26
+ const { repo, ports } = context;
27
+ const saved = await readState(repo, number).catch(() => 'broken');
28
+ if (saved === undefined) {
29
+ return { open: false };
30
+ }
31
+ try {
32
+ const { open, ...issue } = await ports.viewIssue(repo, number);
33
+ if (saved === 'broken' ||
34
+ open ||
35
+ (saved.pr !== undefined && (await ports.prMerged(repo, saved.pr)))) {
36
+ return { open, issue };
37
+ }
38
+ return { open };
39
+ }
40
+ catch (error) {
41
+ context.recorder
42
+ .scope({ issue: number })
43
+ .event('issue.error', { error: message(error) }, 'quiet');
44
+ return { open: false };
45
+ }
46
+ }