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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/cli/dist/commands/branch.js +1 -18
  4. package/cli/dist/commands/issue-board.d.ts +1 -1
  5. package/cli/dist/commands/issue-board.js +1 -1
  6. package/cli/dist/commands/issue-create.js +7 -11
  7. package/cli/dist/commands/issue-dependency.js +21 -12
  8. package/cli/dist/commands/issue-shared.d.ts +8 -2
  9. package/cli/dist/commands/issue-shared.js +22 -4
  10. package/cli/dist/commands/names.d.ts +1 -1
  11. package/cli/dist/commands/names.js +2 -3
  12. package/cli/dist/commands/pr-merge.js +9 -14
  13. package/cli/dist/commands/pr-restack.js +16 -18
  14. package/cli/dist/commands/pr.js +54 -44
  15. package/cli/dist/commands/project.js +2 -2
  16. package/cli/dist/commands/renamed-commands.js +0 -1
  17. package/cli/dist/commands/restack-reading.d.ts +45 -0
  18. package/cli/dist/commands/restack-reading.js +29 -0
  19. package/cli/dist/commands/session-finish.js +6 -18
  20. package/cli/dist/commands/session-start.js +10 -55
  21. package/cli/dist/commands/session.js +51 -168
  22. package/cli/dist/commands/work-target.d.ts +5 -8
  23. package/cli/dist/commands/work-target.js +17 -19
  24. package/cli/dist/domain/branch-name.d.ts +7 -0
  25. package/cli/dist/domain/branch-name.js +23 -1
  26. package/cli/dist/domain/command-hint.d.ts +1 -1
  27. package/cli/dist/domain/pull-request.d.ts +19 -2
  28. package/cli/dist/domain/pull-request.js +25 -9
  29. package/cli/dist/domain/restack.d.ts +4 -0
  30. package/cli/dist/domain/restack.js +4 -0
  31. package/cli/dist/domain/state.d.ts +2 -12
  32. package/cli/dist/domain/state.js +3 -14
  33. package/cli/dist/infra/git.d.ts +5 -0
  34. package/cli/dist/infra/git.js +7 -0
  35. package/cli/dist/infra/paths.d.ts +1 -3
  36. package/cli/dist/infra/paths.js +2 -45
  37. package/cli/dist/infra/state-store.d.ts +3 -8
  38. package/cli/dist/infra/state-store.js +6 -24
  39. package/cli/templates/workflow/pecot-board-sync.yml +3 -2
  40. package/npm-shrinkwrap.json +2 -2
  41. package/package.json +1 -1
@@ -1,47 +1,28 @@
1
- // session show・session restore。cli/commands/session.py の移植。
1
+ // session show。cli/commands/session.py の移植。
2
2
  import { z } from 'zod';
3
- import { extractIssueNumberFromBranch } from '../domain/branch-name.js';
4
3
  import { ConfigError } from '../domain/config.js';
5
- import { PecotError } from '../domain/errors.js';
6
- import { pickLowerPullRequest } from '../domain/pull-request.js';
7
4
  import { describeReadiness } from '../domain/readiness.js';
8
- import { decideRestack, describeNeedsRestack, needsRestack } from '../domain/restack.js';
9
- import { issueReferenceToCliReference, parseIssueReference, ReferenceParseError } from '../domain/reference-parser.js';
10
- import { FLAG_PECOT_ACTIVE } from '../domain/state.js';
5
+ import { describeNeedsRestack, needsRestack } from '../domain/restack.js';
6
+ import { issueReferenceToCliReference, issueReferenceToString } from '../domain/reference-parser.js';
7
+ import { ProjectRootNotFoundError } from '../domain/errors.js';
11
8
  import { describeStackBase } from '../domain/work-start.js';
12
9
  import { loadActiveConfig } from '../infra/config-store.js';
13
- import { gitCurrentBranch, primaryRemoteName, primaryRemoteRepository, remoteBranchHead } from '../infra/git.js';
10
+ import { activeIssueOf, gitCurrentBranch, gitToplevel, primaryRemoteName, primaryRemoteRepository } from '../infra/git.js';
14
11
  import { GitHubAPIError } from '../infra/github/errors.js';
