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

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 (45) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/cli/dist/commands/branch.js +3 -20
  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 +47 -22
  14. package/cli/dist/commands/pr.js +84 -56
  15. package/cli/dist/commands/project.js +2 -2
  16. package/cli/dist/commands/renamed-commands.js +0 -1
  17. package/cli/dist/commands/repository-match.d.ts +6 -0
  18. package/cli/dist/commands/repository-match.js +20 -6
  19. package/cli/dist/commands/restack-reading.d.ts +45 -0
  20. package/cli/dist/commands/restack-reading.js +43 -0
  21. package/cli/dist/commands/session-finish.js +6 -18
  22. package/cli/dist/commands/session-start.js +10 -55
  23. package/cli/dist/commands/session.js +52 -169
  24. package/cli/dist/commands/work-target.d.ts +5 -8
  25. package/cli/dist/commands/work-target.js +17 -19
  26. package/cli/dist/domain/branch-name.d.ts +7 -0
  27. package/cli/dist/domain/branch-name.js +23 -1
  28. package/cli/dist/domain/command-hint.d.ts +1 -1
  29. package/cli/dist/domain/pull-request.d.ts +20 -2
  30. package/cli/dist/domain/pull-request.js +26 -9
  31. package/cli/dist/domain/repository-policy.d.ts +4 -0
  32. package/cli/dist/domain/repository-policy.js +5 -1
  33. package/cli/dist/domain/restack.d.ts +11 -0
  34. package/cli/dist/domain/restack.js +6 -1
  35. package/cli/dist/domain/state.d.ts +2 -12
  36. package/cli/dist/domain/state.js +3 -14
  37. package/cli/dist/infra/git.d.ts +13 -0
  38. package/cli/dist/infra/git.js +19 -0
  39. package/cli/dist/infra/paths.d.ts +1 -3
  40. package/cli/dist/infra/paths.js +2 -45
  41. package/cli/dist/infra/state-store.d.ts +3 -8
  42. package/cli/dist/infra/state-store.js +6 -24
  43. package/cli/templates/workflow/pecot-board-sync.yml +3 -2
  44. package/npm-shrinkwrap.json +2 -2
  45. package/package.json +1 -1
@@ -2,17 +2,14 @@
2
2
  import { z } from 'zod';
3
3
  import { findRepository, getFieldId, getOptionId, isRepositoryInProject } from '../domain/config.js';
4
4
  import { ReferenceParseError, parseIssueReference } from '../domain/reference-parser.js';
5
- import { pythonStringRepr } from '../domain/python-format.js';
6
5
  import { repositoryFullName } from '../domain/repository-resolver.js';
7
6
  import { displayReference } from '../domain/readiness.js';
8
- import { FLAG_PECOT_ACTIVE } from '../domain/state.js';
9
7
  import { decideStart, describeBaseMismatch } from '../domain/work-start.js';
10
8
  import { GitHubAPIError } from '../infra/github/errors.js';
11
- import { readFlag } from '../infra/state-store.js';
12
9
  import { issuePath } from './issue-shared.js';
13
10
  import { createOutput, DRY_RUN_FIELD } from './output.js';
14
11
  import { defineCommand } from './command-definition.js';
15
- import { commandHint, hinted, inputHint, joinHinted } from './command-hint.js';
12
+ import { commandHint, hinted, joinHinted } from './command-hint.js';
16
13
  import { requireActiveConfig, stopWith } from './command-stop.js';
17
14
  import { kindOfFailure } from './failure.js';
18
15
  import { createGitHubClient } from './github-client.js';
@@ -31,15 +28,11 @@ function rejectCwdRepositoryMismatch(out, owner, repository) {
31
28
  const current = resolved.repository;
32
29
  if (current.owner === owner && current.repository === repository)
33
30
  return;
34
- stopWith(out, joinHinted([
35
- `the repository of the work Issue (${owner}/${repository}) differs from `
36
- + `the CWD git remote (${repositoryFullName(current)})\n`
37
- + 'move to the worktree of the target repository and run again:\n'
38
- + `<project-root>/base/${repository}/ or <project-root>/<wtN>/${repository}/\n`
39
- + 'create one with /pecot-w:w-worktree-add only if the repository has no worktree\n'
40
- + 'to issue the command on purpose from outside the CWD (for example in a script), ',
41
- hinted `give ${inputHint(START_PATH, 'allow_cross_repo')}`,
42
- ], ''), 'repo-mismatch', USAGE_EXIT_CODE);
31
+ stopWith(out, `the repository of the work Issue (${owner}/${repository}) differs from `
32
+ + `the CWD git remote (${repositoryFullName(current)})\n`
33
+ + 'move to the worktree of the target repository and run again:\n'
34
+ + `<project-root>/base/${repository}/ or <project-root>/<wtN>/${repository}/\n`
35
+ + 'create one with /pecot-w:w-worktree-add only if the repository has no worktree', 'repo-mismatch', USAGE_EXIT_CODE);
43
36
  }
