@pecot/workflow-mcp 5.0.0 → 6.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 (176) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +80 -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 +59 -0
  6. package/cli/dist/commands/board-judgment.d.ts +60 -0
  7. package/cli/dist/commands/board-judgment.js +144 -0
  8. package/cli/dist/commands/board-move.d.ts +3 -0
  9. package/cli/dist/commands/board-move.js +57 -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 +72 -0
  14. package/cli/dist/commands/board-sync.d.ts +3 -0
  15. package/cli/dist/commands/board-sync.js +111 -0
  16. package/cli/dist/commands/{project-info.d.ts → board-view.d.ts} +21 -7
  17. package/cli/dist/commands/{project-info.js → board-view.js} +22 -12
  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 +100 -0
  22. package/cli/dist/commands/command-binding.js +4 -0
  23. package/cli/dist/commands/command-definition.d.ts +20 -6
  24. package/cli/dist/commands/command-definition.js +11 -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 +34 -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 +33 -0
  38. package/cli/dist/commands/issue-board.js +61 -1
  39. package/cli/dist/commands/issue-comment.js +47 -28
  40. package/cli/dist/commands/issue-create.js +548 -91
  41. package/cli/dist/commands/issue-dependency.d.ts +3 -0
  42. package/cli/dist/commands/issue-dependency.js +282 -0
  43. package/cli/dist/commands/issue-readiness.d.ts +94 -0
  44. package/cli/dist/commands/issue-readiness.js +218 -0
  45. package/cli/dist/commands/issue-reopen.d.ts +3 -0
  46. package/cli/dist/commands/issue-reopen.js +115 -0
  47. package/cli/dist/commands/issue-shared.d.ts +32 -19
  48. package/cli/dist/commands/issue-shared.js +82 -75
  49. package/cli/dist/commands/issue-show.d.ts +3 -0
  50. package/cli/dist/commands/issue-show.js +169 -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 +62 -0
  55. package/cli/dist/commands/output.d.ts +14 -2
  56. package/cli/dist/commands/output.js +14 -7
  57. package/cli/dist/commands/pr-waiting.d.ts +20 -0
  58. package/cli/dist/commands/pr-waiting.js +106 -0
  59. package/cli/dist/commands/pr.d.ts +19 -0
  60. package/cli/dist/commands/pr.js +242 -323
  61. package/cli/dist/commands/project-sync.d.ts +2 -1
  62. package/cli/dist/commands/project-sync.js +18 -9
  63. package/cli/dist/commands/project.d.ts +3 -2
  64. package/cli/dist/commands/project.js +212 -175
  65. package/cli/dist/commands/registry.js +13 -10
  66. package/cli/dist/commands/release.d.ts +2 -2
  67. package/cli/dist/commands/release.js +53 -114
  68. package/cli/dist/commands/renamed-commands.d.ts +26 -0
  69. package/cli/dist/commands/renamed-commands.js +53 -0
  70. package/cli/dist/commands/repository-match.js +3 -2
  71. package/cli/dist/commands/session-finish.d.ts +3 -0
  72. package/cli/dist/commands/session-finish.js +267 -0
  73. package/cli/dist/commands/session-start.d.ts +3 -0
  74. package/cli/dist/commands/{repository.js → session-start.js} +99 -128
  75. package/cli/dist/commands/session.d.ts +3 -0
  76. package/cli/dist/commands/session.js +82 -29
  77. package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
  78. package/cli/dist/commands/{dependabot.js → tracker-sync-dependabot.js} +57 -66
  79. package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
  80. package/cli/dist/commands/{security.js → tracker-sync-security.js} +50 -61
  81. package/cli/dist/commands/tracker-sync.d.ts +7 -0
  82. package/cli/dist/commands/tracker-sync.js +3 -6
  83. package/cli/dist/commands/tracker.d.ts +3 -0
  84. package/cli/dist/commands/tracker.js +18 -0
  85. package/cli/dist/commands/usage-error.d.ts +4 -0
  86. package/cli/dist/commands/usage-error.js +6 -0
  87. package/cli/dist/commands/work-target.d.ts +12 -3
  88. package/cli/dist/commands/work-target.js +46 -5
  89. package/cli/dist/commands/worktree.js +32 -28
  90. package/cli/dist/domain/batch-plan.d.ts +73 -0
  91. package/cli/dist/domain/batch-plan.js +114 -0
  92. package/cli/dist/domain/blocked-by-change.d.ts +99 -0
  93. package/cli/dist/domain/blocked-by-change.js +101 -0
  94. package/cli/dist/domain/board-move.d.ts +90 -0
  95. package/cli/dist/domain/board-move.js +92 -0
  96. package/cli/dist/domain/branch-name.js +1 -1
  97. package/cli/dist/domain/command-hint.d.ts +85 -0
  98. package/cli/dist/domain/command-hint.js +148 -0
  99. package/cli/dist/domain/config.d.ts +4 -0
  100. package/cli/dist/domain/config.js +11 -1
  101. package/cli/dist/domain/dependabot.js +1 -1
  102. package/cli/dist/domain/errors.d.ts +5 -0
  103. package/cli/dist/domain/errors.js +5 -0
  104. package/cli/dist/domain/format.d.ts +51 -4
  105. package/cli/dist/domain/format.js +72 -6
  106. package/cli/dist/domain/frontmatter.d.ts +18 -3
  107. package/cli/dist/domain/frontmatter.js +38 -12
  108. package/cli/dist/domain/issue-order.d.ts +55 -0
  109. package/cli/dist/domain/issue-order.js +65 -0
  110. package/cli/dist/domain/issue-readout.d.ts +36 -0
  111. package/cli/dist/domain/pull-request.d.ts +71 -4
  112. package/cli/dist/domain/pull-request.js +59 -10
  113. package/cli/dist/domain/readiness.d.ts +27 -0
  114. package/cli/dist/domain/readiness.js +114 -3
  115. package/cli/dist/domain/reference-parser.d.ts +3 -1
  116. package/cli/dist/domain/reference-parser.js +6 -2
  117. package/cli/dist/domain/release.d.ts +7 -3
  118. package/cli/dist/domain/release.js +5 -12
  119. package/cli/dist/domain/repository-policy.d.ts +9 -3
  120. package/cli/dist/domain/repository-policy.js +8 -7
  121. package/cli/dist/domain/repository-resolver.js +4 -1
  122. package/cli/dist/domain/security-alerts.js +1 -1
  123. package/cli/dist/domain/state.d.ts +30 -0
  124. package/cli/dist/domain/state.js +39 -0
  125. package/cli/dist/domain/work-start.d.ts +34 -0
  126. package/cli/dist/domain/work-start.js +49 -0
  127. package/cli/dist/infra/authored-notes.d.ts +1 -1
  128. package/cli/dist/infra/authored-notes.js +10 -4
  129. package/cli/dist/infra/config-store.d.ts +4 -0
  130. package/cli/dist/infra/config-store.js +13 -0
  131. package/cli/dist/infra/git.d.ts +12 -0
  132. package/cli/dist/infra/git.js +13 -1
  133. package/cli/dist/infra/github/client.d.ts +5 -0
  134. package/cli/dist/infra/github/client.js +10 -7
  135. package/cli/dist/infra/github/errors.d.ts +18 -0
  136. package/cli/dist/infra/github/errors.js +22 -0
  137. package/cli/dist/infra/github/issues.d.ts +39 -3
  138. package/cli/dist/infra/github/issues.js +178 -23
  139. package/cli/dist/infra/github/projects.d.ts +35 -0
  140. package/cli/dist/infra/github/projects.js +89 -8
  141. package/cli/dist/infra/github/pulls.d.ts +24 -0
  142. package/cli/dist/infra/github/pulls.js +56 -0
  143. package/cli/dist/infra/github/queries.d.ts +12 -4
  144. package/cli/dist/infra/github/queries.js +156 -8
  145. package/cli/dist/infra/github/readout.d.ts +5 -1
  146. package/cli/dist/infra/github/readout.js +11 -0
  147. package/cli/dist/infra/github/repos.d.ts +18 -0
  148. package/cli/dist/infra/github/repos.js +31 -0
  149. package/cli/dist/infra/nx-scope.d.ts +1 -1
  150. package/cli/dist/infra/nx-scope.js +1 -1
  151. package/cli/dist/infra/state-store.d.ts +10 -1
  152. package/cli/dist/infra/state-store.js +14 -2
  153. package/cli/dist/infra/worktree-links.d.ts +3 -0
  154. package/cli/dist/infra/worktree-links.js +8 -1
  155. package/cli/dist/infra/worktree.d.ts +12 -1
  156. package/cli/dist/infra/worktree.js +40 -23
  157. package/cli/dist/mcp/result.d.ts +34 -6
  158. package/cli/dist/mcp/result.js +62 -18
  159. package/cli/dist/mcp/server.d.ts +2 -2
  160. package/cli/dist/mcp/server.js +24 -10
  161. package/cli/templates/comment/plan.md +14 -0
  162. package/cli/templates/issue/bug.md +1 -1
  163. package/cli/templates/issue/task-implement.md +13 -6
  164. package/cli/templates/issue/task.md +1 -1
  165. package/cli/templates/workflow/pecot-board-sync.yml +84 -0
  166. package/npm-shrinkwrap.json +2 -2
  167. package/package.json +1 -1
  168. package/cli/dist/commands/dependabot.d.ts +0 -3
  169. package/cli/dist/commands/issue-project.d.ts +0 -3
  170. package/cli/dist/commands/issue-project.js +0 -176
  171. package/cli/dist/commands/issue-quick.d.ts +0 -3
  172. package/cli/dist/commands/issue-quick.js +0 -126
  173. package/cli/dist/commands/issue-read.d.ts +0 -3
  174. package/cli/dist/commands/issue-read.js +0 -80
  175. package/cli/dist/commands/repository.d.ts +0 -5
  176. package/cli/dist/commands/security.d.ts +0 -3
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable security/detect-non-literal-fs-filename -- パスは利用者が指定する */
2
2
  /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は内部の状態を持つ */