15
- import { hasFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
12
+ import { projectRoot, resolveRealPath } from '../infra/paths.js';
13
+ import { readBaseRecord } from '../infra/state-store.js';
16
14
  import { defineCommand } from './command-definition.js';
17
- import { FAILURE_EXIT_CODE } from './failure.js';
18
- import { commandHint, hinted, placeholder } from './command-hint.js';
19
- import { stopWith } from './command-stop.js';
20
15
  import { directorySchema } from './directory-option.js';
21
16
  import { createGitHubClient } from './github-client.js';
22
17
  import { createReadinessCache, readIssueReadinessIfSupported } from './issue-readiness.js';
23
- import { issuePath } from './issue-shared.js';
24
- import { createOutput, DRY_RUN_FIELD } from './output.js';
18
+ import { createOutput } from './output.js';
19
+ import { readRestackDecision } from './restack-reading.js';
25
20
  import { SESSION_FINISH_COMMANDS } from './session-finish.js';
26
21
  import { SESSION_START_COMMANDS } from './session-start.js';
27
- import { USAGE_EXIT_CODE } from './usage-error.js';
28
- import { planWorkTarget, recordWorkTarget } from './work-target.js';
29
- const ALL_FLAGS = [FLAG_PECOT_ACTIVE];
30
- function collectFlagStatuses() {
31
- return ALL_FLAGS.map((name) => {
32
- const isSet = hasFlag(name);
33
- return { name, isSet, content: isSet ? readFlag(name) ?? '' : '' };
34
- });
35
- }
36
- const FLAG_DATA = z.strictObject({
37
- name: z.string().describe('Name of the session flag'),
38
- isSet: z.boolean().describe('Whether the flag is set'),
39
- content: z.string().describe('Content of the flag (empty when unset)'),
40
- });
41
22
  const ACTIVE_ISSUE_DATA = z.strictObject({
42
- reference: z.string().describe('Issue in .pecot-active (owner/repo/N)'),
43
- title: z.string().describe('Title of the Issue'),
44
- state: z.string().describe('State of the Issue (OPEN or CLOSED)'),
23
+ reference: z.string().describe('Work Issue found from the git remote and the number that ends the branch name (owner/repo/N, the form issue_ref takes)'),
24
+ title: z.string().optional().describe('Title of the Issue (omitted when it cannot be read from GitHub)'),
25
+ state: z.string().optional().describe('State of the Issue, OPEN or CLOSED (omitted when it cannot be read from GitHub)'),
45
26
  });
46
27
  const BASE_PULL_REQUEST_DATA = z.strictObject({
47
28
  number: z.int().describe('PR number'),
@@ -61,26 +42,18 @@ const STACKED_ABOVE_DATA = z.strictObject({
61
42
  const SESSION_SHOW_OUTPUT = z.strictObject({
62
43
  branch: z.string().optional().describe('Current branch (omitted when it cannot be read)'),
63
44
  repository: z.string().optional().describe('Repository of the git remote (owner/repo; omitted when it cannot be read)'),
64
- inferredIssue: z.int().optional().describe('Issue number inferred from the branch name (omitted when none)'),
65
- flags: z.array(FLAG_DATA).describe('Session flags'),
66
- activeIssue: ACTIVE_ISSUE_DATA.optional().describe('Issue in .pecot-active as read from GitHub (omitted when unset or unreadable)'),
45
+ activeIssue: ACTIVE_ISSUE_DATA.optional().describe('Work Issue of the session (omitted when there is none)'),
67
46
  stack: STACK_DATA.optional().describe('Base the work was stacked on (omitted when not stacked)'),
68
47
  stackedAbove: z.array(STACKED_ABOVE_DATA).optional().describe('Open PRs whose base is the current branch (omitted when there are none or they cannot be read)'),
69
48
  });
70
- // .pecot-active の Issue を GitHub から読んで、Markdown の行にする。読めなければ warning だけ出して undefined にする
71
- async function readActiveIssue(statuses, output) {
72
- const active = statuses.find(status => status.name === FLAG_PECOT_ACTIVE && status.isSet && status.content !== '');
73
- if (active === undefined)
49
+ // 作業中の Issue(remote とブランチ名から求める)を GitHub から読んで、Markdown の行にする。
50
+ // 作業中の Issue が無ければ undefined。読めなければ warning を出し、参照だけを返す
51
+ async function readActiveIssue(directory, output) {
52
+ const reference = activeIssueOf(directory);
53
+ if (reference === undefined)
74
54
  return undefined;
75
- let reference;
76
- try {
77
- reference = parseIssueReference(active.content);
78
- }
79
- catch (error) {
80
- if (error instanceof ReferenceParseError)
81
- return undefined;
82
- throw error;
83
- }
55
+ const label = issueReferenceToString(reference);
56
+ const data = { reference: issueReferenceToCliReference(reference) };
84
57
  let issue;
85
58
  let config;
86
59
  let client;
@@ -88,7 +61,7 @@ async function readActiveIssue(statuses, output) {
88
61
  config = loadActiveConfig();
89
62
  if (config === undefined) {
90
63
  output.warning('cannot read the active Issue: no active project');
91
- return undefined;
64
+ return { label, data };
92
65
  }
93
66
  client = createGitHubClient(output, config.host);
94
67
  issue = await client.getIssueSlim(reference.repository.owner, reference.repository.repository, reference.number, 0);
@@ -96,14 +69,29 @@ async function readActiveIssue(statuses, output) {
96
69
  catch (error) {
97
70
  if (error instanceof ConfigError || error instanceof GitHubAPIError) {
98
71
  output.warning(`cannot read the active Issue: ${error.message}`);
99
- return undefined;
72
+ return { label, data };
100
73
  }
101
74
  throw error;
102
75
  }
103
76
  const lines = ['', '## Active Issue', '', `#${String(issue.number)} ${issue.title} (${issue.state})`];
104
77
  if (issue.body !== '')
105
78
  lines.push('', issue.body);
106
- return { reference, config, client, lines, data: { reference: issueReferenceToCliReference(reference), title: issue.title, state: issue.state } };
79
+ return { label, data: { ...data, title: issue.title, state: issue.state }, read: { reference, config, client, lines } };
80
+ }
81
+ // -D の directory がプロジェクトルートの worktree か。積んだ記録(.pecot-base)はプロジェクトルートの状態にあるので、
82
+ // 別の worktree の作業には付けない
83
+ function isProjectRootWorktree(directory) {
84
+ const toplevel = gitToplevel({ cwd: directory });
85
+ if (toplevel === undefined)
86
+ return false;
87
+ try {
88
+ return resolveRealPath(toplevel) === resolveRealPath(projectRoot());
89
+ }
90
+ catch (error) {
91
+ if (error instanceof ProjectRootNotFoundError)
92
+ return false;
93
+ throw error;
94
+ }
107
95
  }
108
96
  // 積んで着手した作業ディレクトリの `## Stack` の節。積んでいなければ空
109
97
  async function stackSection(active, origin, directory, output) {
@@ -115,19 +103,12 @@ async function stackSection(active, origin, directory, output) {
115
103
  const { record, stackedOn } = reading;
116
104
  // ブランチは作業ディレクトリのリポにあるので、PR もそこで探す(pr restack と同じ)
117
105
  const { owner, repository } = origin ?? stackedOn.repository;
118
- let pullRequest;
119
- let restack;
120
- try {
121
- const found = await active.client.listPullRequestsByHead(owner, repository, record.branch);
122
- pullRequest = pickLowerPullRequest(found.pullRequests);
123
- restack = restackDecision(reading, pullRequest, directory);
124
- }
125
- catch (error) {
126
- if (!(error instanceof GitHubAPIError))
127
- throw error;
128
- output.warning(`cannot read the PR of the base branch: ${error.message}`);
129
- pullRequest = 'unknown';
130
- }
106
+ // 載せ直す先は、fetch せずに、下の段の remote の先頭を尋ねて記録と比べる
107
+ const read = await readRestackDecision({ client: () => active.client, owner, repository, cwd: directory, remote: primaryRemoteName(directory), reading, developBranch: '' });
108
+ if (read.kind === 'pull-request-unreadable')
109
+ output.warning(`cannot read the PR of the base branch: ${read.error.message}`);
110
+ const pullRequest = read.kind === 'pull-request-unreadable' ? 'unknown' : read.lowerPullRequest;
111
+ const restack = read.kind === 'decided' ? read.decision : undefined;
131
112
  const readiness = await blockedReadiness(active, output);
132
113
  const needsLine = restack === undefined ? undefined : describeNeedsRestack(restack);
133
114
  const needed = restack === undefined ? undefined : needsRestack(restack);
@@ -142,14 +123,6 @@ async function stackSection(active, origin, directory, output) {
142
123
  },
143
124
  };
144
125
  }
145
- // 載せ直す先の判断。fetch せずに、下の段の remote の先頭を尋ねて記録と比べる。remote に届かなければ undefined
146
- function restackDecision(reading, lowerPullRequest, directory) {
147
- const remote = primaryRemoteName(directory);
148
- if (remote === undefined)
149
- return undefined;
150
- const lowerHead = remoteBranchHead(directory, remote, reading.record.branch);
151
- return lowerHead.isReachable ? decideRestack({ reading, developBranch: '', lowerPullRequest, lowerHead: lowerHead.sha }) : undefined;
152
- }
153
126
  // 今のブランチを base にした、同じリポの開いている PR。読めなければ warning を出して undefined にする
154
127
  async function readStackedAbove(active, origin, branch, output) {
155
128
  try {
@@ -184,7 +157,7 @@ async function blockedReadiness(active, output) {
184
157
  }
185
158
  const SESSION_SHOW = defineCommand({
186
159
  path: ['session', 'show'],
187
- description: 'Show the session flag state, branch information, and inferred Issue',
160
+ description: 'Show the branch, repository and work Issue of the session',
188
161
  input: z.object({ directory: directorySchema }),
189
162
  output: SESSION_SHOW_OUTPUT,
190
163
  positional: [],
@@ -194,17 +167,14 @@ const SESSION_SHOW = defineCommand({
194
167
  const output = createOutput(false, io);
195
168
  const branch = gitCurrentBranch(input.directory);
196
169
  const origin = primaryRemoteRepository(input.directory);
197
- const issueNumber = branch === undefined ? undefined : extractIssueNumberFromBranch(branch);
198
- const statuses = collectFlagStatuses();
199
- const active = await readActiveIssue(statuses, output);
200
- const stack = active === undefined ? { lines: [] } : await stackSection(active, origin, input.directory, output);
170
+ const reading = await readActiveIssue(input.directory, output);
171
+ const active = reading?.read;
172
+ const stack = active === undefined || !isProjectRootWorktree(input.directory) ? { lines: [] } : await stackSection(active, origin, input.directory, output);
201
173
  const above = active === undefined || origin === undefined || branch === undefined ? undefined : await readStackedAbove(active, origin, branch, output);
202
174
  output.result({
203
175
  ...branch !== undefined && { branch },
204
176
  ...origin !== undefined && { repository: `${origin.owner}/${origin.repository}` },
205
- ...issueNumber !== undefined && { inferredIssue: issueNumber },
206
- flags: statuses.map(status => ({ ...status })),
207
- ...active !== undefined && { activeIssue: active.data },
177
+ ...reading !== undefined && { activeIssue: reading.data },
208
178
  ...stack.data !== undefined && { stack: stack.data },
209
179
  ...above !== undefined && above.length > 0 && { stackedAbove: above },
210
180
  });
@@ -213,11 +183,7 @@ const SESSION_SHOW = defineCommand({
213
183
  '',
214
184
  `- Branch: ${branch ?? 'unknown'}`,
215
185
  `- Repository: ${origin === undefined ? 'unknown' : `${origin.owner}/${origin.repository}`}`,
216
- `- Inferred Issue: ${issueNumber === undefined ? 'none' : `#${String(issueNumber)}`}`,
217
- '',
218
- '| Flag | State | Content |',
219
- '|------|-------|---------|',
220
- ...statuses.map(status => `| ${status.name} | ${status.isSet ? 'set' : 'unset'} | ${status.content} |`),
186
+ `- Active Issue: ${reading === undefined ? 'none' : reading.label}`,
221
187
  ...active?.lines ?? [],
222
188
  ...withStackedAbove(stack.lines, above),
223
189
  ];
@@ -225,91 +191,8 @@ const SESSION_SHOW = defineCommand({
225
191
  return 0;
226
192
  },
227
193
  });
228
- // セッション名に添える題名。設定が無いか API が失敗したときだけ空にする。設定が読めないなら ConfigError を伝える
229
- async function fetchIssueTitle(owner, repository, number, output) {
230
- try {
231
- const config = loadActiveConfig();
232
- if (config === undefined)
233
- return '';
234
- const issue = await createGitHubClient(output, config.host).getIssueSlim(owner, repository, number, 0);
235
- return issue.title;
236
- }
237
- catch (error) {
238
- if (error instanceof ConfigError)
239
- throw error;
240
- if (error instanceof PecotError)
241
- return '';
242
- throw error;
243
- }
244
- }
245
- // issue_ref が無いときの、ブランチ名と remote からの推定。決められなければ error を出して終了コード 1
246
- function inferTarget(directory, output) {
247
- const branch = gitCurrentBranch(directory);
248
- if (branch === undefined) {
249
- return stopWith(output, 'cannot read the branch name', 'git-unresolved', FAILURE_EXIT_CODE);
250
- }
251
- const number = extractIssueNumberFromBranch(branch);
252
- if (number === undefined) {
253
- return stopWith(output, hinted `cannot infer the Issue number from the branch name: ${branch}\nrun: ${commandHint(['session', 'restore'], { issue_ref: placeholder('owner/repo/N') })}`, 'git-unresolved', FAILURE_EXIT_CODE);
254
- }
255
- const origin = primaryRemoteRepository(directory);
256
- const message = 'cannot read the repository information';
257
- return origin === undefined ? stopWith(output, message, 'git-unresolved', FAILURE_EXIT_CODE) : { owner: origin.owner, repository: origin.repository, number };
258
- }
259
- // issue_ref の参照を分ける。形が誤っていれば error を出して終了コード 2
260
- function parseTarget(issue, output) {
261
- try {
262
- const reference = parseIssueReference(issue);
263
- return { owner: reference.repository.owner, repository: reference.repository.repository, number: reference.number };
264
- }
265
- catch (error) {
266
- if (!(error instanceof ReferenceParseError))
267
- throw error;
268
- return stopWith(output, error.message, 'invalid-input', USAGE_EXIT_CODE);
269
- }
270
- }
271
- const SESSION_RESTORE_OUTPUT = z.strictObject({
272
- issue: z.string().describe('Work Issue recorded (owner/repo/N)'),
273
- workDirectory: z.string().optional().describe('Absolute path of the work directory (omitted on dry_run or when it could not be created)'),
274
- dryRun: DRY_RUN_FIELD,
275
- });
276
- const SESSION_RESTORE = defineCommand({
277
- path: ['session', 'restore'],
278
- description: 'Restore lost session flags (such as .pecot-active) from the branch information',
279
- input: z.object({
280
- issue_ref: z.string().optional().describe('Issue reference (owner/repo/number)'),
281
- directory: directorySchema,
282
- dry_run: z.boolean().default(false).describe('Show what would be recorded without writing anything'),
283
- }),
284
- output: SESSION_RESTORE_OUTPUT,
285
- positional: [],
286
- shortFlags: { issue_ref: '-i', directory: '-D', dry_run: '-n' },
287
- interactive: false,
288
- run: async (input, io) => {
289
- const output = createOutput(input.dry_run, io);
290
- const target = input.issue_ref === undefined ? inferTarget(input.directory, output) : parseTarget(input.issue_ref, output);
291
- let title;
292
- try {
293
- title = await fetchIssueTitle(target.owner, target.repository, target.number, output);
294
- }
295
- catch (error) {
296
- if (!(error instanceof ConfigError))
297
- throw error;
298
- return stopWith(output, error.message, 'config-invalid', FAILURE_EXIT_CODE);
299
- }
300
- const issue = issuePath(target.owner, target.repository, target.number);
301
- if (input.dry_run) {
302
- output.result({ issue });
303
- planWorkTarget(output, target.owner, target.repository, target.number);
304
- return 0;
305
- }
306
- const recorded = recordWorkTarget(output, target.owner, target.repository, target.number, title, { failWithExit: true });
307
- output.result({ issue, ...recorded.workDirectory !== undefined && { workDirectory: recorded.workDirectory } });
308
- return 0;
309
- },
310
- });
311
194
  /**
312
195
  session のグループのコマンド。start は session-start.ts、finish は session-finish.ts にある。並びは help の一覧に出る順
313
196
  */
314
- export const SESSION_COMMANDS = [...SESSION_START_COMMANDS, SESSION_SHOW, SESSION_RESTORE, ...SESSION_FINISH_COMMANDS];
197
+ export const SESSION_COMMANDS = [...SESSION_START_COMMANDS, SESSION_SHOW, ...SESSION_FINISH_COMMANDS];
315
198
  //# sourceMappingURL=session.js.map
@@ -1,10 +1,6 @@
1
1
  import type { BaseRecord } from '../domain/state.js';
2
2
  import type { Output } from './output.js';
3
3
  export interface RecordWorkTargetOptions {
4
- /**
5
- 真なら、記録の失敗を warning ではなく error の行で出し、終了コード 1 で止める
6
- */
7
- readonly failWithExit?: boolean;
8
4
  /**
9
5
  着手で選んだ base。作業対象を記録できたときに .pecot-base へ書く。省くと .pecot-base は消えたままになる
10
6
  */
@@ -19,12 +15,13 @@ export interface RecordedWorkTarget {
19
15
  readonly workDirectory?: string | undefined;
20
16
  }
21
17
  /**
22
- .pecot-base を消してから作業対象を書き、`set: work target ...` の行を出す。options.base があれば記録後に .pecot-base も書く。
23
- 失敗は warning の行。failWithExit なら error の行と CommandExit(1)。記録できたかと、行に出した参照・作業ディレクトリを返す
18
+ .pecot-base を消してからセッション名のキャッシュを書き、作業ディレクトリを作って `create: work directory ...` の行を出す。
19
+ 作業ディレクトリがすでにあっても同じ行を出す。options.base があれば記録後に .pecot-base も書く。
20
+ 失敗は warning の行。記録できたかと、参照・作業ディレクトリを返す
24
21
  */
25
22
  export declare function recordWorkTarget(out: Readonly<Output>, owner: string, repository: string, issueNumber: number, title: string, options?: Readonly<RecordWorkTargetOptions>): RecordedWorkTarget;
26
23
  /**
27
- 予行の行。recordWorkTarget が書く作業対象(.pecot-active・.pecot-session-title・.pecot-base)を書かずに出す
24
+ 予行の行。recordWorkTarget が作る作業ディレクトリ(と書く .pecot-session-title・.pecot-base)を作らずに出す
28
25
  */
29
- export declare function planWorkTarget(out: Readonly<Output>, owner: string, repository: string, issueNumber: number): void;
26
+ export declare function planWorkTarget(out: Readonly<Output>, issueNumber: number): void;
30
27
  //# sourceMappingURL=work-target.d.ts.map
@@ -1,10 +1,9 @@
1
- // 作業対象(.pecot-active と .pecot-session-title、作業ディレクトリ)を記録して、結果の行を出す。
1
+ // 作業対象のセッション名のキャッシュ(.pecot-session-title)と作業ディレクトリを作って、結果の行を出す。
2
2
  import { InvalidValueError, ProjectRootNotFoundError } from '../domain/errors.js';
3
3
  import { FLAG_PECOT_BASE } from '../domain/state.js';
4
4
  import { OsError, hasErrorCode, toOsError } from '../infra/os-error.js';
5
5
  import { WORK_DIR } from '../infra/paths.js';
6
- import { ensureWorkDirectory, removeFlag, writeBaseRecord, writeWorkTarget } from '../infra/state-store.js';
7
- import { stopWith } from './command-stop.js';
6
+ import { ensureWorkDirectory, removeFlag, writeBaseRecord, writeSessionTitle } from '../infra/state-store.js';
8
7
  /**
9
8
  記録の失敗として扱う例外か。OS の失敗・値の誤り・プロジェクトルート不明。プログラムの誤りは伝える
10
9
  */
@@ -16,35 +15,34 @@ function describeFailure(error) {
16
15
  return converted instanceof Error ? converted.message : error.message;
17
16
  }
18
17
  /**
19
- .pecot-base を消してから作業対象を書き、`set: work target ...` の行を出す。options.base があれば記録後に .pecot-base も書く。
20
- 失敗は warning の行。failWithExit なら error の行と CommandExit(1)。記録できたかと、行に出した参照・作業ディレクトリを返す
18
+ .pecot-base を消してからセッション名のキャッシュを書き、作業ディレクトリを作って `create: work directory ...` の行を出す。
19
+ 作業ディレクトリがすでにあっても同じ行を出す。options.base があれば記録後に .pecot-base も書く。
20
+ 失敗は warning の行。記録できたかと、参照・作業ディレクトリを返す
21
21
  */
22
22
  export function recordWorkTarget(out, owner, repository, issueNumber, title, options = {}) {
23
23
  const issueReference = `${owner}/${repository}/${String(issueNumber)}`;
24
24
  clearBase(out);
25
- let target;
26
- let workDirectory;
27
25
  try {
28
- writeWorkTarget(issueReference, title);
29
- target = `work target ${issueReference}`;
30
- workDirectory = ensureWorkDirectory(issueReference);
31
- if (workDirectory !== undefined)
32
- target += ` (work directory ${WORK_DIR}/${String(issueNumber)}/)`;
26
+ writeSessionTitle(issueReference, title);
33
27
  }
34
28
  catch (error) {
35
29
  if (!isRecordingFailure(error))
36
30
  throw error;
37
- if (options.failWithExit === true) {
38
- stopWith(out, `could not record the work target: ${describeFailure(error)}`, 'other');
39
- }
40
31
  out.warning(`could not record the work target: ${describeFailure(error)}`);
41
32
  return { status: 'failed', issue: issueReference };
42
33
  }
43
- out.done({ verb: 'set', target });
34
+ const workDirectory = ensureWorkDirectory(issueReference);
35
+ if (workDirectory === undefined)
36
+ out.warning(`could not create ${workDirectoryTarget(issueNumber)}`);
37
+ else
38
+ out.done({ verb: 'create', target: workDirectoryTarget(issueNumber) });
44
39
  if (options.base !== undefined)
45
40
  recordBase(options.base, out);
46
41
  return { status: 'recorded', issue: issueReference, workDirectory };
47
42
  }
43
+ function workDirectoryTarget(issueNumber) {
44
+ return `work directory ${WORK_DIR}/${String(issueNumber)}/`;
45
+ }
48
46
  function warnBase(out, error) {
49
47
  if (!isRecordingFailure(error))
50
48
  throw error;
@@ -76,9 +74,9 @@ function recordBase(record, out) {
76
74
  }
77
75
  }
78
76
  /**
79
- 予行の行。recordWorkTarget が書く作業対象(.pecot-active・.pecot-session-title・.pecot-base)を書かずに出す
77
+ 予行の行。recordWorkTarget が作る作業ディレクトリ(と書く .pecot-session-title・.pecot-base)を作らずに出す
80
78
  */
81
- export function planWorkTarget(out, owner, repository, issueNumber) {
82
- out.planned({ verb: 'set', target: `work target ${owner}/${repository}/${String(issueNumber)}` });
79
+ export function planWorkTarget(out, issueNumber) {
80
+ out.planned({ verb: 'create', target: workDirectoryTarget(issueNumber) });
83
81
  }
84
82
  //# sourceMappingURL=work-target.js.map
@@ -1,5 +1,12 @@
1
+ import type { IssueReference } from './reference-parser.js';
2
+ import type { RepositoryReference } from './repository-resolver.js';
1
3
  /**
2
4
  ブランチ名の末尾の Issue 番号。末尾が数字だけの区切りでなければ undefined
3
5
  */
4
6
  export declare function extractIssueNumberFromBranch(branch: string): number | undefined;
7
+ /**
8
+ 作業中の Issue。remote のリポとブランチ名の末尾の番号から決める。
9
+ remote かブランチが無いとき、末尾が数字だけの区切りでないとき、番号が 0 のときは undefined。detached HEAD の `HEAD` も undefined になる
10
+ */
11
+ export declare function activeIssueFromBranch(remote: Readonly<RepositoryReference> | undefined, branch: string | undefined): IssueReference | undefined;
5
12
  //# sourceMappingURL=branch-name.d.ts.map
@@ -1,5 +1,7 @@
1
1
  // ブランチ名の読み取り。pecot session start が作る名前は、末尾が `/Issue番号` になる。
2
- import { parsePythonInteger } from './python-format.js';
2
+ import { parsePythonInteger, ValidationFailure } from './python-format.js';
3
+ import { createIssueReference } from './reference-parser.js';
4
+ import { createRepositoryReference } from './repository-resolver.js';
3
5
  /**
4
6
  ブランチ名の末尾の Issue 番号。末尾が数字だけの区切りでなければ undefined
5
7
  */
@@ -7,4 +9,24 @@ export function extractIssueNumberFromBranch(branch) {
7
9
  const last = branch.split('/').at(-1) ?? '';
8
10
  return /^\p{Nd}+$/u.test(last) ? parsePythonInteger(last) : undefined;
9
11
  }
12
+ /**
13
+ 作業中の Issue。remote のリポとブランチ名の末尾の番号から決める。
14
+ remote かブランチが無いとき、末尾が数字だけの区切りでないとき、番号が 0 のときは undefined。detached HEAD の `HEAD` も undefined になる
15
+ */
16
+ export function activeIssueFromBranch(remote, branch) {
17
+ if (remote === undefined || branch === undefined)
18
+ return undefined;
19
+ const number = extractIssueNumberFromBranch(branch);
20
+ if (number === undefined || number <= 0)
21
+ return undefined;
22
+ try {
23
+ return createIssueReference(createRepositoryReference(remote.owner, remote.repository), number);
24
+ }
25
+ catch (error) {
26
+ // owner・repo に使えない文字が入った remote は、形の合わない remote として扱う
27
+ if (error instanceof ValidationFailure)
28
+ return undefined;
29
+ throw error;
30
+ }
31
+ }
10
32
  //# sourceMappingURL=branch-name.js.map
@@ -18,7 +18,7 @@ export interface CommandHint {
18
18
  readonly input: Readonly<Record<string, HintValue>>;
19
19
  }
20
20
  /**
21
- 入力 1 つだけの案内(`--allow-cross-repo` の形)
21
+ 入力 1 つだけの案内(`--dry-run` の形)
22
22
  */
23
23
  export interface InputHint {
24
24
  readonly kind: 'input';
@@ -2,6 +2,7 @@ import type { HintedText } from './command-hint.js';
2
2
  import type { PullRequestReadout } from './issue-readout.js';
3
3
  import type { SectionHeading } from './sections.js';
4
4
  import type { BaseReading } from './state.js';
5
+ import type { RestackDecision } from './restack.js';
5
6
  export declare const SCREENSHOT_MISSING_ERROR: HintedText;
6
7
  /**
7
8
  本文の Closes / Fixes / Resolves に続く Issue 番号を、出てきた順に重複なしで返す
@@ -166,7 +167,7 @@ export declare function formatPullRequestWithReviewsMarkdown(pr: PullRequestWith
166
167
  export interface PreflightWarning {
167
168
  readonly label: string;
168
169
  readonly message: string;
169
- readonly fixHint: string;
170
+ readonly fixHint: HintedText;
170
171
  }
171
172
  /**
172
173
  `git status` の出力に変更があるか。空・取得失敗の印・「nothing to commit」かつ「working tree clean」は無し
@@ -179,16 +180,32 @@ export declare function hasStashEntries(stashList: string): boolean;
179
180
  export interface PushStatus {
180
181
  readonly isPushed: boolean;
181
182
  readonly message: string;
183
+ /**
184
+ 手元と remote の両方に、相手に無いコミットがあるか
185
+ */
186
+ readonly isDiverged: boolean;
182
187
  }
183
188
  /**
184
189
  ahead と behind のコミット数から、push の状態の文を作る
185
190
  */
186
191
  export declare function describePushStatus(remote: string, branch: string, ahead: number, behind: number): PushStatus;
192
+ /**
193
+ diverged の直し方。fast-forward でない push は拒まれるので、取り込むか、書き換えたなら lease 付きで上書きする
194
+ */
195
+ export declare const DIVERGED_FIX_HINT: HintedText;
196
+ /**
197
+ 積んだブランチが diverged のときの直し方。載せ直しが要れば pr restack、要らなければ diverged の直し方、決められなければ pr restack --check
198
+ */
199
+ export declare function pushFixHintOf(decision: Readonly<RestackDecision> | undefined): HintedText;
187
200
  export interface PreflightFacts {
188
201
  readonly gitStatus: string;
189
202
  readonly stashList: string;
190
203
  readonly isPushed: boolean;
191
204
  readonly pushMessage: string;
205
+ /**
206
+ Push Status の直し方。省くと git push
207
+ */
208
+ readonly pushFixHint?: HintedText | undefined;
192
209
  }
193
210
  /**
194
211
  警告を、未 push・変更あり・stash ありの順で返す
@@ -197,5 +214,5 @@ export declare function collectPreflightWarnings(facts: Readonly<PreflightFacts>
197
214
  /**
198
215
  警告 1 行の文
199
216
  */
200
- export declare function formatPreflightWarning(warning: PreflightWarning): string;
217
+ export declare function formatPreflightWarning(warning: PreflightWarning): HintedText;
201
218
  //# sourceMappingURL=pull-request.d.ts.map
@@ -1,8 +1,9 @@
1
1
  // PR コマンドの入出力を持たない関数。本文の検証、Closes の抽出と追記、`pr show` の Markdown の整形、preflight の警告の判定。
2
2
  // 引数の型は、infra/github/pulls.ts の返す値が構造として満たす形をここに持つ(domain は infra を import できない)。
3
- import { hinted, inputHint, inputNameHint } from './command-hint.js';
3
+ import { commandHint, hinted, inputHint, inputNameHint, joinHinted } from './command-hint.js';
4
4
  import { parsePythonInteger, pythonRightStrip, pythonStrip, splitCodePoints, truncateCodePoints } from './python-format.js';
5
5
  import { hasSummaryImage, validateBodyStyle, validateHeadingSummaries, validateSections } from './sections.js';
6
+ import { RESTACK_PATH } from './restack.js';
6
7
  // Issue 参照(`#N`、URL 内のフラグメントは除く)。`owner/repo#N` の形も受ける
7
8
  const ISSUE_REFERENCE_PATTERN = /(?:^|[^/])#\d+|[\w-]+\/[\w.-]+#\d+/u;
8
9
  // Python の `\s`(str.isspace)と同じ空白
@@ -250,12 +251,27 @@ ahead と behind のコミット数から、push の状態の文を作る
250
251
  */
251
252
  export function describePushStatus(remote, branch, ahead, behind) {
252
253
  if (ahead === 0 && behind === 0)
253
- return { isPushed: true, message: `in sync with ${remote}/${branch}` };
254
+ return { isPushed: true, message: `in sync with ${remote}/${branch}`, isDiverged: false };
254
255
  if (behind === 0)
255
- return { isPushed: false, message: `${String(ahead)} unpushed commits` };
256
+ return { isPushed: false, message: `${String(ahead)} unpushed commits`, isDiverged: false };
256
257
  if (ahead === 0)
257
- return { isPushed: true, message: `${remote}/${branch} is ${String(behind)} commits ahead (pull recommended)` };
258
- return { isPushed: false, message: `diverged: local is ${String(ahead)} commits ahead, ${remote}/${branch} is ${String(behind)} ahead` };
258
+ return { isPushed: true, message: `${remote}/${branch} is ${String(behind)} commits ahead (pull recommended)`, isDiverged: false };
259
+ return { isPushed: false, message: `diverged: local is ${String(ahead)} commits ahead, ${remote}/${branch} is ${String(behind)} ahead`, isDiverged: true };
260
+ }
261
+ // 文の中にロングオプションを書けない(lint)ので、git の引数から組む
262
+ const PULL_REBASE_COMMAND = ['git', 'pull', '--rebase'].join(' ');
263
+ const FORCE_PUSH_COMMAND = ['git', 'push', '--force-with-lease'].join(' ');
264
+ /**
265
+ diverged の直し方。fast-forward でない push は拒まれるので、取り込むか、書き換えたなら lease 付きで上書きする
266
+ */
267
+ export const DIVERGED_FIX_HINT = hinted `${PULL_REBASE_COMMAND}, or ${FORCE_PUSH_COMMAND} if you rewrote pushed commits`;
268
+ /**
269
+ 積んだブランチが diverged のときの直し方。載せ直しが要れば pr restack、要らなければ diverged の直し方、決められなければ pr restack --check
270
+ */
271
+ export function pushFixHintOf(decision) {
272
+ if (decision === undefined || decision.kind === 'gone')
273
+ return hinted `${commandHint(RESTACK_PATH, { check: true })}`;
274
+ return decision.kind === 'moved' || decision.kind === 'merged' ? hinted `${commandHint(RESTACK_PATH)}` : DIVERGED_FIX_HINT;
259
275
  }
260
276
  /**
261
277
  警告を、未 push・変更あり・stash ありの順で返す
@@ -263,12 +279,12 @@ export function describePushStatus(remote, branch, ahead, behind) {
263
279
  export function collectPreflightWarnings(facts) {
264
280
  const warnings = [];
265
281
  if (!facts.isPushed)
266
- warnings.push({ label: 'Push Status', message: facts.pushMessage, fixHint: 'git push' });
282
+ warnings.push({ label: 'Push Status', message: facts.pushMessage, fixHint: facts.pushFixHint ?? hinted `git push` });
267
283
  if (hasStatusChanges(facts.gitStatus))
268
- warnings.push({ label: 'Git Status', message: 'modified or untracked files', fixHint: 'commit' });
284
+ warnings.push({ label: 'Git Status', message: 'modified or untracked files', fixHint: hinted `commit` });
269
285
  if (hasStashEntries(facts.stashList)) {
270
286
  const count = facts.stashList.split(LINE_BREAK).filter(line => pythonStrip(line) !== '').length;
271
- warnings.push({ label: 'Stash List', message: `${String(count)} stash entries`, fixHint: 'check them' });
287
+ warnings.push({ label: 'Stash List', message: `${String(count)} stash entries`, fixHint: hinted `check them` });
272
288
  }
273
289
  return warnings;
274
290
  }
@@ -276,6 +292,6 @@ export function collectPreflightWarnings(facts) {
276
292
  警告 1 行の文
277
293
  */
278
294
  export function formatPreflightWarning(warning) {
279
- return `${warning.label}: ${warning.message} (fix: ${warning.fixHint})`;
295
+ return joinHinted([`${warning.label}: ${warning.message} (fix: `, warning.fixHint, ')'], '');
280
296
  }
281
297
  //# sourceMappingURL=pull-request.js.map
@@ -1,5 +1,9 @@
1
1
  import type { PullRequestReadout } from './issue-readout.js';
2
2
  import type { BaseReading } from './state.js';
3
+ /**
4
+ pr restack のコマンドの path。案内(commandHint)とコマンドの定義が共有する
5
+ */
6
+ export declare const RESTACK_PATH: readonly string[];
3
7
  export interface RestackInput {
4
8
  /**
5
9
  base の記録。形の誤りは呼び出し側が先に止める
@@ -1,5 +1,9 @@
1
1
  // 積んだブランチを載せ直す先の判断と、その表示。git と GitHub の読み取りは commands が行う。
2
2
  /**
3
+ pr restack のコマンドの path。案内(commandHint)とコマンドの定義が共有する
4
+ */
5
+ export const RESTACK_PATH = ['pr', 'restack'];
6
+ /**
3
7
  載せ直す先を決める。base は、載せ直した後の base のブランチ(merged なら開発ブランチ)
4
8
  */
5
9
  export function decideRestack(input) {