@pecot/workflow-mcp 8.0.1-dev.58 → 8.0.1-dev.60

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 (61) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -0
  3. package/cli/dist/commands/base-reading.d.ts +1 -1
  4. package/cli/dist/commands/base-reading.js +1 -1
  5. package/cli/dist/commands/board-sync.js +1 -1
  6. package/cli/dist/commands/github-client.d.ts +6 -2
  7. package/cli/dist/commands/github-client.js +12 -4
  8. package/cli/dist/commands/issue-comment.js +3 -2
  9. package/cli/dist/commands/issue-show.js +3 -2
  10. package/cli/dist/commands/names.js +1 -0
  11. package/cli/dist/commands/output.d.ts +4 -0
  12. package/cli/dist/commands/output.js +1 -0
  13. package/cli/dist/commands/pr-merge.js +3 -2
  14. package/cli/dist/commands/pr-restack.js +16 -9
  15. package/cli/dist/commands/pr.js +18 -18
  16. package/cli/dist/commands/project.js +5 -3
  17. package/cli/dist/commands/registry.js +2 -0
  18. package/cli/dist/commands/release.js +8 -8
  19. package/cli/dist/commands/restack-reading.d.ts +4 -0
  20. package/cli/dist/commands/restack-reading.js +1 -1
  21. package/cli/dist/commands/review-finish.d.ts +3 -0
  22. package/cli/dist/commands/review-finish.js +276 -0
  23. package/cli/dist/commands/session-finish.js +18 -8
  24. package/cli/dist/commands/session.js +1 -1
  25. package/cli/dist/commands/tracker-sync-dependabot.js +1 -1
  26. package/cli/dist/commands/tracker-sync-security.js +1 -1
  27. package/cli/dist/commands/worktree.js +4 -3
  28. package/cli/dist/domain/errors.d.ts +5 -0
  29. package/cli/dist/domain/errors.js +5 -0
  30. package/cli/dist/domain/release.d.ts +10 -1
  31. package/cli/dist/domain/release.js +10 -6
  32. package/cli/dist/domain/review-finish.d.ts +102 -0
  33. package/cli/dist/domain/review-finish.js +169 -0
  34. package/cli/dist/infra/git.d.ts +20 -16
  35. package/cli/dist/infra/git.js +40 -96
  36. package/cli/dist/infra/github/client.d.ts +12 -1
  37. package/cli/dist/infra/github/client.js +49 -16
  38. package/cli/dist/infra/github/issues.d.ts +4 -0
  39. package/cli/dist/infra/github/issues.js +6 -0
  40. package/cli/dist/infra/github/pulls.d.ts +9 -0
  41. package/cli/dist/infra/github/pulls.js +14 -0
  42. package/cli/dist/infra/github/repos.d.ts +4 -0
  43. package/cli/dist/infra/github/repos.js +8 -1
  44. package/cli/dist/infra/nx-scope.d.ts +5 -1
  45. package/cli/dist/infra/nx-scope.js +20 -13
  46. package/cli/dist/infra/process-run.d.ts +57 -0
  47. package/cli/dist/infra/process-run.js +168 -0
  48. package/cli/dist/infra/worktree-setup.d.ts +3 -6
  49. package/cli/dist/infra/worktree-setup.js +8 -26
  50. package/cli/dist/infra/worktree.d.ts +5 -1
  51. package/cli/dist/infra/worktree.js +4 -4
  52. package/cli/dist/mcp/result.d.ts +3 -3
  53. package/cli/dist/mcp/result.js +4 -3
  54. package/cli/dist/mcp/serve.d.ts +12 -0
  55. package/cli/dist/mcp/serve.js +30 -2
  56. package/cli/dist/mcp/server.d.ts +4 -0
  57. package/cli/dist/mcp/server.js +14 -6
  58. package/cli/templates/comment/review-stopped.md +28 -0
  59. package/cli/templates/workflow/pecot-review.yml +11 -2
  60. package/npm-shrinkwrap.json +2 -2
  61. package/package.json +1 -1
@@ -5,13 +5,13 @@
5
5
  // - redirect: 'manual' で呼ぶ。301 などは成功にせず、Python と同じ失敗にする。
6
6
  // - URL は文字列の連結で作る。new URL は GHE の base(/api/v3)を落とす。
7
7
  // - 失敗の文は httpx と gql の文言を写す。
8
- import { spawnSync } from 'node:child_process';
9
8
  import path from 'node:path';
10
9
  import { isJsonObject, parseJsonText } from '../../domain/json.js';
11
- import { BaseError, InvalidValueError } from '../../domain/errors.js';
10
+ import { BaseError, CancelledError, InvalidValueError } from '../../domain/errors.js';
12
11
  import { formatHttpStatusError, isJsonArray, pythonRepr, pythonStrip, pythonTypeName, splitCodePoints, } from '../../domain/python-format.js';
13
12
  import { configDirectory } from '../config-store.js';
14
13
  import { projectRoot } from '../paths.js';
14
+ import { cancelledBy, runProcess } from '../process-run.js';
15
15
  import { ensureEnvironmentFile, environmentValue, getEnvironmentVariableName, loadEnvironmentFile, pythonString, ROOT_ENV_VAR_MAP, scopesFor, tokenUrlFor, } from './auth.js';