3
- // `pecot pr` の 4 コマンド(create・read・preflight・cleanup)。cli/commands/pr.py の移植。
3
+ // pr create・pr show・pr check。cli/commands/pr.py の移植。
4
4
  // 途中で抜ける箇所は CommandExit を投げ、defineCommand が終了コードにする。
5
5
  import { existsSync, statSync, writeFileSync } from 'node:fs';
6
6
  import path from 'node:path';
@@ -13,44 +13,50 @@ import { FrontmatterError } from '../domain/frontmatter.js';
13
13
  import { parseRemoteUrl } from '../domain/git-url.js';
14
14
  import { isEpicIssue } from '../domain/issue-kind.js';
15
15
  import { jsonField } from '../domain/json.js';
16
- import { appendIssueCloseIfNeeded, collectPreflightWarnings, describePushStatus, extractClosingIssueNumbers, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, validatePullRequestContent, } from '../domain/pull-request.js';
16
+ import { appendIssueCloseIfNeeded, collectPreflightWarnings, decidePullRequestBase, describeBaseStop, describePushStatus, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, pickLowerPullRequest, validatePullRequestContent } from '../domain/pull-request.js';
17
17
  import { parsePythonInteger, pythonStrip } from '../domain/python-format.js';
18
18
  import { ReferenceParseError, parsePullRequestReference } from '../domain/reference-parser.js';
19
19
  import { AmbiguousRepositoryError, resolveRepository, splitOwnerRepository } from '../domain/repository-resolver.js';
20
- import { FLAG_MERGE_SLASH_PENDING, FLAG_PECOT_ACTIVE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE, FLAG_PR_CREATE_SLASH_PENDING, FLAG_WIP_BRANCH_LINKED } from '../domain/state.js';
20
+ import { FLAG_PECOT_ACTIVE, FLAG_PR_CREATE_SLASH_PENDING } from '../domain/state.js';
21
21
  import { loadActiveConfig } from '../infra/config-store.js';
22
22
  import { parsePullRequestFile } from '../infra/frontmatter-file.js';
23
- import { gitCurrentBranch, GitCommandError, gitRemoteUrl, gitRunnerFor, gitStdout, gitToplevel, primaryRemoteName, runGit } from '../infra/git.js';
24
- import { GitHubAPIError, GitHubNotFoundError, isClosedByAnotherRequest, isMissingReferenceError } from '../infra/github/errors.js';
23
+ import { gitCurrentBranch, gitRemoteUrl, gitRunnerFor, gitStdout, gitToplevel, primaryRemoteName, runGit } from '../infra/git.js';
24
+ import { TransportFailure } from '../infra/github/client.js';
25
+ import { GitHubAPIError } from '../infra/github/errors.js';
25
26
  import { changedFiles, expectedScope, nxProjects, parseTitleScope } from '../infra/nx-scope.js';
26
27
  import { isFileNotFound } from '../infra/os-error.js';
27
28
  import { outputDirectory, OutputPathReservationError, resolveRealPath, withReservedOutputPath } from '../infra/paths.js';
28
- import { consumeFlag, readFlag, removeFlag } from '../infra/state-store.js';
29
+ import { consumeFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
29
30
  import { readTemplateSections, templateFile } from '../infra/template-store.js';
30
31
  import { readTextFile } from '../infra/text-file.js';
31
- import { getCurrentWorktreeName, isWorktreeEnvironment } from '../infra/worktree.js';
32
+ import { commandHint, hinted, inputHint, inputNameHint, placeholder } from './command-hint.js';
32
33
  import { requireActiveConfigPlain, stopWith } from './command-stop.js';
34
+ import { kindOfFailure } from './failure.js';
33
35
  import { USAGE_EXIT_CODE } from './usage-error.js';
34
36
  import { directorySchema } from './directory-option.js';
35
37
  import { createGitHubClient } from './github-client.js';
36
38
  import { createOutput } from './output.js';
37
39
  import { CommandExit, defineCommand } from './command-definition.js';
38
- import { settle } from './tracker-sync.js';
39
- 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)';
40
+ import { moveWaitingIssues } from './pr-waiting.js';
41
+ 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)';
40
42
  // 本文の検証の失敗。1(通信・設定・引数)と 2(preflight)と区別する
41
43
  const VALIDATION_EXIT_CODE = 3;
42
44
  const PREFLIGHT_EXIT_CODE = 2;
45
+ // 下の段の PR が開いておらず、マージもされていない
46
+ const NO_OPEN_BASE_EXIT_CODE = 2;
47
+ // git ls-remote --exit-code が、一致する参照が無いときに返す
48
+ const LS_REMOTE_NOT_FOUND = 2;
43
49
  // Python の `{e}` に当たる、例外の文
