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