@pecot/workflow-mcp 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +27 -22
  3. package/cli/dist/cli.js +6 -1
  4. package/cli/dist/commands/board-add.d.ts +3 -0
  5. package/cli/dist/commands/board-add.js +69 -0
  6. package/cli/dist/commands/board-judgment.d.ts +69 -0
  7. package/cli/dist/commands/board-judgment.js +150 -0
  8. package/cli/dist/commands/board-move.d.ts +3 -0
  9. package/cli/dist/commands/board-move.js +65 -0
  10. package/cli/dist/commands/board-readiness.d.ts +34 -0
  11. package/cli/dist/commands/board-readiness.js +108 -0
  12. package/cli/dist/commands/board-show.d.ts +3 -0
  13. package/cli/dist/commands/board-show.js +75 -0
  14. package/cli/dist/commands/board-sync.d.ts +3 -0
  15. package/cli/dist/commands/board-sync.js +120 -0
  16. package/cli/dist/commands/board-view.d.ts +151 -0
  17. package/cli/dist/commands/board-view.js +293 -0
  18. package/cli/dist/commands/board.d.ts +3 -0
  19. package/cli/dist/commands/board.js +12 -0
  20. package/cli/dist/commands/branch.d.ts +3 -0
  21. package/cli/dist/commands/branch.js +111 -0
  22. package/cli/dist/commands/command-binding.js +4 -0
  23. package/cli/dist/commands/command-definition.d.ts +39 -8
  24. package/cli/dist/commands/command-definition.js +20 -7
  25. package/cli/dist/commands/command-help.js +2 -2
  26. package/cli/dist/commands/command-hint.d.ts +5 -0
  27. package/cli/dist/commands/command-hint.js +13 -0
  28. package/cli/dist/commands/command-stop.d.ts +5 -3
  29. package/cli/dist/commands/command-stop.js +7 -6
  30. package/cli/dist/commands/failure-kind.d.ts +3 -0
  31. package/cli/dist/commands/failure-kind.js +35 -0
  32. package/cli/dist/commands/failure.d.ts +6 -0
  33. package/cli/dist/commands/failure.js +29 -3
  34. package/cli/dist/commands/github-client.d.ts +6 -2
  35. package/cli/dist/commands/github-client.js +13 -3
  36. package/cli/dist/commands/help.js +8 -13
  37. package/cli/dist/commands/issue-board.d.ts +61 -0
  38. package/cli/dist/commands/issue-board.js +85 -1
  39. package/cli/dist/commands/issue-comment.js +66 -30
  40. package/cli/dist/commands/issue-create.js +632 -92
  41. package/cli/dist/commands/issue-dependency.d.ts +3 -0
  42. package/cli/dist/commands/issue-dependency.js +310 -0
  43. package/cli/dist/commands/issue-readiness.d.ts +122 -0
  44. package/cli/dist/commands/issue-readiness.js +253 -0
  45. package/cli/dist/commands/issue-reopen.d.ts +3 -0
  46. package/cli/dist/commands/issue-reopen.js +130 -0
  47. package/cli/dist/commands/issue-shared.d.ts +33 -20
  48. package/cli/dist/commands/issue-shared.js +84 -76
  49. package/cli/dist/commands/issue-show.d.ts +3 -0
  50. package/cli/dist/commands/issue-show.js +239 -0
  51. package/cli/dist/commands/issue.d.ts +0 -1
  52. package/cli/dist/commands/issue.js +6 -8
  53. package/cli/dist/commands/names.d.ts +33 -0
  54. package/cli/dist/commands/names.js +63 -0
  55. package/cli/dist/commands/output.d.ts +32 -4
  56. package/cli/dist/commands/output.js +28 -8
  57. package/cli/dist/commands/pr-merge.d.ts +3 -0
  58. package/cli/dist/commands/pr-merge.js +230 -0
  59. package/cli/dist/commands/pr-reference.d.ts +8 -0
  60. package/cli/dist/commands/pr-reference.js +30 -0
  61. package/cli/dist/commands/pr-restack.d.ts +6 -0
  62. package/cli/dist/commands/pr-restack.js +233 -0
  63. package/cli/dist/commands/pr-waiting.d.ts +59 -0
  64. package/cli/dist/commands/pr-waiting.js +143 -0
  65. package/cli/dist/commands/pr.d.ts +23 -0
  66. package/cli/dist/commands/pr.js +378 -366
  67. package/cli/dist/commands/project-sync.d.ts +12 -3
  68. package/cli/dist/commands/project-sync.js +23 -13
  69. package/cli/dist/commands/project.d.ts +3 -2
  70. package/cli/dist/commands/project.js +371 -177
  71. package/cli/dist/commands/registry.js +15 -10
  72. package/cli/dist/commands/release.d.ts +2 -2
  73. package/cli/dist/commands/release.js +118 -130
  74. package/cli/dist/commands/renamed-commands.d.ts +26 -0
  75. package/cli/dist/commands/renamed-commands.js +53 -0
  76. package/cli/dist/commands/repository-match.js +9 -3
  77. package/cli/dist/commands/session-finish.d.ts +3 -0
  78. package/cli/dist/commands/session-finish.js +383 -0
  79. package/cli/dist/commands/session-start.d.ts +3 -0
  80. package/cli/dist/commands/session-start.js +252 -0
  81. package/cli/dist/commands/session.d.ts +3 -0
  82. package/cli/dist/commands/session.js +186 -32
  83. package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
  84. package/cli/dist/commands/{dependabot.js → tracker-sync-dependabot.js} +76 -68
  85. package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
  86. package/cli/dist/commands/{security.js → tracker-sync-security.js} +71 -64
  87. package/cli/dist/commands/tracker-sync.d.ts +37 -0
  88. package/cli/dist/commands/tracker-sync.js +18 -6
  89. package/cli/dist/commands/tracker.d.ts +3 -0
  90. package/cli/dist/commands/tracker.js +20 -0
  91. package/cli/dist/commands/usage-error.d.ts +4 -0
  92. package/cli/dist/commands/usage-error.js +6 -0
  93. package/cli/dist/commands/work-target.d.ts +20 -3
  94. package/cli/dist/commands/work-target.js +49 -6
  95. package/cli/dist/commands/worktree.js +103 -33
  96. package/cli/dist/domain/batch-plan.d.ts +73 -0
  97. package/cli/dist/domain/batch-plan.js +114 -0
  98. package/cli/dist/domain/blocked-by-change.d.ts +99 -0
  99. package/cli/dist/domain/blocked-by-change.js +101 -0
  100. package/cli/dist/domain/board-move.d.ts +90 -0
  101. package/cli/dist/domain/board-move.js +92 -0
  102. package/cli/dist/domain/branch-name.js +1 -1
  103. package/cli/dist/domain/command-hint.d.ts +85 -0
  104. package/cli/dist/domain/command-hint.js +148 -0
  105. package/cli/dist/domain/config.d.ts +4 -0
  106. package/cli/dist/domain/config.js +11 -1
  107. package/cli/dist/domain/dependabot.js +1 -1
  108. package/cli/dist/domain/errors.d.ts +5 -0
  109. package/cli/dist/domain/errors.js +5 -0
  110. package/cli/dist/domain/format.d.ts +51 -4
  111. package/cli/dist/domain/format.js +72 -6
  112. package/cli/dist/domain/frontmatter.d.ts +18 -3
  113. package/cli/dist/domain/frontmatter.js +38 -12
  114. package/cli/dist/domain/issue-order.d.ts +55 -0
  115. package/cli/dist/domain/issue-order.js +65 -0
  116. package/cli/dist/domain/issue-readout.d.ts +36 -4
  117. package/cli/dist/domain/pull-request.d.ts +71 -4
  118. package/cli/dist/domain/pull-request.js +59 -10
  119. package/cli/dist/domain/readiness.d.ts +44 -0
  120. package/cli/dist/domain/readiness.js +153 -5
  121. package/cli/dist/domain/reference-parser.d.ts +3 -1
  122. package/cli/dist/domain/reference-parser.js +6 -2
  123. package/cli/dist/domain/release.d.ts +7 -3
  124. package/cli/dist/domain/release.js +5 -12
  125. package/cli/dist/domain/repository-policy.d.ts +9 -3
  126. package/cli/dist/domain/repository-policy.js +8 -7
  127. package/cli/dist/domain/repository-resolver.js +4 -1
  128. package/cli/dist/domain/restack.d.ts +62 -0
  129. package/cli/dist/domain/restack.js +53 -0
  130. package/cli/dist/domain/security-alerts.js +1 -1
  131. package/cli/dist/domain/state.d.ts +69 -0
  132. package/cli/dist/domain/state.js +67 -1
  133. package/cli/dist/domain/work-start.d.ts +30 -0
  134. package/cli/dist/domain/work-start.js +42 -0
  135. package/cli/dist/infra/authored-notes.d.ts +1 -1
  136. package/cli/dist/infra/authored-notes.js +10 -4
  137. package/cli/dist/infra/config-store.d.ts +4 -0
  138. package/cli/dist/infra/config-store.js +13 -0
  139. package/cli/dist/infra/git.d.ts +76 -0
  140. package/cli/dist/infra/git.js +123 -1
  141. package/cli/dist/infra/github/client.d.ts +5 -0
  142. package/cli/dist/infra/github/client.js +10 -7
  143. package/cli/dist/infra/github/errors.d.ts +18 -0
  144. package/cli/dist/infra/github/errors.js +22 -0
  145. package/cli/dist/infra/github/issues.d.ts +39 -3
  146. package/cli/dist/infra/github/issues.js +178 -23
  147. package/cli/dist/infra/github/projects.d.ts +35 -0
  148. package/cli/dist/infra/github/projects.js +89 -8
  149. package/cli/dist/infra/github/pulls.d.ts +105 -2
  150. package/cli/dist/infra/github/pulls.js +172 -5
  151. package/cli/dist/infra/github/queries.d.ts +15 -4
  152. package/cli/dist/infra/github/queries.js +203 -40
  153. package/cli/dist/infra/github/readout.d.ts +5 -1
  154. package/cli/dist/infra/github/readout.js +11 -33
  155. package/cli/dist/infra/github/repos.d.ts +18 -0
  156. package/cli/dist/infra/github/repos.js +31 -0
  157. package/cli/dist/infra/nx-scope.d.ts +1 -1
  158. package/cli/dist/infra/nx-scope.js +1 -1
  159. package/cli/dist/infra/state-store.d.ts +10 -1
  160. package/cli/dist/infra/state-store.js +14 -2
  161. package/cli/dist/infra/worktree-links.d.ts +3 -0
  162. package/cli/dist/infra/worktree-links.js +8 -1
  163. package/cli/dist/infra/worktree.d.ts +12 -1
  164. package/cli/dist/infra/worktree.js +40 -23
  165. package/cli/dist/mcp/result.d.ts +82 -7
  166. package/cli/dist/mcp/result.js +139 -19
  167. package/cli/dist/mcp/server.d.ts +2 -2
  168. package/cli/dist/mcp/server.js +57 -10
  169. package/cli/templates/comment/plan.md +14 -0
  170. package/cli/templates/comment/review-findings.md +3 -2
  171. package/cli/templates/issue/bug.md +13 -4
  172. package/cli/templates/issue/task-implement.md +13 -6
  173. package/cli/templates/issue/task.md +13 -4
  174. package/cli/templates/workflow/pecot-board-sync.yml +84 -0
  175. package/npm-shrinkwrap.json +2 -2
  176. package/package.json +1 -1
  177. package/cli/dist/commands/dependabot.d.ts +0 -3
  178. package/cli/dist/commands/issue-project.d.ts +0 -3
  179. package/cli/dist/commands/issue-project.js +0 -176
  180. package/cli/dist/commands/issue-quick.d.ts +0 -3
  181. package/cli/dist/commands/issue-quick.js +0 -126
  182. package/cli/dist/commands/issue-read.d.ts +0 -3
  183. package/cli/dist/commands/issue-read.js +0 -80
  184. package/cli/dist/commands/project-info.d.ts +0 -48
  185. package/cli/dist/commands/project-info.js +0 -181
  186. package/cli/dist/commands/repository.d.ts +0 -5
  187. package/cli/dist/commands/repository.js +0 -265
  188. package/cli/dist/commands/security.d.ts +0 -3
