@pecot/workflow-mcp 8.0.1-dev.59 → 8.0.1-dev.61

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 (48) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/cli/dist/commands/base-reading.d.ts +1 -1
  3. package/cli/dist/commands/base-reading.js +1 -1
  4. package/cli/dist/commands/board-sync.js +1 -1
  5. package/cli/dist/commands/github-client.d.ts +6 -2
  6. package/cli/dist/commands/github-client.js +12 -4
  7. package/cli/dist/commands/issue-comment.js +3 -2
  8. package/cli/dist/commands/issue-show.js +3 -2
  9. package/cli/dist/commands/output.d.ts +4 -0
  10. package/cli/dist/commands/output.js +1 -0
  11. package/cli/dist/commands/pr-merge.js +3 -2
  12. package/cli/dist/commands/pr-restack.js +85 -15
  13. package/cli/dist/commands/pr.js +18 -18
  14. package/cli/dist/commands/project.js +5 -3
  15. package/cli/dist/commands/release.js +8 -8
  16. package/cli/dist/commands/restack-reading.d.ts +4 -0
  17. package/cli/dist/commands/restack-reading.js +1 -1
  18. package/cli/dist/commands/session-finish.js +18 -8
  19. package/cli/dist/commands/session.js +1 -1
  20. package/cli/dist/commands/tracker-sync-dependabot.js +1 -1
  21. package/cli/dist/commands/tracker-sync-security.js +1 -1
  22. package/cli/dist/commands/worktree.js +4 -3
  23. package/cli/dist/domain/errors.d.ts +5 -0
  24. package/cli/dist/domain/errors.js +5 -0
  25. package/cli/dist/domain/release.d.ts +10 -1
  26. package/cli/dist/domain/release.js +10 -6
  27. package/cli/dist/infra/git.d.ts +20 -16
  28. package/cli/dist/infra/git.js +40 -96
  29. package/cli/dist/infra/github/client.d.ts +12 -1
  30. package/cli/dist/infra/github/client.js +49 -16
  31. package/cli/dist/infra/github/pulls.d.ts +4 -0
  32. package/cli/dist/infra/github/pulls.js +6 -0
  33. package/cli/dist/infra/nx-scope.d.ts +5 -1
  34. package/cli/dist/infra/nx-scope.js +20 -13
  35. package/cli/dist/infra/process-run.d.ts +57 -0
  36. package/cli/dist/infra/process-run.js +168 -0
  37. package/cli/dist/infra/worktree-setup.d.ts +3 -6
  38. package/cli/dist/infra/worktree-setup.js +8 -26
  39. package/cli/dist/infra/worktree.d.ts +5 -1
  40. package/cli/dist/infra/worktree.js +4 -4
  41. package/cli/dist/mcp/result.d.ts +3 -3
  42. package/cli/dist/mcp/result.js +4 -3
  43. package/cli/dist/mcp/serve.d.ts +12 -0
  44. package/cli/dist/mcp/serve.js +30 -2
  45. package/cli/dist/mcp/server.d.ts +4 -0
  46. package/cli/dist/mcp/server.js +14 -6
  47. package/npm-shrinkwrap.json +2 -2
  48. package/package.json +1 -1
@@ -21,7 +21,7 @@ export async function readRestackDecision(target) {
21
21
  }
22
22
  if (remote === undefined)
23
23
  return { kind: 'remote-unreachable', lowerPullRequest };
24
- const lowerHead = remoteBranchHead(target.cwd, remote, reading.record.branch);
24
+ const lowerHead = await remoteBranchHead(target.cwd, remote, reading.record.branch, target.signal);
25
25
  if (!lowerHead.isReachable)
26
26
  return { kind: 'remote-unreachable', lowerPullRequest };
27
27
  const decision = decideRestack({ reading, developBranch: target.developBranch, lowerPullRequest, lowerHead: lowerHead.sha });
@@ -11,7 +11,7 @@ import { createIssueReference } from '../domain/reference-parser.js';
11
11
  import { RESTACK_PATH } from '../domain/restack.js';
12
12
  import { isSameRepository } from '../domain/repository-resolver.js';
13
13
  import { FLAG_PECOT_BASE, FLAG_PECOT_SESSION_TITLE } from '../domain/state.js';
14
- import { gitCurrentBranch, GitCommandError, runGit } from '../infra/git.js';
14
+ import { GIT_TIMED_OUT, gitCurrentBranch, GitCommandError, NON_INTERACTIVE_GIT, REMOTE_TIMEOUT_MILLISECONDS, runGit, runGitAsync } from '../infra/git.js';
15
15
  import { GitHubAPIError, GitHubNotFoundError, isClosedByAnotherRequest, isMissingReferenceError } from '../infra/github/errors.js';
