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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +5 -58
  3. package/cli/dist/commands/board-add.js +11 -1
  4. package/cli/dist/commands/board-judgment.d.ts +12 -3
  5. package/cli/dist/commands/board-judgment.js +12 -6
  6. package/cli/dist/commands/board-move.js +9 -1
  7. package/cli/dist/commands/board-readiness.d.ts +3 -3
  8. package/cli/dist/commands/board-show.js +5 -2
  9. package/cli/dist/commands/board-sync.js +14 -5
  10. package/cli/dist/commands/board-view.d.ts +94 -5
  11. package/cli/dist/commands/board-view.js +119 -17
  12. package/cli/dist/commands/branch.js +11 -17
  13. package/cli/dist/commands/command-definition.d.ts +19 -2
  14. package/cli/dist/commands/command-definition.js +9 -0
  15. package/cli/dist/commands/failure-kind.d.ts +1 -1
  16. package/cli/dist/commands/failure-kind.js +1 -0
  17. package/cli/dist/commands/issue-board.d.ts +31 -3
  18. package/cli/dist/commands/issue-board.js +28 -4
  19. package/cli/dist/commands/issue-comment.js +19 -2
  20. package/cli/dist/commands/issue-create.js +96 -17
  21. package/cli/dist/commands/issue-dependency.js +51 -14
  22. package/cli/dist/commands/issue-readiness.d.ts +30 -2
  23. package/cli/dist/commands/issue-readiness.js +35 -0
  24. package/cli/dist/commands/issue-reopen.js +18 -3
  25. package/cli/dist/commands/issue-shared.d.ts +11 -5
  26. package/cli/dist/commands/issue-shared.js +25 -6
  27. package/cli/dist/commands/issue-show.js +78 -8
  28. package/cli/dist/commands/names.d.ts +1 -1
  29. package/cli/dist/commands/names.js +3 -3
  30. package/cli/dist/commands/output.d.ts +18 -2
  31. package/cli/dist/commands/output.js +16 -3
  32. package/cli/dist/commands/pr-merge.d.ts +3 -0
  33. package/cli/dist/commands/pr-merge.js +225 -0
  34. package/cli/dist/commands/pr-reference.d.ts +8 -0
  35. package/cli/dist/commands/pr-reference.js +30 -0
  36. package/cli/dist/commands/pr-restack.d.ts +6 -0
  37. package/cli/dist/commands/pr-restack.js +231 -0
  38. package/cli/dist/commands/pr-waiting.d.ts +41 -2
  39. package/cli/dist/commands/pr-waiting.js +74 -37
  40. package/cli/dist/commands/pr.d.ts +10 -6
  41. package/cli/dist/commands/pr.js +214 -111
  42. package/cli/dist/commands/project-sync.d.ts +10 -2
  43. package/cli/dist/commands/project-sync.js +7 -6
  44. package/cli/dist/commands/project.js +174 -17
  45. package/cli/dist/commands/registry.js +2 -0
  46. package/cli/dist/commands/release.js +67 -18
  47. package/cli/dist/commands/renamed-commands.js +0 -1
  48. package/cli/dist/commands/repository-match.js +7 -2
  49. package/cli/dist/commands/restack-reading.d.ts +45 -0
  50. package/cli/dist/commands/restack-reading.js +29 -0
  51. package/cli/dist/commands/session-finish.js +132 -28
  52. package/cli/dist/commands/session-start.js +31 -60
  53. package/cli/dist/commands/session.js +119 -135
  54. package/cli/dist/commands/tracker-sync-dependabot.js +21 -4
  55. package/cli/dist/commands/tracker-sync-security.js +22 -4
  56. package/cli/dist/commands/tracker-sync.d.ts +30 -0
  57. package/cli/dist/commands/tracker-sync.js +15 -0
  58. package/cli/dist/commands/tracker.js +2 -0
  59. package/cli/dist/commands/work-target.d.ts +14 -9
  60. package/cli/dist/commands/work-target.js +19 -19
  61. package/cli/dist/commands/worktree.js +71 -5
  62. package/cli/dist/domain/branch-name.d.ts +7 -0
  63. package/cli/dist/domain/branch-name.js +23 -1
  64. package/cli/dist/domain/command-hint.d.ts +1 -1
  65. package/cli/dist/domain/issue-readout.d.ts +0 -4
  66. package/cli/dist/domain/pull-request.d.ts +20 -3
  67. package/cli/dist/domain/pull-request.js +25 -9
  68. package/cli/dist/domain/readiness.d.ts +17 -0
  69. package/cli/dist/domain/readiness.js +39 -2
  70. package/cli/dist/domain/restack.d.ts +66 -0
  71. package/cli/dist/domain/restack.js +57 -0
  72. package/cli/dist/domain/state.d.ts +41 -12
  73. package/cli/dist/domain/state.js +30 -14
  74. package/cli/dist/domain/work-start.d.ts +0 -4
  75. package/cli/dist/domain/work-start.js +0 -7
  76. package/cli/dist/infra/git.d.ts +69 -0
  77. package/cli/dist/infra/git.js +117 -0
  78. package/cli/dist/infra/github/pulls.d.ts +81 -2
  79. package/cli/dist/infra/github/pulls.js +116 -5
  80. package/cli/dist/infra/github/queries.d.ts +4 -1
  81. package/cli/dist/infra/github/queries.js +47 -32
  82. package/cli/dist/infra/github/readout.js +0 -33
  83. package/cli/dist/infra/paths.d.ts +1 -3
  84. package/cli/dist/infra/paths.js +2 -45
  85. package/cli/dist/infra/state-store.d.ts +3 -8
  86. package/cli/dist/infra/state-store.js +6 -24
  87. package/cli/dist/mcp/result.d.ts +63 -16
  88. package/cli/dist/mcp/result.js +106 -30
  89. package/cli/dist/mcp/server.js +37 -4
  90. package/cli/templates/comment/plan.md +2 -2
  91. package/cli/templates/comment/review-findings.md +3 -2
  92. package/cli/templates/issue/bug.md +13 -4
  93. package/cli/templates/issue/task.md +13 -4
  94. package/cli/templates/workflow/pecot-board-sync.yml +3 -2
  95. package/npm-shrinkwrap.json +2 -2
  96. package/package.json +1 -1