16
16
  import { GitHubAPIError, GitHubAuthError, GitHubNotFoundError, GitHubRateLimitError, } from './errors.js';
17
17
  import { asObject, isTruthy } from './payload.js';
@@ -291,6 +291,8 @@ restJson・restObject・restRequest・handleHttpError・executeGraphql。
291
291
  export class GitHubClientBase {
292
292
  diagnostics;
293
293
  usedFallback = false;
294
+ signal;
295
+ ghToken;
294
296
  host;
295
297
  token;
296
298
  timeoutMilliseconds;
@@ -305,7 +307,9 @@ export class GitHubClientBase {
305
307
  this.diagnostics = options.diagnostics;
306
308
  this.host = options.host ?? 'github.com';
307
309
  this.ghTimeoutMilliseconds = options.ghTimeoutMilliseconds ?? DEFAULT_GH_TIMEOUT_MILLISECONDS;
308
- this.token = options.token === undefined || options.token === '' ? this.resolveToken(this.host) : options.token;
310
+ this.signal = options.signal;
311
+ // gh auth token は子プロセスを待つので、構築では読まず ensureToken に回す。空はまだ読んでいない印
312
+ this.token = options.token === undefined || options.token === '' ? this.tokenFromEnvironment(this.host) ?? '' : options.token;
309
313
  this.timeoutMilliseconds = options.timeoutMilliseconds ?? DEFAULT_TIMEOUT_MILLISECONDS;
310
314
  const override = resolveApiUrlOverride();
311
315
  if (override !== undefined) {
@@ -321,13 +325,12 @@ export class GitHubClientBase {
321
325
  this.graphqlUrl = `https://${this.host}/api/graphql`;
322
326
  }
323
327
  }
324
- // config/.env → ルート .env → gh auth token の順
325
- resolveToken(host) {
326
- return this.tokenFromEnvironment(host) ?? this.tokenFromGh(host) ?? this.failAuthentication(host);
327
- }
328
328
  failAuthentication(host) {
329
329
  throw new GitHubAuthError(this.authErrorMessage(host));
330
330
  }
331
+ async loadGhToken() {
332
+ this.token = await this.tokenFromGh(this.host) ?? this.failAuthentication(this.host);
333
+ }
331
334
  tokenFromEnvironment(host) {
332
335
  loadEnvironmentFile(path.join(configDirectory(), '.env'));
333
336
  const token = environmentValue(getEnvironmentVariableName(host));
@@ -340,11 +343,18 @@ export class GitHubClientBase {
340
343
  const rootToken = environmentValue(rootName);
341
344
  return rootToken === undefined || rootToken === '' ? undefined : rootToken;
342
345
  }
343
- tokenFromGh(host) {
346
+ async tokenFromGh(host) {
344
347
  const arguments_ = host === 'github.com' ? ['auth', 'token'] : ['auth', 'token', '-h', host];
345
- const result = spawnSync('gh', arguments_, { encoding: 'utf8', timeout: this.ghTimeoutMilliseconds });
346
- // gh が無い・時間切れ(error)、終了コードが 0 でない、または出力が空
347
- const token = result.error === undefined && result.status === 0 ? pythonStrip(result.stdout) : '';
348
+ let token = '';
349
+ try {
350
+ const result = await runProcess('gh', arguments_, { stdin: 'ignore', timeoutMilliseconds: this.ghTimeoutMilliseconds, signal: this.signal });
351
+ token = result.exitCode === 0 && !result.isTimedOut ? pythonStrip(result.stdout) : '';
352
+ }
353
+ catch (error) {
354
+ // 取り消しは認証の失敗にしない(authErrorMessage が .env を作るため)。gh が無いときは読めなかった扱い
355
+ if (error instanceof CancelledError)
356
+ throw error;
357
+ }
348
358
  return token.length === 0 ? undefined : token;
349
359
  }
350
360
  /**
@@ -391,11 +401,11 @@ or authenticate with the GitHub CLI:
391
401
  /**
392
402
  env のトークンが失効したとき、gh auth token に 1 回だけ切り替える。切り替えたら true
393
403
  */
394
- retryWithFallbackToken() {
404
+ async retryWithFallbackToken() {
395
405
  if (this.usedFallback)
396
406
  return false;
397
407
  this.usedFallback = true;
398
- const newToken = this.tokenFromGh(this.host);
408
+ const newToken = await this.tokenFromGh(this.host);
399
409
  if (newToken === undefined || newToken === this.token)
400
410
  return false;
401
411
  this.diagnostics.warning(TOKEN_FALLBACK_WARNING);
@@ -409,7 +419,9 @@ or authenticate with the GitHub CLI:
409
419
  headers,
410
420
  ...(body !== undefined && { body }),
411
421
  redirect: 'manual',
412
- signal: AbortSignal.timeout(this.timeoutMilliseconds),
422
+ signal: this.signal === undefined
423
+ ? AbortSignal.timeout(this.timeoutMilliseconds)
424
+ : AbortSignal.any([AbortSignal.timeout(this.timeoutMilliseconds), this.signal]),
413
425
  });
414
426
  const text = await response.text();
415
427
  return new RestResponse({
@@ -421,10 +433,17 @@ or authenticate with the GitHub CLI:
421
433
  });
422
434
  }
423
435
  catch (error) {
436
+ this.throwIfCancelled();
424
437
  throw new TransportFailure(describeTransportFailure(error), { cause: error });
425
438
  }
426
439
  }
440
+ // 取り消しは時間切れ(AbortError)と名前で分けられないので、signal で見分ける
441
+ throwIfCancelled() {
442
+ if (this.signal?.aborted === true)
443
+ throw cancelledBy(this.signal);
444
+ }
427
445
  async sendRest(method, url, options) {
446
+ await this.ensureToken();
428
447
  const { json } = options;
429
448
  const base = this.requestHeaders(options.apiVersion);
430
449
  const headers = json === undefined ? base : { ...base, 'Content-Type': 'application/json' };
@@ -437,6 +456,7 @@ or authenticate with the GitHub CLI:
437
456
  response = await this.send('POST', this.graphqlUrl, { ...this.requestHeaders(), 'Content-Type': 'application/json' }, JSON.stringify({ query, variables }));
438
457
  }
439
458
  catch (error) {
459
+ this.throwIfCancelled();
440
460
  throw new GraphqlFailure(error instanceof Error ? error.message : String(error), { cause: error });
441
461
  }
442
462
  const { statusCode } = response;
@@ -488,19 +508,23 @@ or authenticate with the GitHub CLI:
488
508
  return new GitHubAPIError(`GraphQL query error: ${message}`, detail);
489
509
  }
490
510
  async runGraphql(query, variables, isTolerated) {
511
+ // 認証の失敗と取り消しを、GraphQL の失敗に包まないよう try の外で待つ
512
+ await this.ensureToken();
491
513
  try {
492
514
  return await this.sendGraphql(query, variables, isTolerated);
493
515
  }
494
516
  catch (error) {
517
+ this.throwIfCancelled();
495
518
  const failure = toGraphqlFailure(error);
496
519
  if (!isUnauthorized(failure))
497
520
  throw this.classifyGraphqlFailure(failure);
498
- if (!this.retryWithFallbackToken())
521
+ if (!await this.retryWithFallbackToken())
499
522
  throw new GitHubAuthError(`GraphQL authentication error: ${failure.message}`, { cause: failure });
500
523
  try {
501
524
  return await this.sendGraphql(query, variables, isTolerated);
502
525
  }
503
526
  catch (retryError) {
527
+ this.throwIfCancelled();
504
528
  throw this.classifyGraphqlFailure(toGraphqlFailure(retryError));
505
529
  }
506
530
  }
@@ -515,6 +539,15 @@ or authenticate with the GitHub CLI:
515
539
  throw new GitHubAPIError(`refusing to follow a URL on a different host than the API: ${target}`);
516
540
  }
517
541
  /**
542
+ トークンが無ければ gh auth token を 1 回だけ読む。読めなければ GitHubAuthError、取り消されたら CancelledError
543
+ */
544
+ async ensureToken() {
545
+ if (this.token !== '')
546
+ return;
547
+ this.ghToken ??= this.loadGhToken();
548
+ await this.ghToken;
549
+ }
550
+ /**
518
551
  REST の要求(401 のときは gh auth token に切り替えて 1 回だけ再試行する)。
519
552
  target は `/user` のようなパス(base の後ろにつなぐ)か、`https://` で始まる絶対 URL(Link ヘッダの next など)。
520
553
  失敗の状態コードは例外にせず、そのまま返す。呼び出し側が isSuccess を見て handleHttpError に渡す
@@ -523,7 +556,7 @@ or authenticate with the GitHub CLI:
523
556
  this.assertSameOrigin(target);
524
557
  const url = buildUrl(this.apiUrl, target, options.params);
525
558
  const response = await this.sendRest(method, url, options);
526
- return response.statusCode === 401 && this.retryWithFallbackToken() ? this.sendRest(method, url, options) : response;
559
+ return response.statusCode === 401 && await this.retryWithFallbackToken() ? this.sendRest(method, url, options) : response;
527
560
  }
528
561
  /**
529
562
  REST の要求を送り、成功した応答の JSON を返す。失敗の応答は handleHttpError の例外にする。
@@ -84,6 +84,10 @@ export declare class IssuesApi extends ProjectsApi {
84
84
  */
85
85
  addIssueComment(owner: string, repository: string, number: number, body: string): Promise<JsonObject>;
86
86
  /**
87
+ Issue・PR のコメントを全件取る(REST)
88
+ */
89
+ listIssueComments(owner: string, repository: string, number: number): Promise<readonly JsonValue[]>;
90
+ /**
87
91
  Issue 番号から GraphQL Node ID を取る。見つからなければ GitHubNotFoundError
88
92
  */
89
93
  getIssueNodeId(owner: string, repository: string, number: number): Promise<string>;
@@ -190,6 +190,12 @@ export class IssuesApi extends ProjectsApi {
190
190
  return this.restObject('POST', `${repositoryPath(owner, repository)}/issues/${String(number)}/comments`, { json: { body } });
191
191
  }
192
192
  /**
193
+ Issue・PR のコメントを全件取る(REST)
194
+ */
195
+ async listIssueComments(owner, repository, number) {
196
+ return this.listAll(`${repositoryPath(owner, repository)}/issues/${String(number)}/comments`, { per_page: ISSUES_PER_PAGE });
197
+ }
198
+ /**
193
199
  Issue 番号から GraphQL Node ID を取る。見つからなければ GitHubNotFoundError
194
200
  */
195
201
  async getIssueNodeId(owner, repository, number) {
@@ -1,5 +1,6 @@
1
1
  import type { JsonObject } from '../../domain/json.js';
2
2
  import type { PullRequestsByHeadReadout } from '../../domain/issue-readout.js';
3
+ import type { JsonValue } from '../../domain/python-format.js';
3
4
  import { IssuesApi } from './issues.js';
4
5
  /**
5
6
  base のブランチ名で引いた、同じリポの開いている PR
@@ -197,6 +198,14 @@ export declare class PullsApi extends IssuesApi {
197
198
  */
198
199
  addToStack(owner: string, repository: string, stackNumber: number, pullRequestNumbers: readonly number[]): Promise<PullRequestStack>;
199
200
  /**
201
+ PR の state(REST の `open`・`closed`)
202
+ */
203
+ getPullRequestState(owner: string, repository: string, number: number): Promise<string>;
204
+ /**
205
+ PR のレビューのコメント(行に付いたインラインコメント)を全件取る(REST)
206
+ */
207
+ listPullRequestReviewComments(owner: string, repository: string, number: number): Promise<readonly JsonValue[]>;
208
+ /**
200
209
  open の dependabot の PR を全件取る(GraphQL)。pullRequests に author の引数が無いので、全ページを辿ってから絞る。
201
210
  GraphQL のノードをそのまま返す
202
211
  */
@@ -10,6 +10,7 @@ import { asObject, isTruthy, numberOrNull, requireNumber, requireString, require
10
10
  import { QUERY_GET_PULL_REQUEST_FOR_FINISH, QUERY_GET_PULL_REQUEST_FOR_MERGE, QUERY_GET_PULL_REQUEST_FOR_MERGE_WITHOUT_QUEUE, QUERY_GET_PULL_REQUEST_SLIM, QUERY_GET_PULL_REQUEST_WITH_REVIEWS, QUERY_LIST_OPEN_PULL_REQUESTS, QUERY_LIST_PULL_REQUESTS_BY_BASE, QUERY_LIST_PULL_REQUESTS_BY_HEAD } from './queries.js';
11
11
  import { readPullRequests } from './readout.js';
12
12
  import { repositoryPath } from './rest-path.js';
13
+ const REVIEW_COMMENTS_PER_PAGE = 100;
13
14
  /**
14
15
  Stacks API が求める X-GitHub-Api-Version(https://docs.github.com/en/rest/pulls/stacks)
15
16
  */
@@ -321,6 +322,19 @@ export class PullsApi extends IssuesApi {
321
322
  }));
322
323
  }
