@pecot/workflow-mcp 6.0.0 → 7.0.1-dev.19

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 (96) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +5 -58
  3. package/cli/dist/commands/board-add.js +11 -1
  4. package/cli/dist/commands/board-judgment.d.ts +12 -3
  5. package/cli/dist/commands/board-judgment.js +12 -6
  6. package/cli/dist/commands/board-move.js +9 -1
  7. package/cli/dist/commands/board-readiness.d.ts +3 -3
  8. package/cli/dist/commands/board-show.js +5 -2
  9. package/cli/dist/commands/board-sync.js +14 -5
  10. package/cli/dist/commands/board-view.d.ts +94 -5
  11. package/cli/dist/commands/board-view.js +119 -17
  12. package/cli/dist/commands/branch.js +11 -17
  13. package/cli/dist/commands/command-definition.d.ts +19 -2
  14. package/cli/dist/commands/command-definition.js +9 -0
  15. package/cli/dist/commands/failure-kind.d.ts +1 -1
  16. package/cli/dist/commands/failure-kind.js +1 -0
  17. package/cli/dist/commands/issue-board.d.ts +31 -3
  18. package/cli/dist/commands/issue-board.js +28 -4
  19. package/cli/dist/commands/issue-comment.js +19 -2
  20. package/cli/dist/commands/issue-create.js +96 -17
  21. package/cli/dist/commands/issue-dependency.js +51 -14
  22. package/cli/dist/commands/issue-readiness.d.ts +30 -2
  23. package/cli/dist/commands/issue-readiness.js +35 -0
  24. package/cli/dist/commands/issue-reopen.js +18 -3
  25. package/cli/dist/commands/issue-shared.d.ts +11 -5
  26. package/cli/dist/commands/issue-shared.js +25 -6
  27. package/cli/dist/commands/issue-show.js +78 -8
  28. package/cli/dist/commands/names.d.ts +1 -1
  29. package/cli/dist/commands/names.js +3 -3
  30. package/cli/dist/commands/output.d.ts +18 -2
  31. package/cli/dist/commands/output.js +16 -3
  32. package/cli/dist/commands/pr-merge.d.ts +3 -0
  33. package/cli/dist/commands/pr-merge.js +225 -0
  34. package/cli/dist/commands/pr-reference.d.ts +8 -0
  35. package/cli/dist/commands/pr-reference.js +30 -0
  36. package/cli/dist/commands/pr-restack.d.ts +6 -0
  37. package/cli/dist/commands/pr-restack.js +231 -0
  38. package/cli/dist/commands/pr-waiting.d.ts +41 -2
  39. package/cli/dist/commands/pr-waiting.js +74 -37
  40. package/cli/dist/commands/pr.d.ts +10 -6
  41. package/cli/dist/commands/pr.js +214 -111
  42. package/cli/dist/commands/project-sync.d.ts +10 -2
  43. package/cli/dist/commands/project-sync.js +7 -6
  44. package/cli/dist/commands/project.js +174 -17
  45. package/cli/dist/commands/registry.js +2 -0
  46. package/cli/dist/commands/release.js +67 -18
  47. package/cli/dist/commands/renamed-commands.js +0 -1
  48. package/cli/dist/commands/repository-match.js +7 -2
  49. package/cli/dist/commands/restack-reading.d.ts +45 -0
  50. package/cli/dist/commands/restack-reading.js +29 -0
  51. package/cli/dist/commands/session-finish.js +132 -28
  52. package/cli/dist/commands/session-start.js +31 -60
  53. package/cli/dist/commands/session.js +119 -135
  54. package/cli/dist/commands/tracker-sync-dependabot.js +21 -4
  55. package/cli/dist/commands/tracker-sync-security.js +22 -4
  56. package/cli/dist/commands/tracker-sync.d.ts +30 -0
  57. package/cli/dist/commands/tracker-sync.js +15 -0
  58. package/cli/dist/commands/tracker.js +2 -0
  59. package/cli/dist/commands/work-target.d.ts +14 -9
  60. package/cli/dist/commands/work-target.js +19 -19
  61. package/cli/dist/commands/worktree.js +71 -5
  62. package/cli/dist/domain/branch-name.d.ts +7 -0
  63. package/cli/dist/domain/branch-name.js +23 -1
  64. package/cli/dist/domain/command-hint.d.ts +1 -1
  65. package/cli/dist/domain/issue-readout.d.ts +0 -4
  66. package/cli/dist/domain/pull-request.d.ts +20 -3
  67. package/cli/dist/domain/pull-request.js +25 -9
  68. package/cli/dist/domain/readiness.d.ts +17 -0
  69. package/cli/dist/domain/readiness.js +39 -2
  70. package/cli/dist/domain/restack.d.ts +66 -0
  71. package/cli/dist/domain/restack.js +57 -0
  72. package/cli/dist/domain/state.d.ts +41 -12
  73. package/cli/dist/domain/state.js +30 -14
  74. package/cli/dist/domain/work-start.d.ts +0 -4
  75. package/cli/dist/domain/work-start.js +0 -7
  76. package/cli/dist/infra/git.d.ts +69 -0
  77. package/cli/dist/infra/git.js +117 -0
  78. package/cli/dist/infra/github/pulls.d.ts +81 -2
  79. package/cli/dist/infra/github/pulls.js +116 -5
  80. package/cli/dist/infra/github/queries.d.ts +4 -1
  81. package/cli/dist/infra/github/queries.js +47 -32
  82. package/cli/dist/infra/github/readout.js +0 -33
  83. package/cli/dist/infra/paths.d.ts +1 -3
  84. package/cli/dist/infra/paths.js +2 -45
  85. package/cli/dist/infra/state-store.d.ts +3 -8
  86. package/cli/dist/infra/state-store.js +6 -24
  87. package/cli/dist/mcp/result.d.ts +63 -16
  88. package/cli/dist/mcp/result.js +106 -30
  89. package/cli/dist/mcp/server.js +37 -4
  90. package/cli/templates/comment/plan.md +2 -2
  91. package/cli/templates/comment/review-findings.md +3 -2
  92. package/cli/templates/issue/bug.md +13 -4
  93. package/cli/templates/issue/task.md +13 -4
  94. package/cli/templates/workflow/pecot-board-sync.yml +3 -2
  95. package/npm-shrinkwrap.json +2 -2
  96. package/package.json +1 -1
