@pecot/workflow-mcp 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +27 -22
  3. package/cli/dist/cli.js +6 -1
  4. package/cli/dist/commands/board-add.d.ts +3 -0
  5. package/cli/dist/commands/board-add.js +69 -0
  6. package/cli/dist/commands/board-judgment.d.ts +69 -0
  7. package/cli/dist/commands/board-judgment.js +150 -0
  8. package/cli/dist/commands/board-move.d.ts +3 -0
  9. package/cli/dist/commands/board-move.js +65 -0
  10. package/cli/dist/commands/board-readiness.d.ts +34 -0
  11. package/cli/dist/commands/board-readiness.js +108 -0
  12. package/cli/dist/commands/board-show.d.ts +3 -0
  13. package/cli/dist/commands/board-show.js +75 -0
  14. package/cli/dist/commands/board-sync.d.ts +3 -0
  15. package/cli/dist/commands/board-sync.js +120 -0
  16. package/cli/dist/commands/board-view.d.ts +151 -0
  17. package/cli/dist/commands/board-view.js +293 -0
  18. package/cli/dist/commands/board.d.ts +3 -0
  19. package/cli/dist/commands/board.js +12 -0
  20. package/cli/dist/commands/branch.d.ts +3 -0
  21. package/cli/dist/commands/branch.js +111 -0
  22. package/cli/dist/commands/command-binding.js +4 -0
  23. package/cli/dist/commands/command-definition.d.ts +39 -8
  24. package/cli/dist/commands/command-definition.js +20 -7
  25. package/cli/dist/commands/command-help.js +2 -2
  26. package/cli/dist/commands/command-hint.d.ts +5 -0
  27. package/cli/dist/commands/command-hint.js +13 -0
  28. package/cli/dist/commands/command-stop.d.ts +5 -3
  29. package/cli/dist/commands/command-stop.js +7 -6
  30. package/cli/dist/commands/failure-kind.d.ts +3 -0
  31. package/cli/dist/commands/failure-kind.js +35 -0
  32. package/cli/dist/commands/failure.d.ts +6 -0
  33. package/cli/dist/commands/failure.js +29 -3
  34. package/cli/dist/commands/github-client.d.ts +6 -2
  35. package/cli/dist/commands/github-client.js +13 -3
  36. package/cli/dist/commands/help.js +8 -13
  37. package/cli/dist/commands/issue-board.d.ts +61 -0
  38. package/cli/dist/commands/issue-board.js +85 -1
  39. package/cli/dist/commands/issue-comment.js +66 -30
  40. package/cli/dist/commands/issue-create.js +632 -92
  41. package/cli/dist/commands/issue-dependency.d.ts +3 -0
  42. package/cli/dist/commands/issue-dependency.js +310 -0
  43. package/cli/dist/commands/issue-readiness.d.ts +122 -0
  44. package/cli/dist/commands/issue-readiness.js +253 -0
  45. package/cli/dist/commands/issue-reopen.d.ts +3 -0
  46. package/cli/dist/commands/issue-reopen.js +130 -0
  47. package/cli/dist/commands/issue-shared.d.ts +33 -20
  48. package/cli/dist/commands/issue-shared.js +84 -76
  49. package/cli/dist/commands/issue-show.d.ts +3 -0
  50. package/cli/dist/commands/issue-show.js +239 -0
  51. package/cli/dist/commands/issue.d.ts +0 -1
  52. package/cli/dist/commands/issue.js +6 -8
  53. package/cli/dist/commands/names.d.ts +33 -0
  54. package/cli/dist/commands/names.js +63 -0
  55. package/cli/dist/commands/output.d.ts +32 -4
  56. package/cli/dist/commands/output.js +28 -8
  57. package/cli/dist/commands/pr-merge.d.ts +3 -0
  58. package/cli/dist/commands/pr-merge.js +230 -0
  59. package/cli/dist/commands/pr-reference.d.ts +8 -0
  60. package/cli/dist/commands/pr-reference.js +30 -0
  61. package/cli/dist/commands/pr-restack.d.ts +6 -0
  62. package/cli/dist/commands/pr-restack.js +233 -0
  63. package/cli/dist/commands/pr-waiting.d.ts +59 -0
  64. package/cli/dist/commands/pr-waiting.js +143 -0
  65. package/cli/dist/commands/pr.d.ts +23 -0
  66. package/cli/dist/commands/pr.js +378 -366
  67. package/cli/dist/commands/project-sync.d.ts +12 -3
  68. package/cli/dist/commands/project-sync.js +23 -13
  69. package/cli/dist/commands/project.d.ts +3 -2
  70. package/cli/dist/commands/project.js +371 -177
  71. package/cli/dist/commands/registry.js +15 -10
  72. package/cli/dist/commands/release.d.ts +2 -2
  73. package/cli/dist/commands/release.js +118 -130
  74. package/cli/dist/commands/renamed-commands.d.ts +26 -0
  75. package/cli/dist/commands/renamed-commands.js +53 -0
  76. package/cli/dist/commands/repository-match.js +9 -3
  77. package/cli/dist/commands/session-finish.d.ts +3 -0
  78. package/cli/dist/commands/session-finish.js +383 -0
  79. package/cli/dist/commands/session-start.d.ts +3 -0
  80. package/cli/dist/commands/session-start.js +252 -0
  81. package/cli/dist/commands/session.d.ts +3 -0
  82. package/cli/dist/commands/session.js +186 -32
  83. package/cli/dist/commands/tracker-sync-dependabot.d.ts +7 -0
  84. package/cli/dist/commands/{dependabot.js → tracker-sync-dependabot.js} +76 -68
  85. package/cli/dist/commands/tracker-sync-security.d.ts +7 -0
  86. package/cli/dist/commands/{security.js → tracker-sync-security.js} +71 -64
  87. package/cli/dist/commands/tracker-sync.d.ts +37 -0
  88. package/cli/dist/commands/tracker-sync.js +18 -6
  89. package/cli/dist/commands/tracker.d.ts +3 -0
  90. package/cli/dist/commands/tracker.js +20 -0
  91. package/cli/dist/commands/usage-error.d.ts +4 -0
  92. package/cli/dist/commands/usage-error.js +6 -0
  93. package/cli/dist/commands/work-target.d.ts +20 -3
  94. package/cli/dist/commands/work-target.js +49 -6
  95. package/cli/dist/commands/worktree.js +103 -33
  96. package/cli/dist/domain/batch-plan.d.ts +73 -0
  97. package/cli/dist/domain/batch-plan.js +114 -0
  98. package/cli/dist/domain/blocked-by-change.d.ts +99 -0
  99. package/cli/dist/domain/blocked-by-change.js +101 -0
  100. package/cli/dist/domain/board-move.d.ts +90 -0
  101. package/cli/dist/domain/board-move.js +92 -0
  102. package/cli/dist/domain/branch-name.js +1 -1
  103. package/cli/dist/domain/command-hint.d.ts +85 -0
  104. package/cli/dist/domain/command-hint.js +148 -0
  105. package/cli/dist/domain/config.d.ts +4 -0
  106. package/cli/dist/domain/config.js +11 -1
  107. package/cli/dist/domain/dependabot.js +1 -1
  108. package/cli/dist/domain/errors.d.ts +5 -0
  109. package/cli/dist/domain/errors.js +5 -0
  110. package/cli/dist/domain/format.d.ts +51 -4
  111. package/cli/dist/domain/format.js +72 -6
  112. package/cli/dist/domain/frontmatter.d.ts +18 -3
  113. package/cli/dist/domain/frontmatter.js +38 -12
  114. package/cli/dist/domain/issue-order.d.ts +55 -0
  115. package/cli/dist/domain/issue-order.js +65 -0
  116. package/cli/dist/domain/issue-readout.d.ts +36 -4
  117. package/cli/dist/domain/pull-request.d.ts +71 -4
  118. package/cli/dist/domain/pull-request.js +59 -10
  119. package/cli/dist/domain/readiness.d.ts +44 -0
  120. package/cli/dist/domain/readiness.js +153 -5
  121. package/cli/dist/domain/reference-parser.d.ts +3 -1
  122. package/cli/dist/domain/reference-parser.js +6 -2
  123. package/cli/dist/domain/release.d.ts +7 -3
  124. package/cli/dist/domain/release.js +5 -12
  125. package/cli/dist/domain/repository-policy.d.ts +9 -3
  126. package/cli/dist/domain/repository-policy.js +8 -7
  127. package/cli/dist/domain/repository-resolver.js +4 -1
  128. package/cli/dist/domain/restack.d.ts +62 -0
  129. package/cli/dist/domain/restack.js +53 -0
  130. package/cli/dist/domain/security-alerts.js +1 -1
  131. package/cli/dist/domain/state.d.ts +69 -0
  132. package/cli/dist/domain/state.js +67 -1
  133. package/cli/dist/domain/work-start.d.ts +30 -0
  134. package/cli/dist/domain/work-start.js +42 -0
  135. package/cli/dist/infra/authored-notes.d.ts +1 -1
  136. package/cli/dist/infra/authored-notes.js +10 -4
  137. package/cli/dist/infra/config-store.d.ts +4 -0
  138. package/cli/dist/infra/config-store.js +13 -0
  139. package/cli/dist/infra/git.d.ts +76 -0
  140. package/cli/dist/infra/git.js +123 -1
  141. package/cli/dist/infra/github/client.d.ts +5 -0
  142. package/cli/dist/infra/github/client.js +10 -7
  143. package/cli/dist/infra/github/errors.d.ts +18 -0
  144. package/cli/dist/infra/github/errors.js +22 -0
  145. package/cli/dist/infra/github/issues.d.ts +39 -3
  146. package/cli/dist/infra/github/issues.js +178 -23
  147. package/cli/dist/infra/github/projects.d.ts +35 -0
  148. package/cli/dist/infra/github/projects.js +89 -8
  149. package/cli/dist/infra/github/pulls.d.ts +105 -2
  150. package/cli/dist/infra/github/pulls.js +172 -5
  151. package/cli/dist/infra/github/queries.d.ts +15 -4
  152. package/cli/dist/infra/github/queries.js +203 -40
  153. package/cli/dist/infra/github/readout.d.ts +5 -1
  154. package/cli/dist/infra/github/readout.js +11 -33
  155. package/cli/dist/infra/github/repos.d.ts +18 -0
  156. package/cli/dist/infra/github/repos.js +31 -0
  157. package/cli/dist/infra/nx-scope.d.ts +1 -1
  158. package/cli/dist/infra/nx-scope.js +1 -1
  159. package/cli/dist/infra/state-store.d.ts +10 -1
  160. package/cli/dist/infra/state-store.js +14 -2
  161. package/cli/dist/infra/worktree-links.d.ts +3 -0
  162. package/cli/dist/infra/worktree-links.js +8 -1
  163. package/cli/dist/infra/worktree.d.ts +12 -1
  164. package/cli/dist/infra/worktree.js +40 -23
  165. package/cli/dist/mcp/result.d.ts +82 -7
  166. package/cli/dist/mcp/result.js +139 -19
  167. package/cli/dist/mcp/server.d.ts +2 -2
  168. package/cli/dist/mcp/server.js +57 -10
  169. package/cli/templates/comment/plan.md +14 -0
  170. package/cli/templates/comment/review-findings.md +3 -2
  171. package/cli/templates/issue/bug.md +13 -4
  172. package/cli/templates/issue/task-implement.md +13 -6
  173. package/cli/templates/issue/task.md +13 -4
  174. package/cli/templates/workflow/pecot-board-sync.yml +84 -0
  175. package/npm-shrinkwrap.json +2 -2
  176. package/package.json +1 -1
  177. package/cli/dist/commands/dependabot.d.ts +0 -3
  178. package/cli/dist/commands/issue-project.d.ts +0 -3
  179. package/cli/dist/commands/issue-project.js +0 -176
  180. package/cli/dist/commands/issue-quick.d.ts +0 -3
  181. package/cli/dist/commands/issue-quick.js +0 -126
  182. package/cli/dist/commands/issue-read.d.ts +0 -3
  183. package/cli/dist/commands/issue-read.js +0 -80
  184. package/cli/dist/commands/project-info.d.ts +0 -48
  185. package/cli/dist/commands/project-info.js +0 -181
  186. package/cli/dist/commands/repository.d.ts +0 -5
  187. package/cli/dist/commands/repository.js +0 -265
  188. package/cli/dist/commands/security.d.ts +0 -3