323
324
  /**
325
+ PR の state(REST の `open`・`closed`)
326
+ */
327
+ async getPullRequestState(owner, repository, number) {
328
+ const pullRequest = await this.restObject('GET', `${repositoryPath(owner, repository)}/pulls/${String(number)}`);
329
+ return requireString(pullRequest['state'], 'state');
330
+ }
331
+ /**
332
+ PR のレビューのコメント(行に付いたインラインコメント)を全件取る(REST)
333
+ */
334
+ async listPullRequestReviewComments(owner, repository, number) {
335
+ return this.listAll(`${repositoryPath(owner, repository)}/pulls/${String(number)}/comments`, { per_page: REVIEW_COMMENTS_PER_PAGE });
336
+ }
337
+ /**
324
338
  open の dependabot の PR を全件取る(GraphQL)。pullRequests に author の引数が無いので、全ページを辿ってから絞る。
325
339
  GraphQL のノードをそのまま返す
326
340
  */
@@ -32,6 +32,10 @@ export declare class ReposApi extends GitHubClientBase {
32
32
  */
33
33
  getRepositoryId(owner: string, name: string): Promise<string>;
34
34
  /**
35
+ 利用者のリポへの権限(REST の collaborators の permission)。maintain は write、triage は read で返る
36
+ */
37
+ getCollaboratorPermission(owner: string, repository: string, user: string): Promise<string>;
38
+ /**
35
39
  ブランチの最新 commit の SHA(REST)。見つからなければ GitHubNotFoundError
36
40
  */
37
41
  getBranchSha(owner: string, repository: string, branch: string): Promise<string>;
@@ -4,7 +4,7 @@ import { GitHubClientBase } from './client.js';
4
4
  import { GitHubAPIError, GitHubNotFoundError } from './errors.js';
5
5
  import { asArray, isTruthy, requireString } from './payload.js';
6
6
  import { MUTATION_CREATE_LINKED_BRANCH, QUERY_GET_REPOSITORY_ID } from './queries.js';
7
- import { encodePath, repositoryPath } from './rest-path.js';
7
+ import { encodePath, encodePathSegment, repositoryPath } from './rest-path.js';
8
8
  const ALERTS_PER_PAGE = 100;
9
9
  const NO_CONTENT = 204;
10
10
  const NOT_FOUND = 404;
@@ -59,6 +59,13 @@ export class ReposApi extends GitHubClientBase {
59
59
  return requireString(jsonField(repository, 'id'), 'repository.id');
60
60
  }
61
61
  /**
62
+ 利用者のリポへの権限(REST の collaborators の permission)。maintain は write、triage は read で返る
63
+ */
64
+ async getCollaboratorPermission(owner, repository, user) {
65
+ const result = await this.restObject('GET', `${repositoryPath(owner, repository)}/collaborators/${encodePathSegment(user)}/permission`);
66
+ return requireString(jsonField(result, 'permission'), 'permission');
67
+ }
68
+ /**
62
69
  ブランチの最新 commit の SHA(REST)。見つからなければ GitHubNotFoundError
63
70
  */
64
71
  async getBranchSha(owner, repository, branch) {
@@ -26,12 +26,16 @@ export interface NxGraphOptions {
26
26
  nx graph の実行上限(秒)。既定は NX_GRAPH_TIMEOUT_SECONDS
27
27
  */
28
28
  readonly timeoutSeconds?: number | undefined;
29
+ /**
30
+ MCP の要求の取り消し。取り消されたら nx を止めて CancelledError を投げる
31
+ */
32
+ readonly signal?: Readonly<AbortSignal> | undefined;
29
33
  }
30
34
  /**
31
35
  nx の project graph から `{プロジェクト名: NxProject}` を返す。stdout では大きな JSON が切れるため、一時ファイルに書かせて読む。
32
36
  nx が無い・実行失敗・部分 graph・JSON の解析失敗なら undefined
33
37
  */
34
- export declare function nxProjects(toplevel: string, options?: Readonly<NxGraphOptions>): ReadonlyMap<string, NxProject> | undefined;
38
+ export declare function nxProjects(toplevel: string, options?: Readonly<NxGraphOptions>): Promise<ReadonlyMap<string, NxProject> | undefined>;
35
39
  /**
36
40
  `baseReference...head` の変更ファイル(リポジトリ root からの相対パス)を返す。baseReference は、ブランチのほか、コミットの SHA(base の記録の位置)も受ける。
37
41
  rename 検出だと移動元のプロジェクトが漏れ、`core.quotePath` だと非 ASCII パスが一致しなくなるため、`--no-renames` と NUL 区切りで取る。
@@ -4,14 +4,14 @@
4
4
  // 割り当ては `.githooks/pre-push/check-version-plan-required.sh` と同じ規則。
5
5
  // nx の project graph → git diff → project root との最長一致、の順で求める。
6
6
  // 判定できない場合は例外ではなく undefined を返し、呼び出し側が警告して割り当てを飛ばす(フェイルオープン)。
7
- import { spawnSync } from 'node:child_process';
8
7
  import { accessSync, constants, mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs';
9
8
  import path from 'node:path';
10
9
  import { isJsonObject, jsonField, tryParseJsonText } from '../domain/json.js';
11
10
  import { compareStrings, isJsonArray, pythonRepr } from '../domain/python-format.js';
12
11
  import { GitCommandError, runGit } from './git.js';
13
- import { isFileNotFound } from './os-error.js';
12
+ import { isFileNotFound, OsError } from './os-error.js';
14
13
  import { TMP_DIR } from './paths.js';
14
+ import { runProcess } from './process-run.js';
15
15
  import { readTextFile } from './text-file.js';
16
16
  /**
17
17
  nx graph の実行上限(秒)
@@ -85,7 +85,7 @@ function projectsFromGraph(text) {
85
85
  nx の project graph から `{プロジェクト名: NxProject}` を返す。stdout では大きな JSON が切れるため、一時ファイルに書かせて読む。
86
86
  nx が無い・実行失敗・部分 graph・JSON の解析失敗なら undefined
87
87
  */
88
- export function nxProjects(toplevel, options = {}) {
88
+ export async function nxProjects(toplevel, options = {}) {
89
89
  const nx = resolveNx(toplevel);
90
90
  if (nx === undefined)
91
91
  return undefined;
@@ -100,16 +100,23 @@ export function nxProjects(toplevel, options = {}) {
100
100
  }
101
101
  try {
102
102
  const graphFile = path.join(work, 'graph.json');
103
- const result = spawnSync(nx, ['graph', `--file=${graphFile}`], {
104
- cwd: toplevel,
105
- encoding: 'utf8',
106
- stdio: ['ignore', 'pipe', 'pipe'],
107
- timeout: (options.timeoutSeconds ?? NX_GRAPH_TIMEOUT_SECONDS) * 1000,
108
- killSignal: 'SIGKILL',
109
- // interface-env: none
110
- env: { ...process.env, NX_DAEMON: 'false' },
111
- });
112
- if (result.error !== undefined || result.status !== 0 || result.stderr.includes('Showing partial graph'))
103
+ let result;
104
+ try {
105
+ result = await runProcess(nx, ['graph', `--file=${graphFile}`], {
106
+ cwd: toplevel,
107
+ stdin: 'ignore',
108
+ timeoutMilliseconds: (options.timeoutSeconds ?? NX_GRAPH_TIMEOUT_SECONDS) * 1000,
109
+ // interface-env: none
110
+ env: { ...process.env, NX_DAEMON: 'false' },
111
+ signal: options.signal,
112
+ });
113
+ }
114
+ catch (error) {
115
+ if (error instanceof OsError)
116
+ return undefined;
117
+ throw error;
118
+ }
119
+ if (result.isTimedOut || result.exitCode !== 0 || result.stderr.includes('Showing partial graph'))
113
120
  return undefined;
114
121
  let text;
115
122
  try {
@@ -0,0 +1,57 @@
1
+ import { CancelledError } from '../domain/errors.js';
2
+ import type { ChildStdin } from './child-stdin.js';
3
+ /**
4
+ 子の標準出力・標準エラーを溜める上限。出力が大きい git(log・diff 等)でも切れない大きさにし、超えた分は捨てる
5
+ */
6
+ export declare const MAX_OUTPUT_BYTES: number;
7
+ /**
8
+ 止めるときに SIGTERM を送ってから SIGKILL を送るまでの猶予。git が lock ファイルを片付ける時間
9
+ */
10
+ export declare const KILL_GRACE_MILLISECONDS = 1000;
11
+ export interface ProcessOptions {
12
+ readonly cwd?: string | undefined;
13
+ /**
14
+ 子の環境変数の全体。省略すると今の環境を継承する
15
+ */
16
+ readonly env?: Readonly<Record<string, string | undefined>> | undefined;
17
+ /**
18
+ true なら command をシェルで解釈する
19
+ */
20
+ readonly shell?: boolean | undefined;
21
+ /**
22
+ 省略すると childStdin() に従う
23
+ */
24
+ readonly stdin?: ChildStdin | undefined;
25
+ /**
26
+ 過ぎたら止めて、isTimedOut が true の結果を返す
27
+ */
28
+ readonly timeoutMilliseconds?: number | undefined;
29
+ /**
30
+ MCP の要求の取り消し。取り消されたら子を止めて CancelledError を投げる
31
+ */
32
+ readonly signal?: Readonly<AbortSignal> | undefined;
33
+ }
34
+ export interface ProcessResult {
35
+ /**
36
+ シグナルで終わったときは null
37
+ */
38
+ readonly exitCode: number | null;
39
+ readonly signal: NodeJS.Signals | null;
40
+ readonly stdout: string;
41
+ readonly stderr: string;
42
+ readonly isTimedOut: boolean;
43
+ }
44
+ /**
45
+ signal の取り消しの理由を持つ CancelledError
46
+ */
47
+ export declare function cancelledBy(signal: Readonly<AbortSignal>): CancelledError;
48
+ /**
49
+ 生きている子のグループに SIGTERM を送る。サーバの終了のときに呼ぶ
50
+ */
51
+ export declare function killRunningProcesses(): void;
52
+ /**
53
+ 子プロセスを動かし、終わるのを待つ。起動に失敗(ENOENT など)したら OsError を投げる。
54
+ 子が 0 で終わっていれば、取り消しと重なっても成功の結果を返す
55
+ */
56
+ export declare function runProcess(command: string, arguments_: readonly string[], options?: Readonly<ProcessOptions>): Promise<ProcessResult>;
57
+ //# sourceMappingURL=process-run.d.ts.map
@@ -0,0 +1,168 @@
1
+ // 待つ時間の長い子プロセスを、イベントループを止めずに動かす。時間切れと MCP の要求の取り消しで、子をプロセスグループごと止める。
2
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- Node の型が mutable */
3
+ import { spawn } from 'node:child_process';
4
+ import { CancelledError } from '../domain/errors.js';
5
+ import { normalizeNewlines } from '../domain/python-format.js';
6
+ import { childStdin } from './child-stdin.js';
7
+ import { toOsError } from './os-error.js';
8
+ /**
9
+ 子の標準出力・標準エラーを溜める上限。出力が大きい git(log・diff 等)でも切れない大きさにし、超えた分は捨てる
10
+ */
11
+ export const MAX_OUTPUT_BYTES = 1024 * 1024 * 1024;
12
+ /**
13
+ 止めるときに SIGTERM を送ってから SIGKILL を送るまでの猶予。git が lock ファイルを片付ける時間
14
+ */
15
+ export const KILL_GRACE_MILLISECONDS = 1000;
16
+ const running = new Set();
17
+ // 別のセッションの子には端末のシグナルが届かないので、受けたらグループへ送ってから既定の動きに戻す
18
+ const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
19
+ function createCapture() {
20
+ const chunks = [];
21
+ let captured = 0;
22
+ return {
23
+ push: (chunk) => {
24
+ const room = MAX_OUTPUT_BYTES - captured;
25
+ if (room <= 0)
26
+ return;
27
+ const kept = chunk.subarray(0, Math.min(room, chunk.length));
28
+ captured += kept.length;
29
+ chunks.push(kept);
30
+ },
31
+ text: () => normalizeNewlines(Buffer.concat(chunks).toString('utf8')),
32
+ };
33
+ }
34
+ function reasonText(reason) {
35
+ if (typeof reason === 'string')
36
+ return reason;
37
+ return reason instanceof Error ? reason.message : String(reason);
38
+ }
39
+ /**
40
+ signal の取り消しの理由を持つ CancelledError
41
+ */
42
+ export function cancelledBy(signal) {
43
+ return new CancelledError(reasonText(signal.reason));
44
+ }
45
+ // 子はグループの頭なので、負の pid で孫(git-remote-https・フック・シェルの下のコマンド)にも送る
46
+ function signalGroup(child, signal) {
47
+ if (child.pid === undefined)
48
+ return;
49
+ try {
50
+ process.kill(-child.pid, signal);
51
+ }
52
+ catch {
53
+ // 既に終わっている
54
+ }
55
+ }
56
+ // SIGTERM で片付けの機会を渡し、猶予の後も残っていれば SIGKILL で止める
57
+ function terminateGroup(child) {
58
+ signalGroup(child, 'SIGTERM');
59
+ setTimeout(() => {
60
+ signalGroup(child, 'SIGKILL');
61
+ }, KILL_GRACE_MILLISECONDS).unref();
62
+ }
63
+ /**
64
+ 生きている子のグループに SIGTERM を送る。サーバの終了のときに呼ぶ
65
+ */
66
+ export function killRunningProcesses() {
67
+ for (const child of running)
68
+ signalGroup(child, 'SIGTERM');
69
+ }
70
+ /**
71
+ 子プロセスを動かし、終わるのを待つ。起動に失敗(ENOENT など)したら OsError を投げる。
72
+ 子が 0 で終わっていれば、取り消しと重なっても成功の結果を返す
73
+ */
74
+ export async function runProcess(command, arguments_, options = {}) {
75
+ const { signal } = options;
76
+ if (signal?.aborted === true)
77
+ throw cancelledBy(signal);
78
+ const timeout = options.timeoutMilliseconds === undefined ? undefined : AbortSignal.timeout(options.timeoutMilliseconds);
79
+ // 時間切れのとき、フックなどの孫までまとめて止めるため、子を自分のグループの頭にする
80
+ const child = spawn(command, [...arguments_], {
81
+ cwd: options.cwd,
82
+ env: options.env,
83
+ shell: options.shell,
84
+ stdio: [options.stdin ?? childStdin(), 'pipe', 'pipe'],
85
+ detached: true,
86
+ });
87
+ running.add(child);
88
+ const stdout = createCapture();
89
+ const stderr = createCapture();
90
+ child.stdout.on('data', stdout.push);
91
+ child.stderr.on('data', stderr.push);
92
+ return await new Promise((resolve, reject) => {
93
+ let stopped;
94
+ let isSettled = false;
95
+ const hasExited = () => child.exitCode !== null || child.signalCode !== null;
96
+ const onTimeout = () => {
97
+ stop('timed-out');
98
+ };
99
+ const onAbort = () => {
100
+ stop('cancelled');
101
+ };
102
+ const forward = (received) => {
103
+ signalGroup(child, received);
104
+ finish();
105
+ process.kill(process.pid, received);
106
+ };
107
+ const finish = () => {
108
+ isSettled = true;
109
+ running.delete(child);
110
+ timeout?.removeEventListener('abort', onTimeout);
111
+ signal?.removeEventListener('abort', onAbort);
112
+ for (const name of FORWARDED_SIGNALS)
113
+ process.removeListener(name, forward);
114
+ };
115
+ const settle = (exitCode, exitSignal) => {
116
+ if (isSettled)
117
+ return;
118
+ finish();
119
+ if (stopped === 'cancelled' && signal !== undefined) {
120
+ reject(cancelledBy(signal));
121
+ return;
122
+ }
123
+ resolve({ exitCode, signal: exitSignal, stdout: stdout.text(), stderr: stderr.text(), isTimedOut: stopped === 'timed-out' });
124
+ };
125
+ // 止めた後は close を待たない。パイプを握った孫が残ると、close は孫が終わるまで来ない
126
+ const settleOnExit = () => {
127
+ child.stdout.destroy();
128
+ child.stderr.destroy();
129
+ settle(child.exitCode, child.signalCode);
130
+ };
131
+ const stop = (reason) => {
132
+ if (isSettled || stopped !== undefined)
133
+ return;
134
+ terminateGroup(child);
135
+ // 子が先に終わっていれば、その結果を返す。0 で終わっていない取り消しだけは、続きを動かさないために投げる
136
+ if (hasExited()) {
137
+ if (reason === 'cancelled' && child.exitCode !== 0)
138
+ stopped = reason;
139
+ settleOnExit();
140
+ return;
141
+ }
142
+ stopped = reason;
143
+ };
144
+ timeout?.addEventListener('abort', onTimeout, { once: true });
145
+ signal?.addEventListener('abort', onAbort, { once: true });
146
+ for (const name of FORWARDED_SIGNALS)
147
+ process.on(name, forward);
148
+ child.once('error', (error) => {
149
+ if (isSettled)
150
+ return;
151
+ finish();
152
+ const converted = toOsError(error);
153
+ reject(converted instanceof Error ? converted : error);
154
+ });
155
+ child.once('exit', (exitCode) => {
156
+ if (stopped === undefined)
157
+ return;
158
+ // 止める前に 0 で終わっていた(止めるのと終わるのが重なった)なら成功とする
159
+ if (exitCode === 0)
160
+ stopped = undefined;
161
+ settleOnExit();
162
+ });
163
+ child.once('close', (exitCode, exitSignal) => {
164
+ settle(exitCode, exitSignal);
165
+ });
166
+ });
167
+ }
168
+ //# sourceMappingURL=process-run.js.map
@@ -11,11 +11,8 @@ export interface SetupResult {
11
11
  readonly stderr: string;
12
12
  }
13
13
  /**
14
- setup_command を shell 経由で実行して、結果を構造化して返す。
15
-
16
- stdin は常に閉じて、対話プロンプトで stall しないようにする。
17
- timeoutSeconds を超えた場合は子プロセスを kill し、exitCode -1 の SetupResult を返す(例外は投げない)。-1 は timeout 起因の目印。
18
- timeoutSeconds が 0 なら、Python と同じくすぐ時間切れになる
14
+ setup_command を shell 経由で実行して、結果を構造化して返す。stdin は閉じて、対話プロンプトで止まらないようにする。
15
+ timeoutSeconds を超えたら止めて exitCode -1 を返す(0 ならすぐ時間切れ)。signal で取り消されたら、シェルの下のコマンドごと止めて CancelledError を投げる
19
16
  */
20
- export declare function runSetupCommand(command: string, cwd: string, timeoutSeconds?: number): SetupResult;
17
+ export declare function runSetupCommand(command: string, cwd: string, timeoutSeconds?: number, signal?: Readonly<AbortSignal>): Promise<SetupResult>;
21
18
  //# sourceMappingURL=worktree-setup.d.ts.map
@@ -1,9 +1,6 @@
1
1
  // ワークツリー作成後の setup_command の実行。Python の subprocess.run(shell=True)と同じ結果にする。
2
- import { spawnSync } from 'node:child_process';
3
2
  import os from 'node:os';
4
- import { normalizeNewlines } from '../domain/python-format.js';
5
- import { MAX_OUTPUT_BYTES } from './git.js';
6
- import { hasErrorCode, toOsError } from './os-error.js';
3
+ import { runProcess } from './process-run.js';
7
4
  const SIGNAL_NUMBERS = new Map(Object.entries(os.constants.signals));
8
5
  function signalNumber(signal) {
9
6
  return signal === null ? -1 : -(SIGNAL_NUMBERS.get(signal) ?? 1);
@@ -13,29 +10,14 @@ function timeoutMilliseconds(timeoutSeconds) {
13
10
  return timeoutSeconds === undefined ? undefined : Math.max(1, timeoutSeconds * 1000);
14
11
  }
15
12
  /**
16
- setup_command を shell 経由で実行して、結果を構造化して返す。
17
-
18
- stdin は常に閉じて、対話プロンプトで stall しないようにする。
19
- timeoutSeconds を超えた場合は子プロセスを kill し、exitCode -1 の SetupResult を返す(例外は投げない)。-1 は timeout 起因の目印。
20
- timeoutSeconds が 0 なら、Python と同じくすぐ時間切れになる
13
+ setup_command を shell 経由で実行して、結果を構造化して返す。stdin は閉じて、対話プロンプトで止まらないようにする。
14
+ timeoutSeconds を超えたら止めて exitCode -1 を返す(0 ならすぐ時間切れ)。signal で取り消されたら、シェルの下のコマンドごと止めて CancelledError を投げる
21
15
  */
22
- export function runSetupCommand(command, cwd, timeoutSeconds) {
23
- const result = spawnSync(command, {
24
- cwd,
25
- shell: true,
26
- encoding: 'utf8',
27
- stdio: ['ignore', 'pipe', 'pipe'],
28
- timeout: timeoutMilliseconds(timeoutSeconds),
29
- killSignal: 'SIGKILL',
30
- maxBuffer: MAX_OUTPUT_BYTES,
31
- });
32
- const isTimedOut = hasErrorCode(result.error) && result.error.code === 'ETIMEDOUT';
33
- if (!isTimedOut && result.error !== undefined)
34
- throw toOsError(result.error);
35
- const stdout = normalizeNewlines(result.stdout);
36
- const stderr = normalizeNewlines(result.stderr);
37
- return isTimedOut
16
+ export async function runSetupCommand(command, cwd, timeoutSeconds, signal) {
17
+ const result = await runProcess(command, [], { cwd, shell: true, stdin: 'ignore', timeoutMilliseconds: timeoutMilliseconds(timeoutSeconds), signal });
18
+ const { stdout, stderr } = result;
19
+ return result.isTimedOut
38
20
  ? { command, exitCode: -1, stdout, stderr: `${stderr}timeout after ${String(timeoutSeconds)} seconds`.trimStart() }
39
- : { command, exitCode: result.status ?? signalNumber(result.signal), stdout, stderr };
21
+ : { command, exitCode: result.exitCode ?? signalNumber(result.signal), stdout, stderr };
40
22
  }
41
23
  //# sourceMappingURL=worktree-setup.js.map