@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
@@ -1,48 +0,0 @@
1
- import type { ProjectConfig } from '../domain/config.js';
2
- import type { DependabotAlertStatus } from '../domain/dependabot.js';
3
- import type { BoardItem } from '../domain/format.js';
4
- import type { GitHubClient } from '../infra/github/index.js';
5
- import type { Output } from './output.js';
6
- /**
7
- 取得に失敗したリポジトリは、理由の文字列
8
- */
9
- export type AlertStatus = DependabotAlertStatus | string;
10
- /**
11
- Archived のアイテムを updatedAt の新しい順に並べ、最新の 20 件を残して、残りをボードから消す。
12
- 消せなかった分は warning にとどめる
13
- */
14
- export declare function pruneArchivedItems(out: Readonly<Output>, client: Readonly<Pick<GitHubClient, 'deleteProjectItem'>>, config: ProjectConfig, allItems: readonly BoardItem[]): Promise<void>;
15
- /**
16
- 登録リポジトリごとの Dependabot alert の状態(登録の順)。
17
- 1 つの取得の失敗でボードの表示を止めないよう、DependabotAlertError はここで理由の文字列にする
18
- */
19
- export declare function collectAlertStatuses(client: Readonly<GitHubClient>, config: ProjectConfig): Promise<readonly AlertStatus[]>;
20
- /**
21
- items を最大 limit 件ずつ並列に処理し、結果を items の順で返す。1 件でも投げたら、その例外で止まる
22
- */
23
- export declare function mapWithLimit<Item, Result>(items: readonly Item[], limit: number, task: (item: Item) => Promise<Result>): Promise<readonly Result[]>;
24
- export interface InfoView {
25
- readonly config: ProjectConfig;
26
- readonly projectName: string;
27
- readonly statuses: readonly AlertStatus[];
28
- }
29
- /**
30
- info --json の出力
31
- */
32
- export declare function infoJson(view: Readonly<InfoView>, items: readonly BoardItem[]): string;
33
- /**
34
- info の Markdown の出力
35
- */
36
- export declare function infoMarkdown(view: Readonly<InfoView>, effectiveRepository: string | undefined, boardOutput: string): string;
37
- export interface BoardRead {
38
- readonly allItems: readonly BoardItem[];
39
- /**
40
- 表示するアイテム(OPEN の Backlog・Pending・Blocked・Ready・Active・In Review。リポジトリの指定があれば絞る)
41
- */
42
- readonly items: readonly BoardItem[];
43
- }
44
- /**
45
- ボードのアイテムを全部読み、表示するものに絞る
46
- */
47
- export declare function readBoard(client: Readonly<GitHubClient>, config: ProjectConfig, effectiveRepository: string | undefined): Promise<BoardRead>;
48
- //# sourceMappingURL=project-info.d.ts.map
@@ -1,181 +0,0 @@
1
- // project info の表示と、Archived の整理、Dependabot alert の収集。
2
- import { effectiveReleaseType, workflowFieldName } from '../domain/config.js';
3
- import { DependabotAlertError, fetchDependabotAlertStatus } from '../domain/dependabot.js';
4
- import { formatItemsJson, transformItems } from '../domain/format.js';
5
- import { JSON_NULL } from '../domain/json-null.js';
6
- import { compareStrings } from '../domain/python-format.js';
7
- import { createDependabotSource } from '../infra/github/dependabot-source.js';
8
- import { GitHubAPIError } from '../infra/github/errors.js';
9
- /**
10
- Archived のうち、ボードに残す件数
11
- */
12
- const ARCHIVED_KEEP = 20;
13
- /**
14
- Dependabot alert を並列に取る数の上限(Python の _ALERT_FETCH_MAX_WORKERS と同じ)
15
- */
16
- const ALERT_FETCH_MAX_WORKERS = 8;
17
- const DISPLAY_STATUSES = new Set(['Backlog', 'Pending', 'Blocked', 'Ready', 'Active', 'In Review']);
18
- function updatedAtOf(item) {
19
- return typeof item.updatedAt === 'string' ? item.updatedAt : '';
20
- }
21
- /**
22
- Archived のアイテムを updatedAt の新しい順に並べ、最新の 20 件を残して、残りをボードから消す。
23
- 消せなかった分は warning にとどめる
24
- */
25
- export async function pruneArchivedItems(out, client, config, allItems) {
26
- const archived = allItems.filter(item => item.workflow === 'Archived').toSorted((first, second) => compareStrings(updatedAtOf(second), updatedAtOf(first)));
27
- if (archived.length <= ARCHIVED_KEEP)
28
- return;
29
- const targets = archived.slice(ARCHIVED_KEEP);
30
- let deleted = 0;
31
- for (const item of targets) {
32
- // ID が文字列でないアイテムは、API を呼ばず、失敗として数える
33
- if (typeof item.id !== 'string')
34
- continue;
35
- try {
36
- await client.deleteProjectItem(config.project.id, item.id);
37
- deleted += 1;
38
- }
39
- catch (error) {
40
- // 削除の失敗は数えて続ける
41
- if (!(error instanceof GitHubAPIError))
42
- throw error;
43
- }
44
- }
45
- if (deleted > 0)
46
- out.done({ verb: 'delete', target: `${String(deleted)} archived items` });
47
- const failed = targets.length - deleted;
48
- if (failed > 0)
49
- out.warning(`failed to delete ${String(failed)} archived items`);
50
- }
51
- /**
52
- 登録リポジトリごとの Dependabot alert の状態(登録の順)。
53
- 1 つの取得の失敗でボードの表示を止めないよう、DependabotAlertError はここで理由の文字列にする
54
- */
55
- export async function collectAlertStatuses(client, config) {
56
- const source = createDependabotSource(client);
57
- return await mapWithLimit(config.repositories, ALERT_FETCH_MAX_WORKERS, async (entry) => {
58
- try {
59
- return await fetchDependabotAlertStatus(source, config.host, entry.owner, entry.name);
60
- }
61
- catch (error) {
62
- if (error instanceof DependabotAlertError)
63
- return error.message;
64
- throw error;
65
- }
66
- });
67
- }
68
- /**
69
- items を最大 limit 件ずつ並列に処理し、結果を items の順で返す。1 件でも投げたら、その例外で止まる
70
- */
71
- export async function mapWithLimit(items, limit, task) {
72
- const results = [];
73
- // 全ての worker が同じ iterator から次の項目を取る
74
- const pending = items.entries();
75
- const worker = async () => {
76
- // eslint-disable-next-line security/detect-object-injection -- index は entries() の添字
77
- for (const [index, item] of pending)
78
- results[index] = await task(item);
79
- };
80
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
81
- return results;
82
- }
83
- /**
84
- index 番目の取得結果。件数が登録のリポジトリとずれていたら投げる
85
- */
86
- function statusAt(statuses, index) {
87
- const status = statuses.at(index);
88
- if (status === undefined)
89
- throw new RangeError(`no Dependabot alert status for repository #${String(index)}`);
90
- return status;
91
- }
92
- function alertsJson(status) {
93
- return typeof status === 'string' ? { error: status } : { enabled: status.enabled, open_count: status.openCount, max_severity: status.maxSeverity ?? JSON_NULL, alerts_url: status.alertsUrl };
94
- }
95
- function alertsLine(status) {
96
- if (typeof status === 'string')
97
- return ` dependabot_alerts: fetch failed (${status})`;
98
- if (!status.enabled)
99
- return ' dependabot_alerts: disabled';
100
- return ` dependabot_alerts: open ${String(status.openCount)}`;
101
- }
102
- /**
103
- info --json の出力
104
- */
105
- export function infoJson(view, items) {
106
- const { config, projectName, statuses } = view;
107
- const output = {
108
- project: {
109
- name: projectName,
110
- host: config.host,
111
- owner: config.owner,
112
- number: config.project.number,
113
- aggregation_repo: config.aggregation_repo ?? JSON_NULL,
114
- },
115
- repositories: config.repositories.map((entry, index) => ({
116
- full_name: `${entry.owner}/${entry.name}`,
117
- owner: entry.owner,
118
- name: entry.name,
119
- develop_branch: entry.develop_branch ?? JSON_NULL,
120
- release_branch: entry.release_branch ?? JSON_NULL,
121
- dependabot_alerts: alertsJson(statusAt(statuses, index)),
122
- })),
123
- board: formatItemsJson(items),
124
- };
125
- return JSON.stringify(output, undefined, 2);
126
- }
127
- function repositoryLines(view) {
128
- const { config, statuses } = view;
129
- if (config.repositories.length === 0)
130
- return ['## Registered repositories', '- none'];
131
- const lines = ['## Registered repositories'];
132
- for (const [index, entry] of config.repositories.entries()) {
133
- const develop = entry.develop_branch === undefined || entry.develop_branch === '' ? [] : [`develop: ${entry.develop_branch}`];
134
- const release = entry.release_branch === undefined || entry.release_branch === '' ? [] : [`release: ${entry.release_branch}`];
135
- const branches = [...develop, ...release];
136
- const fullName = `${entry.owner}/${entry.name}`;
137
- lines.push(branches.length > 0 ? `- ${fullName} (${branches.join(', ')})` : `- ${fullName}`, ` release_type: ${effectiveReleaseType(entry)}`, alertsLine(statusAt(statuses, index)));
138
- if (entry.packages !== undefined && entry.packages.length > 0) {
139
- for (const item of entry.packages)
140
- lines.push(` package: ${item.name} → ${item.changelog}`);
141
- }
142
- else if (entry.changelog_file !== undefined && entry.changelog_file !== '') {
143
- lines.push(` changelog: ${entry.changelog_file}`);
144
- }
145
- }
146
- return lines;
147
- }
148
- /**
149
- info の Markdown の出力
150
- */
151
- export function infoMarkdown(view, effectiveRepository, boardOutput) {
152
- const { config, projectName } = view;
153
- const aggregation = config.aggregation_repo === undefined || config.aggregation_repo === '' ? 'none' : `\`${config.aggregation_repo}\``;
154
- return [
155
- '# Project info',
156
- '',
157
- '## Overview',
158
- `- Project: ${projectName}`,
159
- `- Host: ${config.host}`,
160
- `- Owner: ${config.owner}`,
161
- `- Roadmap repo: ${aggregation}`,
162
- '',
163
- ...repositoryLines(view),
164
- '',
165
- effectiveRepository === undefined || effectiveRepository === '' ? '## Board status' : `## Board status (filter: ${effectiveRepository})`,
166
- '',
167
- boardOutput,
168
- ].join('\n');
169
- }
170
- /**
171
- ボードのアイテムを全部読み、表示するものに絞る
172
- */
173
- export async function readBoard(client, config, effectiveRepository) {
174
- const fieldName = workflowFieldName(config);
175
- const rawItems = await client.listProjectItems(config.project.id, { workflowFieldName: fieldName });
176
- const allItems = transformItems(rawItems, fieldName);
177
- const open = allItems.filter(item => item.content.state === 'OPEN' && typeof item.workflow === 'string' && DISPLAY_STATUSES.has(item.workflow));
178
- const items = effectiveRepository === undefined || effectiveRepository === '' ? open : open.filter(item => item.content.repository === effectiveRepository);
179
- return { allItems, items };
180
- }
181
- //# sourceMappingURL=project-info.js.map
@@ -1,5 +0,0 @@
1
- /**
2
- ブランチを扱うコマンド。並びは tests/parity/commands.ts と同じ
3
- */
4
- export declare const REPOSITORY_COMMANDS: import("./command-definition.js").CommandDefinition[];
5
- //# sourceMappingURL=repository.d.ts.map
@@ -1,265 +0,0 @@
1
- // リポジトリのブランチを扱うコマンド(create-branch・delete-branch)。Python の cli/commands/repo.py の移植。
2
- import { z } from 'zod';
3
- import { describeApiError } from '../domain/api-error-detail.js';
4
- import { findRepository, getFieldId, getOptionId, isRepositoryInProject } from '../domain/config.js';
5
- import { ReferenceParseError, parseIssueReference, parseRepositoryReference } from '../domain/reference-parser.js';
6
- import { compareStrings, pythonStringRepr } from '../domain/python-format.js';
7
- import { repositoryFullName } from '../domain/repository-resolver.js';
8
- import { FLAG_PECOT_ACTIVE } from '../domain/state.js';
9
- import { GitHubAPIError, isMissingReferenceError } from '../infra/github/errors.js';
10
- import { readFlag } from '../infra/state-store.js';
11
- import { createOutput } from './output.js';
12
- import { defineCommand } from './command-definition.js';
13
- import { requireActiveConfig, stopWith } from './command-stop.js';
14
- import { createGitHubClient } from './github-client.js';
15
- import { USAGE_EXIT_CODE } from './usage-error.js';
16
- import { requireRepositoryMatch, resolveCurrentRepository } from './repository-match.js';
17
- import { recordWorkTarget } from './work-target.js';
18
- /**
19
- A-1. 作業ディレクトリの git remote のリポジトリが Issue のリポジトリと違えば、終了コード 2 で止める
20
- */
21
- function rejectCwdRepositoryMismatch(out, owner, repository) {
22
- const resolved = resolveCurrentRepository(process.cwd());
23
- if (resolved?.source !== 'current-git')
24
- return;
25
- const current = resolved.repository;
26
- if (current.owner === owner && current.repository === repository)
27
- return;
28
- stopWith(out, `the repository of the work Issue (${owner}/${repository}) differs from `
29
- + `the CWD git remote (${repositoryFullName(current)})\n`
30
- + 'move to the worktree of the target repository and run again:\n'
31
- + `<project-root>/base/${repository}/ or <project-root>/<wtN>/${repository}/\n`
32
- + 'create one with /pecot-w:w-worktree-add only if the repository has no worktree\n'
33
- + 'to issue the command on purpose from outside the CWD (for example in a script), '
34
- + 'give --allow-cross-repo', USAGE_EXIT_CODE);
35
- }
36
- /**
37
- 3. ベースブランチを決める(--base を先に、無ければ設定の develop_branch)
38
- */
39
- function resolveBaseBranch(out, query) {
40
- const { config, owner, repository, issueNumber, branchName, base } = query;
41
- if (base !== undefined && base !== '')
42
- return base;
43
- const developBranch = findRepository(config, owner, repository)?.develop_branch;
44
- if (developBranch === undefined || developBranch === '') {
45
- stopWith(out, `develop_branch is not set for ${owner}/${repository}\n`
46
- + `set it with: pecot project set-repo ${owner}/${repository} --develop-branch develop\n`
47
- + `or give the base: pecot create-branch ${owner}/${repository}/${String(issueNumber)} ${branchName} --base main`);
48
- }
49
- return developBranch;
50
- }
51
- /**
52
- A-2. .pecot-active が別の OPEN な Issue を指していれば、終了コード 2 で止める
53
- */
54
- async function guardActiveOverwrite(out, client, issueReference) {
55
- const existing = readFlag(FLAG_PECOT_ACTIVE) ?? '';
56
- if (existing === '' || existing === issueReference)
57
- return;
58
- let existingReference;
59
- try {
60
- existingReference = parseIssueReference(existing);
61
- }
62
- catch (error) {
63
- if (!(error instanceof ReferenceParseError))
64
- throw error;
65
- out.warning(`the content of .pecot-active (${pythonStringRepr(existing)}) is malformed; overwriting it`);
66
- return;
67
- }
68
- const { repository, number } = existingReference;
69
- const { state } = await client.getIssueSlim(repository.owner, repository.repository, number);
70
- if (state === 'OPEN') {
71
- stopWith(out, `this worktree is already working on another Issue (${existing}, OPEN)\n`
72
- + 'overwriting .pecot-active could mix up the tasks\n'
73
- + 'finish the other Issue first, or create another worktree with '
74
- + '/pecot-w:w-worktree-add and run /pecot-w:w-active again in its session\n'
75
- + 'if it is stale and you want to overwrite it on purpose, give --force-overwrite-active', USAGE_EXIT_CODE);
76
- }
77
- out.warning(state === 'CLOSED'
78
- ? `.pecot-active points to closed Issue ${existing}; overwriting it`
79
- : `the state of ${existing} in .pecot-active is unexpected (${pythonStringRepr(state)}); overwriting it`);
80
- }
81
- /**
82
- 7.5. プロジェクトアイテムのステータスを active にする(失敗は warning にとどめる)
83
- */
84
- async function setIssueStatusActive(out, client, config, issue) {
85
- const { owner, repository, number } = issue;
86
- const target = `Issue ${owner}/${repository}/${String(number)} status active`;
87
- try {
88
- const itemId = await client.getItemIdByIssue(config.project.id, owner, repository, number);
89
- if (itemId === undefined || itemId === '') {
90
- out.warning(`could not set ${target}: the Issue is not on the project board`);
91
- return;
92
- }
93
- const fieldId = getFieldId(config, 'workflow');
94
- const optionId = getOptionId(config, 'workflow', 'active');
95
- if (fieldId === undefined || fieldId === '' || optionId === undefined || optionId === '') {
96
- out.warning(`could not set ${target}: the workflow status field has no 'active' option`);
97
- return;
98
- }
99
- await client.updateProjectItemField(config.project.id, itemId, fieldId, optionId);
100
- out.done({ verb: 'set', target });
101
- }
102
- catch (error) {
103
- // ブランチは作成済みなので、ステータスの失敗でコマンドは止めない
104
- if (!(error instanceof GitHubAPIError))
105
- throw error;
106
- out.warning(`could not set ${target}: ${error.message}`);
107
- }
108
- }
109
- const branchCreationCommand = defineCommand({
110
- path: ['create-branch'],
111
- description: 'Create a branch linked to an Issue (shown in the Development section of the Issue)',
112
- input: z.strictObject({
113
- issue_ref: z.string().describe('Issue reference (owner/repo/123)'),
114
- branch_name: z.string().describe('Name of the branch to create'),
115
- base: z.string().optional().describe('Base branch (default: develop_branch from the config)'),
116
- checkout: z.boolean().default(true).describe('Kept for compatibility; has no effect'),
117
- 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)'),
118
- force_overwrite_active: z.boolean().default(false).describe('Disable the .pecot-active overwrite guard (when sure it is stale)'),
119
- }),
120
- positional: ['issue_ref', 'branch_name'],
121
- shortFlags: { base: '-b', allow_cross_repo: '-X', force_overwrite_active: '-F' },
122
- negations: { checkout: '--no-checkout' },
123
- interactive: false,
124
- run: async (input, io) => {
125
- requireRepositoryMatch('reject', input.repo, io, process.cwd());
126
- const out = createOutput(false, io);
127
- // 1. 設定取得
128
- const config = requireActiveConfig(out);
129
- // 2. issue_ref をパース(フル形式必須、基準リポは渡さない)
130
- let issue;
131
- try {
132
- issue = parseIssueReference(input.issue_ref);
133
- }
134
- catch (error) {
135
- if (!(error instanceof ReferenceParseError))
136
- throw error;
137
- return stopWith(out, error.message, USAGE_EXIT_CODE);
138
- }
139
- const { owner, repository } = issue.repository;
140
- const issueNumber = issue.number;
141
- // A-1. 作業ディレクトリと Issue ref のリポジトリの整合チェック
142
- if (!input.allow_cross_repo)
143
- rejectCwdRepositoryMismatch(out, owner, repository);
144
- // 3. ベースブランチ決定(ローカル設定から)
145
- const baseBranch = resolveBaseBranch(out, { config, owner, repository, issueNumber, branchName: input.branch_name, base: input.base });
146
- const finalBranchName = `${input.branch_name}/${String(issueNumber)}`;
147
- try {
148
- const client = createGitHubClient(out, config.host);
149
- // A-2. .pecot-active 上書きガード
150
- if (!input.force_overwrite_active)
151
- await guardActiveOverwrite(out, client, `${owner}/${repository}/${String(issueNumber)}`);
152
- // 4. リポジトリがプロジェクトに含まれているか確認
153
- if (!await isRepositoryInProject(config, owner, repository, client)) {
154
- stopWith(out, `${owner}/${repository} is not in the project`);
155
- }
156
- // 5. Issue Node ID とタイトル取得(タイトルはセッション名用)
157
- const { id: issueNodeId, title: issueTitle } = await client.getIssueNodeIdAndTitle(owner, repository, issueNumber);
158
- // 6. ベースブランチの commit SHA 取得
159
- const baseSha = await client.getBranchSha(owner, repository, baseBranch);
160
- // 7. リンクブランチ作成(ブランチ名末尾に Issue 番号を自動付与)
161
- const createdBranch = await client.createLinkedBranch(issueNodeId, baseSha, finalBranchName);
162
- out.done({ verb: 'create', target: `branch ${createdBranch} in ${owner}/${repository} from ${baseBranch}` });
163
- // 7.5. プロジェクトアイテムのステータスを active に更新
164
- await setIssueStatusActive(out, client, config, { owner, repository, number: issueNumber });
165
- // 9. 作業対象を .pecot-active と .pecot-session-title に保存(hook の自動投稿とセッション名用)
166
- recordWorkTarget(out, owner, repository, issueNumber, issueTitle);
167
- return 0;
168
- }
169
- catch (error) {
170
- if (!(error instanceof GitHubAPIError))
171
- throw error;
172
- out.error(`could not create branch ${finalBranchName} in ${owner}/${repository}: ${error.message}`);
173
- return 1;
174
- }
175
- },
176
- });
177
- const branchDeletionCommand = defineCommand({
178
- path: ['delete-branch'],
179
- description: 'Delete a remote branch (a protected branch is never deleted)',
180
- input: z.strictObject({
181
- repo_ref: z.string().describe('Repository reference (owner/repo)'),
182
- branch: z.string().describe('Name of the branch to delete'),
183
- dry_run: z.boolean().default(false).describe('Show what would be deleted without deleting anything'),
184
- }),
185
- positional: ['repo_ref', 'branch'],
186
- shortFlags: { dry_run: '-n' },
187
- interactive: false,
188
- run: async (input, io) => {
189
- requireRepositoryMatch('reject', input.repo, io, process.cwd());
190
- const out = createOutput(input.dry_run, io);
191
- // 1. repo_ref をパース
192
- let target;
193
- try {
194
- target = parseRepositoryReference(input.repo_ref);
195
- }
196
- catch (error) {
197
- if (!(error instanceof ReferenceParseError))
198
- throw error;
199
- return stopWith(out, error.message, USAGE_EXIT_CODE);
200
- }
201
- const { owner, repository } = target;
202
- // 2. 設定取得
203
- const config = requireActiveConfig(out);
204
- // 3. 保護ブランチ収集(設定の develop_branch・release_branch と、API の既定ブランチ)
205
- const protectedBranches = new Set();
206
- const repositoryConfig = findRepository(config, owner, repository);
207
- for (const branch of [repositoryConfig?.develop_branch, repositoryConfig?.release_branch]) {
208
- if (branch !== undefined && branch !== '')
209
- protectedBranches.add(branch);
210
- }
211
- let client;
212
- try {
213
- client = createGitHubClient(out, config.host);
214
- protectedBranches.add(await client.getRepositoryDefaultBranch(owner, repository));
215
- }
216
- catch (error) {
217
- if (!(error instanceof GitHubAPIError))
218
- throw error;
219
- out.error(`could not read the default branch of ${owner}/${repository}: ${error.message}`);
220
- return 1;
221
- }
222
- // 4. 保護ブランチチェック
223
- if (protectedBranches.has(input.branch)) {
224
- out.error(`${input.branch} is a protected branch\nprotected: ${[...protectedBranches].toSorted(compareStrings).join(', ')}`);
225
- return 1;
226
- }
227
- // 5. dry-run
228
- const operation = { verb: 'delete', target: `remote branch ${input.branch} in ${owner}/${repository}` };
229
- if (input.dry_run) {
230
- out.planned(operation);
231
- return 0;
232
- }
233
- // 6. 削除実行
234
- try {
235
- await client.deleteBranch(owner, repository, input.branch);
236
- }
237
- catch (error) {
238
- if (!(error instanceof GitHubAPIError))
239
- throw error;
240
- out.error(`could not delete remote branch ${input.branch} in ${owner}/${repository}: ${error.message}`);
241
- return 1;
242
- }
243
- out.done(operation);
244
- // wip ブランチも連動削除
245
- const wipBranch = `wip/${input.branch}`;
246
- try {
247
- await client.deleteBranch(owner, repository, wipBranch);
248
- }
249
- catch (error) {
250
- if (!(error instanceof GitHubAPIError))
251
- throw error;
252
- // wip ブランチの削除の失敗だけは、API の応答の本文の詳細も見せる(Python の describe_api_error と同じ)。存在しない場合は何も出さない
253
- if (!isMissingReferenceError(error))
254
- out.warning(`could not delete remote branch ${wipBranch} in ${owner}/${repository}: ${describeApiError(error)}`);
255
- return 0;
256
- }
257
- out.done({ verb: 'delete', target: `remote branch ${wipBranch} in ${owner}/${repository}` });
258
- return 0;
259
- },
260
- });
261
- /**
262
- ブランチを扱うコマンド。並びは tests/parity/commands.ts と同じ
263
- */
264
- export const REPOSITORY_COMMANDS = [branchCreationCommand, branchDeletionCommand];
265
- //# sourceMappingURL=repository.js.map
@@ -1,3 +0,0 @@
1
- import type { CommandDefinition } from './command-definition.js';
2
- export declare const SECURITY_COMMANDS: readonly CommandDefinition[];
3
- //# sourceMappingURL=security.d.ts.map