@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,25 +1,41 @@
1
1
  /* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- 引数の型は readonly にできない */
2
2
  /* eslint-disable security/detect-non-literal-fs-filename -- パスは利用者の引数で決まる */
3
- // issue create。cli/commands/issue.py の issue_create の移植。--prepare・ファイル・-m の 3 つの形がある。
3
+ // issue create。--prepare・ファイル・-m・--freeform の 4 つの形があり、どの形も --dry-run で予行できる。
4
4
  import { existsSync, statSync, writeFileSync } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { z } from 'zod';
7
- import { splitOwnerRepository } from '../domain/repository-resolver.js';
7
+ import { formatPlanTable, formatStackableChains, resolveBatch } from '../domain/batch-plan.js';
8
+ import { decideBoardMove } from '../domain/board-move.js';
9
+ import { getOptionId } from '../domain/config.js';
10
+ import { InternalError, InvalidValueError } from '../domain/errors.js';
11
+ import { splitOwnerRepository, createRepositoryReference } from '../domain/repository-resolver.js';
8
12
  import { FrontmatterError, stripFrontmatter, stripLeadingHtmlComment } from '../domain/frontmatter.js';
9
- import { FLAG_ISSUE_CREATE_SLASH_PENDING, FLAG_ISSUE_PENDING } from '../domain/state.js';
10
- import { compareStrings, pythonStrip, pythonStringRepr } from '../domain/python-format.js';
13
+ import { findBatchDuplicate, planOrders } from '../domain/issue-order.js';
14
+ import { upsertWaitsForMerge } from '../domain/prerequisites.js';
15
+ import { FLAG_ISSUE_CREATE_SLASH_PENDING, FLAG_ISSUE_PENDING, FLAG_PECOT_QUICK_MODE } from '../domain/state.js';
16
+ import { compareStrings, pythonRightStrip, pythonStrip, pythonStringRepr, truncateCodePoints } from '../domain/python-format.js';
17
+ import { createIssueReference, issueReferenceKey, issueReferenceToCliReference } from '../domain/reference-parser.js';
18
+ import { describeReadiness, displayReference, hasStarted, stackChains } from '../domain/readiness.js';
11
19
  import { parseIssueFile } from '../infra/frontmatter-file.js';
20
+ import { DependenciesUnsupportedError, GitHubAPIError } from '../infra/github/errors.js';
21
+ import { DEPENDENCIES_UNSUPPORTED } from '../infra/github/issues.js';
12
22
  import { OutputPathReservationError, normalizePath, outputDirectory, resolveRealPath, withReservedOutputPath } from '../infra/paths.js';
13
- import { consumeFlag } from '../infra/state-store.js';
23
+ import { consumeFlag, touchFlag } from '../infra/state-store.js';
14
24
  import { templateFile } from '../infra/template-store.js';
15
25
  import { readTextFile } from '../infra/text-file.js';
16
- import { defineCommand } from './command-definition.js';
26
+ import { CommandExit, defineCommand } from './command-definition.js';
27
+ import { commandHint, hinted, inputHint, inputNameHint, joinHinted, placeholder } from './command-hint.js';
17
28
  import { stopWith, requireActiveConfigPlain } from './command-stop.js';
18
- import { addToBoardOrWarn, buildIssueTitle, clientForIssueCreate, createIssueOrExit, ISSUE_TYPE_SCHEMA, issuePath, linkToParentEpic, normalizeParentEpicCli, PARENT_EPIC_DESCRIPTION, resolveEpicTargetRepository, resolveParentEpicReference, runWithExit, setIssueFields, summarizeCreatedIssue, TYPE_DEFAULT_STATUS, validateIssueTemplate, validateStatusForType, warnEpicRepositoryException, } from './issue-shared.js';
19
- import { createOutput } from './output.js';
29
+ import { kindOfFailure } from './failure.js';
30
+ import { createGitHubClient } from './github-client.js';
31
+ import { applyBoardMove } from './issue-board.js';
32
+ import { createReadinessCache, readIssueReadiness } from './issue-readiness.js';
33
+ import { addToBoardOrWarn, BACKLOG_TYPES, buildIssueTitle, clientForIssueCreate, createIssueOrExit, ensureRepositoryInProject, ISSUE_TYPE_SCHEMA, issuePath, linkToParentEpic, normalizeParentEpicCli, PARENT_EPIC_DESCRIPTION, readUsedOrders, resolveEpicTargetRepository, resolveParentEpicReference, runWithExit, setIssueFields, stopForDuplicateOrder, summarizeCreatedIssue, TYPE_DEFAULT_STATUS, validateIssueTemplate, validateStatusForType, warnEpicRepositoryException, } from './issue-shared.js';
34
+ import { createOutput, DRY_RUN_FIELD } from './output.js';
20
35
  import { USAGE_EXIT_CODE } from './usage-error.js';
21
36
  const FILES_SCHEMA = z.array(z.string()).optional().describe('Path of a Markdown file with frontmatter (several for a batch post)');
22
37
  const LABEL_SCHEMA = z.array(z.string()).optional().describe('Label (can be given several times)');
38
+ const CREATE_PATH = ['issue', 'create'];
23
39
  const TEMPLATE_SCHEMA = z.enum(['task', 'bug', 'epic', 'tracker', 'task-implement']).default('task').describe('Template type (with --prepare: task/bug/epic/tracker/task-implement)');
24
40
  // 一括投稿の先行 Issue 番号の置き場所。key は先行ファイルの --suffix 由来か、ファイルの stem
25
41
  const PLACEHOLDER_PATTERN = /\{\{issue:([^{}\s]+)\}\}/gu;
@@ -27,46 +43,211 @@ const PLACEHOLDER_PATTERN = /\{\{issue:([^{}\s]+)\}\}/gu;
27
43
  const PREPARED_FILENAME_PATTERN = /^issue-.+-\d{8}-\d{6}-(?<suffix>.+)$/u;
28
44
  // Python の `$` は末尾の改行の前にも当たる
29
45
  const REPOSITORY_SEGMENT_PATTERN = /^[\w.-]+\n?$/u;