@@ -13,4 +13,67 @@ export function byName(left, right) {
13
13
  return -1;
14
14
  return left > right ? 1 : 0;
15
15
  }
16
+ /**
17
+ コマンド名の 1 語目に使うグループ。利用者が操作する対象で、help の一覧はこの順に並ぶ
18
+ */
19
+ export const COMMAND_GROUPS = [
20
+ { name: 'project', meaning: 'プロジェクトとの接続と設定ファイル。ボードの上の Issue には触らない', help: 'Connect to projects and manage the project config' },
21
+ { name: 'board', meaning: 'ボードの上の Issue の置き場所。設定ファイルは書かない', help: 'Show the project board and place Issues on it' },
22
+ { name: 'issue', meaning: 'Issue そのもの', help: 'Work with Issues' },
23
+ { name: 'session', meaning: '1 つの Issue の作業の始まりから終わりまで', help: 'Start, show, restore and finish the work on an Issue' },
24
+ { name: 'pr', meaning: 'PR そのもの', help: 'Work with PRs' },
25
+ { name: 'release', meaning: 'リリース', help: 'Work with releases' },
26
+ { name: 'tracker', meaning: 'Tracker の Issue の書き直し', help: 'Rewrite the list in a Tracker Issue' },
27
+ { name: 'worktree', meaning: 'worktree', help: 'Work with worktrees' },
28
+ { name: 'branch', meaning: 'リモートのブランチ', help: 'Work with remote branches' },
29
+ ];
30
+ /**
31
+ コマンド名の 2 語目に使う動詞の語彙。1 語に 1 つの意味を決める
32
+ */
33
+ export const COMMAND_VERBS = [
34
+ { name: 'list', meaning: '複数を並べる', readOnly: true },
35
+ { name: 'search', meaning: 'GitHub を探す', readOnly: true },
36
+ { name: 'show', meaning: '1 件を出す', readOnly: true },
37
+ { name: 'get', meaning: '設定の値を出す', readOnly: true },
38
+ { name: 'check', meaning: '次の操作の前に確かめる', readOnly: true },
39
+ { name: 'create', meaning: 'GitHub のものを作る' },
40
+ { name: 'delete', meaning: 'GitHub のものを消す' },
41
+ { name: 'add', meaning: '集まりに入れる' },
42
+ { name: 'remove', meaning: '集まりから出す' },
43
+ { name: 'init', meaning: '既にあるものを pecot で使える状態にする' },
44
+ { name: 'set', meaning: '設定のキーに値を入れる' },
45
+ { name: 'unset', meaning: '設定のキーの値を消す' },
46
+ { name: 'link', meaning: 'リポジトリをプロジェクトにつなぐ' },
47
+ { name: 'activate', meaning: '使うプロジェクトを切り替える' },
48
+ { name: 'start', meaning: '作業を始める' },
49
+ { name: 'restore', meaning: '作業の状態を戻す' },
50
+ { name: 'finish', meaning: '作業を終えて片付ける' },
51
+ { name: 'sync', meaning: '判定や一覧に合わせて書き直す' },
52
+ { name: 'move', meaning: 'ボードの列を移す' },
53
+ { name: 'merge', meaning: 'PR をマージする' },
54
+ { name: 'restack', meaning: '積んだブランチを、base の新しい位置へ載せ直す' },
55
+ { name: 'comment', meaning: 'コメントを書く' },
56
+ { name: 'reopen', meaning: '閉じたものを開き直す' },
57
+ { name: 'block', meaning: '前提を付ける' },
58
+ { name: 'unblock', meaning: '前提を外す' },
59
+ ];
60
+ const COMMAND_WORD_COUNT = 2;
61
+ function isListed(words, word) {
62
+ return word === undefined || words.some(listed => listed.name === word);
63
+ }
64
+ /**
65
+ コマンド名の決まり(`<グループ> <動詞>` の 2 語で、1 語目が COMMAND_GROUPS、2 語目が COMMAND_VERBS にある)に合わない path を、渡された順で返す。全部が合えば空
66
+ */
67
+ export function commandNameViolations(paths) {
68
+ return paths
69
+ .map(path => ({
70
+ path: path.join(' '),
71
+ reason: [
72
+ ...path.length === COMMAND_WORD_COUNT ? [] : [`has ${String(path.length)} word(s); a command name is '<group> <verb>' (2 words)`],
73
+ ...isListed(COMMAND_GROUPS, path.at(0)) ? [] : [`'${String(path.at(0))}' is not a group in COMMAND_GROUPS`],
74
+ ...isListed(COMMAND_VERBS, path.at(1)) ? [] : [`'${String(path.at(1))}' is not a verb in COMMAND_VERBS`],
75
+ ].join('; '),
76
+ }))
77
+ .filter(violation => violation.reason !== '');
78
+ }
16
79
  //# sourceMappingURL=names.js.map
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import type { HintedText } from '../domain/command-hint.js';
2
3
  import type { CommandIo } from './registry.js';