16
16
  import { isFileNotFound } from '../infra/os-error.js';
17
17
  import { removeFlag } from '../infra/state-store.js';
@@ -271,13 +271,23 @@ function resolveCheckoutTarget(cwd, config, location, out) {
271
271
  return undefined;
272
272
  }
273
273
  }
274
- function didRunLocalStep(context, operation, cwd, arguments_, failure) {
274
+ // isRemote の git(pull)は、認証の入力を待たず、取り消しと時間切れで止める
275
+ async function didRunLocalStep(context, operation, cwd, arguments_, failure, isRemote = false) {
275
276
  const { out, isDryRun } = context;
276
277
  out.planned(operation);
277
278
  if (isDryRun)
278
279
  return true;
279
280
  try {
280
- runGit(arguments_, { cwd, check: true });
281
+ if (isRemote) {
282
+ const result = await runGitAsync(arguments_, { cwd, check: true, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: REMOTE_TIMEOUT_MILLISECONDS, signal: out.signal });
283
+ if (result.exitCode === GIT_TIMED_OUT) {
284
+ out.warning(`${failure} failed: timed out after ${String(REMOTE_TIMEOUT_MILLISECONDS / 1000)} seconds`);
285
+ return false;
286
+ }
287
+ }
288
+ else {
289
+ runGit(arguments_, { cwd, check: true });
290
+ }
281
291
  }
282
292
  catch (error) {
283
293
  if (!(error instanceof GitCommandError) && !isFileNotFound(error))
@@ -288,7 +298,7 @@ function didRunLocalStep(context, operation, cwd, arguments_, failure) {
288
298
  out.done(operation);
289
299
  return true;
290
300
  }
291
- function localCleanupAfterMerge(context, headBranch, config, location) {
301
+ async function localCleanupAfterMerge(context, headBranch, config, location) {
292
302
  const { out } = context;
293
303
  const cwd = process.cwd();
294
304
  const remote = sameRepositoryRemote(cwd, location, out);
@@ -306,18 +316,18 @@ function localCleanupAfterMerge(context, headBranch, config, location) {
306
316
  if (currentBranch === checkoutTarget) {
307
317
  settle(out, { verb: 'unchanged', target: `current branch ${checkoutTarget}` });
308
318
  }
309
- else if (!didRunLocalStep(context, { verb: 'set', target: `current branch to ${checkoutTarget}` }, cwd, ['checkout', checkoutTarget], `checking out ${checkoutTarget}`)) {
319
+ else if (!await didRunLocalStep(context, { verb: 'set', target: `current branch to ${checkoutTarget}` }, cwd, ['checkout', checkoutTarget], `checking out ${checkoutTarget}`)) {
310
320
  // checkout が失敗したら、pull と branch -D は別のブランチに当たるので止める
311
321
  if (currentBranch !== undefined)
312
322
  context.record.currentBranch = currentBranch;
313
323
  return;
314
324
  }
315
325
  context.record.currentBranch = checkoutTarget;
316
- didRunLocalStep(context, { verb: 'update', target: `${checkoutTarget} from ${remote}/${developBranch}` }, cwd, ['pull', remote, developBranch], `pulling ${developBranch}`);
326
+ await didRunLocalStep(context, { verb: 'update', target: `${checkoutTarget} from ${remote}/${developBranch}` }, cwd, ['pull', remote, developBranch], `pulling ${developBranch}`, true);
317
327
  if (headBranch === checkoutTarget) {
318
328
  settle(out, { verb: 'skip', target: `deleting local branch ${headBranch} (it is the checkout target)` });
319
329
  }
320
- else if (didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`)) {
330
+ else if (await didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`)) {
321
331
  context.record.deletedBranches.push({ branch: headBranch, location: 'local' });
322
332
  }
323
333
  }
@@ -366,7 +376,7 @@ async function finish(input, context) {
366
376
  await deleteMergedBranch(context, client, location, pr.head_ref);
367
377
  if (input.skip_local_cleanup)
368
378
  return;
369
- localCleanupAfterMerge(context, pr.head_ref, config, location);
379
+ await localCleanupAfterMerge(context, pr.head_ref, config, location);
370
380
  if (input.dry_run) {
371
381
  return;
372
382
  }
@@ -92,7 +92,7 @@ async function stackSection(active, origin, directory, output) {
92
92
  // ブランチは作業ディレクトリのリポにあるので、PR もそこで探す(pr restack と同じ)
93
93
  const { owner, repository } = origin ?? stackedOn.repository;
94
94
  // 載せ直す先は、fetch せずに、下の段の remote の先頭を尋ねて記録と比べる
95
- const read = await readRestackDecision({ client: () => active.client, owner, repository, cwd: directory, remote: primaryRemoteName(directory), reading, developBranch: getDevelopBranch(active.config, owner, repository) ?? '' });
95
+ const read = await readRestackDecision({ client: () => active.client, owner, repository, cwd: directory, remote: primaryRemoteName(directory), reading, developBranch: getDevelopBranch(active.config, owner, repository) ?? '', signal: output.signal });
96
96
  if (read.kind === 'pull-request-unreadable')
97
97
  output.warning(`cannot read the PR of the base branch: ${read.error.message}`);
98
98
  const pullRequest = read.kind === 'pull-request-unreadable' ? 'unknown' : read.lowerPullRequest;
@@ -117,7 +117,7 @@ tracker sync の source dependabot の本体。Tracker の Dependabot PRs waitin
117
117
  export async function runDependabotSync(input, io) {
118
118
  const out = createOutput(input.dry_run, io);
119
119
  const { config, owner, repository } = loadTarget(out, input.repo, input.project);
120
- const client = makeClient(out, config);
120
+ const client = await makeClient(out, config);
121
121
  let pullRequests;
122
122
  let issues;
123
123
  try {
@@ -126,7 +126,7 @@ tracker sync の source security の本体。Tracker の open security alerts
126
126
  export async function runSecuritySync(input, io) {
127
127
  const out = createOutput(input.dry_run, io);
128
128
  const { config, owner, repository } = loadTarget(out, input.repo, input.project);
129
- const client = makeClient(out, config);
129
+ const client = await makeClient(out, config);
130
130
  const sources = { scan: createScanAlertSource(client), dependabot: createDependabotSource(client) };
131
131
  const { alerts, failed, disabled } = await fetchOpenAlerts(out, sources, config.host, owner, repository);
132
132
  let issues;
@@ -84,14 +84,14 @@ const worktreeAddCommand = defineCommand({
84
84
  shortFlags: { directory: '-D' },
85
85
  aliases: { allow_existing_branch: '--force' },
86
86
  interactive: false,
87
- run: (input, io) => Promise.resolve(runAdd(input, io)),
87
+ run: async (input, io) => await runAdd(input, io),
88
88
  });
89
- function runAdd(input, io) {
89
+ async function runAdd(input, io) {
90
90
  requireRepositoryMatch('reject', input.repo, io, process.cwd());
91
91
  const out = createOutput(input.dry_run, io);
92
92
  try {
93
93
  ensureDevcontainerEnvironment();
94
- const result = createWorktree(input.directory, out, {
94
+ const result = await createWorktree(input.directory, out, {
95
95
  baseBranch: input.base,
96
96
  path: input.path,
97
97
  shouldCopy: !input.no_copy,
@@ -100,6 +100,7 @@ function runAdd(input, io) {
100
100
  isDryRun: input.dry_run,
101
101
  isExistingBranchAllowed: input.allow_existing_branch,
102
102
  project: input.project,
103
+ signal: out.signal,
103
104
  });
104
105
  const operation = { verb: 'create', target: `worktree ${result.name} at ${result.path} (branch ${result.branch} from ${result.baseBranch})` };
105
106
  out.planned(operation);
@@ -7,6 +7,11 @@ export declare class BaseError extends Error {
7
7
  export declare class PecotError extends BaseError {
8
8
  }
9
9
  /**
10
+ MCP の要求が取り消され、待っていた子プロセスや要求を止めた。message は取り消しの理由
11
+ */
12
+ export declare class CancelledError extends BaseError {
13
+ }
14
+ /**
10
15
  プロジェクトルートが見つからない
11
16
  */
12
17
  export declare class ProjectRootNotFoundError extends PecotError {
@@ -19,6 +19,11 @@ export class BaseError extends Error {
19
19
  export class PecotError extends BaseError {
20
20
  }
21
21
  /**
22
+ MCP の要求が取り消され、待っていた子プロセスや要求を止めた。message は取り消しの理由
23
+ */
24
+ export class CancelledError extends BaseError {
25
+ }
26
+ /**
22
27
  プロジェクトルートが見つからない
23
28
  */
24
29
  export class ProjectRootNotFoundError extends PecotError {
@@ -45,9 +45,18 @@ base より head が進んでいる commit の数。GitHub の compare で数え
45
45
  */
46
46
  export type CountCommitsAhead = (base: string, head: string) => Promise<number>;
47
47
  /**
48
+ remote のタグの有無。尋ねられなければ failure に git の stderr
49
+ */
50
+ export type RemoteTagLookup = {
51
+ readonly isFound: boolean;
52
+ } | {
53
+ readonly failure: string;
54
+ };
55
+ export type LookUpRemoteTag = (remote: string, tagName: string) => Promise<RemoteTagLookup>;
56
+ /**
48
57
  リリース前チェックを実行する。
49
58
  1. CHANGELOG.md の存在、2. バージョンの検出または検証、3. タグが無いこと(ローカル・リモート)、
50
59
  4. release→develop の差分(countAhead)、5. リリースノートの抽出、の順に確かめる。失敗は ReleaseError
51
60
  */
52
- export declare function runPreflight(options: PreflightOptions, git: GitRunner, countAhead: CountCommitsAhead): Promise<PreflightResult>;
61
+ export declare function runPreflight(options: PreflightOptions, git: GitRunner, lookUpRemoteTag: LookUpRemoteTag, countAhead: CountCommitsAhead): Promise<PreflightResult>;
53
62
  //# sourceMappingURL=release.d.ts.map
@@ -9,11 +9,13 @@ git を実行して標準出力を返す。非 0 終了は ReleaseError
9
9
  */
10
10
  function runGit(git, arguments_) {
11
11
  const result = git(arguments_);
12
- if (result.exitCode !== 0) {
13
- throw new ReleaseError(`git command failed: git ${arguments_.join(' ')}\n${pythonStrip(result.stderr)}`);
14
- }
12
+ if (result.exitCode !== 0)
13
+ throw gitFailed(arguments_, result.stderr);
15
14
  return pythonStrip(result.stdout);
16
15
  }
16
+ function gitFailed(arguments_, stderr) {
17
+ return new ReleaseError(`git command failed: git ${arguments_.join(' ')}\n${pythonStrip(stderr)}`);
18
+ }
17
19
  function determineVersion(options, changelogContent) {
18
20
  if (options.version === undefined) {
19
21
  try {
@@ -33,7 +35,7 @@ function determineVersion(options, changelogContent) {
33
35
  1. CHANGELOG.md の存在、2. バージョンの検出または検証、3. タグが無いこと(ローカル・リモート)、
34
36
  4. release→develop の差分(countAhead)、5. リリースノートの抽出、の順に確かめる。失敗は ReleaseError
35
37
  */
36
- export async function runPreflight(options, git, countAhead) {
38
+ export async function runPreflight(options, git, lookUpRemoteTag, countAhead) {
37
39
  const { changelogContent, developBranch, releaseBranch } = options;
38
40
  if (changelogContent === undefined)
39
41
  throw new ReleaseError(changelogNotFoundMessage(options.changelogPath));
@@ -43,8 +45,10 @@ export async function runPreflight(options, git, countAhead) {
43
45
  const localTags = runGit(git, ['tag', '-l', tagName]);
44
46
  if (localTags.split('\n').includes(tagName))
45
47
  throw new ReleaseError(`tag already exists locally: ${tagName}`);
46
- const remoteTags = runGit(git, ['ls-remote', '--tags', remote, `refs/tags/${tagName}`]);
47
- if (remoteTags !== '')
48
+ const remoteTag = await lookUpRemoteTag(remote, tagName);
49
+ if ('failure' in remoteTag)
50
+ throw gitFailed(['ls-remote', '--tags', remote, `refs/tags/${tagName}`], remoteTag.failure);
51
+ if (remoteTag.isFound)
48
52
  throw new ReleaseError(`tag already exists on the remote: ${tagName}`);
49
53
  const diffCount = await countAhead(releaseBranch, developBranch);
50
54
  if (diffCount === 0) {
@@ -2,6 +2,7 @@ import type { GitResult, GitRunner } from '../domain/git-runner.js';
2
2
  import type { RemoteLocation } from '../domain/git-url.js';
3
3
  import { BaseError } from '../domain/errors.js';
4
4
  import type { IssueReference } from '../domain/reference-parser.js';
5
+ import type { RemoteTagLookup } from '../domain/release.js';
5
6
  export interface GitOptions {
6
7
  /**
7
8
  作業ディレクトリ。省略すると呼び出し元の作業ディレクトリ
@@ -38,23 +39,21 @@ export declare class GitCommandError extends BaseError {
38
39
  readonly stderr: string;
39
40
  constructor(arguments_: readonly string[], result: GitResult);
40
41
  }
41
- export declare const MAX_OUTPUT_BYTES: number;
42
- /**
43
- 取り消しで止めたときの exitCode
44
- */
45
- export declare const GIT_CANCELLED = -3;
46
- /**
47
- runGit の非同期版。待つ間もイベントループを止めない。
48
- 時間切れか signal の中断で、git を pre-push のフックごと止め、exitCode が GIT_TIMED_OUT か GIT_CANCELLED の結果を返す
49
- */
50
- export declare function runGitAsync(arguments_: readonly string[], options?: Readonly<Omit<GitOptions, 'stripGitEnvironment' | 'check'>> & {
51
- readonly signal?: Readonly<AbortSignal> | undefined;
52
- }): Promise<GitResult>;
53
42
  /**
54
43
  git を実行する。標準出力・標準エラーは改行を \n に揃えた文字列で返す。
55
44
  git や作業ディレクトリが見つからなければ OsError(code ENOENT)を投げる
56
45
  */
57
46
  export declare function runGit(arguments_: readonly string[], options?: Readonly<GitOptions>): GitResult;
47
+ export interface AsyncGitOptions extends GitOptions {
48
+ /**
49
+ MCP の要求の取り消し。取り消されたら git をプロセスグループごと止めて CancelledError を投げる
50
+ */
51
+ readonly signal?: Readonly<AbortSignal> | undefined;
52
+ }
53
+ /**
54
+ runGit の非同期版。リモートを待つ git に使い、待つ間もイベントループを止めない
55
+ */
56
+ export declare function runGitAsync(arguments_: readonly string[], options?: Readonly<AsyncGitOptions>): Promise<GitResult>;
58
57
  /**
59
58
  cwd を束ねた GitRunner。domain の関数に渡す。非 0 終了は例外にせず結果で返す
60
59
  */
@@ -100,6 +99,7 @@ export declare function activeIssueOf(directory?: string): IssueReference | unde
100
99
  */
101
100
  export declare function remoteRepository(cwd: string | undefined, remote: string): RemoteLocation | undefined;
102
101
  export declare const NON_INTERACTIVE_GIT: Readonly<Record<string, string>>;
102
+ export declare const REMOTE_TIMEOUT_MILLISECONDS = 60000;
103
103
  /**
104
104
  push の時間切れ。pre-push のフックの時間を含める
105
105
  */
@@ -112,14 +112,14 @@ export type PushResult = {
112
112
  readonly pushed: true;
113
113
  } | {
114
114
  readonly pushed: false;
115
- readonly reason: 'rejected' | 'timed-out' | 'cancelled';
115
+ readonly reason: 'rejected' | 'timed-out';
116
116
  readonly stderr: string;
117
117
  };
118
118
  export type RebaseOutcome = 'done' | 'conflict';
119
119
  /**
120
120
  `git fetch <remote>`。失敗・時間切れは succeeded が false
121
121
  */
122
- export declare function fetchRemote(cwd: string, remote: string): FetchResult;
122
+ export declare function fetchRemote(cwd: string, remote: string, signal?: Readonly<AbortSignal>): Promise<FetchResult>;
123
123
  /**
124
124
  ref の指すコミットの SHA。無ければ undefined
125
125
  */
@@ -182,7 +182,7 @@ export interface PushOptions {
182
182
  readonly timeoutMilliseconds?: number | undefined;
183
183
  }
184
184
  /**
185
- remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか、時間切れか、取り消されたら、その理由と stderr を返す
185
+ remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか時間切れなら、その理由と stderr を返す。取り消されたら CancelledError を投げる
186
186
  */
187
187
  export declare function pushWithLease(cwd: string, remote: string, branch: string, expectedSha: string, options?: Readonly<PushOptions>): Promise<PushResult>;
188
188
  export type RemoteHead = {
@@ -194,5 +194,9 @@ export type RemoteHead = {
194
194
  /**
195
195
  remote の branch の先頭の SHA を、追跡参照を更新せずに尋ねる。無ければ sha が undefined。届かないか時間切れなら isReachable が false
196
196
  */
197
- export declare function remoteBranchHead(cwd: string, remote: string, branch: string): RemoteHead;
197
+ export declare function remoteBranchHead(cwd: string, remote: string, branch: string, signal?: Readonly<AbortSignal>): Promise<RemoteHead>;
198
+ /**
199
+ remote にタグがあるか。届かないか時間切れなら failure に git の stderr を入れる
200
+ */
201
+ export declare function remoteTagExists(cwd: string, remote: string, tagName: string, signal?: Readonly<AbortSignal>): Promise<RemoteTagLookup>;
198
202
  //# sourceMappingURL=git.d.ts.map
@@ -1,6 +1,6 @@
1
1
  // git コマンド実行の唯一の窓口。git の subprocess 呼び出しはすべて runGit か runGitAsync を経由する。
2
2
  // 値を返す helper(gitToplevel 等)は、失敗時に undefined を返す。
3
- import { spawn, spawnSync } from 'node:child_process';
3
+ import { spawnSync } from 'node:child_process';
4
4
  import { existsSync } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { activeIssueFromBranch } from '../domain/branch-name.js';
@@ -9,6 +9,7 @@ import { BaseError, InvalidValueError } from '../domain/errors.js';
9
9
  import { normalizeNewlines, pythonRepr, pythonStrip } from '../domain/python-format.js';
10
10
  import { childStdin } from './child-stdin.js';
11
11
  import { isFileNotFound, toOsError } from './os-error.js';
12
+ import { MAX_OUTPUT_BYTES, runProcess } from './process-run.js';
12
13
  /**
13
14
  時間切れで止めたときの exitCode
14
15
  */
@@ -30,96 +31,11 @@ export class GitCommandError extends BaseError {
30
31
  this.stderr = result.stderr;
31
32
  }
32
33
  }
33
- // 出力が大きい git(log・diff 等)でも切れないようにする
34
- export const MAX_OUTPUT_BYTES = 1024 * 1024 * 1024;
35
34
  function withoutGitVariables() {
36
35
  // interface-env: none
37
36
  return Object.fromEntries(Object.entries(process.env).filter((entry) => entry[1] !== undefined && !entry[0].startsWith('GIT_')));
38
37
  }
39
38
  /**
40
- 取り消しで止めたときの exitCode
41
- */
42
- export const GIT_CANCELLED = -3;
43
- // detached の git は端末の Ctrl-C を受けないので、受けたらグループごと止めてから既定の動きに戻す
44
- const FORWARDED_SIGNALS = ['SIGINT', 'SIGTERM'];
45
- function killGroup(pid) {
46
- if (pid === undefined)
47
- return;
48
- try {
49
- // detached の git はプロセスグループの頭なので、負の pid でフックの孫までまとめて止める
50
- process.kill(-pid, 'SIGKILL');
51
- }
52
- catch {
53
- // 既に終わっている
54
- }
55
- }
56
- /**
57
- runGit の非同期版。待つ間もイベントループを止めない。
58
- 時間切れか signal の中断で、git を pre-push のフックごと止め、exitCode が GIT_TIMED_OUT か GIT_CANCELLED の結果を返す
59
- */
60
- export async function runGitAsync(arguments_, options = {}) {
61
- const timeout = options.timeoutMilliseconds === undefined ? undefined : AbortSignal.timeout(options.timeoutMilliseconds);
62
- const stops = [options.signal, timeout].filter(signal => signal !== undefined);
63
- const stop = stops.length === 0 ? undefined : AbortSignal.any(stops);
64
- const child = spawn('git', [...arguments_], {
65
- cwd: options.cwd,
66
- // interface-env: none
67
- env: options.env === undefined ? undefined : { ...process.env, ...options.env },
68
- stdio: [childStdin(), 'pipe', 'pipe'],
69
- detached: true,
70
- });
71
- const stdout = [];
72
- const stderr = [];
73
- child.stdout.setEncoding('utf8').on('data', (chunk) => {
74
- stdout.push(chunk);
75
- });
76
- child.stderr.setEncoding('utf8').on('data', (chunk) => {
77
- stderr.push(chunk);
78
- });
79
- const closed = new Promise((resolve) => {
80
- child.on('close', () => {
81
- resolve();
82
- });
83
- });
84
- const kill = () => {
85
- killGroup(child.pid);
86
- };
87
- const forward = (signal) => {
88
- killGroup(child.pid);
89
- for (const name of FORWARDED_SIGNALS)
90
- process.removeListener(name, forward);
91
- process.kill(process.pid, signal);
92
- };
93
- stop?.addEventListener('abort', kill, { once: true });
94
- for (const name of FORWARDED_SIGNALS)
95
- process.on(name, forward);
96
- const ended = await new Promise((resolve) => {
97
- child.on('error', (error) => {
98
- resolve({ kind: 'error', error });
99
- });
100
- // 'close' は stdio を持つ孫(フック)が終わるまで出ないので、git の終わりは 'exit' で受ける
101
- child.on('exit', (code) => {
102
- resolve({ kind: 'exit', code: code ?? undefined });
103
- });
104
- });
105
- stop?.removeEventListener('abort', kill);
106
- for (const name of FORWARDED_SIGNALS)
107
- process.removeListener(name, forward);
108
- if (ended.kind === 'error')
109
- throw toOsError(ended.error);
110
- // 止めずに終わったなら、出力を読み切る。止めたなら、残ったパイプを捨てる
111
- if (ended.code === 0 || stop?.aborted !== true)
112
- await closed;
113
- else {
114
- child.stdout.destroy();
115
- child.stderr.destroy();
116
- }
117
- const output = { stdout: normalizeNewlines(stdout.join('')), stderr: normalizeNewlines(stderr.join('')) };
118
- if (ended.code === 0 || stop?.aborted !== true)
119
- return { exitCode: ended.code ?? -1, ...output };
120
- return { exitCode: options.signal?.aborted === true ? GIT_CANCELLED : GIT_TIMED_OUT, ...output };
121
- }
122
- /**
123
39
  git を実行する。標準出力・標準エラーは改行を \n に揃えた文字列で返す。
124
40
  git や作業ディレクトリが見つからなければ OsError(code ENOENT)を投げる
125
41
  */
@@ -146,6 +62,25 @@ export function runGit(arguments_, options = {}) {
146
62
  return gitResult;
147
63
  }
148
64
  /**
65
+ runGit の非同期版。リモートを待つ git に使い、待つ間もイベントループを止めない
66
+ */
67
+ export async function runGitAsync(arguments_, options = {}) {
68
+ // interface-env: none
69
+ const base = options.stripGitEnvironment === true ? withoutGitVariables() : (options.env === undefined ? undefined : process.env);
70
+ const result = await runProcess('git', arguments_, {
71
+ cwd: options.cwd,
72
+ env: base === undefined ? undefined : { ...base, ...options.env },
73
+ timeoutMilliseconds: options.timeoutMilliseconds,
74
+ signal: options.signal,
75
+ });
76
+ if (result.isTimedOut)
77
+ return { exitCode: GIT_TIMED_OUT, stdout: result.stdout, stderr: result.stderr };
78
+ const gitResult = { exitCode: result.exitCode ?? -1, stdout: result.stdout, stderr: result.stderr };
79
+ if (options.check === true && gitResult.exitCode !== 0)
80
+ throw new GitCommandError(arguments_, gitResult);
81
+ return gitResult;
82
+ }
83
+ /**
149
84
  cwd を束ねた GitRunner。domain の関数に渡す。非 0 終了は例外にせず結果で返す
150
85
  */
151
86
  export function gitRunnerFor(cwd, options = {}) {
@@ -236,8 +171,8 @@ export function remoteRepository(cwd, remote) {
236
171
  }
237
172
  // 端末で尋ねさせない。ssh は GIT_SSH_COMMAND で BatchMode にすると利用者の GIT_SSH と core.sshCommand を上書きするので、askpass を失敗させる
238
173
  export const NON_INTERACTIVE_GIT = { GIT_TERMINAL_PROMPT: '0', SSH_ASKPASS: 'false', SSH_ASKPASS_REQUIRE: 'force' };
239
- // fetch は、この時間で諦める
240
- const REMOTE_TIMEOUT_MILLISECONDS = 60_000;
174
+ // fetch は、認証の入力を待たずに、この時間で諦める
175
+ export const REMOTE_TIMEOUT_MILLISECONDS = 60_000;
241
176
  /**
242
177
  push の時間切れ。pre-push のフックの時間を含める
243
178
  */
@@ -246,8 +181,8 @@ const PEEL_TO_COMMIT = '^{commit}';
246
181
  /**
247
182
  `git fetch <remote>`。失敗・時間切れは succeeded が false
248
183
  */
249
- export function fetchRemote(cwd, remote) {
250
- const result = runGit(['fetch', remote], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: REMOTE_TIMEOUT_MILLISECONDS });
184
+ export async function fetchRemote(cwd, remote, signal) {
185
+ const result = await runGitAsync(['fetch', remote], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: REMOTE_TIMEOUT_MILLISECONDS, signal });
251
186
  return { succeeded: result.exitCode === 0, stderr: result.stderr };
252
187
  }
253
188
  /**
@@ -351,12 +286,10 @@ export function resetHardTo(cwd, reference) {
351
286
  runGit(['reset', '--quiet', '--hard', reference], { cwd, check: true });
352
287
  }
353
288
  function pushFailure(exitCode) {
354
- if (exitCode === GIT_TIMED_OUT)
355
- return 'timed-out';
356
- return exitCode === GIT_CANCELLED ? 'cancelled' : 'rejected';
289
+ return exitCode === GIT_TIMED_OUT ? 'timed-out' : 'rejected';
357
290
  }
358
291
  /**
359
- remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか、時間切れか、取り消されたら、その理由と stderr を返す
292
+ remote の branch が expectedSha のときだけ、手元の branch で置き換える。拒まれたか時間切れなら、その理由と stderr を返す。取り消されたら CancelledError を投げる
360
293
  */
361
294
  export async function pushWithLease(cwd, remote, branch, expectedSha, options = {}) {
362
295
  const result = await runGitAsync(['push', `--force-with-lease=${branch}:${expectedSha}`, remote, branch], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: options.timeoutMilliseconds ?? PUSH_TIMEOUT_MILLISECONDS, signal: options.signal });
@@ -368,11 +301,22 @@ const LS_REMOTE_TIMEOUT_MILLISECONDS = 10_000;
368
301
  /**
369
302
  remote の branch の先頭の SHA を、追跡参照を更新せずに尋ねる。無ければ sha が undefined。届かないか時間切れなら isReachable が false
370
303
  */
371
- export function remoteBranchHead(cwd, remote, branch) {
372
- const listed = runGit(['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: LS_REMOTE_TIMEOUT_MILLISECONDS });
304
+ export async function remoteBranchHead(cwd, remote, branch, signal) {
305
+ const listed = await runGitAsync(['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: LS_REMOTE_TIMEOUT_MILLISECONDS, signal });
373
306
  if (listed.exitCode === LS_REMOTE_NOT_FOUND)
374
307
  return { isReachable: true, sha: undefined };
375
308
  const [sha] = listed.exitCode === 0 ? listed.stdout.split(/\s/u, 1) : [];
376
309
  return sha === undefined || sha === '' ? { isReachable: false } : { isReachable: true, sha };
377
310
  }
311
+ /**
312
+ remote にタグがあるか。届かないか時間切れなら failure に git の stderr を入れる
313
+ */
314
+ export async function remoteTagExists(cwd, remote, tagName, signal) {
315
+ const listed = await runGitAsync(['ls-remote', '--tags', remote, `refs/tags/${tagName}`], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: LS_REMOTE_TIMEOUT_MILLISECONDS, signal });
316
+ if (listed.exitCode === GIT_TIMED_OUT)
317
+ return { failure: `${listed.stderr}timed out after ${String(LS_REMOTE_TIMEOUT_MILLISECONDS / 1000)} seconds` };
318
+ if (listed.exitCode !== 0)
319
+ return { failure: listed.stderr };
320
+ return { isFound: pythonStrip(listed.stdout) !== '' };
321
+ }
378
322
  //# sourceMappingURL=git.js.map
@@ -89,6 +89,10 @@ export interface GitHubClientOptions {
89
89
  */
90
90
  readonly token?: string | undefined;
91
91
  /**
92
+ MCP の要求の取り消し。gh auth token と HTTP の要求を止める
93
+ */
94
+ readonly signal?: Readonly<AbortSignal> | undefined;
95
+ /**
92
96
  1 回の要求の時間切れ(ミリ秒)。既定は 30000
93
97
  */
94
98
  readonly timeoutMilliseconds?: number | undefined;
@@ -111,6 +115,8 @@ restJson・restObject・restRequest・handleHttpError・executeGraphql。
111
115
  export declare class GitHubClientBase {
112
116
  private readonly diagnostics;
113
117
  private usedFallback;
118
+ private readonly signal;
119
+ private ghToken;
114
120
  readonly host: string;
115
121
  token: string;
116
122
  readonly timeoutMilliseconds: number;
@@ -122,8 +128,8 @@ export declare class GitHubClientBase {
122
128
  */
123
129
  readonly linkedRepositoriesCache: Map<string, readonly LinkedRepository[]>;
124
130
  constructor(options: Readonly<GitHubClientOptions>);
125
- private resolveToken;
126
131
  private failAuthentication;
132
+ private loadGhToken;
127
133
  private tokenFromEnvironment;
128
134
  private tokenFromGh;
129
135
  /**
@@ -137,12 +143,17 @@ export declare class GitHubClientBase {
137
143
  */
138
144
  private retryWithFallbackToken;
139
145
  private send;
146
+ private throwIfCancelled;
140
147
  private sendRest;
141
148
  private sendGraphql;
142
149
  private classifyGraphqlFailure;
143
150
  private runGraphql;
144
151
  private assertSameOrigin;
145
152
  /**
153
+ トークンが無ければ gh auth token を 1 回だけ読む。読めなければ GitHubAuthError、取り消されたら CancelledError
154
+ */
155
+ ensureToken(): Promise<void>;
156
+ /**
146
157
  REST の要求(401 のときは gh auth token に切り替えて 1 回だけ再試行する)。
147
158
  target は `/user` のようなパス(base の後ろにつなぐ)か、`https://` で始まる絶対 URL(Link ヘッダの next など)。
148
159
  失敗の状態コードは例外にせず、そのまま返す。呼び出し側が isSuccess を見て handleHttpError に渡す