46
+ // validateStatusForType が、作るときの status を型の既定(backlog・ready)か、前提があるときの blocked に限る
47
+ const CREATED_STATUS = z.enum(['backlog', 'blocked', 'ready']);
48
+ function isCreatedStatus(value) {
49
+ return CREATED_STATUS.safeParse(value).success;
50
+ }
51
+ const CREATED_ISSUE_DATA = z.strictObject({
52
+ owner: z.string().describe('Owner of the repository of the Issue'),
53
+ repository: z.string().describe('Name of the repository of the Issue'),
54
+ number: z.int().describe('Issue number'),
55
+ url: z.string().describe('URL of the Issue'),
56
+ status: CREATED_STATUS.optional().describe('Workflow status written on the board (ready when it was moved out of blocked; omitted when not written)'),
57
+ parent: z.string().optional().describe('Parent Epic the Issue was added to as a sub-issue (owner/repo/N; omitted when none)'),
58
+ });
59
+ const STACKABLE_CHAINS = z.array(z.array(z.string())).optional().describe('Stackable chains, each from the bottom; files by key, existing Issues as #N or owner/repo#N (omitted when none)');
60
+ const PLAN_PREREQUISITE_DATA = z.strictObject({
61
+ issue: z.string().describe('Prerequisite: key of a file, or #N / owner/repo#N for an existing Issue'),
62
+ wait: z.enum(['stack', 'merge']).describe('How to wait for the prerequisite'),
63
+ });
64
+ const PLAN_ROW_DATA = z.strictObject({
65
+ file: z.string().describe('Key of the file (the --prepare suffix, else the file stem)'),
66
+ order: z.int().optional().describe('Order number in the title (omitted without a parent Epic)'),
67
+ blockedBy: z.array(PLAN_PREREQUISITE_DATA).describe('Prerequisites in the order written'),
68
+ approach: z.enum(['alone', 'wait-merge', 'stack', 'join']).describe('How to proceed'),
69
+ stackOn: z.string().optional().describe('Prerequisite to stack on (only when approach is stack)'),
70
+ });
71
+ const PLANNED_ISSUE_DATA = z.strictObject({
72
+ owner: z.string().describe('Owner of the repository'),
73
+ repository: z.string().describe('Name of the repository'),
74
+ title: z.string().describe('Title of the Issue'),
75
+ });
76
+ const ISSUE_CREATE_OUTPUT = z.strictObject({
77
+ issues: z.array(CREATED_ISSUE_DATA).optional().describe('Issues created, in the order of creation (also kept on a failure after some were created)'),
78
+ stackableChains: STACKABLE_CHAINS,
79
+ plan: z.array(PLAN_ROW_DATA).optional().describe('Progression table of the files (only on dry_run with files)'),
80
+ plannedIssue: PLANNED_ISSUE_DATA.optional().describe('Issue that would be created (only on dry_run with message or freeform)'),
81
+ file: z.string().optional().describe('Absolute path of the template file copied (only with prepare)'),
82
+ dryRun: DRY_RUN_FIELD,
83
+ });
30
84
  // --- 共通 ---
31
85
  // owner/repo の形が不正なら error と終了コード 2。正しければ owner と name を返す
32
86
  function validateRepositoryShape(output, repository) {
33
87
  const parts = splitOwnerRepository(repository);
34
88
  const isValid = parts !== undefined && REPOSITORY_SEGMENT_PATTERN.test(parts.owner) && REPOSITORY_SEGMENT_PATTERN.test(parts.repository);
35
89
  const message = `invalid repository format: ${repository}\nexpected: owner/repo`;
36
- return isValid ? [parts.owner, parts.repository] : stopWith(output, message, USAGE_EXIT_CODE);
90
+ return isValid ? [parts.owner, parts.repository] : stopWith(output, message, 'invalid-input', USAGE_EXIT_CODE);
91
+ }
92
+ function newSession() {
93
+ return { failures: [], cache: createReadinessCache(), issues: [] };
94
+ }
95
+ // 投稿中の Issue は常に末尾にある。isUpdate なら末尾を書き換え、そうでなければ足す
96
+ function recordIssue(output, session, entry, isUpdate) {
97
+ if (isUpdate)
98
+ session.issues.pop();
99
+ session.issues.push(entry);
100
+ output.result({ issues: [...session.issues] });
101
+ }
102
+ function reAddCommand(issue, prerequisite) {
103
+ const base = { issue_ref: issueReferenceToCliReference(issue), by: issueReferenceToCliReference(prerequisite.reference) };
104
+ return commandHint(['issue', 'block'], prerequisite.wait === 'merge' ? { ...base, wait: 'merge', reason: prerequisite.reason ?? '' } : base);
105
+ }
106
+ // 前提を 1 件ずつ付ける。失敗は warning にして続け、付け直すコマンドを session に積む。付けた数を返す
107
+ async function addPrerequisites(output, client, session, issue, issueNodeId, prerequisites) {
108
+ const here = displayReference(issue, issue.repository);
109
+ let linked = 0;
110
+ for (const prerequisite of prerequisites) {
111
+ const there = displayReference(prerequisite.reference, issue.repository);
112
+ try {
113
+ if (issueNodeId === undefined)
114
+ throw new GitHubAPIError('could not read the node ID of the Issue');
115
+ await client.addBlockedBy(issueNodeId, await prerequisite.nodeId());
116
+ }
117
+ catch (error) {
118
+ if (!(error instanceof GitHubAPIError))
119
+ throw error;
120
+ output.warning(`could not add blocked-by ${there} to ${here}: ${error.message}`);
121
+ session.failures.push(reAddCommand(issue, prerequisite));
122
+ continue;
123
+ }
124
+ linked += 1;
125
+ output.done({ verb: 'add', target: `blocked-by ${there} to ${here}` });
126
+ }
127
+ return linked;
128
+ }
129
+ // 列を直す入力。column には、この CLI が今書いた Blocked を渡す
130
+ function boardMoveInput(config, judged) {
131
+ return {
132
+ eligible: judged.target.state === 'open' && judged.target.kind === 'task',
133
+ column: 'Blocked',
134
+ label: judged.target.label,
135
+ hasStarted: hasStarted(judged.target),
136
+ hasPrerequisites: true,
137
+ readiness: judged.readiness,
138
+ labelWrittenByAutomation: false,
139
+ available: {
140
+ blocked: getOptionId(config, 'workflow', 'blocked') !== undefined,
141
+ needsAttention: getOptionId(config, 'status', 'needs_attention') !== undefined,
142
+ todo: getOptionId(config, 'status', 'todo') !== undefined,
143
+ },
144
+ };
145
+ }
146
+ // 既存の Issue を前提に持つ Issue の判定を読み、前提が済んでいれば Ready へ動かす。読めないときは、列をそのままにする
147
+ async function settleColumn(output, client, config, session, issue, item, linked) {
148
+ let judged;
149
+ try {
150
+ judged = await readIssueReadiness(client, config, issue, session.cache);
151
+ }
152
+ catch (error) {
153
+ if (error instanceof DependenciesUnsupportedError)
154
+ return undefined;
155
+ throw error;
156
+ }
157
+ if (judged.kind === 'unreadable' || judged.readiness === undefined)
158
+ return undefined;
159
+ if (judged.prerequisites.length < linked) {
160
+ output.warning(`could not read all blocked-by of ${displayReference(issue, issue.repository)} yet; left it in Blocked`);
161
+ return undefined;
162
+ }
163
+ const move = decideBoardMove(boardMoveInput(config, judged));
164
+ if (move === undefined)
165
+ return undefined;
166
+ // 起票の直後は、既定の自動化が札を書くので、札は書かない
167
+ const applied = await applyBoardMove(output, client, config, item.itemId, { ref: issue, home: issue.repository }, withoutLabel(move), describeReadiness(judged.readiness, judged.prerequisites, issue.repository));
168
+ return applied.column;
169
+ }
170
+ function withoutLabel(move) {
171
+ return { missing: move.missing, ...move.column !== undefined && { column: move.column }, ...move.conflict !== undefined && { conflict: move.conflict } };
37
172
  }
