@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
@@ -2,16 +2,14 @@
2
2
  import { z } from 'zod';
3
3
  import { findRepository, getFieldId, getOptionId, isRepositoryInProject } from '../domain/config.js';
4
4
  import { ReferenceParseError, parseIssueReference } from '../domain/reference-parser.js';
5
- import { pythonStringRepr } from '../domain/python-format.js';
6
5
  import { repositoryFullName } from '../domain/repository-resolver.js';
7
6
  import { displayReference } from '../domain/readiness.js';
8
- import { FLAG_PECOT_ACTIVE } from '../domain/state.js';
9
7
  import { decideStart, describeBaseMismatch } from '../domain/work-start.js';
10
8
  import { GitHubAPIError } from '../infra/github/errors.js';
11
- import { readFlag } from '../infra/state-store.js';
12
- import { createOutput } from './output.js';
9
+ import { issuePath } from './issue-shared.js';
10
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
13
11
  import { defineCommand } from './command-definition.js';
14
- import { commandHint, hinted, inputHint, joinHinted } from './command-hint.js';
12
+ import { commandHint, hinted, joinHinted } from './command-hint.js';
15
13
  import { requireActiveConfig, stopWith } from './command-stop.js';
16
14
  import { kindOfFailure } from './failure.js';
17
15
  import { createGitHubClient } from './github-client.js';
@@ -30,15 +28,11 @@ function rejectCwdRepositoryMismatch(out, owner, repository) {
30
28
  const current = resolved.repository;
31
29
  if (current.owner === owner && current.repository === repository)
32
30
  return;
33
- stopWith(out, joinHinted([
34
- `the repository of the work Issue (${owner}/${repository}) differs from `
35
- + `the CWD git remote (${repositoryFullName(current)})\n`
36
- + 'move to the worktree of the target repository and run again:\n'
37
- + `<project-root>/base/${repository}/ or <project-root>/<wtN>/${repository}/\n`
38
- + 'create one with /pecot-w:w-worktree-add only if the repository has no worktree\n'
39
- + 'to issue the command on purpose from outside the CWD (for example in a script), ',
40
- hinted `give ${inputHint(START_PATH, 'allow_cross_repo')}`,
41
- ], ''), 'repo-mismatch', USAGE_EXIT_CODE);
31
+ stopWith(out, `the repository of the work Issue (${owner}/${repository}) differs from `
32
+ + `the CWD git remote (${repositoryFullName(current)})\n`
33
+ + 'move to the worktree of the target repository and run again:\n'
34
+ + `<project-root>/base/${repository}/ or <project-root>/<wtN>/${repository}/\n`
35
+ + 'create one with /pecot-w:w-worktree-add only if the repository has no worktree', 'repo-mismatch', USAGE_EXIT_CODE);
42
36
  }
43
37
  /**
44
38
  develop_branch を設定する直し方の行
@@ -55,7 +49,7 @@ function resolveBaseBranch(out, query) {
55
49
  return base;
56
50
  const developBranch = findRepository(config, owner, repository)?.develop_branch;
57
51
  if (developBranch === undefined || developBranch === '') {
58
- const withBase = commandHint(START_PATH, { issue_ref: `${owner}/${repository}/${String(issueNumber)}`, branch, base: 'main' });
52
+ const withBase = commandHint(START_PATH, { issue_ref: issuePath(owner, repository, issueNumber), branch, base: 'main' });
59
53
  stopWith(out, joinHinted([`develop_branch is not set for ${owner}/${repository}`, developBranchGuide(owner, repository), hinted `or give the base: ${withBase}`]), 'repo-setting-missing');
60
54
  }
61
55
  return developBranch;
@@ -82,43 +76,11 @@ async function decideWorkStart(out, client, config, issue) {
82
76
  return decision.kind === 'blocked' ? stopWith(out, decision.message, 'not-ready', USAGE_EXIT_CODE) : decision;
83
77
  }
84
78
  /**
85
- A-2. .pecot-active が別の OPEN な Issue を指していれば、終了コード 2 で止める
86
- */
87
- async function guardActiveOverwrite(out, client, issueReference) {
88
- const existing = readFlag(FLAG_PECOT_ACTIVE) ?? '';
89
- if (existing === '' || existing === issueReference)
90
- return;
91
- let existingReference;
92
- try {
93
- existingReference = parseIssueReference(existing);
94
- }
95
- catch (error) {
96
- if (!(error instanceof ReferenceParseError))
97
- throw error;
98
- out.warning(`the content of .pecot-active (${pythonStringRepr(existing)}) is malformed; overwriting it`);
99
- return;
100
- }
101
- const { repository, number } = existingReference;
102
- const { state } = await client.getIssueSlim(repository.owner, repository.repository, number);
103
- if (state === 'OPEN') {
104
- stopWith(out, joinHinted([
105
- `this worktree is already working on another Issue (${existing}, OPEN)\n`
106
- + 'overwriting .pecot-active could mix up the tasks\n'
107
- + 'finish the other Issue first, or create another worktree with '
108
- + '/pecot-w:w-worktree-add and run /pecot-w:w-active again in its session',
109
- hinted `if it is stale and you want to overwrite it on purpose, give ${inputHint(START_PATH, 'force_overwrite_active')}`,
110
- ]), 'guard-blocked', USAGE_EXIT_CODE);
111
- }
112
- out.warning(state === 'CLOSED'
113
- ? `.pecot-active points to closed Issue ${existing}; overwriting it`
114
- : `the state of ${existing} in .pecot-active is unexpected (${pythonStringRepr(state)}); overwriting it`);
115
- }
116
- /**
117
79
  7.5. プロジェクトアイテムのステータスを active にする(失敗は warning にとどめる)
118
80
  */
