next-issue 2.19.0 → 2.21.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/README.md CHANGED
@@ -86,9 +86,19 @@ the run handles one issue. For each issue:
86
86
  check keeps asking for `checkGraceSeconds`, because a new pull request often
87
87
  shows no check yet, and only then goes straight to the review. The later
88
88
  gates of the same issue ask once. GitHub runs no check on a pull request
89
- that conflicts with its base, so no check and a conflict hand the issue to
90
- a person. While GitHub still works out whether the pull request can merge,
91
- the run asks again until `checkTimeoutMinutes`.
89
+ that conflicts with its base, so no check and a conflict start a merge of
90
+ the remote base into the branch. While GitHub still works out whether the
91
+ pull request can merge, the run asks again until `checkTimeoutMinutes`.
92
+ When git merges the base cleanly, the harness commits the merge with no
93
+ agent. When git reports conflicted files, the fixer gets the list, removes
94
+ the conflict markers, and the harness commits the merge. The harness then
95
+ pushes without force, and the run goes to step 6 again. The merge commit
96
+ runs the `pre-commit` and `commit-msg` hooks like any other commit. When
97
+ the branch already holds the base, the harness only pushes. Each attempt
98
+ comes from the check budget, `maxCiFixes`. With the budget used up, or when
99
+ the fixer leaves a conflict marker or the merge unresolved, or the fixer
100
+ fails, the harness undoes the merge and hands the issue to a person with the
101
+ reason `merge conflict`.
92
102
  7. On a red build, give the failed job logs to the fixer agent, then go to step
93
103
  6 again. The budget is `maxCiFixes`.
94
104
  8. Let the reviewer agent judge the diff, at most `diffMaxChars` of it. The
@@ -108,22 +118,25 @@ the run handles one issue. For each issue:
108
118
  finding.
109
119
  10. No open finding means approval: mark the pull request ready for review and
110
120
  set `status:done`. The merge stays with you, unless you pass `--merge`:
111
- then the harness squash-merges the pull request, deletes the remote
112
- branch, waits until the pull request is merged, for example through a
113
- merge queue, and then waits for the checks that the merge commit starts on
114
- the base branch. A cancelled run there is no failure. When those checks
115
- fail, the fixer gets their logs on a branch reset to the base branch, from
116
- the check budget, and the harness force-pushes the fix, reopens the issue
117
- and opens a new pull request that goes to step 6 again, with fresh review
118
- rounds. The next issue waits for this, and a second ctrl-c stops only after
119
- it. The worktree, the local branch and the state file go away. A resume
120
- whose pull request is already merged goes straight to the wait for the
121
- checks on the base branch, and opens no new pull request. A resume that
122
- stopped inside the fix of the base branch carries on with that fix, and
123
- uses no more of the check budget. Without `--merge`, the remote branch
124
- stays, and a resume whose pull request a person merged sets
125
- `status:done` and waits for no check. A problem that the reviewer leaves out
126
- of the findings thus gets an approval: only the findings count.
121
+ then the harness first asks whether the pull request conflicts with its
122
+ base. A conflict starts the merge of the base from step 6, and the run
123
+ goes to step 6 again. With no conflict, the harness squash-merges the pull
124
+ request, deletes the remote branch, waits until the pull request is merged,
125
+ for example through a merge queue, and then waits for the checks that the
126
+ merge commit starts on the base branch. A cancelled run there is no
127
+ failure. When those checks fail, the fixer gets their logs on a branch
128
+ reset to the base branch, from the check budget, and the harness
129
+ force-pushes the fix, reopens the issue and opens a new pull request that
130
+ goes to step 6 again, with fresh review rounds. The next issue waits for
131
+ this, and a second ctrl-c stops only after it. The worktree, the local
132
+ branch and the state file go away. A resume whose pull request is already
133
+ merged goes straight to the wait for the checks on the base branch, and
134
+ opens no new pull request. A resume that stopped inside the fix of the
135
+ base branch carries on with that fix, and uses no more of the check
136
+ budget. Without `--merge`, the remote branch stays, and a resume whose
137
+ pull request a person merged sets `status:done` and waits for no check. A
138
+ problem that the reviewer leaves out of the findings thus gets an
139
+ approval: only the findings count.
127
140
  11. With an open finding, run the fixer agent and go to step 6 again. The