38
173
  /**
39
- Issue を作ってボードへ足し、欄の設定・親 Epic への接続・URL の出力まで行う。
40
- ボードへの追加に失敗したら、そこで止める。作った Issue の番号を返す
174
+ Issue を作り、前提・ボード・欄・列の直し・親 Epic への接続・URL の出力まで順に行う。
175
+ 前提を先に付けるので、後の段で止まっても、作った Issue の前提は付いている。
176
+ ボードへの追加に失敗したら、欄と列は飛ばして親 Epic への接続へ進む
41
177
  */
42
- async function postIssue(output, client, config, posting) {
178
+ async function postIssue(output, client, config, session, posting) {
43
179
  const { owner, repository } = posting;
44
180
  const issue = await createIssueOrExit(output, client, owner, repository, posting.title, posting.body, posting.labels, posting.source);
45
181
  const { number, url, nodeId } = summarizeCreatedIssue(issue);
182
+ const entry = { owner, repository, number, url };
183
+ recordIssue(output, session, entry, false);
46
184
  const target = `Issue ${issuePath(owner, repository, number)}`;
185
+ const reference = createIssueReference(createRepositoryReference(owner, repository), number);
47
186
  consumeFlag(FLAG_ISSUE_PENDING);
48
- const added = await addToBoardOrWarn(output, client, config, owner, repository, number, posting.useResponseNodeId ? nodeId : undefined, url);
49
- if (added === undefined)
50
- return number;
51
- await setIssueFields(output, client, config, added.itemId, target, posting.fields);
52
- if (posting.parentReference !== undefined)
53
- await linkToParentEpic(output, client, target, posting.parentReference, added.issueNodeId, url);
54
- output.data(url);
55
- return number;
187
+ if (posting.consumeSlashPending === true)
188
+ consumeFlag(FLAG_ISSUE_CREATE_SLASH_PENDING);
189
+ // 応答に node_id が無いときだけ、ボードへの追加の結果から取るので、先にボードへ足す
190
+ let added;
191
+ let hasTriedBoard = false;
192
+ let issueNodeId = nodeId;
193
+ if (issueNodeId === undefined && posting.prerequisites.length > 0) {
194
+ added = await addToBoardOrWarn(output, client, config, owner, repository, number, undefined, url);
195
+ hasTriedBoard = true;
196
+ issueNodeId = added?.issueNodeId;
197
+ }
198
+ const linked = await addPrerequisites(output, client, session, reference, issueNodeId, posting.prerequisites);
199
+ if (!hasTriedBoard)
200
+ added = await addToBoardOrWarn(output, client, config, owner, repository, number, posting.useResponseNodeId ? nodeId : undefined, url);
201
+ let isMovedToReady = false;
202
+ let status;
203
+ if (added !== undefined) {
204
+ const written = await setIssueFields(output, client, config, added.itemId, target, posting.fields);
205
+ const option = written.includes('workflow') ? posting.fields.find(field => field.fieldName === 'workflow')?.optionName : undefined;
206
+ if (option !== undefined && isCreatedStatus(option))
207
+ status = option;
208
+ recordIssue(output, session, { ...entry, ...status !== undefined && { status } }, true);
209
+ if (posting.settleColumn && written.includes('workflow') && linked === posting.prerequisites.length) {
210
+ isMovedToReady = await settleColumn(output, client, config, session, reference, added, linked) === 'Ready';
211
+ if (isMovedToReady)
212
+ status = 'ready';
213
+ }
214
+ }
215
+ const knownNodeId = added?.issueNodeId ?? issueNodeId;
216
+ let parent;
217
+ if (posting.parentReference !== undefined) {
218
+ // ボードへの追加に失敗したときは、URL を出し済み
219
+ parent = await linkToParentEpic(output, client, target, posting.parentReference, knownNodeId ?? (() => client.getIssueNodeId(owner, repository, number)), added === undefined ? undefined : url);
220
+ }
221
+ recordIssue(output, session, { ...entry, ...status !== undefined && { status }, ...parent !== undefined && { parent } }, true);
222
+ if (added !== undefined)
223
+ output.data(url);
224
+ return { number, nodeId: knownNodeId, isMovedToReady, isOnBoard: added !== undefined };
225
+ }
226
+ /**
227
+ 予行の行。番号の要るボード・欄・親 Epic の書き込みは出さない
228
+ */
229
+ function planIssue(output, owner, repository, title) {
230
+ output.result({ plannedIssue: { owner, repository, title } });
231
+ output.planned({ verb: 'create', target: `Issue in ${owner}/${repository}: ${title}` });
56
232
  }
57
233
  function parentReferenceOf(raw, config, owner, repository) {
58
234
  return raw === undefined ? undefined : resolveParentEpicReference(raw, config, owner, repository);
59
235
  }
60
236
  // --- --prepare ---
61
- function prepareTemplate(output, template, repository, suffix) {
237
+ function prepareTemplate(output, template, repository, suffix, isDryRun) {
62
238
  if (template !== 'epic' && repository === undefined) {
63
- stopWith(output, '--repo owner/repo is required with --template task|bug|tracker|task-implement', USAGE_EXIT_CODE);
239
+ stopWith(output, hinted `${inputHint(CREATE_PATH, 'repo', placeholder('owner/repo'))} is required with ${inputHint(CREATE_PATH, 'prepare')} unless ${inputHint(CREATE_PATH, 'template', 'epic')}`, 'invalid-input', USAGE_EXIT_CODE);
64
240
  }
65
241
  if (repository !== undefined)
66
242
  validateRepositoryShape(output, repository);
67
243
  const source = templateFile('issue', template);
68
244
  if (!existsSync(source)) {
69
- stopWith(output, `template not found: ${source}`);
245
+ stopWith(output, `template not found: ${source}`, 'other');
246
+ }
247
+ if (isDryRun) {
248
+ output.result({});
249
+ output.planned({ verb: 'create', target: `Issue template ${template} in ${outputDirectory()}` });
250
+ return;
70
251
  }
71
252
  let content = readTextFile(source);
72
253
  // 置き換えの文字列に `$` があっても、そのまま入れる
@@ -76,23 +257,22 @@ function prepareTemplate(output, template, repository, suffix) {
76
257
  try {
77
258
  withReservedOutputPath(outputDirectory(), timestamp => `issue-${template}-${timestamp}${nameSuffix}.md`, (reserved) => {
78
259
  writeFileSync(reserved, content, 'utf8');
260
+ output.result({ file: path.resolve(reserved) });
79
261
  output.data(reserved);
80
262
  });
81
263
  }
82
264
  catch (error) {
83
265
  if (!(error instanceof OutputPathReservationError))
84
266
  throw error;
85
- stopWith(output, error.message);
267
+ stopWith(output, error.message, 'other');
86
268
  }
87
269
  }
88
270
  // --- ファイルからの一括投稿 ---
271
+ // 前提に書けるキーすべて(幹と suffix)と、代表のキー(suffix があれば suffix、無ければ幹)
89
272
  function fileKeys(file) {
90
273
  const stem = path.parse(path.basename(file)).name;
91
- const keys = new Set([stem]);
92
274
  const suffix = PREPARED_FILENAME_PATTERN.exec(stem)?.groups?.['suffix'];
93
- if (suffix !== undefined)
94
- keys.add(suffix);
95
- return keys;
275
+ return suffix === undefined ? { key: stem, keys: [stem] } : { key: suffix, keys: [stem, suffix] };
96
276
  }
97
277
  function isFile(file) {
98
278
  try {
@@ -109,23 +289,23 @@ function validatePlaceholders(output, files) {
109
289
  for (const file of files) {
110
290
  const resolved = resolveRealPath(file);
111
291
  if (seen.has(resolved)) {
112
- stopWith(output, `file specified more than once: ${normalizePath(file)}`);
292
+ stopWith(output, `file specified more than once: ${normalizePath(file)}`, 'invalid-input');
113
293
  }
114
294
  seen.add(resolved);
115
295
  if (!isFile(file)) {
116
- stopWith(output, `file not found: ${normalizePath(file)}`);
296
+ stopWith(output, `file not found: ${normalizePath(file)}`, 'invalid-input');
117
297
  }
118
298
  // フロントマターと冒頭のガイドコメントは投稿本文に出ないので、走査から外す
119
299
  const body = stripLeadingHtmlComment(stripFrontmatter(readTextFile(file)));
120
300
  for (const [, reference] of body.matchAll(PLACEHOLDER_PATTERN)) {
121
301
  if (reference === undefined || available.has(reference))
122
302
  continue;
123
- stopWith(output, `{{issue:${reference}}} in ${path.basename(file)} does not point to an earlier file (forward reference or unknown key)\nput the file it depends on earlier in the arguments`);
303
+ stopWith(output, `{{issue:${reference}}} in ${path.basename(file)} does not point to an earlier file (forward reference or unknown key)\nput the file it depends on earlier in the arguments`, 'content-invalid');
124
304
  }
125
- const keys = fileKeys(file);
126
- const collided = [...keys].filter(key => available.has(key)).toSorted(compareStrings);
305
+ const { keys } = fileKeys(file);
306
+ const collided = keys.filter(key => available.has(key)).toSorted(compareStrings);
127
307
  if (collided.length > 0) {
128
- stopWith(output, `placeholder keys collide: ${collided.join(', ')} (${path.basename(file)})`);
308
+ stopWith(output, `placeholder keys collide: ${collided.join(', ')} (${path.basename(file)})`, 'content-invalid');
129
309
  }
130
310
  for (const key of keys)
131
311
  available.add(key);
@@ -146,28 +326,33 @@ function fileTargetRepository(output, frontmatter, config) {
146
326
  }
147
327
  const parts = splitOwnerRepository(resolved);
148
328
  if (parts === undefined) {
149
- stopWith(output, `invalid repository format in the frontmatter: ${pythonStringRepr(frontmatter.repository)}`);
329
+ stopWith(output, `invalid repository format in the frontmatter: ${pythonStringRepr(frontmatter.repository)}`, 'content-invalid');
150
330
  }
151
331
  return [parts.owner, parts.repository];
152
332
  }
153
- function expandPlaceholders(body, created, owner, repository) {
154
- return body.replaceAll(PLACEHOLDER_PATTERN, (whole, key) => {
155
- const issue = created.get(key);
156
- if (issue === undefined)
157
- return whole;
158
- return issue.repository === `${owner}/${repository}` ? `#${String(issue.number)}` : `${issue.repository}#${String(issue.number)}`;
159
- });
333
+ function stopForFrontmatter(output, error, name) {
334
+ if (error.kind === 'parallel')
335
+ return stopWith(output, `parallel is no longer supported in ${name}. Remove it`, 'content-invalid');
336
+ if (error.kind === 'merge-without-reason')
337
+ return stopWith(output, `blocked_by in ${name} needs reason for wait: merge`, 'content-invalid');
338
+ return stopWith(output, error.message, 'content-invalid');
160
339
  }
161
- function frontmatterFields(frontmatter) {
162
- const fields = [{ fieldName: 'workflow', optionName: frontmatter.status, label: `status ${frontmatter.status}` }];
163
- if (frontmatter.priority !== undefined)
164
- fields.push({ fieldName: 'priority', optionName: frontmatter.priority, label: `priority ${frontmatter.priority}` });
165
- if (frontmatter.size !== undefined)
166
- fields.push({ fieldName: 'size', optionName: frontmatter.size, label: `size ${frontmatter.size}` });
167
- return fields;
340
+ // 投稿の前に、`## Waits for merge` の節が書ける本文かを確かめる(番号は仮)
341
+ function checkWaitsForMergeWritable(output, name, body, home, entries) {
342
+ const entry = entries.find(candidate => candidate.wait === 'merge');
343
+ if (entry === undefined)
344
+ return;
345
+ try {
346
+ upsertWaitsForMerge(body, home, createIssueReference(home, 1), entry.reason ?? 'x');
347
+ }
348
+ catch (error) {
349
+ if (!(error instanceof InvalidValueError))
350
+ throw error;
351
+ stopWith(output, `cannot write the Waits for merge section of ${name}: ${error.message}`, 'content-invalid');
352
+ }
168
353
  }
169
- async function createFromFile(output, file, created) {
170
- const config = requireActiveConfigPlain(output);
354
+ function readLocalFile(output, config, file) {
355
+ const name = path.basename(file);
171
356
  let parsed;
172
357
  try {
173
358
  parsed = parseIssueFile(file);
@@ -175,42 +360,315 @@ async function createFromFile(output, file, created) {
175
360
  catch (error) {
176
361
  if (!(error instanceof FrontmatterError))
177
362
  throw error;
178
- return stopWith(output, error.message);
363
+ return stopForFrontmatter(output, error, name);
179
364
  }
180
365
  const { frontmatter } = parsed;
181
366
  const [owner, repository] = fileTargetRepository(output, frontmatter, config);
182
- const body = created.size > 0 ? expandPlaceholders(parsed.body, created, owner, repository) : parsed.body;
183
- validateIssueTemplate(output, frontmatter.template ?? frontmatter.type, body);
184
- // 作成より前に、純粋な判定で止める
185
- validateStatusForType(output, frontmatter.type, frontmatter.status);
186
- const parentReference = parentReferenceOf(frontmatter.parent_epic, config, owner, repository);
187
- const title = buildIssueTitle(frontmatter.type, frontmatter.title, { parentEpic: parentReference?.number, order: frontmatter.order, parallel: frontmatter.parallel });
188
- const client = await clientForIssueCreate(output, config, owner, repository, frontmatter.repository, parentReference, frontmatter.order, frontmatter.parallel);
189
- const number = await postIssue(output, client, config, {
367
+ const home = createRepositoryReference(owner, repository);
368
+ validateIssueTemplate(output, frontmatter.template ?? frontmatter.type, parsed.body.replaceAll(PLACEHOLDER_PATTERN, '#1'));
369
+ const hasPrerequisites = frontmatter.blocked_by.length > 0;
370
+ const declared = frontmatter.status ?? (hasPrerequisites ? 'blocked' : TYPE_DEFAULT_STATUS[frontmatter.type]);
371
+ validateStatusForType(output, frontmatter.type, declared, hasPrerequisites ? ['blocked'] : undefined);
372
+ checkWaitsForMergeWritable(output, name, parsed.body, home, frontmatter.blocked_by);
373
+ const hasNoBlockedColumn = declared === 'blocked' && getOptionId(config, 'workflow', 'blocked') === undefined;
374
+ const { key, keys } = fileKeys(file);
375
+ return {
376
+ name,
377
+ frontmatter,
378
+ body: parsed.body,
190
379
  owner,
191
380
  repository,
192
- title,
193
- body,
194
- labels: frontmatter.labels.length > 0 ? frontmatter.labels : undefined,
195
- source: path.basename(file),
196
- useResponseNodeId: false,
197
- fields: frontmatterFields(frontmatter),
198
- parentReference,
381
+ key,
382
+ keys,
383
+ parentReference: parentReferenceOf(frontmatter.parent_epic, config, owner, repository),
384
+ status: hasNoBlockedColumn ? 'ready' : declared,
385
+ hasNoBlockedColumn,
386
+ };
387
+ }
388
+ function homeOf(file) {
389
+ return createRepositoryReference(file.owner, file.repository);
390
+ }
391
+ function frontmatterFields(file) {
392
+ const { frontmatter, status } = file;
393
+ const fields = [{ fieldName: 'workflow', optionName: status, label: `status ${status}` }];
394
+ if (frontmatter.priority !== undefined)
395
+ fields.push({ fieldName: 'priority', optionName: frontmatter.priority, label: `priority ${frontmatter.priority}` });
396
+ if (frontmatter.size !== undefined)
397
+ fields.push({ fieldName: 'size', optionName: frontmatter.size, label: `size ${frontmatter.size}` });
398
+ return fields;
399
+ }
400
+ // 同じ親 Epic のファイルを、親ごとに、ファイルの順にまとめる。親の無いファイルは入らない
401
+ function groupByParent(files) {
402
+ const byKey = new Map();
403
+ const groups = [];
404
+ for (const [index, file] of files.entries()) {
405
+ const { parentReference: parent } = file;
406
+ if (parent === undefined)
407
+ continue;
408
+ const key = issueReferenceKey(parent);
409
+ let group = byKey.get(key);
410
+ if (group === undefined) {
411
+ group = { parent, members: [] };
412
+ byKey.set(key, group);
413
+ groups.push(group);
414
+ }
415
+ group.members.push({ index, file });
416
+ }
417
+ return groups;
418
+ }
419
+ function orderRequests(group) {
420
+ return group.members.map(({ file }) => ({ file: file.name, order: file.frontmatter.order }));
421
+ }
422
+ function stopForBatchDuplicate(output, duplicate) {
423
+ return stopWith(output, `order ${String(duplicate.order)} is specified by more than one file: ${duplicate.files.join(', ')}`, 'order-conflict');
424
+ }
425
+ function stopForOrderPlan(output, parent, plan) {
426
+ switch (plan.kind) {
427
+ case 'duplicate-in-batch': {
428
+ return stopForBatchDuplicate(output, plan);
429
+ }
430
+ case 'duplicate-existing': {
431
+ return stopForDuplicateOrder(output, parent.number, plan.order, plan.existing, plan.nextAvailable);
432
+ }
433
+ case 'unreadable-parent': {
434
+ return stopWith(output, `cannot assign order numbers: the parent Epic #${String(parent.number)} could not be read\nspecify order in the frontmatter, or try again`, 'github-api');
435
+ }
436
+ }
437
+ }
438
+ // 親ごとに、使われた番号を読んで番号を振る。ファイルの順に、番号を省いたものへ振った結果を返す
439
+ async function planFileOrders(output, client, files, groups) {
440
+ const assigned = new Map();
441
+ for (const group of groups) {
442
+ const { parent } = group;
443
+ const used = await readUsedOrders(output, client, parent.repository.owner, parent.repository.repository, parent.number);
444
+ const plan = planOrders(used, orderRequests(group));
445
+ if (plan.kind !== 'planned')
446
+ return stopForOrderPlan(output, parent, plan);
447
+ for (const [position, order] of plan.orders.entries()) {
448
+ const member = group.members.at(position);
449
+ if (member === undefined)
450
+ throw new InternalError('the planned orders do not match the files of the parent');
451
+ assigned.set(member.index, order);
452
+ }
453
+ }
454
+ return files.map((_, index) => assigned.get(index));
455
+ }
456
+ // 既存の Issue を前提にしたものの node ID を、投稿の前に読む。読めなければ止める
457
+ async function readExistingPrerequisites(output, client, files, prerequisites) {
458
+ const nodeIds = new Map();
459
+ for (const [index, file] of files.entries()) {
460
+ const own = prerequisites.at(index) ?? [];
461
+ for (const { target } of own) {
462
+ if (target.kind !== 'existing')
463
+ continue;
464
+ const key = issueReferenceKey(target.reference);
465
+ if (nodeIds.has(key))
466
+ continue;
467
+ const { owner, repository } = target.reference.repository;
468
+ try {
469
+ const found = await client.getIssueNodeIdAndTitle(owner, repository, target.reference.number);
470
+ nodeIds.set(key, found.id);
471
+ }
472
+ catch (error) {
473
+ if (!(error instanceof GitHubAPIError))
474
+ throw error;
475
+ stopWith(output, `blocked_by in ${file.name} refers to ${issueReferenceToCliReference(target.reference)}, which could not be read: ${error.message}`, 'dependency-unreadable');
476
+ }
477
+ }
478
+ }
479
+ return nodeIds;
480
+ }
481
+ function chainsText(progressions, labels) {
482
+ return formatStackableChains(progressions, key => labels.get(key) ?? key);
483
+ }
484
+ // formatStackableChains と同じ並びを、表記に直した配列で返す
485
+ function chainsData(progressions, labels) {
486
+ const chains = stackChains(progressions).filter(chain => chain.length >= 2).map(chain => chain.map(key => labels.get(key) ?? key));
487
+ return chains.length === 0 ? {} : { stackableChains: chains };
488
+ }
489
+ function expandPlaceholders(body, created, owner, repository) {
490
+ return body.replaceAll(PLACEHOLDER_PATTERN, (whole, key) => {
491
+ const issue = created.get(key);
492
+ if (issue === undefined)
493
+ return whole;
494
+ return issue.repository === `${owner}/${repository}` ? `#${String(issue.number)}` : `${issue.repository}#${String(issue.number)}`;
199
495
  });
200
- return { repository: `${owner}/${repository}`, number };
201
496
  }
202
- async function createFromFiles(output, files) {
497
+ // blocked_by のあるファイルがあるのに、依存関係に対応しない GHES なら、何も作らずに止める。前提の無い一括は、読み取りを増やさない
498
+ async function ensureDependenciesSupported(output, client, locals) {
499
+ if (locals.every(local => local.frontmatter.blocked_by.length === 0))
500
+ return;
501
+ try {
502
+ if (await client.supportsBlockedBy())
503
+ return;
504
+ }
505
+ catch (error) {
506
+ if (!(error instanceof GitHubAPIError))
507
+ throw error;
508
+ stopWith(output, `could not check whether blocked-by is supported: ${error.message}`, kindOfFailure(error));
509
+ }
510
+ stopWith(output, DEPENDENCIES_UNSUPPORTED, 'dependency-rejected');
511
+ }
512
+ // 1 件も投稿しないうちに確かめられることをすべて確かめ、投稿に要るものをそろえる
513
+ async function prepareBatch(output, files) {
203
514
  validatePlaceholders(output, files);
515
+ const config = requireActiveConfigPlain(output);
516
+ const locals = files.map(file => readLocalFile(output, config, file));
517
+ const [first] = locals;
518
+ if (first === undefined)
519
+ throw new InternalError('no file to post');
520
+ if (locals.some(local => local.hasNoBlockedColumn))
521
+ output.warning('the board has no Blocked column; Issues with blocked-by will be created in Ready');
522
+ const batchFiles = locals.map((local) => ({
523
+ name: local.name,
524
+ key: local.key,
525
+ keys: local.keys,
526
+ blockedBy: local.frontmatter.blocked_by.map(({ issue, wait, reason }) => ({ issue, wait, reason })),
527
+ }));
528
+ const resolution = resolveBatch(batchFiles);
529
+ if (resolution.kind === 'error')
530
+ stopWith(output, resolution.message, 'invalid-input');
531
+ const groups = groupByParent(locals);
532
+ for (const group of groups) {
533
+ const duplicate = findBatchDuplicate(orderRequests(group));
534
+ if (duplicate !== undefined)
535
+ stopForBatchDuplicate(output, duplicate);
536
+ }
537
+ const client = createGitHubClient(output, config.host);
538
+ const checkedRepositories = new Set();
539
+ for (const local of locals) {
540
+ const repository = `${local.owner}/${local.repository}`;
541
+ if (checkedRepositories.has(repository))
542
+ continue;
543
+ checkedRepositories.add(repository);
544
+ await ensureRepositoryInProject(output, config, client, local.owner, local.repository, `${repository} is not linked to the project`);
545
+ }
546
+ await ensureDependenciesSupported(output, client, locals);
547
+ const orders = await planFileOrders(output, client, locals, groups);
548
+ const nodeIds = await readExistingPrerequisites(output, client, locals, resolution.prerequisites);
549
+ return { locals, home: homeOf(first), prerequisites: resolution.prerequisites, progressions: resolution.progressions, orders, nodeIds, client, config };
550
+ }
551
+ function titleOf(local, order) {
552
+ return buildIssueTitle(local.frontmatter.type, local.frontmatter.title, { parentEpic: local.parentReference?.number, order });
553
+ }
554
+ function existingLabels(context) {
555
+ const labels = new Map();
556
+ for (const list of context.prerequisites) {
557
+ for (const { target, key } of list) {
558
+ if (target.kind === 'existing')
559
+ labels.set(key, displayReference(target.reference, context.home));
560
+ }
561
+ }
562
+ return labels;
563
+ }
564
+ function planRowData(row, home) {
565
+ const label = ({ target, key }) => target.kind === 'file' ? key : displayReference(target.reference, home);
566
+ const { progression } = row;
567
+ const stackOn = progression?.kind === 'stack' ? row.prerequisites.find(({ key }) => key === progression.on) : undefined;
568
+ return {
569
+ file: row.file,
570
+ ...row.order !== undefined && { order: row.order },
571
+ blockedBy: row.prerequisites.map(prerequisite => ({ issue: label(prerequisite), wait: prerequisite.wait })),
572
+ approach: progression?.kind ?? 'alone',
573
+ ...progression?.kind === 'stack' && { stackOn: stackOn === undefined ? progression.on : label(stackOn) },
574
+ };
575
+ }
576
+ function printPlan(output, context) {
577
+ const rows = context.locals.map((local, index) => ({
578
+ file: local.key,
579
+ order: context.orders.at(index),
580
+ prerequisites: context.prerequisites.at(index) ?? [],
581
+ progression: context.progressions.get(local.key),
582
+ }));
583
+ const labels = existingLabels(context);
584
+ output.result({ plan: rows.map(row => planRowData(row, context.home)), ...chainsData(context.progressions, labels) });
585
+ const chains = chainsText(context.progressions, labels);
586
+ output.data([formatPlanTable(rows, context.home), ...chains === undefined ? [] : ['', chains]].join('\n'));
587
+ }
588
+ function postPrerequisites(context, index, posted) {
589
+ return (context.prerequisites.at(index) ?? []).map(({ target, key, wait, reason }) => {
590
+ if (target.kind === 'existing') {
591
+ const existingId = context.nodeIds.get(key);
592
+ if (existingId === undefined)
593
+ throw new InternalError(`the node ID of ${key} was not read before posting`);
594
+ return { reference: target.reference, nodeId: () => Promise.resolve(existingId), wait, reason };
595
+ }
596
+ const earlier = posted.at(target.index);
597
+ if (earlier === undefined)
598
+ throw new InternalError('a prerequisite file has not been posted yet');
599
+ return {
600
+ reference: earlier.reference,
601
+ nodeId: () => earlier.nodeId === undefined ? Promise.reject(new GitHubAPIError('could not read the node ID of the Issue')) : Promise.resolve(earlier.nodeId),
602
+ wait,
603
+ reason,
604
+ };
605
+ });
606
+ }
607
+ async function postFiles(output, context) {
608
+ const { locals, client, config } = context;
609
+ const session = newSession();
204
610
  const created = new Map();
205
- for (const file of files) {
206
- const issue = await createFromFile(output, file, created);
207
- for (const key of fileKeys(file))
208
- created.set(key, issue);
611
+ const posted = [];
612
+ const labels = existingLabels(context);
613
+ const progressions = new Map(context.progressions);
614
+ try {
615
+ for (const [index, local] of locals.entries()) {
616
+ const home = homeOf(local);
617
+ const prerequisites = postPrerequisites(context, index, posted);
618
+ let body = expandPlaceholders(local.body, created, local.owner, local.repository);
619
+ for (const prerequisite of prerequisites) {
620
+ if (prerequisite.wait === 'merge')
621
+ body = upsertWaitsForMerge(body, home, prerequisite.reference, prerequisite.reason ?? '');
622
+ }
623
+ const result = await postIssue(output, client, config, session, {
624
+ owner: local.owner,
625
+ repository: local.repository,
626
+ title: titleOf(local, context.orders.at(index)),
627
+ body,
628
+ labels: local.frontmatter.labels.length > 0 ? local.frontmatter.labels : undefined,
629
+ source: local.name,
630
+ useResponseNodeId: false,
631
+ fields: frontmatterFields(local),
632
+ parentReference: local.parentReference,
633
+ prerequisites,
634
+ settleColumn: local.status === 'blocked' && prerequisites.some(({ reference }) => !isBatchReference(reference, posted)),
635
+ });
636
+ const reference = createIssueReference(home, result.number);
637
+ posted.push({ reference, nodeId: result.nodeId });
638
+ labels.set(local.key, displayReference(reference, context.home));
639
+ // Ready へ動かした Issue は、前提が済んでいるので、積む先を持たない
640
+ if (result.isMovedToReady)
641
+ progressions.set(local.key, { kind: 'alone' });
642
+ for (const key of local.keys)
643
+ created.set(key, { repository: `${local.owner}/${local.repository}`, number: result.number });
644
+ }
645
+ }
646
+ finally {
647
+ if (session.failures.length > 0)
648
+ output.error(joinHinted(['could not add some blocked-by; add them again with:', ...session.failures.map(hint => [hint])]));
209
649
  }
210
650
  consumeFlag(FLAG_ISSUE_CREATE_SLASH_PENDING);
651
+ if (session.failures.length > 0)
652
+ throw new CommandExit(1, 'partial-failure');
653
+ output.result(chainsData(progressions, labels));
654
+ const chains = chainsText(progressions, labels);
655
+ if (chains !== undefined)
656
+ output.data(`\n${chains}`);
657
+ }
658
+ // 前提が、この一括で作った Issue か
659
+ function isBatchReference(reference, posted) {
660
+ return posted.some(entry => entry !== undefined && issueReferenceKey(entry.reference) === issueReferenceKey(reference));
661
+ }
662
+ async function createFromFiles(output, files, isDryRun) {
663
+ const context = await prepareBatch(output, files);
664
+ if (isDryRun) {
665
+ printPlan(output, context);
666
+ return;
667
+ }
668
+ await postFiles(output, context);
211
669
  }
212
670
  // config は epic の作成先を決めるときに読み済みなら渡す。無ければ、status の確認の後に読む
213
- async function createDirect(output, options, loadedConfig) {
671
+ async function createDirect(output, options, loadedConfig, isDryRun) {
214
672
  const { issueType } = options;
215
673
  // status は設定の取得や作成より前に確かめる
216
674
  let status;
@@ -228,12 +686,16 @@ async function createDirect(output, options, loadedConfig) {
228
686
  const title = buildIssueTitle(issueType, options.title, { parentEpic: parentReference?.number, order: options.order });
229
687
  validateIssueTemplate(output, issueType, options.message);
230
688
  const client = await clientForIssueCreate(output, config, owner, repository, options.repository, parentReference, options.order);
689
+ if (isDryRun) {
690
+ planIssue(output, owner, repository, title);
691
+ return;
692
+ }
231
693
  const fields = [{ fieldName: 'workflow', optionName: status, label: `status ${status}` }];
232
694
  if (options.priority !== undefined && options.priority !== '')
233
695
  fields.push({ fieldName: 'priority', optionName: options.priority, label: `priority ${options.priority}` });
234
696
  if (options.size !== undefined && options.size !== '')
235
697
  fields.push({ fieldName: 'size', optionName: options.size, label: `size ${options.size}` });
236
- await postIssue(output, client, config, {
698
+ await postIssue(output, client, config, newSession(), {
237
699
  owner,
238
700
  repository,
239
701
  title,
@@ -243,13 +705,15 @@ async function createDirect(output, options, loadedConfig) {
243
705
  useResponseNodeId: true,
244
706
  fields,
245
707
  parentReference,
708
+ prerequisites: [],
709
+ settleColumn: false,
246
710
  });
247
711
  }
248
712
  // -m の作成先。epic 以外は --repo が要る。epic は aggregation_repo の方針で決める
249
713
  function messageModeTarget(output, issueType, repository) {
250
714
  if (issueType !== 'epic') {
251
715
  if (repository === undefined || repository === '') {
252
- stopWith(output, '-r (repository) is required with -m');
716
+ stopWith(output, hinted `${inputNameHint(CREATE_PATH, 'repo')} is required with ${inputNameHint(CREATE_PATH, 'message')}`, 'invalid-input');
253
717
  }
254
718
  return { repository, config: undefined };
255
719
  }
@@ -259,14 +723,79 @@ function messageModeTarget(output, issueType, repository) {
259
723
  warnEpicRepositoryException(output, target.repository, config);
260
724
  return { repository: target.repository, config };
261
725
  }
262
- const USAGE_TEXT = 'missing arguments\n'
263
- + 'direct posting: pecot issue create -t "TITLE" -r owner/repo -m "BODY"\n'
264
- + 'prepare a template: pecot issue create --prepare --template task --repo owner/repo\n'
265
- + 'from a file: pecot issue create <path>';
726
+ const USAGE_TEXT = hinted `missing arguments
727
+ direct posting: ${commandHint(CREATE_PATH, { title: placeholder('TITLE'), repo: 'owner/repo', message: placeholder('BODY') })}
728
+ free format: ${commandHint(CREATE_PATH, { freeform: true, repo: 'owner/repo', message: placeholder('BODY') })}
729
+ prepare a template: ${commandHint(CREATE_PATH, { prepare: true, template: 'task', repo: 'owner/repo' })}
730
+ from a file: ${commandHint(CREATE_PATH, { files: placeholder('path') })}`;
731
+ // --- --freeform ---
732
+ // Python の re の `\s` と同じ集合。JS の `\s` と違い、U+001C〜U+001F を含む。U+FEFF は含まない
733
+ // eslint-disable-next-line no-control-regex -- Python の空白に含まれる制御文字
734
+ const PYTHON_WHITESPACE_RUN = /[\p{White_Space}\u{1C}\u{1D}\u{1E}\u{1F}]+/gu;
735
+ // テンプレートの検証を飛ばす freeform でも、起票規約への参照を本文の末尾に残す
736
+ const FREEFORM_FOOTER = '<!-- issue create の freeform で起票(テンプレ検証スキップ)。起票ルール: skills/w-help/references/issue-flow-rules.md#起票時の既定-status -->';
737
+ const FREEFORM_TITLE_LENGTH = 50;
738
+ /**
739
+ freeform の Issue の欄。priority の既定は medium、size の既定は s(Backlog に置く型には既定を付けない)
740
+ */
741
+ function freeformFields(issueType, status, priority, size) {
742
+ const chosenPriority = priority === undefined || priority === '' ? 'medium' : priority;
743
+ const chosenSize = size === undefined || size === '' ? (BACKLOG_TYPES.has(issueType) ? undefined : 's') : size;
744
+ return [
745
+ { fieldName: 'workflow', optionName: status, label: `status ${status}` },
746
+ { fieldName: 'priority', optionName: chosenPriority, label: `priority ${chosenPriority}` },
747
+ ...chosenSize === undefined ? [] : [{ fieldName: 'size', optionName: chosenSize, label: `size ${chosenSize}` }],
748
+ ];
749
+ }
750
+ // テンプレートを確かめずに、メッセージだけで Issue を作る。タイトルは先頭 50 文字の空白を 1 つにまとめたもの
751
+ async function createFreeform(output, input, isDryRun) {
752
+ const { message, repo, type: issueType } = input;
753
+ if (message === undefined || pythonStrip(message) === '')
754
+ stopWith(output, hinted `${inputNameHint(CREATE_PATH, 'message')} is required with ${inputHint(CREATE_PATH, 'freeform')}`, 'invalid-input', USAGE_EXIT_CODE);
755
+ if (repo === undefined || repo === '')
756
+ stopWith(output, hinted `${inputNameHint(CREATE_PATH, 'repo')} is required with ${inputHint(CREATE_PATH, 'freeform')}`, 'invalid-input', USAGE_EXIT_CODE);
757
+ let status;
758
+ if (input.status === undefined) {
759
+ // eslint-disable-next-line security/detect-object-injection -- issueType は列挙型
760
+ status = TYPE_DEFAULT_STATUS[issueType];
761
+ }
762
+ else {
763
+ validateStatusForType(output, issueType, input.status);
764
+ status = input.status;
765
+ }
766
+ const [owner, repository] = validateRepositoryShape(output, repo);
767
+ const config = requireActiveConfigPlain(output);
768
+ const parentReference = parentReferenceOf(normalizeParentEpicCli(input.parent_epic), config, owner, repository);
769
+ const cleaned = pythonStrip(truncateCodePoints(message, FREEFORM_TITLE_LENGTH).replaceAll(PYTHON_WHITESPACE_RUN, ' '));
770
+ const title = buildIssueTitle(issueType, cleaned, { parentEpic: parentReference?.number, order: input.order });
771
+ const client = await clientForIssueCreate(output, config, owner, repository, repo, parentReference, input.order);
772
+ if (parentReference !== undefined && issueType === 'epic')
773
+ output.warning('giving a parent Epic to an Epic is not recommended');
774
+ if (isDryRun) {
775
+ planIssue(output, owner, repository, title);
776
+ return;
777
+ }
778
+ const posted = await postIssue(output, client, config, newSession(), {
779
+ owner,
780
+ repository,
781
+ title,
782
+ body: `${pythonRightStrip(message)}\n\n${FREEFORM_FOOTER}`,
783
+ labels: input.label !== undefined && input.label.length > 0 ? input.label : undefined,
784
+ source: undefined,
785
+ useResponseNodeId: true,
786
+ fields: freeformFields(issueType, status, input.priority, input.size),
787
+ parentReference,
788
+ prerequisites: [],
789
+ settleColumn: false,
790
+ consumeSlashPending: true,
791
+ });
792
+ if (posted.isOnBoard && !BACKLOG_TYPES.has(issueType))
793
+ touchFlag(FLAG_PECOT_QUICK_MODE);
794
+ }
266
795
  // -m の直接投稿。入力の確認から作成まで
267
- async function createFromMessage(output, input, message) {
796
+ async function createFromMessage(output, input, message, isDryRun) {
268
797
  if (input.title === undefined || input.title === '') {
269
- stopWith(output, '-t (title) is required with -m');
798
+ stopWith(output, hinted `${inputNameHint(CREATE_PATH, 'title')} is required with ${inputNameHint(CREATE_PATH, 'message')}`, 'invalid-input');
270
799
  }
271
800
  const target = messageModeTarget(output, input.type, input.repo);
272
801
  await createDirect(output, {
@@ -280,8 +809,9 @@ async function createFromMessage(output, input, message) {
280
809
  parentEpic: input.parent_epic,
281
810
  labels: input.label,
282
811
  order: input.order,
283
- }, target.config);
284
- consumeFlag(FLAG_ISSUE_CREATE_SLASH_PENDING);
812
+ }, target.config, isDryRun);
813
+ if (!isDryRun)
814
+ consumeFlag(FLAG_ISSUE_CREATE_SLASH_PENDING);
285
815
  }
286
816
  const ISSUE_CREATE = defineCommand({
287
817
  path: ['issue', 'create'],
@@ -300,27 +830,37 @@ const ISSUE_CREATE = defineCommand({
300
830
  parent_epic: z.string().optional().describe(PARENT_EPIC_DESCRIPTION),
301
831
  order: z.int().optional().describe('Order number of the subtask (used with parent_epic)'),
302
832
  label: LABEL_SCHEMA,
833
+ dry_run: z.boolean().default(false).describe('Show what would be created without writing anything (with files: the progression table and stackable chains)'),
834
+ freeform: z.boolean().default(false).describe('Create the Issue from a free-format message without the template check (title from the first 50 characters; priority medium and size s unless given)'),
303
835
  prepare: z.boolean().default(false).describe('Copy a template to the work directory'),
304
836
  template: TEMPLATE_SCHEMA,
305
837
  suffix: z.string().optional().describe('Suffix of the output file name (only with --prepare)'),
306
838
  }),
839
+ output: ISSUE_CREATE_OUTPUT,
307
840
  positional: ['files'],
308
- shortFlags: { message: '-m', title: '-t', repo: '-r', label: '-l', prepare: '-p', suffix: '-s' },
841
+ shortFlags: { message: '-m', title: '-t', repo: '-r', label: '-l', prepare: '-p', suffix: '-s', dry_run: '-n' },
309
842
  interactive: false,
310
843
  run: async (input, io) => {
311
- const output = createOutput(false, io);
844
+ const output = createOutput(input.dry_run, io);
845
+ const hasFiles = input.files !== undefined && input.files.length > 0;
312
846
  return await runWithExit(async () => {
313
- if (input.prepare) {
314
- prepareTemplate(output, input.template, input.repo, input.suffix);
847
+ if ((hasFiles || input.prepare || input.title !== undefined) && input.freeform) {
848
+ stopWith(output, hinted `${inputHint(CREATE_PATH, 'freeform')} cannot be used with ${inputHint(CREATE_PATH, 'prepare')}, ${inputNameHint(CREATE_PATH, 'files')} or ${inputNameHint(CREATE_PATH, 'title')}`, 'invalid-input', USAGE_EXIT_CODE);
849
+ }
850
+ if (input.freeform) {
851
+ await createFreeform(output, input, input.dry_run);
852
+ }
853
+ else if (input.prepare) {
854
+ prepareTemplate(output, input.template, input.repo, input.suffix, input.dry_run);
315
855
  }
316
- else if (input.files !== undefined && input.files.length > 0) {
317
- await createFromFiles(output, input.files);
856
+ else if (hasFiles) {
857
+ await createFromFiles(output, input.files ?? [], input.dry_run);
318
858
  }
319
859
  else if (input.message === undefined) {
320
- stopWith(output, USAGE_TEXT);
860
+ stopWith(output, USAGE_TEXT, 'invalid-input');
321
861
  }
322
862
  else {
323
- await createFromMessage(output, input, input.message);
863
+ await createFromMessage(output, input, input.message, input.dry_run);
324
864
  }
325
865
  });
326
866
  },