44
- function reasonOf(error) {
50
+ export function reasonOf(error) {
45
51
  return error instanceof Error ? error.message : String(error);
46
52
  }
47
53
  function templateKindOf(template) {
48
54
  return template === 'release' ? 'release' : 'create';
49
55
  }
50
- function isPositive(value) {
56
+ export function isPositive(value) {
51
57
  return value !== undefined && value !== 0;
52
58
  }
53
- function primaryRemote(directory) {
59
+ export function primaryRemote(directory) {
54
60
  const name = primaryRemoteName(directory);
55
61
  if (name === undefined)
56
62
  return undefined;
@@ -66,10 +72,11 @@ function primaryRemote(directory) {
66
72
  throw error;
67
73
  }
68
74
  }
69
- // scope を nx のプロジェクトと比べる対象か。release_type が nx、base が develop、remote と作業ツリーが対象に合うときだけ
70
- function nxScopeTarget(config, owner, repository, base, directory) {
75
+ // scope を nx のプロジェクトと比べる対象か。release_type が nx で、base が develop か積んだ base で、remote と作業ツリーが対象に合うときだけ。
76
+ // 下の段を squash でマージした後は、開発ブランチとの差分がその段のファイルも含むので、記録のコミットから比べる
77
+ function nxScopeTarget(config, owner, repository, base, directory, stacked) {
71
78
  const configured = findRepository(config, owner, repository);
72
- if (configured === undefined || effectiveReleaseType(configured) !== 'nx' || (base !== getDevelopBranch(config, owner, repository)))
79
+ if (configured === undefined || effectiveReleaseType(configured) !== 'nx' || (stacked === undefined && base !== getDevelopBranch(config, owner, repository)))
73
80
  return undefined;
74
81
  const found = primaryRemote(directory);
75
82
  const location = found?.location;
@@ -77,7 +84,11 @@ function nxScopeTarget(config, owner, repository, base, directory) {
77
84
  if (found === undefined || !isSameRepository)
78
85
  return undefined;
79
86
  const toplevel = gitToplevel({ cwd: directory });
80
- return toplevel === undefined || !isRegularFile(path.join(toplevel, 'nx.json')) ? undefined : { toplevel, remote: found.name };
87
+ if (toplevel === undefined || !isRegularFile(path.join(toplevel, 'nx.json')))
88
+ return undefined;
89
+ if (stacked === undefined)
90
+ return { toplevel, from: `${found.name}/${base}` };
91
+ return { toplevel, from: 'sha' in stacked ? stacked.sha : `${found.name}/${stacked.branch}` };
81
92
  }
82
93
  // Python の Path.is_file() と同じく、stat の失敗は「無い」と扱う
83
94
  function isRegularFile(file) {
@@ -88,9 +99,9 @@ function isRegularFile(file) {
88
99
  return false;
89
100
  }
90
101
  }
91
- function expectedTitleScope(target, base, head, out) {
102
+ function expectedTitleScope(target, head, out) {
92
103
  const projects = nxProjects(target.toplevel);
93
- const files = projects === undefined ? undefined : changedFiles(target.toplevel, `${target.remote}/${base}`, head);
104
+ const files = projects === undefined ? undefined : changedFiles(target.toplevel, target.from, head);
94
105
  if (projects === undefined || files === undefined) {
95
106
  out.warning('cannot read nx projects or the diff; skipped the PR title scope check');
96
107
  return undefined;
@@ -101,10 +112,10 @@ function titleScopeErrors(query, out) {
101
112
  const { config, owner, repository, title, base, head, directory, template, developBranch, releaseBranch } = query;
102
113
  if (isReleasePullRequest(template, base, head, developBranch, releaseBranch))
103
114
  return [];
104
- const target = nxScopeTarget(config, owner, repository, base, directory);
115
+ const target = nxScopeTarget(config, owner, repository, base, directory, query.stacked);
105
116
  if (target === undefined)
106
117
  return [];
107
- const expected = expectedTitleScope(target, base, head, out);
118
+ const expected = expectedTitleScope(target, head, out);
108
119
  if (expected === undefined || expected.length === 0)
109
120
  return [];
110
121
  const given = parseTitleScope(title);
@@ -153,20 +164,22 @@ async function updateIssueStatusToInReview(config, client, location, headBranch,
153
164
  }
154
165
  out.done(inReviewOperation(issueNumber));
155
166
  }
167
+ const LINK_PATH = ['project', 'link'];
168
+ const PR_CREATE_PATH = ['pr', 'create'];
156
169
  function exitOnUnsetBranch(template, base, head, developBranch, releaseBranch, out) {
157
170
  const isRelease = isReleasePullRequest(template, base, head, developBranch, releaseBranch);
158
171
  if (isRelease && (releaseBranch === undefined || releaseBranch === '')) {
159
- stopWith(out, 'release_branch is not set\nset it with: pecot project set-repo owner/repo --release-branch main');
172
+ stopWith(out, hinted `release_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', release_branch: 'main' })}`, 'repo-setting-missing');
160
173
  }
161
174
  if (!isRelease && (developBranch === undefined || developBranch === '')) {
162
- stopWith(out, 'develop_branch is not set\nset it with: pecot project set-repo owner/repo --develop-branch develop');
175
+ stopWith(out, hinted `develop_branch is not set\nset it with: ${commandHint(LINK_PATH, { repo: 'owner/repo', develop_branch: 'develop' })}`, 'repo-setting-missing');
163
176
  }
164
177
  }
165
178
  function resolveHeadBranch(head, directory, out) {
166
179
  if (head !== undefined && head !== '')
167
180
  return head;
168
181
  const current = gitCurrentBranch(directory);
169
- return current === undefined || current === '' ? stopWith(out, 'cannot determine the head branch') : current;
182
+ return current === undefined || current === '' ? stopWith(out, 'cannot determine the head branch', 'git-unresolved') : current;
170
183
  }
171
184
  async function appendCloseUnlessEpic(config, location, body, issueNumber, out) {
172
185
  try {
@@ -187,7 +200,7 @@ function exitOnValidationErrors(errors, out) {
187
200
  return;
188
201
  for (const error of errors)
189
202
  out.error(error);
190
- throw new CommandExit(VALIDATION_EXIT_CODE);
203
+ throw new CommandExit(VALIDATION_EXIT_CODE, 'content-invalid');
191
204
  }
192
205
  function createOperation(draft) {
193
206
  const kind = draft.isDraft ? 'draft PR' : 'PR';
@@ -224,18 +237,18 @@ function getPushStatus(branch, cwd, remote) {
224
237
  const behindCount = behind === undefined ? undefined : parsePythonInteger(pythonStrip(behind));
225
238
  return aheadCount === undefined || behindCount === undefined ? failed : describePushStatus(remote, branch, aheadCount, behindCount);
226
239
  }
227
- // pr create の早い確認と pr preflight が共有する前提。満たさなければ終了コード 1
240
+ // pr create の早い確認と pr check が共有する前提。満たさなければ終了コード 1
228
241
  function validatePullRequestContext(directory, out) {
229
242
  if (gitToplevel({ cwd: directory }) === undefined)
230
- stopWith(out, 'not a git repository');
243
+ stopWith(out, 'not a git repository', 'git-unresolved');
231
244
  const found = primaryRemote(directory);
232
245
  if (found === undefined)
233
- return stopWith(out, 'git remote not found');
246
+ return stopWith(out, 'git remote not found', 'git-unresolved');
234
247
  const currentBranch = gitCurrentBranch(directory);
235
248
  if (currentBranch === undefined)
236
- return stopWith(out, 'cannot determine the current branch');
249
+ return stopWith(out, 'cannot determine the current branch', 'git-unresolved');
237
250
  if (found.location === undefined)
238
- return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v');
251
+ return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v', 'git-unresolved');
239
252
  return { remoteUrl: found.url, currentBranch, location: found.location, remoteName: found.name };
240
253
  }
241
254
  function runPreflightChecksOrExit(directory, out) {
@@ -246,35 +259,153 @@ function runPreflightChecksOrExit(directory, out) {
246
259
  return;
247
260
  out.error('preflight found warnings; fix them before creating a PR');
248
261
  printPreflightWarnings(out, warnings);
249
- throw new CommandExit(PREFLIGHT_EXIT_CODE);
262
+ throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
263
+ }
264
+ // PR を作った後の処理の失敗は warning にとどめ、URL の出力まで進める
265
+ function isRequestFailure(error) {
266
+ return error instanceof GitHubAPIError || error instanceof TransportFailure;
267
+ }
268
+ function describeRequestFailure(error) {
269
+ return error instanceof GitHubAPIError ? describeApiError(error) : error.message;
270
+ }
271
+ // 1 回の pr create で、クライアントを作るのは要るときの 1 回だけにする
272
+ function lazyClient(config, out) {
273
+ let client;
274
+ return () => {
275
+ client ??= createGitHubClient(out, config.host);
276
+ return client;
277
+ };
278
+ }
279
+ // 下の段の PR が入っているスタックに足す。無ければ下の段と新しい PR で作る。失敗は warning にとどめる
280
+ async function registerStack(client, location, lower, created, out) {
281
+ if (created === undefined) {
282
+ out.warning('could not register stack: the PR creation response has no PR number');
283
+ return;
284
+ }
285
+ try {
286
+ const stack = await client.getStackOfPullRequest(location.owner, location.repository, lower);
287
+ const top = stack?.pullRequests.at(-1);
288
+ // GitHub は一番上にしか足せないので、同じ下の段に 2 つ目を積んだときは 422 を待たずに知らせる
289
+ if (stack !== undefined && top !== lower) {
290
+ out.warning(`could not register stack: PR #${String(lower)} is not the top of stack #${String(stack.number)} (top: PR #${String(top)}); PR #${String(created)} was not added`);
291
+ return;
292
+ }
293
+ const registered = stack === undefined
294
+ ? await client.createStack(location.owner, location.repository, [lower, created])
295
+ : await client.addToStack(location.owner, location.repository, stack.number, [created]);
296
+ out.done({ verb: 'add', target: `PR #${String(created)} to stack #${String(registered.number)}` });
297
+ }
298
+ catch (error) {
299
+ if (!isRequestFailure(error))
300
+ throw error;
301
+ out.warning(`could not register stack: ${describeRequestFailure(error)}`);
302
+ }
303
+ }
304
+ async function moveWaitingIssuesSafely(client, config, location, issueNumber, pullRequest, out) {
305
+ try {
306
+ await moveWaitingIssues(out, client, config, { repository: location, issueNumber, pullRequest });
307
+ }
308
+ catch (error) {
309
+ if (!isRequestFailure(error))
310
+ throw error;
311
+ out.warning(`could not move the Issues waiting for #${String(issueNumber)}: ${describeRequestFailure(error)}`);
312
+ }
250
313
  }
251
- async function submitPullRequest(config, directory, draft, out) {
314
+ async function submitPullRequest(config, client, directory, draft, stackOn, out) {
252
315
  runPreflightChecksOrExit(directory, out);
253
- const client = createGitHubClient(out, config.host);
254
316
  let created;
255
317
  try {
256
- created = await client.createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
318
+ created = await client().createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
257
319
  }
258
320
  catch (error) {
259
321
  if (error instanceof GitHubAPIError)
260
- return stopWith(out, `PR creation failed: ${error.message}`);
322
+ return stopWith(out, `PR creation failed: ${error.message}`, kindOfFailure(error));
261
323
  throw error;
262
324
  }
263
325
  out.done(createOperation(draft));
326
+ const createdNumber = jsonField(created, 'number');
327
+ const pullRequest = typeof createdNumber === 'number' ? createdNumber : undefined;
264
328
  if (!draft.isRelease)
265
- await updateIssueStatusToInReview(config, client, draft.location, draft.head, out);
329
+ await updateIssueStatusToInReview(config, client(), draft.location, draft.head, out);
330
+ if (stackOn !== undefined)
331
+ await registerStack(client(), draft.location, stackOn, pullRequest, out);
332
+ const issueNumber = extractIssueNumberFromBranch(draft.head);
333
+ if (!draft.isRelease && isPositive(issueNumber))
334
+ await moveWaitingIssuesSafely(client(), config, draft.location, issueNumber, pullRequest, out);
266
335
  consumeFlag(FLAG_PR_CREATE_SLASH_PENDING);
267
336
  const url = jsonField(created, 'html_url');
268
337
  if (typeof url !== 'string')
269
- return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub');
338
+ return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub', 'other');
270
339
  out.data(url);
271
340
  }
341
+ function stopOnMalformedRecord(reading, out) {
342
+ if (reading.kind === 'malformed')
343
+ stopWith(out, describeBaseStop({ kind: 'stop', reason: 'malformed', content: reading.content }).join('\n'), 'content-invalid');
344
+ }
345
+ // merge-base --is-ancestor は、祖先でなければ 1、コミットを知らなければ 128 を返す
346
+ const NOT_ANCESTOR = 1;
347
+ // 記録を使うのは、head が今のブランチで、release のテンプレートでないときだけ。形が誤っていれば終了コード 1 で止める。
348
+ // 記録のコミットが head の履歴に無ければ、別のブランチの記録なので止める。開発ブランチ向けに作ると下の段の差分が入りうるため
349
+ function readBaseRecordFor(head, template, directory, out) {
350
+ if (template === 'release' || head !== gitCurrentBranch(directory))
351
+ return undefined;
352
+ const reading = readBaseRecord();
353
+ stopOnMalformedRecord(reading, out);
354
+ if (reading.kind !== 'stacked')
355
+ return reading;
356
+ const { branch, sha } = reading.record;
357
+ const isForeign = runGit(['merge-base', '--is-ancestor', sha, head], { cwd: directory }).exitCode === NOT_ANCESTOR;
358
+ return isForeign
359
+ ? stopWith(out, hinted `.pecot-base records ${branch} at ${sha.slice(0, 7)}, which is not in the history of ${head}\nrun pr create on the branch the record was written for, or pass ${inputHint(PR_CREATE_PATH, 'head', head)} to create the PR without the record`, 'git-unresolved')
360
+ : reading;
361
+ }
362
+ // 積んだ記録なら、PR を作るリポで下の段の PR を読み、base を決める
363
+ async function decideBase(input, client, developBranch, out) {
364
+ const { reading, base, location } = input;
365
+ if (reading === undefined)
366
+ return { kind: 'use', base, stackOn: undefined, stackedBase: undefined, isLowerMerged: false };
367
+ if (reading.kind !== 'stacked')
368
+ return decidePullRequestBase({ reading, base, developBranch });
369
+ const { branch } = reading.record;
370
+ try {
371
+ const found = await client().listPullRequestsByHead(location.owner, location.repository, branch);
372
+ return decidePullRequestBase({ reading, base, developBranch, lowerPullRequest: pickLowerPullRequest(found.pullRequests) });
373
+ }
374
+ catch (error) {
375
+ if (error instanceof GitHubAPIError)
376
+ return stopWith(out, `cannot read the PR of the base branch ${branch}: ${describeApiError(error)}`, kindOfFailure(error));
377
+ throw error;
378
+ }
379
+ }
380
+ // 下の段の PR が開いているのに開発ブランチを渡したときは、内容の検証の失敗と一緒に出す(終了コード 3)
381
+ function useOrStop(decision, out) {
382
+ if (decision.kind === 'use')
383
+ return { use: decision, errors: [] };
384
+ const lines = describeBaseStop(decision);
385
+ if (decision.reason === 'lower-open')
386
+ return { use: undefined, errors: lines };
387
+ if (decision.reason === 'malformed')
388
+ return stopWith(out, lines.join('\n'), 'content-invalid');
389
+ return stopWith(out, lines.join('\n'), 'pr-state', NO_OPEN_BASE_EXIT_CODE);
390
+ }
391
+ // 下の段がマージ済みなら記録のコミットから、開いていてそのブランチへ作るならそのブランチから、題の scope を比べる
392
+ function stackedScopeOf(reading, use) {
393
+ if (use === undefined || reading?.kind !== 'stacked')
394
+ return undefined;
395
+ if (use.isLowerMerged)
396
+ return { sha: reading.record.sha };
397
+ return use.stackOn === undefined ? undefined : { branch: reading.record.branch };
398
+ }
272
399
  // 検証して、dry-run なら計画を出し、そうでなければ投稿する。file と -m の両方がここを通る
273
400
  async function validateAndSubmit(input, out) {
274
- const { config, directory, template, location, title, base, head } = input;
401
+ const { config, directory, template, location, title, head } = input;
402
+ const client = lazyClient(config, out);
275
403
  const developBranch = getDevelopBranch(config, location.owner, location.repository);
276
404
  const releaseBranch = getReleaseBranch(config, location.owner, location.repository);
277
- exitOnUnsetBranch(template, base, head, developBranch, releaseBranch, out);
405
+ exitOnUnsetBranch(template, input.base, head, developBranch, releaseBranch, out);
406
+ const { use, errors: baseErrors } = useOrStop(await decideBase(input, client, developBranch ?? '', out), out);
407
+ const base = use?.base ?? input.base;
408
+ const stacked = stackedScopeOf(input.reading, use);
278
409
  const requiredSections = readTemplateSections(templateFile('pr', templateKindOf(template)));
279
410
  const errors = [
280
411
  ...validatePullRequestContent({
@@ -287,23 +418,27 @@ async function validateAndSubmit(input, out) {
287
418
  skipIssueReferenceCheck: input.noIssueRef,
288
419
  screenshot: input.screenshot,
289
420
  requiredSections,
421
+ stackedBase: use?.stackedBase,
290
422
  }),
291
- ...titleScopeErrors({ config, owner: location.owner, repository: location.repository, title, base, head, directory, template, developBranch, releaseBranch }, out),
423
+ ...baseErrors,
424
+ ...titleScopeErrors({ config, owner: location.owner, repository: location.repository, title, base, head, directory, template, developBranch, releaseBranch, stacked }, out),
292
425
  ];
293
426
  exitOnValidationErrors(errors, out);
294
427
  const isRelease = template === 'release';
295
428
  const draft = { location, title, body: input.body, head, base, isDraft: input.isDraft, isRelease };
296
429
  if (!input.dryRun) {
297
- await submitPullRequest(config, directory, draft, out);
430
+ await submitPullRequest(config, client, directory, draft, use?.stackOn, out);
298
431
  return;
299
432
  }
300
433
  out.planned(createOperation(draft));
301
434
  const issueNumber = extractIssueNumberFromBranch(head);
302
435
  if (!isRelease && issueNumber !== undefined)
303
436
  out.planned(inReviewOperation(issueNumber));
437
+ if (use?.stackOn !== undefined)
438
+ out.planned({ verb: 'add', target: `the new PR to the stack of PR #${String(use.stackOn)}` });
304
439
  }
305
440
  function requireRepository(value, out) {
306
- return splitOwnerRepository(value) ?? stopWith(out, `invalid repository format: ${value} (expected: owner/repo)`);
441
+ return splitOwnerRepository(value) ?? stopWith(out, `invalid repository format: ${value} (expected: owner/repo)`, 'invalid-input');
307
442
  }
308
443
  async function createFromFile(input, directory, out) {
309
444
  const config = requireActiveConfigPlain(out);
@@ -313,14 +448,15 @@ async function createFromFile(input, directory, out) {
313
448
  }
314
449
  catch (error) {
315
450
  if (error instanceof FrontmatterError)
316
- return stopWith(out, error.message);
451
+ return stopWith(out, error.message, 'content-invalid');
317
452
  throw error;
318
453
  }
319
454
  const { frontmatter } = parsed;
320
455
  if (frontmatter.repository === '' || !frontmatter.repository.includes('/'))
321
- return stopWith(out, 'repository is required (e.g. owner/repo)');
456
+ return stopWith(out, 'repository is required (e.g. owner/repo)', 'content-invalid');
322
457
  const location = requireRepository(frontmatter.repository, out);
323
458
  const head = resolveHeadBranch(frontmatter.head, directory, out);
459
+ const reading = readBaseRecordFor(head, input.template, directory, out);
324
460
  let body = parsed.body;
325
461
  const issueNumber = extractIssueNumberFromBranch(head);
326
462
  if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
@@ -339,6 +475,7 @@ async function createFromFile(input, directory, out) {
339
475
  isDraft: frontmatter.draft,
340
476
  body,
341
477
  screenshot: frontmatter.screenshot,
478
+ reading,
342
479
  }, out);
343
480
  }
344
481
  async function createDirect(input, directory, out) {
@@ -347,13 +484,14 @@ async function createDirect(input, directory, out) {
347
484
  if (input.repository === undefined || input.repository === '') {
348
485
  const [only] = config.repositories;
349
486
  if (only === undefined || config.repositories.length !== 1)
350
- return stopWith(out, 'specify the repository (-r owner/repo)');
487
+ return stopWith(out, hinted `specify the repository (${inputHint(PR_CREATE_PATH, 'repo', placeholder('owner/repo'))})`, 'invalid-input');
351
488
  location = { owner: only.owner, repository: only.name };
352
489
  }
353
490
  else {
354
491
  location = requireRepository(input.repository, out);
355
492
  }
356
493
  const head = resolveHeadBranch(input.head, directory, out);
494
+ const reading = readBaseRecordFor(head, input.template, directory, out);
357
495
  let body = input.message;
358
496
  const issueNumber = extractIssueNumberFromBranch(head);
359
497
  if (input.template !== 'release' && !input.noIssueRef && isPositive(issueNumber)) {
@@ -372,15 +510,16 @@ async function createDirect(input, directory, out) {
372
510
  isDraft: input.isDraft,
373
511
  body,
374
512
  screenshot: input.screenshot,
513
+ reading,
375
514
  }, out);
376
515
  }
377
516
  // --prepare
378
- function addScopeHint(content, config, location, base, directory, out) {
379
- const target = nxScopeTarget(config, location.owner, location.repository, base, directory);
517
+ function addScopeHint(content, config, location, base, directory, stacked, out) {
518
+ const target = nxScopeTarget(config, location.owner, location.repository, base, directory, stacked);
380
519
  if (target === undefined)
381
520
  return content;
382
521
  const head = gitCurrentBranch(directory);
383
- const expected = head === undefined || head === '' ? undefined : expectedTitleScope(target, base, head, out);
522
+ const expected = head === undefined || head === '' ? undefined : expectedTitleScope(target, head, out);
384
523
  if (expected === undefined || expected.length === 0)
385
524
  return content;
386
525
  const scope = expected.join(',');
@@ -430,18 +569,23 @@ async function fillClosesInTemplate(content, config, directory, location, out) {
430
569
  async function prepareTemplate(directory, out, template) {
431
570
  const templatePath = templateFile('pr', templateKindOf(template));
432
571
  if (!existsSync(templatePath))
433
- stopWith(out, `template not found: ${templatePath}`);
572
+ stopWith(out, `template not found: ${templatePath}`, 'other');
434
573
  let content = readTextFile(templatePath);
435
574
  // release テンプレートは、base をテンプレートの既定(main)のままにする
436
575
  if (template !== 'release') {
576
+ // 下の段の PR がマージ済みかは、準備と投稿の間に変わりうるので、ここでは読まずに投稿のときに見る
577
+ const reading = readBaseRecord();
578
+ stopOnMalformedRecord(reading, out);
579
+ const record = reading.kind === 'stacked' ? reading.record : undefined;
437
580
  const location = primaryRemote(directory)?.location;
438
581
  const config = loadActiveConfig();
439
582
  if (location !== undefined) {
440
583
  const developBranch = config === undefined ? undefined : getDevelopBranch(config, location.owner, location.repository);
441
584
  if (config !== undefined && developBranch !== undefined && developBranch !== '') {
442
- content = content.replace(/^base:\s*"[^"]*"/mu, () => `base: "${developBranch}"`);
443
- out.done({ verb: 'set', target: `base to ${developBranch}` });
444
- content = addScopeHint(content, config, { owner: location.owner, repository: location.repository }, developBranch, directory, out);
585
+ const base = record?.branch ?? developBranch;
586
+ content = content.replace(/^base:\s*"[^"]*"/mu, () => `base: "${base}"`);
587
+ out.done({ verb: 'set', target: `base to ${base}` });
588
+ content = addScopeHint(content, config, { owner: location.owner, repository: location.repository }, base, directory, record === undefined ? undefined : { sha: record.sha }, out);
445
589
  }
446
590
  }
447
591
  content = await fillClosesInTemplate(content, config, directory, location, out);
@@ -455,7 +599,7 @@ async function prepareTemplate(directory, out, template) {
455
599
  }
456
600
  catch (error) {
457
601
  if (error instanceof OutputPathReservationError)
458
- return stopWith(out, error.message);
602
+ return stopWith(out, error.message, 'other');
459
603
  throw error;
460
604
  }
461
605
  }
@@ -477,21 +621,21 @@ async function runCreate(input, io) {
477
621
  const directory = process.cwd();
478
622
  const out = createOutput(input.dry_run, io);
479
623
  if (input.template !== 'default' && input.template !== 'release')
480
- stopWith(out, `--template must be 'default' or 'release' (given: ${input.template})`);
624
+ stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'template')} must be 'default' or 'release' (given: ${input.template})`, 'invalid-input');
481
625
  if (input.prepare) {
482
626
  await prepareTemplate(directory, createOutput(false, io), input.template);
483
627
  }
484
628
  else if (input.file !== undefined) {
485
629
  if (input.screenshot !== undefined)
486
- stopWith(out, '--screenshot is for -m; write the reason in the `screenshot` frontmatter field instead');
630
+ stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'screenshot')} is for ${inputNameHint(PR_CREATE_PATH, 'message')}; write the reason in the \`screenshot\` frontmatter field instead`, 'invalid-input');
487
631
  await createFromFile({ file: input.file, template: input.template, noIssueRef: input.no_issue_ref, dryRun: input.dry_run }, directory, out);
488
632
  }
489
633
  else if (input.message === undefined) {
490
- stopWith(out, 'missing arguments\nusage:\npecot pr create --prepare\npecot pr create <path>\npecot pr create -m "<body>" -t "<title>" -b <base-branch>');
634
+ stopWith(out, hinted `missing arguments\nusage:\n${commandHint(PR_CREATE_PATH, { prepare: true })}\n${commandHint(PR_CREATE_PATH, { file: placeholder('path') })}\n${commandHint(PR_CREATE_PATH, { message: placeholder('body'), title: placeholder('title'), base: placeholder('base-branch') })}`, 'invalid-input');
491
635
  }
492
636
  else {
493
637
  if (input.title === undefined || input.title === '' || input.base === undefined || input.base === '')
494
- stopWith(out, '-t (title) and -b (base branch) are required with -m');
638
+ stopWith(out, hinted `${inputNameHint(PR_CREATE_PATH, 'title')} and ${inputNameHint(PR_CREATE_PATH, 'base')} (base branch) are required with ${inputNameHint(PR_CREATE_PATH, 'message')}`, 'invalid-input');
495
639
  await createDirect({
496
640
  message: input.message,
497
641
  title: input.title,
@@ -506,7 +650,7 @@ async function runCreate(input, io) {
506
650
  }, directory, out);
507
651
  }
508
652
  }
509
- // pr read
653
+ // pr show
510
654
  // グローバルの --repo か、いまの git の repository。決められなければ undefined
511
655
  function resolveBaseRepository(globalRepository) {
512
656
  try {
@@ -518,23 +662,23 @@ function resolveBaseRepository(globalRepository) {
518
662
  throw error;
519
663
  }
520
664
  }
521
- function parseReference(reference, globalRepository, out) {
665
+ export function parseReference(reference, globalRepository, out) {
522
666
  try {
523
667
  const parsed = parsePullRequestReference(reference, resolveBaseRepository(globalRepository), { repositoryFlag: true });
524
668
  return { owner: parsed.repository.owner, repository: parsed.repository.repository, number: parsed.number };
525
669
  }
526
670
  catch (error) {
527
671
  if (error instanceof ReferenceParseError)
528
- return stopWith(out, error.message, USAGE_EXIT_CODE);
672
+ return stopWith(out, error.hintedText ?? error.message, 'invalid-input', USAGE_EXIT_CODE);
529
673
  throw error;
530
674
  }
531
675
  }
532
- const ReadInputSchema = z.strictObject({
676
+ const ShowInputSchema = z.strictObject({
533
677
  pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
534
678
  json: z.boolean().default(false).describe('Output as JSON'),
535
679
  reviews: z.boolean().default(false).describe('Include review details (bodies and line comments)'),
536
680
  });
537
- async function runRead(input, io) {
681
+ async function runShow(input, io) {
538
682
  const out = createOutput(false, io);
539
683
  const config = requireActiveConfigPlain(out);
540
684
  const { owner, repository, number } = parseReference(input.pr_ref, input.repo, out);
@@ -551,24 +695,43 @@ async function runRead(input, io) {
551
695
  }
552
696
  catch (error) {
553
697
  if (error instanceof GitHubAPIError)
554
- return stopWith(out, error.message);
698
+ return stopWith(out, error.message, kindOfFailure(error));
555
699
  throw error;
556
700
  }
557
701
  }
558
- // pr preflight
702
+ // pr check
559
703
  function hasBranch(branch, cwd) {
560
704
  return runGit(['rev-parse', '--verify', branch], { cwd }).exitCode === 0;
561
705
  }
706
+ // pr check の ls-remote は、認証の入力を待たずに、この時間で諦める
707
+ const LS_REMOTE_TIMEOUT_MILLISECONDS = 10_000;
708
+ // 端末で尋ねさせない。ssh は GIT_SSH_COMMAND で BatchMode にすると利用者の GIT_SSH と core.sshCommand を上書きするので、askpass を失敗させる
709
+ const NON_INTERACTIVE_GIT = { GIT_TERMINAL_PROMPT: '0', SSH_ASKPASS: 'false', SSH_ASKPASS_REQUIRE: 'force' };
710
+ // 下の段のブランチがマージで消えた後は、開発ブランチと比べる。追跡参照は fetch --prune まで残るので、
711
+ // remote に尋ね、無い(終了コード 2)ときだけ消えたとみなす。届かないか時間切れなら追跡参照で決める
712
+ function isOnRemote(branch, cwd, remote, out) {
713
+ const listed = runGit(['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd, env: NON_INTERACTIVE_GIT, timeoutMilliseconds: LS_REMOTE_TIMEOUT_MILLISECONDS });
714
+ if (listed.exitCode === LS_REMOTE_NOT_FOUND)
715
+ return false;
716
+ const isTracked = hasBranch(`${remote}/${branch}`, cwd);
717
+ if (!isTracked && listed.exitCode === 0)
718
+ out.warning(`base branch ${branch} is on ${remote}, but ${remote}/${branch} is not fetched; compared with the develop branch\nrun: git fetch ${remote} ${branch}`);
719
+ return isTracked;
720
+ }
562
721
  function determineBaseBranch(location, cwd, remote, out) {
563
722
  const config = loadActiveConfig();
564
723
  if (config === undefined)
565
- return stopWith(out, 'project config not found\nactivate a project with: pecot project activate <PROJECT>');
724
+ return stopWith(out, hinted `project config not found\nactivate a project with: ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, 'no-active-project');
725
+ const reading = readBaseRecord();
726
+ stopOnMalformedRecord(reading, out);
727
+ if (reading.kind === 'stacked' && isOnRemote(reading.record.branch, cwd, remote, out))
728
+ return `${remote}/${reading.record.branch}`;
566
729
  const developBranch = getDevelopBranch(config, location.owner, location.repository);
567
730
  if (developBranch === undefined || developBranch === '') {
568
- return stopWith(out, `develop_branch is not set for ${location.owner}/${location.repository}\nset it with: pecot project set-repo ${location.owner}/${location.repository} --develop-branch develop`);
731
+ return stopWith(out, hinted `develop_branch is not set for ${location.owner}/${location.repository}\nset it with: ${commandHint(LINK_PATH, { repo: `${location.owner}/${location.repository}`, develop_branch: 'develop' })}`, 'repo-setting-missing');
569
732
  }
570
733
  const branchName = `${remote}/${developBranch}`;
571
- return hasBranch(branchName, cwd) ? branchName : stopWith(out, `branch ${branchName} does not exist\ncheck the remote branches with: git branch -r`);
734
+ return hasBranch(branchName, cwd) ? branchName : stopWith(out, `branch ${branchName} does not exist\ncheck the remote branches with: git branch -r`, 'git-unresolved');
572
735
  }
573
736
  function readGitignore(cwd) {
574
737
  const root = gitToplevel({ cwd });
@@ -610,10 +773,10 @@ function getWorktreeInfo(cwd) {
610
773
  }
611
774
  return lines.join('\n');
612
775
  }
613
- const PreflightInputSchema = z.strictObject({
776
+ const CheckInputSchema = z.strictObject({
614
777
  directory: directorySchema,
615
778
  });
616
- function runPreflight(input, io) {
779
+ function runCheck(input, io) {
617
780
  const out = createOutput(false, io);
618
781
  const directory = input.directory;
619
782
  const context = validatePullRequestContext(directory, out);
@@ -646,242 +809,10 @@ function runPreflight(input, io) {
646
809
  out.count('preflight warnings', warnings.length);
647
810
  printPreflightWarnings(out, warnings);
648
811
  if (warnings.length > 0)
649
- throw new CommandExit(PREFLIGHT_EXIT_CODE);
650
- }
651
- async function fetchPullRequestForCleanup(config, location, out) {
652
- try {
653
- const client = createGitHubClient(out, config.host);
654
- return { client, pr: await client.getPullRequestSlim(location.owner, location.repository, location.number) };
655
- }
656
- catch (error) {
657
- if (error instanceof GitHubNotFoundError)
658
- return stopWith(out, `PR not found: ${location.owner}/${location.repository}/${String(location.number)}`);
659
- if (error instanceof GitHubAPIError)
660
- return stopWith(out, error.message);
661
- throw error;
662
- }
663
- }
664
- function collectClosingIssueNumbers(pr) {
665
- const numbers = new Set(pr.closing_issues.map(issue => issue.number));
666
- for (const number of extractClosingIssueNumbers(pr.body))
667
- numbers.add(number);
668
- const branchNumber = extractIssueNumberFromBranch(pr.head_ref);
669
- if (isPositive(branchNumber))
670
- numbers.add(branchNumber);
671
- return numbers;
672
- }
673
- // Epic 保護。Issue Type が Epic か、sub-issue を持つ Issue
674
- async function findEpicProtectedNumbers(client, location, issueNumbers, out) {
675
- const protectedNumbers = new Set();
676
- const ordered = [...issueNumbers].toSorted((a, b) => a - b);
677
- for (const number of ordered) {
678
- try {
679
- if (isEpicIssue(await client.getIssueKind(location.owner, location.repository, number)))
680
- protectedNumbers.add(number);
681
- }
682
- catch (error) {
683
- if (error instanceof GitHubNotFoundError)
684
- continue;
685
- if (!(error instanceof GitHubAPIError))
686
- throw error;
687
- out.warning(`kind check of Issue #${String(number)} failed: ${error.message}; not protected`);
688
- }
689
- }
690
- return protectedNumbers;
691
- }
692
- async function closeRelatedIssues(context, client, location, closing, epicProtected) {
693
- const { out, isDryRun } = context;
694
- const protectedOrdered = [...epicProtected].toSorted((a, b) => a - b);
695
- const closingOrdered = [...closing].toSorted((a, b) => a - b);
696
- for (const number of protectedOrdered)
697
- settle(out, { verb: 'skip', target: `closing Issue #${String(number)} (Epic)` });
698
- for (const number of closingOrdered) {
699
- const operation = { verb: 'close', target: `Issue #${String(number)}` };
700
- out.planned(operation);
701
- if (isDryRun)
702
- continue;
703
- try {
704
- await client.closeIssue(location.owner, location.repository, number);
705
- out.done(operation);
706
- }
707
- catch (error) {
708
- if (error instanceof GitHubNotFoundError) {
709
- out.warning(`Issue #${String(number)} not found; skipped`);
710
- }
711
- else if (error instanceof GitHubAPIError) {
712
- if (isClosedByAnotherRequest(error))
713
- out.done({ verb: 'unchanged', target: `Issue #${String(number)} (already closed)` });
714
- else
715
- out.warning(`closing Issue #${String(number)} failed: ${describeApiError(error)}`);
716
- }
717
- else {
718
- throw error;
719
- }
720
- }
721
- }
722
- }
723
- // head ブランチを消し、続けて wip ブランチを消す。head が無くても wip は試す
724
- async function deleteMergedBranch(context, client, location, headBranch) {
725
- const { out, isDryRun } = context;
726
- const operation = { verb: 'delete', target: `remote branch ${headBranch}` };
727
- out.planned(operation);
728
- if (isDryRun)
729
- return;
730
- try {
731
- await client.deleteBranch(location.owner, location.repository, headBranch);
732
- out.done(operation);
733
- }
734
- catch (error) {
735
- if (!(error instanceof GitHubAPIError))
736
- throw error;
737
- if (!isMissingReferenceError(error)) {
738
- out.warning(`deleting remote branch ${headBranch} failed: ${describeApiError(error)}`);
739
- return;
740
- }
741
- out.done({ verb: 'unchanged', target: `remote branch ${headBranch} (already deleted)` });
742
- }
743
- const wipBranch = `wip/${headBranch}`;
744
- try {
745
- await client.deleteBranch(location.owner, location.repository, wipBranch);
746
- out.done({ verb: 'delete', target: `remote branch ${wipBranch}` });
747
- }
748
- catch (error) {
749
- if (!(error instanceof GitHubAPIError))
750
- throw error;
751
- if (!isMissingReferenceError(error))
752
- out.warning(`deleting remote branch ${wipBranch} failed: ${describeApiError(error)}`);
753
- }
754
- }
755
- // 手元と PR の repository が同じなら主の remote 名。違えば警告を出して undefined
756
- function sameRepositoryRemote(cwd, location, out) {
757
- const skipped = 'skipped local cleanup';
758
- try {
759
- const found = primaryRemote(cwd);
760
- if (found === undefined) {
761
- out.warning(`cannot read the remote URL; ${skipped}`);
762
- return undefined;
763
- }
764
- if (found.location === undefined) {
765
- out.warning(`cannot read the repository from the remote URL; ${skipped}`);
766
- return undefined;
767
- }
768
- if (found.location.owner !== location.owner || found.location.repository !== location.repository) {
769
- out.warning(`current repository (${found.location.owner}/${found.location.repository}) differs from the PR's (${location.owner}/${location.repository}); ${skipped}`);
770
- return undefined;
771
- }
772
- return found.name;
773
- }
774
- catch {
775
- out.warning(`cannot determine the repository; ${skipped}`);
776
- return undefined;
777
- }
778
- }
779
- // worktree では worktree 名、そうでなければ develop ブランチ
780
- function resolveCheckoutTarget(cwd, config, location, out) {
781
- try {
782
- if (isWorktreeEnvironment(cwd))
783
- return getCurrentWorktreeName(cwd) ?? 'main';
784
- const developBranch = getDevelopBranch(config, location.owner, location.repository);
785
- if (developBranch !== undefined && developBranch !== '')
786
- return developBranch;
787
- out.warning('develop_branch is not set; skipped local cleanup');
788
- return undefined;
789
- }
790
- catch {
791
- out.warning('cannot determine the worktree; skipped local cleanup');
792
- return undefined;
793
- }
794
- }
795
- function didRunLocalStep(context, operation, cwd, arguments_, failure) {
796
- const { out, isDryRun } = context;
797
- out.planned(operation);
798
- if (isDryRun)
799
- return true;
800
- try {
801
- runGit(arguments_, { cwd, check: true });
802
- }
803
- catch (error) {
804
- if (!(error instanceof GitCommandError) && !isFileNotFound(error))
805
- throw error;
806
- out.warning(`${failure} failed: ${reasonOf(error)}`);
807
- return false;
808
- }
809
- out.done(operation);
810
- return true;
811
- }
812
- function localCleanupAfterMerge(context, headBranch, config, location) {
813
- const { out } = context;
814
- const cwd = process.cwd();
815
- const remote = sameRepositoryRemote(cwd, location, out);
816
- if (remote === undefined)
817
- return;
818
- const currentBranch = gitCurrentBranch(cwd);
819
- const checkoutTarget = resolveCheckoutTarget(cwd, config, location, out);
820
- if (checkoutTarget === undefined)
821
- return;
822
- const developBranch = getDevelopBranch(config, location.owner, location.repository);
823
- if (developBranch === undefined || developBranch === '') {
824
- out.warning('develop_branch is not set; skipped local cleanup');
825
- return;
826
- }
827
- if (currentBranch === checkoutTarget) {
828
- settle(out, { verb: 'unchanged', target: `current branch ${checkoutTarget}` });
829
- }
830
- else if (!didRunLocalStep(context, { verb: 'set', target: `current branch to ${checkoutTarget}` }, cwd, ['checkout', checkoutTarget], `checking out ${checkoutTarget}`)) {
831
- // checkout が失敗したら、pull と branch -D は別のブランチに当たるので止める
832
- return;
833
- }
834
- didRunLocalStep(context, { verb: 'update', target: `${checkoutTarget} from ${remote}/${developBranch}` }, cwd, ['pull', remote, developBranch], `pulling ${developBranch}`);
835
- if (headBranch === checkoutTarget) {
836
- settle(out, { verb: 'skip', target: `deleting local branch ${headBranch} (it is the checkout target)` });
837
- }
838
- else {
839
- didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`);
840
- }
841
- }
842
- function removeActiveFlags(out) {
843
- try {
844
- for (const flag of [FLAG_PECOT_ACTIVE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE, FLAG_WIP_BRANCH_LINKED])
845
- removeFlag(flag);
846
- }
847
- catch (error) {
848
- out.warning(`removing flag files failed: ${reasonOf(error)}`);
849
- }
850
- }
851
- const CleanupInputSchema = z.strictObject({
852
- pr_ref: z.string().describe(PR_REFERENCE_DESCRIPTION),
853
- dry_run: z.boolean().default(false).describe('Dry-run (do not actually clean up)'),
854
- delete_branch: z.boolean().default(false).describe('Delete the branch'),
855
- skip_local_cleanup: z.boolean().default(false).describe('Skip the local branch switch and deletion'),
856
- });
857
- async function runCleanup(input, io) {
858
- const out = createOutput(input.dry_run, io);
859
- const context = { out, isDryRun: input.dry_run };
860
- const config = requireActiveConfigPlain(out);
861
- const reference = parseReference(input.pr_ref, input.repo, out);
862
- const location = { owner: reference.owner, repository: reference.repository };
863
- const { client, pr } = await fetchPullRequestForCleanup(config, reference, out);
864
- if (pr.state !== 'MERGED')
865
- stopWith(out, `PR #${String(reference.number)} is not merged yet (state: ${pr.state}); merge it with gh pr merge first`);
866
- const closing = collectClosingIssueNumbers(pr);
867
- const epicProtected = await findEpicProtectedNumbers(client, location, closing, out);
868
- for (const number of epicProtected)
869
- closing.delete(number);
870
- out.count('Issues to close', closing.size);
871
- await closeRelatedIssues(context, client, location, closing, epicProtected);
872
- if (input.delete_branch)
873
- await deleteMergedBranch(context, client, location, pr.head_ref);
874
- if (input.skip_local_cleanup)
875
- return;
876
- localCleanupAfterMerge(context, pr.head_ref, config, location);
877
- if (input.dry_run) {
878
- return;
879
- }
880
- removeActiveFlags(out);
881
- consumeFlag(FLAG_MERGE_SLASH_PENDING);
812
+ throw new CommandExit(PREFLIGHT_EXIT_CODE, 'preflight-failed');
882
813
  }
883
814
  const prCreate = defineCommand({
884
- path: ['pr', 'create'],
815
+ path: PR_CREATE_PATH,
885
816
  description: 'Create a PR (pull request)',
886
817
  input: CreateInputSchema,
887
818
  positional: ['file'],
@@ -893,41 +824,29 @@ const prCreate = defineCommand({
893
824
  return 0;
894
825
  },
895
826
  });
896
- const prRead = defineCommand({
897
- path: ['pr', 'read'],
827
+ const prShow = defineCommand({
828
+ path: ['pr', 'show'],
898
829
  description: 'Get PR details efficiently (GraphQL, only the needed fields)',
899
- input: ReadInputSchema,
830
+ input: ShowInputSchema,
900
831
  positional: ['pr_ref'],
901
832
  shortFlags: { json: '-j', reviews: '-r' },
902
833
  interactive: false,
903
834
  run: async (input, io) => {
904
- await runRead(input, io);
835
+ await runShow(input, io);
905
836
  return 0;
906
837
  },
907
838
  });
908
- const prPreflight = defineCommand({
909
- path: ['pr', 'preflight'],
839
+ const prCheck = defineCommand({
840
+ path: ['pr', 'check'],
910
841
  description: 'Show all the information to check before creating a PR',
911
- input: PreflightInputSchema,
842
+ input: CheckInputSchema,
912
843
  positional: [],
913
844
  shortFlags: { directory: '-D' },
914
845
  interactive: false,
915
846
  run: (input, io) => {
916
- runPreflight(input, io);
847
+ runCheck(input, io);
917
848
  return Promise.resolve(0);
918
849
  },
919
850
  });
920
- const prCleanup = defineCommand({
921
- path: ['pr', 'cleanup'],
922
- description: 'Clean up after a merged PR (close related Issues, delete branches, local cleanup)',
923
- input: CleanupInputSchema,
924
- positional: ['pr_ref'],
925
- shortFlags: { dry_run: '-n', delete_branch: '-d' },
926
- interactive: false,
927
- run: async (input, io) => {
928
- await runCleanup(input, io);
929
- return 0;
930
- },
931
- });
932
- export const PR_COMMANDS = [prCleanup, prCreate, prPreflight, prRead];
851
+ export const PR_COMMANDS = [prCreate, prShow, prCheck];
933
852
  //# sourceMappingURL=pr.js.map