44
37
  /**
45
38
  develop_branch を設定する直し方の行
@@ -83,38 +76,6 @@ async function decideWorkStart(out, client, config, issue) {
83
76
  return decision.kind === 'blocked' ? stopWith(out, decision.message, 'not-ready', USAGE_EXIT_CODE) : decision;
84
77
  }
85
78
  /**
86
- A-2. .pecot-active が別の OPEN な Issue を指していれば、終了コード 2 で止める
87
- */
88
- async function guardActiveOverwrite(out, client, issueReference) {
89
- const existing = readFlag(FLAG_PECOT_ACTIVE) ?? '';
90
- if (existing === '' || existing === issueReference)
91
- return;
92
- let existingReference;
93
- try {
94
- existingReference = parseIssueReference(existing);
95
- }
96
- catch (error) {
97
- if (!(error instanceof ReferenceParseError))
98
- throw error;
99
- out.warning(`the content of .pecot-active (${pythonStringRepr(existing)}) is malformed; overwriting it`);
100
- return;
101
- }
102
- const { repository, number } = existingReference;
103
- const { state } = await client.getIssueSlim(repository.owner, repository.repository, number);
104
- if (state === 'OPEN') {
105
- stopWith(out, joinHinted([
106
- `this worktree is already working on another Issue (${existing}, OPEN)\n`
107
- + 'overwriting .pecot-active could mix up the tasks\n'
108
- + 'finish the other Issue first, or create another worktree with '
109
- + '/pecot-w:w-worktree-add and run /pecot-w:w-active again in its session',
110
- hinted `if it is stale and you want to overwrite it on purpose, give ${inputHint(START_PATH, 'force_overwrite_active')}`,
111
- ]), 'guard-blocked', USAGE_EXIT_CODE);
112
- }
113
- out.warning(state === 'CLOSED'
114
- ? `.pecot-active points to closed Issue ${existing}; overwriting it`
115
- : `the state of ${existing} in .pecot-active is unexpected (${pythonStringRepr(state)}); overwriting it`);
116
- }
117
- /**
118
79
  7.5. プロジェクトアイテムのステータスを active にする(失敗は warning にとどめる)
119
80
  */
120
81
  async function setIssueStatusActive(out, client, config, issue) {
@@ -159,13 +120,11 @@ const sessionStartCommand = defineCommand({
159
120
  branch: z.string().describe('Name of the branch to create'),
160
121
  base: z.string().optional().describe('Base branch (default: chosen by readiness, else develop_branch from the config)'),
161
122
  checkout: z.boolean().default(true).describe('Kept for compatibility; has no effect'),
162
- allow_cross_repo: z.boolean().default(false).describe('Allow the CWD repository to differ from the Issue ref (for scripts and runs outside the CWD)'),
163
- force_overwrite_active: z.boolean().default(false).describe('Disable the .pecot-active overwrite guard (when sure it is stale)'),
164
123
  dry_run: z.boolean().default(false).describe('Show what would be created and recorded without writing anything'),
165
124
  }),
166
125
  output: SESSION_START_OUTPUT,
167
126
  positional: ['issue_ref', 'branch'],
168
- shortFlags: { base: '-b', allow_cross_repo: '-X', force_overwrite_active: '-F', dry_run: '-n' },
127
+ shortFlags: { base: '-b', dry_run: '-n' },
169
128
  negations: { checkout: '--no-checkout' },
170
129
  interactive: false,
171
130
  run: async (input, io) => {
@@ -186,14 +145,10 @@ const sessionStartCommand = defineCommand({
186
145
  const { owner, repository } = issue.repository;
187
146
  const issueNumber = issue.number;
188
147
  // A-1. 作業ディレクトリと Issue ref のリポジトリの整合チェック
189
- if (!input.allow_cross_repo)
190
- rejectCwdRepositoryMismatch(out, owner, repository);
148
+ rejectCwdRepositoryMismatch(out, owner, repository);
191
149
  const finalBranchName = `${input.branch}/${String(issueNumber)}`;
192
150
  try {
193
151
  const client = createGitHubClient(out, config.host);
194
- // A-2. .pecot-active 上書きガード
195
- if (!input.force_overwrite_active)
196
- await guardActiveOverwrite(out, client, issuePath(owner, repository, issueNumber));
197
152
  // 4. リポジトリがプロジェクトに含まれているか確認
198
153
  if (!await isRepositoryInProject(config, owner, repository, client)) {
199
154
  stopWith(out, `${owner}/${repository} is not in the project`, 'repo-not-in-project');
@@ -224,7 +179,7 @@ const sessionStartCommand = defineCommand({
224
179
  out.result({ ...started, branch: finalBranchName });
225
180
  out.planned({ verb: 'create', target: `branch ${finalBranchName} in ${owner}/${repository} from ${baseBranch}${stackedNote}` });
226
181
  out.planned({ verb: 'set', target: `Issue ${issuePath(owner, repository, issueNumber)} status active` });
227
- planWorkTarget(out, owner, repository, issueNumber);
182
+ planWorkTarget(out, issueNumber);
228
183
  return 0;
229
184
  }
230
185
  // 7. リンクブランチ作成(ブランチ名末尾に Issue 番号を自動付与)
@@ -233,7 +188,7 @@ const sessionStartCommand = defineCommand({
233
188
  out.result({ ...started, branch: createdBranch });
234
189
  // 7.5. プロジェクトアイテムのステータスを active に更新
235
190
  await setIssueStatusActive(out, client, config, { owner, repository, number: issueNumber });
236
- // 9. 作業対象を .pecot-active と .pecot-session-title に保存(hook の自動投稿とセッション名用)
191
+ // 9. セッション名のキャッシュ(.pecot-session-title)と作業ディレクトリを作る
237
192
  const recorded = recordWorkTarget(out, owner, repository, issueNumber, issueTitle, {
238
193
  base: { branch: baseBranch, sha: baseSha, stackedOn: decision.kind === 'stack' ? decision.issue : undefined },
239
194
  });
@@ -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
- import { ConfigError } from '../domain/config.js';
5
- import { PecotError } from '../domain/errors.js';
6
- import { pickLowerPullRequest } from '../domain/pull-request.js';
3
+ import { ConfigError, getDevelopBranch } from '../domain/config.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: getDevelopBranch(active.config, owner, repository) ?? '' });
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';