119
81
  async function setIssueStatusActive(out, client, config, issue) {
120
82
  const { owner, repository, number } = issue;
121
- const target = `Issue ${owner}/${repository}/${String(number)} status active`;
83
+ const target = `Issue ${issuePath(owner, repository, number)} status active`;
122
84
  try {
123
85
  const itemId = await client.getItemIdByIssue(config.project.id, owner, repository, number);
124
86
  if (itemId === undefined || itemId === '') {
@@ -141,6 +103,15 @@ async function setIssueStatusActive(out, client, config, issue) {
141
103
  out.warning(`could not set ${target}: ${error.message}`);
142
104
  }
143
105
  }
106
+ const SESSION_START_OUTPUT = z.strictObject({
107
+ branch: z.string().describe('Branch created (or to be created), with the Issue number appended'),
108
+ repository: z.string().describe('Repository of the branch (owner/repo)'),
109
+ base: z.string().describe('Base branch the branch starts from'),
110
+ stackedOn: z.int().optional().describe('Issue number whose branch this one is stacked on (omitted when not stacked)'),
111
+ issue: z.string().describe('Work Issue (owner/repo/N)'),
112
+ workDirectory: z.string().optional().describe('Absolute path of the work directory (omitted on dry_run or when it could not be created)'),
113
+ dryRun: DRY_RUN_FIELD,
114
+ });
144
115
  const sessionStartCommand = defineCommand({
145
116
  path: START_PATH,
146
117
  description: 'Create a branch linked to an Issue (shown in the Development section of the Issue)',
@@ -149,12 +120,11 @@ const sessionStartCommand = defineCommand({
149
120
  branch: z.string().describe('Name of the branch to create'),
150
121
  base: z.string().optional().describe('Base branch (default: chosen by readiness, else develop_branch from the config)'),
151
122
  checkout: z.boolean().default(true).describe('Kept for compatibility; has no effect'),
152
- allow_cross_repo: z.boolean().default(false).describe('Allow the CWD repository to differ from the Issue ref (for scripts and runs outside the CWD)'),
153
- force_overwrite_active: z.boolean().default(false).describe('Disable the .pecot-active overwrite guard (when sure it is stale)'),
154
123
  dry_run: z.boolean().default(false).describe('Show what would be created and recorded without writing anything'),
155
124
  }),
125
+ output: SESSION_START_OUTPUT,
156
126
  positional: ['issue_ref', 'branch'],
157
- shortFlags: { base: '-b', allow_cross_repo: '-X', force_overwrite_active: '-F', dry_run: '-n' },
127
+ shortFlags: { base: '-b', dry_run: '-n' },
158
128
  negations: { checkout: '--no-checkout' },
159
129
  interactive: false,
160
130
  run: async (input, io) => {
@@ -175,14 +145,10 @@ const sessionStartCommand = defineCommand({
175
145
  const { owner, repository } = issue.repository;
176
146
  const issueNumber = issue.number;
177
147
  // A-1. 作業ディレクトリと Issue ref のリポジトリの整合チェック
178
- if (!input.allow_cross_repo)
179
- rejectCwdRepositoryMismatch(out, owner, repository);
148
+ rejectCwdRepositoryMismatch(out, owner, repository);
180
149
  const finalBranchName = `${input.branch}/${String(issueNumber)}`;
181
150
  try {
182
151
  const client = createGitHubClient(out, config.host);
183
- // A-2. .pecot-active 上書きガード
184
- if (!input.force_overwrite_active)
185
- await guardActiveOverwrite(out, client, `${owner}/${repository}/${String(issueNumber)}`);
186
152
  // 4. リポジトリがプロジェクトに含まれているか確認
187
153
  if (!await isRepositoryInProject(config, owner, repository, client)) {
188
154
  stopWith(out, `${owner}/${repository} is not in the project`, 'repo-not-in-project');
@@ -208,21 +174,26 @@ const sessionStartCommand = defineCommand({
208
174
  throw error;
209
175
  }
210
176
  const stackedNote = decision.kind === 'stack' ? ` (stacked on ${displayReference(decision.issue, issue.repository)})` : '';
177
+ const started = { repository: `${owner}/${repository}`, base: baseBranch, ...decision.kind === 'stack' && { stackedOn: decision.issue.number }, issue: issuePath(owner, repository, issueNumber) };
211
178
  if (input.dry_run) {
179
+ out.result({ ...started, branch: finalBranchName });
212
180
  out.planned({ verb: 'create', target: `branch ${finalBranchName} in ${owner}/${repository} from ${baseBranch}${stackedNote}` });
213
- out.planned({ verb: 'set', target: `Issue ${owner}/${repository}/${String(issueNumber)} status active` });
214
- planWorkTarget(out, owner, repository, issueNumber);
181
+ out.planned({ verb: 'set', target: `Issue ${issuePath(owner, repository, issueNumber)} status active` });
182
+ planWorkTarget(out, issueNumber);
215
183
  return 0;
216
184
  }
217
185
  // 7. リンクブランチ作成(ブランチ名末尾に Issue 番号を自動付与)
218
186
  const createdBranch = await client.createLinkedBranch(issueNodeId, baseSha, finalBranchName);
219
187
  out.done({ verb: 'create', target: `branch ${createdBranch} in ${owner}/${repository} from ${baseBranch}${stackedNote}` });
188
+ out.result({ ...started, branch: createdBranch });
220
189
  // 7.5. プロジェクトアイテムのステータスを active に更新
221
190
  await setIssueStatusActive(out, client, config, { owner, repository, number: issueNumber });
222
- // 9. 作業対象を .pecot-active と .pecot-session-title に保存(hook の自動投稿とセッション名用)
223
- recordWorkTarget(out, owner, repository, issueNumber, issueTitle, {
191
+ // 9. セッション名のキャッシュ(.pecot-session-title)と作業ディレクトリを作る
192
+ const recorded = recordWorkTarget(out, owner, repository, issueNumber, issueTitle, {
224
193
  base: { branch: baseBranch, sha: baseSha, stackedOn: decision.kind === 'stack' ? decision.issue : undefined },
225
194
  });
195
+ if (recorded.workDirectory !== undefined)
196
+ out.result({ workDirectory: recorded.workDirectory });
226
197
  return 0;
227
198
  }
228
199
  catch (error) {
@@ -1,49 +1,59 @@
1
- // session show・session restore。cli/commands/session.py の移植。
1
+ // session show。cli/commands/session.py の移植。
2
2
  import { z } from 'zod';
3
- import { extractIssueNumberFromBranch } from '../domain/branch-name.js';
4
3
  import { ConfigError } from '../domain/config.js';
5
- import { PecotError } from '../domain/errors.js';
6
4
  import { describeReadiness } from '../domain/readiness.js';
7
- import { parseIssueReference, ReferenceParseError } from '../domain/reference-parser.js';
8
- import { FLAG_PECOT_ACTIVE } from '../domain/state.js';
9
- import { describeStackBase, pickBasePullRequest } from '../domain/work-start.js';
5
+ import { describeNeedsRestack, needsRestack } from '../domain/restack.js';
6
+ import { issueReferenceToCliReference, issueReferenceToString } from '../domain/reference-parser.js';
7
+ import { ProjectRootNotFoundError } from '../domain/errors.js';
8
+ import { describeStackBase } from '../domain/work-start.js';
10
9
  import { loadActiveConfig } from '../infra/config-store.js';
11
- import { gitCurrentBranch, primaryRemoteRepository } from '../infra/git.js';
10
+ import { activeIssueOf, gitCurrentBranch, gitToplevel, primaryRemoteName, primaryRemoteRepository } from '../infra/git.js';
12
11
  import { GitHubAPIError } from '../infra/github/errors.js';
13
- import { hasFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
12
+ import { projectRoot, resolveRealPath } from '../infra/paths.js';
13
+ import { readBaseRecord } from '../infra/state-store.js';
14
14
  import { defineCommand } from './command-definition.js';
15
- import { FAILURE_EXIT_CODE } from './failure.js';
16
- import { commandHint, hinted, placeholder } from './command-hint.js';
17
- import { stopWith } from './command-stop.js';
18
15
  import { directorySchema } from './directory-option.js';
19
16
  import { createGitHubClient } from './github-client.js';
20
17
  import { createReadinessCache, readIssueReadinessIfSupported } from './issue-readiness.js';
21
18
  import { createOutput } from './output.js';
19
+ import { readRestackDecision } from './restack-reading.js';
22
20
  import { SESSION_FINISH_COMMANDS } from './session-finish.js';
23
21
  import { SESSION_START_COMMANDS } from './session-start.js';
24
- import { USAGE_EXIT_CODE } from './usage-error.js';
25
- import { planWorkTarget, recordWorkTarget } from './work-target.js';
26
- const ALL_FLAGS = [FLAG_PECOT_ACTIVE];
27
- function collectFlagStatuses() {
28
- return ALL_FLAGS.map((name) => {
29
- const isSet = hasFlag(name);
30
- return { name, isSet, content: isSet ? readFlag(name) ?? '' : '' };
31
- });
32
- }
33
- // .pecot-active の Issue を GitHub から読んで、Markdown の行にする。読めなければ warning だけ出して undefined にする
34
- async function readActiveIssue(statuses, output) {
35
- const active = statuses.find(status => status.name === FLAG_PECOT_ACTIVE && status.isSet && status.content !== '');
36
- if (active === undefined)
22
+ const ACTIVE_ISSUE_DATA = z.strictObject({
23
+ reference: z.string().describe('Work Issue found from the git remote and the number that ends the branch name (owner/repo/N, the form issue_ref takes)'),
24
+ title: z.string().optional().describe('Title of the Issue (omitted when it cannot be read from GitHub)'),
25
+ state: z.string().optional().describe('State of the Issue, OPEN or CLOSED (omitted when it cannot be read from GitHub)'),
26
+ });
27
+ const BASE_PULL_REQUEST_DATA = z.strictObject({
28
+ number: z.int().describe('PR number'),
29
+ state: z.string().describe('State of the PR'),
30
+ });
31
+ const STACK_DATA = z.strictObject({
32
+ branch: z.string().describe('Base branch the work branch is stacked on'),
33
+ stackedOn: z.string().describe('Issue stacked on (owner/repo/N)'),
34
+ pullRequest: BASE_PULL_REQUEST_DATA.optional().describe('PR of the base branch (omitted when there is none or it cannot be read)'),
35
+ needsRestack: z.boolean().optional().describe('Whether the branch needs pr restack: the base branch moved or its PR is merged (omitted when it cannot be decided)'),
36
+ readiness: z.string().optional().describe('Readiness of the active Issue (only when blocked)'),
37
+ });
38
+ const STACKED_ABOVE_DATA = z.strictObject({
39
+ number: z.int().describe('PR number'),
40
+ branch: z.string().describe('Head branch of the PR'),
41
+ });
42
+ const SESSION_SHOW_OUTPUT = z.strictObject({
43
+ branch: z.string().optional().describe('Current branch (omitted when it cannot be read)'),
44
+ repository: z.string().optional().describe('Repository of the git remote (owner/repo; omitted when it cannot be read)'),
45
+ activeIssue: ACTIVE_ISSUE_DATA.optional().describe('Work Issue of the session (omitted when there is none)'),
46
+ stack: STACK_DATA.optional().describe('Base the work was stacked on (omitted when not stacked)'),
47
+ stackedAbove: z.array(STACKED_ABOVE_DATA).optional().describe('Open PRs whose base is the current branch (omitted when there are none or they cannot be read)'),
48
+ });
49
+ // 作業中の Issue(remote とブランチ名から求める)を GitHub から読んで、Markdown の行にする。
50
+ // 作業中の Issue が無ければ undefined。読めなければ warning を出し、参照だけを返す
51
+ async function readActiveIssue(directory, output) {
52
+ const reference = activeIssueOf(directory);
53
+ if (reference === undefined)
37
54
  return undefined;
38
- let reference;
39
- try {
40
- reference = parseIssueReference(active.content);
41
- }
42
- catch (error) {
43
- if (error instanceof ReferenceParseError)
44
- return undefined;
45
- throw error;
46
- }
55
+ const label = issueReferenceToString(reference);
56
+ const data = { reference: issueReferenceToCliReference(reference) };
47
57
  let issue;
48
58
  let config;
49
59
  let client;
@@ -51,7 +61,7 @@ async function readActiveIssue(statuses, output) {
51
61
  config = loadActiveConfig();
52
62
  if (config === undefined) {
53
63
  output.warning('cannot read the active Issue: no active project');
54
- return undefined;
64
+ return { label, data };
55
65
  }
56
66
  client = createGitHubClient(output, config.host);
57
67
  issue = await client.getIssueSlim(reference.repository.owner, reference.repository.repository, reference.number, 0);
@@ -59,54 +69,97 @@ async function readActiveIssue(statuses, output) {
59
69
  catch (error) {
60
70
  if (error instanceof ConfigError || error instanceof GitHubAPIError) {
61
71
  output.warning(`cannot read the active Issue: ${error.message}`);
62
- return undefined;
72
+ return { label, data };
63
73
  }
64
74
  throw error;
65
75
  }
66
76
  const lines = ['', '## Active Issue', '', `#${String(issue.number)} ${issue.title} (${issue.state})`];
67
77
  if (issue.body !== '')
68
78
  lines.push('', issue.body);
69
- return { reference, config, client, lines };
79
+ return { label, data: { ...data, title: issue.title, state: issue.state }, read: { reference, config, client, lines } };
80
+ }
81
+ // -D の directory がプロジェクトルートの worktree か。積んだ記録(.pecot-base)はプロジェクトルートの状態にあるので、
82
+ // 別の worktree の作業には付けない
83
+ function isProjectRootWorktree(directory) {
84
+ const toplevel = gitToplevel({ cwd: directory });
85
+ if (toplevel === undefined)
86
+ return false;
87
+ try {
88
+ return resolveRealPath(toplevel) === resolveRealPath(projectRoot());
89
+ }
90
+ catch (error) {
91
+ if (error instanceof ProjectRootNotFoundError)
92
+ return false;
93
+ throw error;
94
+ }
70
95
  }
71
96
  // 積んで着手した作業ディレクトリの `## Stack` の節。積んでいなければ空
72
- async function stackLines(active, output) {
97
+ async function stackSection(active, origin, directory, output) {
73
98
  const reading = readBaseRecord();
74
99
  if (reading.kind === 'malformed')
75
100
  output.warning(`.pecot-base is malformed: ${reading.content}`);
76
101
  if (reading.kind !== 'stacked')
77
- return [];
102
+ return { lines: [] };
78
103
  const { record, stackedOn } = reading;
79
- const { owner, repository } = stackedOn.repository;
80
- let pullRequest;
104
+ // ブランチは作業ディレクトリのリポにあるので、PR もそこで探す(pr restack と同じ)
105
+ const { owner, repository } = origin ?? stackedOn.repository;
106
+ // 載せ直す先は、fetch せずに、下の段の remote の先頭を尋ねて記録と比べる
107
+ const read = await readRestackDecision({ client: () => active.client, owner, repository, cwd: directory, remote: primaryRemoteName(directory), reading, developBranch: '' });
108
+ if (read.kind === 'pull-request-unreadable')
109
+ output.warning(`cannot read the PR of the base branch: ${read.error.message}`);
110
+ const pullRequest = read.kind === 'pull-request-unreadable' ? 'unknown' : read.lowerPullRequest;
111
+ const restack = read.kind === 'decided' ? read.decision : undefined;
112
+ const readiness = await blockedReadiness(active, output);
113
+ const needsLine = restack === undefined ? undefined : describeNeedsRestack(restack);
114
+ const needed = restack === undefined ? undefined : needsRestack(restack);
115
+ return {
116
+ lines: ['', '## Stack', describeStackBase(record.branch, stackedOn, pullRequest), ...needsLine === undefined ? [] : [needsLine], ...readiness === undefined ? [] : [`- readiness: ${readiness}`]],
117
+ data: {
118
+ branch: record.branch,
119
+ stackedOn: issueReferenceToCliReference(stackedOn),
120
+ ...pullRequest !== 'unknown' && pullRequest !== undefined && { pullRequest: { number: pullRequest.number, state: pullRequest.state } },
121
+ ...needed !== undefined && { needsRestack: needed },
122
+ ...readiness !== undefined && { readiness },
123
+ },
124
+ };
125
+ }
126
+ // 今のブランチを base にした、同じリポの開いている PR。読めなければ warning を出して undefined にする
127
+ async function readStackedAbove(active, origin, branch, output) {
81
128
  try {
82
- const found = await active.client.listPullRequestsByHead(owner, repository, record.branch);
83
- pullRequest = pickBasePullRequest(found.pullRequests);
129
+ const found = await active.client.listPullRequestsByBase(origin.owner, origin.repository, branch);
130
+ return found.pullRequests.map(pullRequest => ({ number: pullRequest.number, branch: pullRequest.headRefName }));
84
131
  }
85
132
  catch (error) {
86
133
  if (!(error instanceof GitHubAPIError))
87
134
  throw error;
88
- output.warning(`cannot read the PR of the base branch: ${error.message}`);
89
- pullRequest = 'unknown';
135
+ output.warning(`cannot read the PRs stacked above: ${error.message}`);
136
+ return undefined;
90
137
  }
91
- const readiness = await readinessLines(active, output);
92
- return ['', '## Stack', describeStackBase(record.branch, stackedOn, pullRequest), ...readiness];
93
138
  }
94
- // 着手中の Issue の判定が blocked のときだけ出す
95
- async function readinessLines(active, output) {
139
+ // 積んだ記録の節に上の段の行を足す。積んだ記録が無くても、上の段があれば節を出す
140
+ function withStackedAbove(stackLines, above) {
141
+ if (above === undefined || above.length === 0)
142
+ return stackLines;
143
+ const lines = above.map(pullRequest => `- stacked above: PR #${String(pullRequest.number)} (${pullRequest.branch})`);
144
+ return stackLines.length === 0 ? ['', '## Stack', ...lines] : [...stackLines, ...lines];
145
+ }
146
+ // 着手中の Issue の判定が blocked のときだけ、判定の文を返す
147
+ async function blockedReadiness(active, output) {
96
148
  const result = await readIssueReadinessIfSupported(active.client, active.config, active.reference, createReadinessCache());
97
149
  if (result === undefined)
98
- return [];
150
+ return undefined;
99
151
  if (result.kind === 'unreadable') {
100
152
  output.warning(`cannot judge readiness of the active Issue: ${result.reason}`);
101
- return [];
153
+ return undefined;
102
154
  }
103
155
  const { readiness } = result;
104
- return readiness?.kind === 'blocked' ? [`- readiness: ${describeReadiness(readiness, result.prerequisites, active.reference.repository)}`] : [];
156
+ return readiness?.kind === 'blocked' ? describeReadiness(readiness, result.prerequisites, active.reference.repository) : undefined;
105
157
  }
106
158
  const SESSION_SHOW = defineCommand({
107
159
  path: ['session', 'show'],
108
- description: 'Show the session flag state, branch information, and inferred Issue',
160
+ description: 'Show the branch, repository and work Issue of the session',
109
161
  input: z.object({ directory: directorySchema }),
162
+ output: SESSION_SHOW_OUTPUT,
110
163
  positional: [],
111
164
  shortFlags: { directory: '-D' },
112
165
  interactive: false,
@@ -114,101 +167,32 @@ const SESSION_SHOW = defineCommand({
114
167
  const output = createOutput(false, io);
115
168
  const branch = gitCurrentBranch(input.directory);
116
169
  const origin = primaryRemoteRepository(input.directory);
117
- const issueNumber = branch === undefined ? undefined : extractIssueNumberFromBranch(branch);
118
- const statuses = collectFlagStatuses();
119
- const active = await readActiveIssue(statuses, output);
170
+ const reading = await readActiveIssue(input.directory, output);
171
+ const active = reading?.read;
172
+ const stack = active === undefined || !isProjectRootWorktree(input.directory) ? { lines: [] } : await stackSection(active, origin, input.directory, output);
173
+ const above = active === undefined || origin === undefined || branch === undefined ? undefined : await readStackedAbove(active, origin, branch, output);
174
+ output.result({
175
+ ...branch !== undefined && { branch },
176
+ ...origin !== undefined && { repository: `${origin.owner}/${origin.repository}` },
177
+ ...reading !== undefined && { activeIssue: reading.data },
178
+ ...stack.data !== undefined && { stack: stack.data },
179
+ ...above !== undefined && above.length > 0 && { stackedAbove: above },
180
+ });
120
181
  const lines = [
121
182
  '# Session status',
122
183
  '',
123
184
  `- Branch: ${branch ?? 'unknown'}`,
124
185
  `- Repository: ${origin === undefined ? 'unknown' : `${origin.owner}/${origin.repository}`}`,
125
- `- Inferred Issue: ${issueNumber === undefined ? 'none' : `#${String(issueNumber)}`}`,
126
- '',
127
- '| Flag | State | Content |',
128
- '|------|-------|---------|',
129
- ...statuses.map(status => `| ${status.name} | ${status.isSet ? 'set' : 'unset'} | ${status.content} |`),
186
+ `- Active Issue: ${reading === undefined ? 'none' : reading.label}`,
130
187
  ...active?.lines ?? [],
131
- ...active === undefined ? [] : await stackLines(active, output),
188
+ ...withStackedAbove(stack.lines, above),
132
189
  ];
133
190
  output.data(lines.join('\n'));
134
191
  return 0;
135
192
  },
136
193
  });
137
- // セッション名に添える題名。設定が無いか API が失敗したときだけ空にする。設定が読めないなら ConfigError を伝える
138
- async function fetchIssueTitle(owner, repository, number, output) {
139
- try {
140
- const config = loadActiveConfig();
141
- if (config === undefined)
142
- return '';
143
- const issue = await createGitHubClient(output, config.host).getIssueSlim(owner, repository, number, 0);
144
- return issue.title;
145
- }
146
- catch (error) {
147
- if (error instanceof ConfigError)
148
- throw error;
149
- if (error instanceof PecotError)
150
- return '';
151
- throw error;
152
- }
153
- }
154
- // issue_ref が無いときの、ブランチ名と remote からの推定。決められなければ error を出して終了コード 1
155
- function inferTarget(directory, output) {
156
- const branch = gitCurrentBranch(directory);
157
- if (branch === undefined) {
158
- return stopWith(output, 'cannot read the branch name', 'git-unresolved', FAILURE_EXIT_CODE);
159
- }
160
- const number = extractIssueNumberFromBranch(branch);
161
- if (number === undefined) {
162
- return stopWith(output, hinted `cannot infer the Issue number from the branch name: ${branch}\nrun: ${commandHint(['session', 'restore'], { issue_ref: placeholder('owner/repo/N') })}`, 'git-unresolved', FAILURE_EXIT_CODE);
163
- }
164
- const origin = primaryRemoteRepository(directory);
165
- const message = 'cannot read the repository information';
166
- return origin === undefined ? stopWith(output, message, 'git-unresolved', FAILURE_EXIT_CODE) : { owner: origin.owner, repository: origin.repository, number };
167
- }
168
- // issue_ref の参照を分ける。形が誤っていれば error を出して終了コード 2
169
- function parseTarget(issue, output) {
170
- try {
171
- const reference = parseIssueReference(issue);
172
- return { owner: reference.repository.owner, repository: reference.repository.repository, number: reference.number };
173
- }
174
- catch (error) {
175
- if (!(error instanceof ReferenceParseError))
176
- throw error;
177
- return stopWith(output, error.message, 'invalid-input', USAGE_EXIT_CODE);
178
- }
179
- }
180
- const SESSION_RESTORE = defineCommand({
181
- path: ['session', 'restore'],
182
- description: 'Restore lost session flags (such as .pecot-active) from the branch information',
183
- input: z.object({
184
- issue_ref: z.string().optional().describe('Issue reference (owner/repo/number)'),
185
- directory: directorySchema,
186
- dry_run: z.boolean().default(false).describe('Show what would be recorded without writing anything'),
187
- }),
188
- positional: [],
189
- shortFlags: { issue_ref: '-i', directory: '-D', dry_run: '-n' },
190
- interactive: false,
191
- run: async (input, io) => {
192
- const output = createOutput(input.dry_run, io);
193
- const target = input.issue_ref === undefined ? inferTarget(input.directory, output) : parseTarget(input.issue_ref, output);
194
- let title;
195
- try {
196
- title = await fetchIssueTitle(target.owner, target.repository, target.number, output);
197
- }
198
- catch (error) {
199
- if (!(error instanceof ConfigError))
200
- throw error;
201
- return stopWith(output, error.message, 'config-invalid', FAILURE_EXIT_CODE);
202
- }
203
- if (input.dry_run)
204
- planWorkTarget(output, target.owner, target.repository, target.number);
205
- else
206
- recordWorkTarget(output, target.owner, target.repository, target.number, title, { failWithExit: true });
207
- return 0;
208
- },
209
- });
210
194
  /**
211
195
  session のグループのコマンド。start は session-start.ts、finish は session-finish.ts にある。並びは help の一覧に出る順
212
196
  */
213
- export const SESSION_COMMANDS = [...SESSION_START_COMMANDS, SESSION_SHOW, SESSION_RESTORE, ...SESSION_FINISH_COMMANDS];
197
+ export const SESSION_COMMANDS = [...SESSION_START_COMMANDS, SESSION_SHOW, ...SESSION_FINISH_COMMANDS];
214
198
  //# sourceMappingURL=session.js.map
@@ -42,10 +42,18 @@ function operationsFor(plan, tracker, title, isUnchanged) {
42
42
  rewrite.push({ verb: 'update', target: `Tracker #${String(tracker)} body` });
43
43
  return { create: [], rewrite, close: plan.close ? [{ verb: 'close', target: `Tracker #${String(tracker)}` }] : [] };
44
44
  }
45
+ // 足す行と外す行。open の Tracker が無ければ、立てる Tracker に載せる行を足す行にする
46
+ function rowsOf(plan, tracker) {
47
+ const added = tracker === undefined ? (plan.create ? plan.entries : []) : plan.added;
48
+ return {
49
+ added: added.map(entry => ({ kind: 'pull-request', number: entry.number })),
50
+ removed: plan.removed.map(number => ({ kind: 'pull-request', number })),
51
+ };
52
+ }
45
53
  // Tracker を作る・書き直す・閉じる・ボードに載せる。失敗の数を返す。
46
54
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は可変
47
55
  async function applyChanges(out, input) {
48
- const { client, config, owner, repository, plan, title, body, stages, number, isUnchanged } = input;
56
+ const { client, config, owner, repository, plan, title, body, stages, number, isUnchanged, rows } = input;
49
57
  try {
50
58
  if (number === undefined) {
51
59
  if (!plan.create) {
@@ -56,7 +64,9 @@ async function applyChanges(out, input) {
56
64
  const issue = await createIssue(client, owner, repository, title, body, [PR_LABEL]);
57
65
  for (const operation of stages.create)
58
66
  out.done(operation);
59
- await putOnBoard(client, config, owner, repository, requireNumber(issue['number'], 'number'), PRIORITY, { onlyIfEmpty: false });
67
+ const created = requireNumber(issue['number'], 'number');
68
+ out.result({ tracker: created, created: true, added: rows.added });
69
+ await putOnBoard(client, config, owner, repository, created, PRIORITY, { onlyIfEmpty: false });
60
70
  return 0;
61
71
  }
62
72
  if (!isUnchanged) {
@@ -74,6 +84,7 @@ async function applyChanges(out, input) {
74
84
  }
75
85
  for (const operation of stages.rewrite)
76
86
  out.done(operation);
87
+ out.result(rows);
77
88
  const [closing] = stages.close;
78
89
  if (closing !== undefined) {
79
90
  try {
@@ -87,6 +98,7 @@ async function applyChanges(out, input) {
87
98
  return 1;
88
99
  }
89
100
  out.done(closing);
101
+ out.result({ closed: true });
90
102
  return 0;
91
103
  }
92
104
  // 作った後にボード登録が失敗した実行を直す。Status・Priority は空のときだけ入れる
@@ -146,9 +158,14 @@ export async function runDependabotSync(input, io) {
146
158
  const stages = operationsFor(plan, number, title, isUnchanged);
147
159
  for (const operation of [...stages.create, ...stages.rewrite, ...stages.close])
148
160
  out.planned(operation);
149
- if (input.dry_run)
161
+ const rows = rowsOf(plan, number);
162
+ const synced = { source: 'dependabot', ...number !== undefined && { tracker: number } };
163
+ if (input.dry_run) {
164
+ out.result({ ...synced, created: number === undefined && plan.create, ...rows, closed: plan.close });
150
165
  return 0;
151
- const failures = await applyChanges(out, { client, config, owner, repository, plan, title, body, stages, number, isUnchanged });
166
+ }
167
+ out.result({ ...synced, created: false, added: [], removed: [], closed: false });
168
+ const failures = await applyChanges(out, { client, config, owner, repository, plan, title, body, stages, number, isUnchanged, rows });
152
169
  if (failures > 0)
153
170
  throw new CommandExit(1, 'partial-failure');
154
171
  return 0;
@@ -57,10 +57,21 @@ function operationsOf(plan, tracker, title, isUnchanged) {
57
57
  ];
58
58
  return { create: [], rewrite: rewrite.length === 0 ? [{ verb: 'update', target: `Tracker ${label} body` }] : rewrite };
59
59
  }
60
+ // 足す行と外す行。open の Tracker が無ければ、立てる Tracker に載せる行を足す行にする。本文が変わらなければどちらも空
61
+ function rowsOf(plan, tracker, isUnchanged) {
62
+ if (tracker !== undefined && isUnchanged)
63
+ return { added: [], removed: [] };
64
+ const added = tracker === undefined ? (plan.create ? plan.entries : []) : plan.added;
65
+ const removed = tracker === undefined ? [] : plan.removed;
66
+ return {
67
+ added: added.map(entry => ({ kind: entry.kind, number: entry.number })),
68
+ removed: removed.map(entry => ({ kind: entry.kind, number: entry.number })),
69
+ };
70
+ }
60
71
  // Tracker を作る・書き直す・ボードに載せる。失敗の数を返す。
61
72
  // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types -- GitHubClient は可変
62
73
  async function applyChanges(out, input) {
63
- const { client, config, owner, repository, plan, title, body, stages, number, isUnchanged } = input;
74
+ const { client, config, owner, repository, plan, title, body, stages, number, isUnchanged, rows } = input;
64
75
  const priority = maxPriority(plan.entries);
65
76
  try {
66
77
  if (number === undefined) {
@@ -72,7 +83,9 @@ async function applyChanges(out, input) {
72
83
  const issue = await createIssue(client, owner, repository, title, body, [ALERT_LABEL]);
73
84
  for (const operation of stages.create)
74
85
  out.done(operation);
75
- await putOnBoard(client, config, owner, repository, requireNumber(issue['number'], 'number'), priority, { onlyIfEmpty: false });
86
+ const created = requireNumber(issue['number'], 'number');
87
+ out.result({ tracker: created, created: true, added: rows.added });
88
+ await putOnBoard(client, config, owner, repository, created, priority, { onlyIfEmpty: false });
76
89
  return 0;
77
90
  }
78
91
  let failures = 0;
@@ -91,9 +104,11 @@ async function applyChanges(out, input) {
91
104
  out.error(`could not update Tracker #${String(number)} body: ${text}`);
92
105
  }
93
106
  }
94
- if (isUpdated)
107
+ if (isUpdated) {
95
108
  for (const operation of stages.rewrite)
96
109
  out.done(operation);
110
+ out.result(rows);
111
+ }
97
112
  // 作った後にボード登録が失敗した実行を直す。Status・Priority は空のときだけ入れる
98
113
  await putOnBoard(client, config, owner, repository, number, priority, { onlyIfEmpty: true });
99
114
  return failures;
@@ -145,7 +160,10 @@ export async function runSecuritySync(input, io) {
145
160
  const stages = operationsOf(plan, number, title, isUnchanged);
146
161
  for (const operation of [...stages.create, ...stages.rewrite])
147
162
  out.planned(operation);
148
- const failures = input.dry_run ? 0 : await applyChanges(out, { client, config, owner, repository, plan, title, body, stages, number, isUnchanged });
163
+ const rows = rowsOf(plan, number, isUnchanged);
164
+ const synced = { source: 'security', ...number !== undefined && { tracker: number }, closed: false };
165
+ out.result(input.dry_run ? { ...synced, created: number === undefined && plan.create, ...rows } : { ...synced, created: false, added: [], removed: [] });
166
+ const failures = input.dry_run ? 0 : await applyChanges(out, { client, config, owner, repository, plan, title, body, stages, number, isUnchanged, rows });
149
167
  if (failed.size > 0 || failures > 0)
150
168
  throw new CommandExit(1, 'partial-failure');
151
169
  return 0;