128
141
  budget is `maxReviewRounds`. A fixer that holds every finding to be wrong
129
142
  changes nothing and gives its reason instead. The reason goes on the pull
@@ -452,8 +465,8 @@ state of an issue that a label still holds back stays as it was.
452
465
  | Argument | Effect |
453
466
  | ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
454
467
  | `init` | Write the config file with the defaults |
455
- | `serve` | Run the worker that pi extensions talk to, see [Worker](#worker) |
456
- | `stop` | Stop the worker, see [Worker](#worker) |
468
+ | `serve` | Run the worker of this repository that pi extensions talk to, see [Worker](#worker) |
469
+ | `stop` | Stop the worker of this repository, see [Worker](#worker) |
457
470
  | `logs` | Show the latest run log and follow it, see [Observability](#observability) |
458
471
  | `--force` | Replace an existing config file, with `init` |
459
472
  | `--once` | Stop after the first handled issue |
@@ -499,20 +512,20 @@ The watch stops:
499
512
 
500
513
  ## Worker
501
514
 
502
- `next-issue serve` runs one worker for the machine. The
515
+ `next-issue serve` runs one worker for the repository it is run in. The
503
516
  [`@ravshansbox/pi-next-issue`](../pi-next-issue) extension starts it and talks
504
- to it. The worker:
505
-
506
- - listens with WebSocket on the socket file `~/.pi/agent/next-issue.sock`, or
507
- in the folder that `PI_CODING_AGENT_DIR` names. Only your user can open the
508
- file. It works on macOS and Linux;
509
- - holds `next-issue.lock` in the same folder, with its process id, so only one
510
- worker runs. A lock whose process is no longer alive is taken over;
511
- - keeps the repositories it knows in `next-issue.roots.json` in the same
512
- folder, so it still knows them after a restart;
513
- - runs at most one run per repository, and runs in several repositories at
514
- once. Each run is like `next-issue` without `--watch`, and the client says
515
- whether it merges;
517
+ to it. Each repository has its own worker, so the runs, restarts and upgrades
518
+ of one repository never affect another. The worker:
519
+
520
+ - listens with WebSocket on the socket file `.next-issue/worker.sock` in the
521
+ repository. Only your user can open the file. It works on macOS and Linux.
522
+ When the path of the socket file is too long for the system, about 103
523
+ bytes on macOS and 107 on Linux, it exits with an error that says so;
524
+ - holds `.next-issue/worker.lock` in the repository, with its process id, so
525
+ only one worker runs per repository. A lock whose process is no longer alive
526
+ is taken over;
527
+ - runs at most one run at a time. Each run is like `next-issue` without
528
+ `--watch`, and the client says whether it merges;
516
529
  - sends every client the progress of every run when it connects and on every
517
530
  change: for each running issue the issue, the step, the tool count and the
518
531
  last tool, and the handled issues;
@@ -522,7 +535,7 @@ to it. The worker:
522
535
  repository, the pull request when there is one, and the `needsHuman` and
523
536
  `skip` labels. It reads them
524
537
  from GitHub, so the list is the same after a restart. It sends them when a
525
- client connects, for each repository it knows, after each issue of a run
538
+ client connects, for its repository, after each issue of a run
526
539
  ends, and when a client sends `{ "type": "questions", "root": "<path>" }`.
527
540
  An issue that no longer has the label leaves the list. An issue with the
528
541
  label but no hand-over comment is in the list with an empty reason and url.
@@ -532,17 +545,34 @@ to it. The worker:
532
545
  `{ "type": "questions-error", "root": "<path>", "message": "<text>" }`;
533
546
  - stops a run, when a client asks, like a second `Ctrl-C`: each running issue
534
547
  after its current round, with the state kept;
535
- - stays when all clients close;
548
+ - exits, and removes its socket and lock files, when no run is going and no
549
+ client is connected, or when no client connects in the 30 seconds after it
550
+ starts;
551
+ - waits up to 5 seconds for the lock when a worker that is closing still
552
+ holds it;
536
553
  - closes once no run is going when a client with a newer version connects, so
537
554
  that the client can start the newer worker;
538
555
  - stops every agent and command and exits on `SIGTERM` or `SIGINT`, and
539
556
  removes its socket and lock files.
540
557
 
541
- Stop it with `next-issue stop`. This sends `SIGTERM` to the process in the
542
- lock file, so the worker stops at once and a run that is going resumes from
558
+ Stop the worker of a repository with `next-issue stop` in that repository.
559
+ Workers of other repositories carry on. This sends `SIGTERM` to the process in
560
+ the lock file, so the worker stops at once and a run that is going resumes from
543
561
  its saved state next time. When no worker is running, the command says so and
544
562
  exits with 0.
545
563
 
564
+ Versions before one worker per repository ran one worker for the machine,
565
+ with `next-issue.sock`, `next-issue.lock` and `next-issue.roots.json` in
566
+ `~/.pi/agent`, or in the folder that `PI_CODING_AGENT_DIR` names. That worker
567
+ does not stop by itself, `next-issue stop` does not reach it, and a run in it
568
+ can claim issues alongside the new worker of the same repository. Stop it once
569
+ after you upgrade:
570
+
571
+ ```sh
572
+ kill "$(cat ~/.pi/agent/next-issue.lock)"
573
+ rm -f ~/.pi/agent/next-issue.roots.json
574
+ ```
575
+
546
576
  ## Development
547
577
 
548
578
  ```bash
package/dist/args.mjs CHANGED
@@ -2,8 +2,8 @@ import { CONFIG_FILE } from './config.mjs';
2
2
  export const USAGE = `next-issue [command] [options]
3
3
 
4
4
  init write ${CONFIG_FILE} with the defaults
5
- serve run the worker that pi extensions talk to
6
- stop stop the worker
5
+ serve run the worker of this repository that pi extensions talk to
6
+ stop stop the worker of this repository
7
7
  logs show the latest run log and follow it
8
8
 
9
9
  --once stop after the first handled issue
package/dist/cli.mjs CHANGED
@@ -6,7 +6,7 @@ import { listenForInterrupts } from './interrupt.mjs';
6
6
  import { followLog, newestRunLog } from './logs.mjs';
7
7
  import { message } from './observe.mjs';
8
8
  import { runRepo } from './run.mjs';
9
- import { serve, socketPaths, stopWorker } from './serve.mjs';
9
+ import { serve, stopWorker, workerPaths } from './serve.mjs';
10
10
  import { STATE_DIR } from './state.mjs';
11
11
  import { formatSummary } from './summary.mjs';
12
12
  function write(stream, text) {
@@ -20,17 +20,17 @@ async function main() {
20
20
  await write(process.stdout, USAGE);
21
21
  return 0;
22
22
  }
23
+ const root = await repoRoot(process.cwd());
23
24
  if (args.command === 'serve') {
24
- return serve();
25
+ return serve(root);
25
26
  }
26
27
  if (args.command === 'stop') {
27
- const pid = await stopWorker(socketPaths().lockPath);
28
+ const pid = await stopWorker(workerPaths(root).lockPath);
28
29
  await write(process.stdout, pid === undefined
29
30
  ? 'next-issue: no worker is running\n'
30
31
  : `next-issue: stopped the worker with process id ${pid}\n`);
31
32
  return 0;
32
33
  }
33
- const root = await repoRoot(process.cwd());
34
34
  if (args.command === 'init') {
35
35
  return init(root, args.force);
36
36
  }
@@ -0,0 +1,57 @@
1
+ import { CODING } from './agents.mjs';
2
+ import { commitWork } from './fix.mjs';
3
+ import { escalate, finish } from './handover.mjs';
4
+ import { fixPrompt, parseCommitSubject } from './prompts.mjs';
5
+ import { writeState } from './state.mjs';
6
+ export async function conflicts(job) {
7
+ const { repo, config, ports } = job.context;
8
+ return ports.prConflicts(repo, job.state.pr, {
9
+ intervalSeconds: config.checkIntervalSeconds,
10
+ timeoutMs: config.checkTimeoutMinutes * 60_000,
11
+ });
12
+ }
13
+ export async function resolveConflict(job) {
14
+ const { context, log, state, worktree, branch } = job;
15
+ const { repo, config, ports } = context;
16
+ if (state.ciFixes >= config.maxCiFixes) {
17
+ await escalate(job, `The pull request conflicts with its base, and the limit of ${config.maxCiFixes} check fixes was reached.`);
18
+ return { done: true, report: await finish(job, 'needs-human', 'merge conflict') };
19
+ }
20
+ state.ciFixes += 1;
21
+ await writeState(repo, state);
22
+ const before = await ports.revision(worktree);
23
+ const files = await log.step('merge-base', { base: context.base }, () => ports.startMerge(worktree, context.base, config.remote));
24
+ log.event('merge-base.conflicts', { files }, 'quiet');
25
+ if (files !== undefined && !(await mergeBase(job, before, files))) {
26
+ await ports.abortMerge(worktree, before);
27
+ await escalate(job, 'The fixer left the conflict with the base unresolved.');
28
+ return { done: true, report: await finish(job, 'needs-human', 'merge conflict') };
29
+ }
30
+ await ports.push(worktree, config.remote, branch);
31
+ return { done: false, fixed: true };
32
+ }
33
+ async function mergeBase(job, before, files) {
34
+ const { context, issue, log, state, worktree } = job;
35
+ const { config, ports } = context;
36
+ try {
37
+ let text = '';
38
+ if (files.length > 0) {
39
+ const reason = 'The pull request conflicts with its base.';
40
+ const result = await log.step('fix', { reason, cause: 'conflict', round: state.ciFixes, limit: config.maxCiFixes }, () => ports.runAgent(log, {
41
+ name: 'fixer',
42
+ cwd: worktree,
43
+ prompt: fixPrompt(issue, reason, files.join('\n'), [], 'conflict', job.reply),
44
+ profile: CODING,
45
+ model: config.models.fixer,
46
+ timeoutMs: config.agentTimeoutMinutes * 60_000,
47
+ }));
48
+ text = result.text;
49
+ }
50
+ const subject = parseCommitSubject(text, `chore: merge ${config.remote}/${context.base}`);
51
+ return await commitWork(job, before, subject, 'fixer', (cwd, message) => ports.commitMerge(cwd, files, message));
52
+ }
53
+ catch (error) {
54
+ await ports.abortMerge(worktree, before);
55
+ throw error;
56
+ }
57
+ }
package/dist/fix.mjs CHANGED
@@ -39,12 +39,13 @@ export async function fixRound(job, reason, detail, earlier, kind, force = false
39
39
  await ports.push(worktree, config.remote, branch, force);
40
40
  return { committed: true };
41
41
  }
42
- export async function commitWork(job, before, subject, role) {
42
+ export async function commitWork(job, before, subject, role, commit) {
43
43
  const { context, issue, log, state, worktree, comments } = job;
44
44
  const { repo, config, ports } = context;
45
+ const commitChanges = commit ?? ports.commitAll;
45
46
  for (;;) {
46
47
  try {
47
- if (await ports.commitAll(worktree, `${subject}\n\nRefs #${issue.number}`)) {
48
+ if (await commitChanges(worktree, `${subject}\n\nRefs #${issue.number}`)) {
48
49
  log.event('commit', { subject });
49
50
  }
50
51
  if ((await ports.revision(worktree)) === before) {
package/dist/gate.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { conflicts, resolveConflict } from './conflict.mjs';
1
2
  import { fixRound } from './fix.mjs';
2
3
  import { escalate, finish } from './handover.mjs';
3
4
  import { history } from './job.mjs';
@@ -19,13 +20,8 @@ export async function checkGate(job) {
19
20
  await escalate(job, 'The checks did not finish in time.');
20
21
  return { done: true, report: await finish(job, 'needs-human', 'checks timeout') };
21
22
  }
22
- if (checks === 'none' &&
23
- (await ports.prConflicts(repo, state.pr, {
24
- intervalSeconds: config.checkIntervalSeconds,
25
- timeoutMs: config.checkTimeoutMinutes * 60_000,
26
- }))) {
27
- await escalate(job, 'The pull request conflicts with its base, so no checks ran.');
28
- return { done: true, report: await finish(job, 'needs-human', 'merge conflict') };
23
+ if (checks === 'none' && (await conflicts(job))) {
24
+ return resolveConflict(job);
29
25
  }
30
26
  if (checks === 'moved') {
31
27
  await escalate(job, 'Someone pushed to the pull request while the harness waited for the checks.');
package/dist/git.mjs CHANGED
@@ -115,6 +115,10 @@ export async function commitAll(cwd, message) {
115
115
  return false;
116
116
  }
117
117
  await must('git', ['add', '-A'], { cwd });
118
+ await commitStaged(cwd, message);
119
+ return true;
120
+ }
121
+ async function commitStaged(cwd, message) {
118
122
  const folder = await mkdtemp(join(tmpdir(), 'next-issue-message-'));
119
123
  const file = join(folder, 'COMMIT_EDITMSG');
120
124
  try {
@@ -126,7 +130,6 @@ export async function commitAll(cwd, message) {
126
130
  finally {
127
131
  await rm(folder, { recursive: true, force: true });
128
132
  }
129
- return true;
130
133
  }
131
134
  async function runHook(cwd, name, ...args) {
132
135
  try {
@@ -163,6 +166,44 @@ export async function resetToBase(cwd, base, remote) {
163
166
  await must('git', ['fetch', remote, base], { cwd });
164
167
  await must('git', ['reset', '--hard', `${remote}/${base}`], { cwd });
165
168
  }
169
+ export async function startMerge(cwd, base, remote) {
170
+ await must('git', ['fetch', remote, base], { cwd });
171
+ const result = await run('git', ['merge', '--no-ff', '--no-commit', `${remote}/${base}`], {
172
+ cwd,
173
+ });
174
+ if (result.code === 0) {
175
+ return (await merging(cwd)) ? [] : undefined;
176
+ }
177
+ const listed = await must('git', ['diff', '--name-only', '--diff-filter=U'], { cwd });
178
+ const files = listed.split('\n').filter((line) => line.length > 0);
179
+ if (files.length === 0) {
180
+ throw new Error(`git merge ${remote}/${base} failed: ${result.stderr.trim()}`);
181
+ }
182
+ return files;
183
+ }
184
+ async function merging(cwd) {
185
+ const result = await run('git', ['rev-parse', '--quiet', '--verify', 'MERGE_HEAD'], { cwd });
186
+ return result.code === 0;
187
+ }
188
+ const CONFLICT_MARKER = /^(?:<{7}|>{7})(?: |$)/m;
189
+ export async function commitMerge(cwd, files, message) {
190
+ if (!(await merging(cwd))) {
191
+ return false;
192
+ }
193
+ for (const file of files) {
194
+ const text = await readFile(join(cwd, file), 'utf8').catch(() => '');
195
+ if (CONFLICT_MARKER.test(text)) {
196
+ return false;
197
+ }
198
+ }
199
+ await must('git', ['add', '-A'], { cwd });
200
+ await commitStaged(cwd, message);
201
+ return true;
202
+ }
203
+ export async function abortMerge(cwd, target) {
204
+ await must('git', ['reset', '--hard', target], { cwd });
205
+ await must('git', ['clean', '-fd'], { cwd });
206
+ }
166
207
  export async function latestSubject(cwd, base, remote) {
167
208
  const subject = await must('git', ['log', '-1', '--format=%s', `${remote}/${base}..HEAD`], {
168
209
  cwd,
package/dist/ports.mjs CHANGED
@@ -1,14 +1,16 @@
1
1
  import { runAgent } from './agents.mjs';
2
2
  import { run } from './exec.mjs';
3
- import { addWorktree, commitAll, deleteBranch, diff, discardChanges, disputeBranches, findWorktree, isDirty, latestSubject, push, removeWorktree, resetToBase, revision, setAside, } from './git.mjs';
3
+ import { abortMerge, addWorktree, commitAll, commitMerge, deleteBranch, diff, discardChanges, disputeBranches, findWorktree, isDirty, latestSubject, push, removeWorktree, resetToBase, revision, setAside, startMerge, } from './git.mjs';
4
4
  import { canWrite, commentOnIssue, commentOnPr, createPr, failedBaseLogs, failedCheckLogs, findPr, issueComments, markPrReady, mergeCommit, mergePr, openBlockers, openIssues, prConflicts, prMerged, reopenIssue, setLabel, threadComments, viewIssue, waitForBaseChecks, waitForChecks, } from './github.mjs';
5
5
  import { detectSetupCommand } from './setup.mjs';
6
6
  export const PORTS = {
7
+ abortMerge,
7
8
  addWorktree,
8
9
  canWrite,
9
10
  commentOnIssue,
10
11
  commentOnPr,
11
12
  commitAll,
13
+ commitMerge,
12
14
  createPr,
13
15
  deleteBranch,
14
16
  detectSetupCommand,
@@ -38,6 +40,7 @@ export const PORTS = {
38
40
  runSetup: async (command, cwd, timeoutMs) => run('bash', ['-lc', command], { cwd, timeoutMs }),
39
41
  setAside,
40
42
  setLabel,
43
+ startMerge,
41
44
  threadComments,
42
45
  viewIssue,
43
46
  waitForBaseChecks,
package/dist/prompts.mjs CHANGED
@@ -87,6 +87,16 @@ const DISPUTE_RULE = [
87
87
  'If only some of the findings are wrong, fix the correct ones and change nothing for the wrong ones. Write no `unrelated` line in that round. The next round holds only the findings that are left, and you can dispute them there.',
88
88
  'The reviewer reads that line in the next round. Do not make a change that you hold to be wrong only to end the round.',
89
89
  ].join('\n');
90
+ const CONFLICT_RULE = [
91
+ 'The harness merged the base branch into this branch, and git left conflict markers in the files listed under Detail.',
92
+ 'Resolve each conflict so that both the change of this issue and the change on the base branch survive, and remove every conflict marker.',
93
+ 'Leave the merge in progress. The harness commits the merge and pushes it.',
94
+ ].join('\n');
95
+ const KIND_RULES = {
96
+ checks: UNRELATED_RULE,
97
+ review: DISPUTE_RULE,
98
+ conflict: CONFLICT_RULE,
99
+ };
90
100
  export function fixPrompt(issue, reason, detail, earlier, kind, reply = []) {
91
101
  return [
92
102
  `You are the fixer. Correct the work for issue #${issue.number}: ${issue.title}.`,
@@ -102,7 +112,7 @@ export function fixPrompt(issue, reason, detail, earlier, kind, reply = []) {
102
112
  replyBlock(reply),
103
113
  '## Rules',
104
114
  'Fix the cause, not the symptom. Keep the change minimal.',
105
- kind === 'checks' ? UNRELATED_RULE : DISPUTE_RULE,
115
+ KIND_RULES[kind],
106
116
  COMMIT_RULES,
107
117
  ]
108
118
  .filter((part) => part.length > 0)
package/dist/review.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { REVIEWING } from './agents.mjs';
2
+ import { conflicts, resolveConflict } from './conflict.mjs';
2
3
  import { fixRound } from './fix.mjs';
3
4
  import { checkGate } from './gate.mjs';
4
5
  import { escalate, finish } from './handover.mjs';
@@ -65,6 +66,10 @@ export async function reviewRound(job) {
65
66
  log.event('pull-request.undraft.fail', { pr }, 'quiet');
66
67
  }
67
68
  if (context.merge) {
69
+ if (await conflicts(job)) {
70
+ const resolved = await resolveConflict(job);
71
+ return resolved.done ? { done: true, report: resolved.report } : { done: false };
72
+ }
68
73
  if (!(await ports.mergePr(repo, pr))) {
69
74
  await escalate(job, 'The merge of the pull request failed.');
70
75
  return { done: true, report: await finish(job, 'needs-human', 'merge failed') };
package/dist/serve.mjs CHANGED
@@ -1,8 +1,7 @@
1
1
  import { rmSync } from 'node:fs';
2
- import { readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { createServer } from 'node:http';
4
- import { join } from 'node:path';
5
- import { getAgentDir } from '@earendil-works/pi-coding-agent';
4
+ import { dirname, join } from 'node:path';
6
5
  import { WebSocketServer } from 'ws';
7
6
  import { parseArgs } from './args.mjs';
8
7
  import { loadConfig } from './config.mjs';
@@ -14,14 +13,24 @@ import { applyEvent, startProgress } from './progress.mjs';
14
13
  import { PORTS } from './ports.mjs';
15
14
  import { isNewer, } from './protocol.mjs';
16
15
  import { runRepo } from './run.mjs';
16
+ import { STATE_DIR } from './state.mjs';
17
17
  import { packageVersion } from './version.mjs';
18
- export function socketPaths(agentDir = getAgentDir()) {
18
+ const LOCK_WAIT_MS = 5_000;
19
+ const LOCK_POLL_MS = 100;
20
+ const IDLE_MS = 30_000;
21
+ export function workerPaths(root) {
19
22
  return {
20
- socketPath: join(agentDir, 'next-issue.sock'),
21
- lockPath: join(agentDir, 'next-issue.lock'),
22
- rootsPath: join(agentDir, 'next-issue.roots.json'),
23
+ socketPath: join(root, STATE_DIR, 'worker.sock'),
24
+ lockPath: join(root, STATE_DIR, 'worker.lock'),
23
25
  };
24
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
+ }
25
34
  function alive(pid) {
26
35
  try {
27
36
  process.kill(pid, 0);
@@ -42,8 +51,9 @@ export async function stopWorker(lockPath) {
42
51
  }
43
52
  return pid;
44
53
  }
45
- async function lock(path) {
46
- for (let attempt = 0; attempt < 2; attempt += 1) {
54
+ async function lock(path, waitMs) {
55
+ const deadline = Date.now() + waitMs;
56
+ for (;;) {
47
57
  try {
48
58
  await writeFile(path, `${process.pid}\n`, { flag: 'wx', mode: 0o600 });
49
59
  return true;
@@ -52,21 +62,16 @@ async function lock(path) {
52
62
  if (error.code !== 'EEXIST') {
53
63
  throw error;
54
64
  }
55
- if ((await holder(path)) !== undefined) {
56
- return false;
57
- }
65
+ }
66
+ if ((await holder(path)) === undefined) {
58
67
  await rm(path, { force: true });
59
68
  }
60
- }
61
- return false;
62
- }
63
- async function readRoots(path) {
64
- try {
65
- const value = JSON.parse(await readFile(path, 'utf8'));
66
- return new Set(Array.isArray(value) ? value.filter((root) => typeof root === 'string') : []);
67
- }
68
- catch {
69
- return new Set();
69
+ else if (Date.now() >= deadline) {
70
+ return false;
71
+ }
72
+ else {
73
+ await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
74
+ }
70
75
  }
71
76
  }
72
77
  export async function listQuestions(root) {
@@ -74,23 +79,13 @@ export async function listQuestions(root) {
74
79
  return waitingQuestions(await detectRepo(root, config.remote), config, PORTS);
75
80
  }
76
81
  export async function startWorker(options) {
77
- if (!(await lock(options.lockPath))) {
82
+ checkSocketPath(options.socketPath);
83
+ await mkdir(dirname(options.lockPath), { recursive: true });
84
+ if (!(await lock(options.lockPath, options.lockWaitMs ?? LOCK_WAIT_MS))) {
78
85
  return undefined;
79
86
  }
80
87
  await rm(options.socketPath, { force: true });
81
88
  const runs = new Map();
82
- const roots = await readRoots(options.rootsPath);
83
- let saving = Promise.resolve();
84
- const remember = (root) => {
85
- if (roots.has(root)) {
86
- return;
87
- }
88
- roots.add(root);
89
- const value = `${JSON.stringify([...roots], null, 2)}\n`;
90
- saving = saving
91
- .then(() => writeFile(options.rootsPath, value, { mode: 0o600 }))
92
- .catch(() => undefined);
93
- };
94
89
  const reads = new Map();
95
90
  const delivered = new WeakMap();
96
91
  let restart = false;
@@ -114,7 +109,6 @@ export async function startWorker(options) {
114
109
  }
115
110
  };
116
111
  const sendQuestions = async (root, targets, id) => {
117
- remember(root);
118
112
  const read = (reads.get(root) ?? 0) + 1;
119
113
  reads.set(root, read);
120
114
  let value;
@@ -138,19 +132,24 @@ export async function startWorker(options) {
138
132
  }
139
133
  };
140
134
  const busy = () => [...runs.values()].some((run) => run.progress.status === 'running' || run.progress.status === 'stopping');
141
- const close = async () => {
142
- for (const socket of sockets.clients) {
143
- socket.terminate();
144
- }
145
- await new Promise((resolve) => sockets.close(() => resolve()));
146
- await new Promise((resolve) => server.close(() => resolve()));
147
- await rm(options.socketPath, { force: true });
148
- await saving;
149
- await rm(options.lockPath, { force: true });
150
- finish();
135
+ let closing;
136
+ 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;
151
150
  };
152
- const restartWhenIdle = () => {
153
- if (restart && !busy()) {
151
+ const closeWhenIdle = () => {
152
+ if ((restart || sockets.clients.size === 0) && !busy()) {
154
153
  void close();
155
154
  }
156
155
  };
@@ -166,7 +165,6 @@ export async function startWorker(options) {
166
165
  }
167
166
  const run = { progress: startProgress(), stop: false };
168
167
  runs.set(root, run);
169
- remember(root);
170
168
  const interrupts = {
171
169
  afterIssue: () => run.stop,
172
170
  afterRound: () => run.stop,
@@ -205,7 +203,7 @@ export async function startWorker(options) {
205
203
  : 'failed';
206
204
  update({ ...run.progress, status });
207
205
  }, (error) => update({ ...run.progress, status: 'failed', error: message(error) }))
208
- .finally(restartWhenIdle);
206
+ .finally(closeWhenIdle);
209
207
  };
210
208
  const stop = (root) => {
211
209
  const run = runs.get(root);
@@ -220,9 +218,8 @@ export async function startWorker(options) {
220
218
  sockets.on('connection', (socket) => {
221
219
  send(socket, { type: 'hello', version: options.version });
222
220
  send(socket, snapshot());
223
- for (const root of roots) {
224
- void sendQuestions(root, () => [socket]);
225
- }
221
+ void sendQuestions(options.root, () => [socket]);
222
+ socket.on('close', closeWhenIdle);
226
223
  socket.on('message', (data) => {
227
224
  let value;
228
225
  try {
@@ -234,7 +231,7 @@ export async function startWorker(options) {
234
231
  if (value.type === 'hello') {
235
232
  if (isNewer(value.version, options.version)) {
236
233
  restart = true;
237
- restartWhenIdle();
234
+ closeWhenIdle();
238
235
  }
239
236
  }
240
237
  else if (value.type === 'start') {
@@ -261,11 +258,13 @@ export async function startWorker(options) {
261
258
  process.umask(umask);
262
259
  }
263
260
  });
261
+ idleTimer = setTimeout(closeWhenIdle, options.idleMs ?? IDLE_MS);
264
262
  return { closed, close };
265
263
  }
266
- export async function serve() {
267
- const paths = socketPaths();
264
+ export async function serve(root) {
265
+ const paths = workerPaths(root);
268
266
  const worker = await startWorker({
267
+ root,
269
268
  ...paths,
270
269
  version: await packageVersion(),
271
270
  runRepo,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-issue",
3
- "version": "2.19.0",
3
+ "version": "2.21.0",
4
4
  "description": "Autonomous issue harness driven by the pi SDK",
5
5
  "keywords": [
6
6
  "github",