@@ -39,7 +39,7 @@ run の本体を包む。終わったら 0 を返す。BadParameterError は使
39
39
  */
40
40
  export declare function runWithExit(body: () => Promise<void>): Promise<0>;
41
41
  /**
42
- `owner/repo/N` の表記。エラー文と done の行の対象に使う
42
+ `owner/repo/N` の表記。エラー文と done の行の対象、MCP の data の参照に使う
43
43
  */
44
44
  export declare function issuePath(owner: string, repository: string, number: number): string;
45
45
  export interface IssueTarget {
@@ -135,13 +135,19 @@ export interface IssueField {
135
135
  readonly label: string;
136
136
  }
137
137
  /**
138
- カスタムフィールドを順に設定し、設定できた分を 1 行の set にする。失敗したフィールドは、何も出さずに飛ばす。設定できたフィールドの名前を返す
138
+ 選択肢の ID を読み直す案内を 1 回の実行で 1 回だけ出すための印
139
139
  */
140
- export declare function setIssueFields(output: Output, client: GitHubClient, config: ProjectConfig, itemId: string, target: string, fields: readonly IssueField[]): Promise<readonly string[]>;
140
+ export interface FieldHintState {
141
+ hasHinted: boolean;
142
+ }
143
+ /**
144
+ カスタムフィールドを順に設定し、設定できた分を 1 行の set にする。書き込みに失敗したフィールドは warning にして飛ばす。設定できたフィールドの名前を返す
145
+ */
146
+ export declare function setIssueFields(output: Output, client: GitHubClient, config: ProjectConfig, itemId: string, target: string, fields: readonly IssueField[], hintState: FieldHintState): Promise<readonly string[]>;
141
147
  /**
142
- 親 Epic のサブ Issue にする。失敗は Issue の URL(issueUrl が undefined なら出し済みとして省く)、error の行の順に出して終了コード 1。issueNodeId は、無ければ取り直す関数
148
+ 親 Epic のサブ Issue にする。失敗は Issue の URL(issueUrl が undefined なら出し済みとして省く)、error の行の順に出して終了コード 1。issueNodeId は、無ければ取り直す関数。行に出した親の参照(owner/repo/N)を返す
143
149
  */
144
- export declare function linkToParentEpic(output: Output, client: GitHubClient, target: string, parentReference: IssueReference, issueNodeId: string | (() => Promise<string>), issueUrl: string | undefined): Promise<void>;
150
+ export declare function linkToParentEpic(output: Output, client: GitHubClient, target: string, parentReference: IssueReference, issueNodeId: string | (() => Promise<string>), issueUrl: string | undefined): Promise<string>;
145
151
  /**
146
152
  リポジトリがプロジェクトにリンクされていなければ、message を error に出して終了コード 1
147
153
  */
@@ -15,10 +15,11 @@ import { issueReferenceToCliReference, parseIssueReference, ReferenceParseError
15
15
  import { AmbiguousRepositoryError, createRepositoryReference, resolveRepository } from '../domain/repository-resolver.js';
16
16
  import { CLOSED_HEADINGS_BY_TEMPLATE, FOLD_SUMMARY_BY_TEMPLATE, validateBodyStyle, validateClosedHeadings, validateFoldBalance, validateFoldSummaries, validateHeadingSummaries, validateSections, } from '../domain/sections.js';
17
17
  import { gitRunnerFor } from '../infra/git.js';
18
- import { GitHubAPIError } from '../infra/github/errors.js';
18
+ import { GitHubAPIError, GitHubAuthError, GitHubRateLimitError } from '../infra/github/errors.js';
19
19
  import { requireNumber, requireString } from '../infra/github/payload.js';
20
20
  import { readTemplateSections, templateFile } from '../infra/template-store.js';
21
- import { commandHint, hinted, inputHint, inputNameHint } from './command-hint.js';
21
+ import { getActiveConfigPath, projectsDirectory } from '../infra/config-store.js';
22
+ import { commandHint, hinted, inputHint, inputNameHint, joinHinted, placeholder } from './command-hint.js';
22
23
  import { stopWith } from './command-stop.js';
23
24
  import { kindOfFailure } from './failure.js';
24
25
  import { createGitHubClient } from './github-client.js';
@@ -83,7 +84,7 @@ export async function runWithExit(body) {
83
84
  }
84
85
  // --- Issue 参照 ---
85
86
  /**
86
- `owner/repo/N` の表記。エラー文と done の行の対象に使う
87
+ `owner/repo/N` の表記。エラー文と done の行の対象、MCP の data の参照に使う
87
88
  */
88
89
  export function issuePath(owner, repository, number) {
89
90
  return `${owner}/${repository}/${String(number)}`;
@@ -305,10 +306,18 @@ export async function addToBoardOrWarn(output, client, config, owner, repository
305
306
  output.done({ verb: 'add', target: `Issue ${issuePath(owner, repository, issueNumber)} to project` });
306
307
  return added;
307
308
  }
309
+ function rereadOptionsHint() {
310
+ const configPath = getActiveConfigPath();
311
+ // projects/ の外の config は、ファイル名では project activate が見つけられない
312
+ const project = configPath === undefined
313
+ ? placeholder('PROJECT')
314
+ : (path.dirname(configPath) === projectsDirectory() ? path.basename(configPath, '.json') : configPath);
315
+ return hinted `hint: if the board options were recreated, run ${commandHint(['project', 'activate'], { project })} to read their IDs again`;
316
+ }
308
317
  /**
309
- カスタムフィールドを順に設定し、設定できた分を 1 行の set にする。失敗したフィールドは、何も出さずに飛ばす。設定できたフィールドの名前を返す
318
+ カスタムフィールドを順に設定し、設定できた分を 1 行の set にする。書き込みに失敗したフィールドは warning にして飛ばす。設定できたフィールドの名前を返す
310
319
  */
311
- export async function setIssueFields(output, client, config, itemId, target, fields) {
320
+ export async function setIssueFields(output, client, config, itemId, target, fields, hintState) {
312
321
  const labels = [];
313
322
  const written = [];
314
323
  for (const { fieldName, optionName, label } of fields) {
@@ -321,6 +330,15 @@ export async function setIssueFields(output, client, config, itemId, target, fie
321
330
  catch (error) {
322
331
  if (!(error instanceof GitHubAPIError))
323
332
  throw error;
333
+ const message = `could not set ${label} of ${target}: ${error.message}`;
334
+ // 選択肢を作り直すと config の ID が古くなり、書き込みが落ちる。認証とレート制限の失敗は、読み直しても直らない
335
+ const canReread = !(error instanceof GitHubAuthError || error instanceof GitHubRateLimitError);
336
+ if (!canReread || hintState.hasHinted) {
337
+ output.warning(message);
338
+ continue;
339
+ }
340
+ output.warning(joinHinted([message, rereadOptionsHint()]));
341
+ hintState.hasHinted = true;
324
342
  }
325
343
  }
326
344
  if (labels.length > 0)
@@ -328,7 +346,7 @@ export async function setIssueFields(output, client, config, itemId, target, fie
328
346
  return written;
329
347
  }
330
348
  /**
331
- 親 Epic のサブ Issue にする。失敗は Issue の URL(issueUrl が undefined なら出し済みとして省く)、error の行の順に出して終了コード 1。issueNodeId は、無ければ取り直す関数
349
+ 親 Epic のサブ Issue にする。失敗は Issue の URL(issueUrl が undefined なら出し済みとして省く)、error の行の順に出して終了コード 1。issueNodeId は、無ければ取り直す関数。行に出した親の参照(owner/repo/N)を返す
332
350
  */
333
351
  export async function linkToParentEpic(output, client, target, parentReference, issueNodeId, issueUrl) {
334
352
  const parent = issueReferenceToCliReference(parentReference);
@@ -344,6 +362,7 @@ export async function linkToParentEpic(output, client, target, parentReference,
344
362
  stopWith(output, `could not add ${target} as sub-issue of ${parent}: ${error.message}\nthe order in its title is not counted for the next numbering until it is linked to the parent; link it by hand`, kindOfFailure(error));
345
363
  }
346
364
  output.done({ verb: 'add', target: `${target} as sub-issue of ${parent}` });
365
+ return parent;
347
366
  }
348
367
  /**
349
368
  リポジトリがプロジェクトにリンクされていなければ、message を error に出して終了コード 1
@@ -10,7 +10,7 @@ import { stopWith, requireActiveConfigPlain } from './command-stop.js';
10
10
  import { kindOfFailure } from './failure.js';
11
11
  import { createGitHubClient } from './github-client.js';
12
12
  import { ISSUE_REF_DESCRIPTION, issuePath, parseIssueReferenceOrExit, runWithExit } from './issue-shared.js';
13
- import { blockedByReadCount, createReadinessCache, judgeSnapshot, readIssueReadiness, readinessJson, snapshotWithoutPrerequisites } from './issue-readiness.js';
13
+ import { blockedByReadCount, createReadinessCache, judgeSnapshot, READINESS_JSON, readIssueReadiness, readinessJson, snapshotWithoutPrerequisites } from './issue-readiness.js';
14
14
  import { createOutput } from './output.js';
15
15
  const MAX_COMMENT_LIMIT = 20;
16
16
  const DEFAULT_COMMENT_LIMIT = 5;
@@ -25,14 +25,14 @@ function parentLine(issue, owner, repository) {
25
25
  /**
26
26
  Issue の情報を Markdown にする。owner・repo は、親が別のリポジトリかを調べる元
27
27
  */
28
- function formatIssueMarkdown(issue, owner, repository, readiness) {
28
+ function formatIssueMarkdown(issue, owner, repository, readinessLines) {
29
29
  const lines = [`## #${String(issue.number)} ${issue.title}`, ''];
30
30
  const meta = [`**State:** ${issue.state}`];
31
31
  if (issue.comments.total_count > 0)
32
32
  meta.push(`**Comments:** ${String(issue.comments.total_count)}`);
33
33
  lines.push(meta.join(' | '), '');
34
34
  const parent = parentLine(issue, owner, repository);
35
- const header = [...parent === undefined ? [] : [parent], ...readiness?.lines ?? []];
35
+ const header = [...parent === undefined ? [] : [parent], ...readinessLines];
36
36
  if (header.length > 0)
37
37
  lines.push(...header, '');
38
38
  if (issue.linked_branches.length > 0) {
@@ -54,6 +54,54 @@ function formatIssueMarkdown(issue, owner, repository, readiness) {
54
54
  }
55
55
  return lines.join('\n');
56
56
  }
57
+ const PREREQUISITE_JSON = z.strictObject({
58
+ number: z.int().describe('Issue number of the prerequisite'),
59
+ repository: z.string().describe('Repository of the prerequisite (owner/repo)'),
60
+ state: z.enum(['OPEN', 'CLOSED']).describe('State of the prerequisite'),
61
+ wait: z.enum(['stack', 'merge']).describe('How to wait for the prerequisite (stack on its branch, or wait for its merge)'),
62
+ reason: z.string().nullable().describe('Reason written in the Waits for merge section (null when none)'),
63
+ });
64
+ const COMMENT_JSON = z.strictObject({
65
+ author: z.string().describe('Login of the author (ghost when deleted)'),
66
+ created_at: z.string().describe('Creation time (ISO 8601)'),
67
+ body: z.string().describe('Body of the comment'),
68
+ });
69
+ const COMMENTS_JSON = z.strictObject({
70
+ total_count: z.int().describe('Number of all comments'),
71
+ nodes: z.array(COMMENT_JSON).describe('Latest comments, up to comment_limit'),
72
+ });
73
+ const PARENT_JSON = z.strictObject({
74
+ number: z.int().describe('Issue number of the parent'),
75
+ title: z.string().describe('Title of the parent'),
76
+ state: z.string().describe('State of the parent (OPEN or CLOSED)'),
77
+ owner: z.string().nullable().describe('Owner of the parent repository'),
78
+ repo: z.string().nullable().describe('Name of the parent repository'),
79
+ });
80
+ const SUB_ISSUE_JSON = z.strictObject({
81
+ number: z.int().describe('Issue number of the sub-issue'),
82
+ state: z.string().describe('State of the sub-issue (OPEN or CLOSED)'),
83
+ title: z.string().describe('Title of the sub-issue'),
84
+ });
85
+ const LINKED_PR_JSON = z.strictObject({
86
+ number: z.int().describe('PR number'),
87
+ title: z.string().describe('Title of the PR'),
88
+ state: z.string().describe('State of the PR'),
89
+ });
90
+ const ISSUE_SHOW_OUTPUT = z.strictObject({
91
+ number: z.int().describe('Issue number'),
92
+ state: z.string().describe('State of the Issue (OPEN or CLOSED)'),
93
+ title: z.string().describe('Title of the Issue'),
94
+ body: z.string().describe('Body of the Issue'),
95
+ comments: COMMENTS_JSON.describe('Comments of the Issue'),
96
+ parent: PARENT_JSON.nullable().describe('Parent Issue (null when none)'),
97
+ sub_issues: z.array(SUB_ISSUE_JSON).describe('Sub-issues'),
98
+ linked_branches: z.array(z.string()).describe('Branches linked to the Issue'),
99
+ linked_prs: z.array(LINKED_PR_JSON).describe('PRs linked to the Issue'),
100
+ owner: z.string().describe('Owner of the Issue repository'),
101
+ repo: z.string().describe('Name of the Issue repository'),
102
+ blockedBy: z.array(PREREQUISITE_JSON).nullable().describe('Prerequisites (blocked by) of the Issue (null when they could not be read)'),
103
+ readiness: READINESS_JSON.nullable().describe('Readiness judgment (null when it could not be judged)'),
104
+ });
57
105
  // 前提と判定を読めなかったとき
58
106
  const UNREAD = { lines: [], blockedBy: JSON_NULL, readiness: JSON_NULL };
59
107
  /**
@@ -63,10 +111,11 @@ function readinessView(source, readiness, text) {
63
111
  const home = source.ref.repository;
64
112
  const entries = source.prerequisites.map((prerequisite) => {
65
113
  const { issue, wait, reason } = prerequisite;
114
+ const state = issue.state === 'open' ? 'OPEN' : 'CLOSED';
66
115
  return {
67
116
  label: displayReference(issue.ref, home),
68
117
  title: source.titles.get(issueReferenceKey(issue.ref)) ?? '',
69
- state: issue.state === 'open' ? 'OPEN' : 'CLOSED',
118
+ state,
70
119
  status: describePrerequisiteState(prerequisite),
71
120
  wait,
72
121
  reason,
@@ -82,6 +131,27 @@ function readinessView(source, readiness, text) {
82
131
  readiness: readiness === undefined || text === undefined ? JSON_NULL : readinessJson(readiness, text),
83
132
  };
84
133
  }
134
+ /**
135
+ --json の標準出力と MCP の data の中身。キーを並べた順が --json の出力の順になる
136
+ */
137
+ // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types -- zod の入れ子の型
138
+ function issueShowJson(issue, owner, repository, view) {
139
+ return {
140
+ number: issue.number,
141
+ state: issue.state,
142
+ title: issue.title,
143
+ body: issue.body,
144
+ comments: { total_count: issue.comments.total_count, nodes: [...issue.comments.nodes] },
145
+ parent: issue.parent,
146
+ sub_issues: [...issue.sub_issues],
147
+ linked_branches: [...issue.linked_branches],
148
+ linked_prs: [...issue.linked_prs],
149
+ owner,
150
+ repo: repository,
151
+ blockedBy: view.blockedBy === JSON_NULL ? JSON_NULL : [...view.blockedBy],
152
+ readiness: view.readiness,
153
+ };
154
+ }
85
155
  function judgedView(judged) {
86
156
  const { readiness } = judged;
87
157
  return readinessView(judged, readiness, readiness === undefined ? undefined : describeReadiness(readiness, judged.prerequisites, judged.ref.repository));
@@ -139,6 +209,7 @@ const ISSUE_SHOW = defineCommand({
139
209
  json: z.boolean().default(false).describe('Output as JSON'),
140
210
  comment_limit: z.int().min(0).max(MAX_COMMENT_LIMIT).default(DEFAULT_COMMENT_LIMIT).describe('Number of comments to show (0-20; 0 hides them)'),
141
211
  }),
212
+ output: ISSUE_SHOW_OUTPUT,
142
213
  positional: ['issue_ref'],
143
214
  shortFlags: { json: '-j', comment_limit: '-c' },
144
215
  interactive: false,
@@ -157,11 +228,10 @@ const ISSUE_SHOW = defineCommand({
157
228
  throw error;
158
229
  return stopWith(output, `could not read Issue ${issuePath(owner, repository, number)}: ${error.message}`, kindOfFailure(error));
159
230
  }
160
- const jsonFields = { ...issue, blockedByCount: undefined };
161
231
  const view = await readView(output, client, config, issue, createIssueReference(createRepositoryReference(owner, repository), number));
162
- output.data(input.json
163
- ? JSON.stringify({ ...jsonFields, owner, repo: repository, blockedBy: view.blockedBy, readiness: view.readiness }, undefined, 2)
164
- : formatIssueMarkdown(issue, owner, repository, view));
232
+ const json = issueShowJson(issue, owner, repository, view);
233
+ output.result(json);
234
+ output.data(input.json ? JSON.stringify(json, undefined, 2) : formatIssueMarkdown(issue, owner, repository, view.lines));
165
235
  });
166
236
  },
167
237
  });
@@ -1,5 +1,5 @@
1
1
  /**
2
- 入力名を長いオプションの形にする。`force_overwrite_active` は `--force-overwrite-active`
2
+ 入力名を長いオプションの形にする。`dry_run` は `--dry-run`
3
3
  */
4
4
  export declare function flagOf(name: string): string;
5
5
  /**
@@ -1,6 +1,6 @@
1
1
  // コマンドの名前まわりの小さな関数。help・バインド・定義書の書き出しが同じものを使う。
2
2
  /**
3
- 入力名を長いオプションの形にする。`force_overwrite_active` は `--force-overwrite-active`
3
+ 入力名を長いオプションの形にする。`dry_run` は `--dry-run`
4
4
  */
5
5
  export function flagOf(name) {
6
6
  return `--${name.replaceAll('_', '-')}`;
@@ -20,7 +20,7 @@ export const COMMAND_GROUPS = [
20
20
  { name: 'project', meaning: 'プロジェクトとの接続と設定ファイル。ボードの上の Issue には触らない', help: 'Connect to projects and manage the project config' },
21
21
  { name: 'board', meaning: 'ボードの上の Issue の置き場所。設定ファイルは書かない', help: 'Show the project board and place Issues on it' },
22
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' },
23
+ { name: 'session', meaning: '1 つの Issue の作業の始まりから終わりまで', help: 'Start, show and finish the work on an Issue' },
24
24
  { name: 'pr', meaning: 'PR そのもの', help: 'Work with PRs' },
25
25
  { name: 'release', meaning: 'リリース', help: 'Work with releases' },
26
26
  { name: 'tracker', meaning: 'Tracker の Issue の書き直し', help: 'Rewrite the list in a Tracker Issue' },
@@ -46,11 +46,11 @@ export const COMMAND_VERBS = [
46
46
  { name: 'link', meaning: 'リポジトリをプロジェクトにつなぐ' },
47
47
  { name: 'activate', meaning: '使うプロジェクトを切り替える' },
48
48
  { name: 'start', meaning: '作業を始める' },
49
- { name: 'restore', meaning: '作業の状態を戻す' },
50
49
  { name: 'finish', meaning: '作業を終えて片付ける' },
51
50
  { name: 'sync', meaning: '判定や一覧に合わせて書き直す' },
52
51
  { name: 'move', meaning: 'ボードの列を移す' },
53
52
  { name: 'merge', meaning: 'PR をマージする' },
53
+ { name: 'restack', meaning: '積んだブランチを、base の新しい位置へ載せ直す' },
54
54
  { name: 'comment', meaning: 'コメントを書く' },
55
55
  { name: 'reopen', meaning: '閉じたものを開き直す' },
56
56
  { name: 'block', meaning: '前提を付ける' },
@@ -34,7 +34,14 @@ export interface Operation {
34
34
  */
35
35
  readonly aside?: boolean;
36
36
  }
37
- 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>> {
38
45
  /**
39
46
  dry-run のときだけ、実行する操作を stderr に出す
40
47
  */
@@ -56,8 +63,17 @@ export interface Output {
56
63
  結果の本体を stdout にそのまま出す。末尾に改行が無ければ 1 つ足す
57
64
  */
58
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;
59
71
  }
60
- 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>;
61
77
  /**
62
78
  fd から buffer へ読んだバイト数。0 は終端
63
79
  */
@@ -55,11 +55,19 @@ export function pastOf(verb) {
55
55
  }
56
56
  }
57
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
+ /**
58
66
  末尾の改行を取り除き、2 行目以降の先頭に空白 2 つを付け、末尾に改行を 1 つ付ける
59
67
  */
60
68
  function formatMessage(prefix, message) {
61
69
  const lines = message.replace(/\n+$/, '').split('\n');
62
- return `${prefix}: ${lines.join('\n ')}\n`;
70
+ return `${prefix}${lines.join('\n ')}\n`;
63
71
  }
64
72
  export function createOutput(isDryRun, io) {
65
73
  const render = (message) => formatHinted(message, io.surface ?? 'cli');
@@ -81,10 +89,12 @@ export function createOutput(isDryRun, io) {
81
89
  writeResult(`${pastOf(verb)}: ${target}`, aside);
82
90
  },
83
91
  warning: (message) => {
84
- io.stderr(formatMessage('warning', render(message)));
92
+ const text = render(message);
93
+ io.stderr(formatMessage(WARNING_PREFIX, text));
94
+ io.warning?.(text.replace(/\n+$/, ''));
85
95
  },
86
96
  error: (message) => {
87
- io.stderr(formatMessage('error', render(message)));
97
+ io.stderr(formatMessage('error: ', render(message)));
88
98
  },
89
99
  count: (label, value) => {
90
100
  io.stderr(`count: ${label}: ${value === undefined ? 'unknown' : String(value)}\n`);
@@ -92,6 +102,9 @@ export function createOutput(isDryRun, io) {
92
102
  data: (text) => {
93
103
  io.stdout(text.endsWith('\n') ? text : `${text}\n`);
94
104
  },
105
+ result(fields) {
106
+ io.data?.(isDryRun ? { ...fields, dryRun: true } : fields);
107
+ },
95
108
  };
96
109
  }
97
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,225 @@
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 { GitHubAPIError, GitHubNotFoundError } from '../infra/github/errors.js';
8
+ import { requireActiveConfigPlain, stopWith } from './command-stop.js';
9
+ import { defineCommand } from './command-definition.js';
10
+ import { kindOfFailure } from './failure.js';
11
+ import { createGitHubClient } from './github-client.js';
12
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
13
+ import { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
14
+ // 要求を送らずに止める(ドラフト、閉じている、スタックの最下段でない)
15
+ const NOT_MERGEABLE_EXIT_CODE = 2;
16
+ const POLL_INTERVAL_MILLISECONDS = 2000;
17
+ // R14 では 3〜8 秒で終わった。時刻でなく回数で数え、偽のタイマーでも同じに動かす
18
+ const POLL_LIMIT = 30;
19
+ const POLL_LIMIT_SECONDS = (POLL_INTERVAL_MILLISECONDS * POLL_LIMIT) / 1000;
20
+ // 同期のマージ API が、マージできない(405)・head が sha と違う(409)ときに返す状態コード
21
+ const SYNC_MERGE_REJECTED_STATUSES = new Set([405, 409]);
22
+ const MergeInputSchema = z.strictObject({
23
+ pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
24
+ dry_run: z.boolean().default(false).describe('Read the PR and its stack, and show what would happen without merging'),
25
+ });
26
+ const PR_MERGE_OUTPUT = z.strictObject({
27
+ pullRequest: z.string().describe('PR (owner/repo/N)'),
28
+ base: z.string().describe('Base branch the PR is merged into'),
29
+ status: z.enum(['merged', 'enqueued']).optional().describe('merged, or enqueued when the PR was added to the merge queue (absent on dry_run)'),
30
+ stack: z.strictObject({
31
+ number: z.int().describe('Stack number'),
32
+ size: z.int().describe('Number of PRs in the stack from this PR upward (K of "1 of K")'),
33
+ }).optional().describe('Stack the PR is the bottom of (absent for a PR outside a stack)'),
34
+ dryRun: DRY_RUN_FIELD,
35
+ });
36
+ function pathOf(target) {
37
+ return `${target.owner}/${target.repository}/${String(target.number)}`;
38
+ }
39
+ function stopNotMergeable(out, message) {
40
+ return stopWith(out, message, 'pr-state', NOT_MERGEABLE_EXIT_CODE);
41
+ }
42
+ // 印は残す。w-merge は必須チェックを待って同じ PR に pr_merge を呼び直す
43
+ function stopRejected(out, reason) {
44
+ return stopWith(out, `merge was rejected: ${reason}`, 'pr-state');
45
+ }
46
+ async function readPullRequest(out, client, target) {
47
+ try {
48
+ return await client.getPullRequestForMerge(target.owner, target.repository, target.number);
49
+ }
50
+ catch (error) {
51
+ if (error instanceof GitHubNotFoundError)
52
+ return stopWith(out, `PR not found: ${pathOf(target)}`, 'github-not-found');
53
+ if (!(error instanceof GitHubAPIError))
54
+ throw error;
55
+ return stopWith(out, `could not read PR ${pathOf(target)}: ${describeApiError(error)}`, kindOfFailure(error));
56
+ }
57
+ }
58
+ function checkState(out, name, pullRequest) {
59
+ if (pullRequest.state === 'MERGED')
60
+ stopNotMergeable(out, `${name} is already merged`);
61
+ if (pullRequest.state !== 'OPEN')
62
+ stopNotMergeable(out, `${name} is closed`);
63
+ if (pullRequest.isDraft)
64
+ stopNotMergeable(out, `${name} is a draft`);
65
+ }
66
+ // 下の段に open の PR があれば止める。マージ済みで並びに残る PR は飛ばす。スタックの機能が無いリポは単独の PR として扱う
67
+ async function bottomOfStack(out, client, target) {
68
+ let stack;
69
+ try {
70
+ stack = await client.getStackOfPullRequest(target.owner, target.repository, target.number);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof GitHubNotFoundError)
74
+ return undefined;
75
+ if (!(error instanceof GitHubAPIError))
76
+ throw error;
77
+ return stopWith(out, `could not read the stack of PR ${pathOf(target)}: ${describeApiError(error)}`, kindOfFailure(error));
78
+ }
79
+ if (stack === undefined)
80
+ return undefined;
81
+ const index = stack.pullRequests.indexOf(target.number);
82
+ for (const lower of stack.pullRequests.slice(0, index)) {
83
+ const pullRequest = await readPullRequest(out, client, { ...target, number: lower });
84
+ if (pullRequest.state === 'OPEN') {
85
+ stopNotMergeable(out, `PR #${String(target.number)} is not the bottom of stack #${String(stack.number)}. Merge PR #${String(lower)} first`);
86
+ }
87
+ }
88
+ return { number: stack.number, size: stack.pullRequests.length - index };
89
+ }
90
+ function finishMerged(context) {
91
+ context.out.done({ verb: 'merge', target: `${context.name} into ${context.base}${context.suffix}` });
92
+ context.out.result({ status: 'merged' });
93
+ return 0;
94
+ }
95
+ function finishEnqueued(context) {
96
+ context.out.done({ verb: 'add', target: `${context.name} to merge queue of ${context.base}` });
97
+ context.out.result({ status: 'enqueued' });
98
+ return 0;
99
+ }
100
+ function finishResult(context, result) {
101
+ if (result.status === 'merged')
102
+ return finishMerged(context);
103
+ if (result.status === 'enqueued')
104
+ return finishEnqueued(context);
105
+ return stopRejected(context.out, result.message ?? 'GitHub gave no reason');
106
+ }
107
+ // PR の状態から決める。マージ済みでもキューの中でもなければ undefined
108
+ async function finishIfSettled(context) {
109
+ const pullRequest = await readPullRequest(context.out, context.client, context.target);
110
+ if (pullRequest.state === 'MERGED')
111
+ return finishMerged(context);
112
+ if (pullRequest.isInMergeQueue)
113
+ return finishEnqueued(context);
114
+ return undefined;
115
+ }
116
+ function stopUnconfirmed(context) {
117
+ return stopWith(context.out, `could not confirm the merge of ${context.name}: it is neither merged nor in the merge queue`, 'pr-state');
118
+ }
119
+ async function finishFromState(context) {
120
+ return await finishIfSettled(context) ?? stopUnconfirmed(context);
121
+ }
122
+ // 結果の 404 は、消えた結果のほか、書いた直後の読み取りの遅れでも返る。そのときは期限まで読み直す
123
+ async function pollResult(context, uuid) {
124
+ const { owner, repository, number } = context.target;
125
+ let isResultMissing = false;
126
+ for (let attempt = 0; attempt < POLL_LIMIT; attempt += 1) {
127
+ await delay(POLL_INTERVAL_MILLISECONDS);
128
+ let result;
129
+ try {
130
+ result = await context.client.getAsyncMergeResult(owner, repository, number, uuid);
131
+ }
132
+ catch (error) {
133
+ if (!(error instanceof GitHubAPIError))
134
+ throw error;
135
+ return stopWith(context.out, `could not read the merge result of PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
136
+ }
137
+ if (result === undefined) {
138
+ isResultMissing = true;
139
+ const settled = await finishIfSettled(context);
140
+ if (settled !== undefined)
141
+ return settled;
142
+ continue;
143
+ }
144
+ isResultMissing = false;
145
+ if (result.status !== 'pending')
146
+ return finishResult(context, result);
147
+ }
148
+ return isResultMissing
149
+ ? stopUnconfirmed(context)
150
+ : stopWith(context.out, `merge did not finish in ${String(POLL_LIMIT_SECONDS)}s. Check ${context.name}`, 'github-api');
151
+ }
152
+ function reasonOf(error) {
153
+ const message = jsonField(tryParseJsonText(error.responseBody ?? ''), 'message');
154
+ return typeof message === 'string' && message !== '' ? message : describeApiError(error);
155
+ }
156
+ // merge-async の無い GHES 向け。sha を渡し、読んだ後に push された PR をマージしない
157
+ async function mergeSynchronously(context, pullRequest) {
158
+ const { owner, repository, number } = context.target;
159
+ try {
160
+ await context.client.mergePullRequest(owner, repository, number, 'squash', pullRequest.headRefOid);
161
+ }
162
+ catch (error) {
163
+ if (!(error instanceof GitHubAPIError))
164
+ throw error;
165
+ return error.statusCode !== undefined && SYNC_MERGE_REJECTED_STATUSES.has(error.statusCode)
166
+ ? stopRejected(context.out, reasonOf(error))
167
+ : stopWith(context.out, `could not merge PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
168
+ }
169
+ return finishMerged(context);
170
+ }
171
+ async function requestMerge(context, pullRequest) {
172
+ const { owner, repository, number } = context.target;
173
+ let requested;
174
+ try {
175
+ requested = await context.client.requestAsyncMerge(owner, repository, number, { sha: pullRequest.headRefOid, mergeQueue: pullRequest.isMergeQueueEnabled });
176
+ }
177
+ catch (error) {
178
+ if (!(error instanceof GitHubAPIError))
179
+ throw error;
180
+ // 同期の API はスタックの PR を 403 で拒むので、スタックの中では戻さない
181
+ return error instanceof GitHubNotFoundError && !context.isInStack
182
+ ? mergeSynchronously(context, pullRequest)
183
+ : stopWith(context.out, `could not merge PR ${pathOf(context.target)}: ${describeApiError(error)}`, kindOfFailure(error));
184
+ }
185
+ switch (requested.outcome) {
186
+ case 'rejected': {
187
+ return stopRejected(context.out, requested.message);
188
+ }
189
+ // 文書は 409 の本文の形を示していない。uuid が無ければ PR の状態から決める
190
+ case 'conflict': {
191
+ return requested.uuid === undefined ? finishFromState(context) : pollResult(context, requested.uuid);
192
+ }
193
+ case 'accepted': {
194
+ const { result } = requested;
195
+ return result.status === 'pending' && result.uuid !== undefined ? pollResult(context, result.uuid) : finishResult(context, result);
196
+ }
197
+ }
198
+ }
199
+ export const PR_MERGE_COMMAND = defineCommand({
200
+ path: ['pr', 'merge'],
201
+ description: 'Merge a PR with the asynchronous merge API (a PR in a stack must be the bottom one)',
202
+ input: MergeInputSchema,
203
+ output: PR_MERGE_OUTPUT,
204
+ positional: ['pr_ref'],
205
+ shortFlags: { dry_run: '-n' },
206
+ interactive: false,
207
+ run: async (input, io) => {
208
+ const out = createOutput(input.dry_run, io);
209
+ const config = requireActiveConfigPlain(out);
210
+ const target = parseReference(input.pr_ref, input.repo, out);
211
+ const client = createGitHubClient(out, config.host);
212
+ const name = `PR #${String(target.number)}`;
213
+ const pullRequest = await readPullRequest(out, client, target);
214
+ checkState(out, name, pullRequest);
215
+ const stack = await bottomOfStack(out, client, target);
216
+ out.result({ pullRequest: pathOf(target), base: pullRequest.baseRefName, ...stack !== undefined && { stack } });
217
+ const suffix = stack === undefined ? '' : ` (stack #${String(stack.number)}, 1 of ${String(stack.size)})`;
218
+ if (input.dry_run) {
219
+ out.planned({ verb: 'merge', target: `${name} into ${pullRequest.baseRefName}${suffix}` });
220
+ return 0;
221
+ }
222
+ return requestMerge({ out, client, target, name, base: pullRequest.baseRefName, suffix, isInStack: stack !== undefined }, pullRequest);
223
+ },
224
+ });
225
+ //# 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