@@ -22,7 +22,8 @@ import { commandHint, hinted, inputHint, inputNameHint, placeholder } from './co
22
22
  import { NO_ACTIVE_PROJECT, stopWith } from './command-stop.js';
23
23
  import { kindOfFailure } from './failure.js';
24
24
  import { createGitHubClient, makeClient } from './github-client.js';
25
- import { createOutput } from './output.js';
25
+ import { issuePath } from './issue-shared.js';
26
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
26
27
  import { CommandExit, defineCommand } from './command-definition.js';
27
28
  import { requireRepositoryMatch } from './repository-match.js';
28
29
  import { USAGE_EXIT_CODE } from './usage-error.js';
@@ -80,8 +81,8 @@ function warnAlertsUnavailable(out, reason) {
80
81
  const [first = ''] = reason.trim().split(/\r\n|[\n\r]/u, 1);
81
82
  out.warning(`could not check Dependabot alerts. The release is not blocked.\nreason: ${first.trim().replace(/\.+$/u, '').trimEnd()}`);
82
83
  }
83
- // open の Dependabot alert は警告だけで、リリースを止めない
84
- async function checkDependabotAlerts(out, config, owner, repository) {
84
+ // open の Dependabot alert は警告だけで、リリースを止めない。読めた状態を返し、読めなければ undefined
85
+ async function checkDependabotAlerts(out, config, owner, repository, skip) {
85
86
  let status;
86
87
  try {
87
88
  const client = createGitHubClient(out, config.host);
@@ -90,31 +91,32 @@ async function checkDependabotAlerts(out, config, owner, repository) {
90
91
  catch (error) {
91
92
  if (error instanceof DependabotAlertError) {
92
93
  warnAlertsUnavailable(out, error.message);
93
- return;
94
+ return undefined;
94
95
  }
95
96
  if (error instanceof GitHubAPIError) {
96
97
  warnAlertsUnavailable(out, error.message);
97
- return;
98
+ return undefined;
98
99
  }
99
100
  throw error;
100
101
  }
101
102
  if (!status.enabled) {
102
- out.done({ verb: 'skip', target: 'Dependabot alerts (feature disabled)', aside: true });
103
- return;
103
+ skip('Dependabot alerts (feature disabled)');
104
+ return status;
104
105
  }
105
106
  if (status.openCount === 0) {
106
107
  out.count('open Dependabot alerts', 0);
107
- return;
108
+ return status;
108
109
  }
109
110
  const severity = status.maxSeverity === undefined ? '' : ` (highest severity: ${status.maxSeverity})`;
110
111
  const listing = status.openAlerts.map(alert => `\n${alertLabel(alert.number, alert.package, alert.severity)}`).join('');
111
112
  const noun = status.openCount === 1 ? 'alert' : 'alerts';
112
113
  out.warning(`${String(status.openCount)} open Dependabot ${noun}${severity}. The release is not blocked.${listing}\n→ ${status.alertsUrl}`);
114
+ return status;
113
115
  }
114
116
  /**
115
117
  code scanning・secret scanning の open の alert があれば、false を返す。機能が無効のリポジトリは通る
116
118
  */
117
- async function isScanningPassed(out, name, fetchStatus) {
119
+ async function isScanningPassed(out, name, fetchStatus, skip) {
118
120
  let status;
119
121
  try {
120
122
  status = await fetchStatus();
@@ -126,7 +128,7 @@ async function isScanningPassed(out, name, fetchStatus) {
126
128
  return false;
127
129
  }
128
130
  if (!status.enabled) {
129
- out.done({ verb: 'skip', target: `${name} (feature disabled)`, aside: true });
131
+ skip(`${name} (feature disabled)`);
130
132
  return true;
131
133
  }
132
134
  if (status.openCount === 0) {
@@ -140,14 +142,20 @@ async function isScanningPassed(out, name, fetchStatus) {
140
142
  /**
141
143
  3 種を確かめる。1 つが失敗しても残りを続け、最後に成否を返す
142
144
  */
143
- async function areAlertsPassed(out, config, owner, repository) {
145
+ async function checkAlerts(out, config, owner, repository) {
146
+ const skipped = [];
147
+ const skip = (target) => {
148
+ out.done({ verb: 'skip', target, aside: true });
149
+ skipped.push(target);
150
+ };
151
+ let dependabot;
144
152
  const checks = [
145
153
  async () => {
146
- await checkDependabotAlerts(out, config, owner, repository);
154
+ dependabot = await checkDependabotAlerts(out, config, owner, repository, skip);
147
155
  return true;
148
156
  },
149
- async () => await isScanningPassed(out, 'code scanning', async () => await fetchCodeScanningStatus(createScanAlertSource(createGitHubClient(out, config.host)), config.host, owner, repository)),
150
- async () => await isScanningPassed(out, 'secret scanning', async () => await fetchSecretScanningStatus(createScanAlertSource(createGitHubClient(out, config.host)), config.host, owner, repository)),
157
+ async () => await isScanningPassed(out, 'code scanning', async () => await fetchCodeScanningStatus(createScanAlertSource(createGitHubClient(out, config.host)), config.host, owner, repository), skip),
158
+ async () => await isScanningPassed(out, 'secret scanning', async () => await fetchSecretScanningStatus(createScanAlertSource(createGitHubClient(out, config.host)), config.host, owner, repository), skip),
151
159
  ];
152
160
  let isPassed = true;
153
161
  for (const check of checks) {
@@ -162,8 +170,21 @@ async function areAlertsPassed(out, config, owner, repository) {
162
170
  isPassed = false;
163
171
  }
164
172
  }
165
- return isPassed;
173
+ return { isPassed, skipped, dependabot };
166
174
  }
175
+ const RELEASE_CHECK_OUTPUT = z.strictObject({
176
+ version: z.string().optional().describe('Version to release (omitted when release_type is nx, where only the alerts are checked)'),
177
+ tag: z.string().optional().describe('Tag to create (omitted when release_type is nx)'),
178
+ releaseNotes: z.string().optional().describe('Release notes from the CHANGELOG (omitted when release_type is nx)'),
179
+ commitCount: z.int().optional().describe('Number of commits from the release branch to the develop branch (omitted when release_type is nx)'),
180
+ skipped: z.array(z.string()).describe('Checks skipped because the feature is disabled, as in the skipped lines (e.g. "Dependabot alerts (feature disabled)")'),
181
+ dependabotAlerts: z.strictObject({
182
+ enabled: z.boolean().describe('Whether Dependabot alerts are enabled'),
183
+ openCount: z.int().describe('Number of open alerts (0 when disabled)'),
184
+ maxSeverity: z.string().optional().describe('Highest severity of the open alerts (omitted when there is none)'),
185
+ alertsUrl: z.string().describe('URL of the alert list'),
186
+ }).optional().describe('Dependabot alert status (omitted when it could not be read; the release is not blocked)'),
187
+ });
167
188
  const releaseCheckCommand = defineCommand({
168
189
  path: CHECK_PATH,
169
190
  description: 'Run the pre-release checks; for an nx repository only the alerts are checked',
@@ -171,6 +192,7 @@ const releaseCheckCommand = defineCommand({
171
192
  version: z.string().optional().describe('Release version (detected from the CHANGELOG when omitted)'),
172
193
  package: z.string().optional().describe('Package name in a monorepo (required for repositories with packages configured)'),
173
194
  }),
195
+ output: RELEASE_CHECK_OUTPUT,
174
196
  positional: ['version'],
175
197
  interactive: false,
176
198
  run: async (input, io) => {
@@ -179,8 +201,13 @@ const releaseCheckCommand = defineCommand({
179
201
  const cwd = process.cwd();
180
202
  const context = loadReleaseContext(out, adopted, input.repo, input.package, { version: input.version, nxAlertsOnly: true });
181
203
  const { config, owner, repository } = context;
182
- const isAlertsPassed = await areAlertsPassed(out, config, owner, repository);
183
- if (!isAlertsPassed)
204
+ const alerts = await checkAlerts(out, config, owner, repository);
205
+ const { dependabot } = alerts;
206
+ out.result({
207
+ skipped: [...alerts.skipped],
208
+ ...dependabot !== undefined && { dependabotAlerts: { enabled: dependabot.enabled, openCount: dependabot.openCount, ...dependabot.maxSeverity !== undefined && { maxSeverity: dependabot.maxSeverity }, alertsUrl: dependabot.alertsUrl } },
209
+ });
210
+ if (!alerts.isPassed)
184
211
  throw new CommandExit(1, 'preflight-failed');
185
212
  if (context.repositoryConfig !== undefined && effectiveReleaseType(context.repositoryConfig) === 'nx')
186
213
  return 0;
@@ -199,6 +226,7 @@ const releaseCheckCommand = defineCommand({
199
226
  remote,
200
227
  }, gitRunnerFor(cwd), async (base, head) => await client.countCommitsAhead(owner, repository, base, head));
201
228
  out.count(`commits to release (${remote}/${result.developBranch} -> ${remote}/${result.releaseBranch})`, result.diffCount);
229
+ out.result({ version: result.version, tag: result.tagName, releaseNotes: result.releaseNotes, commitCount: result.diffCount });
202
230
  out.data(`version: ${result.version}\ntag: ${result.tagName}\n\n${result.releaseNotes}`);
203
231
  return 0;
204
232
  }
@@ -212,6 +240,12 @@ const releaseCheckCommand = defineCommand({
212
240
  }
213
241
  },
214
242
  });
243
+ const RELEASE_CREATE_OUTPUT = z.strictObject({
244
+ tag: z.string().describe('Tag of the release'),
245
+ url: z.string().optional().describe('URL of the created release (omitted on dry_run)'),
246
+ releaseNotes: z.string().describe('Release notes from the CHANGELOG'),
247
+ dryRun: DRY_RUN_FIELD,
248
+ });
215
249
  const releaseCreateCommand = defineCommand({
216
250
  path: ['release', 'create'],
217
251
  description: 'Create a GitHub release and its tag (the release notes come from the CHANGELOG)',
@@ -220,6 +254,7 @@ const releaseCreateCommand = defineCommand({
220
254
  dry_run: z.boolean().default(false).describe('Show what would happen without changing anything'),
221
255
  package: z.string().optional().describe('Package name in a monorepo (required for repositories with packages configured)'),
222
256
  }),
257
+ output: RELEASE_CREATE_OUTPUT,
223
258
  positional: ['version'],
224
259
  interactive: false,
225
260
  run: async (input, io) => {
@@ -250,6 +285,7 @@ const releaseCreateCommand = defineCommand({
250
285
  const operation = { verb: 'create', target: `release ${tagName} on ${releaseBranch}` };
251
286
  if (input.dry_run) {
252
287
  out.planned(operation);
288
+ out.result({ tag: tagName, releaseNotes });
253
289
  out.data(releaseNotes);
254
290
  return 0;
255
291
  }
@@ -258,6 +294,7 @@ const releaseCreateCommand = defineCommand({
258
294
  const result = await client.createRelease(owner, repository, tagName, releaseName, releaseNotes, { targetCommitish: releaseBranch });
259
295
  out.done(operation);
260
296
  const url = result['html_url'];
297
+ out.result({ tag: tagName, releaseNotes, ...typeof url === 'string' && { url } });
261
298
  out.data(typeof url === 'string' ? url : '');
262
299
  return 0;
263
300
  }
@@ -268,6 +305,13 @@ const releaseCreateCommand = defineCommand({
268
305
  }
269
306
  },
270
307
  });
308
+ const RELEASE_MERGE_OUTPUT = z.strictObject({
309
+ pullRequest: z.string().describe('Release PR (owner/repo/N)'),
310
+ head: z.string().describe('Head branch of the PR'),
311
+ base: z.string().describe('Base branch of the PR (the release branch)'),
312
+ deletedBranch: z.boolean().describe('Whether the remote head branch was deleted (false without delete_branch, on dry_run, or when the deletion failed)'),
313
+ dryRun: DRY_RUN_FIELD,
314
+ });
271
315
  const releaseMergeCommand = defineCommand({
272
316
  path: ['release', 'merge'],
273
317
  description: 'Merge a release PR with a regular merge',
@@ -277,6 +321,7 @@ const releaseMergeCommand = defineCommand({
277
321
  delete_branch: z.boolean().default(false).describe('Delete the branch after merging'),
278
322
  admin: z.boolean().default(false).describe('Merge with admin rights (skip the mergeability check)'),
279
323
  }),
324
+ output: RELEASE_MERGE_OUTPUT,
280
325
  positional: ['pr_ref'],
281
326
  shortFlags: { dry_run: '-n', delete_branch: '-d' },
282
327
  interactive: false,
@@ -295,7 +340,7 @@ const releaseMergeCommand = defineCommand({
295
340
  }
296
341
  const { owner, repository } = reference.repository;
297
342
  const number = reference.number;
298
- const pullRequestName = `${owner}/${repository}/${String(number)}`;
343
+ const pullRequestName = issuePath(owner, repository, number);
299
344
  let client;
300
345
  let pullRequest;
301
346
  try {
@@ -322,8 +367,10 @@ const releaseMergeCommand = defineCommand({
322
367
  }
323
368
  const headBranch = pullRequest.head_ref;
324
369
  const operation = { verb: 'merge', target: `PR ${pullRequestName} (${headBranch} -> ${pullRequest.base_ref}, merge commit)` };
370
+ const merged = { pullRequest: pullRequestName, head: headBranch, base: pullRequest.base_ref, deletedBranch: false };
325
371
  if (input.dry_run) {
326
372
  out.planned(operation);
373
+ out.result(merged);
327
374
  return 0;
328
375
  }
329
376
  try {
@@ -335,10 +382,12 @@ const releaseMergeCommand = defineCommand({
335
382
  return stopWith(out, `could not merge PR ${pullRequestName}: ${describeApiError(error)}`, kindOfFailure(error));
336
383
  }
337
384
  out.done(operation);
385
+ out.result(merged);
338
386
  if (input.delete_branch) {
339
387
  try {
340
388
  await client.deleteBranch(owner, repository, headBranch);
341
389
  out.done({ verb: 'delete', target: `remote branch ${headBranch} in ${owner}/${repository}` });
390
+ out.result({ deletedBranch: true });
342
391
  }
343
392
  catch (error) {
344
393
  if (!(error instanceof GitHubAPIError))
@@ -31,7 +31,6 @@ export function findRenamedCommand(path) {
31
31
  }
32
32
  export const RENAMED_INPUTS = [
33
33
  { command: 'issue comment', oldName: 'issue', newName: 'issue_ref' },
34
- { command: 'session restore', oldName: 'issue', newName: 'issue_ref' },
35
34
  { command: 'branch delete', oldName: 'repo_ref', newName: 'repo' },
36
35
  { command: 'project link', oldName: 'owner_repo', newName: 'repo' },
37
36
  { command: 'session start', oldName: 'branch_name', newName: 'branch' },
@@ -5,6 +5,7 @@ import { applyRepositoryPolicy } from '../domain/repository-policy.js';
5
5
  import { AmbiguousRepositoryError, resolveRepository } from '../domain/repository-resolver.js';
6
6
  import { gitRunnerFor } from '../infra/git.js';
7
7
  import { CommandExit } from './command-definition.js';
8
+ import { WARNING_PREFIX } from './output.js';
8
9
  /**
9
10
  今の git remote からリポジトリを解決する。git の外・remote 無しは undefined
10
11
  */
@@ -25,8 +26,12 @@ export function resolveCurrentRepository(cwd) {
25
26
  */
26
27
  export function requireRepositoryMatch(mode, explicit, io, cwd) {
27
28
  const outcome = applyRepositoryPolicy({ explicit, resolved: resolveCurrentRepository(cwd), mode });
28
- for (const line of outcome.stderr)
29
- io.stderr(`${formatHinted(line, io.surface ?? 'cli')}\n`);
29
+ for (const line of outcome.stderr) {
30
+ const text = formatHinted(line, io.surface ?? 'cli');
31
+ io.stderr(`${text}\n`);
32
+ if (text.startsWith(WARNING_PREFIX))
33
+ io.warning?.(text.slice(WARNING_PREFIX.length));
34
+ }
30
35
  if (outcome.kind === 'exit')
31
36
  throw new CommandExit(outcome.exitCode, outcome.failure);
32
37
  return outcome.adopted;
@@ -0,0 +1,45 @@
1
+ import type { PullRequestReadout } from '../domain/issue-readout.js';
2
+ import type { RestackDecision } from '../domain/restack.js';
3
+ import type { BaseReading } from '../domain/state.js';
4
+ import { GitHubAPIError } from '../infra/github/errors.js';
5
+ import type { GitHubClient } from '../infra/github/index.js';
6
+ /**
7
+ 既に読んだ下の段の PR。PR が無かったことも示せるよう、包んで渡す
8
+ */
9
+ export interface KnownLowerPullRequest {
10
+ readonly pullRequest: PullRequestReadout | undefined;
11
+ }
12
+ export interface RestackTarget {
13
+ readonly client: () => Readonly<GitHubClient>;
14
+ readonly owner: string;
15
+ readonly repository: string;
16
+ readonly cwd: string;
17
+ /**
18
+ remote が無ければ undefined。そのときは remote に届かないのと同じに扱う
19
+ */
20
+ readonly remote: string | undefined;
21
+ readonly reading: Extract<BaseReading, {
22
+ kind: 'stacked';
23
+ }>;
24
+ readonly developBranch: string;
25
+ /**
26
+ 渡されたら、下の段の PR を読み直さない
27
+ */
28
+ readonly lowerPullRequest?: KnownLowerPullRequest | undefined;
29
+ }
30
+ export type RestackReading = {
31
+ readonly kind: 'decided';
32
+ readonly decision: RestackDecision;
33
+ readonly lowerPullRequest: PullRequestReadout | undefined;
34
+ } | {
35
+ readonly kind: 'remote-unreachable';
36
+ readonly lowerPullRequest: PullRequestReadout | undefined;
37
+ } | {
38
+ readonly kind: 'pull-request-unreadable';
39
+ readonly error: GitHubAPIError;
40
+ };
41
+ /**
42
+ 下の段の PR を読み、remote の先頭を尋ねて、載せ直す先を決める。PR を読めないか remote に届かなければ、その種類を返す
43
+ */
44
+ export declare function readRestackDecision(target: Readonly<RestackTarget>): Promise<RestackReading>;
45
+ //# sourceMappingURL=restack-reading.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { pickLowerPullRequest } from '../domain/pull-request.js';
2
+ import { decideRestack } from '../domain/restack.js';
3
+ import { remoteBranchHead } from '../infra/git.js';
4
+ import { GitHubAPIError } from '../infra/github/errors.js';
5
+ /**
6
+ 下の段の PR を読み、remote の先頭を尋ねて、載せ直す先を決める。PR を読めないか remote に届かなければ、その種類を返す
7
+ */
8
+ export async function readRestackDecision(target) {
9
+ const { reading, remote } = target;
10
+ let lowerPullRequest = target.lowerPullRequest?.pullRequest;
11
+ if (target.lowerPullRequest === undefined) {
12
+ try {
13
+ const found = await target.client().listPullRequestsByHead(target.owner, target.repository, reading.record.branch);
14
+ lowerPullRequest = pickLowerPullRequest(found.pullRequests);
15
+ }
16
+ catch (error) {
17
+ if (error instanceof GitHubAPIError)
18
+ return { kind: 'pull-request-unreadable', error };
19
+ throw error;
20
+ }
21
+ }
22
+ if (remote === undefined)
23
+ return { kind: 'remote-unreachable', lowerPullRequest };
24
+ const lowerHead = remoteBranchHead(target.cwd, remote, reading.record.branch);
25
+ return lowerHead.isReachable
26
+ ? { kind: 'decided', decision: decideRestack({ reading, developBranch: target.developBranch, lowerPullRequest, lowerHead: lowerHead.sha }), lowerPullRequest }
27
+ : { kind: 'remote-unreachable', lowerPullRequest };
28
+ }
29
+ //# sourceMappingURL=restack-reading.js.map
@@ -3,22 +3,54 @@
3
3
  import { z } from 'zod';
4
4
  import { describeApiError } from '../domain/api-error-detail.js';
5
5
  import { extractIssueNumberFromBranch } from '../domain/branch-name.js';
6
- import { getDevelopBranch } from '../domain/config.js';
6
+ import { getDevelopBranch, homeRepositoryOf } from '../domain/config.js';
7
7
  import { isEpicIssue } from '../domain/issue-kind.js';
8
8
  import { extractClosingIssueNumbers } from '../domain/pull-request.js';
9
- import { FLAG_MERGE_SLASH_PENDING, FLAG_PECOT_ACTIVE, FLAG_PECOT_BASE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE, FLAG_WIP_BRANCH_LINKED } from '../domain/state.js';
9
+ import { assumePullRequestState, describeReadinessChange, displayReference, hasReadinessChanged, isDone, isStackedOn } from '../domain/readiness.js';
10
+ import { createIssueReference } from '../domain/reference-parser.js';
11
+ import { RESTACK_PATH } from '../domain/restack.js';
12
+ import { FLAG_PECOT_BASE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE } from '../domain/state.js';
10
13
  import { gitCurrentBranch, GitCommandError, runGit } from '../infra/git.js';
11
14
  import { GitHubAPIError, GitHubNotFoundError, isClosedByAnotherRequest, isMissingReferenceError } from '../infra/github/errors.js';
12
15
  import { isFileNotFound } from '../infra/os-error.js';
13
- import { consumeFlag, removeFlag } from '../infra/state-store.js';
16
+ import { removeFlag } from '../infra/state-store.js';
14
17
  import { getCurrentWorktreeName, isWorktreeEnvironment } from '../infra/worktree.js';
18
+ import { commandHint, hinted } from './command-hint.js';
15
19
  import { requireActiveConfigPlain, stopWith } from './command-stop.js';
20
+ import { createReadinessCache, judgeAssuming } from './issue-readiness.js';
21
+ import { moveIssuesWaitingFor, prerequisiteOf } from './pr-waiting.js';
16
22
  import { kindOfFailure } from './failure.js';
17
23
  import { createGitHubClient } from './github-client.js';
18
- import { createOutput } from './output.js';
24
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
19
25
  import { defineCommand } from './command-definition.js';
20
26
  import { settle } from './tracker-sync.js';
21
27
  import { isPositive, parseReference, PR_REFERENCE_DESCRIPTION, primaryRemote, reasonOf } from './pr.js';
28
+ const SKIPPED_ISSUE_DATA = z.strictObject({
29
+ number: z.int().describe('Issue number'),
30
+ reason: z.enum(['epic', 'already-closed', 'not-found', 'failed']).describe('Why it was not closed: epic (protected), already-closed, not-found, or failed (see warnings)'),
31
+ });
32
+ const DELETED_BRANCH_DATA = z.strictObject({
33
+ branch: z.string().describe('Name of the branch'),
34
+ location: z.enum(['remote', 'local']).describe('Whether the remote or the local branch was deleted'),
35
+ });
36
+ const READINESS_CHANGE_DATA = z.strictObject({
37
+ issue: z.string().describe('Issue waiting for a closed Issue (#N, or owner/repo#N in another repository)'),
38
+ from: z.string().describe('Readiness before the merge (blocked, startable, or stackable on #N)'),
39
+ to: z.string().describe('Readiness after the merge (blocked, startable, or stackable on #N)'),
40
+ });
41
+ const RESTACK_DATA = z.strictObject({
42
+ issue: z.string().describe('Started Issue stacked on a closed Issue (#N, or owner/repo#N in another repository)'),
43
+ branch: z.string().optional().describe('Branch linked to that Issue, to restack in its working directory (omitted when none)'),
44
+ });
45
+ const SESSION_FINISH_OUTPUT = z.strictObject({
46
+ closedIssues: z.array(z.int()).describe('Issue numbers closed (to be closed on dry_run)'),
47
+ skippedIssues: z.array(SKIPPED_ISSUE_DATA).describe('Closing Issues of the PR that this command did not close'),
48
+ deletedBranches: z.array(DELETED_BRANCH_DATA).describe('Branches deleted (to be deleted on dry_run)'),
49
+ readinessChanges: z.array(READINESS_CHANGE_DATA).describe('Issues waiting for the closed Issues whose readiness changed by the merge'),
50
+ restack: z.array(RESTACK_DATA).describe('Upper stacked Issues to restack with pr restack in their working directories'),
51
+ currentBranch: z.string().optional().describe('Current branch after the local cleanup (omitted when the local cleanup was skipped)'),
52
+ dryRun: DRY_RUN_FIELD,
53
+ });
22
54
  async function fetchPullRequestForCleanup(config, location, out) {
23
55
  try {
24
56
  const client = createGitHubClient(out, config.host);
@@ -61,29 +93,37 @@ async function findEpicProtectedNumbers(client, location, issueNumbers, out) {
61
93
  return protectedNumbers;
62
94
  }
63
95
  async function closeRelatedIssues(context, client, location, closing, epicProtected) {
64
- const { out, isDryRun } = context;
96
+ const { out, isDryRun, record } = context;
65
97
  const protectedOrdered = [...epicProtected].toSorted((a, b) => a - b);
66
98
  const closingOrdered = [...closing].toSorted((a, b) => a - b);
67
- for (const number of protectedOrdered)
99
+ for (const number of protectedOrdered) {
68
100
  settle(out, { verb: 'skip', target: `closing Issue #${String(number)} (Epic)` });
101
+ record.skippedIssues.push({ number, reason: 'epic' });
102
+ }
69
103
  for (const number of closingOrdered) {
70
104
  const operation = { verb: 'close', target: `Issue #${String(number)}` };
71
105
  out.planned(operation);
72
- if (isDryRun)
106
+ if (isDryRun) {
107
+ record.closedIssues.push(number);
73
108
  continue;
109
+ }
74
110
  try {
75
111
  await client.closeIssue(location.owner, location.repository, number);
76
112
  out.done(operation);
113
+ record.closedIssues.push(number);
77
114
  }
78
115
  catch (error) {
79
116
  if (error instanceof GitHubNotFoundError) {
80
117
  out.warning(`Issue #${String(number)} not found; skipped`);
118
+ record.skippedIssues.push({ number, reason: 'not-found' });
81
119
  }
82
120
  else if (error instanceof GitHubAPIError) {
83
- if (isClosedByAnotherRequest(error))
121
+ const isClosed = isClosedByAnotherRequest(error);
122
+ if (isClosed)
84
123
  out.done({ verb: 'unchanged', target: `Issue #${String(number)} (already closed)` });
85
124
  else
86
125
  out.warning(`closing Issue #${String(number)} failed: ${describeApiError(error)}`);
126
+ record.skippedIssues.push({ number, reason: isClosed ? 'already-closed' : 'failed' });
87
127
  }
88
128
  else {
89
129
  throw error;
@@ -91,16 +131,75 @@ async function closeRelatedIssues(context, client, location, closing, epicProtec
91
131
  }
92
132
  }
93
133
  }
94
- // head ブランチを消し、続けて wip ブランチを消す。head が無くても wip は試す
134
+ function mergedPullRequestOf(location, number, pr) {
135
+ return { repository: location, number, state: 'merged', headRefName: pr.head_ref, baseRefName: pr.base_ref, isDraft: pr.is_draft, isCrossRepository: false };
136
+ }
137
+ // 閉じた Issue のうち、判定に出ている前提がすべて済んでいるか
138
+ function isClosedReflected(judged, heads) {
139
+ const found = heads.flatMap(head => prerequisiteOf(judged, head) ?? []);
140
+ return found.length > 0 && found.every(({ issue }) => isDone(issue));
141
+ }
142
+ function waitingCheck(source, heads, isDryRun, cache, home) {
143
+ const { client, config, pullRequest } = source;
144
+ const names = heads.map(head => displayReference(head, home)).join(', ');
145
+ const unconfirmed = (name) => hinted `could not confirm that GitHub reflects the close of ${names} in the readiness of ${name}; its column was not moved; run ${commandHint(['board', 'sync'])} later to move it`;
146
+ if (!isDryRun)
147
+ return { isReflected: judged => isClosedReflected(judged, heads), unconfirmed };
148
+ // dry-run では Issue を閉じていないので、閉じた後を置き換えで作る
149
+ return {
150
+ isReflected: () => true,
151
+ unconfirmed,
152
+ assume: async ({ target, result }) => (result.kind === 'judged'
153
+ ? { target, result: await judgeAssuming(client, config, result, prerequisites => assumePullRequestState(prerequisites, heads, pullRequest, 'merged'), cache) }
154
+ : { target, result }),
155
+ };
156
+ }
157
+ // 閉じた Issue を待つ Issue の列と札を動かし、マージの前と比べた判定の変化と、載せ直す上の段を記録する
158
+ async function updateWaitingIssues(context, source) {
159
+ const { out, isDryRun, record } = context;
160
+ const { client, config, location, pullRequest } = source;
161
+ const alreadyClosed = record.skippedIssues.filter(({ reason }) => reason === 'already-closed').map(({ number }) => number);
162
+ const heads = [...record.closedIssues, ...alreadyClosed].toSorted((a, b) => a - b).map(number => createIssueReference(location, number));
163
+ if (heads.length === 0)
164
+ return;
165
+ const home = homeRepositoryOf(config);
166
+ const cache = createReadinessCache();
167
+ const board = { out, client, config, home };
168
+ const judged = await moveIssuesWaitingFor(board, { heads, check: waitingCheck(source, heads, isDryRun, cache, home), isDryRun, cache });
169
+ for (const { target, result } of judged) {
170
+ if (result.kind !== 'judged' || result.readiness === undefined)
171
+ continue;
172
+ const before = await judgeAssuming(client, config, result, prerequisites => assumePullRequestState(prerequisites, heads, pullRequest, 'open'), cache);
173
+ if (before.kind !== 'judged' || before.readiness === undefined || !hasReadinessChanged(before.readiness, result.readiness))
174
+ continue;
175
+ const { repository } = target.ref;
176
+ record.readinessChanges.push({ issue: displayReference(target.ref, home), from: describeReadinessChange(before.readiness, repository), to: describeReadinessChange(result.readiness, repository) });
177
+ }
178
+ if (record.readinessChanges.length > 0)
179
+ out.data(['Readiness changed:', ...record.readinessChanges.map(change => `- ${change.issue} ${change.from} -> ${change.to}`)].join('\n'));
180
+ for (const { target, result } of judged) {
181
+ if (result.kind !== 'judged' || !isStackedOn(result.target, result.prerequisites, heads))
182
+ continue;
183
+ const name = displayReference(target.ref, home);
184
+ const lower = heads.filter(head => prerequisiteOf(result, head)?.wait === 'stack').map(head => displayReference(head, home)).join(', ');
185
+ const [branch] = result.target.branches;
186
+ record.restack.push({ issue: name, ...branch !== undefined && { branch } });
187
+ out.warning(hinted `${name} is stacked on ${lower}; run ${commandHint(RESTACK_PATH)} in the working directory of ${branch ?? 'its branch'}`);
188
+ }
189
+ }
190
+ // head ブランチを消す。無ければ unchanged、ほかの失敗は warning にして続ける
95
191
  async function deleteMergedBranch(context, client, location, headBranch) {
96
- const { out, isDryRun } = context;
192
+ const { out, isDryRun, record } = context;
97
193
  const operation = { verb: 'delete', target: `remote branch ${headBranch}` };
98
194
  out.planned(operation);
99
- if (isDryRun)
195
+ if (isDryRun) {
196
+ record.deletedBranches.push({ branch: headBranch, location: 'remote' });
100
197
  return;
198
+ }
101
199
  try {
102
200
  await client.deleteBranch(location.owner, location.repository, headBranch);
103
201
  out.done(operation);
202
+ record.deletedBranches.push({ branch: headBranch, location: 'remote' });
104
203
  }
105
204
  catch (error) {
106
205
  if (!(error instanceof GitHubAPIError))
@@ -111,17 +210,6 @@ async function deleteMergedBranch(context, client, location, headBranch) {
111
210
  }
112
211
  out.done({ verb: 'unchanged', target: `remote branch ${headBranch} (already deleted)` });
113
212
  }
114
- const wipBranch = `wip/${headBranch}`;
115
- try {
116
- await client.deleteBranch(location.owner, location.repository, wipBranch);
117
- out.done({ verb: 'delete', target: `remote branch ${wipBranch}` });
118
- }
119
- catch (error) {
120
- if (!(error instanceof GitHubAPIError))
121
- throw error;
122
- if (!isMissingReferenceError(error))
123
- out.warning(`deleting remote branch ${wipBranch} failed: ${describeApiError(error)}`);
124
- }
125
213
  }
126
214
  // 手元と PR の repository が同じなら主の remote 名。違えば警告を出して undefined
127
215
  function sameRepositoryRemote(cwd, location, out) {
@@ -200,19 +288,22 @@ function localCleanupAfterMerge(context, headBranch, config, location) {
200
288
  }
201
289
  else if (!didRunLocalStep(context, { verb: 'set', target: `current branch to ${checkoutTarget}` }, cwd, ['checkout', checkoutTarget], `checking out ${checkoutTarget}`)) {
202
290
  // checkout が失敗したら、pull と branch -D は別のブランチに当たるので止める
291
+ if (currentBranch !== undefined)
292
+ context.record.currentBranch = currentBranch;
203
293
  return;
204
294
  }
295
+ context.record.currentBranch = checkoutTarget;
205
296
  didRunLocalStep(context, { verb: 'update', target: `${checkoutTarget} from ${remote}/${developBranch}` }, cwd, ['pull', remote, developBranch], `pulling ${developBranch}`);
206
297
  if (headBranch === checkoutTarget) {
207
298
  settle(out, { verb: 'skip', target: `deleting local branch ${headBranch} (it is the checkout target)` });
208
299
  }
209
- else {
210
- didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`);
300
+ else if (didRunLocalStep(context, { verb: 'delete', target: `local branch ${headBranch}` }, cwd, ['branch', '-D', headBranch], `deleting local branch ${headBranch}`)) {
301
+ context.record.deletedBranches.push({ branch: headBranch, location: 'local' });
211
302
  }
212
303
  }
213
304
  function removeActiveFlags(out) {
214
305
  try {
215
- for (const flag of [FLAG_PECOT_ACTIVE, FLAG_PECOT_BASE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE, FLAG_WIP_BRANCH_LINKED])
306
+ for (const flag of [FLAG_PECOT_BASE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE])
216
307
  removeFlag(flag);
217
308
  }
218
309
  catch (error) {
@@ -227,19 +318,32 @@ const FinishInputSchema = z.strictObject({
227
318
  });
228
319
  async function runFinish(input, io) {
229
320
  const out = createOutput(input.dry_run, io);
230
- const context = { out, isDryRun: input.dry_run };
321
+ const record = { closedIssues: [], skippedIssues: [], deletedBranches: [], readinessChanges: [], restack: [], hasStarted: false };
322
+ try {
323
+ await finish(input, { out, isDryRun: input.dry_run, record });
324
+ }
325
+ finally {
326
+ const { closedIssues, skippedIssues, deletedBranches, readinessChanges, restack, currentBranch } = record;
327
+ if (record.hasStarted)
328
+ out.result({ closedIssues, skippedIssues, deletedBranches, readinessChanges, restack, ...currentBranch !== undefined && { currentBranch } });
329
+ }
330
+ }
331
+ async function finish(input, context) {
332
+ const { out } = context;
231
333
  const config = requireActiveConfigPlain(out);
232
334
  const reference = parseReference(input.pr_ref, input.repo, out);
233
335
  const location = { owner: reference.owner, repository: reference.repository };
234
336
  const { client, pr } = await fetchPullRequestForCleanup(config, reference, out);
235
337
  if (pr.state !== 'MERGED')
236
- stopWith(out, `PR #${String(reference.number)} is not merged yet (state: ${pr.state}); merge it with gh pr merge first`, 'pr-state');
338
+ stopWith(out, hinted `PR #${String(reference.number)} is not merged yet (state: ${pr.state}); merge it with ${commandHint(['pr', 'merge'])} first`, 'pr-state');
339
+ context.record.hasStarted = true;
237
340
  const closing = collectClosingIssueNumbers(pr);
238
341
  const epicProtected = await findEpicProtectedNumbers(client, location, closing, out);
239
342
  for (const number of epicProtected)
240
343
  closing.delete(number);
241
344
  out.count('Issues to close', closing.size);
242
345
  await closeRelatedIssues(context, client, location, closing, epicProtected);
346
+ await updateWaitingIssues(context, { client, config, location, pullRequest: mergedPullRequestOf(location, reference.number, pr) });
243
347
  if (input.delete_branch)
244
348
  await deleteMergedBranch(context, client, location, pr.head_ref);
245
349
  if (input.skip_local_cleanup)
@@ -249,12 +353,12 @@ async function runFinish(input, io) {
249
353
  return;
250
354
  }
251
355
  removeActiveFlags(out);
252
- consumeFlag(FLAG_MERGE_SLASH_PENDING);
253
356
  }
254
357
  const sessionFinishCommand = defineCommand({
255
358
  path: ['session', 'finish'],
256
359
  description: 'Clean up after a merged PR (close related Issues, delete branches, local cleanup)',
257
360
  input: FinishInputSchema,
361
+ output: SESSION_FINISH_OUTPUT,
258
362
  positional: ['pr_ref'],
259
363
  shortFlags: { dry_run: '-n', delete_branch: '-d' },
260
364
  interactive: false,