3
4
  /**
4
5
  操作の動詞。自由な文字列を受け取らない
@@ -19,13 +20,28 @@ export declare const VerbSchema: z.ZodEnum<{
19
20
  }>;
20
21
  export type Verb = z.infer<typeof VerbSchema>;
21
22
  /**
23
+ 動詞の過去分詞。done の前置きになる
24
+ */
25
+ export declare function pastOf(verb: Verb): string;
26
+ /**
22
27
  plan と result の元になる操作
23
28
  */
24
29
  export interface Operation {
25
30
  readonly verb: Verb;
26
31
  readonly target: string;
32
+ /**
33
+ 本題でない片付けの操作。行は同じに出し、MCP の結果の message には選ばない
34
+ */
35
+ readonly aside?: boolean;
27
36
  }
28
- export interface Output {
37
+ /**
38
+ dry_run を持つコマンドの output の dryRun。値は createOutput の result が入れる
39
+ */
40
+ export declare const DRY_RUN_FIELD: z.ZodOptional<z.ZodLiteral<true>>;
41
+ /**
42
+ D は MCP の成功の data の型(コマンドの output の z.input)。CLI では result は何も出さない
43
+ */
44
+ export interface Output<D extends object = Record<string, unknown>> {
29
45
  /**
30
46
  dry-run のときだけ、実行する操作を stderr に出す
31
47
  */
@@ -34,8 +50,11 @@ export interface Output {
34
50
  dry-run でないときだけ、実行した操作を stderr に出す
35
51
  */
36
52
  readonly done: (operation: Operation) => void;
37
- readonly warning: (message: string) => void;
38
- readonly error: (message: string) => void;
53
+ /**
54
+ 案内(HintedText)は io の出し先の形にする
55
+ */
56
+ readonly warning: (message: string | HintedText) => void;
57
+ readonly error: (message: string | HintedText) => void;
39
58
  /**
40
59
  value が未設定なら `unknown` と出す
41
60
  */
@@ -44,8 +63,17 @@ export interface Output {
44
63
  結果の本体を stdout にそのまま出す。末尾に改行が無ければ 1 つ足す
45
64
  */
46
65
  readonly data: (text: string) => void;
66
+ /**
67
+ MCP の成功の data に項目を渡す。何度も呼べば浅く重なる(後の値が勝つ)ので、配列は組み終えてから 1 回だけ渡す。
68
+ dry-run のときは dryRun: true を重ねるので、output に DRY_RUN_FIELD を置く
69
+ */
70
+ result(fields: Readonly<Partial<D>>): void;
47
71
  }
48
- export declare function createOutput(isDryRun: boolean, io: CommandIo): Output;
72
+ /**
73
+ warning の行の前置き。MCP の側はこれで stderr から warning の文を拾う
74
+ */
75
+ export declare const WARNING_PREFIX = "warning: ";
76
+ export declare function createOutput<D extends object = Record<string, unknown>>(isDryRun: boolean, io: CommandIo): Output<D>;
49
77
  /**
50
78
  fd から buffer へ読んだバイト数。0 は終端
51
79
  */
@@ -5,6 +5,7 @@
5
5
  // 期待の行は tests/output/cases.json に置き、Python の側と同じ値を共有する。
6
6
  import { readSync } from 'node:fs';
7
7
  import { z } from 'zod';
8
+ import { formatHinted } from '../domain/command-hint.js';
8
9
  import { hasErrorCode } from '../infra/os-error.js';
9
10
  /**
10
11
  操作の動詞。自由な文字列を受け取らない
@@ -13,7 +14,7 @@ export const VerbSchema = z.enum(['create', 'update', 'delete', 'add', 'remove',
13
14
  /**
14
15
  動詞の過去分詞。done の前置きになる
15
16
  */
16
- function pastOf(verb) {
17
+ export function pastOf(verb) {
17
18
  switch (verb) {
18
19
  case 'create': {
19
20
  return 'created';
@@ -54,30 +55,46 @@ function pastOf(verb) {
54
55
  }
55
56
  }
56
57
  /**
58
+ dry_run を持つコマンドの output の dryRun。値は createOutput の result が入れる
59
+ */
60
+ export const DRY_RUN_FIELD = z.literal(true).optional().describe('true on dry_run (nothing was changed)');
61
+ /**
62
+ warning の行の前置き。MCP の側はこれで stderr から warning の文を拾う
63
+ */
64
+ export const WARNING_PREFIX = 'warning: ';
65
+ /**
57
66
  末尾の改行を取り除き、2 行目以降の先頭に空白 2 つを付け、末尾に改行を 1 つ付ける
58
67
  */
59
68
  function formatMessage(prefix, message) {
60
69
  const lines = message.replace(/\n+$/, '').split('\n');
61
- return `${prefix}: ${lines.join('\n ')}\n`;
70
+ return `${prefix}${lines.join('\n ')}\n`;
62
71
  }
63
72
  export function createOutput(isDryRun, io) {
73
+ const render = (message) => formatHinted(message, io.surface ?? 'cli');
74
+ const writeResult = (line, aside) => {
75
+ io.stderr(`${line}\n`);
76
+ if (aside !== true)
77
+ io.resultLine?.(line);
78
+ };
64
79
  return {
65
- planned: ({ verb, target }) => {
80
+ planned: ({ verb, target, aside }) => {
66
81
  if (!isDryRun)
67
82
  return;
68
83
  // unchanged に現在形は無いので、文を変える
69
- io.stderr(verb === 'unchanged' ? `dry-run: would leave ${target} unchanged\n` : `dry-run: would ${verb} ${target}\n`);
84
+ writeResult(verb === 'unchanged' ? `dry-run: would leave ${target} unchanged` : `dry-run: would ${verb} ${target}`, aside);
70
85
  },
71
- done: ({ verb, target }) => {
86
+ done: ({ verb, target, aside }) => {
72
87
  if (isDryRun)
73
88
  return;
74
- io.stderr(`${pastOf(verb)}: ${target}\n`);
89
+ writeResult(`${pastOf(verb)}: ${target}`, aside);
75
90
  },
76
91
  warning: (message) => {
77
- io.stderr(formatMessage('warning', message));
92
+ const text = render(message);
93
+ io.stderr(formatMessage(WARNING_PREFIX, text));
94
+ io.warning?.(text.replace(/\n+$/, ''));
78
95
  },
79
96
  error: (message) => {
80
- io.stderr(formatMessage('error', message));
97
+ io.stderr(formatMessage('error: ', render(message)));
81
98
  },
82
99
  count: (label, value) => {
83
100
  io.stderr(`count: ${label}: ${value === undefined ? 'unknown' : String(value)}\n`);
@@ -85,6 +102,9 @@ export function createOutput(isDryRun, io) {
85
102
  data: (text) => {
86
103
  io.stdout(text.endsWith('\n') ? text : `${text}\n`);
87
104
  },
105
+ result(fields) {
106
+ io.data?.(isDryRun ? { ...fields, dryRun: true } : fields);
107
+ },
88
108
  };
89
109
  }
90
110
  const RETRY_WAIT_MILLISECONDS = 10;
@@ -0,0 +1,3 @@
1
+ import type { CommandDefinition } from './command-definition.js';
2
+ export declare const PR_MERGE_COMMAND: CommandDefinition;
3
+ //# sourceMappingURL=pr-merge.d.ts.map
@@ -0,0 +1,230 @@
1
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は内部の状態を持つ */
2
+ // pr merge。単独の PR もスタックの PR も、非同期のマージ API(merge-async)でマージする。
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { z } from 'zod';
5
+ import { describeApiError } from '../domain/api-error-detail.js';
6
+ import { jsonField, tryParseJsonText } from '../domain/json.js';
7
+ import { FLAG_MERGE_SLASH_PENDING } from '../domain/state.js';
8
+ import { GitHubAPIError, GitHubNotFoundError } from '../infra/github/errors.js';
9
+ import { consumeFlag } from '../infra/state-store.js';
10
+ import { requireActiveConfigPlain, stopWith } from './command-stop.js';
11
+ import { defineCommand } from './command-definition.js';
12
+ import { kindOfFailure } from './failure.js';
13
+ import { createGitHubClient } from './github-client.js';
14
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
15
+ import { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
16
+ // 要求を送らずに止める(ドラフト、閉じている、スタックの最下段でない)
17
+ const NOT_MERGEABLE_EXIT_CODE = 2;
18
+ const POLL_INTERVAL_MILLISECONDS = 2000;
19
+ // R14 では 3〜8 秒で終わった。時刻でなく回数で数え、偽のタイマーでも同じに動かす
20
+ const POLL_LIMIT = 30;
21
+ const POLL_LIMIT_SECONDS = (POLL_INTERVAL_MILLISECONDS * POLL_LIMIT) / 1000;
22
+ // 同期のマージ API が、マージできない(405)・head が sha と違う(409)ときに返す状態コード
23
+ const SYNC_MERGE_REJECTED_STATUSES = new Set([405, 409]);
24
+ const MergeInputSchema = z.strictObject({
25
+ pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
26
+ dry_run: z.boolean().default(false).describe('Read the PR and its stack, and show what would happen without merging'),
27
+ });
28
+ const PR_MERGE_OUTPUT = z.strictObject({
29
+ pullRequest: z.string().describe('PR (owner/repo/N)'),
30
+ base: z.string().describe('Base branch the PR is merged into'),
31
+ status: z.enum(['merged', 'enqueued']).optional().describe('merged, or enqueued when the PR was added to the merge queue (absent on dry_run)'),
32
+ stack: z.strictObject({
33
+ number: z.int().describe('Stack number'),
34
+ size: z.int().describe('Number of PRs in the stack from this PR upward (K of "1 of K")'),
35
+ }).optional().describe('Stack the PR is the bottom of (absent for a PR outside a stack)'),
36
+ dryRun: DRY_RUN_FIELD,
37
+ });
38
+ function pathOf(target) {
39
+ return `${target.owner}/${target.repository}/${String(target.number)}`;
40
+ }
41
+ // マージまで進まずに止まるので、/pecot-w:w-merge が立てた確認の免除を残さない。dry-run は状態を変えない
42
+ function stopNotMergeable(out, message, isDryRun) {
43
+ if (!isDryRun)
44
+ consumeFlag(FLAG_MERGE_SLASH_PENDING);
45
+ return stopWith(out, message, 'pr-state', NOT_MERGEABLE_EXIT_CODE);
46
+ }
47
+ // 印は残す。w-merge は必須チェックを待って同じ PR に pr_merge を呼び直す
48
+ function stopRejected(out, reason) {
49
+ return stopWith(out, `merge was rejected: ${reason}`, 'pr-state');
50
+ }
51
+ async function readPullRequest(out, client, target) {
52
+ try {
53
+ return await client.getPullRequestForMerge(target.owner, target.repository, target.number);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof GitHubNotFoundError)
57
+ return stopWith(out, `PR not found: ${pathOf(target)}`, 'github-not-found');
58
+ if (!(error instanceof GitHubAPIError))
59
+ throw error;
60
+ return stopWith(out, `could not read PR ${pathOf(target)}: ${describeApiError(error)}`, kindOfFailure(error));
61
+ }
62
+ }
63
+ function checkState(out, name, pullRequest, isDryRun) {
64
+ if (pullRequest.state === 'MERGED')
65
+ stopNotMergeable(out, `${name} is already merged`, isDryRun);
66
+ if (pullRequest.state !== 'OPEN')
67
+ stopNotMergeable(out, `${name} is closed`, isDryRun);
68
+ if (pullRequest.isDraft)
69
+ stopNotMergeable(out, `${name} is a draft`, isDryRun);
70
+ }
71
+ // 下の段に open の PR があれば止める。マージ済みで並びに残る PR は飛ばす。スタックの機能が無いリポは単独の PR として扱う
72
+ async function bottomOfStack(out, client, target, isDryRun) {
73
+ let stack;
74
+ try {
75
+ stack = await client.getStackOfPullRequest(target.owner, target.repository, target.number);
76
+ }
77
+ catch (error) {
78
+ if (error instanceof GitHubNotFoundError)
79
+ return undefined;
80
+ if (!(error instanceof GitHubAPIError))
81
+ throw error;
82
+ return stopWith(out, `could not read the stack of PR ${pathOf(target)}: ${describeApiError(error)}`, kindOfFailure(error));
83
+ }
84
+ if (stack === undefined)
85
+ return undefined;
86
+ const index = stack.pullRequests.indexOf(target.number);
87
+ for (const lower of stack.pullRequests.slice(0, index)) {
88
+ const pullRequest = await readPullRequest(out, client, { ...target, number: lower });
89
+ if (pullRequest.state === 'OPEN') {
90
+ stopNotMergeable(out, `PR #${String(target.number)} is not the bottom of stack #${String(stack.number)}. Merge PR #${String(lower)} first`, isDryRun);
91
+ }
92
+ }
93
+ return { number: stack.number, size: stack.pullRequests.length - index };
94
+ }
95
+ function finishMerged(context) {
96
+ context.out.done({ verb: 'merge', target: `${context.name} into ${context.base}${context.suffix}` });
97
+ context.out.result({ status: 'merged' });
98
+ return 0;
99
+ }
100
+ function finishEnqueued(context) {
101
+ context.out.done({ verb: 'add', target: `${context.name} to merge queue of ${context.base}` });
102
+ context.out.result({ status: 'enqueued' });
103
+ return 0;
104
+ }
105
+ function finishResult(context, result) {
106
+ if (result.status === 'merged')
107
+ return finishMerged(context);
108
+ if (result.status === 'enqueued')
109
+ return finishEnqueued(context);
110
+ return stopRejected(context.out, result.message ?? 'GitHub gave no reason');
111
+ }
112
+ // PR の状態から決める。マージ済みでもキューの中でもなければ undefined
113
+ async function finishIfSettled(context) {
114
+ const pullRequest = await readPullRequest(context.out, context.client, context.target);
115
+ if (pullRequest.state === 'MERGED')
116
+ return finishMerged(context);
117
+ if (pullRequest.isInMergeQueue)
118
+ return finishEnqueued(context);
119
+ return undefined;
120
+ }
121
+ function stopUnconfirmed(context) {
122
+ return stopWith(context.out, `could not confirm the merge of ${context.name}: it is neither merged nor in the merge queue`, 'pr-state');
123
+ }
124
+ async function finishFromState(context) {
125
+ return await finishIfSettled(context) ?? stopUnconfirmed(context);
126
+ }
127
+ // 結果の 404 は、消えた結果のほか、書いた直後の読み取りの遅れでも返る。そのときは期限まで読み直す
128
+ async function pollResult(context, uuid) {
129
+ const { owner, repository, number } = context.target;
130
+ let isResultMissing = false;
131
+ for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {
132
+ await delay(POLL_INTERVAL_MILLISECONDS);
133
+ let result;
134
+ try {
135
+ result = await context.client.getAsyncMergeResult(owner, repository, number, uuid);
136
+ }
137
+ catch (error) {
138
+ if (!(error instanceof GitHubAPIError))
139
+ throw error;
140
+ return stopWith(context.out, `could not read the merge result of PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
141
+ }
142
+ if (result === undefined) {
143
+ isResultMissing = true;
144
+ const settled = await finishIfSettled(context);
145
+ if (settled !== undefined)
146
+ return settled;
147
+ continue;
148
+ }
149
+ isResultMissing = false;
150
+ if (result.status !== 'pending')
151
+ return finishResult(context, result);
152
+ }
153
+ return isResultMissing
154
+ ? stopUnconfirmed(context)
155
+ : stopWith(context.out, `merge did not finish in ${String(POLL_LIMIT_SECONDS)}s. Check ${context.name}`, 'github-api');
156
+ }
157
+ function reasonOf(error) {
158
+ const message = jsonField(tryParseJsonText(error.responseBody ?? ''), 'message');
159
+ return typeof message === 'string' && message !== '' ? message : describeApiError(error);
160
+ }
161
+ // merge-async の無い GHES 向け。sha を渡し、読んだ後に push された PR をマージしない
162
+ async function mergeSynchronously(context, pullRequest) {
163
+ const { owner, repository, number } = context.target;
164
+ try {
165
+ await context.client.mergePullRequest(owner, repository, number, 'squash', pullRequest.headRefOid);
166
+ }
167
+ catch (error) {
168
+ if (!(error instanceof GitHubAPIError))
169
+ throw error;
170
+ return error.statusCode !== undefined && SYNC_MERGE_REJECTED_STATUSES.has(error.statusCode)
171
+ ? stopRejected(context.out, reasonOf(error))
172
+ : stopWith(context.out, `could not merge PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
173
+ }
174
+ return finishMerged(context);
175
+ }
176
+ async function requestMerge(context, pullRequest) {
177
+ const { owner, repository, number } = context.target;
178
+ let requested;
179
+ try {
180
+ requested = await context.client.requestAsyncMerge(owner, repository, number, { sha: pullRequest.headRefOid, mergeQueue: pullRequest.isMergeQueueEnabled });
181
+ }
182
+ catch (error) {
183
+ if (!(error instanceof GitHubAPIError))
184
+ throw error;
185
+ // 同期の API はスタックの PR を 403 で拒むので、スタックの中では戻さない
186
+ return error instanceof GitHubNotFoundError && !context.isInStack
187
+ ? mergeSynchronously(context, pullRequest)
188
+ : stopWith(context.out, `could not merge PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
189
+ }
190
+ switch (requested.outcome) {
191
+ case 'rejected': {
192
+ return stopRejected(context.out, requested.message);
193
+ }
194
+ // 文書は 409 の本文の形を示していない。uuid が無ければ PR の状態から決める
195
+ case 'conflict': {
196
+ return requested.uuid === undefined ? finishFromState(context) : pollResult(context, requested.uuid);
197
+ }
198
+ case 'accepted': {
199
+ const { result } = requested;
200
+ return result.status === 'pending' && result.uuid !== undefined ? pollResult(context, result.uuid) : finishResult(context, result);
201
+ }
202
+ }
203
+ }
204
+ export const PR_MERGE_COMMAND = defineCommand({
205
+ path: ['pr', 'merge'],
206
+ description: 'Merge a PR with the asynchronous merge API (a PR in a stack must be the bottom one)',
207
+ input: MergeInputSchema,
208
+ output: PR_MERGE_OUTPUT,
209
+ positional: ['pr_ref'],
210
+ shortFlags: { dry_run: '-n' },
211
+ interactive: false,
212
+ run: async (input, io) => {
213
+ const out = createOutput(input.dry_run, io);
214
+ const config = requireActiveConfigPlain(out);
215
+ const target = parseReference(input.pr_ref, input.repo, out);
216
+ const client = createGitHubClient(out, config.host);
217
+ const name = `PR #${String(target.number)}`;
218
+ const pullRequest = await readPullRequest(out, client, target);
219
+ checkState(out, name, pullRequest, input.dry_run);
220
+ const stack = await bottomOfStack(out, client, target, input.dry_run);
221
+ out.result({ pullRequest: pathOf(target), base: pullRequest.baseRefName, ...stack !== undefined && { stack } });
222
+ const suffix = stack === undefined ? '' : ` (stack #${String(stack.number)}, 1 of ${String(stack.size)})`;
223
+ if (input.dry_run) {
224
+ out.planned({ verb: 'merge', target: `${name} into ${pullRequest.baseRefName}${suffix}` });
225
+ return 0;
226
+ }
227
+ return requestMerge({ out, client, target, name, base: pullRequest.baseRefName, suffix, isInStack: stack !== undefined }, pullRequest);
228
+ },
229
+ });
230
+ //# sourceMappingURL=pr-merge.js.map
@@ -0,0 +1,8 @@
1
+ import type { Output } from './output.js';
2
+ export declare const PR_REFERENCE_DESCRIPTION = "PR reference (`owner/repo/N`, or the short form `N` in the repository of `--repo`, or else of the git remote of the current directory)";
3
+ export declare function parseReference(reference: string, globalRepository: string | undefined, out: Readonly<Output>): {
4
+ readonly owner: string;
5
+ readonly repository: string;
6
+ readonly number: number;
7
+ };
8
+ //# sourceMappingURL=pr-reference.d.ts.map
@@ -0,0 +1,30 @@
1
+ // PR の参照(pr_ref)の読み方。pr show・pr merge・session finish が共有する。
2
+ import { ReferenceParseError, parsePullRequestReference } from '../domain/reference-parser.js';
3
+ import { AmbiguousRepositoryError, resolveRepository } from '../domain/repository-resolver.js';
4
+ import { gitRunnerFor } from '../infra/git.js';
5
+ import { stopWith } from './command-stop.js';
6
+ import { USAGE_EXIT_CODE } from './usage-error.js';
7
+ export const PR_REFERENCE_DESCRIPTION = 'PR reference (`owner/repo/N`, or the short form `N` in the repository of `--repo`, or else of the git remote of the current directory)';
8
+ // グローバルの --repo か、いまの git の repository。決められなければ undefined
9
+ function resolveBaseRepository(globalRepository) {
10
+ try {
11
+ return resolveRepository(globalRepository, gitRunnerFor(process.cwd())).repository;
12
+ }
13
+ catch (error) {
14
+ if (error instanceof AmbiguousRepositoryError)
15
+ return undefined;
16
+ throw error;
17
+ }
18
+ }
19
+ export function parseReference(reference, globalRepository, out) {
20
+ try {
21
+ const parsed = parsePullRequestReference(reference, resolveBaseRepository(globalRepository), { repositoryFlag: true });
22
+ return { owner: parsed.repository.owner, repository: parsed.repository.repository, number: parsed.number };
23
+ }
24
+ catch (error) {
25
+ if (error instanceof ReferenceParseError)
26
+ return stopWith(out, error.hintedText ?? error.message, 'invalid-input', USAGE_EXIT_CODE);
27
+ throw error;
28
+ }
29
+ }
30
+ //# sourceMappingURL=pr-reference.js.map
@@ -0,0 +1,6 @@
1
+ import type { CommandDefinition } from './command-definition.js';
2
+ /**
3
+ pr restack。pr のグループの最後に並ぶ
4
+ */
5
+ export declare const PR_RESTACK_COMMANDS: readonly CommandDefinition[];
6
+ //# sourceMappingURL=pr-restack.d.ts.map