@@ -0,0 +1,233 @@
1
+ // pr restack。積んだブランチを、base にしたブランチの新しい位置へ載せ直す。
2
+ // 途中で抜ける箇所は CommandExit を投げ、defineCommand が終了コードにする。
3
+ import { z } from 'zod';
4
+ import { describeApiError } from '../domain/api-error-detail.js';
5
+ import { getDevelopBranch } from '../domain/config.js';
6
+ import { pickLowerPullRequest } from '../domain/pull-request.js';
7
+ import { decideRestack, describeGone, describeRestackCheck } from '../domain/restack.js';
8
+ import { FLAG_PECOT_RESTACK, formatRestackProgress, interpretRestackProgress } from '../domain/state.js';
9
+ import { abortRebase, conflictedFiles, continueRebase, fetchRemote, gitStdout, hasSameTree, isRebaseInProgress, mergeBase, pushWithLease, rebaseOnto, remoteBranchHead, remoteOnlyChanges, resetHardTo, resolveCommit, } from '../infra/git.js';
10
+ import { GitHubAPIError } from '../infra/github/errors.js';
11
+ import { readBaseRecord, readFlag, removeFlag, writeBaseRecord, writeFlag } from '../infra/state-store.js';
12
+ import { defineCommand } from './command-definition.js';
13
+ import { commandHint, hinted } from './command-hint.js';
14
+ import { requireActiveConfigPlain, stopWith } from './command-stop.js';
15
+ import { kindOfFailure } from './failure.js';
16
+ import { createGitHubClient } from './github-client.js';
17
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
18
+ import { stopOnMalformedRecord, validatePullRequestContext } from './pr.js';
19
+ import { USAGE_EXIT_CODE } from './usage-error.js';
20
+ const RESTACK_PATH = ['pr', 'restack'];
21
+ const CONFLICT_EXIT_CODE = 3;
22
+ const UNCOMMITTED_EXIT_CODE = 2;
23
+ // 文の中にロングオプションを書けない(lint)ので、git の引数から組む
24
+ const SKIP_COMMAND = ['git', 'rebase', '--skip'].join(' ');
25
+ const PR_RESTACK_OUTPUT = z.strictObject({
26
+ branch: z.string().describe('Branch that is restacked'),
27
+ base: z.string().describe('Base branch after the restack (the develop branch when the lower PR is merged)'),
28
+ outcome: z.enum(['up-to-date', 'needs-restack', 'restacked', 'synced', 'conflict', 'aborted']).describe('What happened, or with check, what a restack would do'),
29
+ cause: z.enum(['base-moved', 'base-merged']).optional().describe('Why a restack is needed (only with check or dry_run, when one is needed)'),
30
+ pullRequest: z.int().optional().describe('Merged PR of the lower branch (only when the cause is base-merged)'),
31
+ pushed: z.boolean().optional().describe('Whether the branch was pushed (only when restacked)'),
32
+ conflicts: z.array(z.string()).optional().describe('Files with conflicts (only on conflict)'),
33
+ dryRun: DRY_RUN_FIELD,
34
+ });
35
+ const RestackInputSchema = z.strictObject({
36
+ check: z.boolean().default(false).describe('Only report whether a restack is needed'),
37
+ continue: z.boolean().default(false).describe('Continue a restack that stopped on conflicts, after resolving them'),
38
+ abort: z.boolean().default(false).describe('Abort a restack that stopped on conflicts and go back to the position before it'),
39
+ dry_run: z.boolean().default(false).describe('Show what would be done without rebasing, pushing or writing records'),
40
+ });
41
+ function causeOf(decision) {
42
+ if (decision.kind === 'moved')
43
+ return { cause: 'base-moved' };
44
+ return decision.kind === 'merged' ? { cause: 'base-merged', pullRequest: decision.pullRequest } : {};
45
+ }
46
+ // 衝突したファイルと、続行・取りやめの案内を出して、終了コード 3 で止まる。途中の記録は残す
47
+ function stopOnConflict(out, cwd, progress) {
48
+ const conflicts = conflictedFiles(cwd);
49
+ out.result({ branch: progress.branch, base: progress.ontoBranch, outcome: 'conflict', conflicts: [...conflicts] });
50
+ // 衝突したファイルが無いのに止まるのは、解いた結果が空のコミットになったとき
51
+ const message = conflicts.length === 0
52
+ ? hinted `the rebase stopped without conflicted files (a commit may have become empty)\nskip the commit with: ${SKIP_COMMAND}, then run: ${commandHint(RESTACK_PATH, { continue: true })}\nor go back to the position before the restack: ${commandHint(RESTACK_PATH, { abort: true })}`
53
+ : hinted `conflict in ${conflicts.join(', ')}\nresolve the conflicts and git add the files, then run: ${commandHint(RESTACK_PATH, { continue: true })}\nor go back to the position before the restack: ${commandHint(RESTACK_PATH, { abort: true })}`;
54
+ return stopWith(out, message, 'git-conflict', CONFLICT_EXIT_CODE);
55
+ }
56
+ // remote のブランチにだけあるコミット。patch-id は前後の行も含むので、載せ直しの前と後のどちらとも合わないものだけを数える
57
+ function remoteOnlyCommits(cwd, progress, remoteBranch) {
58
+ const reading = readBaseRecord();
59
+ const excluded = [progress.ontoSha, ...reading.kind === 'stacked' ? [reading.record.sha] : []];
60
+ const before = remoteOnlyChanges(cwd, progress.originalSha, remoteBranch, excluded);
61
+ if (before.length === 0)
62
+ return [];
63
+ const after = new Set(remoteOnlyChanges(cwd, 'HEAD', remoteBranch, excluded));
64
+ return before.filter(sha => after.has(sha));
65
+ }
66
+ // rebase が終わった後。remote が載せ直し済みで木が同じなら合わせ、違えば push し、base の記録を書き直す
67
+ function finishRestack(out, cwd, progress) {
68
+ const { remote, branch, ontoBranch, leaseSha } = progress;
69
+ const remoteBranch = `${remote}/${branch}`;
70
+ if (leaseSha !== undefined && remoteOnlyCommits(cwd, progress, remoteBranch).length > 0) {
71
+ resetHardTo(cwd, progress.originalSha);
72
+ removeFlag(FLAG_PECOT_RESTACK);
73
+ stopWith(out, hinted `${remoteBranch} has commits that are not in ${branch}\n${branch} is back at the position before the restack\nrebase or merge them into ${branch} first, then run again: ${commandHint(RESTACK_PATH)}`, 'git-unresolved');
74
+ }
75
+ // 木が同じでも、remote が新しい base の上に無ければ、古い履歴のままなので合わせない
76
+ const isSynced = leaseSha !== undefined && mergeBase(cwd, progress.ontoSha, remoteBranch) === progress.ontoSha && hasSameTree(cwd, 'HEAD', remoteBranch);
77
+ if (isSynced)
78
+ resetHardTo(cwd, remoteBranch);
79
+ else if (leaseSha !== undefined) {
80
+ const push = pushWithLease(cwd, remote, branch, leaseSha);
81
+ if (!push.pushed) {
82
+ removeFlag(FLAG_PECOT_RESTACK);
83
+ stopWith(out, hinted `push was rejected: ${push.stderr.trim()}\n${branch} is restacked locally and the base record is unchanged\nrun again: ${commandHint(RESTACK_PATH)}`, 'git-unresolved');
84
+ }
85
+ }
86
+ const record = { branch: ontoBranch, sha: mergeBase(cwd, 'HEAD', `${remote}/${ontoBranch}`) ?? progress.ontoSha, stackedOn: progress.stackedOn };
87
+ writeBaseRecord(record);
88
+ removeFlag(FLAG_PECOT_RESTACK);
89
+ out.result({ branch, base: ontoBranch, outcome: isSynced ? 'synced' : 'restacked', ...!isSynced && { pushed: leaseSha !== undefined } });
90
+ out.done({ verb: 'update', target: isSynced ? `${branch} synced with ${remoteBranch}` : `${branch} restacked on ${ontoBranch}` });
91
+ }
92
+ // --continue と --abort。途中の記録だけを読む。記録が無ければ、利用者が始めた rebase を動かさずに止まる
93
+ function resumeRestack(out, cwd, mode, isDryRun) {
94
+ const reading = interpretRestackProgress(readFlag(FLAG_PECOT_RESTACK));
95
+ if (reading.kind === 'malformed')
96
+ stopWith(out, `.pecot-restack is malformed: ${reading.content}`, 'content-invalid');
97
+ const isRebasing = isRebaseInProgress(cwd);
98
+ // 利用者が自分で rebase を終えていれば、続行は残りの手順(push と記録の書き直し)だけを行う
99
+ const isRebased = reading.kind === 'progress' && !isRebasing && mode === 'continue'
100
+ && currentBranch(cwd) === reading.progress.branch && mergeBase(cwd, 'HEAD', reading.progress.ontoSha) === reading.progress.ontoSha;
101
+ if (reading.kind === 'none' || (!isRebasing && !isRebased)) {
102
+ if (!isDryRun)
103
+ removeFlag(FLAG_PECOT_RESTACK);
104
+ return stopWith(out, hinted `no restack in progress\nto restack the branch, run: ${commandHint(RESTACK_PATH)}`, 'invalid-input', USAGE_EXIT_CODE);
105
+ }
106
+ const { progress } = reading;
107
+ if (isDryRun) {
108
+ out.result({ branch: progress.branch, base: progress.ontoBranch, outcome: mode === 'abort' ? 'aborted' : 'restacked' });
109
+ out.planned(mode === 'abort' ? { verb: 'unchanged', target: `${progress.branch} restack aborted` } : { verb: 'update', target: `${progress.branch} restacked on ${progress.ontoBranch}` });
110
+ return;
111
+ }
112
+ if (mode === 'abort') {
113
+ abortRebase(cwd);
114
+ removeFlag(FLAG_PECOT_RESTACK);
115
+ out.result({ branch: progress.branch, base: progress.ontoBranch, outcome: 'aborted' });
116
+ out.done({ verb: 'unchanged', target: `${progress.branch} restack aborted` });
117
+ return;
118
+ }
119
+ if (isRebasing && continueRebase(cwd) === 'conflict')
120
+ stopOnConflict(out, cwd, progress);
121
+ finishRestack(out, cwd, progress);
122
+ }
123
+ function currentBranch(cwd) {
124
+ return gitStdout(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd })?.trim();
125
+ }
126
+ function hasUncommittedChanges(cwd) {
127
+ return (gitStdout(['status', '--porcelain', '--untracked-files=no'], { cwd }) ?? '').trim() !== '';
128
+ }
129
+ // 下の段の PR と、remote の先頭を読んで、載せ直す先を決める
130
+ async function decideFor(out, cwd, host, target) {
131
+ const { remote, owner, repository, developBranch } = target;
132
+ const { record } = target.reading;
133
+ let lowerPullRequest;
134
+ try {
135
+ const found = await createGitHubClient(out, host).listPullRequestsByHead(owner, repository, record.branch);
136
+ lowerPullRequest = pickLowerPullRequest(found.pullRequests);
137
+ }
138
+ catch (error) {
139
+ if (error instanceof GitHubAPIError)
140
+ return stopWith(out, `cannot read the PR of the base branch ${record.branch}: ${describeApiError(error)}`, kindOfFailure(error));
141
+ throw error;
142
+ }
143
+ const lowerHead = remoteBranchHead(cwd, remote, record.branch);
144
+ return lowerHead.isReachable ? decideRestack({ reading: target.reading, developBranch, lowerPullRequest, lowerHead: lowerHead.sha }) : stopWith(out, `cannot reach ${remote} to read the base branch ${record.branch}`, 'git-unresolved');
145
+ }
146
+ // 載せ直す先の ref と SHA。開発ブランチへ載せ直すときは、積んだ先を記録から外す
147
+ function progressOf(out, cwd, branch, target, decision) {
148
+ const { remote } = target;
149
+ const { record } = target.reading;
150
+ const ontoSha = resolveCommit(cwd, `${remote}/${decision.base}`);
151
+ const originalSha = resolveCommit(cwd, 'HEAD');
152
+ if (ontoSha === undefined || originalSha === undefined)
153
+ return stopWith(out, `branch ${remote}/${decision.base} does not exist\ncheck the remote branches with: git branch -r`, 'git-unresolved');
154
+ return { remote, branch, originalSha, ontoBranch: decision.base, ontoSha, leaseSha: resolveCommit(cwd, `${remote}/${branch}`), stackedOn: decision.kind === 'moved' ? record.stackedOn : undefined };
155
+ }
156
+ async function runRestack(input, io) {
157
+ const out = createOutput(input.dry_run, io);
158
+ const modes = [input.check, input.continue, input.abort].filter(Boolean).length;
159
+ if (modes > 1)
160
+ stopWith(out, 'give only one of check, continue and abort', 'invalid-input', USAGE_EXIT_CODE);
161
+ const cwd = '.';
162
+ if (input.continue || input.abort) {
163
+ resumeRestack(out, cwd, input.abort ? 'abort' : 'continue', input.dry_run);
164
+ return;
165
+ }
166
+ const { currentBranch: branch, remoteName: remote, location } = validatePullRequestContext(cwd, out);
167
+ if (isRebaseInProgress(cwd)) {
168
+ stopWith(out, hinted `a rebase is in progress\ncontinue the restack: ${commandHint(RESTACK_PATH, { continue: true })}\nor abort it: ${commandHint(RESTACK_PATH, { abort: true })}`, 'invalid-input', USAGE_EXIT_CODE);
169
+ }
170
+ const reading = readBaseRecord();
171
+ stopOnMalformedRecord(reading, out);
172
+ const config = requireActiveConfigPlain(out);
173
+ const developBranch = getDevelopBranch(config, location.owner, location.repository);
174
+ if (developBranch === undefined || developBranch === '')
175
+ return stopWith(out, `develop_branch is not set for ${location.owner}/${location.repository}`, 'repo-setting-missing');
176
+ if (reading.kind !== 'stacked') {
177
+ out.result({ branch, base: developBranch, outcome: 'up-to-date' });
178
+ if (input.check)
179
+ out.data(describeRestackCheck(branch, { kind: 'not-stacked', base: developBranch }));
180
+ else
181
+ out.done({ verb: 'unchanged', target: `${branch} is up to date` });
182
+ return;
183
+ }
184
+ if (!input.check && hasUncommittedChanges(cwd))
185
+ stopWith(out, 'working tree has uncommitted changes', 'preflight-failed', UNCOMMITTED_EXIT_CODE);
186
+ const fetched = fetchRemote(cwd, remote);
187
+ if (!fetched.succeeded)
188
+ stopWith(out, `cannot fetch ${remote}: ${fetched.stderr.trim()}`, 'git-unresolved');
189
+ const target = { remote, owner: location.owner, repository: location.repository, reading, developBranch };
190
+ const decision = await decideFor(out, cwd, config.host, target);
191
+ if (decision.kind === 'gone')
192
+ return stopWith(out, describeGone(decision), 'pr-state');
193
+ if (input.check) {
194
+ const isNeeded = decision.kind === 'moved' || decision.kind === 'merged';
195
+ out.result({ branch, base: decision.base, outcome: isNeeded ? 'needs-restack' : 'up-to-date', ...causeOf(decision) });
196
+ out.data(describeRestackCheck(branch, decision));
197
+ return;
198
+ }
199
+ if (decision.kind !== 'moved' && decision.kind !== 'merged') {
200
+ out.result({ branch, base: decision.base, outcome: 'up-to-date' });
201
+ out.done({ verb: 'unchanged', target: `${branch} is up to date` });
202
+ return;
203
+ }
204
+ const progress = progressOf(out, cwd, branch, target, decision);
205
+ if (input.dry_run) {
206
+ out.result({ branch, base: decision.base, outcome: 'needs-restack', ...causeOf(decision) });
207
+ out.planned({ verb: 'update', target: `${branch} restacked on ${decision.base}` });
208
+ return;
209
+ }
210
+ if (rebaseOnto(cwd, progress.ontoSha, reading.record.sha) === 'conflict') {
211
+ writeFlag(FLAG_PECOT_RESTACK, formatRestackProgress(progress));
212
+ stopOnConflict(out, cwd, progress);
213
+ }
214
+ finishRestack(out, cwd, progress);
215
+ }
216
+ const prRestack = defineCommand({
217
+ path: RESTACK_PATH,
218
+ description: 'Restack the current branch onto the new position of its base branch',
219
+ input: RestackInputSchema,
220
+ output: PR_RESTACK_OUTPUT,
221
+ positional: [],
222
+ shortFlags: { dry_run: '-n' },
223
+ interactive: false,
224
+ run: async (input, io) => {
225
+ await runRestack(input, io);
226
+ return 0;
227
+ },
228
+ });
229
+ /**
230
+ pr restack。pr のグループの最後に並ぶ
231
+ */
232
+ export const PR_RESTACK_COMMANDS = [prRestack];
233
+ //# sourceMappingURL=pr-restack.js.map
@@ -0,0 +1,59 @@
1
+ import type { ProjectConfig } from '../domain/config.js';
2
+ import type { Prerequisite } from '../domain/readiness.js';
3
+ import type { IssueReference } from '../domain/reference-parser.js';
4
+ import type { RepositoryReference } from '../domain/repository-resolver.js';
5
+ import type { GitHubClient } from '../infra/github/index.js';
6
+ import type { BoardContext, JudgedTarget } from './board-judgment.js';
7
+ import type { HintedText } from './command-hint.js';
8
+ import type { BoardMoveLine } from './issue-board.js';
9
+ import type { JudgedIssue, ReadinessCache } from './issue-readiness.js';
10
+ import type { Output } from './output.js';
11
+ export interface CreatedPullRequest {
12
+ readonly repository: RepositoryReference;
13
+ /**
14
+ head ブランチの末尾の番号の Issue
15
+ */
16
+ readonly issueNumber: number;
17
+ /**
18
+ 作った PR の番号。応答に無ければ undefined(読み直しの確かめを省く)
19
+ */
20
+ readonly pullRequest: number | undefined;
21
+ }
22
+ /**
23
+ 待つ Issue の判定に、呼ぶ側の変化(作った PR・閉じた Issue)が出ているかの確かめ方
24
+ */
25
+ export interface WaitingCheck {
26
+ readonly isReflected: (judged: JudgedIssue) => boolean;
27
+ /**
28
+ 読み直しても出ないときの warning の文。name は待つ Issue の表記
29
+ */
30
+ readonly unconfirmed: (name: string) => HintedText;
31
+ /**
32
+ 列と札を動かす前に、判定を置き換える
33
+ */
34
+ readonly assume?: (judged: JudgedTarget) => Promise<JudgedTarget>;
35
+ }
36
+ export interface WaitingOptions {
37
+ /**
38
+ 待たれている Issue。並びの順に読む
39
+ */
40
+ readonly heads: readonly IssueReference[];
41
+ readonly check: WaitingCheck;
42
+ readonly isDryRun: boolean;
43
+ readonly cache: ReadinessCache;
44
+ }
45
+ /**
46
+ 判定の前提のうち、issue の前提
47
+ */
48
+ export declare function prerequisiteOf(judged: JudgedIssue, issue: IssueReference): Prerequisite | undefined;
49
+ /**
50
+ heads を待つ Issue を読み、判定に合わせてボードの列と札を動かす。読むのは、待つ Issue のボードの項目だけ。
51
+ 動かした列と札を moves に足していき、確かめた判定(assume の後)を返す。途中で例外が出ても、書けた分は moves に残る
52
+ */
53
+ export declare function moveIssuesWaitingFor(context: Readonly<BoardContext>, options: WaitingOptions, moves?: BoardMoveLine[]): Promise<readonly JudgedTarget[]>;
54
+ /**
55
+ pr create の後に、head の Issue を待つ Issue の列と札を動かす。作った PR が判定に出るまで 1 回だけ読み直す。
56
+ 動かした列と札(moved: と set: の行の値)を moves に足していき、それを返す
57
+ */
58
+ export declare function moveWaitingIssues(out: Readonly<Output>, client: GitHubClient, config: ProjectConfig, created: CreatedPullRequest, moves?: BoardMoveLine[]): Promise<readonly BoardMoveLine[]>;
59
+ //# sourceMappingURL=pr-waiting.d.ts.map
@@ -0,0 +1,143 @@
1
+ /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- 引数の型は readonly にできない */
2
+ // pr create と session finish の後に、head の Issue を待つ Issue(blocking)の列と札を、判定で動かす。
3
+ // どの失敗も warning にとどめ、終了コードを変えない。
4
+ import { setTimeout as delay } from 'node:timers/promises';
5
+ import { homeRepositoryOf, workflowFieldName } from '../domain/config.js';
6
+ import { boardItemKey } from '../domain/format.js';
7
+ import { displayReference } from '../domain/readiness.js';
8
+ import { createIssueReference, issueReferenceKey } from '../domain/reference-parser.js';
9
+ import { DependenciesUnsupportedError, GitHubNotFoundError } from '../infra/github/errors.js';
10
+ import { applyJudgedMoves, judgeBoard, SYNCED_COLUMNS } from './board-judgment.js';
11
+ import { mapWithLimit } from './board-view.js';
12
+ import { commandHint, hinted } from './command-hint.js';
13
+ import { apiFailureMessage } from './github-client.js';
14
+ import { createReadinessCache } from './issue-readiness.js';
15
+ // GitHub は書いた直後の読み取りの一致を保証しない。読み直す前に、反映を待つ時間
16
+ const RECHECK_DELAY_MILLISECONDS = 1500;
17
+ const READ_MAX_WORKERS = 8;
18
+ /**
19
+ 判定の前提のうち、issue の前提
20
+ */
21
+ export function prerequisiteOf(judged, issue) {
22
+ const key = issueReferenceKey(issue);
23
+ return judged.prerequisites.find(({ issue: other }) => issueReferenceKey(other.ref) === key);
24
+ }
25
+ function isConfirmed(judged, waiting) {
26
+ return judged.result.kind !== 'judged' || waiting.options.check.isReflected(judged.result);
27
+ }
28
+ async function judgeKeys(waiting, items, keys) {
29
+ const { context: { client, config }, options: { cache } } = waiting;
30
+ return await judgeBoard(client, config, items, new Map(), { columns: SYNCED_COLUMNS, withoutRead: target => (keys.has(target.key) ? undefined : 'skip'), cache });
31
+ }
32
+ // 変化が判定に出ていない分を、少し待ってから 1 回だけ読み直す
33
+ async function judgeConfirmed(waiting, items) {
34
+ const first = await judgeKeys(waiting, items, new Set(items.flatMap(item => boardItemKey(item) ?? [])));
35
+ if (first === undefined)
36
+ return undefined;
37
+ const stale = new Set(first.filter(judged => !isConfirmed(judged, waiting)).map(judged => judged.target.key));
38
+ if (stale.size > 0)
39
+ await delay(RECHECK_DELAY_MILLISECONDS);
40
+ const second = stale.size === 0 ? [] : await judgeKeys(waiting, items, stale);
41
+ if (second === undefined)
42
+ return undefined;
43
+ const latest = [...first.filter(judged => !stale.has(judged.target.key)), ...second];
44
+ return { confirmed: latest.filter(judged => isConfirmed(judged, waiting)), unconfirmed: latest.filter(judged => !isConfirmed(judged, waiting)) };
45
+ }
46
+ // head の Issue が PR のリポに無いとき(集約リポの運用・番号が Issue でないブランチ)と、依存関係に対応しない GHES では、何も出さない
47
+ async function readWaitingIssues(context, head) {
48
+ const { out, client, home } = context;
49
+ const name = displayReference(head, home);
50
+ const failed = `could not read the Issues waiting for ${name}`;
51
+ let read;
52
+ try {
53
+ read = await client.getIssueBlockingReferences(head.repository.owner, head.repository.repository, head.number);
54
+ }
55
+ catch (error) {
56
+ if (error instanceof DependenciesUnsupportedError || error instanceof GitHubNotFoundError)
57
+ return undefined;
58
+ out.warning(`${failed}: ${apiFailureMessage(error)}`);
59
+ return undefined;
60
+ }
61
+ if (read.kind === 'read-failed') {
62
+ out.warning(`${failed}: ${read.reason}`);
63
+ return undefined;
64
+ }
65
+ const partial = read.total > read.issues.length ? `read ${String(read.issues.length)} of ${String(read.total)} Issues waiting for ${name}; the rest were not moved` : undefined;
66
+ return { issues: read.issues, partial };
67
+ }
68
+ // 待つ Issue のうち、開いていてボードに載っているものの項目だけを読む
69
+ async function readBoardItems(waiting, issues) {
70
+ const { client, config } = waiting.context;
71
+ const field = workflowFieldName(config);
72
+ const open = issues.filter(issue => issue.state === 'OPEN');
73
+ const items = await mapWithLimit(open, READ_MAX_WORKERS, async ({ repository, number }) => await client.getIssueBoardItem(config.project.id, repository.owner, repository.repository, number, field));
74
+ return items.flatMap(item => item ?? []);
75
+ }
76
+ async function moveWaiting(waiting, issues, moves) {
77
+ const { context, options } = waiting;
78
+ const items = await readBoardItems(waiting, issues);
79
+ if (items.length === 0)
80
+ return [];
81
+ const judged = await judgeConfirmed(waiting, items);
82
+ if (judged === undefined)
83
+ return [];
84
+ const { assume } = options.check;
85
+ const confirmed = assume === undefined ? judged.confirmed : await Promise.all(judged.confirmed.map(async (target) => await assume(target)));
86
+ await applyJudgedMoves(context, confirmed, options.isDryRun, moves);
87
+ for (const { target } of judged.unconfirmed)
88
+ context.out.warning(options.check.unconfirmed(displayReference(target.ref, context.home)));
89
+ return confirmed;
90
+ }
91
+ function uniqueIssues(issues) {
92
+ const seen = new Set();
93
+ return issues.filter((issue) => {
94
+ const key = issueReferenceKey(createIssueReference(issue.repository, issue.number));
95
+ if (seen.has(key))
96
+ return false;
97
+ seen.add(key);
98
+ return true;
99
+ });
100
+ }
101
+ /**
102
+ heads を待つ Issue を読み、判定に合わせてボードの列と札を動かす。読むのは、待つ Issue のボードの項目だけ。
103
+ 動かした列と札を moves に足していき、確かめた判定(assume の後)を返す。途中で例外が出ても、書けた分は moves に残る
104
+ */
105
+ export async function moveIssuesWaitingFor(context, options, moves = []) {
106
+ const waiting = { context, options };
107
+ const reads = [];
108
+ for (const head of options.heads) {
109
+ const read = await readWaitingIssues(context, head);
110
+ if (read !== undefined)
111
+ reads.push(read);
112
+ }
113
+ const issues = uniqueIssues(reads.flatMap(read => read.issues));
114
+ let judged = [];
115
+ try {
116
+ if (issues.length > 0)
117
+ judged = await moveWaiting(waiting, issues, moves);
118
+ }
119
+ catch (error) {
120
+ const names = options.heads.map(head => displayReference(head, context.home)).join(', ');
121
+ context.out.warning(`could not move the Issues waiting for ${names}: ${apiFailureMessage(error)}`);
122
+ }
123
+ for (const { partial } of reads) {
124
+ if (partial !== undefined)
125
+ context.out.warning(partial);
126
+ }
127
+ return judged;
128
+ }
129
+ /**
130
+ pr create の後に、head の Issue を待つ Issue の列と札を動かす。作った PR が判定に出るまで 1 回だけ読み直す。
131
+ 動かした列と札(moved: と set: の行の値)を moves に足していき、それを返す
132
+ */
133
+ export async function moveWaitingIssues(out, client, config, created, moves = []) {
134
+ const context = { out, client, config, home: homeRepositoryOf(config) };
135
+ const head = createIssueReference(created.repository, created.issueNumber);
136
+ const check = {
137
+ isReflected: judged => created.pullRequest === undefined || (prerequisiteOf(judged, head)?.issue.pullRequests.some(pullRequest => pullRequest.number === created.pullRequest) ?? false),
138
+ unconfirmed: name => hinted `could not confirm that GitHub reflects PR #${String(created.pullRequest)} in the readiness of ${name}; its column was not moved; run ${commandHint(['board', 'sync'])} later to move it`,
139
+ };
140
+ await moveIssuesWaitingFor(context, { heads: [head], check, isDryRun: false, cache: createReadinessCache() }, moves);
141
+ return moves;
142
+ }
143
+ //# sourceMappingURL=pr-waiting.js.map
@@ -1,3 +1,26 @@
1
+ import type { RemoteLocation } from '../domain/git-url.js';
2
+ import type { BaseReading } from '../domain/state.js';
3
+ import type { Output } from './output.js';
1
4
  import type { CommandDefinition } from './command-definition.js';
5
+ export { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
6
+ export declare function reasonOf(error: unknown): string;
7
+ export declare function isPositive(value: number | undefined): value is number;
8
+ export interface PrimaryRemote {
9
+ readonly name: string;
10
+ readonly url: string;
11
+ /**
12
+ URL が読めなければ undefined
13
+ */
14
+ readonly location: RemoteLocation | undefined;
15
+ }
16
+ export declare function primaryRemote(directory: string): PrimaryRemote | undefined;
17
+ interface PullRequestContext {
18
+ readonly remoteUrl: string;
19
+ readonly currentBranch: string;
20
+ readonly location: RemoteLocation;
21
+ readonly remoteName: string;
22
+ }
23
+ export declare function validatePullRequestContext(directory: string, out: Readonly<Output>): PullRequestContext;
24
+ export declare function stopOnMalformedRecord(reading: BaseReading, out: Readonly<Output>): void;
2
25
  export declare const PR_COMMANDS: readonly CommandDefinition[];
3
26
  //# sourceMappingURL=pr.d.ts.map