@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
@@ -0,0 +1,169 @@
1
+ // review finish の結果の決め方と、止まったことを知らせるコメントの本文。決まりは spec 027 の contracts/cli-commands.md。
2
+ // GitHub を読む・書くのは commands/review-finish.ts が受け持つ。
3
+ import { isJsonObject, jsonField, tryParseJsonText } from './json.js';
4
+ import { isJsonArray } from './python-format.js';
5
+ function stringField(object, key) {
6
+ const value = jsonField(object, key);
7
+ return typeof value === 'string' ? value : undefined;
8
+ }
9
+ function readResultLine(line) {
10
+ const errors = jsonField(line, 'errors');
11
+ return {
12
+ subtype: stringField(line, 'subtype'),
13
+ isError: jsonField(line, 'is_error') === true,
14
+ terminalReason: stringField(line, 'terminal_reason'),
15
+ text: stringField(line, 'result') ?? '',
16
+ errors: isJsonArray(errors) ? errors.filter(entry => typeof entry === 'string') : [],
17
+ };
18
+ }
19
+ /**
20
+ execution_file の本文を読む。JSON の配列でなければ unreadable、result の行が無ければ last は undefined
21
+ */
22
+ export function readExecution(text) {
23
+ const parsed = tryParseJsonText(text);
24
+ if (!isJsonArray(parsed))
25
+ return { kind: 'unreadable' };
26
+ const last = parsed.findLast(line => isJsonObject(line) && jsonField(line, 'type') === 'result');
27
+ return { kind: 'read', last: last === undefined ? undefined : readResultLine(last) };
28
+ }
29
+ const AUTHENTICATION_ERROR = 'authentication_error';
30
+ function isAuthenticationFailure(last) {
31
+ return last.text.includes(AUTHENTICATION_ERROR) || last.errors.some(entry => entry.includes(AUTHENTICATION_ERROR));
32
+ }
33
+ function write(result, next, shouldCheckActor = false) {
34
+ return { action: 'write', result, next, shouldCheckActor };
35
+ }
36
+ function decideFailure(input) {
37
+ const last = input.execution.kind === 'read' ? input.execution.last : undefined;
38
+ if (last?.isError === true && last.terminalReason === 'api_error')
39
+ return write('failed', isAuthenticationFailure(last) ? 'auth' : 'retry');
40
+ if (last?.subtype === 'error_max_turns')
41
+ return write('limit', 'limit');
42
+ // action は、Claude の App のトークンを受け取れずに止めたときも、空の github_token を出力する
43
+ if (input.reviewOutcome === 'failure' && !input.hasToken)
44
+ return write('setup-missing', 'app-token');
45
+ // Claude Code が動かずに step が落ちた run には、action が書いた人の権限で止めた場合が入る
46
+ return write('failed', 'retry', input.reviewOutcome === 'failure' && input.reviewConclusion === '');
47
+ }
48
+ /**
49
+ 結果を決める。順は spec 027 の contracts/cli-commands.md の表のとおりで、最初に当たった行で決める
50
+ */
51
+ export function decideReviewFinish(input) {
52
+ if (input.kind === 'result') {
53
+ switch (input.result) {
54
+ case 'reviewed': {
55
+ return { action: 'skip', reason: 'reviewed' };
56
+ }
57
+ case 'failed': {
58
+ return write('failed', 'retry');
59
+ }
60
+ case 'limit': {
61
+ return write('limit', 'limit');
62
+ }
63
+ case 'setup-missing': {
64
+ return write('setup-missing', 'setup-detail');
65
+ }
66
+ }
67
+ }
68
+ // PR のブランチで雛形を変えた run は、Claude の App がトークンを出さず、action がレビューを飛ばして step を成功で終える
69
+ if (input.reviewOutcome === 'success' && input.reviewConclusion === '')
70
+ return { action: 'skip', reason: 'workflow-mismatch' };
71
+ switch (input.jobStatus) {
72
+ case 'success': {
73
+ return { action: 'skip', reason: 'job-succeeded' };
74
+ }
75
+ // 時間の上限と、人が run を取り消したときは同じ cancelled で、見分けない(research の R9)
76
+ case 'cancelled': {
77
+ return write('limit', 'limit');
78
+ }
79
+ case 'failure': {
80
+ return decideFailure(input);
81
+ }
82
+ }
83
+ }
84
+ // w-revise の指摘のインラインコメントの先頭。`**F-NN**` か、2 巡目以降の `**R<巡>/F-NN**`
85
+ const FINDING_HEAD = /^\*\*(?:R\d+\/F|F)-\d+\*\*/u;
86
+ /**
87
+ 止まった場所。since より後に作られた指摘のインラインコメントがあれば after-inline。since が無ければ unknown
88
+ */
89
+ export function stopLocationOf(comments, since) {
90
+ if (since === undefined)
91
+ return 'unknown';
92
+ const sinceTime = since.getTime();
93
+ const hasPosted = comments.some(comment => FINDING_HEAD.test(comment.body) && Date.parse(comment.createdAt) >= sinceTime);
94
+ return hasPosted ? 'after-inline' : 'before-findings';
95
+ }
96
+ /**
97
+ 同じ実行で 2 度書かないための、画面に出ない目印の行。re-run では run の ID が変わらないので、試行の番号も入れる
98
+ */
99
+ export function stoppedMarker(run) {
100
+ return `<!-- pecot-review-stopped run=${run.runId} attempt=${run.attempt} -->`;
101
+ }
102
+ /**
103
+ 同じ実行の目印を持つコメントがあるか。人が目印を書き込んで記録を消せないよう、Bot のコメントだけを見る
104
+ */
105
+ export function hasStoppedMarker(comments, run) {
106
+ const marker = stoppedMarker(run);
107
+ return comments.some(comment => comment.userType === 'Bot' && comment.body.includes(marker));
108
+ }
109
+ // テンプレートのプレースホルダ。cli/templates/comment/review-stopped.md の本文と同じ文字列
110
+ export const REVIEW_STOPPED_PLACEHOLDERS = {
111
+ summary: '<止まった理由を1行で>',
112
+ result: '<結果>',
113
+ location: '<止まった場所>',
114
+ next: '<次にすること>',
115
+ };
116
+ const SUMMARIES = {
117
+ 'failed': '自動レビューが途中で失敗して止まった',
118
+ 'limit': '自動レビューがターンか時間の上限で止まった',
119
+ 'setup-missing': '自動レビューに要る設定が足りずに止まった',
120
+ };
121
+ const RESULT_LINES = {
122
+ 'failed': '`failed`(途中で失敗した)',
123
+ 'limit': '`limit`(ターンか時間の上限で止まった)',
124
+ 'setup-missing': '`setup-missing`(要る権限か設定が足りない)',
125
+ };
126
+ const LOCATION_LINES = {
127
+ 'before-findings': '指摘を投稿する前',
128
+ 'after-inline': 'インラインコメントを投稿した後(指摘の一覧はまだ無い)',
129
+ 'unknown': '分からない',
130
+ };
131
+ // 利用者の値をコードの書き方の中に入れる。改行とバッククォートで書き方が崩れないよう、空白と引用符に替える
132
+ function code(text) {
133
+ return `\`${text.replaceAll(/\s+/gu, ' ').replaceAll('`', '\'')}\``;
134
+ }
135
+ function nextLine(next, triggerPhrase, detail) {
136
+ const retry = `PR に ${code(triggerPhrase)} とコメントして起動し直すか、端末で ${code('/pecot-w:w-revise')} を回す`;
137
+ switch (next) {
138
+ case 'retry': {
139
+ return `実行の記録で原因を確かめてから、${retry}`;
140
+ }
141
+ case 'auth': {
142
+ return `モデルの認証に失敗した。${code('claude setup-token')} でトークンを作り直し、secret ${code('CLAUDE_CODE_OAUTH_TOKEN')} に登録し直す。その後、${retry}`;
143
+ }
144
+ case 'app-token': {
145
+ return `リポに Claude の GitHub App を入れてから、${retry}`;
146
+ }
147
+ case 'limit': {
148
+ return `大きな PR は、端末で ${code('/pecot-w:w-revise')} を回す。自動で回すなら、変数 ${code('PECOT_REVIEW_MAX_TURNS')}・${code('PECOT_REVIEW_TIMEOUT_MINUTES')} で上限を上げる。その後、PR に ${code(triggerPhrase)} とコメントして起動し直す`;
149
+ }
150
+ case 'setup-detail': {
151
+ const missing = detail === undefined || detail.trim() === '' ? '' : `足りない設定は ${code(detail.trim())} だ。`;
152
+ return `${missing}設定を整えてから、${retry}`;
153
+ }
154
+ }
155
+ }
156
+ /**
157
+ テンプレートの本文(フロントマターと冒頭のコメントを外したもの)のプレースホルダを埋める。
158
+ run があれば、末尾に目印の行を足す
159
+ */
160
+ export function renderReviewStopped(templateBody, values) {
161
+ const filled = templateBody
162
+ .replace(REVIEW_STOPPED_PLACEHOLDERS.summary, () => SUMMARIES[values.result])
163
+ .replace(REVIEW_STOPPED_PLACEHOLDERS.result, () => RESULT_LINES[values.result])
164
+ .replace(REVIEW_STOPPED_PLACEHOLDERS.location, () => LOCATION_LINES[values.location])
165
+ .replace(REVIEW_STOPPED_PLACEHOLDERS.next, () => nextLine(values.next, values.triggerPhrase, values.detail))
166
+ .trim();
167
+ return values.run === undefined ? `${filled}\n` : `${filled}\n\n${stoppedMarker(values.run)}\n`;
168
+ }
169
+ //# sourceMappingURL=review-finish.js.map
@@ -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 に渡す