@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
@@ -6,17 +6,16 @@ import { existsSync, statSync, writeFileSync } from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import { z } from 'zod';
8
8
  import { describeApiError } from '../domain/api-error-detail.js';
9
- import { extractIssueNumberFromBranch } from '../domain/branch-name.js';
9
+ import { activeIssueFromBranch, extractIssueNumberFromBranch } from '../domain/branch-name.js';
10
10
  import { effectiveReleaseType, findRepository, getDevelopBranch, getFieldId, getOptionId, getReleaseBranch } from '../domain/config.js';
11
11
  import { InvalidValueError } from '../domain/errors.js';
12
12
  import { FrontmatterError } from '../domain/frontmatter.js';
13
13
  import { parseRemoteUrl } from '../domain/git-url.js';
14
14
  import { isEpicIssue } from '../domain/issue-kind.js';
15
15
  import { jsonField } from '../domain/json.js';
16
- import { appendIssueCloseIfNeeded, collectPreflightWarnings, decidePullRequestBase, describeBaseStop, describePushStatus, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, pickLowerPullRequest, validatePullRequestContent } from '../domain/pull-request.js';
16
+ import { appendIssueCloseIfNeeded, collectPreflightWarnings, decidePullRequestBase, describeBaseStop, describePushStatus, DIVERGED_FIX_HINT, formatPreflightWarning, formatPullRequestMarkdown, formatPullRequestWithReviewsMarkdown, isReleasePullRequest, pickLowerPullRequest, pushFixHintOf, validatePullRequestContent } from '../domain/pull-request.js';
17
17
  import { parsePythonInteger, pythonStrip } from '../domain/python-format.js';
18
18
  import { splitOwnerRepository } from '../domain/repository-resolver.js';
19
- import { FLAG_PECOT_ACTIVE, FLAG_PR_CREATE_SLASH_PENDING } from '../domain/state.js';
20
19
  import { loadActiveConfig } from '../infra/config-store.js';
21
20
  import { parsePullRequestFile } from '../infra/frontmatter-file.js';
22
21
  import { gitCurrentBranch, gitRemoteUrl, gitStdout, gitToplevel, primaryRemoteName, remoteBranchHead, runGit } from '../infra/git.js';
@@ -25,7 +24,7 @@ import { GitHubAPIError } from '../infra/github/errors.js';
25
24
  import { changedFiles, expectedScope, nxProjects, parseTitleScope } from '../infra/nx-scope.js';
26
25
  import { isFileNotFound } from '../infra/os-error.js';
27
26
  import { outputDirectory, OutputPathReservationError, resolveRealPath, withReservedOutputPath } from '../infra/paths.js';
28
- import { consumeFlag, readBaseRecord, readFlag } from '../infra/state-store.js';
27
+ import { readBaseRecord } from '../infra/state-store.js';
29
28
  import { readTemplateSections, templateFile } from '../infra/template-store.js';
30
29
  import { readTextFile } from '../infra/text-file.js';
31
30
  import { commandHint, hinted, inputHint, inputNameHint, placeholder } from './command-hint.js';
@@ -38,6 +37,7 @@ import { CommandExit, defineCommand } from './command-definition.js';
38
37
  import { BOARD_MOVE_JSON, moveJson } from './issue-board.js';
39
38
  import { PR_MERGE_COMMAND } from './pr-merge.js';
40
39
  import { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
40
+ import { readRestackDecision } from './restack-reading.js';
41
41
  import { moveWaitingIssues } from './pr-waiting.js';
42
42
  export { parseReference, PR_REFERENCE_DESCRIPTION } from './pr-reference.js';
43
43
  // 本文の検証の失敗。1(通信・設定・引数)と 2(preflight)と区別する
@@ -237,15 +237,15 @@ function getStashList(cwd) {
237
237
  return stdout === undefined ? '(git stash list failed)' : pythonStrip(stdout) || '(no stash)';
238
238
  }
239
239
  function getPushStatus(branch, cwd, remote) {
240
- const failed = { isPushed: false, message: '(git rev-list failed)' };
240
+ const failed = { isPushed: false, message: '(git rev-list failed)', isDiverged: false };
241
241
  try {
242
242
  if (runGit(['rev-parse', '--verify', `${remote}/${branch}`], { cwd }).exitCode !== 0) {
243
- return { isPushed: false, message: `${remote}/${branch} does not exist (not pushed)` };
243
+ return { isPushed: false, message: `${remote}/${branch} does not exist (not pushed)`, isDiverged: false };
244
244
  }
245
245
  }
246
246
  catch (error) {
247
247
  if (isFileNotFound(error))
248
- return { isPushed: false, message: '(git rev-parse failed)' };
248
+ return { isPushed: false, message: '(git rev-parse failed)', isDiverged: false };
249
249
  throw error;
250
250
  }
251
251
  const ahead = gitStdout(['rev-list', '--count', `${remote}/${branch}..${branch}`], { cwd });
@@ -268,10 +268,29 @@ export function validatePullRequestContext(directory, out) {
268
268
  return stopWith(out, 'cannot read repository info from the remote URL\ncheck it with: git remote -v', 'git-unresolved');
269
269
  return { remoteUrl: found.url, currentBranch, location: found.location, remoteName: found.name };
270
270
  }
271
- function runPreflightChecksOrExit(directory, out) {
271
+ // diverged のときの Push Status の直し方。積んでいれば載せ直しが要るかを読んで決める。diverged でなければ undefined(git push)
272
+ async function pushFixHintFor(push, reading, target) {
273
+ if (!push.isDiverged)
274
+ return undefined;
275
+ if (reading?.kind !== 'stacked')
276
+ return DIVERGED_FIX_HINT;
277
+ const { config, location, directory, remote, client, lowerPullRequest } = target;
278
+ const developBranch = getDevelopBranch(config, location.owner, location.repository) ?? '';
279
+ try {
280
+ const read = await readRestackDecision({ client, owner: location.owner, repository: location.repository, cwd: directory, remote, reading, developBranch, lowerPullRequest });
281
+ return pushFixHintOf(read.kind === 'decided' ? read.decision : undefined);
282
+ }
283
+ catch (error) {
284
+ if (error instanceof TransportFailure)
285
+ return pushFixHintOf(undefined);
286
+ throw error;
287
+ }
288
+ }
289
+ async function runPreflightChecksOrExit(directory, base, config, client, out) {
272
290
  const context = validatePullRequestContext(directory, out);
273
291
  const push = getPushStatus(context.currentBranch, directory, context.remoteName);
274
- const warnings = collectPreflightWarnings({ gitStatus: getGitStatus(directory), stashList: getStashList(directory), isPushed: push.isPushed, pushMessage: push.message });
292
+ const pushFixHint = await pushFixHintFor(push, base.reading, { config, location: context.location, directory, remote: context.remoteName, client, lowerPullRequest: base.lowerPullRequest });
293
+ const warnings = collectPreflightWarnings({ gitStatus: getGitStatus(directory), stashList: getStashList(directory), isPushed: push.isPushed, pushMessage: push.message, pushFixHint });
275
294
  if (warnings.length === 0)
276
295
  return;
277
296
  out.error('preflight found warnings; fix them before creating a PR');
@@ -332,8 +351,8 @@ async function moveWaitingIssuesSafely(client, config, location, issueNumber, pu
332
351
  out.warning(`could not move the Issues waiting for #${String(issueNumber)}: ${describeRequestFailure(error)}`);
333
352
  }
334
353
  }
335
- async function submitPullRequest(config, client, directory, draft, stackOn, out) {
336
- runPreflightChecksOrExit(directory, out);
354
+ async function submitPullRequest(config, client, directory, draft, stackOn, base, out) {
355
+ await runPreflightChecksOrExit(directory, base, config, client, out);
337
356
  let created;
338
357
  try {
339
358
  created = await client().createPullRequest(draft.location.owner, draft.location.repository, draft.title, draft.body, draft.head, draft.base, draft.isDraft);
@@ -363,7 +382,6 @@ async function submitPullRequest(config, client, directory, draft, stackOn, out)
363
382
  finally {
364
383
  out.result({ moves: moves.map(move => moveJson(move)) });
365
384
  }
366
- consumeFlag(FLAG_PR_CREATE_SLASH_PENDING);
367
385
  if (typeof url !== 'string')
368
386
  return stopWith(out, 'PR was created, but the response has no html_url; find it on GitHub', 'other');
369
387
  out.data(url);
@@ -393,13 +411,14 @@ function readBaseRecordFor(head, template, directory, out) {
393
411
  async function decideBase(input, client, developBranch, out) {
394
412
  const { reading, base, location } = input;
395
413
  if (reading === undefined)
396
- return { kind: 'use', base, stackOn: undefined, stackedBase: undefined, isLowerMerged: false };
414
+ return { decision: { kind: 'use', base, stackOn: undefined, stackedBase: undefined, isLowerMerged: false }, lowerPullRequest: undefined };
397
415
  if (reading.kind !== 'stacked')
398
- return decidePullRequestBase({ reading, base, developBranch });
416
+ return { decision: decidePullRequestBase({ reading, base, developBranch }), lowerPullRequest: undefined };
399
417
  const { branch } = reading.record;
400
418
  try {
401
419
  const found = await client().listPullRequestsByHead(location.owner, location.repository, branch);
402
- return decidePullRequestBase({ reading, base, developBranch, lowerPullRequest: pickLowerPullRequest(found.pullRequests) });
420
+ const lower = pickLowerPullRequest(found.pullRequests);
421
+ return { decision: decidePullRequestBase({ reading, base, developBranch, lowerPullRequest: lower }), lowerPullRequest: { pullRequest: lower } };
403
422
  }
404
423
  catch (error) {
405
424
  if (error instanceof GitHubAPIError)
@@ -433,7 +452,8 @@ async function validateAndSubmit(input, out) {
433
452
  const developBranch = getDevelopBranch(config, location.owner, location.repository);
434
453
  const releaseBranch = getReleaseBranch(config, location.owner, location.repository);
435
454
  exitOnUnsetBranch(template, input.base, head, developBranch, releaseBranch, out);
436
- const { use, errors: baseErrors } = useOrStop(await decideBase(input, client, developBranch ?? '', out), out);
455
+ const decided = await decideBase(input, client, developBranch ?? '', out);
456
+ const { use, errors: baseErrors } = useOrStop(decided.decision, out);
437
457
  const base = use?.base ?? input.base;
438
458
  const stacked = stackedScopeOf(input.reading, use);
439
459
  const requiredSections = readTemplateSections(templateFile('pr', templateKindOf(template)));
@@ -457,7 +477,7 @@ async function validateAndSubmit(input, out) {
457
477
  const isRelease = template === 'release';
458
478
  const draft = { location, title, body: input.body, head, base, isDraft: input.isDraft, isRelease };
459
479
  if (!input.dryRun) {
460
- await submitPullRequest(config, client, directory, draft, use?.stackOn, out);
480
+ await submitPullRequest(config, client, directory, draft, use?.stackOn, { reading: input.reading, lowerPullRequest: decided.lowerPullRequest }, out);
461
481
  return;
462
482
  }
463
483
  out.planned(createOperation(draft));
@@ -560,22 +580,11 @@ function addScopeHint(content, config, location, base, directory, stacked, out)
560
580
  return hinted;
561
581
  }
562
582
  async function fillClosesInTemplate(content, config, directory, location, out) {
563
- let target;
564
- const segments = readFlag(FLAG_PECOT_ACTIVE)?.split('/');
565
- if (segments?.length === 3) {
566
- const [activeOwner, activeRepository, digits] = segments;
567
- const activeNumber = digits !== undefined && /^\p{Nd}+$/u.test(digits) ? parsePythonInteger(digits) : undefined;
568
- if (activeOwner !== undefined && activeRepository !== undefined && activeNumber !== undefined)
569
- target = { owner: activeOwner, repository: activeRepository, number: activeNumber };
570
- }
571
- if (target === undefined && location !== undefined) {
572
- const branch = gitCurrentBranch(directory);
573
- const branchNumber = branch === undefined || branch === '' ? undefined : extractIssueNumberFromBranch(branch);
574
- if (isPositive(branchNumber))
575
- target = { owner: location.owner, repository: location.repository, number: branchNumber };
576
- }
577
- if (target === undefined || target.owner === '' || target.repository === '')
583
+ // 作業中の Issue は remote とブランチ名から決める。古い .pecot-active は読まない
584
+ const active = activeIssueFromBranch(location, gitCurrentBranch(directory));
585
+ if (active === undefined)
578
586
  return content;
587
+ const target = { owner: active.repository.owner, repository: active.repository.repository, number: active.number };
579
588
  const label = `Issue #${String(target.number)}`;
580
589
  try {
581
590
  const kind = await createGitHubClient(out, config?.host).getIssueKind(target.owner, target.repository, target.number);
@@ -786,12 +795,7 @@ function isOnRemote(branch, cwd, remote, out) {
786
795
  out.warning(`base branch ${branch} is on ${remote}, but ${remote}/${branch} is not fetched; compared with the develop branch\nrun: git fetch ${remote} ${branch}`);
787
796
  return isTracked;
788
797
  }
789
- function determineBaseBranch(location, cwd, remote, out) {
790
- const config = loadActiveConfig();
791
- if (config === undefined)
792
- return stopWith(out, hinted `project config not found\nactivate a project with: ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, 'no-active-project');
793
- const reading = readBaseRecord();
794
- stopOnMalformedRecord(reading, out);
798
+ function determineBaseBranch(config, reading, location, cwd, remote, out) {
795
799
  if (reading.kind === 'stacked' && isOnRemote(reading.record.branch, cwd, remote, out))
796
800
  return `${remote}/${reading.record.branch}`;
797
801
  const developBranch = getDevelopBranch(config, location.owner, location.repository);
@@ -861,11 +865,16 @@ function formatWorktreeInfo(info) {
861
865
  const CheckInputSchema = z.strictObject({
862
866
  directory: directorySchema,
863
867
  });
864
- function runCheck(input, io) {
868
+ async function runCheck(input, io) {
865
869
  const out = createOutput(false, io);
866
870
  const directory = input.directory;
867
871
  const context = validatePullRequestContext(directory, out);
868
- const baseBranch = determineBaseBranch(context.location, directory, context.remoteName, out);
872
+ const config = loadActiveConfig();
873
+ if (config === undefined)
874
+ return stopWith(out, hinted `project config not found\nactivate a project with: ${commandHint(['project', 'activate'], { project: placeholder('PROJECT') })}`, 'no-active-project');
875
+ const reading = readBaseRecord();
876
+ stopOnMalformedRecord(reading, out);
877
+ const baseBranch = determineBaseBranch(config, reading, context.location, directory, context.remoteName, out);
869
878
  const gitStatus = getGitStatus(directory);
870
879
  const commits = gitStdout(['log', '--oneline', `${baseBranch}..HEAD`], { cwd: directory });
871
880
  const diffSummary = gitStdout(['diff', '--stat', `${baseBranch}...HEAD`], { cwd: directory });
@@ -895,7 +904,8 @@ function runCheck(input, io) {
895
904
  out.data(`${heading}\n`);
896
905
  out.data(`${content}\n`);
897
906
  }
898
- const warnings = collectPreflightWarnings({ gitStatus, stashList, isPushed: push.isPushed, pushMessage: push.message });
907
+ const pushFixHint = await pushFixHintFor(push, reading, { config, location: context.location, directory, remote: context.remoteName, client: lazyClient(config, out) });
908
+ const warnings = collectPreflightWarnings({ gitStatus, stashList, isPushed: push.isPushed, pushMessage: push.message, pushFixHint });
899
909
  out.count('preflight warnings', warnings.length);
900
910
  printPreflightWarnings(out, warnings);
901
911
  if (warnings.length > 0)
@@ -936,9 +946,9 @@ const prCheck = defineCommand({
936
946
  positional: [],
937
947
  shortFlags: { directory: '-D' },
938
948
  interactive: false,
939
- run: (input, io) => {
940
- runCheck(input, io);
941
- return Promise.resolve(0);
949
+ run: async (input, io) => {
950
+ await runCheck(input, io);
951
+ return 0;
942
952
  },
943
953
  });
944
954
  export const PR_COMMANDS = [prCreate, prShow, prCheck, PR_MERGE_COMMAND];
@@ -424,7 +424,7 @@ async function activateFromConfigFile(out, configPath, host, isDryRun) {
424
424
  const title = projectInfo['title'];
425
425
  if (typeof title !== 'string' || title === '')
426
426
  stopWith(out, `could not read the title of project #${String(config.project.number)}`, 'project-not-found');
427
- reportSynced(out, await syncProjectConfig(out, client, { owner: config.owner, name: title, host: config.host, isDryRun }));
427
+ reportSynced(out, await syncProjectConfig(out, client, { owner: config.owner, name: title, host: config.host, suffix: config.workflow_suffix, isDryRun }));
428
428
  });
429
429
  }
430
430
  async function resolveActivationOwner(out, client, owner) {
@@ -629,7 +629,7 @@ async function linkRepository(out, config, repositoryOwner, repositoryName) {
629
629
  return await createGitHubClient(out, config.host).linkRepositoryToProject(config.owner, config.project.number, repositoryOwner, repositoryName);
630
630
  }
631
631
  catch (error) {
632
- // API の失敗の文は、Python と同じく message をそのまま使う(応答の本文の詳細は、wip ブランチの削除の警告だけが足す)
632
+ // API の失敗の文は、Python と同じく message をそのまま使う
633
633
  if (error instanceof GitHubAPIError)
634
634
  return { status: 'failed', detail: error.message };
635
635
  throw error;
@@ -31,7 +31,6 @@ export function findRenamedCommand(path) {
31
31
  }
32
32
  export const RENAMED_INPUTS = [
33
33
  { command: 'issue comment', oldName: 'issue', newName: 'issue_ref' },
34
- { command: 'session restore', oldName: 'issue', newName: 'issue_ref' },
35
34
  { command: 'branch delete', oldName: 'repo_ref', newName: 'repo' },
36
35
  { command: 'project link', oldName: 'owner_repo', newName: 'repo' },
37
36
  { command: 'session start', oldName: 'branch_name', newName: 'branch' },
@@ -0,0 +1,45 @@
1
+ import type { PullRequestReadout } from '../domain/issue-readout.js';
2
+ import type { RestackDecision } from '../domain/restack.js';
3
+ import type { BaseReading } from '../domain/state.js';
4
+ import { GitHubAPIError } from '../infra/github/errors.js';
5
+ import type { GitHubClient } from '../infra/github/index.js';
6
+ /**
7
+ 既に読んだ下の段の PR。PR が無かったことも示せるよう、包んで渡す
8
+ */
9
+ export interface KnownLowerPullRequest {
10
+ readonly pullRequest: PullRequestReadout | undefined;
11
+ }
12
+ export interface RestackTarget {
13
+ readonly client: () => Readonly<GitHubClient>;
14
+ readonly owner: string;
15
+ readonly repository: string;
16
+ readonly cwd: string;
17
+ /**
18
+ remote が無ければ undefined。そのときは remote に届かないのと同じに扱う
19
+ */
20
+ readonly remote: string | undefined;
21
+ readonly reading: Extract<BaseReading, {
22
+ kind: 'stacked';
23
+ }>;
24
+ readonly developBranch: string;
25
+ /**
26
+ 渡されたら、下の段の PR を読み直さない
27
+ */
28
+ readonly lowerPullRequest?: KnownLowerPullRequest | undefined;
29
+ }
30
+ export type RestackReading = {
31
+ readonly kind: 'decided';
32
+ readonly decision: RestackDecision;
33
+ readonly lowerPullRequest: PullRequestReadout | undefined;
34
+ } | {
35
+ readonly kind: 'remote-unreachable';
36
+ readonly lowerPullRequest: PullRequestReadout | undefined;
37
+ } | {
38
+ readonly kind: 'pull-request-unreadable';
39
+ readonly error: GitHubAPIError;
40
+ };
41
+ /**
42
+ 下の段の PR を読み、remote の先頭を尋ねて、載せ直す先を決める。PR を読めないか remote に届かなければ、その種類を返す
43
+ */
44
+ export declare function readRestackDecision(target: Readonly<RestackTarget>): Promise<RestackReading>;
45
+ //# sourceMappingURL=restack-reading.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { pickLowerPullRequest } from '../domain/pull-request.js';
2
+ import { decideRestack } from '../domain/restack.js';
3
+ import { remoteBranchHead } from '../infra/git.js';
4
+ import { GitHubAPIError } from '../infra/github/errors.js';
5
+ /**
6
+ 下の段の PR を読み、remote の先頭を尋ねて、載せ直す先を決める。PR を読めないか remote に届かなければ、その種類を返す
7
+ */
8
+ export async function readRestackDecision(target) {
9
+ const { reading, remote } = target;
10
+ let lowerPullRequest = target.lowerPullRequest?.pullRequest;
11
+ if (target.lowerPullRequest === undefined) {
12
+ try {
13
+ const found = await target.client().listPullRequestsByHead(target.owner, target.repository, reading.record.branch);
14
+ lowerPullRequest = pickLowerPullRequest(found.pullRequests);
15
+ }
16
+ catch (error) {
17
+ if (error instanceof GitHubAPIError)
18
+ return { kind: 'pull-request-unreadable', error };
19
+ throw error;
20
+ }
21
+ }
22
+ if (remote === undefined)
23
+ return { kind: 'remote-unreachable', lowerPullRequest };
24
+ const lowerHead = remoteBranchHead(target.cwd, remote, reading.record.branch);
25
+ return lowerHead.isReachable
26
+ ? { kind: 'decided', decision: decideRestack({ reading, developBranch: target.developBranch, lowerPullRequest, lowerHead: lowerHead.sha }), lowerPullRequest }
27
+ : { kind: 'remote-unreachable', lowerPullRequest };
28
+ }
29
+ //# sourceMappingURL=restack-reading.js.map
@@ -8,11 +8,12 @@ import { isEpicIssue } from '../domain/issue-kind.js';
8
8
  import { extractClosingIssueNumbers } from '../domain/pull-request.js';
9
9
  import { assumePullRequestState, describeReadinessChange, displayReference, hasReadinessChanged, isDone, isStackedOn } from '../domain/readiness.js';
10
10
  import { createIssueReference } from '../domain/reference-parser.js';
11
- import { FLAG_MERGE_SLASH_PENDING, FLAG_PECOT_ACTIVE, FLAG_PECOT_BASE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE, FLAG_WIP_BRANCH_LINKED } from '../domain/state.js';
11
+ import { RESTACK_PATH } from '../domain/restack.js';
12
+ import { FLAG_PECOT_BASE, FLAG_PECOT_QUICK_MODE, FLAG_PECOT_SESSION_TITLE } from '../domain/state.js';
12
13
  import { gitCurrentBranch, GitCommandError, runGit } from '../infra/git.js';
13
14
  import { GitHubAPIError, GitHubNotFoundError, isClosedByAnotherRequest, isMissingReferenceError } from '../infra/github/errors.js';
14
15
  import { isFileNotFound } from '../infra/os-error.js';
15
- import { consumeFlag, removeFlag } from '../infra/state-store.js';
16
+ import { removeFlag } from '../infra/state-store.js';
16
17
  import { getCurrentWorktreeName, isWorktreeEnvironment } from '../infra/worktree.js';
17
18
  import { commandHint, hinted } from './command-hint.js';
18
19
  import { requireActiveConfigPlain, stopWith } from './command-stop.js';
@@ -183,10 +184,10 @@ async function updateWaitingIssues(context, source) {
183
184
  const lower = heads.filter(head => prerequisiteOf(result, head)?.wait === 'stack').map(head => displayReference(head, home)).join(', ');
184
185
  const [branch] = result.target.branches;
185
186
  record.restack.push({ issue: name, ...branch !== undefined && { branch } });
186
- out.warning(hinted `${name} is stacked on ${lower}; run ${commandHint(['pr', 'restack'])} in the working directory of ${branch ?? 'its branch'}`);
187
+ out.warning(hinted `${name} is stacked on ${lower}; run ${commandHint(RESTACK_PATH)} in the working directory of ${branch ?? 'its branch'}`);
187
188
  }
188
189
  }
189
- // head ブランチを消し、続けて wip ブランチを消す。head が無くても wip は試す
190
+ // head ブランチを消す。無ければ unchanged、ほかの失敗は warning にして続ける
190
191
  async function deleteMergedBranch(context, client, location, headBranch) {
191
192
  const { out, isDryRun, record } = context;
192
193
  const operation = { verb: 'delete', target: `remote branch ${headBranch}` };
@@ -209,18 +210,6 @@ async function deleteMergedBranch(context, client, location, headBranch) {
209
210
  }
210
211
  out.done({ verb: 'unchanged', target: `remote branch ${headBranch} (already deleted)` });
211
212
  }
212
- const wipBranch = `wip/${headBranch}`;
213
- try {
214
- await client.deleteBranch(location.owner, location.repository, wipBranch);
215
- out.done({ verb: 'delete', target: `remote branch ${wipBranch}` });
216
- record.deletedBranches.push({ branch: wipBranch, location: 'remote' });
217
- }
218
- catch (error) {
219
- if (!(error instanceof GitHubAPIError))
220
- throw error;
221
- if (!isMissingReferenceError(error))
222
- out.warning(`deleting remote branch ${wipBranch} failed: ${describeApiError(error)}`);
223
- }
224
213
  }
225
214
  // 手元と PR の repository が同じなら主の remote 名。違えば警告を出して undefined
226
215
  function sameRepositoryRemote(cwd, location, out) {
@@ -314,7 +303,7 @@ function localCleanupAfterMerge(context, headBranch, config, location) {
314
303
  }
315
304
  function removeActiveFlags(out) {
316
305
  try {
317
- for (const flag of [FLAG_PECOT_ACTIVE, FLAG_PECOT_BASE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE, FLAG_WIP_BRANCH_LINKED])
306
+ for (const flag of [FLAG_PECOT_BASE, FLAG_PECOT_SESSION_TITLE, FLAG_PECOT_QUICK_MODE])
318
307
  removeFlag(flag);
319
308
  }
320
309
  catch (error) {
@@ -364,7 +353,6 @@ async function finish(input, context) {
364
353
  return;
365
354
  }
366
355
  removeActiveFlags(out);
367
- consumeFlag(FLAG_MERGE_SLASH_PENDING);
368
356
  }
369
357
  const sessionFinishCommand = defineCommand({
370
358
  path: ['session', 'finish'],
@@ -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
  });